Esempio n. 1
0
// ============================================================================
StatusCode Gaudi::Utils::Histos::fromXml
( TH1F& result , const std::string& input )
{
  //
  result.Reset() ;                                 // RESET old histogram
  //
  _Xml<TH1F> _xml ;
  std::auto_ptr<TH1F> histo =  _xml ( input ) ;
  if ( 0 == histo.get() ) { return StatusCode::FAILURE ; }        // RETURN
  //
  result.Reset() ;
  histo->Copy ( result ) ;
  //
  return StatusCode::SUCCESS ;
}
Esempio n. 2
0
double NewChi2Func(const double *xx ){
 const Double_t scale = xx[0];
 fileInMC->cd();
 TTree* MyTreeMC = (TTree*) fileInMC->Get(treeNameMC.c_str());
 outFile->cd();
 TString nameDATA = Form("hDATA_%d_%d_%.5f",Data_or_MC,nIter,ScaleTrue);
 TH1F* hDATA = (TH1F*) outFile->Get(nameDATA);
 
 TString NameMC = Form("hMC_Chi2_%.5f",scale);
 TH1F* hMC;
 if (!gROOT->FindObject(NameMC.Data())){
  hMC = new TH1F(NameMC,NameMC,numBINS,minBINS,maxBINS);
  hMC->Reset();
  
  MyTreeMC->SetEntryList(0); 
  MyTreeMC->Draw(">> myListMCTot",(AdditionalCut + Form(" && (ET * (1+(%f)))>%f",scale,minET)).Data(),"entrylist");
  TEntryList *mylistMCTot = (TEntryList*)gDirectory->Get("myListMCTot");
  MyTreeMC->SetEntryList(mylistMCTot);
  
  TString DrawMC = Form("(%s * (1+(%f)))>>%s",variableName.c_str(),scale,NameMC.Data());
  MyTreeMC->Draw(DrawMC);
//   MyTreeMC->Draw(DrawMC,(AdditionalCut+Form("&& (ET * (1+(%f)))>%f",scale,minET)).Data());
  hMC->Sumw2();
  hMC->Scale(hDATA->GetEffectiveEntries()/hMC->GetEffectiveEntries());
  outFile->cd();
  hMC->Write();
 } 
 else {
//   std::cerr << " NewChi2 old " << NameMC.Data() << std::endl;
  hMC = (TH1F*) outFile->Get(NameMC.Data());
 }
 
 double result = myChi2(hMC,hDATA);
 return result;
}
Esempio n. 3
0
TH1F* Prediction::CalcPrediction(TH2F* prediction_raw) {

   TH1F* prediction = new TH1F();
   prediction = (TH1F*) prediction_raw->ProjectionX();
   prediction->Reset();

   for (int i = 0; i <= prediction_raw->GetXaxis()->GetNbins() + 1; ++i) {
   
      TH1F h = *((TH1F*) prediction_raw->ProjectionY("py", i, i));
      
      double summ = 0;
      double sumv = 0;
      int N = 0;
      
      //// Calculate mean
      for (int j = 1; j <= (int) h.GetNbinsX(); ++j) {
         summ += h.GetBinContent(j);
         ++N;
      }
      double mean = summ / N;
      
      //// Calculated variance
      for (int j = 1; j <= (int) h.GetNbinsX(); ++j) {
         sumv += pow(mean - h.GetBinContent(j), 2);
      }
      double variance = sqrt(sumv / N);
      
      prediction->SetBinContent(i, mean);
      prediction->SetBinError(i, variance);

   }
   
   return prediction;
   
}
TH1F RestoreBinning(TH1F const& src, TH1F const& ref) {
  TH1F res = ref;
  res.Reset();
  for (int x = 1; x <= res.GetNbinsX(); ++x) {
    res.SetBinContent(x, src.GetBinContent(x));
  }
  return res;
}
Esempio n. 5
0
TH1F* eff_bg(TH1F* h1, TH1F* h2, TH1F* h3, TH1F* h4, const char* name="eff"){

  // first, verify that all histograms have same binning
  // nx is the number of visible bins
  // nxtot = nx+2 includes underflow and overflow
  Int_t nx = h1->GetNbinsX();
  Int_t nxtot = nx + 2;
  if (h2->GetNbinsX() != nx) {
    //    cout << "Histograms must have same number of bins" << endl;
    return 0;
  }
  if (h3->GetNbinsX() != nx) {
    //    cout << "Histograms must have same number of bins" << endl;
    return 0;
  }
  if (h3->GetNbinsX() != nx) {
    //    cout << "Histograms must have same number of bins" << endl;
    return 0;
  }

  // get the new histogram
  TH1F* temp = (TH1F*) h1->Clone(name);
  temp->SetTitle(name);
  temp->Reset();
  temp->Sumw2();

  // Loop over bins, calculate efficiency and error, put it in histogram
  for (Int_t i=0; i<nxtot; i++) {
    Double_t x1 = h1->GetBinContent(i);
    Double_t x2 = h2->GetBinContent(i);
    Double_t x3 = h3->GetBinContent(i);
    Double_t x4 = h4->GetBinContent(i);
    Double_t denom = x1 - x3;
    Double_t eff;
    if (denom == 0.) {
      eff = 0;
    } else {
      eff   = (x2-x4)/denom;
    }
    Double_t failSig = x1 - x2;
    Double_t failBg  = x3 - x4;
    Double_t blah    = (1-eff)*(1-eff)*(x2+x4) + eff*eff*(failSig+failBg);
    if (blah <= 0.) blah=0.0;
    Double_t err;
    if (denom == 0) {
      err = 0.;
    } else {
      err = sqrt(blah)/denom;
    }
    temp->SetBinContent(i,eff);
    temp->SetBinError(i,err);
  }

  // Done
  return temp;
}
Esempio n. 6
0
TH1F * MakeOnePSE(TH1F * sig, int nsig, TH1F * back, int nback){

  //threw one data PSE  and fill it
  TH1F * data  = (TH1F*) sig ->Clone("data");
  data->Reset();
  data->FillRandom(sig,nsig);
  data->FillRandom(back,nback);

  return data;

}//MakeOnePSE
Esempio n. 7
0
TH1F * getErrHist(TH1F * h, bool rel = true)
{
	TH1F * res = (TH1F *) h->Clone("errhist");
	res->Reset();
	
	for(int j = 1; j <= res->GetNbinsX(); j++)
		if(rel) res->SetBinContent(j,h->GetBinError(j)/h->GetBinContent(j));
		else res->SetBinContent(j,h->GetBinError(j));

	return res;
}
Esempio n. 8
0
TH1F * sqSum(TH1F * h1, TH1F * h2)
{
	TH1F * res = (TH1F *) h2->Clone("sum");
	res->Reset();
	
	for(int j = 1; j <= res->GetNbinsX(); j++)
	{
		if(h1) res->SetBinContent(j,TMath::Sqrt( TMath::Power(h1->GetBinContent(j),2) + TMath::Power(h2->GetBinContent(j),2)));
		else res->SetBinContent(j,h2->GetBinContent(j));
	}
	
	return res;
}
Esempio n. 9
0
double Chi2F(const double *xx ){
 const Double_t scale = xx[0];
 fileInMC->cd();
 TTree* MyTreeMC = (TTree*) fileInMC->Get(treeNameMC.c_str());
 outFile->cd();
 TString nameDATA = Form("hDATA_%d_%d_%.5f",Data_or_MC,nIter,ScaleTrue);
 TH1F* hDATA = (TH1F*) outFile->Get(nameDATA);
 TString NameMC = Form("hMC_Chi2_%.5f",scale);
 
 //std::cerr << " NameMC = "  << NameMC.Data() << " => " << scale << std::endl;
 
 TH1F* hMC;
 if (!gROOT->FindObject(NameMC.Data())){
  hMC = new TH1F(NameMC,NameMC,numBINS,minBINS,maxBINS);
  hMC->Reset();

//  std::cerr << " AdditionalCut.Data() = " << AdditionalCut.Data() << std::endl;
  
  MyTreeMC->SetEntryList(0); 
  MyTreeMC->Draw(">> myListMCTot",(AdditionalCut + Form(" && (ET * (1+(%f)))>%f",scale,minET)).Data(),"entrylist");
  TEntryList *mylistMCTot = (TEntryList*)gDirectory->Get("myListMCTot");
  MyTreeMC->SetEntryList(mylistMCTot);
  
  TString DrawMC = Form("(%s * (1+(%f)))>>%s",variableName.c_str(),scale,NameMC.Data());
//  std::cerr << " DrawMC = " << DrawMC.Data() << std::endl;
  MyTreeMC->Draw(DrawMC);
//   MyTreeMC->Draw(DrawMC,(AdditionalCut+Form("&& (ET * (1+(%f)))>%f",scale,minET)).Data());
  hMC->Sumw2();
  hMC->Scale(hDATA->GetEffectiveEntries()/hMC->GetEffectiveEntries());
  outFile->cd();
  hMC->Write();
 }
 else {
//   std::cerr << " KM old "  << NameMC.Data() << std::endl;
  hMC = (TH1F*) outFile->Get(NameMC.Data());
 }
 
 outFile->cd();
//  hDATA.Write();
//  hMC.Write();
 
 double result = hMC->KolmogorovTest(hDATA,"M");
// double result = - hMC->KolmogorovTest(hDATA,"X");
//  double result = hMC->Chi2Test(&hDATA,"CHI2/NDF");
//=========> E' QUESTO! ==> double result = hMC->Chi2Test(hDATA,"CHI2");
 //double result = - hMC.Chi2Test(&hDATA,""); ///==== http://root.cern.ch/root/html/TH1.html#TH1:Chi2Test
 return result;
}
void make(TDirectory & out, TObject * o) {
  TDirectory * dir;
  TH1F * th1f;
  TH1D * th1d;
  TH2F * th2f;
  TH2D * th2d;
  out.cd();
  if((dir = dynamic_cast<TDirectory*>(o)) != 0) {
    TDirectory * outDir = out.mkdir(dir->GetName(), dir->GetTitle());
    TIter next(dir->GetListOfKeys());
    TKey *key;
    while( (key = dynamic_cast<TKey*>(next())) ) {
      string className(key->GetClassName());
      string name(key->GetName());
      TObject * obj = dir->Get(name.c_str());
      if(obj == 0) {
	cerr <<"error: key " << name << " not found in directory " << dir->GetName() << endl;
	exit(-1);
      }
      make(*outDir, obj);
    }
  } else if((th1f = dynamic_cast<TH1F*>(o)) != 0) {
    TH1F *h = (TH1F*) th1f->Clone();
    h->Reset();
    h->Sumw2();
    h->SetDirectory(&out);
  } else if((th1d = dynamic_cast<TH1D*>(o)) != 0) {
    TH1D *h = (TH1D*) th1d->Clone();
    h->Reset();
    h->Sumw2();
    h->SetDirectory(&out);
  } else if((th2f = dynamic_cast<TH2F*>(o)) != 0) {
    TH2F *h = (TH2F*) th2f->Clone();
    h->Reset();   
    h->Sumw2();
    h->SetDirectory(&out);
  } else if((th2d = dynamic_cast<TH2D*>(o)) != 0) {
    TH2D *h = (TH2D*) th2d->Clone();
    h->Reset();   
    h->Sumw2();
    h->SetDirectory(&out);
  }
}
Esempio n. 11
0
// Method by pointer
TH1F* eff(TH1F* h1, TH1F* h2, const char* name="eff"){

  // first, verify that all histograms have same binning
  // nx is the number of visible bins
  // nxtot = nx+2 includes underflow and overflow
  Int_t nx = h1->GetNbinsX();
  if (h2->GetNbinsX() != nx) {
    cout << "Histograms must have same number of bins" << endl;
    return 0;
  }

  // get the new histogram
  TH1F* temp = (TH1F*) h1->Clone(name);
  temp->SetTitle(name);
  temp->Reset();
  temp->Sumw2();

  // Do the calculation
  temp->Divide(h2,h1,1.,1.,"B");

  // Done
  return temp;
}
Esempio n. 12
0
void efficiency( TString denfile="60-120.root",
                 TString numfile="orig.root",
                 TString outfile="res.root" ) {

  gROOT ->Reset();
  
  TFile * nume = new TFile(numfile);
  TFile * deno = new TFile(denfile);
  
  nume->cd("/");
  deno->cd("/");

  TString theName = "d02-x01-y01";

  const TH1F *myNume;
  nume->GetObject(theName,myNume);
  myNume->Sumw2();
  myNume->Print("all");

  const TH1F *myDeno;
  deno->GetObject(theName,myDeno);
  myDeno->Sumw2();
  myDeno->Print("all");

  TH1F *Acce = (TH1F*)myNume->Clone("efficiency");
  Acce->Reset();
  Double_t f1(1.),f2(1.);
  Option_t* opt("b");
  Acce->Divide(myNume,myDeno,f1,f2,opt);
  Acce->Print("all");

  TFile * out = new TFile(outfile,"NEW");
  Acce->Write();
  out->Close();

}
Esempio n. 13
0
void cetaflatHFP12(int nIterN=1, double Ethr1=10, double Ethr2=150) {
  
  gStyle->SetOptLogz(0);
  gStyle->SetMarkerSize(0.7);
  gStyle->SetMarkerStyle(20);
  gStyle->SetPadGridX(0);
  gStyle->SetPadGridY(0);
  gStyle->SetTitleOffset(1.7,"Y");
  gStyle->SetTitleOffset(0.9,"X");
  //gStyle->SetPadRightMargin(0.12);
  gStyle->SetPadRightMargin(0.03);
  gStyle->SetPadLeftMargin(0.18);
  //gStyle->SetNdivisions(516);
  gStyle->SetStatH(0.025);
  gStyle->SetStatW(0.3);
  gStyle->SetTitleW(0.4);
  gStyle->SetTitleX(0.28);
  gStyle->SetOptStat(0);
  gROOT->ForceStyle();

  char ctit[245],ftit[245];
  float etaBounds[14] = {2.853,2.964,3.139,3.314,3.489,3.664,3.839,4.013,4.191,4.363,4.538,4.716,4.889,5.205};

  // ------Histos input: spectra of all channels-----------------------------------

  //sprintf(ftit,"%s","phi43val2012A");
  //sprintf(ftit,"%s","phi2012A_May");
  //sprintf(ftit,"%s","phiSym524_2012AB");
  //sprintf(ftit,"%s","phiSym524newGain_2012AB");
  //sprintf(ftit,"%s","phiSym524newGain_2012ABC");
  //sprintf(ftit,"%s","phisymNewCond2012Cval");
  //sprintf(ftit,"%s","phisymOldCond2012Cval");
  //sprintf(ftit,"%s","phiSym533Gain507_2012D");
  sprintf(ftit,"%s","phiSym533Corr45Gain507_2012D");

  sprintf(ctit,"/home/vodib/beam12/intercal/%s.root",ftit);
  TFile *fila = new TFile (ctit);
  cout<<"File= "<<ctit<<endl;

  TH1F *hcounter =   new TH1F(*((TH1F*)fila->Get("phaseHF/hcounter")));
  cout<<"Stat= "<<hcounter->GetBinContent(2)<<endl;
  cout<<"E within: "<<Ethr1<<" - "<<Ethr2<<endl;

  TH2F* hLmapP = new TH2F("hLmapP","E L HFP;i#eta;i#phi",13,28.5,41.5,36,0,72);
  TH2F* hSmapP = new TH2F("hSmapP","E S HFP;i#eta;i#phi",13,28.5,41.5,36,0,72);
  TH2F* hLmapP0 = new TH2F("hLmapP0","E0 L HFP;i#eta;i#phi",13,28.5,41.5,36,0,72);
  TH2F* hSmapP0 = new TH2F("hSmapP0","E0 S HFP;i#eta;i#phi",13,28.5,41.5,36,0,72);
  TH2F* hLmapPc = new TH2F("hLmapPc","corr L HFP;i#eta;i#phi",13,28.5,41.5,36,0,72);
  TH2F* hSmapPc = new TH2F("hSmapPc","corr S HFP;i#eta;i#phi",13,28.5,41.5,36,0,72);
  hLmapPc->Sumw2(); hSmapPc->Sumw2();
  //TH1F *hLcorr1D = new TH1F("hLcorr1D","Corr L",300,0.5,2);
  //TH1F *hScorr1D = new TH1F("hScorr1D","Corr S",300,0.5,2);
  TH1F *hLcorr1D = new TH1F("hLcorr1D","Corr L",180,0.7,1.5);
  TH1F *hScorr1D = new TH1F("hScorr1D","Corr S",180,0.7,1.5);
  TH1F *hLdatP[13][36], *hSdatP[13][36], *hLdatPx[13][36], *hSdatPx[13][36];
  for (int ii=0;ii<13;ii++) for (int jj=0;jj<36;jj++) {
    sprintf(ctit,"hL%d_%d",ii+29,2*jj+1);
    hLdatP[ii][jj] = new TH1F(ctit,ctit,8000,0,250);
    sprintf(ctit,"hS%d_%d",ii+29,2*jj+1);
    hSdatP[ii][jj] = new TH1F(ctit,ctit,8000,0,250);
  }
  TH1F *htL = new TH1F("htL","htL",20000,0,7e8/3.);
  TH1F *htS = new TH1F("htS","htS",20000,0,5e8/3.);
  //TH1F *htL = new TH1F("htL","htL",20000,0,4e8/40);
  //TH1F *htS = new TH1F("htS","htS",20000,0,2e8/40);
  TH1F *hLdatPx[13][36], *hSdatPx[13][36];

  TCanvas *cLx[200],*cSx[200];
  TSpline5 *ttL,*ttS;

  Double_t x,y,rPL,rPS,drPL,drPS,mLE,mSE,ermean,rms;
  Double_t xxL[1000],yyL[1000];
  Double_t xxS[1000],yyS[1000];
  Int_t nELP, nESP, nIter=0;
  Double_t mcorrL,scorrL,mcorrS,scorrS,erLP,erSP,rLP,drLP,rSP,drSP,corrL,corrS,dcorrL,dcorrS;
  double mLEphi[13],mSEphi[13],dmLEphi[13],dmSEphi[13];

  TCanvas *ccxx = new TCanvas("ccxx","ccxx",100,300,900,500);
  ccxx->Divide(2,1);

  for (int ii=0;ii<13;ii++) {
  //for (int ii=1;ii<2;ii++) {
    int ieta=ii+29;

    mLE=mSE=0;   // ------------------for initial condition
    int nmLE=0, nmSE=0;
    htL->Reset(); htS->Reset();
    for (int ll=1;ll<=72;ll+=2) {
      int iphi=ll;
      if (abs(ieta)>39 && (iphi-1)%4==0) continue;
      hSmapPc->SetBinContent(ii+1,ll/2+1,1);
      hLmapPc->SetBinContent(ii+1,ll/2+1,1);
      hSmapPc->SetBinError(ii+1,ll/2+1,1.e-6);
      hLmapPc->SetBinError(ii+1,ll/2+1,1.e-6);
      sprintf(ctit,"phaseHF/espec/E_+%d_%d_1",ieta,iphi);
      hLdatPx[ii][ll/2]  =   new TH1F(*((TH1F*)fila->Get(ctit)));
      hLdatPx[ii][ll/2]->SetAxisRange(Ethr1,Ethr2);
      rLP = hLdatPx[ii][ll/2]->Integral()*hLdatPx[ii][ll/2]->GetMean();
      hLmapP0->SetBinContent(ii+1,ll/2+1,rLP);
      sprintf(ctit,"phaseHF/espec/E_+%d_%d_2",ieta,iphi);
      hSdatPx[ii][ll/2]  =   new TH1F(*((TH1F*)fila->Get(ctit)));
      hSdatPx[ii][ll/2]->SetAxisRange(Ethr1,Ethr2);
      rSP = hSdatPx[ii][ll/2]->Integral()*hSdatPx[ii][ll/2]->GetMean();
      hSmapP0->SetBinContent(ii+1,ll/2+1,rSP);
      if (ieta<=32 && iphi==67) continue;
      if (rLP>0) {
	htL->Fill(rLP);
	mLE += rLP;
	nmLE++;
      }
      if (rSP>0) {
	htS->Fill(rSP);
	mSE += rSP;
	nmSE++;
      }
    }
    if (nmLE>0) mLE /= nmLE; 
    else continue;
    if (nmSE>0) mSE /= nmSE; 
    else continue;
    ccxx->cd(1); htL->Draw("hist");
    ccxx->cd(2); htS->Draw("hist");
    ccxx->Update();
    //histspec(htL,mLE,ermean,rms,4,3);
    //histspec(htS,mSE,ermean,rms,4,3);
    mLEphi[ii]=mLE;
    mSEphi[ii]=mSE;
    dmLEphi[ii]=htL->GetRMS();
    dmSEphi[ii]=htS->GetRMS();
    printf("ieta %2d :  <E>L= %8.1f (%6.1f) x %d    <E>S= %8.1f (%6.1f) x %d \n",
	   ieta,mLE,dmLEphi[ii],nmLE,mSE,dmSEphi[ii],nmSE);
    
    for (int jj=1;jj<=72;jj+=2) {
      int iphi=jj;
      if (abs(ieta)>39 && (iphi-1)%4==0) continue;
      if (ieta<=32 && iphi==67) {
	hLmapP->SetBinContent(ii+1,jj/2+1,hLmapP0->GetBinContent(ii+1,jj/2+1));
	hSmapP->SetBinContent(ii+1,jj/2+1,hSmapP0->GetBinContent(ii+1,jj/2+1));
	continue;
      }

      for (nIter=1;nIter<nIterN;nIter++) { //cout<<nIter<<" |  ";
	corrL=hLmapPc->GetBinContent(ii+1,jj/2+1);
	hLdatP[ii][jj/2]->Reset();

	for (int kk=1;kk<=hLdatPx[ii][jj/2]->GetNbinsX();kk++) {
	  xxL[kk-1]=hLdatPx[ii][jj/2]->GetBinCenter(kk);
	  yyL[kk-1]=hLdatPx[ii][jj/2]->GetBinContent(kk);
	}
	ttL = new TSpline5("tt",xxL,yyL,1000,"",10,20);

	for (int kk=1;kk<=hLdatP[ii][jj/2]->GetNbinsX();kk++) {
	  x=hLdatP[ii][jj/2]->GetBinCenter(kk);
	  y=hLdatP[ii][jj/2]->GetBinContent(kk);
	  hLdatP[ii][jj/2]->Fill(x*corrL,ttL->Eval(x)/8.0);
	}
	ttL->Delete();

	hLdatP[ii][jj/2]->SetAxisRange(Ethr1,Ethr2);
	rLP = hLdatP[ii][jj/2]->Integral()*hLdatP[ii][jj/2]->GetMean();
	dcorrL=(rLP-mLE)/mLE;
	if (rLP>0) drLP=
	      sqrt(pow(hLdatP[ii][jj/2]->GetMeanError()/hLdatP[ii][jj/2]->GetMean(),2)+
		   1.f/hLdatP[ii][jj/2]->Integral()+
		   pow(dcorrL/(1.0+sqrt((float) nIter)),2));
	else drLP=1.e-6;
	if (fabs(dcorrL)>0.001) { 
	  corrL*=1-dcorrL/(1.0+sqrt((float) nIter));
	  //printf("%2d : %2d / %2d / 1 %7.3f %7.3f\n",nIter,ieta,iphi,dcorrL,corrL);
	  hLmapPc->SetBinContent(ii+1,jj/2+1,corrL);
	  hLmapPc->SetBinError(ii+1,jj/2+1,corrL*drLP);
	  hLmapP->SetBinContent(ii+1,jj/2+1,rLP);
	}
	else {
	  printf("%2d : %2d / %2d / 1 %7.3f %8.4f %8.4f\n",nIter,ieta,iphi,dcorrL,corrL,corrL*drLP);
	  hLmapP->SetBinContent(ii+1,jj/2+1,rLP);
	  hLmapPc->SetBinError(ii+1,jj/2+1,corrL*drLP);
	  break;
	}
	if (nIter==nIterN-1) {
	  printf("%2d : %2d / %2d / 1 %7.3f %8.4f %8.4f\n",nIter,ieta,iphi,dcorrL,corrL,corrL*drLP);
	}
      }

      for (nIter=1;nIter<nIterN;nIter++) { //cout<<nIter<<" |  ";
	corrS=hSmapPc->GetBinContent(ii+1,jj/2+1);
	hSdatP[ii][jj/2]->Reset();

	for (int kk=1;kk<=hSdatPx[ii][jj/2]->GetNbinsX();kk++) {
	  xxS[kk-1]=hSdatPx[ii][jj/2]->GetBinCenter(kk);
	  yyS[kk-1]=hSdatPx[ii][jj/2]->GetBinContent(kk);
	}
	ttS = new TSpline5("tt",xxS,yyS,1000,"",10,20);

	for (int kk=1;kk<=hSdatP[ii][jj/2]->GetNbinsX();kk++) {
	  x=hSdatP[ii][jj/2]->GetBinCenter(kk);
	  y=hSdatP[ii][jj/2]->GetBinContent(kk);
	  hSdatP[ii][jj/2]->Fill(x*corrS,ttS->Eval(x)/8.0);
	}
	ttS->Delete();

	hSdatP[ii][jj/2]->SetAxisRange(Ethr1,Ethr2);
	rSP = hSdatP[ii][jj/2]->Integral()*hSdatP[ii][jj/2]->GetMean();
	dcorrS=(rSP-mSE)/mSE;
	if (rSP>0) drSP=sqrt(pow(hSdatP[ii][jj/2]->GetMeanError()/hSdatP[ii][jj/2]->GetMean(),2)+
			     1.f/hSdatP[ii][jj/2]->Integral()+
			     pow(dcorrS/(1.0+sqrt((float) nIter)),2));
	else drSP=1.e-6;
	if (fabs(dcorrS)>0.001) { 
	  corrS*=1-dcorrS/(1.0+sqrt((float) nIter));
	  //printf("%2d : %2d / %2d / 1 %7.3f %7.3f\n",nIter,ieta,iphi,dcorrS,corrS);
	  hSmapPc->SetBinContent(ii+1,jj/2+1,corrS);
	  hSmapPc->SetBinError(ii+1,jj/2+1,corrS*drSP);
	  hSmapP->SetBinContent(ii+1,jj/2+1,rSP);
	}
	else {
	  printf("%2d : %2d / %2d / 2 %7.3f %8.4f %8.4f\n",nIter,ieta,iphi,dcorrS,corrS,corrS*drSP);
	  hSmapP->SetBinContent(ii+1,jj/2+1,rSP);
	  hSmapPc->SetBinError(ii+1,jj/2+1,corrS*drSP);
	  break;
	}
	if (nIter==nIterN-1) {
	  printf("%2d : %2d / %2d / 2 %7.3f %8.4f %8.4f\n",nIter,ieta,iphi,dcorrS,corrS,corrS*drSP);
	}
      }
    }
  }
  //fila->Close();

  cout<<endl<<"Rings :  "<<endl;
  cout<<"       E L        "<<"E S        "<<"eta     "<<"delta eta"<<endl;
  double xeta[13], weta[13], reta[13];
  for (int i=29;i<=41;i++) {
    xeta[i-29]=(etaBounds[i-28]+etaBounds[i-29])/2;
    weta[i-29]=(etaBounds[i-28]-etaBounds[i-29]);
    mLEphi[i-29]=mLEphi[i-29]*36/weta[i-29];
    mSEphi[i-29]=mSEphi[i-29]*36/weta[i-29];
    dmLEphi[i-29]=dmLEphi[i-29]*36/weta[i-29];
    dmSEphi[i-29]=dmSEphi[i-29]*36/weta[i-29];
    if (i>39) {  mLEphi[i-29]/=2; mSEphi[i-29]/=2; dmLEphi[i-29]/=2; dmSEphi[i-29]/=2; }
    reta[i-29] = mSEphi[i-29]/mLEphi[i-29];
    cout<<i<<" :  "<<mLEphi[i-29]<<"    "<<mSEphi[i-29]<<"    "<<xeta[i-29]<<"   "<<weta[i-29]<<endl;
  }
  TCanvas *cgL = new TCanvas("cgL","cgL",300,300,600,600);
  TGraphErrors *grL = new TGraphErrors(13,xeta,mLEphi,0,dmLEphi);
  grL->SetTitle("HFP L;#eta;E_{Ring} / #Delta#eta_{Ring} ,  GeV");
  grL->SetMinimum(0);
  grL->SetMarkerStyle(20);
  grL->Draw("1+PAl");
  cgL->Print("pictHFplot/etaProfHFPL.gif");
  mSEphi[12]/=2; mSEphi[11]/=2;
  TCanvas *cgS = new TCanvas("cgS","cgS",300,300,600,600);
  TGraphErrors *grS = new TGraphErrors(13,xeta,mSEphi,0,dmSEphi);
  grS->SetTitle("HFP S;#eta;E_{Ring} / #Delta#eta_{Ring} ,  GeV");
  grS->SetMinimum(0);
  grS->SetMarkerStyle(20);
  grS->Draw("1+PAl");
  cgS->Print("pictHFplot/etaProfHFPS.gif");
  TCanvas *crg = new TCanvas("crg","crg",300,300,600,600);
  TGraphErrors *rg = new TGraphErrors(13,xeta,reta,0,0);
  rg->SetTitle("HFP;#eta;E(S) / E(L)");
  rg->SetMinimum(0);
  rg->Draw("1+PAl");
  crg->Print("pictHFplot/SoverLetaHFP.gif");

  TCanvas *cL0 = new TCanvas("cL0","cL0",0,0,650,600);
  hLmapP0->Draw("colz");
  cL0->Update();
  TCanvas *cS = new TCanvas("cS0","cS0",1000,0,650,600);
  hSmapP0->Draw("colz");
  cS0->Update();

  //TFile *histf = new TFile("HFPmc.root","RECREATE");

  FILE *ft1;
  //sprintf(ctit,"corrHFPmc_%d_%d.txt",((int) Ethr1),((int) Ethr2));
  sprintf(ctit,"corrHFP_%s_%d_%d.txt",ftit,((int) Ethr1),((int) Ethr2));
  if ((ft1 = fopen(ctit,"w"))==NULL){               // Open new file
    printf("\nNo file %s open => EXIT\n\n",file);
    return;
  }
  printf("\n\n File '%s' open \n\n",ctit);

  TH1D *hprL[13],*hprS[13],*hprL0[13],*hprS0[13];
  TH1D *hprcL[13],*hprcS[13];
  TCanvas *cpr[13],*ccc[13];
  TLine *lin1 = new TLine(0,1,71,1); lin1->SetLineWidth(1);

  int noff=0;
  for (int ii=0;ii<13;ii++) {

    sprintf(ctit,"HFPcorr_%d_L",ii+29);  // draw corrections
    hprcL[ii] = hLmapPc->ProjectionY(ctit,ii+1,ii+1);
    hprcL[ii]->SetTitle(ctit);
    sprintf(ctit,"HFPcorr_%d_S",ii+29);
    hprcS[ii] = hSmapPc->ProjectionY(ctit,ii+1,ii+1);
    hprcS[ii]->SetTitle(ctit);
    ccc[ii] = new TCanvas(ctit,ctit,800,100,500,900);
    ccc[ii]->Divide(1,2);
    ccc[ii]->cd(1);
    if (ii+29>39) {
      hprcL[ii]->Rebin(2);
      hprcS[ii]->Rebin(2);
    }
    hprcL[ii]->SetMinimum(0);
    hprcL[ii]->SetTitleOffset(0.9,"X");
    hprcL[ii]->Draw("e");
    lin1->Draw();
    ccc[ii]->cd(2);
    hprcS[ii]->SetMinimum(0);
    hprcS[ii]->SetTitleOffset(0.9,"X");
    hprcS[ii]->Draw("e");
    lin1->Draw();
    sprintf(ctit,"pictHFplot/HFPcorr_%d.gif",ii+29);
    ccc[ii]->Update();
    ccc[ii]->Print(ctit);
    //hprcL[ii]->Write();
    //hprcS[ii]->Write();

    sprintf(ctit,"HFP_%d_L",ii+29);  //  draw E depositions
    hprL0[ii] = hLmapP0->ProjectionY(ctit,ii+1,ii+1);
    sprintf(ctit,"HFP_%d_L;i#phi;GeV;",29+ii);  //  draw E depositions
    hprL0[ii]->SetTitle(ctit);
    sprintf(ctit,"HFP_L_%d",ii+29);
    hprL[ii] = hLmapP->ProjectionY(ctit,ii+1,ii+1);
    sprintf(ctit,"HFP_%d_S",ii+29);
    hprS0[ii] = hSmapP0->ProjectionY(ctit,ii+1,ii+1);
    sprintf(ctit,"HFP_%d_S;i#phi;GeV;",29+ii);  //  draw E depositions
    hprS0[ii]->SetTitle(ctit);
    sprintf(ctit,"HFP_S_%d",ii+29);
    hprS[ii] = hSmapP->ProjectionY(ctit,ii+1,ii+1);

    cpr[ii] = new TCanvas(ctit,ctit,800,100,500,900);
    cpr[ii]->Divide(1,2);
    cpr[ii]->cd(1);
    if (ii+29>39) {
      hprL0[ii]->Rebin(2);
      hprL[ii]->Rebin(2);
      hprS0[ii]->Rebin(2);
      hprS[ii]->Rebin(2);
    }
    hprL0[ii]->SetFillColor(3);hprL0[ii]->SetLineColor(3);hprL0[ii]->SetLineWidth(3);
    hprL0[ii]->SetMinimum(0);
    hprL0[ii]->SetTitleOffset(0.9,"X");
    hprL0[ii]->Draw("hist");
    hprL[ii]->Draw("samehist");
    cpr[ii]->cd(2);
    hprS0[ii]->SetMinimum(0);
    hprS0[ii]->SetTitleOffset(0.9,"X");
    hprS0[ii]->SetFillColor(3);hprS0[ii]->SetLineColor(3);hprS0[ii]->SetLineWidth(3);
    hprS0[ii]->Draw("hist");
    hprS[ii]->Draw("samehist");
    sprintf(ctit,"pictHFplot/HFP_%d.gif",ii+29);
    cpr[ii]->Print(ctit);
    //hprS0[ii]->Write();
    //hprL0[ii]->Write();

    cout<<"Results : "<<endl;
    for (int jj=1;jj<=72;jj+=2) {
      int ieta=ii+29;
      int iphi=jj;
      if (abs(ieta)>39 && (iphi-1)%4==0) continue;
      //if (ieta==29 && iphi==67) continue;
      corrL=hLmapPc->GetBinContent(ii+1,jj/2+1);
      corrS=hSmapPc->GetBinContent(ii+1,jj/2+1);
      dcorrL=hLmapPc->GetBinError(ii+1,jj/2+1);
      dcorrS=hSmapPc->GetBinError(ii+1,jj/2+1);
      hLcorr1D->Fill(corrL); hScorr1D->Fill(corrS);
      noff++;
      //printf("%2d : %2d / %2d / 1 %9.4f %9.4f\n",noff,ieta,iphi,corrL,dcorrL);
      fprintf(ft1,"%2d   %2d   1 %9.4f %9.4f\n",ieta,iphi,corrL,dcorrL);
      noff++;
      //printf("%2d : %2d / %2d / 2 %9.4f %9.4f\n",noff,ieta,iphi,corrS,dcorrS);
      fprintf(ft1,"%2d   %2d   2 %9.4f %9.4f\n",ieta,iphi,corrS,dcorrS);
    }
  }
  fclose(ft1);

  for (int ii=0;ii<13;ii++) for (int jj=1;jj<=72;jj+=2) {
      int ieta=ii+29;
      int iphi=jj;
      if (abs(ieta)>39 && (iphi-1)%4==0) continue;
      if (ieta==29 && iphi==67) continue;
      corrL=hLmapPc->GetBinContent(ii+1,jj/2+1);
      if (fabs(corrL-1)>0.16) printf("%2d / %2d / 1 %9.4f %9.4f\n",ieta,iphi,corrL,dcorrL);
      corrS=hSmapPc->GetBinContent(ii+1,jj/2+1);
      if (fabs(corrS-1)>0.16) printf("%2d / %2d / 2 %9.4f %9.4f\n",ieta,iphi,corrS,dcorrS);
  }

  TCanvas *cLcorr =new TCanvas("cLcorr","cLcorr",30,30,600,600);
  cLcorr->SetRightMargin(0.12);
  hLmapPc->SetAxisRange(0.6,1.6,"Z");
  hLmapPc->Draw("colz");
  TCanvas *cScorr =new TCanvas("cScorr","cScorr",30,300,600,600);
  cScorr->SetRightMargin(0.12);
  hSmapPc->SetAxisRange(0.6,1.6,"Z");
  hSmapPc->Draw("colz");

  TCanvas *cL = new TCanvas("cL","cL",0,0,650,600);
  hLmapP->Draw("colz");
  cL->Update();
  TCanvas *cS = new TCanvas("cS","cS",1000,0,650,600);
  hSmapP->Draw("colz");
  cS->Update();

  TCanvas *c1corr =new TCanvas("c1corr","c1corr",30,30,900,500);
  c1corr->Divide(2,1);
  c1corr->cd(1);  hLcorr1D->Draw("hist");  histStat(hLcorr1D,1);
  c1corr->cd(2);  hScorr1D->Draw("hist");  histStat(hScorr1D,1);
  //hLcorr1D->Write(); hScorr1D->Write();  

  c1corr->Print("pictHFplot/corrHFP.gif");
  //c1corr->Print("pictHFmc/corrHFP.gif");
  c1corr->Update();
  
  //fila->Close();
  //histf->Close();

  sprintf(ctit,"HFPo_%s_%d_%d.root",ftit,((int) Ethr1),((int) Ethr2));
  TFile *histf = new TFile(ctit,"RECREATE");
  hLcorr1D->Write(); 
  hScorr1D->Write();  
  hLmapP->Write(); 
  hLmapP0->Write(); 
  hLmapPc->Write(); 
  hSmapP->Write(); 
  hSmapP0->Write(); 
  hSmapPc->Write(); 
  grL->Write();
  grS->Write();
  histf->Close();
}
Esempio n. 14
0
void produceHisto(std::string outputName="", std::string var="0.692-9.240*ecalIso/pt-11.117*hcalIso/pt",double genIsoCut=5.0,bool normalize=false )
{
   if(outputName=="")outputName = var;
   vector<string> mixFile;
   vector<double> mixWeight;
   vector<TTree*> mixTree;
   vector<int> mixPtHatLo;
   vector<int> mixPtHatHi;

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

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


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

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

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

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

      nfile++; 
    }	 
	
   } 

   std::string treeName = "Analysis";

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

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


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

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

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

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


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

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

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

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


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

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

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

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

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


}
Esempio n. 15
0
// Function to draw EE, ME, MM channel and all channel merged plot
void cutStepPlots(const char* cutStep, const char* histNameTitle[2],
                  double minY, double maxY, bool doLogY)
{
 const char* histName = histNameTitle[0];
 const char* histTitle = histNameTitle[1];

  //cout << histName << " : " << histTitle << endl;

  TH1F* hDataEE = (TH1F*)fEE->Get(Form("%s/hData_%s_%s", cutStep, cutStep, histName));
  TH1F* hDataME = (TH1F*)fME->Get(Form("%s/hData_%s_%s", cutStep, cutStep, histName));
  TH1F* hDataMM = (TH1F*)fMM->Get(Form("%s/hData_%s_%s", cutStep, cutStep, histName));

  if ( !hDataEE ) { cout << Form("%s/hData_%s_%s", cutStep, cutStep, histName) << " for EE " << "\n"; return; }
  if ( !hDataME ) { cout << Form("%s/hData_%s_%s", cutStep, cutStep, histName) << " for ME " << "\n"; return; }
  if ( !hDataMM ) { cout << Form("%s/hData_%s_%s", cutStep, cutStep, histName) << " for MM " << "\n"; return; }


  TH1F* hDataLL = (TH1F*)hDataEE->Clone(Form("hData_%s_%s", cutStep, histName));
  hDataLL->Reset();
  hDataLL->Add(hDataEE);
  hDataLL->Add(hDataME);
  hDataLL->Add(hDataMM);

  THStack* hStackEE = new THStack(TString("hEE_")+cutStep+"_"+histName, histTitle);
  THStack* hStackME = new THStack(TString("hME_")+cutStep+"_"+histName, histTitle);
  THStack* hStackMM = new THStack(TString("hMM_")+cutStep+"_"+histName, histTitle);
  THStack* hStackLL = new THStack(TString("hLL_")+cutStep+"_"+histName, histTitle);

  TH1F* hSigEE = (TH1F*)fEE->Get(Form("%s/%s_%s_%s", cutStep, sigNames[0], cutStep, histName));
  TH1F* hSigME = (TH1F*)fME->Get(Form("%s/%s_%s_%s", cutStep, sigNames[0], cutStep, histName));
  TH1F* hSigMM = (TH1F*)fMM->Get(Form("%s/%s_%s_%s", cutStep, sigNames[0], cutStep, histName));

  hSigEE->SetFillColor(color_sig);
  hSigME->SetFillColor(color_sig);
  hSigMM->SetFillColor(color_sig);

  hSigEE->SetFillStyle(style_sig);
  hSigME->SetFillStyle(style_sig);
  hSigMM->SetFillStyle(style_sig);

  //hSigEE->SetLineColor(color_sig);
  //hSigME->SetLineColor(color_sig);
  //hSigMM->SetLineColor(color_sig);




  if ( !hSigEE || !hSigME || !hSigMM ) { cout << "No signal hist for " << histName << "\n"; return; }

  TH1F* hSigLL = (TH1F*)hSigEE->Clone(Form("%s_%s_%s", sigNames[0], cutStep, histName));
  hSigLL->Reset();
  hSigLL->Add(hSigEE);
  hSigLL->Add(hSigME);
  hSigLL->Add(hSigMM);

  if( stackSig ){
    hStackEE->Add(hSigEE);
    hStackME->Add(hSigME);
    hStackMM->Add(hSigMM);
    hStackLL->Add(hSigLL);
  }

  // Build legends
  TLegend* legEE = buildLegend();
  TLegend* legME = buildLegend();
  TLegend* legMM = buildLegend();
  TLegend* legLL = buildLegend();

  if ( hDataEE->GetEntries() > 0 ) legEE->AddEntry(hDataEE, "Data", "p");
  if ( hDataME->GetEntries() > 0 ) legME->AddEntry(hDataME, "Data", "p");
  if ( hDataMM->GetEntries() > 0 ) legMM->AddEntry(hDataMM, "Data", "p");
  if ( hDataLL->GetEntries() > 0 ) legLL->AddEntry(hDataLL, "Data", "p");

  TH1F* hEEs[nBkg];
  TH1F* hMEs[nBkg];
  TH1F* hMMs[nBkg];
  TH1F* hLLs[nBkg];

  for ( int i=0; i<nBkg; ++i )
  {
    TH1F* hEE = (TH1F*)fEE->Get(Form("%s/%s_%s_%s", cutStep, bkgNames[i], cutStep, histName));
    TH1F* hME = (TH1F*)fME->Get(Form("%s/%s_%s_%s", cutStep, bkgNames[i], cutStep, histName));
    TH1F* hMM = (TH1F*)fMM->Get(Form("%s/%s_%s_%s", cutStep, bkgNames[i], cutStep, histName));

    hEE->SetFillColor(color[i]);
    hME->SetFillColor(color[i]);
    hMM->SetFillColor(color[i]);

    hEE->SetFillStyle(style[i]);
    hME->SetFillStyle(style[i]);
    hMM->SetFillStyle(style[i]);

   // hEE->SetLineColor(color[i]);
   // hME->SetLineColor(color[i]);
   // hMM->SetLineColor(color[i]);


    if ( !hEE || !hME || !hMM ) { cout << "No bkg hist " << bkgNames[i] << endl; continue; }

    TH1F* hLL = (TH1F*)hEE->Clone(Form("%s_%s_%s", bkgNames[i], cutStep, histName));
    hLL->Reset();
    hLL->Add(hEE);
    hLL->Add(hME);
    hLL->Add(hMM);

    hEEs[i] = hEE;
    hMEs[i] = hME;
    hMMs[i] = hMM;
    hLLs[i] = hLL;

    hStackEE->Add(hEE);
    hStackME->Add(hME);
    hStackMM->Add(hMM);
    hStackLL->Add(hLL);
  }

  for ( int i=nBkg-1; i>=0; --i )
  {
    legEE->AddEntry(hEEs[i], bkgLabels[i], "f");
    legME->AddEntry(hMEs[i], bkgLabels[i], "f");
    legMM->AddEntry(hMMs[i], bkgLabels[i], "f");
    legLL->AddEntry(hLLs[i], bkgLabels[i], "f");
  }

  legEE->AddEntry(hSigEE, sigLabels[0], "f");
  legME->AddEntry(hSigME, sigLabels[0], "f");
  legMM->AddEntry(hSigMM, sigLabels[0], "f");
  legLL->AddEntry(hSigLL, sigLabels[0], "f");


  // Be ready for draw
  double YmaxEE = 0, YmaxMM=0, YmaxME=0, YmaxLL=0;
  YmaxEE = hDataEE->GetMaximum();
  YmaxMM = hDataMM->GetMaximum();
  YmaxME = hDataME->GetMaximum();
  YmaxLL = hDataLL->GetMaximum();

  hDataEE->SetMinimum(minY);
  hDataME->SetMinimum(minY);
  hDataMM->SetMinimum(minY);
  hDataLL->SetMinimum(minY);

  if(YmaxEE >YmaxMM) YmaxMM=YmaxEE;
  else               YmaxEE=YmaxMM;

  if(doLogY)
  {
    hDataEE->SetMaximum(YmaxEE*10000);
    hDataME->SetMaximum(YmaxME*10000);
    hDataMM->SetMaximum(YmaxMM*10000);
    hDataLL->SetMaximum(YmaxLL*10000);
  }
  else
  {
    hDataEE->SetMaximum(YmaxEE*2.5);
    hDataME->SetMaximum(YmaxME*2.5);
    hDataMM->SetMaximum(YmaxMM*2.5);
    hDataLL->SetMaximum(YmaxLL*2.5);
  }


  TCanvas* cEE = new TCanvas(TString("cEE_")+cutStep+"_"+histName, TString("cEE_")+cutStep+"_"+histName, 1);
  if ( doLogY ) cEE->SetLogy();
  hDataEE->Draw();
  legEE->Draw();
  getHeader(19.6, "ee channel")->Draw();
  hStackEE->Draw("same");
  hSigEE->Draw("same");
  hDataEE->Draw("same");
  hDataEE->Draw("sameaxis");

  if(doLogY)
  {
    cEE->Print(Form("%s/log/cEE_%s_%s.eps", outDirName.Data(), cutStep, histName));
    cEE->Print(Form("%s/log/cEE_%s_%s.pdf", outDirName.Data(), cutStep, histName));
    cEE->Print(Form("%s/log/cEE_%s_%s.png", outDirName.Data(), cutStep, histName));
  }
  else
  {
    cEE->Print(Form("%s/linear/cEE_%s_%s.eps", outDirName.Data(), cutStep, histName));
    cEE->Print(Form("%s/linear/cEE_%s_%s.pdf", outDirName.Data(), cutStep, histName));
    cEE->Print(Form("%s/linear/cEE_%s_%s.png", outDirName.Data(), cutStep, histName));
  }

  TCanvas* cME = new TCanvas(TString("cME_")+cutStep+"_"+histName, TString("cME_")+cutStep+"_"+histName, 1);
  if ( doLogY ) cME->SetLogy();
  hDataME->Draw();
  legME->Draw();
  getHeader(19.6, "#mue channel")->Draw();
  hStackME->Draw("same");
  if( nSig > 0 ) hSigME->Draw("same");
  hDataME->Draw("same");
  hDataME->Draw("sameaxis");

  if(doLogY)
  {
    cME->Print(Form("%s/log/cME_%s_%s.eps", outDirName.Data(), cutStep, histName));
    cME->Print(Form("%s/log/cME_%s_%s.pdf", outDirName.Data(), cutStep, histName));
    cME->Print(Form("%s/log/cME_%s_%s.png", outDirName.Data(), cutStep, histName));
  }
  else
  {
    cME->Print(Form("%s/linear/cME_%s_%s.eps", outDirName.Data(), cutStep, histName));
    cME->Print(Form("%s/linear/cME_%s_%s.pdf", outDirName.Data(), cutStep, histName));
    cME->Print(Form("%s/linear/cME_%s_%s.png", outDirName.Data(), cutStep, histName));
  }


  TCanvas* cMM = new TCanvas(TString("cMM_")+cutStep+"_"+histName, TString("cMM_")+cutStep+"_"+histName, 1);
  if ( doLogY ) cMM->SetLogy();
  hDataMM->Draw();
  legMM->Draw();
  getHeader(19.6, "#mu#mu channel")->Draw();
  hStackMM->Draw("same");
  hSigMM->Draw("same");
  hDataMM->Draw("same");
  hDataMM->Draw("sameaxis");

  if(doLogY)
  {
    cMM->Print(Form("%s/log/cMM_%s_%s.eps", outDirName.Data(), cutStep, histName));
    cMM->Print(Form("%s/log/cMM_%s_%s.pdf", outDirName.Data(), cutStep, histName));
    cMM->Print(Form("%s/log/cMM_%s_%s.png", outDirName.Data(), cutStep, histName));
  }
  else
  {
    cMM->Print(Form("%s/linear/cMM_%s_%s.eps", outDirName.Data(), cutStep, histName));
    cMM->Print(Form("%s/linear/cMM_%s_%s.pdf", outDirName.Data(), cutStep, histName));
    cMM->Print(Form("%s/linear/cMM_%s_%s.png", outDirName.Data(), cutStep, histName));
  } 

  TCanvas* cLL = new TCanvas(TString("cLL_")+cutStep+"_"+histName, TString("cLL_")+cutStep+"_"+histName, 1);
  if ( doLogY ) cLL->SetLogy();
  hDataLL->Draw();
  legLL->Draw();
  getHeader(19.6, "All channel")->Draw();
  hStackLL->Draw("same");
  if( !stackSig ) hSigLL->Draw("same");
  hDataLL->Draw("same");
  hDataLL->Draw("sameaxis");

  if(doLogY)
  {
    cLL->Print(Form("%s/log/cLL_%s_%s.eps", outDirName.Data(), cutStep, histName));
    cLL->Print(Form("%s/log/cLL_%s_%s.pdf", outDirName.Data(), cutStep, histName));
    cLL->Print(Form("%s/log/cLL_%s_%s.png", outDirName.Data(), cutStep, histName));
  } 
  else
  {
    cLL->Print(Form("%s/linear/cLL_%s_%s.eps", outDirName.Data(), cutStep, histName));
    cLL->Print(Form("%s/linear/cLL_%s_%s.pdf", outDirName.Data(), cutStep, histName));
    cLL->Print(Form("%s/linear/cLL_%s_%s.png", outDirName.Data(), cutStep, histName));
  }
}
Esempio n. 16
0
void calCrystalDepo(TTree *t1041, int ThisModule = -99, bool IsBatch =0){
  if(IsBatch) gROOT->SetBatch();

  TString ThisModuleString = TString::Itoa(ThisModule,10);
  int UpOrDown = ThisModule/abs(ThisModule);
  float Scale = 1.;
  if(UpOrDown == -1) Scale = 0.5;
  cout << "Creating energy distributions of events with maximum deposition in module: " << ThisModuleString << endl;
//Define Histograms

//This histogram is a tool
  TH1F* MatrixDepo = new TH1F("MatrixDepo", "Deposition on Matrix", 68, -17, 17);

  TH1F* fracDep = new TH1F("fracDep", "Highest Amplitude Crystal/Total Deposition", 100, 0, 1.2);
  TH1F* MaxBin = new TH1F("MaxBin", "Deposition of Highest Amplitude Crystal", 100,400*Scale,7000*Scale);
  TH1F* Integral = new TH1F("Integral", "Integral", 100,4000*Scale,13000*Scale);
  TH1F* SigNoise = new TH1F("SigNoise", "Signa/Pedestal", 100, 0, 2.);

//

  gStyle->SetOptStat(0);
  

  Mapper *mapper=Mapper::Instance();

  TBEvent *event = new TBEvent();
  t1041->SetBranchAddress("tbevent", &event);
  bool haverechits=false;
  vector<TBRecHit> *rechits=0;

  if(t1041->GetListOfBranches()->FindObject("tbrechits")) {
    cout <<"found rechits"<<endl;
    t1041->SetBranchAddress("tbrechits",&rechits);
    haverechits=true;
  }

  Int_t start=0; Int_t end=t1041->GetEntries();  
  
  int nEntries=0;
//  end = 10;
  for (Int_t i=start; i<end; i++) {
    t1041->GetEntry(i);
    if (i==0) mapper->SetEpoch(event->GetTimeStamp());
    if(haverechits && rechits->size() < 1) continue;

    MatrixDepo->Reset();
    float maxDepoModuleID = -99;
    float maxDepo = 0;
    float secondMaxDepo = 0;
    float secondMaxDepoModuleID = -99;
    float totdep = 0;
    float totalnoise = 0;
    float sumrms = 0;
    for (Int_t j = 0; j < event->NPadeChan(); j++){
      if (haverechits && j>=(int)rechits->size()) break;
      double ped,sig, max, maxTime;
      int channelID;
      if (haverechits){
	TBRecHit &hit=rechits->at(j);
	ped=hit.Pedestal();
	sig=hit.NoiseRMS();
	max=hit.AMax();
	maxTime=hit.TRise();
	channelID=hit.GetChannelID();
      }

      double x,y;
      int moduleID,fiberID;
      mapper->ChannelID2ModuleFiber(channelID,moduleID,fiberID);
      mapper->ModuleXY(moduleID,x,y);

      MatrixDepo->Fill(moduleID, max);      
      if(UpOrDown > 0 && moduleID > 0)	totalnoise+=ped;
      if(UpOrDown < 0 && moduleID < 0)	totalnoise+=ped;
    }

    int minx = 0;
    int maxx = 0;
    if(UpOrDown > 0){
      minx = MatrixDepo->GetXaxis()->FindBin(0.);
      maxx = MatrixDepo->GetXaxis()->FindBin(17.);
      MatrixDepo->GetXaxis()->SetRange(minx, maxx);
    }
    if(UpOrDown < 0){
      minx = MatrixDepo->GetXaxis()->FindBin(-17.);
      maxx = MatrixDepo->GetXaxis()->FindBin(0.);	
      MatrixDepo->GetXaxis()->SetRange(minx, maxx);
    }

//    cout << "TOTAL NOISE: " << totalnoise << endl;

    float maxbin = MatrixDepo->GetBinContent(MatrixDepo->GetMaximumBin());
    float integral = MatrixDepo->Integral(minx,maxx);

    maxDepoModuleID = MatrixDepo->GetBinLowEdge(MatrixDepo->GetMaximumBin());

    if( abs(ThisModule) != 99 && maxDepoModuleID != ThisModule ) continue;
    if( abs(ThisModule) == 100 ){
	if( abs(maxDepoModuleID) != 6 &&
	    abs(maxDepoModuleID) != 7 &&
	    abs(maxDepoModuleID) != 10 &&
	    abs(maxDepoModuleID) != 11) continue;
    }

    
//    if(sumrms/totdep > 0.3) continue;
//      if( maxDepo/totdep < 0.2 ||  maxDepo/totdep > 0.5) continue;
      if( maxbin/integral < .55) continue;
//      if( totdep/totalnoise < 1.) continue;
//      if( totdep < 950) continue;
//    if(sumrms/totdep < 0.3) cout << totdep << endl;




    MaxBin->Fill(maxbin);
    Integral->Fill(integral);
    fracDep->Fill(maxbin/integral);
//    cout << maxbin/integral;
//    SigNoise->Fill(integral/totalnoise);
//    cout << maxbin << endl;

    nEntries++;
  }

  TString FileFig;
  TCanvas *c5=new TCanvas("c5","Average Peak Height",800,800);
  c5->SetGrid();
  fracDep->Draw();
  FileFig = "energy/R9_Module_"+ThisModuleString+".png";
  c5->SaveAs(FileFig);

  TCanvas *c7=new TCanvas("c7","MAXBIN",800,800);
  c7->SetGrid();
//  MaxBin->Fit("gaus", "","", 4100, 6000);
  MaxBin->Draw();
  FileFig = "energy/eMaxCrystal_Module_"+ThisModuleString+".png";
  c7->SaveAs(FileFig);

  TCanvas *c8=new TCanvas("c8","Integral",800,800);
  c8->SetGrid();
//  TF1* fit = new TF1("fit","p0*exp(-(0.5)*((x-760)/p1)^2)",0, 3000);
//  fit->SetParameters(500, 50);
  Integral->Fit("gaus");//, "", "", 3000, 4000);
  gStyle->SetOptFit();
  Integral->Draw();
  FileFig = "energy/eMatrix_Module_"+ThisModuleString+".png";
  c8->SaveAs(FileFig);

  TCanvas *c9=new TCanvas("c9","Integral",800,800);
  c9->SetGrid();
  SigNoise->Draw();
  FileFig = "energy/SignalToNoise_Module"+ThisModuleString+".png";
  c9->SaveAs(FileFig);


}
Esempio n. 17
0
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;
}
Esempio n. 18
0
TH1F* JackknifammiStiHistos(std::vector<TH1F*> histos_splitted){

  int n = histos_splitted.size();
  assert (n>0);
  int nbins = histos_splitted.at(0)->GetNbinsX();
  for (int i=0; i<n; i++) assert(nbins==histos_splitted.at(i)->GetNbinsX());

#ifdef DEBUG
  for (int i=0; i<n; i++) cout << "split " << i << " " << histos_splitted.at(i)->GetBinContent(1) << endl;
  {
    float m = 0;
    for (int i=0;i<n; i++) m+=histos_splitted.at(i)->GetBinContent(1);
    m/=n;
    float v = 0;
    for (int i=0;i<n; i++) v+=pow(histos_splitted.at(i)->GetBinContent(1)-m,2);
    v/=(n-1);
    v/=n;
    cout << m*n << " +/- " << sqrt(v)*n << endl;
  }
#endif

  TH1F *hout = (TH1F*)(histos_splitted.at(0)->Clone("jackknife"));
  hout->Reset();

  std::vector<TH1F*> histos_resampled;
  for (int i=0; i<n; i++) {
    TH1F *resampled = (TH1F*)(hout->Clone(Form("resampled_%d",i)));
    resampled->Reset();
    for (int k=0; k<n; k++) if (k!=i) resampled->Add(histos_splitted.at(k));
    histos_resampled.push_back(resampled);
  }

  for (int j=1; j<nbins+1; j++){

    std::vector<float> v;
    for (int i=0; i<n; i++) v.push_back(histos_resampled.at(i)->GetBinContent(j));

    float mean = 0;
    for (int i=0; i<n; i++) mean += v.at(i)*n/(n-1);
    mean /= n;

    float var = 0;
    for (int i=0; i<n; i++) var += pow(v.at(i)*n/(n-1)-mean,2);
    var *= float(n-1)/n;

   
#ifdef DEBUG
    cout << "bin " << j << endl;
    for (int i=0; i<n; i++) cout << "est " << i << " " << v.at(i)*n/(n-1) << endl;
    cout << "mean " << mean << endl;
    cout << "std " << sqrt(var) << endl;
#endif

    hout->SetBinContent(j,mean);
    hout->SetBinError(j,sqrt(var));

  }

  for (int i=0; i<n; i++) delete histos_resampled.at(i);

  return hout;

};
Esempio n. 19
0
void checkflat(int icent = 0, int ihar=0){
    int color[nsub]={1,2,3,4,5,6,7,8};
    float pi = acos(-1.0);
    TString str;
    TFile *fin;
        TH1::SetDefaultSumw2();
        gStyle->SetOptStat(kFALSE);
        int iharE=0;
     if(nhar==1||nhar==2) iharE=1;
        int n = ihar+1.0+iharE;
    int nrun = GetTotalRun();
    float FitGood[nsub][1000];
    float FitGooderr[nsub][1000];
    float runlist[1000];
        TH1F* hpsi = new TH1F("psi","psi",100,-pi,pi);
        TH1F* hunpsi = new TH1F("unpsi","unpsi",100,-pi,pi);
        TH1F* h = new TH1F("h","",100,-4,4);
        for(int irun=0;irun<nrun;irun++){
        std::ifstream corrs("run15pAl200MBPro104.Lst");
        int index=0; int run=0;
        for(int jrun=0;jrun<irun+1;jrun++){
        corrs>>index>>run;
        }
        runlist[irun] = run;
       // system(Form("hadd -f /phenix/plhf/xuq/taxi/Run15pAl200MBPro104/10241/data/%d.root /phenix/plhf/xuq/taxi/Run15pAl200MBPro104/10241/data/%d_*.root",run,run));
        fin = TFile::Open(Form("/phenix/plhf/xuq/taxi/Run15pAl200MBPro104/10241/data/%d.root",run));
        for(int isub=0;isub<nsub;isub++){
        str = choosesub(isub);
        if(str=="ABORT") continue;
        hpsi->Reset();
        hunpsi->Reset();
        for(int ibbcz=0;ibbcz<nbbcz;ibbcz++){
          TH1F* hunpsitemp = (TH1F*)fin->Get(Form("psi_0_0_%d_%d_%d_%d",icent,ibbcz,ihar,isub));
          TH1F* hpsitemp = (TH1F*)fin->Get(Form("psiFla_0_0_%d_%d_%d_%d",icent,ibbcz,ihar,isub));
          hpsi->Add(hpsitemp);
          hunpsi->Add(hunpsitemp);
        }
        TF1 *fun = new TF1("fun","pol0",-pi,pi);
        TCanvas *c1 = new TCanvas("c1","c1",600,450);
        h->GetXaxis()->SetTitle(Form("#Psi_{%d}",n));
        h->GetYaxis()->SetTitle(Form("# of events"));
        h->GetYaxis()->SetRangeUser(hunpsi->GetBinContent(hunpsi->GetMinimumBin())*0.9,hunpsi->GetBinContent(hunpsi->GetMaximumBin())*1.1);
        h->Draw("C");
       // h->GetYaxis()->SetRangeUser(0,hunpsi->GetBinContent(hunpsi->GetMaximumBin())*1.2);
      if(hpsi->GetEntries()>1000){
	hpsi->Fit("fun","QR0");
	float par=fun->GetParameter(0);
	float parerr=fun->GetParError(0);
        FitGood[isub][irun]=fun->GetChisquare()/fun->GetNDF();
        FitGooderr[isub][irun]=0;
        fun->SetLineColor(4);
        fun->Draw("same");
      }
        else{
        FitGood[isub][irun]=0;
        FitGooderr[isub][irun]=0;
        }
        if(irun!=104) continue;
	hpsi->SetMarkerStyle(20);
	hpsi->SetMarkerSize(0.8);
	hpsi->SetMarkerColor(2);
	hpsi->SetLineColor(2);
	hunpsi->SetMarkerStyle(20);
	hunpsi->SetMarkerSize(0.8);
	hunpsi->SetMarkerColor(1);
	hunpsi->SetLineColor(1);
        TLegend *leg = new TLegend(0.4,0.7,0.8,0.85);
        leg->SetTextSize(0.04);
        leg->SetFillColor(0);
        leg->SetBorderSize(0);
        leg->AddEntry(hunpsi,Form("Run%d %s",run,str.Data()));
        leg->AddEntry(hunpsi,"before flattening","L");
        leg->AddEntry(hpsi,"After flattening","L");
        hpsi->Draw("Csame");
        hunpsi->Draw("Csame");
        leg->Draw("same");
        c1->Print(Form("run-by-run/checkflat_%d_%d_%d_%d.png",icent,ihar,isub,irun));
        delete c1;
        }
        fin->Close();
    }  
        TGraphErrors *grRun[nsub];
    TCanvas *c1 = new TCanvas("c1","c1",600,450);
    TCanvas *c2 = new TCanvas("c2","c2",600,450);
    TH1F* h1 = new TH1F("h1","",4000,436000,439000);
    h1->GetXaxis()->SetTitle(Form("Run Number"));
    h1->GetYaxis()->SetTitle("Fit #chi^{2}/Ndf");
    h1->GetXaxis()->SetRangeUser(runlist[0]-15,runlist[nrun-1]+15);
    h1->GetYaxis()->SetRangeUser(0,4);
    TLegend *leg = new TLegend(0.65,0.75,0.88,0.85);
    leg->SetTextSize(0.035);
    leg->SetBorderSize(0);
    leg->SetFillColor(0);
    c1->cd();
    h1->Draw("0");
        for(int isub=0;isub<nsub;isub++){
            if(isub!=4 && isub!=5) continue;
            grRun[isub] = new TGraphErrors(nrun,runlist,FitGood[isub],0,FitGooderr[isub]);
            grRun[isub] -> SetMarkerColor(isub-3);
            grRun[isub] -> SetMarkerSize(1.);
            grRun[isub] -> SetMarkerStyle(16+isub);
            grRun[isub] -> SetLineColor(isub-3);
            grRun[isub] -> Draw("Psame");
            leg->AddEntry(grRun[isub],choosesub(isub).Data(),"P");
        leg->Draw("same");
        }
      c1->Print(Form("run-by-run/fitsum%d.png",n));
}
void DrawErrorPropEle(int pt, bool data, bool analysisFake){
  
  TFile *F22=0, *F23=0;
  if(pt == 40 && !data)F22 = new TFile("DYtoEEWeightedProper74.root","READ");
  if(pt == 50 && !data)F22 = new TFile("DYtoEEWeightedProper74_Pt50.root","READ");
  
  if(pt == 40 && data){
    if(analysisFake)F22 = new TFile("Data_RunD_All_AnalysisFake_217fb.root","READ");
    else F22 = new TFile("Data_RunD_All_ExtendedFake_217fb.root","READ");
  }
  
  TH1F *h_DoubleElectron_MET_Reweighted = (TH1F*)F22->Get("h_DoubleElectron_MET_Reweighted");
  TH1F *h_DoubleElectron_MET_ReweightedNJets = (TH1F*)F22->Get("h_DoubleElectron_MET_ReweightedNJets");
  TH1F *h_DoubleElectron_MET_ReweightedDiEMPtNJets = (TH1F*)F22->Get("h_DoubleElectron_MET_ReweightedDiEMPtNJets");
  
  h_DoubleElectron_MET_Reweighted = getOverflow(h_DoubleElectron_MET_Reweighted);
  h_DoubleElectron_MET_ReweightedNJets = getOverflow(h_DoubleElectron_MET_ReweightedNJets);
  h_DoubleElectron_MET_ReweightedDiEMPtNJets = getOverflow(h_DoubleElectron_MET_ReweightedDiEMPtNJets);
  
  double integralall = h_DoubleElectron_MET_Reweighted->Integral();
  //h_DoubleElectron_MET_Reweighted->Scale(1./integralall);
  
  
  if(pt == 40 && !data)F23 = new TFile("GJet_Pt40_All.root","READ");
  if(pt == 50 && !data)F23 = new TFile("GJet_Pt40_All_Pt50.root","READ");
  if(pt == 40 && data){
    if(analysisFake)F23 = new TFile("Data_RunD_All_AnalysisFake_217fb.root","READ");
    else F23 = new TFile("Data_RunD_All_ExtendedFake_217fb.root","READ");
  }
  
  TH1F *h_DoubleFake_MET_Reweighted = (TH1F*)F23->Get("h_DoubleFake_MET_Reweighted");
  TH1F *h_DoubleFakeShowershape_MET_Reweighted = (TH1F*)F23->Get("h_DoubleFakeShowershape_MET_Reweighted");
  
  TH1F *h_DoubleFake_MET_ReweightedNJets = (TH1F*)F23->Get("h_DoubleFake_MET_ReweightedNJets");
  TH1F *h_DoubleFakeShowershape_MET_ReweightedNJets = (TH1F*)F23->Get("h_DoubleFakeShowershape_MET_ReweightedNJets");
  
  TH1F *h_DoubleFake_MET_ReweightedDiEMPtNJets = (TH1F*)F23->Get("h_DoubleFake_MET_ReweightedDiEMPtNJets");
  TH1F *h_DoubleFakeShowershape_MET_ReweightedDiEMPtNJets = (TH1F*)F23->Get("h_DoubleFakeShowershape_MET_ReweightedDiEMPtNJets");
  
  TH1F* h_DoubleElectron_NJets_Reweighted = (TH1F*)F23->Get("h_DoubleElectron_NJets_Reweighted");
  TH1F* h_DoubleFake_NJets_Reweighted = (TH1F*)F23->Get("h_DoubleFake_NJets_Reweighted");
  
  TH1F *h_DoubleElectron_MET_ReweightedDiEMPtNJets_From2DRatio = (TH1F*)F23->Get("h_DoubleElectron_MET_ReweightedDiEMPtNJets_From2DRatio");
  TH1F *h_DoubleFake_MET_ReweightedDiEMPtNJets_From2DRatio = (TH1F*)F23->Get("h_DoubleFake_MET_ReweightedDiEMPtNJets_From2DRatio");
  
  
  h_DoubleFake_MET_Reweighted = getOverflow(h_DoubleFake_MET_Reweighted);
  h_DoubleFakeShowershape_MET_Reweighted = getOverflow(h_DoubleFakeShowershape_MET_Reweighted);
  
  h_DoubleFake_MET_ReweightedNJets = getOverflow(h_DoubleFake_MET_ReweightedNJets);
  h_DoubleFakeShowershape_MET_ReweightedNJets = getOverflow(h_DoubleFakeShowershape_MET_ReweightedNJets);
  
  h_DoubleFake_MET_ReweightedDiEMPtNJets = getOverflow(h_DoubleFake_MET_ReweightedDiEMPtNJets);
  h_DoubleFakeShowershape_MET_ReweightedDiEMPtNJets = getOverflow(h_DoubleFakeShowershape_MET_ReweightedDiEMPtNJets);
  
  h_DoubleElectron_NJets_Reweighted = getOverflow(h_DoubleElectron_NJets_Reweighted);
  h_DoubleFake_NJets_Reweighted = getOverflow(h_DoubleFake_NJets_Reweighted);
  
  h_DoubleElectron_MET_ReweightedDiEMPtNJets_From2DRatio = getOverflow(h_DoubleElectron_MET_ReweightedDiEMPtNJets_From2DRatio);
  h_DoubleFake_MET_ReweightedDiEMPtNJets_From2DRatio = getOverflow(h_DoubleFake_MET_ReweightedDiEMPtNJets_From2DRatio);
  
  
  double integralff = h_DoubleFake_MET_Reweighted->Integral();
  //h_DoubleFake_MET_Reweighted->Scale(1./integralff);
  double integralffshowershape = h_DoubleFakeShowershape_MET_Reweighted->Integral();
  //h_DoubleFakeShowershape_MET_Reweighted->Scale(1./integralffshowershape);
  
  
  //Float_t bins2[] = {0,5,10,15,20,25,30,35,40,45,50,55,60,70,80,100,125,175,250,400};
  //Int_t  binnum2 = sizeof(bins2)/sizeof(Float_t) - 1; 
  TH1F* ErrorPropDiEMPteeMET;
  TH1F* ErrorPropDiEMPtffMET;
  TH1F* ErrorPropDiEMPtffshowershapeMET;
  
  TH1F* ErrorPropNJetseeMET;
  TH1F* ErrorPropNJetsffMET;
  TH1F* ErrorPropNJetsffshowershapeMET;
  
  TH1F* ErrorPropDiEMPtNJetseeMET;
  TH1F* ErrorPropDiEMPtNJetsffMET;
  TH1F* ErrorPropDiEMPtNJetsffshowershapeMET;
  
  TH1F* ErrorPropDiEMPtWeightedNJetsee;
  TH1F* ErrorPropDiEMPtWeightedNJetsff;
  
  
  TH1F* ErrorPropDiEMPtVsNJetWeightedee;
  TH1F* ErrorPropDiEMPtVsNJetWeightedff;
  
  
  ErrorPropDiEMPteeMET = (TH1F*)h_DoubleElectron_MET_Reweighted->Clone("ErrorPropDiEMPteeMET");
  ErrorPropDiEMPteeMET->Reset();
  ErrorPropDiEMPteeMET->SetTitle("ee E_{T}^{miss} with error propagation from diempt");
  
  ErrorPropDiEMPtffMET = (TH1F*)h_DoubleFake_MET_Reweighted->Clone("ErrorPropDiEMPtffMET");
  ErrorPropDiEMPtffMET->Reset();
  ErrorPropDiEMPtffMET->SetTitle("ff E_{T}^{miss} with error propagation from diempt");
  
  ErrorPropDiEMPtffshowershapeMET = (TH1F*)h_DoubleFakeShowershape_MET_Reweighted->Clone("ErrorPropDiEMPtffshowershapeMET");
  ErrorPropDiEMPtffshowershapeMET->Reset();
  ErrorPropDiEMPtffshowershapeMET->SetTitle("ff E_{T}^{miss} with error propagation from diempt");
  
  
  
  ErrorPropNJetseeMET = (TH1F*)h_DoubleElectron_MET_ReweightedNJets->Clone("ErrorPropNJetseeMET");
  ErrorPropNJetseeMET->Reset();
  ErrorPropNJetseeMET->SetTitle("ee E_{T}^{miss} with error propagation from njets");
  
  ErrorPropNJetsffMET = (TH1F*)h_DoubleFake_MET_ReweightedNJets->Clone("ErrorPropNJetsffMET");
  ErrorPropNJetsffMET->Reset();
  ErrorPropNJetsffMET->SetTitle("ff E_{T}^{miss} with error propagation from njets");
  
  ErrorPropNJetsffshowershapeMET = (TH1F*)h_DoubleFakeShowershape_MET_ReweightedNJets->Clone("ErrorPropNJetsffshowershapeMET");
  ErrorPropNJetsffshowershapeMET->Reset();
  ErrorPropNJetsffshowershapeMET->SetTitle("ff E_{T}^{miss} with error propagation from njets");
  
  
  
  ErrorPropDiEMPtNJetseeMET = (TH1F*)h_DoubleElectron_MET_ReweightedDiEMPtNJets->Clone("ErrorPropDiEMPtNJetseeMET");
  ErrorPropDiEMPtNJetseeMET->Reset();
  ErrorPropDiEMPtNJetseeMET->SetTitle("ee E_{T}^{miss} with error propagation from njets");
  
  ErrorPropDiEMPtNJetsffMET = (TH1F*)h_DoubleFake_MET_ReweightedDiEMPtNJets->Clone("ErrorPropDiEMPtNJetsffMET");
  ErrorPropDiEMPtNJetsffMET->Reset();
  ErrorPropDiEMPtNJetsffMET->SetTitle("ff E_{T}^{miss} with error propagation from njets");
  
  ErrorPropDiEMPtNJetsffshowershapeMET = (TH1F*)h_DoubleFakeShowershape_MET_ReweightedDiEMPtNJets->Clone("ErrorPropDiEMPtNJetsffshowershapeMET");
  ErrorPropDiEMPtNJetsffshowershapeMET->Reset();
  ErrorPropDiEMPtNJetsffshowershapeMET->SetTitle("ff E_{T}^{miss} with error propagation from njets");
  
  
  ErrorPropDiEMPtWeightedNJetsee = (TH1F*)h_DoubleElectron_NJets_Reweighted->Clone("ErrorPropDiEMPtWeightedNJetsee");
  ErrorPropDiEMPtWeightedNJetsee->Reset();
  ErrorPropDiEMPtWeightedNJetsee->SetTitle("ee Njets with error propagation from diempt");
  
  
  ErrorPropDiEMPtWeightedNJetsff = (TH1F*)h_DoubleFake_NJets_Reweighted->Clone("ErrorPropDiEMPtWeightedNJetsff");
  ErrorPropDiEMPtWeightedNJetsff->Reset();
  ErrorPropDiEMPtWeightedNJetsff->SetTitle("ff Njets with error propagation from diempt");
  
  
  ErrorPropDiEMPtVsNJetWeightedee = (TH1F*)h_DoubleElectron_MET_ReweightedDiEMPtNJets_From2DRatio->Clone("ErrorPropDiEMPtVsNJetWeightedee");
  ErrorPropDiEMPtVsNJetWeightedee->Reset();
  ErrorPropDiEMPtVsNJetWeightedee->SetTitle("ee diEMPt vs NJet error propagation");
  
  
  ErrorPropDiEMPtVsNJetWeightedff = (TH1F*)h_DoubleFake_MET_ReweightedDiEMPtNJets_From2DRatio->Clone("ErrorPropDiEMPtVsNJetWeightedff");
  ErrorPropDiEMPtVsNJetWeightedff->Reset();
  ErrorPropDiEMPtVsNJetWeightedff->SetTitle("ff diEMPt vs NJet error propagation");
  
  

  TH1F *DiEMPtRatioWeightedee[1000], *DiEMPtRatioWeightedff[1000], *DiEMPtRatioWeightedffshowershape[1000];
  TH1F *NJetsRatioWeightedee[1000], *NJetsRatioWeightedff[1000], *NJetsRatioWeightedffshowershape[1000];
  TH1F *DiEMPtRatioWeightedeeNJets[1000], *DiEMPtRatioWeightedffNJets[1000];
  
  TH1F *DiEMPtVsNJetRatioWeightedee[1000], *DiEMPtVsNJetRatioWeightedff[1000];
  
  
  for(int g=0; g<1000; ++g){
    char *nameGraph3        = new char[50];
    
    sprintf(nameGraph3,"DiEMPtReweightedee%d",g+1);
    DiEMPtRatioWeightedee[g] = (TH1F*)F22->Get(nameGraph3);
    //double w = DiEMPtRatioWeightedee[g]->Integral();
    //DiEMPtRatioWeightedee[g]->Scale(1./w);
    
    sprintf(nameGraph3,"DiEMPtReweightedff%d",g+1);
    DiEMPtRatioWeightedff[g] = (TH1F*)F23->Get(nameGraph3);
    //double w2 = DiEMPtRatioWeightedff[g]->Integral();
    //DiEMPtRatioWeightedff[g]->Scale(1./w2);
    
    sprintf(nameGraph3,"DiEMPtReweightedffshowershape%d",g+1);
    DiEMPtRatioWeightedffshowershape[g] = (TH1F*)F23->Get(nameGraph3);
    //double w3 = DiEMPtRatioWeightedffshowershape[g]->Integral();
    //DiEMPtRatioWeightedffshowershape[g]->Scale(1./w3);
    
    
    sprintf(nameGraph3,"NJetsReweightedee%d",g+1);
    NJetsRatioWeightedee[g] = (TH1F*)F22->Get(nameGraph3);
    //double w = DiEMPtRatioWeightedee[g]->Integral();
    //DiEMPtRatioWeightedee[g]->Scale(1./w);
    
    sprintf(nameGraph3,"NJetsReweightedff%d",g+1);
    NJetsRatioWeightedff[g] = (TH1F*)F23->Get(nameGraph3);
    //double w2 = DiEMPtRatioWeightedff[g]->Integral();
    //DiEMPtRatioWeightedff[g]->Scale(1./w2);
    
    sprintf(nameGraph3,"NJetsReweightedffshowershape%d",g+1);
    NJetsRatioWeightedffshowershape[g] = (TH1F*)F23->Get(nameGraph3);
    //double w3 = DiEMPtRatioWeightedffshowershape[g]->Integral();
    //DiEMPtRatioWeightedffshowershape[g]->Scale(1./w3);
    
    sprintf(nameGraph3, "DiEMPtReweightedNJetsee%d",g+1);
    DiEMPtRatioWeightedeeNJets[g] = (TH1F*)F23->Get(nameGraph3);
    
    sprintf(nameGraph3, "DiEMPtReweightedNJetsff%d",g+1);
    DiEMPtRatioWeightedffNJets[g] = (TH1F*)F23->Get(nameGraph3);
    
    
    sprintf(nameGraph3, "DiEMPtVsNJetReweightedee%d",g+1);
    DiEMPtVsNJetRatioWeightedee[g] = (TH1F*)F23->Get(nameGraph3);
    
    sprintf(nameGraph3, "DiEMPtVsNJetReweightedff%d",g+1);
    DiEMPtVsNJetRatioWeightedff[g] = (TH1F*)F23->Get(nameGraph3);
    
  }

  


  double xbindiempt[50][1000]                 = {{0},{0}};
  double centraldiempt[50]                    = {0};
  double errorupdiempt[50]                    = {0};
  double errordowndiempt[50]                  = {0};
  
  double xbinffdiempt[50][1000]                 = {{0},{0}};
  double centralffdiempt[50]                    = {0};
  double errorupffdiempt[50]                    = {0};
  double errordownffdiempt[50]                  = {0};
  
  
  double xbindiemptreweightednjetsee[50][1000]   = {{0},{0}};
  double centraldiemptreweightednjetsee[50]      = {0};
  double errorupdiemptreweightednjetsee[50]      = {0};
  double errordowndiemptreweightednjetsee[50]    = {0};
  
  
  double xbindiemptreweightednjetsff[50][1000]   = {{0},{0}};
  double centraldiemptreweightednjetsff[50]      = {0};
  double errorupdiemptreweightednjetsff[50]      = {0};
  double errordowndiemptreweightednjetsff[50]    = {0};
  
  
  double xbinffshowershapediempt[50][1000]      = {{0},{0}};
  double centralffshowershapediempt[50]         = {0};
  double errorupffshowershapediempt[50]         = {0};
  double errordownffshowershapediempt[50]       = {0};
  
  
  double xbinnjets[50][1000]                 = {{0},{0}};
  double centralnjets[50]                    = {0};
  double errorupnjets[50]                    = {0};
  double errordownnjets[50]                  = {0};
  
  double xbinffnjets[50][1000]                 = {{0},{0}};
  double centralffnjets[50]                    = {0};
  double errorupffnjets[50]                    = {0};
  double errordownffnjets[50]                  = {0};
  
  double xbinffshowershapenjets[50][1000]      = {{0},{0}};
  double centralffshowershapenjets[50]         = {0};
  double errorupffshowershapenjets[50]         = {0};
  double errordownffshowershapenjets[50]       = {0};
  
  
  double totalerrordiempt[50]               = {0};
  double totalerrorffdiempt[50]             = {0};
  double totalerrorffshowershapediempt[50]  = {0};
  
  double totalerrornjets[50]               = {0};
  double totalerrorffnjets[50]             = {0};
  double totalerrorffshowershapenjets[50]  = {0};
  
  
  double totalerror[50]                     = {0};
  double totalerrorff[50]                   = {0};
  double totalerrorffshowershape[50]        = {0};
  
  
  double totalerrordiemptreweightednjetsee[50] = {0};
  double totalerrordiemptreweightednjetsff[50] = {0};
  
  
  
  
  
  double xbindiemptvsnjetsee[50][1000]                 = {{0},{0}};
  double centraldiemptvsnjetsee[50]                    = {0};
  double errorupdiemptvsnjetsee[50]                    = {0};
  double errordowndiemptvsnjetsee[50]                  = {0};
  
  double xbindiemptvsnjetsff[50][1000]                 = {{0},{0}};
  double centraldiemptvsnjetsff[50]                    = {0};
  double errorupdiemptvsnjetsff[50]                    = {0};
  double errordowndiemptvsnjetsff[50]                  = {0};
  
  double totalerrordiemptvsnjetreweightedee[50] = {0};
  double totalerrordiemptvsnjetreweightedff[50] = {0};

  for(int j=0 ; j < ErrorPropDiEMPteeMET->GetNbinsX() ; ++j){
    
    double mindiempt(100000000), minffdiempt(100000000), minffshowershapediempt(10000000);
    double maxdiempt(-10), maxffdiempt(-10), maxffshowershape(-10);
    
    double minnjets(100000000), minffnjets(100000000), minffshowershapenjets(10000000);
    double maxnjets(-10), maxffnjets(-10), maxffshowershapenjets(-10);
    
    double mindiemptvsnjetsee(100000000), mindiemptvsnjetsff(100000000);
    double maxdiemptvsnjetsee(-10), maxdiemptvsnjetsff(-10);
    
    
  
    for(int k=0 ; k<1000; ++k){
      xbindiempt[j][k]       = DiEMPtRatioWeightedee[k]->GetBinContent(j+1);
      if(maxdiempt < xbindiempt[j][k])maxdiempt=xbindiempt[j][k];
      if(mindiempt > xbindiempt[j][k])mindiempt=xbindiempt[j][k];
      
      
      xbinffdiempt[j][k]       = DiEMPtRatioWeightedff[k]->GetBinContent(j+1);
      if(maxffdiempt < xbinffdiempt[j][k])maxffdiempt=xbinffdiempt[j][k];
      if(minffdiempt > xbinffdiempt[j][k])minffdiempt=xbinffdiempt[j][k];
      
      xbinffshowershapediempt[j][k]       = DiEMPtRatioWeightedffshowershape[k]->GetBinContent(j+1);
      if(maxffshowershape < xbinffshowershapediempt[j][k])maxffshowershape=xbinffshowershapediempt[j][k];
      if(minffshowershapediempt > xbinffshowershapediempt[j][k])minffshowershapediempt=xbinffshowershapediempt[j][k];
      
      
      xbinnjets[j][k]       = NJetsRatioWeightedee[k]->GetBinContent(j+1);
      if(maxnjets < xbinnjets[j][k])maxnjets=xbinnjets[j][k];
      if(minnjets > xbinnjets[j][k])minnjets=xbinnjets[j][k];
      
      xbinffnjets[j][k]       = NJetsRatioWeightedff[k]->GetBinContent(j+1);
      if(maxffnjets < xbinffnjets[j][k])maxffnjets=xbinffnjets[j][k];
      if(minffnjets > xbinffnjets[j][k])minffnjets=xbinffnjets[j][k];
      
      xbinffshowershapenjets[j][k]       = NJetsRatioWeightedffshowershape[k]->GetBinContent(j+1);
      if(maxffshowershapenjets < xbinffshowershapenjets[j][k])maxffshowershapenjets=xbinffshowershapenjets[j][k];
      if(minffshowershapenjets > xbinffshowershapenjets[j][k])minffshowershapenjets=xbinffshowershapenjets[j][k];
      
      
      xbindiemptvsnjetsee[j][k]       = DiEMPtVsNJetRatioWeightedee[k]->GetBinContent(j+1);
      if(maxdiemptvsnjetsee < xbindiemptvsnjetsee[j][k])maxdiemptvsnjetsee=xbindiemptvsnjetsee[j][k];
      if(mindiemptvsnjetsee > xbindiemptvsnjetsee[j][k])mindiemptvsnjetsee=xbindiemptvsnjetsee[j][k];
      
      xbindiemptvsnjetsff[j][k]       = DiEMPtVsNJetRatioWeightedff[k]->GetBinContent(j+1);
      if(maxdiemptvsnjetsff < xbindiemptvsnjetsff[j][k])maxdiemptvsnjetsff=xbindiemptvsnjetsff[j][k];
      if(mindiemptvsnjetsff > xbindiemptvsnjetsff[j][k])mindiemptvsnjetsff=xbindiemptvsnjetsff[j][k];
      
    }
    
    centraldiempt[j]   = h_DoubleElectron_MET_Reweighted->GetBinContent(j+1);
    errorupdiempt[j]   = 0.68*(maxdiempt-centraldiempt[j]);
    errordowndiempt[j] = 0.68*(centraldiempt[j]-mindiempt); 
    
    centralffdiempt[j]   = h_DoubleFake_MET_Reweighted->GetBinContent(j+1);
    errorupffdiempt[j]   = 0.68*(maxffdiempt-centralffdiempt[j]);
    errordownffdiempt[j] = 0.68*(centralffdiempt[j]-minffdiempt); 
    
    centralffshowershapediempt[j]   = h_DoubleFakeShowershape_MET_Reweighted->GetBinContent(j+1);
    errorupffshowershapediempt[j]   = 0.68*(maxffshowershape-centralffshowershapediempt[j]);
    errordownffshowershapediempt[j] = 0.68*(centralffshowershapediempt[j]-minffshowershapediempt); 



    centralnjets[j]   = h_DoubleElectron_MET_ReweightedNJets->GetBinContent(j+1);
    errorupnjets[j]   = 0.68*(maxnjets-centralnjets[j]);
    errordownnjets[j] = 0.68*(centralnjets[j]-minnjets); 
    
    centralffnjets[j]   = h_DoubleFake_MET_ReweightedNJets->GetBinContent(j+1);
    errorupffnjets[j]   = 0.68*(maxffnjets-centralffnjets[j]);
    errordownffnjets[j] = 0.68*(centralffnjets[j]-minffnjets); 
    
    centralffshowershapenjets[j]   = h_DoubleFakeShowershape_MET_ReweightedNJets->GetBinContent(j+1);
    errorupffshowershapenjets[j]   = 0.68*(maxffshowershapenjets-centralffshowershapenjets[j]);
    errordownffshowershapenjets[j] = 0.68*(centralffshowershapenjets[j]-minffshowershapenjets);
    
    
    totalerrordiempt[j] = sqrt((errorupdiempt[j]+errordowndiempt[j])*(errorupdiempt[j]+errordowndiempt[j])); 
    totalerrorffdiempt[j] = sqrt((errorupffdiempt[j]+errordownffdiempt[j])*(errorupffdiempt[j]+errordownffdiempt[j]));
    totalerrorffshowershapediempt[j] = sqrt((errorupffshowershapediempt[j]+errordownffshowershapediempt[j])*(errorupffshowershapediempt[j]+errordownffshowershapediempt[j]));
    
    totalerrornjets[j] = sqrt((errorupnjets[j]+errordownnjets[j])*(errorupnjets[j]+errordownnjets[j])); 
    totalerrorffnjets[j] = sqrt((errorupffnjets[j]+errordownffnjets[j])*(errorupffnjets[j]+errordownffnjets[j]));
    totalerrorffshowershapenjets[j] = sqrt((errorupffshowershapenjets[j]+errordownffshowershapenjets[j])*(errorupffshowershapenjets[j]+errordownffshowershapenjets[j]));
    
    totalerror[j] = sqrt(totalerrordiempt[j]*totalerrordiempt[j]+totalerrornjets[j]*totalerrornjets[j]);
    totalerrorff[j] = sqrt(totalerrorffdiempt[j]*totalerrorffdiempt[j]+totalerrorffnjets[j]*totalerrorffnjets[j]);
    totalerrorffshowershape[j] = sqrt(totalerrorffshowershapediempt[j]*totalerrorffshowershapediempt[j]+totalerrorffshowershapenjets[j]*totalerrorffshowershapenjets[j]);
    
    
    
    double metvalue = h_DoubleElectron_MET_Reweighted->GetBinContent(j+1);
    ErrorPropDiEMPteeMET->SetBinContent(j+1, metvalue);
    ErrorPropDiEMPteeMET->SetBinError(j+1, totalerrordiempt[j]);
    //cout << "ee bin: " << j << " total error diempt: " << totalerrordiempt[j] << " and E_{T}^{miss} value: " << metvalue << endl;
    double metvalue2 = h_DoubleFake_MET_Reweighted->GetBinContent(j+1);
    ErrorPropDiEMPtffMET->SetBinContent(j+1, metvalue2);
    ErrorPropDiEMPtffMET->SetBinError(j+1, totalerrorffdiempt[j]);
    //cout << "ff bin: " << j << " total error diempt: " << totalerrorffdiempt[j] << " and E_{T}^{miss} value: " << metvalue2 << endl;
    
    double metvalue3 = h_DoubleFakeShowershape_MET_Reweighted->GetBinContent(j+1);
    ErrorPropDiEMPtffshowershapeMET->SetBinContent(j+1, metvalue3);
    ErrorPropDiEMPtffshowershapeMET->SetBinError(j+1, totalerrorffshowershapediempt[j]);
    
    
    
    
    double metvalue4 = h_DoubleElectron_MET_ReweightedNJets->GetBinContent(j+1);
    ErrorPropNJetseeMET->SetBinContent(j+1, metvalue4);
    ErrorPropNJetseeMET->SetBinError(j+1, totalerrornjets[j]);
    //cout << "ee bin: " << j << " total error njet: " << totalerrornjets[j] << " and E_{T}^{miss} value: " << metvalue4 << endl;
    double metvalue5 = h_DoubleFake_MET_ReweightedNJets->GetBinContent(j+1);
    ErrorPropNJetsffMET->SetBinContent(j+1, metvalue5);
    ErrorPropNJetsffMET->SetBinError(j+1, totalerrorffnjets[j]);
    //cout << "ff bin: " << j << " total error njet: " << totalerrorffnjets[j] << " and E_{T}^{miss} value: " << metvalue2 << endl;
    
    double metvalue6 = h_DoubleFakeShowershape_MET_ReweightedNJets->GetBinContent(j+1);
    ErrorPropNJetsffshowershapeMET->SetBinContent(j+1, metvalue6);
    ErrorPropNJetsffshowershapeMET->SetBinError(j+1, totalerrorffshowershapenjets[j]);
    
    
    
    metvalue4 = h_DoubleElectron_MET_ReweightedDiEMPtNJets->GetBinContent(j+1);
    ErrorPropDiEMPtNJetseeMET->SetBinContent(j+1, metvalue4);
    ErrorPropDiEMPtNJetseeMET->SetBinError(j+1, totalerror[j]);
    //cout << "ee bin: " << j << " total error: " << totalerror[j] << " and E_{T}^{miss} value: " << metvalue4 << endl;
    
    metvalue5 = h_DoubleFake_MET_ReweightedDiEMPtNJets->GetBinContent(j+1);
    ErrorPropDiEMPtNJetsffMET->SetBinContent(j+1, metvalue5);
    ErrorPropDiEMPtNJetsffMET->SetBinError(j+1, totalerrorff[j]);
    //cout << "ff bin: " << j << " total error: " << totalerrorff[j] << " and E_{T}^{miss} value: " << metvalue2 << endl;
    
    metvalue6 = h_DoubleFakeShowershape_MET_ReweightedDiEMPtNJets->GetBinContent(j+1);
    ErrorPropDiEMPtNJetsffshowershapeMET->SetBinContent(j+1, metvalue6);
    ErrorPropDiEMPtNJetsffshowershapeMET->SetBinError(j+1, totalerrorffshowershapenjets[j]);
    
    
    
    
    // from 2D plots
    centraldiemptvsnjetsee[j]     = h_DoubleElectron_MET_ReweightedDiEMPtNJets_From2DRatio->GetBinContent(j+1);
    errorupdiemptvsnjetsee[j]     = 0.68*(maxdiemptvsnjetsee - centraldiemptvsnjetsee[j]);
    errordowndiemptvsnjetsee[j]   = 0.68*(centraldiemptvsnjetsee[j] - mindiemptvsnjetsee);
    
    
    centraldiemptvsnjetsff[j]     = h_DoubleFake_MET_ReweightedDiEMPtNJets_From2DRatio->GetBinContent(j+1);
    errorupdiemptvsnjetsff[j]     = 0.68*(maxdiemptvsnjetsff - centraldiemptvsnjetsff[j]);
    errordowndiemptvsnjetsff[j]   = 0.68*(centraldiemptvsnjetsff[j] - mindiemptvsnjetsff);
    
    
    totalerrordiemptvsnjetreweightedee[j] = sqrt((errorupdiemptvsnjetsee[j]+errordowndiemptvsnjetsee[j])*(errorupdiemptvsnjetsee[j]+errordowndiemptvsnjetsee[j]));
    totalerrordiemptvsnjetreweightedff[j] = sqrt((errorupdiemptvsnjetsff[j]+errordowndiemptvsnjetsff[j])*(errorupdiemptvsnjetsff[j]+errordowndiemptvsnjetsff[j]));
    
    metvalue5 = h_DoubleElectron_MET_ReweightedDiEMPtNJets_From2DRatio->GetBinContent(j+1);
    ErrorPropDiEMPtVsNJetWeightedee->SetBinContent(j+1, metvalue5);
    ErrorPropDiEMPtVsNJetWeightedee->SetBinError(j+1, totalerrordiemptvsnjetreweightedee[j]);
    
    metvalue5 = h_DoubleFake_MET_ReweightedDiEMPtNJets_From2DRatio->GetBinContent(j+1);
    ErrorPropDiEMPtVsNJetWeightedff->SetBinContent(j+1, metvalue5);
    ErrorPropDiEMPtVsNJetWeightedff->SetBinError(j+1, totalerrordiemptvsnjetreweightedff[j]); 
  }
  
  
  for(int j = 0; j < ErrorPropDiEMPtWeightedNJetsee->GetNbinsX();++j){
    double mindiemptreweightednjetsee(100000000), mindiemptreweightednjetsff(100000000);
    double maxdiemptreweightednjetsee(-10), maxdiemptreweightednjetsff(-10);
    
    for(int k=0; k<1000; ++k){
      xbindiemptreweightednjetsee[j][k]       = DiEMPtRatioWeightedeeNJets[k]->GetBinContent(j+1);
      if(maxdiemptreweightednjetsee < xbindiemptreweightednjetsee[j][k])maxdiemptreweightednjetsee=xbindiemptreweightednjetsee[j][k];
      if(mindiemptreweightednjetsee > xbindiemptreweightednjetsee[j][k])mindiemptreweightednjetsee=xbindiemptreweightednjetsee[j][k];
      
      xbindiemptreweightednjetsff[j][k]       = DiEMPtRatioWeightedffNJets[k]->GetBinContent(j+1);
      if(maxdiemptreweightednjetsff < xbindiemptreweightednjetsff[j][k])maxdiemptreweightednjetsff=xbindiemptreweightednjetsff[j][k];
      if(mindiemptreweightednjetsff > xbindiemptreweightednjetsff[j][k])mindiemptreweightednjetsff=xbindiemptreweightednjetsff[j][k];
    }
    
    centraldiemptreweightednjetsee[j]   = h_DoubleElectron_NJets_Reweighted->GetBinContent(j+1);
    errorupdiemptreweightednjetsee[j]   = 0.68*(maxdiemptreweightednjetsee-centraldiemptreweightednjetsee[j]);
    errordowndiemptreweightednjetsee[j] = 0.68*(centraldiemptreweightednjetsee[j]-mindiemptreweightednjetsee); 
    
    centraldiemptreweightednjetsff[j]   = h_DoubleFake_NJets_Reweighted->GetBinContent(j+1);
    errorupdiemptreweightednjetsff[j]   = 0.68*(maxdiemptreweightednjetsff-centraldiemptreweightednjetsff[j]);
    errordowndiemptreweightednjetsff[j] = 0.68*(centraldiemptreweightednjetsff[j]-mindiemptreweightednjetsff); 
    
    totalerrordiemptreweightednjetsee[j] = sqrt((errorupdiemptreweightednjetsee[j]+errordowndiemptreweightednjetsee[j])*(errorupdiemptreweightednjetsee[j]+errordowndiemptreweightednjetsee[j]));
    totalerrordiemptreweightednjetsff[j] = sqrt((errorupdiemptreweightednjetsff[j]+errordowndiemptreweightednjetsff[j])*(errorupdiemptreweightednjetsff[j]+errordowndiemptreweightednjetsff[j]));
    
    
    double njetsValue = h_DoubleElectron_NJets_Reweighted->GetBinContent(j+1);
    ErrorPropDiEMPtWeightedNJetsee->SetBinContent(j+1, njetsValue);
    ErrorPropDiEMPtWeightedNJetsee->SetBinError(j+1, totalerrordiemptreweightednjetsee[j]);
    
    njetsValue = h_DoubleFake_NJets_Reweighted->GetBinContent(j+1);
    ErrorPropDiEMPtWeightedNJetsff->SetBinContent(j+1, njetsValue);
    ErrorPropDiEMPtWeightedNJetsff->SetBinError(j+1, totalerrordiemptreweightednjetsff[j]);
    
  }

  ErrorPropDiEMPteeMET->Draw();
  TString OutputFolder = "";
  
  if(analysisFake)OutputFolder="Data_RunD_Ratio_AnalysisFake_217fb";
  else OutputFolder="Data_RunD_Ratio_ExtendedFake_217fb";
    
  int stat0;
  stat0 = mkdir(OutputFolder, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);

  TFile* fout2=0;
  if(!data)fout2= new TFile(OutputFolder+"/ErrorPropDiEMPttoElectronMET.root","RECREATE");
  else fout2= new TFile(OutputFolder+"/ErrorPropDiEMPttoElectronMET_Data.root","RECREATE");
  fout2->cd();
  
  ErrorPropDiEMPteeMET->Write();
  ErrorPropDiEMPtffMET->Write();
  ErrorPropDiEMPtffshowershapeMET->Write();
  
  ErrorPropNJetseeMET->Write();
  ErrorPropNJetsffMET->Write();
  ErrorPropNJetsffshowershapeMET->Write();
  
  ErrorPropDiEMPtNJetseeMET->Write();
  ErrorPropDiEMPtNJetsffMET->Write();
  ErrorPropDiEMPtNJetsffshowershapeMET->Write();
  
  ErrorPropDiEMPtWeightedNJetsee->Write();
  ErrorPropDiEMPtWeightedNJetsff->Write();
  
  ErrorPropDiEMPtVsNJetWeightedee->Write();
  ErrorPropDiEMPtVsNJetWeightedff->Write();
  
  F22->Close();
  F23->Close();
  fout2->Close();
  
}
Esempio n. 21
0
void DrawVariable(TString DIR,TString VAR,float LUMI,bool LOG,int REBIN,float XMIN,float XMAX,TString XTITLE,bool isINT,int XNDIV,bool PRINT)
{
  gROOT->ForceStyle();
  const int N = 14;

  TString SAMPLE[N] = {
    "JetHT",
    "TT_TuneCUETP8M1_13TeV-powheg-pythia8",
    "WJetsToQQ_HT180_13TeV-madgraphMLM-pythia8",
    "DYJetsToQQ_HT180_13TeV-madgraphMLM-pythia8",
    "ST_t-channel_top_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1",
    "ST_t-channel_antitop_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1",
    "ST_tW_top_5f_inclusiveDecays_13TeV-powheg-pythia8_TuneCUETP8M1",
    "ST_tW_antitop_5f_inclusiveDecays_13TeV-powheg-pythia8_TuneCUETP8M1",
    "QCD_HT300to500_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT500to700_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT700to1000_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT1000to1500_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT1500to2000_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT2000toInf_TuneCUETP8M1_13TeV-madgraphMLM-pythia8"
  };
  float XSEC[N] = {1.0,0.5*832,3539,1460.,136.02,80.95,35.6,35.6,3.67e+5,2.94e+4,6.524e+03,1.064e+03,121.5,2.542e+01};

  TFile *inf[N];
  TH1F  *h[N];

  TCanvas *can = new TCanvas("DataVsMC_"+DIR+"_"+VAR,"DataVsMC_"+DIR+"_"+VAR,900,600);
  can->SetRightMargin(0.15);

  for(int i=0;i<N;i++) {
    inf[i] = TFile::Open("Histo_"+SAMPLE[i]+".root");
    h[i] = (TH1F*)inf[i]->Get(DIR+"/hWt_"+VAR);
    if (!h[i]) {
      cout<<"Histogram "<<"hWt_"+VAR<<" does not exist !!!"<<endl;
      break;
    } 
    h[i]->SetDirectory(0);
    h[i]->Sumw2();
    h[i]->Rebin(REBIN);
    h[i]->SetLineWidth(1);
    h[i]->SetLineColor(kBlack);
    if (i>0) {
      float norm = ((TH1F*)inf[i]->Get("eventCounter/GenEventWeight"))->GetSumOfWeights();   
      //cout<<SAMPLE[i]<<" "<<norm<<endl;
      h[i]->Scale(LUMI*XSEC[i]/norm);
    }
    inf[i]->Close();
  }

  TH1F *hQCD = (TH1F*)h[8]->Clone("hQCD");
  for(int i=9;i<N;i++) {
    hQCD->Add(h[i]);
  }
 
  TH1F *hST = (TH1F*)h[4]->Clone("hST");
  hST->Add(h[5]);
  hST->Add(h[6]);
  hST->Add(h[7]);
  h[0]->SetLineWidth(2);//data
  hQCD->SetFillColor(kBlue-10);//QCD
  h[1]->SetFillColor(kOrange);//ttbar
  h[2]->SetFillColor(kGreen-10);//WJets
  h[3]->SetFillColor(kGreen-8);//ZJets
  hST->SetFillColor(kOrange-1);//ST

  float kfactor = 1.0;
  if (hQCD->Integral() > 0) { 
    kfactor = (h[0]->Integral()-h[1]->Integral()-h[2]->Integral()-h[3]->Integral()-hST->Integral())/hQCD->Integral();
  }  
  hQCD->Scale(kfactor);

  TH1F *hBkg = (TH1F*)hQCD->Clone("hBkg");
  hBkg->Add(h[1]);
  hBkg->Add(h[2]);
  hBkg->Add(h[3]);
  hBkg->Add(h[4]);
  hBkg->Add(hST);
  //hBkg->SetFillColor(kGray);

  cout<<"======== "<<VAR<<"====================="<<endl;
  cout<<"Data events:  "<<h[0]->Integral()<<endl;
  cout<<"QCD events:   "<<hQCD->Integral()<<endl;
  cout<<"WJets events: "<<h[2]->Integral()<<endl;
  cout<<"ZJets events: "<<h[3]->Integral()<<endl;
  cout<<"ST events:    "<<hST->Integral()<<endl;
  cout<<"TTbar events: "<<h[1]->Integral()<<endl;
  cout<<"kfactor:      "<<kfactor<<endl;

  THStack *hs = new THStack("hs","hs");
  if (LOG) {   
    hs->Add(h[2]);
    hs->Add(h[3]);
    hs->Add(hST); 
    hs->Add(hQCD);
    hs->Add(h[1]);
  }
  else {
    hs->Add(h[3]);
    hs->Add(hST);
    hs->Add(h[2]);
    hs->Add(hQCD);
    hs->Add(h[1]);
  }
  TH1F *hRatio = (TH1F*)h[0]->Clone("Ratio");
  hRatio->SetLineWidth(2);
  hRatio->Divide(hBkg);

  TLegend *leg = new TLegend(0.86,0.7,0.99,0.9);
  leg->SetFillColor(0);
  leg->SetTextFont(42);
  leg->SetTextSize(0.03);
  leg->AddEntry(hQCD,"QCD","F");
  leg->AddEntry(h[1],"TTbar","F"); 
  leg->AddEntry(hST,"ST","F"); 
  leg->AddEntry(h[2],"WJets","F");
  leg->AddEntry(h[3],"ZJets","F"); 
  
  can->SetBottomMargin(0.25);
  TH1F *hAux = (TH1F*)h[0]->Clone("aux");
  hAux->Reset();
  hAux->GetXaxis()->SetNdivisions(XNDIV);
  if (isINT) {
    hAux->GetXaxis()->CenterLabels();
  } 
  hAux->GetYaxis()->SetRangeUser(0.5,1.1*TMath::Max(hBkg->GetBinContent(hBkg->GetMaximumBin()),h[0]->GetBinContent(h[0]->GetMaximumBin())));  
  if (LOG) {
    gPad->SetLogy(); 
    hAux->GetYaxis()->SetRangeUser(0.5,2*TMath::Max(hBkg->GetBinContent(hBkg->GetMaximumBin()),h[0]->GetBinContent(h[0]->GetMaximumBin())));
  }
  hAux->GetXaxis()->SetRangeUser(XMIN,XMAX);
  hAux->GetYaxis()->SetTitle(TString::Format("Number of events / %1.2f fb^{-1}",LUMI/1000));
  hAux->GetXaxis()->SetTitle("");
  hAux->GetXaxis()->SetLabelSize(0.0);
  hAux->Draw();
  hs->Draw("hist same");
  //hBkg->Draw("sames hist"); 
  h[0]->Draw("sames E");
  
  leg->Draw();
  gPad->RedrawAxis();

  TPad *pad = new TPad("pad","pad",0.,0.,1.,1.);
  pad->SetTopMargin(0.77);
  pad->SetRightMargin(0.15);
  pad->SetFillColor(0);
  pad->SetFillStyle(0);
  pad->Draw();
  pad->cd(0);
  pad->SetGridy();
  hRatio->GetXaxis()->SetTitleOffset(0.95);
  hRatio->GetYaxis()->SetTitleOffset(1.5);
  hRatio->GetYaxis()->SetTickLength(0.06);
  hRatio->GetYaxis()->SetTitleSize(0.03);
  hRatio->GetYaxis()->SetLabelSize(0.03);
  hRatio->GetYaxis()->SetTitle("Data/MC");
  hRatio->GetXaxis()->SetTitle(XTITLE);
  hRatio->GetXaxis()->SetRangeUser(XMIN,XMAX);
  hRatio->GetYaxis()->SetRangeUser(0.5,1.5);
  hRatio->GetYaxis()->SetNdivisions(505);
  hRatio->GetXaxis()->SetNdivisions(XNDIV);
  if (isINT) {
    hRatio->GetXaxis()->CenterLabels();
  }
  hRatio->Draw();
  if (PRINT) {
    can->Print("plots/"+TString(can->GetName())+".pdf"); 
    can->Print("plots/"+TString(can->GetName())+".png");
  }
}
Esempio n. 22
0
void TMVAClassificationElecTau(std::string ordering_ = "Pt", std::string bkg_ = "qqH115vsWZttQCD") {

    TMVA::Tools::Instance();

    TString outfileName( "TMVAElecTau"+ordering_+"Ord_"+bkg_+".root" );
    TFile* outputFile = TFile::Open( outfileName, "RECREATE" );

    TMVA::Factory *factory = new TMVA::Factory( "TMVAClassificationElecTau"+ordering_+"Ord_"+bkg_, outputFile,
            "!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D" );
    factory->AddVariable( "pt1", "pT-tag1", "GeV/c"         , 'F'  );
    factory->AddVariable( "pt2", "pT-tag2", "GeV/c"         , 'F'  );
    factory->AddVariable( "Deta","|y-tag1 - y-tag2|",""     , 'F'  );
    //factory->AddVariable( "opposite:=abs(eta1*eta2)/eta1/eta2","sign1*sign2",""             , 'F'  );
    //factory->AddVariable( "Dphi", "#Delta#phi" ,""             , 'F'  );
    factory->AddVariable( "Mjj", "M(tag1,tag2)", "GeV/c^{2}"  , 'F'  );

    factory->AddSpectator( "eta1",  "#eta_{tag1}" , 'F' );
    factory->AddSpectator( "eta2",  "#eta_{tag2}" , 'F' );

    factory->SetWeightExpression( "sampleWeight" );

    TString fSignalName              = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/ElecTauStream2011/nTupleVBFH115-powheg-PUS1_Open_ElecTauStream.root";
    TString fBackgroundNameDYJets    = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/ElecTauStream2011/nTupleZjets-alpgen-PUS1_Open_ElecTauStream.root";
    TString fBackgroundNameWJets     = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/ElecTauStream2011/nTupleWJets-madgraph-PUS1_Open_ElecTauStream.root";
    TString fBackgroundNameQCD       = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/ElecTauStream2011/nTupleQCD_Open_ElecTauStream.root";
    TString fBackgroundNameTTbar     = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/ElecTauStream2011/nTupleTTJets-madgraph-PUS1_Open_ElecTauStream.root";


    TFile *fSignal(0);
    TFile *fBackgroundDYJets(0);
    TFile *fBackgroundWJets(0);
    TFile *fBackgroundQCD(0);
    TFile *fBackgroundTTbar(0);

    fSignal           = TFile::Open( fSignalName );
    fBackgroundDYJets = TFile::Open( fBackgroundNameDYJets );
    fBackgroundWJets  = TFile::Open( fBackgroundNameWJets );
    fBackgroundQCD    = TFile::Open( fBackgroundNameQCD );
    fBackgroundTTbar  = TFile::Open( fBackgroundNameTTbar );

    if(!fSignal || !fBackgroundDYJets || !fBackgroundWJets || !fBackgroundQCD || !fBackgroundTTbar) {
        std::cout << "ERROR: could not open files" << std::endl;
        exit(1);
    }

    TString tree = "outTree"+ordering_+"Ord";

    TCut mycuts = "";
    TCut mycutb = "";

    TCut cutA  = "pt1>0 && tightestHPSWP>0";
    TCut cutB  = "pt1>0 && combRelIsoLeg1<0.1";
    TCut cutBl = "pt1>0 && combRelIsoLeg1<0.3";
    TCut cutC  = "pt1>0 && diTauCharge==0";
    TCut cutD  = "pt1>0 && MtLeg1<40";

    // select events for training
    TFile* dummy = new TFile("dummy.root","RECREATE");
    TH1F* allEvents = new TH1F("allEvents","",1,-10,10);
    float totalEvents, cutEvents;

    // signal: all
    TTree *signal           = ((TTree*)(fSignal->Get(tree)))->CopyTree(cutA&&cutB&&cutC&&cutD);
    cout << "Copied signal tree with full selection: " << ((TTree*)(fSignal->Get(tree)))->GetEntries() << " --> "  << signal->GetEntries()  << endl;
    allEvents->Reset();
    signal->Draw("eta1>>allEvents","sampleWeight");
    cutEvents  = allEvents->Integral();
    Double_t signalWeight =   1.0;
    cout << "Signal: expected yield " << cutEvents << " -- weight " << signalWeight << endl;

    // Z+jets: all
    TTree *backgroundDYJets = ((TTree*)(fBackgroundDYJets->Get(tree)))->CopyTree(cutA&&cutB&&cutC&&cutD);
    cout << "Copied DYJets tree with full selection: " << ((TTree*)(fBackgroundDYJets->Get(tree)))->GetEntries() << " --> "  << backgroundDYJets->GetEntries()  << endl;
    allEvents->Reset();
    backgroundDYJets->Draw("eta1>>allEvents","sampleWeight");
    cutEvents  = allEvents->Integral();
    Double_t backgroundDYJetsWeight = 1.0;
    cout << "ZJets: expected yield " << cutEvents << " -- weight " << backgroundDYJetsWeight << endl;

    // W+jets: iso+Mt
    TTree *backgroundWJets  = ((TTree*)(fBackgroundWJets->Get(tree)))->CopyTree(cutB&&cutD);
    cout << "Copied WJets tree with iso+Mt selection: " << ((TTree*)(fBackgroundWJets->Get(tree)))->GetEntries() << " --> "  << backgroundWJets->GetEntries()  << endl;
    allEvents->Reset();
    backgroundWJets->Draw("eta1>>allEvents","sampleWeight");
    totalEvents  = allEvents->Integral();
    allEvents->Reset();
    backgroundWJets->Draw("eta1>>allEvents","sampleWeight*(tightestHPSWP>0 && diTauCharge==0)");
    cutEvents  = allEvents->Integral();
    Double_t backgroundWJetsWeight  =  cutEvents / totalEvents;
    cout << "WJets: expected yield " << cutEvents  << " -- weight " << backgroundWJetsWeight << endl;

    // QCD: Mt+loose iso
    TTree *backgroundQCD    = ((TTree*)(fBackgroundQCD->Get(tree)))->CopyTree(cutD&&cutBl);
    cout << "Copied QCD tree with Mt selection: " << ((TTree*)(fBackgroundQCD->Get(tree)))->GetEntries() << " --> "  << backgroundQCD->GetEntries()  << endl;
    allEvents->Reset();
    backgroundQCD->Draw("eta1>>allEvents","sampleWeight");
    totalEvents  = allEvents->Integral();
    allEvents->Reset();
    backgroundQCD->Draw("eta1>>allEvents","sampleWeight*(tightestHPSWP>0 && diTauCharge==0 && combRelIsoLeg1<0.1)");
    cutEvents  = allEvents->Integral();
    Double_t backgroundQCDWeight  =  cutEvents / totalEvents;
    cout << "QCD: expected yield " << cutEvents  << " -- weight "  << backgroundQCDWeight << endl;


    // TTbar: iso+Mt
    TTree *backgroundTTbar  = ((TTree*)(fBackgroundTTbar->Get(tree)))->CopyTree(cutB&&cutD);
    cout << "Copied TTbar tree with iso+Mt selection: " << ((TTree*)(fBackgroundTTbar->Get(tree)))->GetEntries() << " --> "  << backgroundTTbar->GetEntries()  << endl;
    allEvents->Reset();
    backgroundTTbar->Draw("eta1>>allEvents","sampleWeight");
    totalEvents  = allEvents->Integral();
    allEvents->Reset();
    backgroundTTbar->Draw("eta1>>allEvents","sampleWeight*(tightestHPSWP>0 && diTauCharge==0)");
    cutEvents  = allEvents->Integral();
    Double_t backgroundTTbarWeight  =  cutEvents / totalEvents;
    cout << "TTbar: expected yield "  << cutEvents  << " -- weight " << backgroundTTbarWeight << endl;


    delete allEvents;


    factory->AddSignalTree    ( signal,           signalWeight           );
    //factory->AddBackgroundTree( backgroundDYJets, backgroundDYJetsWeight );
    //factory->AddBackgroundTree( backgroundWJets,  backgroundWJetsWeight  );
    factory->AddBackgroundTree( backgroundQCD,    backgroundQCDWeight    );
    //factory->AddBackgroundTree( backgroundTTbar,  backgroundTTbarWeight  );


    factory->PrepareTrainingAndTestTree( mycuts, mycutb,
                                         "nTrain_Signal=0:nTrain_Background=0:nTest_Signal=1:nTest_Background=1:SplitMode=Random:NormMode=NumEvents:!V" );

    factory->BookMethod( TMVA::Types::kCuts, "Cuts",
                         "!H:!V:FitMethod=GA:EffSel:CutRangeMin[0]=25.:CutRangeMax[0]=999:CutRangeMin[1]=25.:CutRangeMax[1]=999.:CutRangeMin[2]=1.0:CutRangeMax[2]=9.:CutRangeMin[3]=100:CutRangeMax[3]=7000:VarProp=FSmart" );

    /*
    factory->BookMethod( TMVA::Types::kBDT, "BDT",
    	       "!H:!V:NTrees=200:BoostType=AdaBoost:SeparationType=GiniIndex:nCuts=20:PruneMethod=NoPruning" );
    */

    factory->TrainAllMethods();

    factory->TestAllMethods();

    factory->EvaluateAllMethods();

    outputFile->Close();

    std::cout << "==> Wrote root file: " << outputFile->GetName() << std::endl;
    std::cout << "==> TMVAClassification is done!" << std::endl;

    delete factory;

    //if (!gROOT->IsBatch()) TMVAGui( outfileName );

}
Esempio n. 23
0
  Int_t AnalyzeCells_Fill( const char* runlist = "/home/yuxip/FMS/CellScan/macros/fill15419.list",const char* ls = "small" ){
	
	gStyle->SetPalette(1);
	gSystem->Load("../lib/libMyCellMgr.so");
	gROOT->LoadMacro("/home/yuxip/FMS/CellScan/macros/Legal.C");
	gROOT->LoadMacro("/home/yuxip/FMS/CellScan/macros/ConvertTH2Bin.C");
	mGeom = new Geom("./","geom.txt");
	cout<<"runlist: "<<runlist<<endl;
	
	Int_t fillnum = 0;
	Int_t runtoshow = 1;
	Long_t runnum = 0;
	Int_t rcnt = 0;
	sscanf(runlist,"/home/yuxip/FMS/CellScan/macros/fill%d.list",&fillnum);
	fstream infill(runlist,ios::in);
	if(!infill){
		cout<<"ERROR! "<<runlist<<" does not exist!!"<<endl;
		return -1;
	}
	while(infill>>runnum){
		rcnt++;
		if(rcnt==runtoshow)break;
	}
	cout<<"runtoshow: "<<runnum<<endl;
		
	
	Char_t outfilename[30];
	if(!strcmp(ls,"large")){
		sprintf(outfilename,"LargeCells_fill%d_run%ld_n2.ps",fillnum,runnum);
	}
	else if(!strcmp(ls,"small")){
		sprintf(outfilename,"SmallCells_fill%d_run%ld_n4.ps",fillnum,runnum);
	}
	else{
		cout<<"invalid 2nd argument!!"<<endl;
		return -1;
	}
	

	TString outfile(outfilename);
	TString headout = outfile + "[";
	TString endout = outfile + "]";
	
	TCanvas* c1 = new TCanvas("c1","c1",700,1100);
	c1->Divide(2,3);
	c1->Print(headout);
	
	Int_t ncell = 1000;		//for test only
	Int_t cellcnt  = 0;
	Char_t cellname[30];
	Char_t cellfile[30];
	TDirectory* h1where = gDirectory;
	TH1F* hmass 	= new TH1F("hmass","hmass",50,0,1);
	TH2F* hxy1	= new TH2F("hxy1","hxy1",34,-98.6,98.6,34,-98.6,98.6);
	TH2F* hxy2	= new TH2F("hxy2","hxy2",34,-98.6,98.6,34,-98.6,98.6);
	TH2F* smallxy1	= new TH2F("smallxy1","smallxy1",52,-98.6,98.6,52,-98.6,98.6);
	TH2F* smallxy2	= new TH2F("smallxy2","smallxy2",52,-98.6,98.6,52,-98.6,98.6);
	Float_t wbox 	= 12.0*3.8;

	Int_t nentries;
	Int_t 	maxy 	= 0;
	Int_t 	maxx 	= 0;
	UChar_t Status = 0x00;
	Char_t  text[30];
	MyCell* mcell 	= new MyCell();
	TTree* Trpi;
	Float_t	x2, y2;
	Int_t cnt = 1;
	Int_t n1  = 0;
        Int_t n2  = 0;

        if(!strcmp(ls,"large")){
                n1 = 2;
                n2 = 2;		//analysis each nstb separately
        }
        else if(!strcmp(ls,"small")){
                n1 = 4;
                n2 = 4;
        }
        else{
                cout<<"invalid 2nd argument"<<endl;
                return -1;
        }
	Int_t largeN1 = 0;
	Int_t smallN1 = 0;
	Int_t largeN2 = 0;
	Int_t smallN2 = 0;
	TFile* 	fcell = 0;
	MyCellEvt* mcevt = new MyCellEvt();
	
	for(Int_t nstb = n1; nstb <= n2; nstb++){
		for(Int_t row0 = 0; row0 < 34; row0++){
			for(Int_t col0 = 0; col0 < 17; col0++){

				cout<<"row0: "<<row0<<" col0: "<<col0<<" nstb: "<<nstb<<endl;
				if(!Legal(2,nstb,row0,col0)){
					continue;
				}
				cellcnt++;
				sprintf(cellname,"Cellr%d_c%d_n%d",row0,col0,nstb);
				cout<<"processing "<<cellname<<endl;
				sprintf(cellfile,"../cells/Cellr%d_c%d_n%d.root",row0,col0,nstb);
				
				fcell = new TFile(cellfile,"read");
				mcell = (MyCell*)fcell->Get(cellname);
				mcell->SetGeom(mGeom);
				mcell->Print();
				if(!mcell){
					cout<<"ERROR getting "<<cellname<<endl;
					return 0;
				}
				c1->cd(cnt);
				c1->GetPad(cnt)->SetLogy();
				c1->GetPad(cnt)->SetLogx();
				mcell->GetAdcSpectrum(runnum)->Draw();
				cnt++;
				c1->cd(cnt);
				c1->GetPad(cnt)->SetLogy();
				c1->GetPad(cnt)->SetLogx();
				mcell->GetLEDSpectrum(runnum)->Draw();
				mcell->GetLEDSpectrum(runnum)->SetLineColor(kBlue);
				Status = mcell->GetStatusBit(runnum);
				sprintf(text,"0x%x",Status);
				TLatex l(0.5,0.5,text);
				l.SetNDC();
				l.SetTextColor(2);
				l.Draw();
				cnt++;
				c1->cd(cnt);
//				c1->GetPad(cnt)->SetLogy();
				c1->GetPad(cnt)->SetFillColor(37);
				maxy = mcell->GetLEDvsEvt(runnum)->FindLastBinAbove(0,2);
				maxx = mcell->GetLEDvsEvt(runnum)->FindLastBinAbove(0,1);
				cout<<"maxx: "<<maxx<<endl;
				if(maxy < 2000){
					mcell->GetLEDvsEvt(runnum)->GetYaxis()->SetRange(0,2*maxy);
				}
				if(maxx < 2000){
					mcell->GetLEDvsEvt(runnum)->GetXaxis()->SetRange(0,(maxx+100));
				}
				
				mcell->GetLEDvsEvt(runnum)->Draw("COLZ");
				
				Trpi = mcell->GetPionSample("all",runlist);
				nentries = Trpi->GetEntries();
			//	Trpi->Print();
				cout<<"Trpi nentries: "<<nentries<<endl;
				

				if(nentries!=0){
/*
*/					
//					h1where->cd();
//					cnt++;
//					c1->cd(cnt);
//					Trpi->Project("hmass","M","");
//					hmass->Draw();
//					cnt++;
//					c1->cd(cnt);
					Float_t x1;
                                        Float_t x2;
                                        Float_t y1;
                                        Float_t y2;
					Float_t m;
					Trpi->ResetBranchAddresses();	//the orginal MergedTr was hooked up with transient member MyCellEvt of MyCell
                                        Trpi->SetBranchAddress("mycevt",&mcevt);
//                                        Trpi->SetBranchAddress("Y2",&y2);
//					Trpi->SetBranchAddress("M",&m);
                                        Trpi->SetBranchStatus("*",0);
                                        Trpi->SetBranchStatus("X2",1);
                                        Trpi->SetBranchStatus("Y2",1);
                                        Trpi->SetBranchStatus("M",1);
//					Trpi->GetEntry(0);
//					Trpi->Show(0);
//					cout<<"X2: "<<(mcevt->X2)<<", Y2: "<<(mcevt->Y2)<<", M: "<<(mcevt->M)<<endl;

					Int_t binx;
					Int_t biny;
					TString partner;
					Int_t pnstb = 0;
					Int_t prow0 = 0;
					Int_t pcol0 = 0;
					Long_t prun = 0;
					for(Int_t i = 0; i < nentries; i++){
						
						if(nstb<3){		//large cells
							if(!ConvertTH2Bin(nstb,row0,col0,binx,biny,hxy1)){
								cout<<"ERROR in ConvertTH2Bin()!"<<endl;
								return -1;
							}
							hxy1->SetBinContent(binx,biny,(hxy1->GetBinContent(binx,biny)+1));
						}

						if(nstb>2){		//small cells
							if(!ConvertTH2Bin(nstb,row0,col0,binx,biny,smallxy1)){
                                                                cout<<"ERROR in ConvertTH2Bin()!"<<endl;
                                                                return -1;
                                                        }
							smallxy1->SetBinContent(binx,biny,(smallxy1->GetBinContent(binx,biny)+1));
						}
//						cout<<"binx: "<<binx<<", biny: "<<biny<<endl;
						
						Trpi->GetEntry(i);
//						Trpi->Show(i);
						x2 = mcevt->X2;
						y2 = mcevt->Y2;
						 m = mcevt->M; 
//						cout<<"X2: "<<x2<<", Y2: "<<y2<<", M: "<<m<<endl;
						hmass->Fill(m);
						if(!mGeom->getNSTB(x2,y2))continue;	//bypass abnormal nstb
						partner = mcell->GetPartnerByXY(x2,y2,runnum);
						if(col0==0){
							cout<<"debug: partner: "<<partner<<endl;
						}
						sscanf((const char*)partner,"Cellr%d_c%d_n%d_run%ld",&prow0,&pcol0,&pnstb,&prun);
						if(col0==0){
                                                        cout<<"debug: partner (nstb,row0,col0): ("<<pnstb<<", "<<prow0<<", "<<pcol0<<") "<<endl;
                                                }

						if(!Legal(2,pnstb,prow0,pcol0)){
							cout<<"invalid partner id"<<endl;
							continue;
						}
						if(pnstb<3){             //large cells
							if(!ConvertTH2Bin(pnstb,prow0,pcol0,binx,biny,hxy2)){
                                                                cout<<"ERROR in ConvertTH2Bin()!"<<endl;
                                                                return -1;
                                                        }
							hxy2->SetBinContent(binx,biny,(hxy2->GetBinContent(binx,biny)+1));
						}
						if(pnstb>2){		//small cells
							if(!ConvertTH2Bin(pnstb,prow0,pcol0,binx,biny,smallxy2)){
                                                                cout<<"ERROR in ConvertTH2Bin()!"<<endl;
                                                                return -1;
                                                        }
							smallxy2->SetBinContent(binx,biny,(smallxy2->GetBinContent(binx,biny)+1));
						}
					}
					
					smallN1 = smallxy1->GetBinContent(smallxy1->GetMaximumBin());
					largeN1 = hxy1->GetBinContent(hxy1->GetMaximumBin());
					if(smallN1>=largeN1){
						cout<<"smallN1: "<<smallN1<<endl;
						hxy1->GetZaxis()->SetRangeUser(0,smallN1);
						smallxy1->GetZaxis()->SetRangeUser(0,smallN1);
					}
					else{
						cout<<"largeN1: "<<largeN1<<endl;
						hxy1->GetZaxis()->SetRangeUser(0,largeN1);
                                                smallxy1->GetZaxis()->SetRangeUser(0,largeN1);
					}
	
					cnt++;
                                        c1->cd(cnt);	
					hmass->Draw();

					cnt++;
                                        c1->cd(cnt);
					hxy1->SetStats(0);
					hxy1->Draw("COLZ");
					TBox bx(-wbox,-wbox,wbox,wbox);
					bx.SetFillColor(18);
					bx.Draw("same");
					smallxy1->SetStats(0);
					smallxy1->Draw("zcolsame");
				
					cnt++;
					c1->cd(cnt);
					
					largeN2 = hxy2->GetBinContent(hxy2->GetMaximumBin());
					smallN2 = smallxy2->GetBinContent(smallxy2->GetMaximumBin());
					if(smallN2>=largeN2){
						cout<<"smallN2: "<<smallN2<<endl;
                                                hxy2->GetZaxis()->SetRangeUser(0,smallN2);
                                                smallxy2->GetZaxis()->SetRangeUser(0,smallN2);
                                        }
                                        else{
						cout<<"largeN2: "<<largeN2<<endl;
                                                hxy2->GetZaxis()->SetRangeUser(0,largeN2);
                                                smallxy2->GetZaxis()->SetRangeUser(0,largeN2);
                                        }
					hxy2->SetStats(0);
					hxy2->Draw("COLZ");
					bx.Draw("same");
					smallxy2->SetStats(0);
					smallxy2->Draw("zcolsame");
				}
				largeN1 = largeN2 = 0;
				smallN1 = smallN2 = 0;
				Trpi = 0;
				c1->Print(outfile);
				mcell = 0;
				hmass->Reset();
                                hxy1->Reset();
                                hxy2->Reset();
                                smallxy1->Reset();
                                smallxy2->Reset();
				fcell->Close();
				fcell = 0;
				c1->Clear();
				c1->Divide(2,3);
				cnt = 1;
				if(cellcnt == ncell)break;
				
			}
			if(cellcnt == ncell)break;
		}
		if(cellcnt == ncell)break;
	}
	c1->Print(endout);
  	return 1;
  }
Esempio n. 24
0
void CorrMatchMacro() {
  
  const int n_files   = 10;

  const TString directory = "/nfs/dust/cms/user/multh/RunII_80X_v3/Selection/Nominal/03Feb2017_Relaunch_17Jan2018/Matching/bhad_blep/";
 
  const TString file_name[n_files] =  {"Tstar_M-700","Tstar_M-800","Tstar_M-900","Tstar_M-1000","Tstar_M-1100","Tstar_M-1200", "Tstar_M-1300", "Tstar_M-1400", "Tstar_M-1500", "Tstar_M-1600"};

  TList *list_tophad = new TList; 
  TList *list_toplep = new TList; 
  TList *list_Tstar_M_diff = new TList;
  TList *list_DeltaPhi = new TList;
  TList *list_DeltaPhi_gluon = new TList;
  TList *list_Pt_TstarTstar  = new TList;

  TH1F *h_signal_tophad[n_files];
  TH1F *h_signal_toplep[n_files];
  TH1F *h_signal_Tstar_M_diff[n_files];
  TH1F *h_signal_DeltaPhi[n_files];
  TH1F *h_signal_DeltaPhi_gluon[n_files];
  TH1F *h_signal_PtTstarTstar[n_files];

  TH1F *h_tophadVsMass = new TH1F("tophadVsMass","tophadVsMass", 10, 650, 1650);
  
  float tophad_mean[n_files];
 
  for(int i = 0; i<n_files; i++){
    TFile *signal = new TFile(directory+"uhh2.AnalysisModuleRunner.MC."+file_name[i]+".root");

    /*   
    h_signal_tophad[i]  = (TH1F*)signal->Get("corrmatch__HypHists/M_tophad");
    h_signal_toplep[i]  = (TH1F*)signal->Get("corrmatch__HypHists/M_toplep");
    h_signal_Tstar_M_diff[i] = (TH1F*)signal->Get("corrmatch__HypHists/M_TstarhadTstarlep_Diff_rel");
    h_signal_DeltaPhi[i] = (TH1F*)signal->Get("corrmatch__HypHists/DeltaPhi_TstarhadTstarlep");
    h_signal_DeltaPhi_gluon[i] = (TH1F*)signal->Get("corrmatch__HypHists/DeltaPhi_GluonhadGluonlep");
    */
    //  h_signal_PtTstarTstar[i] = (TH1F*)signal->Get("corrmatch__HypHists/Pt_TstarTstar_Diff");
    
    
    h_signal_tophad[i]  = (TH1F*)signal->Get("corrmatch_ttag__HypHists/M_tophad");
    h_signal_toplep[i]  = (TH1F*)signal->Get("corrmatch_ttag__HypHists/M_toplep");
    h_signal_Tstar_M_diff[i] = (TH1F*)signal->Get("corrmatch_ttag__HypHists/M_TstarhadTstarlep_Diff_rel");
    h_signal_DeltaPhi[i] = (TH1F*)signal->Get("corrmatch_ttag__HypHists/DeltaPhi_TstarhadTstarlep");
    h_signal_DeltaPhi_gluon[i] = (TH1F*)signal->Get("corrmatch_ttag__HypHists/DeltaPhi_GluonhadGluonlep");
    //  h_signal_PtTstarTstar[i] = (TH1F*)signal->Get("corrmatch_ttag__HypHists/Pt_TstarTstar_Diff");
    

    /*
    h_signal_tophad[i]->Fit("gaus","","",150,210);
      TF1 *myfunc = h_signal_tophad[i]->GetFunction("gaus");
    h_tophadVsMass->SetBinContent(i+1, myfunc->GetParameter(1));
    h_tophadVsMass->SetBinError(i+1,  myfunc->GetParError(1));
    */   
 
    list_tophad->Add(h_signal_tophad[i]);
    list_toplep->Add(h_signal_toplep[i]);
    list_Tstar_M_diff->Add(h_signal_Tstar_M_diff[i]);
    list_DeltaPhi->Add(h_signal_DeltaPhi[i]);
    list_DeltaPhi_gluon->Add(h_signal_DeltaPhi_gluon[i]);
    //    list_Pt_TstarTstar->Add(h_signal_PtTstarTstar[i]);
  }

  gStyle->SetOptStat(0);
  gStyle->SetOptFit(0111);
  int bin_up = 700;
  int bin_down = 500;
  
  TCanvas* c1= new TCanvas("c1","c1",bin_up,bin_down);
  c1->Divide(2,2);
  c1->cd(1);
  TH1F *h = (TH1F*)h_signal_tophad[0]->Clone("h_tophad");
  h->Reset(); 
  h->Merge(list_tophad); 
  h->SetTitle("");
  h->GetXaxis()->SetTitle("M_{top}^{had} [GeV/c^{2}]");
  h->GetXaxis()->SetTitleSize(0.045);
  h->GetXaxis()->SetTitleOffset(1.1);
  h->GetYaxis()->SetTitle("Events");
  h->GetYaxis()->SetTitleSize(0.04);
  h->GetYaxis()->SetTitleOffset(1.1);
  h->Fit("gaus","","",50,230);
  h->Draw();
    
  c1->cd(2);
  TH1F *t = (TH1F*)h_signal_toplep[0]->Clone("h_toplep"); 
  t->Reset(); 
  t->Merge(list_toplep); 
  t->SetTitle("");
  t->GetXaxis()->SetTitle("M_{top}^{lep} [GeV/c^{2}]");
  t->GetXaxis()->SetTitleSize(0.045);
  t->GetXaxis()->SetTitleOffset(1.1);
  t->GetYaxis()->SetTitle("Events");
  t->GetYaxis()->SetTitleSize(0.04);
  t->GetYaxis()->SetTitleOffset(1.1);
  t->Fit("gaus","","",50,230);
  t->Draw();
  
  c1->cd(3);

  TH1F *p = (TH1F*)h_signal_Tstar_M_diff[0]->Clone("h_Tstar_M_diff"); 
  p->Reset(); 
  p->Merge(list_Tstar_M_diff); 
  p->SetTitle("");
  p->GetXaxis()->SetTitle("#Delta M_{T*#bar{T*}}");
  p->GetXaxis()->SetTitleSize(0.045);
  p->GetXaxis()->SetTitleOffset(1.1);
  p->GetYaxis()->SetTitle("Events");
  p->GetYaxis()->SetTitleSize(0.04);
  p->GetYaxis()->SetTitleOffset(1.1);
  p->Fit("gaus","","",-0.2,0.2);
  p->Draw();

  c1->cd(4);
  
  TH1F *k = (TH1F*)h_signal_DeltaPhi[0]->Clone("h_DeltaPhi"); 
  k->Reset(); 
  k->Merge(list_DeltaPhi); 
  k->SetTitle("");
  k->GetXaxis()->SetTitle("#Delta #Phi");
  k->GetXaxis()->SetTitleSize(0.045);
  k->GetXaxis()->SetTitleOffset(1.1);
  k->GetYaxis()->SetTitle("Events");
  k->GetYaxis()->SetTitleSize(0.04);
  k->GetYaxis()->SetTitleOffset(1.1);
  k->Fit("gaus","","",2.8,3.5);
  k->Draw();
  
  /*
  TH1F *k = (TH1F*)h_signal_DeltaPhi_gluon[0]->Clone("h_DeltaPhi"); 
  k->Reset(); 
  k->Merge(list_DeltaPhi_gluon); 
  k->SetTitle("");
  k->GetXaxis()->SetTitle("#Delta #Phi");
  k->GetXaxis()->SetTitleSize(0.045);
  k->GetXaxis()->SetTitleOffset(1.1);
  k->GetYaxis()->SetTitle("Events");
  k->GetYaxis()->SetTitleSize(0.04);
  k->GetYaxis()->SetTitleOffset(1.1);
  k->Fit("gaus","","",2.8,3.5);
  k->Draw();
  */
  
  /*
  TCanvas* c2= new TCanvas("c2","c2",bin_up,bin_down);
  gStyle->SetOptStat(0);
  gStyle->SetOptFit(0111);
  h_tophadVsMass->SetTitle("");
  h_tophadVsMass->GetXaxis()->SetTitle("T* Mass");
  h_tophadVsMass->GetYaxis()->SetTitle("top_{had} mean");
  h_tophadVsMass->Draw();
  */
  /*
  TCanvas* c3= new TCanvas("c3","c3",bin_up,bin_down);
  gStyle->SetOptStat(0);
  gStyle->SetOptFit(0111);
    h_signal_tophad[9]->Draw();
  */
}
Esempio n. 25
0
void compareCorrRCSpike(){
	

  char tmp[1000];
  setTDRStyle();
  // settings for purity TGraphAsymmetryErrors
  Double_t fBinsPtMidPoint[nPtBin]={0};
  Double_t fBinsPtError[nPtBin]={0};
  
  for(int ipt=0; ipt < nPtBin; ipt++)
    {
      fBinsPtMidPoint[ipt] = 0.5*(fBinsPt[ipt+1]+fBinsPt[ipt]);
      fBinsPtError[ipt] = 0.5*(fBinsPt[ipt+1]-fBinsPt[ipt]);
    }


  TH1F* hTemplate_S[nEtaBin][nPtBin];
  TH1F* hdata_S[nEtaBin][nPtBin];

  
  std::string dataFile     = "SBDataTemplate_131511_139239.root";
  std::string templateFile = "spike_131511_139239.root";

  TFile* inf_data = new TFile(dataFile.data());
  TFile* inf_template = new TFile(templateFile.data());

  
  char* dec[2] = {"EB","EE"};
  for(int ieta=0; ieta<1; ieta++){
    for(int ipt=0; ipt < nPtBin; ipt++){

      // getting histograms from data root file

      sprintf(tmp,"h_%s_comb3Iso_sig_pt%d",dec[ieta],(int)fBinsPt[ipt]);
      cout << "looking for histogram " << tmp << " in file " << 
	inf_data->GetName() << endl;
      hdata_S[ieta][ipt] = (TH1F*)inf_data->FindObjectAny(tmp);
      hdata_S[ieta][ipt]->SetName(Form("hdata_S_%d_%d",ieta,ipt));
      hdata_S[ieta][ipt]->Rebin(REBINNINGS);

      // getting histogram for template root file
      sprintf(tmp,"h_EB_comb3Iso_EGdata_SIG");
      cout << "looking for histogram " << tmp << " in file " << 
	inf_template->GetName() << endl;
      hTemplate_S[ieta][ipt] = (TH1F*)inf_template->FindObjectAny(tmp);
      hTemplate_S[ieta][ipt]->SetName(Form("hTemplate_S_%d_%d",ieta,ipt));
      hTemplate_S[ieta][ipt]->Rebin(REBINNINGS);

    }
  }


  TH1F* hfit_sig;
  TH1F* hfit_spike;

  TH1F* hsig = new TH1F("hsig","",120,-1,11);
  hsig->SetXTitle("Iso (GeV)");
  hsig->SetYTitle("A.U.");
  hsig->GetYaxis()->SetDecimals();
  hsig->SetYTitle("Iso (GeV)");

  hsig->SetLineColor(2);
  TH1F* hspike = new TH1F("hspike","",120,-1,11);
  hspike->SetLineColor(4);

  TCanvas* c1 = new TCanvas("c1","",500,500);

  for(int ieta=0; ieta< 1; ieta++){
    for(int ipt=0; ipt < nPtBin; ipt++){


      hsig->Reset();
      hspike->Reset();

      // first obtain fit for the random cone corrected values
      hfit_sig  = (TH1F*)hdata_S[ieta][ipt]->Clone();
      hfit_sig  -> SetName("hfit_sig");
      hfit_sig  -> Rebin(4);

      double sigPar[20] = {hfit_sig->GetMaximum(), 1., 0.5, 0.3,
			   1.,-.3,-1., 0.01, 0.5, 0.01, 1., 1.};

      TF1 *fsig = new TF1("fsig", exp_conv, -1., 11., 12);
      fsig->SetParameters(sigPar);
      fsig->SetNpx(2500);
      fsig->SetLineColor(2);
      hfit_sig->Fit(fsig,"","",-1,5.0);

      c1->Print(Form("hfit_sig_pt%d.gif",(int)fBinsPt[ipt]));
      
      fsig->SetParameter(0,2);
      fsig->SetParameter(1,fsig->GetParameter(1)*8.39614e-01/6.83080e-01);//correction from RC
      fsig->SetParameter(2,4.83182e-01);
      fsig->SetParameter(3,fsig->GetParameter(3)*2.33769e-01/2.26323e-01);
    
      cout << "fsig Integral = " << fsig->Integral(-1,11) << endl;
      for(int i=0;i<4;i++)
	cout << "fsig par " << i << "= " << fsig->GetParameter(i) << endl;

      // second obtain fit for the spikes
      hfit_spike  = (TH1F*)hTemplate_S[ieta][ipt]->Clone();
      hfit_spike  -> SetName("hfit_spike");
      hfit_spike  -> Rebin(4);

      TF1 *fspike = new TF1("fspike", exp_conv, -1., 11., 12);
      fspike->SetParameters(sigPar);
      fspike->SetParameter(0,hfit_spike->GetMaximum());
      fspike->SetLineColor(4);
      fspike->SetNpx(2500);
      hfit_spike->Fit(fspike,"","",-1,5.0);

      c1->Print(Form("hfit_spike_pt%d.gif",(int)fBinsPt[ipt]));
      
      fspike->SetParameter(0,2.0);
      cout << "fspike Integral = " << fspike->Integral(-1,11) << endl;
      float scale = (float)fsig->Integral(-1,11)/(float)fspike->Integral(-1,11);
      fspike->SetParameter(0,2.0*scale);
      cout << "now fspike Integral = " << fspike->Integral(-1,11) << endl;

      for(int i=0;i<4;i++)
	cout << "fspike par " << i << "= " << fspike->GetParameter(i) << endl;

    
      hsig->FillRandom("fsig",10000);
      hspike->FillRandom("fspike",10000);

      cout << "KS test for sideband data and sideband MC = " << 
	hsig->KolmogorovTest(hspike,"X") << endl;
      cout << "KS test 2 for sideband data and sideband MC = " << 
	hsig->KolmogorovTest(hspike) << endl;
     
      hsig->Reset();
      hsig->SetMaximum(1.2);
      hsig->Draw();
//       hspike->Draw("same");
      fsig->Draw("same");
      fspike->Draw("same");

      TLegend* leg = new TLegend(0.35,0.70,0.55,0.85);
      leg->SetHeader(Form("p_{T}[%d,%d]",(int)fBinsPt[ipt],(int)fBinsPt[ipt+1]));
      leg->SetFillColor(0);
      leg->SetFillStyle(0);
      leg->SetTextSize(0.04);
      leg->SetBorderSize(0);
      leg->AddEntry(fsig,"Random-cone-corrected MC","f");
      leg->AddEntry(fspike,"Spike","f");   
      leg->Draw("same");
      
      c1->Print(Form("CorrRCSpike_pt%d.eps",(int)fBinsPt[ipt]));
      c1->Print(Form("CorrRCSpike_pt%d.gif",(int)fBinsPt[ipt]));
      c1->Print(Form("CorrRCSpike_pt%d.C",(int)fBinsPt[ipt]));
      
    } 
  }

    
   

}
Esempio n. 26
0
void DrawVariable(TString VAR,bool SHAPE,int REBIN,float XMIN,float XMAX,TString XTITLE,bool PRINT,bool BLIND=false,float BLIND_MIN=0,float BLIND_MAX=0)
{
  gROOT->ForceStyle();
  const int N = 20;

  TString SAMPLE[N] = {
    "JetHT",
    "ttHJetTobb_M125_13TeV_amcatnloFXFX_madspin_pythia8",
    "ttHJetToNonbb_M125_13TeV_amcatnloFXFX_madspin_pythia8_mWCutfix",
    "QCD_HT300to500_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT500to700_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT700to1000_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT1000to1500_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT1500to2000_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT2000toInf_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "DYJetsToQQ_HT180_13TeV-madgraphMLM-pythia8",
    "WJetsToQQ_HT180_13TeV-madgraphMLM-pythia8",
    "TT_TuneCUETP8M1_13TeV-powheg-pythia8",
    "ST_t-channel_antitop_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1",
    "ST_tW_top_5f_inclusiveDecays_13TeV-powheg-pythia8_TuneCUETP8M1",
    "ST_tW_antitop_5f_inclusiveDecays_13TeV-powheg-pythia8_TuneCUETP8M1",
    "TTWJetsToQQ_TuneCUETP8M1_13TeV-amcatnloFXFX-madspin-pythia8",
    "TTZToQQ_TuneCUETP8M1_13TeV-amcatnlo-pythia8",
    "WZ_TuneCUETP8M1_13TeV-pythia8",
    "WWTo4Q_13TeV-powheg",
    "ZZTo4Q_13TeV_amcatnloFXFX_madspin_pythia8"
  };

  float XSEC[N] = {
    1.0,
    0.2934,
    0.2151,
    347700, 
    32100,
    6831,
    1207,
    119.9,
    25.24,
    1460,
    3539,
    832,
    217,
    35.6,
    35.6,
    0.4062,
    0.5297,
    47.13,
    51.723,
    22.29
  }; 
 
  float LUMI(5760);
  TFile *inf[N];
  TH1F  *h[N];

  TCanvas *can = new TCanvas("can_"+VAR,"can_"+VAR,900,600);
  can->SetRightMargin(0.15);

  for(int i=0;i<N;i++) {
    inf[i] = TFile::Open("Histo_"+SAMPLE[i]+".root");
    //cout<<inf[i]->GetName()<<" "<<VAR<<endl;
    h[i]   = (TH1F*)inf[i]->Get("ttH/h_"+VAR);
    h[i]->SetDirectory(0);
    h[i]->Rebin(REBIN);
    h[i]->Sumw2();
    h[i]->SetLineWidth(1);
    h[i]->SetLineColor(kBlack);
    if (i>0) {
      float norm = ((TH1F*)inf[i]->Get("eventCounter/GenEventWeight"))->GetSumOfWeights();
      //cout<<inf[i]->GetName()<<" "<<norm<<endl; 
      h[i]->Scale(LUMI*XSEC[i]/norm);
    }
    else {
      h[i]->SetLineWidth(2);
    }
    inf[i]->Close();
  }

  TH1F *hQCD = (TH1F*)h[3]->Clone("hQCD");
  hQCD->Add(h[4]);
  hQCD->Add(h[5]);
  hQCD->Add(h[6]); 
  hQCD->Add(h[7]);
  hQCD->Add(h[8]);

  TH1F *hVV = (TH1F*)h[17]->Clone("hVV");
  hVV->Add(h[18]);
  hVV->Add(h[19]);

  TH1F *hST = (TH1F*)h[12]->Clone("hST");
  hST->Add(h[13]);
  hST->Add(h[14]);

  h[1]->SetLineColor(kRed);//ttHbb
  h[1]->SetFillColor(kRed-9);
  h[1]->SetLineWidth(2);
  h[2]->SetLineColor(kRed);//ttHNobb
  h[2]->SetFillColor(kRed-10);
  h[2]->SetLineWidth(2);

  TH1F *hTT     = (TH1F*)h[11]->Clone("TTbar");
  TH1F *hTTZ    = (TH1F*)h[16]->Clone("TTZ");
  TH1F *hTTW    = (TH1F*)h[15]->Clone("TTW");
  TH1F *hWJets  = (TH1F*)h[10]->Clone("WJets");
  TH1F *hDYJets = (TH1F*)h[9]->Clone("DYJets");
 
  hQCD->SetFillColor(kBlue-10);//QCD
  hTT->SetFillColor(kOrange);
  hST->SetFillColor(kOrange-1);//ST
  hVV->SetFillColor(kMagenta-10);//VV
  hTTZ->SetFillColor(kYellow-10);//ttZ
  hTTW->SetFillColor(kYellow-9);//ttW
  hWJets->SetFillColor(kGreen-10);//WJets
  hDYJets->SetFillColor(kGreen-8);//ZJets
 
 

  float kfactor = 1.0;
  if (hQCD->Integral() > 0) { 
    kfactor = (h[0]->Integral()-hTT->Integral()-hWJets->Integral()-hDYJets->Integral()-hST->Integral())/hQCD->Integral();
  }  
  hQCD->Scale(kfactor);

  TH1F *hBkg = (TH1F*)hQCD->Clone("hBkg");
  hBkg->Add(hTT);
  hBkg->Add(hST);
  hBkg->Add(hTTW);
  hBkg->Add(hTTZ);
  hBkg->Add(hWJets);
  hBkg->Add(hDYJets);
  hBkg->Add(hVV);
  hBkg->SetFillColor(kGray);

  cout<<"Data events:  "<<h[0]->Integral()<<endl;
  cout<<"ttHJetTobb:   "<<h[1]->Integral()<<endl;
  cout<<"ttHJetToNonbb:"<<h[2]->Integral()<<endl;
  cout<<"QCD events:   "<<hQCD->Integral()<<endl;
  cout<<"TTbar events: "<<hTT->Integral()<<endl;
  cout<<"ST events:    "<<hST->Integral()<<endl;
  cout<<"TTZ events:   "<<hTTZ->Integral()<<endl;  
  cout<<"TTW events:   "<<hTTW->Integral()<<endl;
  cout<<"WJets events: "<<hWJets->Integral()<<endl;
  cout<<"DYJets events:"<<hDYJets->Integral()<<endl;
  cout<<"VV events:    "<<hVV->Integral()<<endl;
  cout<<"kfactor:      "<<kfactor<<endl;

  THStack *hs = new THStack("hs","hs");
  hs->Add(hVV);
  hs->Add(hTTW);
  hs->Add(hTTZ);
  hs->Add(hWJets);
  hs->Add(hDYJets);
  hs->Add(hST);
  hs->Add(hTT);
  hs->Add(hQCD);

  if (BLIND) {
    for(int i=0;i<h[0]->GetNbinsX();i++) {
      if (h[0]->GetBinCenter(i+1) > BLIND_MIN && h[0]->GetBinCenter(i+1) < BLIND_MAX) {
        h[0]->SetBinContent(i+1,0);
        h[0]->SetBinError(i+1,0);
      } 
    }
  }

  TH1F *hRatio = (TH1F*)h[0]->Clone("Ratio");
  hRatio->SetLineWidth(2);
  hRatio->Divide(hBkg);

  TLegend *leg = new TLegend(0.86,0.55,0.99,0.9);
  leg->SetFillColor(0);
  leg->SetTextFont(42);
  leg->SetTextSize(0.03);
  leg->AddEntry(hQCD,"QCD","F");
  leg->AddEntry(hTT,"TTbar","F");
  leg->AddEntry(hST,"ST","F");
  leg->AddEntry(hTTZ,"ttZ","F");
  leg->AddEntry(hTTW,"ttW","F");
  leg->AddEntry(hWJets,"WJets","F");
  leg->AddEntry(hDYJets,"ZJets","F");
  leg->AddEntry(hVV,"Diboson","F");
  leg->AddEntry(h[1],"ttHbb","L");
  leg->AddEntry(h[2],"ttHNonbb","L");
  
  if (SHAPE) {
    h[1]->SetFillStyle(3001);
    h[2]->SetFillStyle(3001);
    h[0]->Scale(1./h[0]->Integral());
    h[1]->Scale(1./h[1]->Integral());
    h[2]->Scale(1./h[2]->Integral());
    hQCD->Scale(1./hQCD->Integral());
    hBkg->Scale(1./hBkg->Integral());
    double max = TMath::Max(h[0]->GetBinContent(h[0]->GetMaximumBin()),hBkg->GetBinContent(hBkg->GetMaximumBin()));
    hBkg->SetMaximum(1.1*max);
    hBkg->GetXaxis()->SetTitle(XTITLE);
    hBkg->GetXaxis()->SetRangeUser(XMIN,XMAX);
    hBkg->Draw("hist");
    h[0]->Draw("same E"); 
    //h[1]->Draw("same hist"); 
    leg->Draw();
    gPad->RedrawAxis();
    can->Print("can_"+VAR+"_norm.pdf"); 
  }
  else {
    can->SetBottomMargin(0.25);
    gPad->SetLogy(); 
    //h[1]->Scale(h[0]->Integral()/h[1]->Integral());
    h[1]->SetFillColor(0);
    TH1F *hAux = (TH1F*)h[0]->Clone("aux");
    hAux->Reset();
    hAux->GetYaxis()->SetRangeUser(0.5,1.1*TMath::Max(h[1]->GetBinContent(h[1]->GetMaximumBin()),h[0]->GetBinContent(h[0]->GetMaximumBin()))); 
    
    hAux->GetXaxis()->SetRangeUser(XMIN,XMAX);
    hAux->GetYaxis()->SetTitle(TString::Format("Number of events / %1.2f fb^{-1}",LUMI/1000));
    hAux->GetXaxis()->SetTitle("");
    hAux->GetXaxis()->SetLabelSize(0.0);
    hAux->Draw();
    hs->Draw("hist same"); 
    h[0]->Draw("same E");
    h[1]->Draw("same hist");
    h[2]->Draw("same hist");
    leg->Draw();
    gPad->RedrawAxis();

    TPad *pad = new TPad("pad","pad",0.,0.,1.,1.);
    pad->SetTopMargin(0.77);
    pad->SetRightMargin(0.15);
    pad->SetFillColor(0);
    pad->SetFillStyle(0);
    pad->Draw();
    pad->cd(0);
    pad->SetGridy();
    hRatio->GetXaxis()->SetTitleOffset(0.95);
    hRatio->GetYaxis()->SetTitleOffset(1.5);
    hRatio->GetYaxis()->SetTickLength(0.06);
    hRatio->GetYaxis()->SetTitleSize(0.03);
    hRatio->GetYaxis()->SetLabelSize(0.03);
    hRatio->GetYaxis()->SetTitle("Data/MC");
    hRatio->GetXaxis()->SetTitle(XTITLE);
    hRatio->GetXaxis()->SetRangeUser(XMIN,XMAX);
    hRatio->GetYaxis()->SetRangeUser(0.5,1.5);
    hRatio->GetYaxis()->SetNdivisions(505);
    hRatio->Draw();
    if (PRINT) {
      can->Print("plots/can_"+VAR+"_abs.pdf"); 
      can->Print("plots/can_"+VAR+"_abs.png");
    }
  }
}
Esempio n. 27
0
void rateStudy() {
  const int NRUNS = 25;
  const int NCH = 32;
  const int NBINS = 32;

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

  TMultiGraph *mg = new TMultiGraph();

  TLegend *legend=new TLegend(0.65,0.15,0.88,0.55);
  legend->SetNColumns(4);
  legend->SetFillColor(0);

  TH1F* hRate = new TH1F("hRate", "hist", 32.0, 0, 8.0);

  //Color buffer
  const int NCOLORS = 32;
  int color[NCOLORS] = {73, 2, 3, 4, 99, 6, 7, 8, 9, 12, 28, 32, 34,
                        28, 50, 51, 56, 58, 88, 99, 1, 208, 209,
                        218, 212, 210, 221, 224, 225, 226, 227, 228 };

  ifstream fin;
  //fin.open("runlist.txt");
  fin.open("filter_runlist.txt");

  string line = "";

  TFile* out = new TFile("outtemp.root", "REACREATE");
  TH1F* h = new TH1F("h","hist", NBINS, 0, NBINS);
  TF1* pois = new TF1("pois","[0]*TMath::Poisson(x,[1])",0,50);
  TF1* ppp = new TF1("ppp","[0]*TMath::Power(0.5,x*[1])",0.01,1.0);


  for (int ch = 0; ch < NCH; ++ch) {

    //if ( ch==26 || ch==27 )
    //continue;

    //Graph points and errors
    Double_t x[NRUNS];
    Double_t y[NRUNS];
    Double_t errX[NRUNS] = {0};
    Double_t errY[NRUNS] = {0};

    int fileCounter = 0;
    while(getline(fin, line)) {
      vector<double> data = parse(line);
      stringstream filePath;
      filePath << "pmtratestudy/run" << data[0] << "*.root";
      cout << "opening file at " << filePath.str() << endl;
      cout << "file counter: " << fileCounter << " channel=" << ch << endl;
      //TFile* f = new TFile(filePath.str().c_str());
      //TTree* t = (TTree *)f->Get("eventtree");
      TChain* t = new TChain("eventtree");
      t->Add( filePath.str().c_str() );
      out->cd();

      x[fileCounter] = data[1];

      int nfires[NCH] = {0};
      int samples = 0;
      float chmax = 0.0;
      t->SetBranchAddress("nfires", &nfires);
      t->SetBranchAddress("samples", &samples);
      t->SetBranchAddress("chmax", &chmax);
      
      h->Reset();
      
      int nentries = t->GetEntries();
      for (int entry = 0; entry < nentries; ++entry) {
        t->GetEntry(entry);
        if (chmax < 100.0) {
          h->Fill(nfires[ch]);
        }
      }


      
      pois->SetParameter(0,1);
      pois->SetParameter(1, h->GetMean());

      h->Fit(pois,"RQ","",0,50);
      //TF1 *myfit = (TF1 *)h->GetFunction("pois");
      TF1 *myfit = (TF1 *)pois;
      Double_t lambda = myfit->GetParameter(1);  
      h->Draw();
      stringstream histFileName;
      histFileName << "hist/h" << data[0] << "_ch" << ch << ".png";
      c1->SaveAs(histFileName.str().c_str());
      //Graph with poisson method
#if 1
      y[fileCounter] = lambda / ((samples - 1) * 15.625E-6);
      errY[fileCounter] = myfit->GetParError(1) / ((samples - 1) * 15.625E-6);
#endif
      //Graph with mean method
#if 0
      y[fileCounter] = h->GetMean() / ((samples - 1) * 15.625E-6);
      errY[fileCounter] = h->GetMeanError() / ((samples - 1) * 15.625E-6);
#endif
      cout << x[fileCounter] << ", " << y[fileCounter] 
           << " | " << (samples - 1) << endl;
      delete t;
      //f->Close();
      fileCounter++;
    } 

    ppp->SetParameter(0,1);
    ppp->SetParameter(1,0.4);
     
    TGraphErrors* gr = new TGraphErrors(NRUNS, x, y, errX, errY);
    gr->SetLineColor(color[ch % NCOLORS]);
    cout << "color: " << color[ch % NCOLORS] << endl;
    gr->SetLineWidth(2);
    gr->SetMarkerStyle(7);
    gr->Fit("ppp","R0","Q0",0.045,2.0);
    TF1 *afit = (TF1 *)gr->GetFunction("ppp");
    Double_t aRate = 1/afit->GetParameter(1);  
    if (aRate > 0) {
      hRate->Fill(aRate);
    }
    gr->GetXaxis()->SetTitle("Run Date");
    gr->GetYaxis()->SetTitle("Rate [kHz]");

    stringstream entryName, fileName;
    entryName << "Channel" << ch;
    gr->SetTitle(entryName.str().c_str());
    fileName << "plots/" << ch << ".png";
    legend->AddEntry(gr, entryName.str().c_str());
    gr->Draw("alp");
    c1->SaveAs(fileName.str().c_str());
    mg->Add(gr);
    cout << "added plot to mg\n";
    fin.clear();
    fin.seekg(0, ios::beg);
  } // loop over channel
  hRate->Draw();
  hRate->Fit("gaus");
  c1->SaveAs("hrate.pdf");
  mg->Draw("alp");
  mg->GetXaxis()->SetTitle("Days since first run");
  mg->GetYaxis()->SetTitle("Rate [kHz]");
  mg->SetTitle("All channels: Rate vs. Days since first Run");

  legend->Draw();
  c1->SaveAs("mg.pdf");
  
}
Esempio n. 28
0
int main(int argc, char* argv[]){
//int analyzer_stackRatio(){
gROOT->ProcessLine(".x /afs/cern.ch/work/n/nchernya/setTDRStyle.C");
int set_type = atoi(argv[1]); //0 - double, 1 - single
int region_type=atoi(argv[2]); // 0 - analysis, 1 - control region , top
 
const int nfiles  = 22;
TString leg_names[nfiles] = {"Data","VBF, m(H) = 125 GeV","GF, m(H) = 125 GeV","t#bar{t}H, H#rightarrow b#bar{b}","t#bar{t}H, non b#bar{b}","Z(ll) + jets","W(l#nu) + jets","Single top(s-ch)","Single t,t-top","Single t,t-antitop","Single t","Z + jets","W + jets","t#bar{t}","QCD, H_{T}>100 GeV","QCD, H_{T}>200 GeV","QCD, H_{T}>300 GeV","QCD, H_{T}>500 GeV","QCD, H_{T}>700 GeV","QCD, H_{T}>1000 GeV","QCD, H_{T}>1500 GeV","QCD, H_{T}>2000 GeV"};
TString set_names[2] = {"DoubleB","SingleB"}; 
//if (set_type==0)leg_names[0] = "Data (DoubleB)";
//if (set_type==1)leg_names[0] = "Data (SingleB)";


TString file_names[nfiles] = { "BTagCSV","VBFHToBB_M-125","GluGluHToBB_M-125","ttHTobb_M125","ttHToNonbb_M125","DYJetsToLL","WJetsToLNu","ST_s-channel","ST_tW","ST_t-channel_antitop_4f_inclusiveDecays","ST_t-channel_top_4f_inclusiveDecays","DYJetsToQQ","WJetsToQQ","TT_powheg","QCD_HT2000toInf","QCD_HT1500to2000","QCD_HT1000to1500","QCD_HT100to200","QCD_HT700to1000","QCD_HT200to300","QCD_HT500to700","QCD_HT300to500"};
TString file_names_trigUncUp[nfiles]; 
TString file_names_trigUncDown[nfiles]; 
int bg_begin;
int qcd_begin=14;
if (region_type==0) bg_begin=7;
else bg_begin=5;

int FILLCOLOR[nfiles] = {1,kRed,kBlue+0,kViolet+2,kGreen+2,kYellow-4,kYellow-8,kYellow-9,kYellow-9, kYellow-9,kYellow-9,kOrange-9,kYellow-10,kOrange-2,kRed+2,kRed+1,kRed+0, kRed-7,kRed-9,kRed-6,kRed-8,kRed-10};
int LINECOLOR[nfiles] = {1,kRed,kBlue+0,kViolet+2,kGreen+2,1,1,kYellow-9,kYellow-9,kYellow-9,1,1,1,1,1,1,1,1,1,1,1,1};
int LINESTYLE[nfiles] = {1,1,2,3,8,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
int LINEWIDTH[nfiles] = {1,3,3,3,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
int FILLSTYLE[nfiles] = {1001,1001,1001,1001,1001,1001,1001,1001,1001,1001,1001,1001,1001,1001,1001,1001,1001,1001,1001,1001,1001,1001};
	
int order[nfiles] = {0,1,2,3,4, 5, 6, 7, 8, 9,10,11,12,13,  21,20,19,14,18,15,17,16};// number in file_names array as they should appear in the legend
//int order[nfiles] = {0,1,2,3,4, 5, 6, 7, 8,9,10,  18,17,16,11,15,12,14,13};// number in file_names array as they should appear in the legend
int order_legend[nfiles]; 
for (int i=0;i<nfiles;i++){
	order_legend[order[i]]=i;
}
	

TString btag[2] = {"v14, DoubleBtag","v14, SingleBtagBlike"}; 
TString region[3]={"_analysis","_controlTop","_controlDY"}; // 0 - analysis, 1 - control region , top; 2 - control region DY

TString set[2] = {"_double","_single"};
for (int i=0;i<nfiles;i++){
	file_names[i].Prepend("dcap://t3se01.psi.ch:22125//pnfs/psi.ch/cms/trivcat//store/user/nchernya/Hbb/plotterOutput/v21/");
	file_names[i].Append(region[region_type]);
	file_names[i].Append(set[set_type]);
//	file_names[i].Append("_v21_v21");
	file_names[i].Append("_trignone_v21_v21");
	file_names[i].Append(".root");
}
TString trigger[2] = {"RatioDoubleBtag_blike_", "RatioSingleBtag_blike_"};
//TString trigger[2] = {"trigWeightRatioDoubleBtag_", "trigWeightSilvioRatioSingleBtag_"};
//TString dir_name= "plots_powheg_130/";
TString dir_name= "plots_powheg_125_exclusive";
dir_name.Append(region[region_type]+"/");
//TString dir_name = "plots_amc/";
Float_t lumi = 2320;

	


TLegend *leg = new TLegend(0.77,0.45,0.92,0.9); //without writing about SF
leg->SetFillColor(0);
leg->SetBorderSize(0);
leg->SetTextFont(42);
leg->SetTextSize(0.025);
TLegend *leg2 = new TLegend(0.77,0.35,0.92,0.4); //with  writing about SF
leg2->SetFillColor(0);
leg2->SetBorderSize(0);
leg2->SetTextFont(42);
leg2->SetTextSize(0.025);

const int nhistos = 76; //40//52
//TString hist_names[nhistos]={"hJet1_pt","hJet2_pt","hJet3_pt","hJet4_pt","hJet1_eta","hJet2_eta","hJet3_eta","hJet4_eta","hJet1_phi","hJet2_phi","hJet3_phi","hJet4_phi","hMqq", "hEtaQQ", "hPhiBB","hMbb","hbtag","hbtag2","hcosOqqbb","hEtaQB1", "hEtaQB2", "hPhiQB1", "hPhiQB2","hx1","hx2","hVB1_mass","hVB2_mass","hEtot","hPxtot","hPytot","hPztot","hJet5_pt","hPtqqbb","hEtaqqbb","hPhiqqbb","hJet1_pt_bin","hJet2_pt_bin","hJet3_pt_bin","hJet4_pt_bin", "hMqq_bin","hEtaSoftJets", "hPtSoftJets","hMassSoftJets","hHTsoft","hSoft_n2","hSoft_n5","hSoft_n10","hqgl","hqgl2", "hPtSoftJets2","hPtSoftJets3","hPVs", "hJet1q_pt", "hJet1q_eta", "hJet1q_ptd", "hJet1q_axis2", "hJet1q_mult", "hJet2q_pt", "hJet2q_eta", "hJet2q_ptd", "hJet2q_axis2", "hJet2q_mult","hMbb_regVBF","hMbb_regVBF_fsr","hblike1","hblike2", "hmet", "hqgl1_VBF", "hqgl2_VBF", "hbdt", "hPhiQQ", "hMbb_regVBF_fsr_high", "hMbb_regVBF_fsr_high_cat","hselLeptons_relIso03"};
TString hist_names[nhistos]={"hJet1_pt","hJet2_pt","hJet3_pt","hJet4_pt","hJet1_eta","hJet2_eta","hJet3_eta","hJet4_eta","hJet1_phi","hJet2_phi","hJet3_phi","hJet4_phi","hMqq", "hEtaQQ", "hPhiBB","hMbb","hbtag","hbtag2","hcosOqqbb","hEtaQB1", "hEtaQB2", "hPhiQB1", "hPhiQB2","hx1","hx2","hVB1_mass","hVB2_mass","hEtot","hPxtot","hPytot","hPztot","hJet5_pt","hPtqqbb","hEtaqqbb","hPhiqqbb","hJet1_pt_bin","hJet2_pt_bin","hJet3_pt_bin","hJet4_pt_bin", "hMqq_bin","hEtaSoftJets", "hPtSoftJets","hMassSoftJets","hHTsoft","hSoft_n2","hSoft_n5","hSoft_n10","hqgl","hqgl2", "hPtSoftJets2","hPtSoftJets3","hPVs", "hJet1q_pt", "hJet1q_eta", "hJet1q_ptd", "hJet1q_axis2", "hJet1q_mult", "hJet2q_pt", "hJet2q_eta", "hJet2q_ptd", "hJet2q_axis2", "hJet2q_mult","hMbb_regVBF","hMbb_regVBF_fsr","hblike1","hblike2", "hmet", "hmet", "hmet", "hmet", "hPhiQQ", "hMbb_regVBF_fsr_high", "hMbb_regVBF_fsr_high_cat","hselLeptons_relIso03", "hbtag_log","hbtag2_log"};
int UNITS[nhistos]={1,1,1,1 ,0,0,0,0 ,0,0,0,0, 1 ,0,0 ,1, 0,0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1 ,0,0, 1,1,1,1,1, 0, 1,1,1 ,0,0,0,0,0, 1,1, 0, 1,0,0,0,0, 1,0,0,0,0, 1,1 ,0,0, 1, 0,0,0,0 ,1,1, 0};
std::array<int,100> LOGY_array = {71,72,51,52,53,54,55,56,57,58,59,60,61};

TString hist_names_sum[nhistos]={};
TString sum_histos_names[nhistos]={};
std::string hist_names_sort[nhistos];
for (int i=0;i<nhistos;i++){
	hist_names_sort[i] = hist_names[i];
	hist_names_sum[i] = hist_names[i];
	hist_names_sum[i].Append("_sum");
	sum_histos_names[i] = hist_names[i];
	sum_histos_names[i].Append("_sum0");
}
Float_t discriminators[nhistos];
TString stacks_names[nhistos];
for (int i=0;i<nhistos;i++){
	stacks_names[i] = hist_names[i];
	stacks_names[i].Prepend("s");
}
TString output_names[nhistos];
for (int i=0;i<nhistos;i++){
	output_names[i] = hist_names[i];
	output_names[i].Prepend(dir_name);
	output_names[i].Prepend(trigger[set_type]);
	output_names[i].Prepend("wo_trigger/");
	output_names[i].Append(region[region_type]);
	output_names[i].Append(set[set_type]+"_v21.png");
}

TH1F *data_histos[nhistos];
TH1F *data_histos2[nhistos];
TH1F *signal_histos[nhistos];
TH1F *signal_histos2[nhistos];
TH1F *tthbb_histos[nhistos];
TH1F *tthnbb_histos[nhistos];
TH1F *gf_histos[nhistos];
TH1F *sum_histos[nhistos];
TH1F *histos_forUnc[nhistos];
TH1F *histos_for_legened[nhistos];
TH1F *discr_histos[nhistos];//Mqq,delta eta, delta phi, qgl, btag //12,13,14,21,22
TH1F *hBkgVis[nhistos];
TH1F *hBkgUncUp[nhistos];
TH1F *hBkgUncLo[nhistos];


int files=0; 
THStack *stacks[nhistos];
for (int i=0;i<nhistos;++i){
	stacks[i] = new THStack(stacks_names[i],"");
}
Double_t totalBG=0.;
Double_t totalQCD=0.;
Double_t totalMC=0.;
Double_t totalData=0.;
Double_t totalDataQCD=0.;
ofstream out_efficiency;
ofstream out_discrimination;
out_efficiency.open("wo_trigger/"+trigger[set_type]+dir_name+"efficiency.txt"); 

//Float_t MC_data[2] = {1.,1.};////////////for efficiency 
//Float_t MC_data[2] = {1./0.7581,1./0.906};////////////for blike single btag logic and with PU for golden FINAL WITHOUT TRIGGER CORRECTION
//Float_t MC_data[2] = {1./1.5,1./1.56};////////////trigger correction using 4 jets, mqq(double) and csv1,csv2(double)
//Float_t MC_data[2] = {1./1.07,1./1.52};////////////trigger correction using 4 jets (not 3,4 for single), mqq(double) and csv1
//Float_t MC_data[2] = {1./1.07,1./1.17};////////////trigger correction using 4 jets (not 3 for single), mqq(double) and csv1(double)
//Float_t MC_data[2] = {1./1.43,1./1.68};////////////trigger correction using 4 jets (not 3 for single), mqq(double) and csv1(double) and normalization with 3rd jet in double and 1st in single
Float_t MC_data[2] = {1./1.01,1./1.13};//////////// FINAL after trigger correction
if (region_type!=0) {
	MC_data[0]=1.; 
	MC_data[1]=1.; 
}
Float_t lumi_qcd=lumi/MC_data[set_type];

do{
	TFile *file_initial;
  	file_initial = TFile::Open(file_names[files]);
	TH1F *histos[100];
	for (int hist=0;hist<nhistos;++hist){
	//	if (region_type!=0) ((TH1F*)file_initial->Get(hist_names[hist]))->Rebin(2);
		if ((hist==71)||(hist==72)) ((TH1F*)file_initial->Get(hist_names[hist]))->Rebin(2);
		if (hist==12) ((TH1F*)file_initial->Get(hist_names[hist]))->Rebin(2.);
		histos[hist] = (TH1F*)file_initial->Get(hist_names[hist])->Clone("h");
		if (files==0) data_histos[hist] = (TH1F*)file_initial->Get(hist_names[hist])->Clone("data");
		if ((files>0)&&(files<qcd_begin))histos[hist]->Scale(lumi);
		if (files>=qcd_begin)histos[hist]->Scale(lumi_qcd);
		
		if (files==1) 	sum_histos[hist] = (TH1F*)histos[hist]->Clone(sum_histos_names[hist]);
		if (files>1)	sum_histos[hist]->Add(histos[hist]); 

		if (files>0) histos[hist]->Sumw2(kFALSE);
		if (hist==4) cout<<files<<"   "<<histos[4]->Integral() <<endl;

		if (files==1) {
			signal_histos[hist] = (TH1F*)file_initial->Get(hist_names[hist])->Clone(hist_names_sum[hist]+"newhist");
			signal_histos[hist]->Scale(lumi);
			signal_histos[hist]->Sumw2(kFALSE);
			signal_histos[hist]->SetLineColor(LINECOLOR[files]);
			signal_histos[hist]->SetLineStyle(LINESTYLE[files]);
			signal_histos2[hist]=(TH1F*)signal_histos[hist]->Clone("signalHist2");
		}
		if (files==2) {
			gf_histos[hist] = (TH1F*)file_initial->Get(hist_names[hist])->Clone(hist_names_sum[hist]+"tthnb");
			gf_histos[hist]->Scale(lumi);
			gf_histos[hist]->Sumw2(kFALSE);
			gf_histos[hist]->SetLineColor(LINECOLOR[files]);
			gf_histos[hist]->SetLineStyle(LINESTYLE[files]);
		}
		if (files==3) {
			tthbb_histos[hist] = (TH1F*)file_initial->Get(hist_names[hist])->Clone(hist_names_sum[hist]+"tthb");
			tthbb_histos[hist]->Scale(lumi);
			tthbb_histos[hist]->Sumw2(kFALSE);
			tthbb_histos[hist]->SetLineColor(LINECOLOR[files]);
			tthbb_histos[hist]->SetLineStyle(LINESTYLE[files]);
		}
		if (files==4) {
			tthnbb_histos[hist] = (TH1F*)file_initial->Get(hist_names[hist])->Clone(hist_names_sum[hist]+"tthnb");
			tthnbb_histos[hist]->Scale(lumi);
			tthnbb_histos[hist]->Sumw2(kFALSE);
			tthnbb_histos[hist]->SetLineColor(LINECOLOR[files]);
			tthnbb_histos[hist]->SetLineStyle(LINESTYLE[files]);
		}
		histos[hist]->SetLineColor(LINECOLOR[files]);
		histos[hist]->SetLineStyle(LINESTYLE[files]);
		histos[hist]->SetLineWidth(LINEWIDTH[files]);
		histos[hist]->SetFillStyle(FILLSTYLE[files]);
		if ((files!=0)) histos[hist]->SetFillColor(FILLCOLOR[files]);
		if ((region_type!=0)&&(files>=qcd_begin)) histos[hist]->SetFillColor(kRed+2);
		
		if (files==0) {
			histos[hist]->SetMarkerStyle(20);
			data_histos[hist]->SetLineColor(1);
			data_histos[hist]->SetMarkerStyle(20);
			data_histos[hist]->SetMarkerSize(.8);
		}
	 	if (files>=bg_begin) stacks[hist]->Add(histos[hist]);
		if (hist==0) histos_for_legened[files] = (TH1F*)histos[0]->Clone("newd");
		if (files==bg_begin)	discr_histos[hist] = (TH1F*)file_initial->Get(hist_names[hist])->Clone("discr");
		if (files>bg_begin)	discr_histos[hist]->Add(histos[hist]); 
   	}
		if (files>=bg_begin) totalBG+=histos[4]->Integral();
		if (files>=qcd_begin) totalQCD+=histos[4]->Integral();
		if (files>0) totalMC+=histos[4]->Integral();
		if (files==0) {totalData+=histos[4]->Integral(); totalDataQCD+=histos[4]->Integral();}
		if ((files>0)&&(files<qcd_begin)) {totalDataQCD-=histos[4]->Integral();}
		if (files==0) out_efficiency<<"Sample & \t\t\t yield(per "<< lumi<<" $pb^{-1}$)"<<endl;
		if (files==0) out_efficiency<<leg_names[order[files]]<<"&\t \t \t"<< std::setprecision(5)<<histos[4]->Integral() <<endl;
		else out_efficiency<<leg_names[order[files]]<<"&\t\t\t  "<<std::setprecision(5)<<histos[4]->Integral()<<endl;
		if (files==nfiles-1) out_efficiency<<"Total BG"<<"&\t \t \t  "<<std::setprecision(5)<<totalBG<<endl;
		if (files==nfiles-1) out_efficiency<<"Total MC"<<"&\t \t \t  "<<std::setprecision(5)<<totalMC<<endl;
		if (files==nfiles-1) out_efficiency<<"Data/MC"<<"&\t \t \t  "<<std::setprecision(3)<<totalData/totalMC<<endl;
		if (files==nfiles-1) out_efficiency<<"DataQCD/QCD"<<"&\t \t \t  "<<std::setprecision(3)<<totalDataQCD/totalQCD<<endl;
		if (files==nfiles-1) cout<<"DataQCD/QCD"<<"&\t \t \t  "<<std::setprecision(3)<<totalDataQCD/totalQCD<<endl;
files++;
}while (files<nfiles);
out_efficiency.close();

for (int hist=0;hist<nhistos;hist++){
	hBkgUncUp[hist] = (TH1F*)sum_histos[hist]->Clone("hBkgUncUp");
	hBkgUncLo[hist] = (TH1F*)sum_histos[hist]->Clone("hBkgUncLo");
  	hBkgVis[hist]   = (TH1F*)sum_histos[hist]->Clone("hbkgVis");
  	for(int i=0;i<hBkgUncUp[hist]->GetNbinsX();i++) {
  		float e = 0.0;
  		float eUpTrig = 0.0;
  		float eDownTrig = 0.0;
    	if (sum_histos[hist]->GetBinContent(i+1) != 0) {
      	e = sum_histos[hist]->GetBinError(i+1)/sum_histos[hist]->GetBinContent(i+1);
   	}
    	hBkgUncUp[hist]->SetBinContent(i+1,e);
    	hBkgUncLo[hist]->SetBinContent(i+1,-e);
	}
  	hBkgVis[hist]->SetMarkerSize(0);
 	hBkgVis[hist]->SetFillColor(kBlack);
 	hBkgVis[hist]->SetFillStyle(3004);
 	hBkgUncUp[hist]->SetLineColor(kBlack);
 	hBkgUncUp[hist]->SetLineWidth(1);
 	hBkgUncUp[hist]->SetFillColor(kBlack);
 	hBkgUncUp[hist]->SetFillStyle(3004);
	hBkgUncLo[hist]->SetLineColor(kBlack);
 	hBkgUncLo[hist]->SetLineWidth(1);
  	hBkgUncLo[hist]->SetFillColor(kBlack);
	hBkgUncLo[hist]->SetFillStyle(3004);
}


//Float_t TSF[2] = {0.452433,0.525697}; old v13
//Float_t TSF[2] = {1.,1.}; //v14 (cmssw74)
Float_t TSF[2] = {0.89,1.07};
Float_t kfactors[2] = {0.,0.};
kfactors[set_type] = 1./(MC_data[set_type] * TSF[set_type]);
cout<<"kfactor = "<<kfactors[set_type]<<endl;
cout<<"Data/MC = "<< MC_data[set_type]<<endl;


for (int i=0;i<nfiles;i++){
	if ((i==7)||(i==8)||(i==9)) continue;
	if (i==0) leg->AddEntry(histos_for_legened[order_legend[i]],leg_names[i],"P");
	if ((i==1)||(i==2)||(i==3) || (i==4))  leg->AddEntry(histos_for_legened[order_legend[i]],leg_names[i],"L");
//	if ((i==1)||(i==2))  leg->AddEntry(histos_for_legened[order_legend[i]],leg_names[i],"L");
	if ((i>=bg_begin)&&(i<qcd_begin)) leg->AddEntry(histos_for_legened[order_legend[i]],leg_names[i],"F");
}
if (region_type==0){
	for (int i=0;i<nfiles;i++){
		if (i>=qcd_begin) leg->AddEntry(histos_for_legened[order_legend[i]],leg_names[i],"F");
	}
}
if (region_type!=0) {
	leg->AddEntry(histos_for_legened[order_legend[qcd_begin]],"QCD","F");
}
leg->AddEntry(hBkgUncUp[0],"MC stat. unc.","F");
leg2->AddEntry(hBkgUncUp[0],"without dynamical","");
leg2->AddEntry(hBkgUncUp[0],"trigger SF","");



for (int d=0;d<nhistos;d++){
	discriminators[d] = Discr(discr_histos[d],signal_histos2[d]);
}

bubblesort(discriminators, hist_names_sort,nhistos);

out_discrimination.open("wo_trigger/"+trigger[set_type]+dir_name+"discrimination.txt");
for (int d=0;d<nhistos;d++){
	if (d==0) out_discrimination<<"Variable &\t d"<<endl;
	out_discrimination<<"$"<<hist_names_sort[d]<<"$"<<" & \t "<< std::setprecision(2)<< discriminators[d]<<endl;
}
out_discrimination.close();

TLatex* tex = new TLatex(0.75,0.95,"2.32 fb^{-1} (13 TeV)");
tex->SetNDC();
tex->SetTextAlign(35);
tex->SetTextFont(42);
tex->SetTextSize(0.035);
tex->SetLineWidth(2);
TLatex *tex1 = new TLatex(0.17,0.95,"CMS");
tex1->SetNDC();
tex1->SetTextAlign(20);
tex1->SetTextFont(61);
tex1->SetTextSize(0.04);
tex1->SetLineWidth(2);
TLatex* tex2 = new TLatex(0.27,0.89,"Work in progress");
tex2->SetNDC();
tex2->SetTextAlign(20);
tex2->SetTextFont(52);
tex2->SetTextSize(0.035);
tex2->SetLineWidth(2);
TString temp_str;
temp_str.Form("%2.2f",kfactors[set_type]);
//		temp_str.Form("%2.2f",(1./MC_data[set_type]));
TString k_factor_str = temp_str.Prepend("QCD MC #times  ");
TLatex* tex_k = new TLatex(0.63,0.89,k_factor_str);
tex_k->SetNDC();
tex_k->SetTextAlign(20);
tex_k->SetTextFont(42);
tex_k->SetTextSize(0.03);
tex_k->SetLineWidth(2);
TLatex* tex_set = new TLatex(0.667,0.86,set_names[set_type]);
tex_set->SetNDC();
tex_set->SetTextAlign(20);
tex_set->SetTextFont(42);
tex_set->SetTextSize(0.03);
tex_set->SetLineWidth(2);
for (int i=0;i<nhistos;i++){
//	for (int i=0;i<4;i++){
		//temp_str.Form("%2.2f",Discr(discr_histos[i],signal_histos2[i]));
		Float_t d_value = Discr((TH1F*)data_histos[i]->Clone("data2"),signal_histos2[i]);
		temp_str.Form("%2.2f",d_value);
		TString disc_value = temp_str.Prepend(" d = ");
		TLatex *disc_value_text = new TLatex(0.668,0.83,disc_value);
      disc_value_text->SetNDC();
     	disc_value_text->SetTextAlign(20);
      disc_value_text->SetTextFont(42);
      disc_value_text->SetTextSize(0.03);
      disc_value_text->SetLineWidth(2);
		
		temp_str.Form("%2d",i);
		TString can_name="c1";
		can_name.Append(temp_str);
		TCanvas *c1 = new TCanvas(can_name,"",900,750);
		c1->cd();
		gPad->SetLogy(0);
		c1->SetBottomMargin(.3);
		c1->SetRightMargin(.25);
	
		bool LOGY=true;
		if ((region_type==0)&&(i==51)) LOGY=false;	
	//	bool LOGY=std::find(LOGY_array.begin(),LOGY_array.end(),i) != LOGY_array.end();
  	//	if ((region_type==0) && (LOGY==true)) gPad->SetLogy();
  		if ((region_type==0) && (LOGY==true)) gPad->SetLogy();

		Double_t xmin = signal_histos[i]->GetBinCenter(0);
		Double_t xmax = signal_histos[i]->GetBinCenter(signal_histos[i]->GetNbinsX())*1.02;
		if ((region_type!=0 ) && (i==66)) {xmin=0.;xmax=400;}
		TH1F *frame = new TH1F("frame","",1,xmin,xmax);
		frame->Reset();
		frame->SetMinimum(1e-3);
      frame->SetMaximum(1e8);
		if ((region_type!=0) || (LOGY==false))	frame->SetMaximum(hBkgVis[i]->GetMaximum()*1.2);
      frame->GetXaxis()->SetTitleOffset(0.91);
      frame->SetStats(0);
		frame->GetYaxis()->SetNdivisions(505);
	 	frame->GetXaxis()->SetLabelSize(0.0);
		char name[1000];
		if (UNITS[i]==0) {
			if (data_histos[i]->GetBinWidth(1)>1) sprintf(name,"Events / %1.0f",data_histos[i]->GetBinWidth(1));
			else sprintf(name,"Events / %1.2f",data_histos[i]->GetBinWidth(1));
		} else {
      	sprintf(name,"Events / %1.0f %s",data_histos[i]->GetBinWidth(1),"GeV");
		}
		frame->GetYaxis()->SetTitle(name);

      frame->Draw();
		tex->Draw();
		tex1->Draw();
		tex2->Draw();
		if (region_type==0) tex_k->Draw();
		tex_set->Draw();
		if ((region_type==0)&&(d_value>0.1)&&(d_value<1.)) disc_value_text->Draw();
    	stacks[i]->Draw("same");	
		signal_histos[i]->Draw("same");
		tthbb_histos[i]->Draw("same");
		tthnbb_histos[i]->Draw("same");
		gf_histos[i]->Draw("same");
/////////////////cross check of stupid THStack//////
//
//		sum_histos[i]->SetLineColor(kCyan);
//		sum_histos[i]->Scale(lumi);
//		sum_histos[i]->Draw("Lsame");
//
///////////////////////////////////////////////////
		data_histos[i]->Draw("Psame");
		hBkgVis[i]->Draw("same E2");

		leg->Draw("same");
		leg2->Draw("same");
  		gPad->RedrawAxis();
	
  		TPad* pad2 = new TPad("pad2", "pad2", 0., 0., 1., 1.);
 		pad2->SetTopMargin(0.73);
 		pad2->SetRightMargin(0.25);
 		pad2->SetFillColor(0);
  		pad2->SetFillStyle(0);
  		pad2->Draw();
  		pad2->cd(0);
  		gPad->SetGridy();

		TH1F *frame2 = new TH1F("frame2","",1,xmin,xmax);
		frame2->SetMinimum(-1.);
      frame2->SetMaximum(1.);
      frame2->SetStats(0);
      frame2->SetTitleFont(42,"x");
		frame2->SetTitleFont(42,"y");
      frame2->SetTitleSize(0.13, "XYZ");
		frame2->GetYaxis()->SetNdivisions(505);
 		frame2->GetYaxis()->SetTickLength(0.06);
  		frame2->GetYaxis()->SetTitleSize(0.04);
  		frame2->GetYaxis()->SetTitleOffset(1.5);
 		frame2->GetYaxis()->SetLabelSize(0.03);
  		frame2->GetYaxis()->CenterTitle(kTRUE);
  		frame2->GetXaxis()->SetTitleSize(0.05);
  		frame2->GetXaxis()->SetLabelSize(0.04);
		frame2->SetXTitle(signal_histos[i]->GetXaxis()->GetTitle());
		frame2->SetYTitle("Data / MC - 1");
		frame2->Draw();	

 		Double_t aa[2] = {xmin,xmax};
   	Double_t bb[2] = {0,0};
   	TGraph *cons = new TGraph(2,aa,bb);
    	cons->SetLineStyle(2);
		cons->Draw("Lsame");

		data_histos2[i] = (TH1F*)data_histos[i]->Clone("new");
		data_histos2[i]->Add(sum_histos[i],-1);
		data_histos2[i]->Divide(sum_histos[i]);
		data_histos2[i]->Draw("PEsame");
		hBkgUncUp[i]->Draw("HIST same");
		hBkgUncLo[i]->Draw("HIST same");
		pad2->RedrawAxis();
		c1->Print(output_names[i]);
		c1->Delete();
	}



return 0;
}
Esempio n. 29
0
void SPEFit(char * fLEDname, char * fPEDname, int run, int LED_amp, double cutmax = 250.0)
{

  //set plotting styles
  gStyle->SetCanvasColor(0);
  gStyle->SetPadColor(0);
  gStyle->SetCanvasBorderMode(0);
  gStyle->SetFrameBorderMode(0);
  gStyle->SetStatColor(0);
  gStyle->SetPadTickX(1);
  gStyle->SetPadTickY(1);

    //set file names
    stringstream out_fname;
    stringstream out_fname1;
    out_fname<<"SPEconstants_Run_"<<run<<".txt";
    out_fname1<<"SPEspec_Run_"<<run<<".txt";

    ofstream  constants_file(out_fname.str().c_str(),ios_base::trunc); 
    //ofstream  constants_file1(out_fname1.str().c_str(),ios_base::trunc); 
    constants_file<<"Run "<<run<<endl;
    constants_file<<"type SPE"<<endl;
    constants_file<<"LED_amplitude "<<LED_amp<<endl<<endl;

    constants_file<<endl<<"LED_amplitude Depth Phi Eta Ped_mean Ped_mean_err Ped_RMS  Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl;

    out_fname.str("");
    out_fname<<"SPEdistributions_Run_"<<run<<".txt";

    out_fname.str("");
    out_fname<<"SPEextra_Run_"<<run<<".txt";
    //ofstream  extra_file(out_fname.str().c_str(),ios_base::trunc); 


    double scale = 1.0;
    scale = 2.6; //Need to scale up HF charge
    double fC2electrons = 6240.; //convert fC to #electrons

    char spename[128], pedname[128], spehistname[128];
 
    TFile *tfLED = new TFile(fLEDname);
    TFile *tfPED = new TFile(fPEDname);
    


    //const int NnewBins = 106;
    //double binsX[NnewBins] = {0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,180,190,200,210,220,230,240,250,266,282,298,316,336,356,378,404,430,456,482,500};

    const int NnewBins = 80;
    double binsX[NnewBins] = {0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,60,63,66,69,72,75,78,81,84,87,90,93,96,99,102,105,108,111,114,117,120,123,126,129,132,135,138,141,144,147,150,153,156,159,162,165,168,171,174,177,180,190,200,210,220,230,240,250,266,282,298,316,336,356,378,404,430,456,482,500};	  
    TH1F* hspe = new TH1F("hspe","hspe",NnewBins-1,binsX);


    int NDepth = 2; //number of depths
    int MinDepth = 1;
    int MaxDepth = 2;
    int MinEta = 29; 
    int MaxEta = 41;
    int MinPhi = 41;
    int MaxPhi = 53;
   
 
    TCanvas *Carray[NDepth+1][MaxPhi+1];
    bool drawflag[NDepth+1][MaxPhi+1];  
    TH1F *LED[NDepth+1][MaxEta+1][MaxPhi+1];
    TH1F *PED[NDepth+1][MaxEta+1][MaxPhi+1];

    for(int iDepth = MinDepth; iDepth <= MaxDepth; iDepth++){
      for(int iPhi = MinPhi; iPhi <= MaxPhi; iPhi++){

	bool nonNull = false;

	for(int iEta = MinEta; iEta <= MaxEta; iEta++){

	  sprintf(spename,"Analyzer/CommonDir/ResPlotDir/Histo_for_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi);
	  LED[iDepth][iEta][iPhi]=(TH1F *)tfLED->Get(spename);
	  if(LED[iDepth][iEta][iPhi]) nonNull = true;
      
	  sprintf(spename,"Analyzer/CommonDir/ResPlotDir/Histo_for_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi);
	  PED[iDepth][iEta][iPhi]=(TH1F *)tfPED->Get(spename);
	}

	drawflag[iDepth][iPhi] = false;
	char canvname[16];
	sprintf(canvname, "c_%d_%d", iDepth,iPhi);
	if(nonNull){ //only create canvas if distributions exist
	  Carray[iDepth][iPhi] = new TCanvas(canvname,canvname,1200,700);
	  Carray[iDepth][iPhi]->Divide(5,3);
	}

      }
    }



    int HV=0;

    for(int iDepth = MinDepth; iDepth <= MaxDepth; iDepth++){
      for(int iPhi = MinPhi; iPhi <= MaxPhi; iPhi++){
	for(int iEta = MinEta; iEta <= MaxEta; iEta++){

	  //cout<<iDepth<<" "<<iPhi<<" "<<iEta<<endl;

	  if(!LED[iDepth][iEta][iPhi]) continue;

	  sprintf(spehistname,"led %d %d %d",iDepth,iEta,iPhi);
	  TH1F *hspe_temp = (TH1F *)LED[iDepth][iEta][iPhi]->Clone(spehistname);
	  sprintf(spehistname,"ped %d %d %d",iDepth,iEta,iPhi);
	  TH1F *hped = (TH1F *)PED[iDepth][iEta][iPhi]->Clone(spehistname);
	  hspe->Reset();
	  sprintf (spehistname, "SumLED_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi);
	  hspe->SetTitle(spehistname);

	  //combine bins of original SPE histogram
	  for(int ib=1; ib<=hspe_temp->GetNbinsX(); ib++) {
	    double bin_center = hspe_temp->GetBinCenter(ib);
	    if(bin_center>hspe->GetXaxis()->GetXmax()) continue;
	    int newbin = hspe->FindBin(bin_center);
	    double new_content = hspe->GetBinContent(newbin) + hspe_temp->GetBinContent(ib);
	    double new_error = sqrt(pow(hspe->GetBinError(newbin),2)+pow(hspe_temp->GetBinError(ib),2));
	    hspe->SetBinContent(newbin,new_content);
	    hspe->SetBinError(newbin,new_error);
	  }
	  TH1F* hspe_unscaled = (TH1F*)hspe->Clone("hspe_unscaled");
	  //renormalize bins of new SPE histogram
	  for(int ib=1; ib<=hspe->GetNbinsX(); ib++) {
	    double new_content = hspe->GetBinContent(ib)/hspe->GetXaxis()->GetBinWidth(ib)*hspe_temp->GetXaxis()->GetBinWidth(1);
	    double new_error = hspe->GetBinError(ib)/hspe->GetXaxis()->GetBinWidth(ib)*hspe_temp->GetXaxis()->GetBinWidth(1);
	    hspe->SetBinContent(ib,new_content);
	    hspe->SetBinError(ib,new_error);
	  }
	  
	  if(hspe_temp->Integral()==0) continue;
	  else drawflag[iDepth][iPhi] = true;	  

	  Nev = hspe_temp->Integral()*hspe_temp->GetXaxis()->GetBinWidth(1); 
	  TF1 *fped = new TF1("fped","gaus",0, 80);
	  hped->Fit(fped,"NQR");
	  double pploc = fped->GetParameter(1), ppwidth = fped->GetParameter(2);
	  hspe->Fit(fped, "NQ", "", pploc - 3*ppwidth, pploc + ppwidth);  
	  
	  //estimate SPE peak location
	  int max_SPE_bin, maxbin, Nbins;
	  double max_SPE_height=0, minheight, max_SPE_location;
	  bool minflag = false;
	  maxbin=hspe->FindBin(fped->GetParameter(1)); //location of pedestal peak
	  minheight=hspe->GetBinContent(maxbin); //initialize minheight
	  Nbins = hspe->GetNbinsX();
	  for(int j=maxbin+1; j<Nbins-1; j++) { //start from pedestal peak and loop through bins
	    if(hspe->GetBinContent(j) > minheight && !minflag) minflag=true; //only look for SPE peak when minflag=true
	    if(hspe->GetBinContent(j) < minheight )  minheight = hspe->GetBinContent(j);
	    if(minflag && hspe->GetBinContent(j) > max_SPE_height){
	      max_SPE_bin = j;
	      max_SPE_location = hspe->GetBinCenter(max_SPE_bin);
	      max_SPE_height = hspe->GetBinContent(j);
	    }
	  } //start from pedestal peak and loop through bins
	  //find minimum bin between pedestal and SPE peaks
	  hspe->GetXaxis()->SetRange(maxbin,max_SPE_bin);
	  int minbin = hspe->GetMinimumBin(); 
	  double minbin_location = hspe->GetBinCenter(minbin);
	  hspe->GetXaxis()->SetRange(1,Nbins);	    
	  
	  TF1 *fit = new TF1("fit", FitFun, 0, 500, 5);
	    
	  double mu = - log(fped->Integral(0,100)/Nev);
	  if(mu<0) mu=0.01;
	  double gain_est = max_SPE_location-1.0*fped->GetParameter(1);
	  if(max_SPE_bin > (minbin+1)) fit->SetParameters(mu, 20, 1, gain_est, gain_est*0.5);
	  else fit->SetParameters(mu, 20, 1, 2.1*fped->GetParameter(2), 10); //case of no clear minimum; start looking for SPE peak at 2sigma away from pedestal peak
	  fit->SetParLimits(0, 0, 10);
	  fit->FixParameter(1, fped->GetParameter(1));
	  fit->FixParameter(2, fped->GetParameter(2));
	  fit->SetParLimits(3, fped->GetParameter(2)*2, 350);
	  fit->SetParLimits(4, fped->GetParameter(2)*1.01, 250);
	  

	  double maxfitrange = 500.;    
	  double minfitrange = 0.;
	  hspe->Fit(fit, "MNQL", "", minfitrange, maxfitrange);
	  maxfitrange = fped->GetParameter(1)+4*fit->GetParameter(3)+fit->GetParameter(4);
	  if(500<maxfitrange) maxfitrange = 500;
	  hspe->Fit(fit, "MNQL", "", minfitrange, maxfitrange);

	  //calculate NDOF of fit excluding bins with 0 entries
	  int myNDOF=-3; //three free parameters
	  for(int j=hspe->FindBin(minfitrange); j<=hspe->FindBin(maxfitrange); j++) { //loop through fitted spe bins
	    if(hspe->GetBinContent(j)) myNDOF++;
	  } //loop through fitted spe bins


	  //calculate means and integrals of the fit and data
	  double fint, fint_error, hint, favg, havg;
	  int temp_lowbin, temp_highbin;
	  temp_lowbin = hspe->FindBin(minfitrange);
	  temp_highbin = hspe->FindBin(maxfitrange);
	  hspe_unscaled->GetXaxis()->SetRangeUser(minfitrange, maxfitrange);
	  havg = hspe_unscaled->GetMean();
	  hint = hspe->Integral(temp_lowbin,temp_highbin,"width");
	  double min_frange = hspe->GetBinLowEdge(temp_lowbin);
	  favg = fit->Mean(min_frange, maxfitrange);
	  fint = fit->Integral(min_frange, maxfitrange);
	  //fint_error = fit->IntegralError(min_frange, maxfitrange);
	  
	  double PE5int = 0; //integral of events with >=5 PE
	  double PE5loc =  fped->GetParameter(1)+ 5*fit->GetParameter(3);
	  if(PE5loc>500) PE5int = 0;
	  else {
	    int PE5bin =  hspe_temp->FindBin(PE5loc);
	    temp_highbin = hspe_temp->FindBin(maxfitrange)-1;
	    PE5int =  hspe_temp->Integral(PE5bin,temp_highbin,"width");
	  }
	  int PE5flag = 0;
	  if(PE5int/hint>0.05) PE5flag = 1; //set flag if more than 5% of events in the fit correspond to >=5PE
	//=========================================    
	  //for(int i1=1;i1<hspe->GetNbinsX();i1++){
	    //constants_file1<<HV<<"\t"<<iDepth<<"\t"<<iEta<<"\t"<<iPhi<<"\t"<<2.6*hspe->GetBinCenter(i1)<<"\t"<<hspe->GetBinContent(i1)<<"\t"<<fit->Eval(hspe->GetBinCenter(i1))<<"\n";
          //}
        //=========================================    

	  //printf("%d\n",myNDOF);
	  //output calibrations constants
	  //constants_file<<endl<<"LED_amplitude HV Spigot Channel Ped_mean Ped_mean_err Ped_RMS  Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl;
	  constants_file<<LED_amp<<" "<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParError(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fped->GetParError(2)<<" "<<scale*fit->GetParameter(4)<<" "<<scale*fit->GetParError(4)<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<scale*fit->GetParError(3)*fC2electrons<<" "<<fit->GetChisquare()/myNDOF/*fit->GetNDF()*/<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<endl;
	    

	  /*
	  if(iDepth==2 && iPhi==53 && iEta==36){
	    cout<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<gain_est<<" "<<fit->GetParameter(3)<<endl;
	    cout<<LED_amp<<" "<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParError(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fped->GetParError(2)<<" "<<scale*fit->GetParameter(4)<<" "<<scale*fit->GetParError(4)<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<scale*fit->GetParError(3)*fC2electrons<<" "<<fit->GetChisquare()/myNDOF<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<endl;
	  }
	  */

	  Carray[iDepth][iPhi]->cd(iEta-MinEta+1);
	  gPad->SetBorderMode(0);
	  gPad->SetBorderSize(0);
	  gPad->SetRightMargin(0.01);
	  gPad->SetBottomMargin(0.1);
	  gPad->SetLogy(true);
	  hspe->GetXaxis()->SetRangeUser(0, 200 /*300*//*508*/);
	  hspe->SetLineColor(kBlue);
	  hspe->DrawClone("hist");
	  fit->SetLineWidth(2);
	  fit->Draw("same");

	}
    
	if(drawflag[iDepth][iPhi]) { //draw plots of fit if data for the HV is present
	  stringstream plot_name;
	  plot_name<<"Plots/SPEFits_Run_"<<run<<"_Depth"<<iDepth<<"_Phi"<<iPhi<<".pdf";
	  Carray[iDepth][iPhi]->SaveAs(plot_name.str().c_str());
	  plot_name.str( std::string() );
	}

      }
    }

    constants_file.close();
    //constants_file1.close();
}
Esempio n. 30
0
int compare(){
	
    gROOT->SetStyle("Plain");

    // For the canvas:
    gStyle->SetCanvasColor(0);

    // For the Pad:
    gStyle->SetPadColor(0);
    gStyle->SetPadTickX(1);
    gStyle->SetPadTickY(1);
    gStyle->SetPadBorderSize(2);

    // For the frame:
    gStyle->SetFrameBorderMode(0);


    // For the statistics box:
    gStyle->SetOptStat(0);

    // Margins:
    gStyle->SetPadBottomMargin(0.25);
    gStyle->SetPadTopMargin(0.15);
    gStyle->SetPadLeftMargin(0.15);
    gStyle->SetPadRightMargin(0.1);

    // For the Global title:
    gStyle->SetOptTitle(0);
    gStyle->SetTitleColor(1);
    gStyle->SetTitleFillColor(10);
    gStyle->SetTitleTextColor(1);
    gStyle->SetTitleFont(42);
    gStyle->SetTitleFontSize(0.05);
    gStyle->SetTitleBorderSize(0);

    // For the axis
    gStyle->SetNdivisions(510, "X");
    gStyle->SetNdivisions(510, "Y");
    gStyle->SetTickLength(0.03);

    // For the axis titles:
    gStyle->SetTitleOffset(1.4, "X");
    gStyle->SetTitleOffset(1.2, "Y");
    gStyle->SetTitleOffset(0.5, "Z");
    gStyle->SetTitleSize(0.061, "XYZ");
    gStyle->SetTitleFont(42, "XYZ");

    // For the axis labels:
    gStyle->SetLabelSize(0.04, "XYZ");
    gStyle->SetLabelOffset(0.01, "XYZ");
    gStyle->SetLabelFont(42, "XYZ");

    // For the legend
    gStyle->SetLegendBorderSize(0);

    gROOT->ForceStyle();

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

	TFile *f1 = new TFile("output_GetPrediction/prediction_histos_MyTest_data_METsoftSmeared_noAngSmear_N20_CR_v3.root", "READ", "", 0);
    TFile *f2 = new TFile("output_GetPrediction/bkg.root", "READ", "", 0);
	selection = (TH1F*) f1->FindObjectAny("VBF_MET_presel_4JV_dPhiSide_selection");
	prediction = (TH1F*) f1->FindObjectAny("VBF_MET_presel_4JV_dPhiSide_prediction_px");
	background2 = (TH1F*) f2->FindObjectAny("met_check_inVR_rebin");
	TH1F* background = new TH1F(*prediction);
	background->Reset();
	for (int i = 1; i <= background->GetXaxis()->GetNbins(); ++i) {
		float x = background->GetXaxis()->GetBinCenter(i);
		int j = background2->GetXaxis()->FindBin(x);
		float value = background2->GetBinContent(j);
		float error = background2->GetBinError(j);
		background->SetBinContent(i,value);
		background->SetBinError(i,error);
	}
	
	//double MinX = selection->GetXaxis()->GetBinLowEdge(1);
    //double MaxX = selection->GetXaxis()->GetBinUpEdge(selection->GetXaxis()->GetNbins());
	double MinX = 150;
    double MaxX = 500;
    double BinWidth = selection->GetXaxis()->GetBinWidth(selection->GetXaxis()->GetNbins());
    double MaxY = prediction->GetBinContent(prediction->GetMaximumBin());
    double MaxYsel = selection->GetBinContent(selection->GetMaximumBin());
    if (MaxY < MaxYsel) MaxY = MaxYsel;
    double YRangeMax = 2.*pow(10., int(log10(MaxY))+2);
    double MinY = prediction->GetBinContent(prediction->GetMinimumBin());
    double MinYsel = selection->GetBinContent(selection->GetMinimumBin());
    if (MinY > MinYsel) MinY = MinYsel;
    if (MinY < 0.001) MinY = 0.001;
    double YRangeMin = 0.5*pow(10., int(log10(MinY))-2);
    TString titlePrediction;
    TString titleSelection;
    TString titleBackground;
    TString RatioTitle;
    TString LumiTitle;
    TString Title;
    TString xTitle;
    TString yTitle;

	LumiTitle = "ATLAS internal, L = 36.1 fb^{  -1}, #sqrt{s} = 13 TeV";

    Title = "3 jets, 1.8<#Delta#phi(jj)<2.7, MET>150 GeV, M(jj)>0.6 TeV, p_{T}^{3rd}<50 GeV";
    xTitle = "#slash{E}_{T} (GeV)";
    yTitle = "Events";

    titlePrediction = "Data-driven Pred.";
    titleSelection = "Data";
    titleBackground = "non-QCD background";

    RatioTitle = "(Pred-Data)/Data";

    static Int_t c_LightBrown = TColor::GetColor( "#D9D9CC" );
    static Int_t c_LightGray  = TColor::GetColor( "#DDDDDD" );

    selection->SetAxisRange(MinX, MaxX, "X");
    selection->GetYaxis()->SetRangeUser(YRangeMin, YRangeMax);
    selection->SetMarkerStyle(20);
    selection->SetMarkerSize(0.9);
    selection->SetMarkerColor(kBlack);
    selection->SetXTitle(xTitle);
    selection->SetYTitle(yTitle);

    prediction->SetAxisRange(MinX, MaxX, "X");
    prediction->GetYaxis()->SetRangeUser(YRangeMin, YRangeMax);
    prediction->SetFillColor(c_LightGray);
    prediction->SetTitle("");
    prediction->SetXTitle(xTitle);
    prediction->SetYTitle(yTitle);

    background->SetAxisRange(MinX, MaxX, "X");
    background->GetYaxis()->SetRangeUser(YRangeMin, YRangeMax);
    background->SetTitle("");
    background->SetLineColor(kRed);
    background->SetLineWidth(2);
    background->SetXTitle(xTitle);
    background->SetYTitle(yTitle);

    TCanvas *c = new TCanvas("ca", "Comparison and ratio of two histos", 700, 700);

    TPad *pad1 = new TPad("pad1a", "pad1a", 0, 0.35, 1, 1);
    pad1->SetLogy();
    pad1->SetBottomMargin(0);
    pad1->Draw();
    pad1->cd();

    prediction->DrawCopy("hist");
    selection->Draw("same");
    prediction->SetFillColor(kAzure-3);
    prediction->SetFillStyle(3354);
    prediction->DrawCopy("e2same");
    background->Scale(36.1/32.6);
    background->Draw("same");

    prediction->SetFillStyle(1001);
    //prediction->SetFillColor(c_LightBrown);
    prediction->SetFillColor(c_LightGray);

    //TLegend* leg1 = new TLegend(0.48, 0.63, 0.95, 0.83);
    TLegend* leg1 = new TLegend(0.44, 0.63, 0.91, 0.83);
    leg1->SetFillStyle(0);
    leg1->SetLineStyle(1);
    leg1->SetTextFont(42);
    //leg1->SetTextSize(0.04);
    leg1->SetTextSize(0.045);
    leg1->AddEntry(prediction, titlePrediction, "lf");
    leg1->AddEntry(selection, titleSelection, "lep");
    leg1->AddEntry(background, titleBackground, "l");
    leg1->Draw("same");

    TPaveText* pt = new TPaveText(0.11, 0.98, 0.95, 0.86, "NDC");
    pt->SetBorderSize(0);
    pt->SetFillStyle(0);
    pt->SetTextAlign(12);
    pt->SetTextSize(0.045);
    pt->AddText(Title);
    pt->AddText(LumiTitle);
    pt->Draw();

    c->cd();
    TPad *pad2 = new TPad("pad2a", "pad2a", 0, 0, 1, 0.35);
    pad2->SetTopMargin(0);
    pad2->Draw();
    pad2->cd();
    TH1F* r = new TH1F(*prediction);
    r->SetTitle("");
    r->SetLabelSize(0.08, "XYZ");
    r->SetLabelOffset(0.01, "XYZ");
    // r->SetTitleSize(0.09, "XYZ");
    r->SetTitleSize(0.125, "XYZ");
    r->SetTitleOffset(0.95, "X");
    r->SetTitleOffset(0.53, "Y");
    // r->SetTitleOffset(0.65, "Y");
    r->SetTickLength(0.05);
    r->SetYTitle(RatioTitle);
    r->SetStats(0);
    r->SetMarkerStyle(20);
    r->SetMarkerSize(0.9);
    r->SetMarkerColor(kBlack);
    r->Reset();
    r->Add(prediction, 1);
    r->Add(background, 1);
    r->Add(selection, -1);
    r->Divide(selection);
    r->SetMaximum(2.2);
    r->SetMinimum(-2.2);
    r->Draw("ep");
    TLine l;
    l.DrawLine(MinX, 0., MaxX+BinWidth, 0.);
    c->cd();
    
    c->SaveAs("compare.pdf");
	
	return 0;
}