Exemple #1
0
TH2F *prof2d(TTree *tree, TString var1Name, TString var2Name, TString nllName, TString binning="(40,0,0.05,40,0,0.2)", bool delta=false){

  var1Name.ReplaceAll("-","_");
  var2Name.ReplaceAll("-","_");
  //  tree->Print();
  TString histName="h";
  std::cout << var1Name << "\t" << var2Name << "\t" << histName << std::endl;
  tree->Draw(var1Name+":"+var2Name+">>"+histName+binning);
  TH2F *hEntries = (TH2F*)gROOT->FindObject(histName);
  if(hEntries==NULL) return NULL;
  //std::cerr << "e qui ci sono?" << std::endl;
  tree->Draw(var1Name+":"+var2Name+">>shervin"+binning,nllName);

  TH2F *h = (TH2F*)gROOT->FindObject("shervin");
  if(h==NULL) return NULL;
  h->Divide(hEntries);


  //std::cerr << "io sono qui" << std::endl;    
  delete hEntries;
  Double_t min=1e20, max=0;

  if(delta){
    for(Int_t iBinX=1; iBinX <= h->GetNbinsX(); iBinX++){
      for(Int_t iBinY=1; iBinY <= h->GetNbinsY(); iBinY++){
	Double_t binContent=h->GetBinContent(iBinX, iBinY);
	if(min>binContent && binContent!=0) min=binContent;
	if(max<binContent) max=binContent;
      }
    }
    std::cout << "min=" << min << "\tmax=" << max<<std::endl;    
    for(Int_t iBinX=1; iBinX <= h->GetNbinsX(); iBinX++){
      for(Int_t iBinY=1; iBinY <= h->GetNbinsY(); iBinY++){
	Double_t binContent=h->GetBinContent(iBinX, iBinY);
	//std::cout << binContent << std::endl;
	if(binContent!=0) binContent-=min;
	else binContent=-1;
	h->SetBinContent(iBinX,iBinY,binContent);
      }
    }
  }
  h->GetZaxis()->SetRangeUser(0,500);
  //std::cerr << "io sono qui 3" << std::endl;    
  return h;
//   Double_t variables[2];
//   Double_t nll;
//   tree->SetBranchAddress(var1Name, &(variables[0]));
//   tree->SetBranchAddress(var2Name, &(variables[1]));
//   tree->SetBranchAddress(nllName, &(nll));

  
//   Long64_t nEntries=tree->GetEntries();
//   for(Long64_t jentry=0; jentry<nEntries; jentry++){
    
}
TH2F SantanderMatching(TH2F const& h4f, TH2F const& h5f, TH2F const* mass) {
  TH2F res = h4f;
  for (int x = 1; x <= h4f.GetNbinsX(); ++x) {
    for (int y = 1; y <= h4f.GetNbinsY(); ++y) {
      double mh =
          mass ? mass->GetBinContent(x, y) : h4f.GetXaxis()->GetBinCenter(x);
      double t = log(mh / 4.75) - 2.;
      double fourflav = h4f.GetBinContent(x, y);
      double fiveflav = h5f.GetBinContent(x, y);
      double sigma = (1. / (1. + t)) * (fourflav + t * fiveflav);
      res.SetBinContent(x, y, sigma);
    }
  }
  return res;
}
Exemple #3
0
void makeTable(TString rootfilename, 
	       TString histname, char* tablefilename)
{

  TFile myhistos(rootfilename); 
  TH2F* h = (TH2F*) myhistos.Get(histname);
  int nX = h->GetNbinsX();
  int nY = h->GetNbinsY();


  FILE *file = fopen(tablefilename,"w+");


  for(int i=1; i<=nX; ++i) {
  
    Double_t pT0 = h->GetXaxis()->GetBinLowEdge(i);
    Double_t pT1 = h->GetXaxis()->GetBinLowEdge(i+1);

    for(int j=1; j<=nY; ++j) {
      Double_t x = h->GetBinContent(i,j);
      Double_t dx = 8.0 * h->GetBinError(i,j);
      if( dx > 1.0 ) dx = 1.0;
      Double_t eta0 = h->GetYaxis()->GetBinLowEdge(j);
      Double_t eta1 = h->GetYaxis()->GetBinLowEdge(j+1);

      fprintf( file ,"%4.1f  %4.1f   %+6.4f   %+6.4f  %6.4f   %6.4f \n", 
	       pT0, pT1, eta0, eta1, x, dx);
    }
  }

  fclose(file);
}
Exemple #4
0
/*=========================================================*/
void writemat4(Char_t *filename)
{
  Int_t ix,iy,nx,ny,zi;
  TH2F *hist;
  Char_t str[16];
  //Short_t zmat[NCHX][NCHY];
  Int_t zmat[NCHX][NCHY];

  hist=(TH2F*)f1->Get(filename);
  FILE *zout;

  if(hist!=NULL){
    for(iy=1; iy<=NCHY; iy++)
      for(ix=1; ix<=NCHX; ix++)
        zmat[ix-1][iy-1]=(Int_t)hist->GetBinContent(ix,iy);

    sprintf(str, "%s.spn", filename);
    zout = fopen(str,"wb+");
    for(zi=0;zi<NCHX;zi++)
      fwrite(zmat[zi],4,NCHY,zout);
    fclose(zout);
  } else
    printf("spectrum %s not found\n", filename);
  return;
}
Exemple #5
0
//2d reweighting of rho and its sigma
void reweight_rhosigma(TH1F* weight_rho, TH1F* weight_rhoo,TH2F*weight_rhon,TH2F*weight_rho2o,TH2F* weight_rhonr, TH2F* weight_rho2,TH2F*weight_sigman,TH2F*weight_sigma2o,TH2F* weight_sigmanr, TH2F* weight_sigma2,RooDataSet **dset, RooDataSet *dsetdestination, bool deleteold){
  if (!(*dset)) return;
//  TH2F *hnum = new TH2F("hnum","hnum",n_rhobins_forreweighting,rhobins_forreweighting,n_sigmabins_forreweighting,sigmabins_forreweighting);
//  TH2F *hden = new TH2F("hden","hden",n_rhobins_forreweighting,rhobins_forreweighting,n_sigmabins_forreweighting,sigmabins_forreweighting);
  TH2F *hnum = new TH2F("hnum","hnum",100,0,100,20,0,20);
  TH2F *hden = new TH2F("hden","hden",100,0,100,20,0,20);
  hnum->Sumw2();
  hden->Sumw2();
  for (int i=0; i<(*dset)->numEntries(); i++){
    hden->Fill(fabs((*dset)->get(i)->getRealValue("roorho")),fabs((*dset)->get(i)->getRealValue("roosigma")),(*dset)->store()->weight(i));
  }
  for (int i=0; i<dsetdestination->numEntries(); i++){
    hnum->Fill(fabs(dsetdestination->get(i)->getRealValue("roorho")),fabs(dsetdestination->get(i)->getRealValue("roosigma")),dsetdestination->store()->weight(i));
  }

  hnum->Scale(1.0/hnum->Integral());
  hden->Scale(1.0/hden->Integral());
//data/MC
  hnum->Divide(hden);
  TH2F *h = hnum;

  RooDataSet *newdset = new RooDataSet(**dset,Form("%s_rhosigmarew",(*dset)->GetName()));
  newdset->reset();
  for (int i=0; i<(*dset)->numEntries(); i++){
    RooArgSet args = *((*dset)->get(i));
    float oldw = (*dset)->store()->weight(i);
    float rho = args.getRealValue("roorho");
    float sigma = args.getRealValue("roosigma");
    float neww = oldw*h->GetBinContent(h->FindBin(rho,sigma));
	if(debug){
		weight_rho->Fill(neww);
		weight_rhoo->Fill(oldw);
		weight_rho2o->Fill(h->GetXaxis()->FindBin(rho),oldw);	
		weight_rhon->Fill(h->GetXaxis()->FindBin(rho),neww);	
		if(oldw!=0)weight_rhonr->Fill(h->GetXaxis()->FindBin(rho),oldw/neww);
		else {weight_rhonr->Fill(-10,1);}//cout << "dipho weight old 0" << endl;}
		if(oldw!=0)weight_rho2->Fill(rho,oldw/neww);
		weight_sigma2o->Fill(h->GetYaxis()->FindBin(sigma),oldw);	
		weight_sigman->Fill(h->GetYaxis()->FindBin(sigma),neww);	
		if(oldw!=0)weight_sigmanr->Fill(h->GetYaxis()->FindBin(sigma),oldw/neww);
		else {weight_sigmanr->Fill(-10,1);}//cout << "dipho weight old 0" << endl;}
		if(oldw!=0)weight_sigma2->Fill(sigma,oldw/neww);
	}
		newdset->add(args,neww);
	  }
	  newdset->SetName((*dset)->GetName());
	  newdset->SetTitle((*dset)->GetTitle());
	  delete hnum; delete hden;
	  RooDataSet *old_dset = *dset;
	  *dset=newdset;
	  std::cout << "RhoSigma2D rew: norm from " << old_dset->sumEntries() << " to " << newdset->sumEntries() << std::endl;
	  if (deleteold) delete old_dset;
	};
TH2F* XsecThisHistogram(TH2F *hold, TH1D *hxsec){
  TString name = hold->GetName() + (TString)"Xsec";
  TH2F *hnew = (TH2F*)hold->Clone(name);
  for(int x = 1; x<=hnew->GetNbinsX(); ++x){
    for(int y = 1; y<=hnew->GetNbinsY(); ++y){
      float val = hnew->GetBinContent(x,y);
      float mstop = hnew->GetXaxis()->GetBinLowEdge(x);
      //cout << "check " << "bin " << x << " gets me mstop " << mstop << endl;
      float xsec = hxsec->GetBinContent(hxsec->FindBin(mstop));
      hnew->SetBinContent(x,y,val*xsec);
    }
  }
  return hnew;
}
Double_t histFunction2D::evaluate(Double_t *x, Double_t *par) {
     
  Double_t xx = x[0];
  int binY=GetBinNumber(xx,lowEdgeY,highEdgeY,nbinY);
  
  Double_t total=0;
  for (int j=0;j<nbinX;j++) {  
     total+=fabs(par[j])*hist->GetBinContent(j+1,binY); 
  }
  
  // add a constant term 
  total+=par[(int)nbinX];
  return total;
}
TH2F* PassThisHistogram(TH2F *hold){
  TString name = hold->GetName() + (TString)"Pass";
  TH2F *hnew = (TH2F*)hold->Clone(name);
  for(int x = 1; x<=hnew->GetNbinsX(); ++x){
    for(int y = 1; y<=hnew->GetNbinsY(); ++y){
      float val = hnew->GetBinContent(x,y);
      float pass = 0;
      if(val>1) pass = 0.001;
      else if(val>0) pass = 1;
      hnew->SetBinContent(x,y,pass);
    }
  }
  return hnew;
}
Exemple #9
0
void shakeErrors(TString inFileName, TString histName){
  TFile inFile(inFileName);
  TH2F* h = (TH2F*)gROOT->FindObject(histName);
  if(!h){
    std::cout<<"Could not access histogram!"<<std::endl;
    return;
  }

  TFile lowFile(TString("low_")+inFileName,"recreate");
  TH2F* hLow = (TH2F*)h->Clone(histName);
  for(int i=0; i<h->GetSize(); i++){
    hLow->SetBinContent( i, h->GetBinContent(i)-h->GetBinError(i) );
  }
  hLow->Write();
  lowFile.Close();

  TFile hiFile(TString("hi_")+inFileName,"recreate");
  TH2F* hHi = (TH2F*)h->Clone(histName);
  for(int i=0; i<h->GetSize(); i++){
    hHi->SetBinContent( i, h->GetBinContent(i)+h->GetBinError(i) );
  }
  hHi->Write();
  hiFile.Close();
}
double
SimpleTrackCorrector::getWeight(double pT, double eta, double occ ) 
{

  double eff = reff2D->GetBinContent(
                  reff2D->GetXaxis()->FindBin(eta),
                  reff2D->GetYaxis()->FindBin(pT) );
  if( eff >= 0.9999 || eff <= 0.0001) eff = 1;

  double sec = rsec2D->GetBinContent(
              rsec2D->GetXaxis()->FindBin(eta),
              rsec2D->GetYaxis()->FindBin(pT));
  if( sec >= 0.9999 || sec <= 0.0001) sec = 0;
  double fak = rfak2D->GetBinContent(
              rfak2D->GetXaxis()->FindBin(eta),
              rfak2D->GetYaxis()->FindBin(pT));
  if( fak >= 0.9999 || fak <= 0.0001) fak = 0;
  double mul = rmul2D->GetBinContent(
              rmul2D->GetXaxis()->FindBin(eta),
              rmul2D->GetYaxis()->FindBin(pT));
  if( mul >= 0.9999 || mul <= 0.0001) mul = 0;

  return (1. - fak ) * ( 1. - sec ) / eff  / (1. + mul );
}
void psf(){


  gROOT->Reset();

  int nbinx = 512;
  int nbiny = 512;

  TFile *fout = new TFile("psf.root","recreate");
  TH2F *image = new TH2F("psf","psf",nbinx,-250.0,250.0,nbiny,-250.0,250.0);
  //  FILE *fo;
  //  if((fo=fopen("psf.dat","wb"))==NULL){
  //    std::cout << "error " << std::endl;
  //  }

  //  float xcenter = 0.05;
  //  float ycenter =0.05;

  float xcenter = 0.0;
  float ycenter =0.0;
  float sum = 0.0;
  for(int i=1;i<=nbinx;i++){
    for(int j=1;j<=nbiny;j++){
      float a = image->GetXaxis()->GetBinCenter(i);
      float b = image->GetYaxis()->GetBinCenter(j);
      float r =  TMath::Sqrt(TMath::Power(xcenter-a,2)+TMath::Power(ycenter-b,2));

      float value =  TMath::Gaus(r,0,8.0,kTRUE);
      //      value = value * (1.+0.01*gRandom->Rndm());
      sum = sum + value;
      image->SetBinContent(i,j,value);

    }
  }

  for(int i=1;i<=nbinx;i++){
    for(int j=1;j<=nbiny;j++){
      image->SetBinContent(i,j,image->GetBinContent(i,j)/sum);
    }
  }

  image->Write();
  fout->Close();
  //  fclose(fo);

}
float getSMSxs(float mlsp,float mglu) {
  TH2F *refh  =  new TH2F("ReferenceHisto","ReferenceHisto",(int)((mgluend-mglustart)/mglustep+1),mglustart-0.5*mglustep,mgluend+0.5*mglustep,int((mLSPend-mLSPstart)/mLSPstep+1),mLSPstart-0.5*mLSPstep,mLSPend+0.5*mLSPstep);
  refh->SetBinContent(refh->FindBin(mglu,mlsp),1);//only compute the cross section for our point
  TFile *xsecfile = new TFile((PlottingSetup::cbafbasedir+"/"+PlottingSetup::SMSReferenceXSFile).c_str());
  if(xsecfile->IsZombie()) {
      write_error(__FUNCTION__,"Cross section file is invalid!!!!");
      return -1;
  }
  xsecfile->Close();
  delete xsecfile;
  TH2F *xsec = adjust_histo(get_XS(PlottingSetup::cbafbasedir+"/"+PlottingSetup::SMSReferenceXSFile,"gluino",refh),refh);
  int GlobalBin = xsec->FindBin(mglu,mlsp);
  float refxs=xsec->GetBinContent(GlobalBin);
  delete refh;
  delete xsec;
  return refxs;
}
void smoothHorizontal(TH2F* h, float threshold) {
    TH2F* hist = (TH2F*)(h->Clone((std::string(h->GetName())+"_hori").c_str()));
    for (int i = 1; i <= hist->GetNbinsX(); ++i) {
        for(int j = 1; j <= hist->GetNbinsY(); ++j) {
            float val = hist->GetBinContent(i,j);
            float count = 0.;
            if (val < threshold) { 
                if (i-1 != 0)                                                  val += hist->GetBinContent(i-1,j  );
                else                                                           count -= 1.0;;
                if (i+1 != hist->GetNbinsX()+1)                                val += hist->GetBinContent(i+1,j  );
                else                                                           count -= 1.0;
                val /= (3.0+count);
                h->SetBinContent(i,j,val);
            }
        }
    }
}
Exemple #14
0
void test_combine()
{
   gROOT->ProcessLine(".L combine.C");

   int nbins = 2;
   double x[2] = {1,2};
   // double y[4] = {10.5,9.5,13.5,14.};
   double y[2] = {2066,2087};
   double ex[2] = {0.1,0.1};
   double ey[2] = {23,30};
   double ey2[2] = {sqrt(23*23+97*97+54*54),sqrt(30*30+104*104+54*54)};
   // double ey[4] = {sqrt(0.0145),sqrt(0.016),sqrt(0.017),sqrt(0.026)};
   // double ey[4] = {1,3,3,3};
   TGraphErrors *gr12 = new TGraphErrors(nbins,x,y,ex,ey);

   TH2F *hcov12 = new TH2F("hcov12","hcov12",nbins,0,nbins,nbins,0,nbins);
   for (int i=0; i<nbins; i++)
      for (int j=0; j<nbins; j++)
         hcov12->SetBinContent(i+1,j+1,i==j ? ey2[i]*ey2[i] : 0);
   // hcov12->SetBinContent(1,3,0.45);
   // hcov12->SetBinContent(3,1,0.45);
   hcov12->SetBinContent(1,2,sqrt((97*97+54*54)*(104*104+54*54)));
   hcov12->SetBinContent(2,1,sqrt((97*97+54*54)*(104*104+54*54)));
   // hcov12->SetBinContent(3,4,8.96);
   // hcov12->SetBinContent(4,3,8.96);
   for (int i=0; i<nbins; i++)
   {
      for (int j=0; j<nbins; j++)
         cout << hcov12->GetBinContent(i+1,j+1) << " ";
      cout << endl;
   }

   TGraphErrors *grcombo = new TGraphErrors(nbins/2);
   TH2F *hcovcombo = new TH2F("hcovcombo","hcovcombo",nbins/2,0,nbins/2,nbins/2,0,nbins/2);
   combine_blue(gr12,hcov12,grcombo,hcovcombo);
   for (int i=0; i<nbins/2; i++)
   {
      for (int j=0; j<nbins/2; j++)
         cout << hcovcombo->GetBinContent(i+1,j+1) << " ";
      cout << endl;
   }
}
TH2F* InterpolateThisHistogram(TH2F *hold/*, TH2F* hnew*/){
  float binsize = hold->GetXaxis()->GetBinWidth(1)/2.;
  TString name = hold->GetName();
  name.ReplaceAll("Org","");
  TGraph2D *g = new TGraph2D(hold);
  //cout << g->GetXmax() << " " << g->GetXmin() << " " << g->GetYmax() << " " << g->GetYmin() << " " << binsize << endl;
  g->SetNpx(int(g->GetXmax()-g->GetXmin())/binsize);
  g->SetNpy(int(g->GetYmax()-g->GetYmin())/binsize);
  TH2F *hnew = (TH2F*)g->GetHistogram();
  //TH2F *htemp = (TH2F*)hnew->Clone(name);
  //name.ReplaceAll("YXZ","");
  TH2F *h = new TH2F(name.Data(),hold->GetTitle(),hnew->GetNbinsX(),g->GetXmin()-binsize,g->GetXmax()-binsize,hnew->GetNbinsY(),g->GetYmin()-binsize,g->GetYmax()-binsize);
  for(unsigned int x = 1; x<=hnew->GetNbinsX(); ++x){
    for(unsigned int y = 1; y<=hnew->GetNbinsY(); ++y){
      h->SetBinContent(x,y,hnew->GetBinContent(x,y));
    }
  }
  delete g;
  return h;
}
void smooth(TH2F* h, int binmin, int binmax, float arraysize) {
    TH2F* hist = (TH2F*)(h->Clone((std::string(h->GetName())+"_temp").c_str()));
    for (int i = binmin; i <= hist->GetNbinsX() && i <= binmax; ++i) {
        for(int j = 1; j <= hist->GetNbinsY(); ++j) {
            float count = 0.;
            float val = 0;
            for (int m = i-arraysize; m <= i+arraysize; m++) {
                //for (int n = j-arraysize; n <= j+arraysize; n++) {
                //for (int n = j-1; n <= j+1; n++) {
                    int n = j;
                    if (m >= binmin && m <= hist->GetNbinsX() && m <= binmax && n > 0 && n <= hist->GetNbinsY()) {
                        count += 1.0;
                        val += hist->GetBinContent(m, n);
                    }
                //}
            }
            val /= count;
            if (val > 0.0) h->SetBinContent(i,j,val);
            else h->SetBinContent(i,j,0.00001);
        }
    }
}
Exemple #17
0
//Usage:
//.x Draw_EtaRing_EE.C+
void Draw_EtaRing_EE( bool EB=false, bool EE=true, bool noplot = true ){

  cout<<"Let's start with Parsing!"<<endl;
  //PARSING
  ifstream file;
  file.open("../common/Endc_x_y_ring.txt", ifstream::in);
  vector<iXiYtoRing> VectRing;

  while ( !file.eof() ) {
    string Line;
    getline( file, Line);
    string value;
    stringstream MyLine(Line);

    char * cstr, *p;
    cstr = new char [Line.size()+1];
    strcpy (cstr, Line.c_str());
    p=strtok (cstr," ");
    int i(0);
    while (p!=NULL){
	if(i==0)  GiveRing.iX = atoi(p);
	if(i==1)  GiveRing.iY = atoi(p);
	if(i==2)  GiveRing.sign = atoi(p);
	if(i==3){ 
	  GiveRing.Ring = atoi(p);
	  VectRing.push_back(GiveRing);
	}
	p=strtok(NULL," ");
	i++;
    }
    delete[] cstr;  
  }
  if(!noplot){
    //EE
    cout<<"Loop on the EE histo."<<endl;
    TH2F* h_EE = new TH2F("h_EE","EE etaring", 100, 0., 100., 100, 0., 100. );

    for(int x=0; x<100;x++){
	for(int y=0; y<100;y++){
	  int ring = GetRing( x, y, VectRing);
	  if( ring==-1 )     h_EE->SetBinContent(x,y,0);
	  else if(ring%2==0) h_EE->SetBinContent(x,y,100);
	  else               h_EE->SetBinContent(x,y,50);
	}
    }
    TCanvas* myc1 = new TCanvas("myc1", "CMS", 600, 600);
    h_EE->Draw("colz");
    myc1->SaveAs("EE_EtaRing.png");
    cout<<"Drawing..."<<endl;
    cout<<"Finally: THE END!"<<endl;
  }
  //Check on the Histo
  TFile* f_Ec  = TFile::Open( "../AfterCalibTools/WorkOnIC/prova_7Iter/ECAL/IC_SetAverageTo1_EtaRing.root" );
  if(!f_Ec) cout<<"Problem with File: EcalPro"<<endl;
  TFile* f_Ca  = TFile::Open( "../AfterCalibTools/WorkOnIC/prova_7Iter/CAL/IC_SetAverageTo1_EtaRing.root" );
  if(!f_Ca) cout<<"Problem with File: EtaRing"<<endl;
  TFile* f_Div = TFile::Open( "../AfterCalibTools/WorkOnIC/prova_7Iter/2012C_ECALCC_Vs_CalCC_7Iter_EtaRing1.root" );
  if(!f_Div) cout<<"Problem with File: division"<<endl;

  if(EB){
  cout<<"Now EB: "<<endl;
    TCanvas* myc1 = new TCanvas("myc1", "CMS", 600, 600);
    gStyle->SetOptStat(0);
    for(int nh=0; nh<=3; nh++){
	TProfile *pr_h = new TProfile("pr_h","profile", 171, 0., 171., 0.9, 1.1); pr_h->GetXaxis()->SetTitle("iEtaBin");
	TH2F* h;
	if(nh==0) h = (TH2F*) f_Ec->Get( "calibMap_EB" );
	if(nh==1) h = (TH2F*) f_Ca->Get( "calibMap_EB" );
	if(nh==2) h = (TH2F*) f_Div->Get( "Ratio_EBMap" );
	if(nh==3){h = (TH2F*) f_Ec->Get( "calibMap_EB" ); TH2F* h_2 = (TH2F*) f_Ca->Get( "calibMap_EB" ); h->Divide(h_2); }
	float Corr[171]={0.};
	float Norm[360]={0.};
	for(int iEta=0+1; iEta<171+1; iEta++){
	  for(int iPhi=0+1; iPhi<360+1; iPhi++){
	    if( iEta!=86 && h->GetBinContent(nh!=2?iEta:iPhi,nh!=2?iPhi:iEta)!=0 && h->GetBinContent(nh!=2?iEta:iPhi,nh!=2?iPhi:iEta)!=1 ){
		Corr[iEta-1] += h->GetBinContent(nh!=2?iEta:iPhi,nh!=2?iPhi:iEta);
		Norm[iEta-1] += 1.;
		if(nh==2) pr_h->Fill( float(iEta) , h->GetBinContent(nh!=2?iEta:iPhi,nh!=2?iPhi:iEta) );
		//cout<<iPhi<<" "<<iEta<<" : "<<h->GetBinContent(nh!=2?iEta:iPhi,nh!=2?iPhi:iEta)<<"  "<<Corr[iEta-1]<<"  "<<Norm[iEta-1]<<endl;
	    }
	  }
	}
	if(nh==2){ pr_h->Draw("colz"); myc1->SaveAs("Profile.png");}
	if(nh==0) cout<<"Now ECALpro"<<endl;
	if(nh==1) cout<<"Now Caltech"<<endl;
	if(nh==2) cout<<"Now Comparison"<<endl;
	if(nh==3) cout<<"Now the division"<<endl;
	for(int i=0; i<171;i++){
	  if(Norm[i]>0) cout<<Corr[i]/Norm[i]<<endl;
	}

    }
  }
  if(EE){
    cout<<"Now EE: "<<endl;
    for(int nh=0; nh<=3; nh++){
	TH2F* h;
	if(nh==0) h = (TH2F*) f_Ec->Get( "calibMap_EEp" ); 
	if(nh==1) h = (TH2F*) f_Ca->Get( "calibMap_EEp" ); 
	if(nh==2) h = (TH2F*) f_Div->Get( "Ratio_EEpMap" ); 
	if(nh==3){h = (TH2F*) f_Ec->Get( "calibMap_EEp" ); TH2F* h_2 = (TH2F*) f_Ca->Get( "calibMap_EEp" ); h->Divide(h_2); }
	float Corr[40]={0.};
	float Norm[40]={0.};
	for(int x=0; x<100;x++){
	  for(int y=0; y<100;y++){
	    int ring = GetRing( x, y, VectRing);
	    if( h->GetBinContent(x+1,y+1)!=0 && h->GetBinContent(x+1,y+1)!=1 ){
		//cout<<x<<" "<<y<<" "<<ring<<" "<<h->GetBinContent(x+1,y+1)<<endl;
		Corr[ring] += h->GetBinContent(x+1,y+1);
		Norm[ring] += 1.;
	    }
	  }
	}
	if(nh==0) cout<<"Now ECALpro"<<endl;
	if(nh==1) cout<<"Now Caltech"<<endl;
	if(nh==2) cout<<"Now Comparison"<<endl;
	if(nh==3) cout<<"Now the division"<<endl;
	for(int i=0; i<40;i++){
	  if(Norm[i]>0) cout<<Corr[i]/Norm[i]<<endl;
	}
    }
  }
}
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();
}
Exemple #19
0
void drawICmap(const string& wwwPath = "",
	       const string& eosPath = "", 
	       const string& dirName = "", 
	       const string& iterNumber = "", 
	       const string& tagName = "") {

  gStyle->SetPalette(1, 0);  // raibow palette                                                
  gStyle->SetNumberContours(50); // default is 20 

  string filename = "root://eoscms//eos/cms" + eosPath + dirName + "/" + iterNumber + "/" + tagName + "calibMap.root";

  TFile* f = TFile::Open(filename.c_str(),"READ");
  if (!f || !f->IsOpen()) {
    cout<<"*******************************"<<endl;
    cout<<"Error opening file \""<<filename<<"\".\nApplication will be terminated."<<endl;
    cout<<"*******************************"<<endl;
    exit(EXIT_FAILURE);
  }

  TH2F *mapEB = (TH2F*) f->Get("calibMap_EB");
  TH2F *h = NULL;
  h = (TH2F*) f->Get("calibMap_EEp");
  TH2F *mapEEp = (TH2F*) h->Clone();
  h = (TH2F*) f->Get("calibMap_EEm");
  TH2F *mapEEm = (TH2F*) h->Clone();

  if (!mapEB || !mapEEp || !mapEEm) {
    cout << "Error: could not get one or more histograms. End of programme" << endl;
    exit(EXIT_FAILURE);
  }

  TH2F *mapEB_new = new TH2F("mapEB_new","EB calib coefficients", 360, 0.5, 360.5, 171,-85.5,85.5 );

  // profile along ieta. ieta goea from -85 to 85, exluding 0, for a total of 170 non empty bins (they are 171 including ieta = 0 which is actually empty)
  // in the profile, ieta = 30 is the bin with x from 29.5 to 30.5
  // simila logic for profile along iphi
  TProfile * EB_ieta_profile = new TProfile("EB_ieta_profile","EB calib coefficients - i#eta profile",171,-85.5,85.5);
  TProfile * EB_iphi_profile = new TProfile("EB_iphi_profile","EB calib coefficients - i#phi profile",360,0.5,360.5);


  Int_t nbinsX = mapEB->GetNbinsX(); // ieta
  Int_t nbinsY = mapEB->GetNbinsY(); // iphi

  for (Int_t i = 1; i <= nbinsX; i++) {

      for (Int_t j = 1; j <= nbinsY; j++) {
	
	mapEB_new->Fill(j,(i-86.0),mapEB->GetBinContent(i,j));
	EB_ieta_profile->Fill((i-86.0),mapEB->GetBinContent(i,j));
	EB_iphi_profile->Fill(j,mapEB->GetBinContent(i,j));

      }

  }

  string wwwAllPath = wwwPath + dirName + "/" + iterNumber + "/2DMaps/";
  string name = "";
  TPaletteAxis *palette = NULL;

  //EB
  TCanvas *cEB = new TCanvas("cEB","IC map EB");
  mapEB_new->Draw("COLZ");
  mapEB_new->GetXaxis()->SetTitle("i #phi");
  mapEB_new->GetXaxis()->SetTitleSize(0.06);
  mapEB_new->GetXaxis()->SetTitleOffset(0.7);
  mapEB_new->GetYaxis()->SetTitle("i #eta");
  mapEB_new->GetYaxis()->SetTitleSize(0.06);
  mapEB_new->GetYaxis()->SetTitleOffset(0.8);
  mapEB_new->GetZaxis()->SetRangeUser(0.9,1.1);
  mapEB_new->SetStats(0);
  gPad->Update();
  palette = (TPaletteAxis*)mapEB_new->GetListOfFunctions()->FindObject("palette");
  // the following lines move the palette. Choose the values you need for the position.                                                                              
  palette->SetX1NDC(0.91);
  palette->SetX2NDC(0.94);
  gPad->Modified();
  gPad->Update();
  // end of palette fixes                                                                                                                                             
  name = wwwAllPath + "Barrel/IC_calibMapEB";
  cEB->SaveAs((name + ".pdf").c_str());
  cEB->SaveAs((name + ".png").c_str());

  TCanvas *cEB_ietaProfile = new TCanvas("cEB_ietaProfile","IC map EB - i#eta profile");
  EB_ieta_profile->Draw("HIST");
  EB_ieta_profile->GetXaxis()->SetTitle("i #eta");
  EB_ieta_profile->GetXaxis()->SetTitleSize(0.06);
  EB_ieta_profile->GetXaxis()->SetTitleOffset(0.7);
  EB_ieta_profile->GetYaxis()->SetTitle("IC");
  EB_ieta_profile->GetYaxis()->SetTitleSize(0.06);
  EB_ieta_profile->GetYaxis()->SetTitleOffset(0.8);
  // Double_t maxY = EB_ieta_profile->GetBinContent(EB_ieta_profile->GetMaximumBin());
  // Double_t scale_factor = 1.1;
  // Double_t minY = 999.9; // minimum would be 0, corresponding to ieta = 0; look for minimum excluding ieta = 0
  // for (Int_t ieta = -85; ieta<= 85; ieta++) {
  //   if (ieta == 0) continue;
  //   minY = (EB_ieta_profile->GetBinContent(ieta+86) < minY) ? EB_ieta_profile->GetBinContent(ieta+86) : minY;
  // }
  // Double_t offset = scale_factor * (maxY -minY); 
  // EB_ieta_profile->GetYaxis()->SetRangeUser(minY - offset, maxY + offset);
  EB_ieta_profile->GetYaxis()->SetRangeUser(0.89,0.99);
  EB_ieta_profile->SetStats(0);
  gPad->Update();
  name = wwwAllPath + "Barrel/IC_calibMapEB_ietaProfile";
  cEB_ietaProfile->SaveAs((name + ".pdf").c_str());
  cEB_ietaProfile->SaveAs((name + ".png").c_str());


  TCanvas *cEB_iphiProfile = new TCanvas("cEB_iphiProfile","IC map EB - i#phi profile");
  EB_iphi_profile->Draw("HIST");
  EB_iphi_profile->GetXaxis()->SetTitle("i #phi");
  EB_iphi_profile->GetXaxis()->SetTitleSize(0.06);
  EB_iphi_profile->GetXaxis()->SetTitleOffset(0.7);
  EB_iphi_profile->GetYaxis()->SetTitle("IC");
  EB_iphi_profile->GetYaxis()->SetTitleSize(0.06);
  EB_iphi_profile->GetYaxis()->SetTitleOffset(0.8);
  // maxY = EB_iphi_profile->GetBinContent(EB_iphi_profile->GetMaximumBin());
  // minY = EB_iphi_profile->GetBinContent(EB_iphi_profile->GetMinimumBin()); 
  // offset = scale_factor * (maxY -minY); 
  // EB_iphi_profile->GetYaxis()->SetRangeUser(minY - offset, maxY + offset);
  EB_iphi_profile->GetYaxis()->SetRangeUser(0.91,0.97);
  EB_iphi_profile->SetStats(0);
  gPad->Update();
  name = wwwAllPath + "Barrel/IC_calibMapEB_iphiProfile";
  cEB_iphiProfile->SaveAs((name + ".pdf").c_str());
  cEB_iphiProfile->SaveAs((name + ".png").c_str());


  //EE+
  TCanvas *cEEp = new TCanvas("cEEp","IC map EE+");
  mapEEp->Draw("COLZ");
  mapEEp->GetXaxis()->SetTitle("iX");
  mapEEp->GetXaxis()->SetTitleSize(0.06);
  mapEEp->GetXaxis()->SetTitleOffset(0.7);
  mapEEp->GetYaxis()->SetTitle("iY");
  mapEEp->GetYaxis()->SetTitleSize(0.06);
  mapEEp->GetYaxis()->SetTitleOffset(0.8);
  mapEEp->GetZaxis()->SetRangeUser(0.75,1.25);
  mapEEp->SetStats(0);
  gPad->Update();
  palette = (TPaletteAxis*)mapEEp->GetListOfFunctions()->FindObject("palette");
  // the following lines move the palette. Choose the values you need for the position.                    
  palette->SetX1NDC(0.91);
  palette->SetX2NDC(0.94);
  gPad->Modified();
  gPad->Update();
  // end of palette fixes                                    
  name = wwwAllPath + "Endcap/EEp/IC_calibMapEEp";
  cEEp->SaveAs((name + ".pdf").c_str());
  cEEp->SaveAs((name + ".png").c_str());

  //EE-
  TCanvas *cEEm = new TCanvas("cEEm","IC map EE-");
  mapEEm->Draw("COLZ");
  mapEEm->GetXaxis()->SetTitle("iX");
  mapEEm->GetXaxis()->SetTitleSize(0.06);
  mapEEm->GetXaxis()->SetTitleOffset(0.7);
  mapEEm->GetYaxis()->SetTitle("iY");
  mapEEm->GetYaxis()->SetTitleSize(0.06);
  mapEEm->GetYaxis()->SetTitleOffset(0.8);
  mapEEm->GetZaxis()->SetRangeUser(0.75,1.25);
  mapEEm->SetStats(0);
  gPad->Update();
  palette = (TPaletteAxis*)mapEEm->GetListOfFunctions()->FindObject("palette");
  // the following lines move the palette. Choose the values you need for the position.                    
  palette->SetX1NDC(0.91);
  palette->SetX2NDC(0.94);
  gPad->Modified();
  gPad->Update();
  // end of palette fixes                                    
  name = wwwAllPath + "Endcap/EEm/IC_calibMapEEm";
  cEEm->SaveAs((name + ".pdf").c_str());
  cEEm->SaveAs((name + ".png").c_str());

  


}
Exemple #20
0
void IsovsPt(){


  TFile *f1 = new TFile("../../CutTMVATrees_Barrel.root");
 
  float ppt,peta,Sie_ie,iso_P,iso_C,iso_N,to_e,weight;
  int nvtx;

  gStyle->SetOptStat(0);



  //Signal Tree
  t_S->SetBranchAddress("Sieie",&Sie_ie);
  t_S->SetBranchAddress("isoP",&iso_P);
  t_S->SetBranchAddress("isoC",&iso_C);
  t_S->SetBranchAddress("isoN",&iso_N);
  t_S->SetBranchAddress("ToE",&to_e);
  t_S->SetBranchAddress("weighT",&weight);
  t_S->SetBranchAddress("Nvtx",&nvtx);
  t_S->SetBranchAddress("Peta",&peta);
  t_S->SetBranchAddress("Ppt",&ppt);

  //Background Tree
  t_B->SetBranchAddress("Sieie",&Sie_ie);
  t_B->SetBranchAddress("isoP",&iso_P);
  t_B->SetBranchAddress("isoC",&iso_C);
  t_B->SetBranchAddress("isoN",&iso_N);
  t_B->SetBranchAddress("ToE",&to_e);
  t_B->SetBranchAddress("weighT",&weight);
  t_B->SetBranchAddress("Nvtx",&nvtx);
  t_B->SetBranchAddress("Peta",&peta);
  t_B->SetBranchAddress("Ppt",&ppt);



  TH2F *isoCptS = new TH2F("isoCptS","Iso Charge vs Pt",100,0,200,3000,0,30);
  TH2F *isoNptS = new TH2F("isoNptS","Iso Neutral vs Pt",100,0,200,3000,0,30);
  TH2F *isoPptS = new TH2F("isoPptS","Iso Photon vs Pt",100,0,200,3000,0,30);




  for(int i  = 0; i < t_S->GetEntries();i++){

    t_S->GetEntry(i);

 
    isoCptS->Fill(ppt,iso_C);
 
    if(to_e < 0.05){
      
      isoNptS->Fill(ppt,iso_N);

    }

    isoPptS->Fill(ppt,iso_P);
  }




  // Now that we have the Iso vs pt histograms lets see the efficiency in pt bins

  double BinCch [100][3000] = {0};
  double BinCph [100][3000] = {0};
  double BinCh  [100][3000] = {0};
 
  double ptX[100] ={0};

  

  cout<<"here"<<endl;

  for(int j  = 0 ; j < 100 ; j++){
  
    double ptx = 200.0*j/100 + 1.0; 
    ptX[j] = ptx; 

    for(int i  = 0; i < 3000 ; i++){
      double isocx = 30.0*i/3000 + 0.005; 
      double isopx = 30.0*i/3000 + 0.005; 
      double isonx = 30.0*i/3000 + 0.005; 
      
      int bin =  isoCptS->FindBin(ptx,isocx);    
      BinCch[j][i] = isoCptS->GetBinContent(bin);

      bin =  isoPptS->FindBin(ptx,isopx);    
      BinCph[j][i] = isoPptS->GetBinContent(bin);

      bin =  isoNptS->FindBin(ptx,isonx);    
      BinCh[j][i] = isoNptS->GetBinContent(bin);

    
    
    }

  } 




  double ch_95[100] = {0};
  double ch_90[100] = {0}; 
  double ch_80[100] = {0}; 
  double ch_70[100] = {0}; 
  
  

  double ph_95[100] = {0};
  double ph_90[100] = {0}; 
  double ph_80[100] = {0}; 
  double ph_70[100] = {0}; 
  
  double ne_95[100] = {0};
  double ne_90[100] = {0}; 
  double ne_80[100] = {0}; 
  double ne_70[100] = {0}; 
  
  double ch_95e[100] = {0};
  double ch_90e[100] = {0}; 
  double ch_80e[100] = {0}; 
  double ch_70e[100] = {0}; 
  
  double ph_95e[100] = {0}; 
  double ph_90e[100] = {0}; 
  double ph_80e[100] = {0}; 
  double ph_70e[100] = {0}; 
  
  double ne_95e[100] = {0};
  double ne_90e[100] = {0}; 
  double ne_80e[100] = {0}; 
  double ne_70e[100] = {0}; 



  
  for(int j = 0 ; j  < 100; j ++){
    
    double totC = 0;
    double totN = 0;
    double totP = 0;
    
    for(int i = 0; i < 3000; i++) totC = totC + BinCch[j][i];
    for(int i = 0; i < 3000; i++) totN = totN + BinCh[j][i]; 
    for(int i = 0; i < 3000; i++) totP = totP + BinCph[j][i]; 

    double entrC = 0;
    double entrP = 0;
    double entrN = 0;
    
    int passc95 = 0; 
    int passc9 = 0;
    int passc8 = 0;
    int passc7 = 0;

    int passp95 = 0; 
    int passp9 = 0;
    int passp8 = 0;
    int passp7 = 0;

    int passn95 = 0; 
    int passn9 = 0;
    int passn8 = 0;
    int passn7 = 0; 

    for(int i  = 0; i < 3000 ; i++){
      
      entrC = entrC + BinCch[j][i];
      entrP = entrP + BinCph[j][i];
      entrN = entrN + BinCh[j][i];

      //------- photon
      if(passp95 == 0 && entrP*1.0/totP  > 0.95){
	
	double num = sqrt(entrP);
	double den = sqrt(totP);

	ph_95e[j] = 0.95*sqrt(pow(num/totP,2) + pow(den/entrP,2) );



	ph_95[j] = i*0.01;
	passp95= 1; 
      }

      


      if(passp9 == 0 && entrP*1.0/totP  > 0.90){
	
	double num = sqrt(entrP);
	double den = sqrt(totP);

	ph_90e[j] = 0.9*sqrt(pow(num/totP,2) + pow(den/entrP,2) );



	ph_90[j] = i*0.01;
	passp9 = 1; 
      }
      if(passp8 == 0 && entrP*1.0/totP  > 0.80){

	
	double num = sqrt(entrP);
	double den = sqrt(totP);

	ph_80e[j] = 0.8*sqrt(pow(num/totP,2) + pow(den/entrP,2) );

	
	ph_80[j] = i*0.01;
	passp8 = 1; 
      }
      if(passp7 == 0 && entrP*1.0/totP  > 0.70){

	
	double num = sqrt(entrP);
	double den = sqrt(totP);

	ph_70e[j] = 0.7*sqrt(pow(num/totP,2) + pow(den/entrP,2) );



	ph_70[j] = i*0.01;
	passp7 = 1; 
      }


      //--------- charge
      if(passc95 == 0 && entrC*1.0/totC  > 0.95){
	
	double num = sqrt(entrC);
	double den = sqrt(totC);

	ch_95e[j] = 0.95*sqrt(pow(num/totC,2) + pow(den/entrC,2) );



	ch_95[j] = i*0.01;
	passc95= 1; 
      }
      

      if(passc9 == 0 && entrC*1.0/totC  > 0.90){

	double num = sqrt(entrC);
	double den = sqrt(totC);

	ch_90e[j] = 0.9*sqrt(pow(num/totC,2) + pow(den/entrC,2) );

	ch_90[j] = i*0.01;
	passc9 = 1; 
      }
      if(passc8 == 0 && entrC*1.0/totC  > 0.80){

	double num = sqrt(entrC);
	double den = sqrt(totC);

	ch_80e[j] = 0.8*sqrt(pow(num/totC,2) + pow(den/entrC,2) );

	ch_80[j] = i*0.01;
	passc8 = 1; 
      }
      if(passc7 == 0 && entrC*1.0/totC  > 0.70){
	
	double num = sqrt(entrC);
	double den = sqrt(totC);

	ch_70e[j] = 0.7*sqrt(pow(num/totC,2) + pow(den/entrC,2) );

	ch_70[j] = i*0.01;
	passc7 = 1; 
      }

      
      //--------- neutral
      if(passn95 == 0 && entrN*1.0/totN  > 0.95){
	
	double num = sqrt(entrN);
	double den = sqrt(totN);

	ne_95e[j] = 0.95*sqrt(pow(num/totN,2) + pow(den/entrN,2) );



	ne_95[j] = i*0.01;
	passn95= 1; 
      }
    






      if(passn9 == 0 && entrN*1.0/totN  > 0.90){

	
	double num = sqrt(entrN);
	double den = sqrt(totN);

	ne_90e[j] = 0.9*sqrt(pow(num/totN,2) + pow(den/entrN,2) );



	ne_90[j] = i*0.01;
	passn9 = 1; 
      }
      if(passn8 == 0 && entrN*1.0/totN  > 0.80){

	
	double num = sqrt(entrN);
	double den = sqrt(totN);

	ne_80e[j] = 0.8*sqrt(pow(num/totN,2) + pow(den/entrN,2) );


	ne_80[j] = i*0.01; 
	passn8 = 1; 
      }
      if(passn7 == 0 && entrN*1.0/totN  > 0.70){

	
	double num = sqrt(entrN);
	double den = sqrt(totN);

	ne_70e[j] = 0.7*sqrt(pow(num/totN,2) + pow(den/entrN,2) );


	ne_70[j] = i*0.01;
	passn7 = 1; 
      }


    }
    
  }
  

  double ptXe[100] = {2};
  
  TGraph *p95 = new TGraphErrors(100,ptX,ph_95,ptXe,ph_95e);
  TGraph *p9 = new TGraphErrors(100,ptX,ph_90,ptXe,ph_90e);
  TGraph *p8 = new TGraphErrors(100,ptX,ph_80,ptXe,ph_80e);
  TGraph *p7 = new TGraphErrors(100,ptX,ph_70,ptXe,ph_70e);

  p95->SetMarkerColor(kMagenta);
  p9->SetMarkerColor(kRed);
  p8->SetMarkerColor(kOrange);
  p7->SetMarkerColor(kYellow);
 

  p95->SetMarkerSize(kMagenta);
  p9->SetMarkerSize(1);
  p8->SetMarkerSize(1);
  p7->SetMarkerSize(1);

  
  p95->SetLineColor(kMagenta);
  p9->SetLineColor(kRed);
  p8->SetLineColor(kOrange);
  p7->SetLineColor(kYellow);






  TGraph *n95 = new TGraphErrors(100,ptX,ne_95,ptXe,ne_95e);
  TGraph *n9 = new TGraphErrors(100,ptX,ne_90,ptXe,ne_90e);
  TGraph *n8 = new TGraphErrors(100,ptX,ne_80,ptXe,ne_80e);
  TGraph *n7 = new TGraphErrors(100,ptX,ne_70,ptXe,ne_70e);

  n95->SetMarkerColor(kMagenta);
  n9->SetMarkerColor(kRed);
  n8->SetMarkerColor(kOrange);
  n7->SetMarkerColor(kYellow);

  n95->SetMarkerSize(kMagenta);
  n9->SetMarkerSize(1);
  n8->SetMarkerSize(1);
  n7->SetMarkerSize(1);

  n95->SetLineColor(kMagenta);
  n9->SetLineColor(kRed);
  n8->SetLineColor(kOrange);
  n7->SetLineColor(kYellow);




  TGraph *c95 = new TGraphErrors(100,ptX,ch_95,ptXe,ch_95e);
  TGraph *c9 = new TGraphErrors(100,ptX,ch_90,ptXe,ch_90e);
  TGraph *c8 = new TGraphErrors(100,ptX,ch_80,ptXe,ch_80e);
  TGraph *c7 = new TGraphErrors(100,ptX,ch_70,ptXe,ch_70e);

  c95->SetMarkerColor(kMagenta); 
  c9->SetMarkerColor(kRed);
  c8->SetMarkerColor(kOrange);
  c7->SetMarkerColor(kYellow);


  c95->SetLineColor(kMagenta); 
  c9->SetLineColor(kRed);
  c8->SetLineColor(kOrange);
  c7->SetLineColor(kYellow);



  c95->SetMarkerSize(1);
  c9->SetMarkerSize(1);
  c8->SetMarkerSize(1);
  c7->SetMarkerSize(1);




  TMultiGraph *PhoIso = new TMultiGraph();
  TMultiGraph *ChgIso = new TMultiGraph();
  TMultiGraph *NeuIso = new TMultiGraph();


  PhoIso->Add(p95,"p");
  PhoIso->Add(p9,"p");
  PhoIso->Add(p7,"p");
  PhoIso->Add(p8,"p");


  ChgIso->Add(c95,"p");
  ChgIso->Add(c9,"p");
  ChgIso->Add(c7,"p");
  ChgIso->Add(c8,"p");

  NeuIso->Add(n95,"p");
  NeuIso->Add(n9,"p");
  NeuIso->Add(n7,"p");
  NeuIso->Add(n8,"p");

  



  TCanvas *c1 = new TCanvas("c1","Iso P vs Pt",1000,500);
  c1->Divide(2,1); 

  c1->cd(1);
  PhoIso->Draw("AP");
  PhoIso->GetXaxis()->SetTitle("Pt GeVc^{-1}");
  PhoIso->GetYaxis()->SetTitle("Isolation PF:gamma");
  

  
  c1->cd(2)->SetLogz();
  
  isoPptS->Draw("colz");  
  isoPptS->GetXaxis()->SetTitle("Pt GeVc^{-1}");
  isoPptS->GetYaxis()->SetTitle("Isolation PF:gamma");

  c1->SaveAs("PhotonIso_95.png");


  TCanvas *c2 = new TCanvas("c2","Iso C vs Pt",1000,500);
  c2->Divide(2,1);
  c2->cd(1);
  ChgIso->Draw("AP");
  ChgIso->GetXaxis()->SetTitle("Pt GeVc^{-1}");
  ChgIso->GetYaxis()->SetTitle("Isolation PF:ch hadrons");
  

  c2->cd(2)->SetLogz();
  
  isoCptS->Draw("colz");  
  isoCptS->GetXaxis()->SetTitle("Pt GeVc^{-1}");
  isoCptS->GetYaxis()->SetTitle("Isolation PF:ch hadrons");


  c2->SaveAs("ChargeIso_95.png");
  
  TCanvas *c3 = new TCanvas("c3","Iso N vs Pt",1000,500);
  c3->Divide(2,1);
  c3->cd(1);
  NeuIso->Draw("AP");
  NeuIso->GetXaxis()->SetTitle("Pt GeVc^{-1}");
  NeuIso->GetYaxis()->SetTitle("Isolation PF:h0");
  

  c3->cd(2)->SetLogz();
  
  isoNptS->Draw("colz");  
  isoNptS->GetXaxis()->SetTitle("Pt GeVc^{-1}");
  isoNptS->GetYaxis()->SetTitle("Isolation PF:h0");


  c3->SaveAs("NeutralIso_95_HoEcut.png");

  c1->Update();
  c2->Update();
  c3->Update();

}
Exemple #21
0
int looperCR2lep( analysis* myAnalysis, sample* mySample, int nEvents = -1, bool fast = true) {

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

	// Setup
	TChain *chain = mySample->GetChain();
	TString sampleName = mySample->GetLabel();
	const int nSigRegs = myAnalysis->GetSigRegionsAll().size();
	const int nVariations = mySample->IsData() ? 0 : myAnalysis->GetSystematics(false).size();
	bool isFastsim = mySample->IsSignal();
	cout << "\nSample: " << sampleName.Data() << " (CR2L";
	if(      myContext.GetJesDir() == contextVars::kUp )   cout << ", JES up";
	else if( myContext.GetJesDir() == contextVars::kDown ) cout << ", JES down";
	cout << ")" << endl;

	myContext.SetUseRl( true );

	/////////////////////////////////////////////////////////
	// Histograms
	TDirectory *rootdir = gDirectory->GetDirectory("Rint:");  // Use TDirectories to assist in memory management
	TDirectory *histdir = new TDirectory( "histdir", "histdir", "", rootdir );
	TDirectory *systdir = new TDirectory( "systdir", "systdir", "", rootdir );
	TDirectory *zerodir = new TDirectory( "zerodir", "zerodir", "", rootdir );

	TH1::SetDefaultSumw2();

	TH1D* h_bkgtype_sum[nSigRegs][nVariations+1];
	TH1D* h_evttype_sum[nSigRegs][nVariations+1];
	TH2D* h_sigyields[nSigRegs][nVariations+1];

	TH1D* h_bkgtype[nSigRegs][nVariations+1]; // per-file versions for zeroing
	TH1D* h_evttype[nSigRegs][nVariations+1];

	TH1D *h_mt[nSigRegs];
	TH1D *h_met[nSigRegs];
	TH1D *h_mt2w[nSigRegs];
	TH1D *h_chi2[nSigRegs];
	TH1D *h_htratio[nSigRegs];
	TH1D *h_mindphi[nSigRegs];
	TH1D *h_ptb1[nSigRegs];
	TH1D *h_drlb1[nSigRegs];
	TH1D *h_ptlep[nSigRegs];
	TH1D *h_metht[nSigRegs];
	TH1D *h_dphilw[nSigRegs];
	TH1D *h_njets[nSigRegs];
	TH1D *h_nbtags[nSigRegs];
	TH1D *h_ptj1[nSigRegs];
	TH1D *h_j1btag[nSigRegs];
	TH1D *h_modtop[nSigRegs];
	TH1D *h_dphilmet[nSigRegs];
	TH1D *h_mlb[nSigRegs];

	vector<TString> regNames = myAnalysis->GetSigRegionLabelsAll();
	vector<sigRegion*> sigRegions = myAnalysis->GetSigRegionsAll();
	vector<systematic*> variations = myAnalysis->GetSystematics(false);

	for( int i=0; i<nSigRegs; i++ ) {

		TString plotLabel = sampleName + "_" + regNames.at(i);
		systdir->cd();

		for( int j=1; j<=nVariations; j++ ) {
			TString varName = variations.at(j-1)->GetNameLong();
			h_bkgtype_sum[i][j] = new TH1D( "bkgtype_" + plotLabel + "_" + varName, "Yield by background type",  5, 0.5, 5.5);
			h_evttype_sum[i][j] = new TH1D( "evttype_" + regNames.at(i) + "_" + varName, "Yield by event type",  6, 0.5, 6.5);
			h_sigyields[i][j] = new TH2D( "sigyields_" + regNames.at(i) + "_" + varName, "Signal yields by mass point", 37,99,1024, 19,-1,474 );
		}

		histdir->cd();

		h_bkgtype_sum[i][0] = new TH1D( "bkgtype_" + plotLabel, "Yield by background type",  5, 0.5, 5.5);
		h_evttype_sum[i][0] = new TH1D( "evttype_" + regNames.at(i), "Yield by event type",  6, 0.5, 6.5);
		h_sigyields[i][0] = new TH2D( "sigyields_" + regNames.at(i), "Signal yields by mass point", 37,99,1024, 19,-1,474 );

		h_mt[i]       = new TH1D(  "mt_"      + plotLabel, "Transverse mass",          80, 0, 800);
		h_met[i]      = new TH1D(  "met_"     + plotLabel, "MET",                      40, 0, 1000);
		h_mt2w[i]     = new TH1D(  "mt2w_"    + plotLabel, "MT2W",                     50, 0, 500);
		h_chi2[i]     = new TH1D(  "chi2_"    + plotLabel, "Hadronic #chi^{2}",        50, 0, 15);
		h_htratio[i]  = new TH1D(  "htratio_" + plotLabel, "H_{T} ratio",              50, 0, 1);
		h_mindphi[i]  = new TH1D(  "mindphi_" + plotLabel, "min #Delta#phi(j12,MET)",  63, 0, 3.15);
		h_ptb1[i]     = new TH1D(  "ptb1_"    + plotLabel, "p_{T} (b1)",               50, 0, 500);
		h_drlb1[i]    = new TH1D(  "drlb1_"   + plotLabel, "#DeltaR (lep, b1)",        50, 0, 5);
		h_ptlep[i]    = new TH1D(  "ptlep_"   + plotLabel, "p_{T} (lep)",              50, 0, 500);
		h_metht[i]    = new TH1D(  "metht_"   + plotLabel, "MET/sqrt(HT)",             50, 0, 100);
		h_dphilw[i]   = new TH1D(  "dphilw_"  + plotLabel, "#Delta#phi (lep,W)",       63, 0, 3.15);
		h_njets[i]    = new TH1D(  "njets_"   + plotLabel, "Number of jets",           16, -0.5, 15.5);
		h_nbtags[i]   = new TH1D(  "nbtags_"  + plotLabel, "Number of b-tags",          7, -0.5, 6.5);
		h_ptj1[i]     = new TH1D(  "ptj1_"    + plotLabel, "Leading jet p_{T}",        40, 0, 1000);
		h_j1btag[i]   = new TH1D(  "j1btag_"  + plotLabel, "Is leading jet b-tagged?",  2, -0.5, 1.5);
		h_modtop[i]   = new TH1D(  "modtop_"  + plotLabel, "Modified topness",         30, -15., 15.);
		h_dphilmet[i] = new TH1D(  "dphilmet_"+ plotLabel, "#Delta#phi (lep1, MET)",   63, 0., 3.15);
		h_mlb[i]      = new TH1D(  "mlb_"     + plotLabel, "M_{lb}",                   50, 0., 500.);


		for( int j=0; j<=nVariations; j++ ) {

			TAxis* axis = h_bkgtype_sum[i][j]->GetXaxis();
			axis->SetBinLabel( 1, "2+lep" );
			axis->SetBinLabel( 2, "1lepW" );
			axis->SetBinLabel( 3, "1lepTop" );
			axis->SetBinLabel( 4, "ZtoNuNu" );
			axis->SetBinLabel( 5, "Other" );

			axis = h_evttype_sum[i][j]->GetXaxis();
			axis->SetBinLabel( 1, "Data" );
			axis->SetBinLabel( 2, "Signals" );
			axis->SetBinLabel( 3, "2+lep" );
			axis->SetBinLabel( 4, "1lepW" );
			axis->SetBinLabel( 5, "1lepTop" );
			axis->SetBinLabel( 6, "ZtoNuNu" );
		}

	}

	TH1D *h_yields_sum = new TH1D( Form("srYields_%s", sampleName.Data()), "Yield by signal region", nSigRegs, 0.5, float(nSigRegs)+0.5);
	for( int i=0; i<nSigRegs; i++ ) h_yields_sum->GetXaxis()->SetBinLabel( i+1, regNames.at(i) );

	// Set up copies of histograms, in order to zero out negative yields
	zerodir->cd();
	TH1D* h_yields = (TH1D*)h_yields_sum->Clone( "tmp_" + TString(h_yields_sum->GetName()) );

	for( int i=0; i<nSigRegs; i++ ) {
		for( int j=0; j<=nVariations; j++ ) {
			h_bkgtype[i][j] = (TH1D*)h_bkgtype_sum[i][j]->Clone( "tmp_" + TString(h_bkgtype_sum[i][j]->GetName()) );
			h_evttype[i][j] = (TH1D*)h_evttype_sum[i][j]->Clone( "tmp_" + TString(h_evttype_sum[i][j]->GetName()) );
		}
	}

	// Set up cutflow variables
	double yield_total = 0;
	double yield_unique = 0;
	double yield_filter = 0;
	double yield_vtx = 0;
	double yield_1goodlep = 0;
	double yield_lepSel = 0;
	double yield_2lepveto = 0;
	double yield_trkVeto = 0;
	double yield_2lepCR = 0;
	double yield_tauVeto = 0;
	double yield_njets = 0;
	double yield_1bjet = 0;
	double yield_METcut = 0;
	double yield_MTcut = 0;
	double yield_dPhi = 0;
	double yield_chi2 = 0;

	int yGen_total = 0;
	int yGen_unique = 0;
	int yGen_filter = 0;
	int yGen_vtx = 0;
	int yGen_1goodlep = 0;
	int yGen_lepSel = 0;
	int yGen_2lepveto = 0;
	int yGen_trkVeto = 0;
	int yGen_tauVeto = 0;
	int yGen_2lepCR = 0;
	int yGen_njets = 0;
	int yGen_1bjet = 0;
	int yGen_METcut = 0;
	int yGen_MTcut = 0;
	int yGen_dPhi = 0;
	int yGen_chi2 = 0;

	////////////////////////////////////////////////////////////////////
	// Set up data-specific filters

	if( mySample->IsData() ) {
		set_goodrun_file_json( "reference-files/Cert_271036-284044_13TeV_23Sep2016ReReco_Collisions16_JSON.txt" );
		duplicate_removal::clear_list();
	}


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

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

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

		// Get File Content
		TFile file( currentFile->GetTitle() );
		TString filename = file.GetName();
		TTree *tree = (TTree*)file.Get("t");
		if(fast) TTreeCache::SetLearnEntries(10);
		if(fast) tree->SetCacheSize(128*1024*1024);
		cms3.Init(tree);

		// Load event weight histograms
		TH2F* hNEvts = (TH2F*)file.Get("histNEvts");
		TH3D* hCounterSMS = (TH3D*)file.Get("h_counterSMS");
		TH1D* hCounter = (TH1D*)file.Get("h_counter");
		myHelper.Setup( isFastsim, hCounter, hNEvts, hCounterSMS );

		// Reset zeroing histograms
		for( int i=0; i<nSigRegs; i++ ) {
			for( int j=0; j<=nVariations; j++ ) {
				h_bkgtype[i][j]->Reset();
				h_evttype[i][j]->Reset();
			}
		}
		h_yields->Reset();

		// Loop over Events in current file
		if( nEventsTotal >= nEventsChain ) continue;
		unsigned int nEventsTree = tree->GetEntriesFast();
		for( unsigned int event = 0; event < nEventsTree; ++event) {

			// Get Event Content
			if( nEventsTotal >= nEventsChain ) continue;
			if(fast) tree->LoadTree(event);
			cms3.GetEntry(event);
			++nEventsTotal;

			// Progress
			CMS3::progress( nEventsTotal, nEventsChain );

			////////////////////////////////////////////////////////////////////////////////////////////////////////
			// Analysis Code
			// ---------------------------------------------------------------------------------------------------//


			///////////////////////////////////////////////////////////////
			// Special filters to more finely categorize background events
			if(      sampleName == "tt2l"  && gen_nfromtleps_() != 2 ) continue;  //Require 2 leps from top in "tt2l" events
			else if( sampleName == "tt1l"  && gen_nfromtleps_() != 1 ) continue;  //Require 1 lep from top in "tt1l" events

			// Stitch W+NJets samples together by removing the MET<200 events from the non-nupT samples
			if( sampleName.Contains("wjets") && filename.Contains("JetsToLNu_madgraph") && nupt()>=200. ) continue;

			//FastSim anomalous event filter
			if( isFastsim && !context::filt_fastsimjets() ) continue;

			if( !mySample->PassSelections() ) continue;


			/////////////////////////////////
			// Set event weight

			double evtWeight = 1.;

			// Data should have a weight of 1.0
			if( is_data() || mySample->IsData() ) evtWeight = 1.;
			else {

				// Weight background MC using scale1fb
				evtWeight = myAnalysis->GetLumi() * scale1fb();

				// Weight signal MC using xsec and nEvents
				if( mySample->IsSignal() ) {
					myHelper.PrepSignal();
					double nEvtsSample = hNEvts->GetBinContent( hNEvts->FindBin( mass_stop(), mass_lsp() ) );
					evtWeight = myAnalysis->GetLumi() * 1000. * xsec() / nEvtsSample;
				}

				// Apply scale factors to correct the shape of the MC
				evtWeight *= myHelper.TrigEff2l();
				evtWeight *= myHelper.LepSF();
				evtWeight *= myHelper.BtagSF();
				if(  isFastsim ) evtWeight *= myHelper.LepSFfastsim();
				if( !isFastsim ) evtWeight *= myHelper.PileupSF();
				if( mySample->GetLabel() == "tt2l" || filename.Contains("W_5f_powheg_pythia8") ) {
					evtWeight *= myHelper.MetResSF();
					// evtWeight *= myHelper.TopSystPtSF();
				}
				else if( mySample->GetLabel() == "tt1l" || mySample->GetLabel() == "wjets" ) evtWeight *= myHelper.MetResSF();
				if( mySample->GetLabel() == "tt2l" || mySample->GetLabel() == "tt1l" || mySample->IsSignal() ) evtWeight *= myHelper.ISRnJetsSF();

				// Correct event weight when samples are merged together
				if(      filename.Contains("ttbar_diLept_madgraph_pythia8_ext1_25ns") ) evtWeight *= 23198554./(23198554.+5689986.);
				else if( filename.Contains("ttbar_diLept_madgraph_pythia8_25ns") ) evtWeight *= 5689986./(23198554.+5689986.);
				else if( filename.Contains("t_tW_5f_powheg_pythia8_noHadDecays_25ns") ) evtWeight *= 4473156./(4473156.+3145334.);
				else if( filename.Contains("t_tW_5f_powheg_pythia8_noHadDecays_ext1_25ns") ) evtWeight *= 3145334./(4473156.+3145334.);
				else if( filename.Contains("t_tbarW_5f_powheg_pythia8_noHadDecays_25ns") ) evtWeight *= 5029568./(5029568.+3146940.);
				else if( filename.Contains("t_tbarW_5f_powheg_pythia8_noHadDecays_ext1_25ns") ) evtWeight *= 3146940./(5029568.+3146940.);
			}

			// Count the number of events processed
			yield_total += evtWeight;
			yGen_total++;

			// Remove duplicate events in data
			if( is_data() ) {
				duplicate_removal::DorkyEventIdentifier id( run(), evt(), ls() );
				if( is_duplicate(id) ) continue;
				yield_unique += evtWeight;
				yGen_unique++;
			}

			// MET filters, bad event filters, and triggers for data
			if( is_data() ) {
				if( !goodrun( run(), ls() ) ) continue;
				if( !filt_met() ) continue;
				if( !filt_badChargedCandidateFilter() ) continue;
				if( !filt_badMuonFilter() ) continue;
				if( !context::filt_jetWithBadMuon() ) continue;
				if( !filt_pfovercalomet() ) continue;
				if( !HLT_MET() && !HLT_MET110_MHT110() && !HLT_MET120_MHT120() ) {
					if( !(HLT_SingleEl() && (abs(lep1_pdgid())==11 || abs(lep2_pdgid())==11) ) &&
					    !(HLT_SingleMu() && (abs(lep1_pdgid())==13 || abs(lep2_pdgid())==13) ) ) continue;
				}
				yield_filter += evtWeight;
				yGen_filter++;
			}

			// First vertex must be good
			if( nvtxs() < 1 ) continue;
			yield_vtx += evtWeight;
			yGen_vtx++;

			// Must have at least 1 good lepton
			if( ngoodleps() < 1 ) continue;
			yield_1goodlep += evtWeight;
			yGen_1goodlep++;

			// Lep 1 must pass lepton selections
			// if( abs(lep1_pdgid())==11 ) {
			// 	if( lep1_p4().pt() < 20. ) continue;
			// 	if( fabs(lep1_p4().eta()) > 1.4442 ) continue;
			// 	if( !lep1_passMediumID() ) continue;
			// }
			// else if( abs(lep1_pdgid())==13 ) {
			// 	if( lep1_p4().pt() < 20. ) continue;
			// 	if( fabs(lep1_p4().eta()) > 2.4 ) continue;
			// 	if( !lep1_passTightID() ) continue;
			// }
			yield_lepSel += evtWeight;
			yGen_lepSel++;


			///////////////////
			// Make 2-lepton CR

			int countGoodLeps = 0;

			// Count the number of veto leptons
			if( nvetoleps() >= 2 && lep2_p4().pt() > 10. ) countGoodLeps += nvetoleps();

			if( countGoodLeps > 1 ) {
				yield_2lepveto += evtWeight;
				yGen_2lepveto++;
			}

			// If we fail the track veto, count another good lepton
			// if( !PassTrackVeto() ) {
			// 	countGoodLeps++;
			// 	yield_trkVeto += evtWeight;
			// 	yGen_trkVeto++;
			// }

			// If we fail the tau veto, count another good lepton
			// if( !PassTauVeto() ) {
			// 	countGoodLeps++;
			// 	yield_tauVeto += evtWeight;
			// 	yGen_tauVeto++;
			// }

			if( countGoodLeps < 2 ) continue;
			yield_2lepCR += evtWeight;
			yGen_2lepCR++;


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

			// N-jet requirement
			if( context::ngoodjets() < 2 ) continue;
			yield_njets += evtWeight;
			yGen_njets++;

			j1pt = context::ak4pfjets_p4().at(0).pt();

			// B-tag requirement
			if( context::ngoodbtags() < 1 ) continue;
			yield_1bjet += evtWeight;
			yGen_1bjet++;

			j1_isBtag = context::ak4pfjets_passMEDbtag().at(0);

			// Baseline MET cut (with 2nd lepton pT added to MET)
			if( context::Met() < 250. ) continue;
			yield_METcut += evtWeight;
			yGen_METcut++;

			// MT cut (with 2nd lepton pT added to MET)
			if( context::MT_met_lep() < 150. ) continue;
			yield_MTcut += evtWeight;
			yGen_MTcut++;

			// Min delta-phi between MET and j1/j2 (with 2nd lepton pT added to MET)
			if( context::Mindphi_met_j1_j2() < 0.5 ) continue;
			yield_dPhi += evtWeight;
			yGen_dPhi++;

			// Chi^2 cut
			// if( hadronic_top_chi2() >= 10. ) continue;
			yield_chi2 += evtWeight;
			yGen_chi2++;


			//////////////////////////////////////////////////////////
			// Classify event based on number of leptons / neutrinos
			// Order of evaluation matters, because some events fall into multiple categories

			int bkgType = -99;
			if( filename.Contains("ZZTo2L2Nu") && isZtoNuNu() ) bkgType = 1; // Force ZZto2L2Nu to be 2lep
			else if( isZtoNuNu() )     bkgType = 4;   // Z to nu nu
			else if( is2lep() )        bkgType = 1;   // 2 or more leptons
			else if( is1lepFromTop() ) bkgType = 3;   // 1 lepton from top quark
			else if( is1lepFromW() )   bkgType = 2;   // 1 lepton from a W not from top
			else                       bkgType = 5;   // Other

			int evtType = -99;
			if(      mySample->IsData()   ) evtType = 1;
			else if( mySample->IsSignal() ) evtType = 2;
			else                            evtType = 2+bkgType;

			// Quickly calculate some variables
			double metSqHT = context::Met() / sqrt( context::ak4_HT() );

			const TVector3 lepVec( lep1_p4().x(), lep1_p4().y(), lep1_p4().z() );
			const TVector3 metVec( context::Met()*cos(context::MetPhi()), context::Met()*sin(context::MetPhi()), 0 );
			const TVector3 wVec = lepVec + metVec;
			double dPhiLepW = fabs( lepVec.DeltaPhi(wVec) );

			double drLepLeadb = ROOT::Math::VectorUtil::DeltaR( lep1_p4(), context::ak4pfjets_leadMEDbjet_p4() );

			lep1pt = lep1_p4().Pt();

			myMlb = context::Mlb_closestb();

			///////////////////////////////////////////
			// Signal region cuts and histo filling

			// If the event passes the SR cuts, store which background type this event is, and fill histograms
			for( int i=0; i<nSigRegs; i++ ) {

				if( !sigRegions.at(i)->PassAllCuts() ) continue;

				// Make some corrections that depend on the signal region
				double fillWeight = evtWeight;
				bool is_corridor = sigRegions.at(i)->GetLabel().Contains("corr");
				myHelper.SetCorridor( is_corridor );
				if(      !is_data() &&  is_corridor ) fillWeight *= sfhelp::MetResCorrectionCorridor();
				else if( !is_data() && !is_corridor ) fillWeight *= sfhelp::BtagCorrectionTight();

				h_bkgtype[i][0]->Fill( bkgType,                            fillWeight );
				h_evttype[i][0]->Fill( evtType,                            fillWeight );
				if( mySample->IsSignal() ) h_sigyields[i][0]->Fill( mass_stop(), mass_lsp(), fillWeight );

				h_mt[i]->Fill(      context::MT_met_lep(),                 fillWeight );
				h_met[i]->Fill(     context::Met(),                        fillWeight );
				h_mt2w[i]->Fill(    context::MT2W(),                       fillWeight );
				h_chi2[i]->Fill(    hadronic_top_chi2(),                   fillWeight );
				h_htratio[i]->Fill( context::ak4_htratiom(),               fillWeight );
				h_mindphi[i]->Fill( context::Mindphi_met_j1_j2(),          fillWeight );
				h_ptb1[i]->Fill( context::ak4pfjets_leadMEDbjet_p4().pt(), fillWeight );
				h_drlb1[i]->Fill(   drLepLeadb,                            fillWeight );
				h_ptlep[i]->Fill(   lep1_p4().pt(),                        fillWeight );
				h_metht[i]->Fill(   metSqHT,                               fillWeight );
				h_dphilw[i]->Fill(  dPhiLepW,                              fillWeight );
				h_njets[i]->Fill(   context::ngoodjets(),                  fillWeight );
				h_nbtags[i]->Fill(  context::ngoodbtags(),                 fillWeight );
				h_ptj1[i]->Fill(    j1pt,                                  fillWeight );
				h_j1btag[i]->Fill(  j1_isBtag,                             fillWeight );
				h_modtop[i]->Fill(  context::TopnessMod(),                 fillWeight );
				h_dphilmet[i]->Fill( context::lep1_dphiMET(),              fillWeight );
				h_mlb[i]->Fill(     myMlb,                                 fillWeight );

				h_yields->Fill(     double(i+1),                           fillWeight );

				// Special systematic variation histograms
				for( int j=1; j<=nVariations; j++ ) {
					h_bkgtype[i][j]->Fill( bkgType,  fillWeight * variations.at(j-1)->GetWeight() );
					h_evttype[i][j]->Fill( evtType,  fillWeight * variations.at(j-1)->GetWeight() );
					if( mySample->IsSignal() ) h_sigyields[i][j]->Fill( mass_stop(), mass_lsp(), fillWeight * variations.at(j-1)->GetWeight() );
				}

			}

			// ---------------------------------------------------------------------------------------------------//
			////////////////////////////////////////////////////////////////////////////////////////////////////////
		} //End of loop over events in file

		// Clean Up
		delete tree;
		file.Close();

		// Zero negative values in each signal region
		for( int i=0; i<nSigRegs; i++ ) {
			for( int j=0; j<=nVariations; j++ ) {
				bool negsFound = false;

				// First zero any decay modes with negative yields
				for( int k=1; k<= h_bkgtype[i][j]->GetNbinsX(); k++ ) {
					if( h_bkgtype[i][j]->GetBinContent(k) < 0.0 ) {
						h_bkgtype[i][j]->SetBinContent(k, 0.);
						h_bkgtype[i][j]->SetBinError(k, 0.);
						negsFound = true;
					}
					if( h_evttype[i][j]->GetBinContent(k+2) < 0.0 ) {
						h_evttype[i][j]->SetBinContent(k+2, 0.);
						h_evttype[i][j]->SetBinError(k+2, 0.);
					}
				}
				// If any negative yields were found in any decay mode, recalculate the total yield
				if( j==0 && negsFound ) {
					double newYield, newErr;
					newYield = h_bkgtype[i][0]->IntegralAndError( 0, -1, newErr );
					h_yields->SetBinContent(i+1, newYield);
					h_yields->SetBinError(i+1, newErr);
				}
				// Add zeroed histograms to total histograms
				h_bkgtype_sum[i][j]->Add( h_bkgtype[i][j] );
				h_evttype_sum[i][j]->Add( h_evttype[i][j] );
			}
		}
		h_yields_sum->Add( h_yields );

	} // End loop over files in the chain

	cout << "Cutflow yields:                        (yield)  (gen evts)" << endl;

	printf("Total number of events:             %10.2f %9i\n",   yield_total    , yGen_total    );
	if( mySample->IsData() ) {
		printf("Events passing duplicate removal:   %10.2f %9i\n", yield_unique   , yGen_unique   );
		printf("Events passing filters and trigger: %10.2f %9i\n", yield_filter   , yGen_filter   );
	}
	printf("Events with 1st vertex good:        %10.2f %9i\n",   yield_vtx      , yGen_vtx      );
	printf("Events with at least 1 good lepton: %10.2f %9i\n",   yield_1goodlep , yGen_1goodlep );
	printf("Events passing lepton selection:    %10.2f %9i\n",   yield_lepSel   , yGen_lepSel   );

	printf("\nEvents passing 2-lep requirement:   %10.2f %9i\n", yield_2lepCR   , yGen_2lepCR   );
	printf("   Events with veto lepton:         %10.2f %9i\n",   yield_2lepveto , yGen_2lepveto );
	printf("   Events with isolated track:      %10.2f %9i\n",   yield_trkVeto  , yGen_trkVeto  );
	printf("   Events with identified tau:      %10.2f %9i\n\n", yield_tauVeto  , yGen_tauVeto  );

	printf("Events with at least 2 jets:        %10.2f %9i\n",   yield_njets    , yGen_njets    );
	printf("Events with at least 1 b-tag:       %10.2f %9i\n",   yield_1bjet    , yGen_1bjet    );
	printf("Events with MET > 250 GeV:          %10.2f %9i\n",   yield_METcut   , yGen_METcut   );
	printf("Events with MT > 150 GeV:           %10.2f %9i\n",   yield_MTcut    , yGen_MTcut    );
	printf("Events with min dPhi > 0.5:         %10.2f %9i\n",   yield_dPhi     , yGen_dPhi     );
	// printf("Events with chi2 < 10:              %10.2f %9i\n",   yield_chi2     , yGen_chi2     );
	printf("Yield after preselection:           %10.2f %9i\n",   yield_chi2     , yGen_chi2     );

	if ( nEventsChain != nEventsTotal ) {
		cout << Form( "ERROR: number of events from files (%d) is not equal to total number of events (%d)", nEventsChain, nEventsTotal ) << endl;
	}


	///////////////////////////////////////////////////////////////////////////////
	// Store histograms and clean them up
	TFile* plotfile = new TFile( myAnalysis->GetPlotFileName(), "READ");
	TFile* systfile = new TFile( myAnalysis->GetSystFileName(), "READ");
	TFile* sourcefile;

	// Certain histograms are cumulative across multiple samples. For those histograms, add what the
	// looper has just collected to the cumulative version stored in our output files
	for( int j=0; j<=nVariations; j++ ) {

		if( j==0 ) sourcefile = plotfile;
		else       sourcefile = systfile;

		for( int i=0; i<nSigRegs; i++ ) {

			// Build up cumulative histo of SUSY scan yields
			TH2D* hTemp2 = (TH2D*)sourcefile->Get( h_sigyields[i][j]->GetName() );
			if( hTemp2 != 0 ) h_sigyields[i][j]->Add( hTemp2 );

			// Build up cumulative histo of yields by signal/background type
			TH1D* hTemp = (TH1D*)sourcefile->Get( h_evttype_sum[i][j]->GetName() );
			if( hTemp != 0 ) h_evttype_sum[i][j]->Add( hTemp );
		}
	}
	delete plotfile;
	delete systfile;

	// Take all histograms in histdir and write them to plotfile
	plotfile = new TFile( myAnalysis->GetPlotFileName(), "UPDATE");
	plotfile->cd();
	histdir->GetList()->Write( "", TObject::kOverwrite );
	delete plotfile;

	// Take all histograms in systdir and write them to systfile
	systfile = new TFile( myAnalysis->GetSystFileName(), "UPDATE");
	systfile->cd();
	systdir->GetList()->Write( "", TObject::kOverwrite );
	delete systfile;

	// Cleanup
	zerodir->Close();
	histdir->Close();
	systdir->Close();

	// return
	bmark->Stop("benchmark");
	cout << endl;
	cout << nEventsTotal << " Events Processed" << endl;
	cout << "------------------------------" << endl;
	cout << "CPU  Time:	" << Form( "%.01f", bmark->GetCpuTime("benchmark")  ) << endl;
	cout << "Real Time:	" << Form( "%.01f", bmark->GetRealTime("benchmark") ) << endl;
	cout << endl;
	delete bmark;
	return 0;
}
void makeValidationPlots(TTree* tree, sel_t type,bool isMC) {

  SelectionStrings strings;

  TString tag="";

  TString lowString="",midString="",highString="";

  switch(type) {
  case kReal:
    tag = "_realselection";
    break;
  case kShift:
    tag = "_side";
    break;
  case kSingleIso:
    tag = "_singleIso";
    break;
  }
  if(isMC) {
    tag+="__DiPhotonJets";
  }
  Double_t Red[] = {0.00, 0.70, 0.90, 1.00, 1.00, 1.00, 1.00};
  Double_t Green[] ={0.00, 0.70, 0.90, 1.00, 0.90, 0.70, 0.00};
  Double_t Blue[] = {1.00, 1.00, 1.00, 1.00, 0.90, 0.70, 0.00};
  Double_t Length[] =  {0.00, 0.20, 0.35, 0.50, 0.65, 0.8, 1.00};

  TCanvas cv;

  std::vector<TH2F*> nSigs;
  std::vector<TH2F*> nSigs_gauss;

  cv.SetLogx();
  for(int iBox=0; iBox<SigRegionBinning::nBoxes; iBox++) {
    TString boxName = SigRegionBinning::getRegionName(static_cast<SigRegionBinning::BinningRegion>(iBox));
    switch(type) {
    case kReal:
      lowString = strings.baseSelection+" && mgg>103 && mgg<120";
      midString = strings.baseSelection+" && "+strings.mggSigRegion[iBox];
      highString = strings.baseSelection+" && mgg>131 && mgg<160";
      break;
    case kShift:
      lowString = strings.baseSelection+" && mgg>130 && mgg<140";
      midString = strings.baseSelection+" && mgg>140 && mgg<150";
      highString = strings.baseSelection+" && mgg>150 && mgg<160";
      break;
    case kSingleIso:
      lowString = TString("(pho1_pt>40 && pho2_pt>25 && abs(pho1_eta)<1.48 && abs(pho2_eta)<1.48 && (pho1_pass_iso || pho2_pass_iso) && !(pho1_pass_iso && pho2_pass_iso))")+" && mgg>103 && mgg<120";
      midString = TString("(pho1_pt>40 && pho2_pt>25 && abs(pho1_eta)<1.48 && abs(pho2_eta)<1.48 && (pho1_pass_iso || pho2_pass_iso) && !(pho1_pass_iso && pho2_pass_iso))")+" && "+strings.mggSigRegion[iBox];
      highString = TString("(pho1_pt>40 && pho2_pt>25 && abs(pho1_eta)<1.48 && abs(pho2_eta)<1.48 && (pho1_pass_iso || pho2_pass_iso) && !(pho1_pass_iso && pho2_pass_iso))")+" && mgg>131 && mgg<160";      
      break;
    }


    TH2F* low = SigRegionBinning::makeHistogram(static_cast<SigRegionBinning::BinningRegion>(iBox),"low");
    TH2F* mid = SigRegionBinning::makeHistogram(static_cast<SigRegionBinning::BinningRegion>(iBox),"mid");
    TH2F* high = SigRegionBinning::makeHistogram(static_cast<SigRegionBinning::BinningRegion>(iBox),"high");
  
    TH2F* nsig = SigRegionBinning::makeHistogram(static_cast<SigRegionBinning::BinningRegion>(iBox),"nsig_"+boxName);
    TH2F* nsig_gauss = SigRegionBinning::makeHistogram(static_cast<SigRegionBinning::BinningRegion>(iBox),"nsig_gauss_"+boxName);

    low->SetMinimum(0.1);
    mid->SetMinimum(0.1);
    high->SetMinimum(0.1);

    tree->Project("low","Rsq:MR",lowString+" && "+strings.boxDefs[iBox]);
    tree->Project("mid","Rsq:MR",midString+" && "+strings.boxDefs[iBox]);
    tree->Project("high","Rsq:MR",highString+" && "+strings.boxDefs[iBox]);

    //SigRegionBinning::formatSigRegionPlot(low);
    //SigRegionBinning::formatSigRegionPlot(mid);
    //SigRegionBinning::formatSigRegionPlot(high);

    //get the difference in the prediction
    TH2F* low_norm = (TH2F*)low->Clone("low_norm");
    TH2F* high_norm = (TH2F*)high->Clone("high_norm");

    low_norm->Scale(1./low_norm->Integral());
    high_norm->Scale(1./high_norm->Integral());

    TH2F* pred_diff = (TH2F*)high_norm->Clone("pred_diff");
    pred_diff->Add(low_norm,-1);

    TH2F* norm_av = (TH2F*)low_norm->Clone("norm_av");
    norm_av->Add(high_norm);
    norm_av->Scale(0.5);

    TH2F* pred_per_diff = (TH2F*)pred_diff->Clone("pred_per_diff");
    pred_per_diff->Divide(norm_av);
    cv.SetLogx(1);
    cv.SetLogy(0);
    pred_per_diff->Draw("COLZ TEXT");
    cv.SaveAs("RsqMR_high_minus_low_div_av_"+boxName+tag+".png");
    cv.SetLogx(1);
    cv.SetLogy(0);

    TH1D* low_1D = SigRegionBinning::make1DProj(low);
    TH1D* high_1D = SigRegionBinning::make1DProj(high);
    
    pred_per_diff->SetYTitle("high - low / (high+low/2)");
    TH1D* pred_per_diff_1D = SigRegionBinning::make1DProj(pred_per_diff);
    cv.SetLogx(0);
    cv.SetLogy(0);
    pred_per_diff_1D->Draw();
    cv.SaveAs("RsqMR_1D_high_minus_low_div_av_"+boxName+tag+".png");
    cv.SetLogx(1);
    cv.SetLogy(0);
    
    TFile out("RsqMR_1D_high_minus_low_div_av_"+boxName+tag+".root","RECREATE");
    low->Write();
    high->Write();
    low_1D->Write();
    high_1D->Write();
    pred_per_diff_1D->Write();
    pred_per_diff->Write();
    out.Close();



    TH2F* sideband_tot = (TH2F*)low->Clone("sideband_tot");
    sideband_tot->Add(high);


    sideband_tot->Draw("COLZ TEXT");
    cv.SetLogz();
    cv.SaveAs("RsqMR_low_plus_high_"+boxName+tag+".png");
    cv.SetLogz(0);

    float sf = mid->Integral()/sideband_tot->Integral();
    std::cout << "sf: " << sf << std::endl;
    TH2F* sideband_pred = (TH2F*)sideband_tot->Clone("sideband_pred");

    sideband_pred->Scale(sf);

    sideband_pred->Draw("COLZ TEXT");
    cv.SetLogz();
    cv.SaveAs("RsqMR_sideband_pred_"+boxName+tag+".png");
    cv.SetLogz(0);

    mid->Draw("COLZ TEXT");
    cv.SetLogz();
    cv.SaveAs("RsqMR_mid_"+boxName+tag+".png");
    cv.SetLogz(0);

    TH1D* pred_1D = SigRegionBinning::make1DProj(sideband_pred,true,sf);
    TH1D* mid_1D  = SigRegionBinning::make1DProj(mid);
    cv.SetLogx(0);
    cv.SetLogy();
    mid_1D->SetMarkerStyle(20);
    mid_1D->SetMarkerColor(kBlack);
    mid_1D->SetMarkerSize(1.4);

    pred_1D->SetFillColor(kRed);
    pred_1D->SetFillStyle(3001);
    pred_1D->SetLineColor(kRed);
    pred_1D->SetLineWidth(2);
    pred_1D->SetMarkerSize(0);
    pred_1D->Draw("L E2");
    pred_1D->Draw("LSAME");
    mid_1D->Draw("PSAME");
    cv.SaveAs("RsqMR_1D_obs_sideband_pred_"+boxName+tag+".png");    
    cv.SetLogx(1);
    cv.SetLogy(0);


    TH2F* perdiff = (TH2F*)mid->Clone("perdiff");
    perdiff->Add(sideband_pred,-1);
    perdiff->Divide(perdiff);
    perdiff->Draw("COLZ TEXT");

    cv.SaveAs("RsqMR_percentDiff_"+boxName+tag+".png");
    

    for(int iXbin=1; iXbin<=sideband_pred->GetNbinsX(); iXbin++) {
      for(int iYbin=1; iYbin<=sideband_pred->GetNbinsY(); iYbin++) {
	float obs = mid->GetBinContent(iXbin,iYbin);
	float exp = sideband_pred->GetBinContent(iXbin,iYbin);
	float err = TMath::Sqrt(sideband_tot->GetBinContent(iXbin,iYbin))*sf;
	float ns = fabs(TMath::NormQuantile(SigRegionBinning::pValue(obs,exp,err/exp)/2));
	if(obs<exp) ns*=-1;

	nsig->SetBinContent(iXbin,iYbin,ns);
	std::cout << "\t" << iXbin << "  " << iYbin << "  " << nsig->GetBinContent(iXbin,iYbin) << std::endl;

	float gauss_err = TMath::Sqrt(TMath::Power(err,2)+exp);
	if(gauss_err==0) gauss_err=1;
	nsig_gauss->SetBinContent(iXbin,iYbin,(obs-exp)/gauss_err);

      }
    }
    
    SigRegionBinning::formatSigRegionPlot(nsig); 
    SigRegionBinning::formatSigRegionPlot(nsig_gauss); 
    //cv.SetLogx();

    nSigs.push_back(nsig);
    nSigs_gauss.push_back(nsig_gauss);
    

    delete low;
    delete mid;
    delete high;
    delete sideband_tot;
    delete sideband_pred;

  }

  for(int iBox=0; iBox<SigRegionBinning::nBoxes; iBox++) {
    TString boxName = SigRegionBinning::getRegionName(static_cast<SigRegionBinning::BinningRegion>(iBox));
    TColor::CreateGradientColorTable(7,Length,Red,Green,Blue,999);
    TH2F* nsig = nSigs.at(iBox);

    nsig->SetMaximum(5.1);
    nsig->SetMinimum(-5.1);
    nsig->SetContour(999);


    nsig->Draw("COLZ TEXT0");
    cv.SaveAs("RsqMR_low_plus_high_RAWSUM_NSIGMA_"+boxName+tag+".png");
    
    TH2F* nsig_gauss = nSigs_gauss.at(iBox);
    nsig_gauss->SetMaximum(5.1);
    nsig_gauss->SetMinimum(-5.1);
    nsig_gauss->SetContour(999);

    nsig_gauss->Draw("COLZ");
    cv.SaveAs("RsqMR_low_plus_high_RAWSUM_NSIGMAGAUSS_"+boxName+tag+".png");
    

    TH1D* nsig_gauss_1D = SigRegionBinning::make1DProj(nsig_gauss);

    nsig_gauss_1D->SetLineColor(kBlack);
    nsig_gauss_1D->SetLineWidth(1.5);
    nsig_gauss_1D->SetMinimum(-5.1);
    nsig_gauss_1D->SetMaximum(5.1);
    nsig_gauss_1D->SetYTitle("Number of Sigma");
    cv.SetLogx(0);
    cv.SetLogy(0);
    nsig_gauss_1D->Draw();
    cv.SaveAs("RsqMR_low_plus_high_1D_RAWSUM_NSIGMAGAUSS_"+boxName+tag+".png");
    cv.SetLogx(1);
  }
}
Exemple #23
0
void XYMap()
{
  gROOT->ProcessLine(".x chain.C");

  int nbin = 50;

  TFile f("XYCorr.root","RECREATE");

  TH2F* XAccu  = new TH2F("XAccu", "XAccu",   nbin, -2400, 2400, nbin, -2400, 2400);
  TH2F* NXAccu = new TH2F("NXAccu", "NXAccu", nbin, -2400, 2400, nbin, -2400, 2400);
  TH2F* XCorr  = new TH2F("XCorr",  "XCorr",  nbin, -2400, 2400, nbin, -2400, 2400);

  TH2F* YAccu  = new TH2F("YAccu", "YAccu",   nbin, -2400, 2400, nbin, -2400, 2400);
  TH2F* NYAccu = new TH2F("NYAccu", "NYAccu", nbin, -2400, 2400, nbin, -2400, 2400);
  TH2F* YCorr = new TH2F("YCorr", "YCorr",    nbin, -2400, 2400, nbin, -2400, 2400);
  
  /* Y correction */
  Event.Draw("Y[0]:X[0]>>YAccu" ,"(YT[0]-Y[0])*(Fold==2 && E[0]-ET[0]>-0.443 && E[0]-ET[0]<0.956 && abs(ZT[0])<1500)", "colz");
  Event.Draw("Y[0]:X[0]>>NYAccu","             (Fold==2 && E[0]-ET[0]>-0.443 && E[0]-ET[0]<0.956 && abs(ZT[0])<1500)", "colz");

  for( unsigned int nbinx = 1; nbinx<=nbin; nbinx++ ) {
    for( unsigned int nbiny = 1; nbiny<=nbin; nbiny++ ) {
      double A = YAccu->GetBinContent( nbinx, nbiny );
      double N = NYAccu->GetBinContent( nbinx, nbiny );
      double Corr = 0;
      if( N>0 ) Corr = A/N;

      //if( Corr<-2000 ) cout<<nbinx<<" "<<nbiny<<" "<<A<<" "<<N<<" "<<Corr<<endl;
      YCorr->SetBinContent( nbinx, nbiny, Corr );
    }
  }

  YCorr->Draw("colz");
  
  //YCorr->Smooth(1);
  //YCorr->Smooth(1);
  
  /* X corrrection */
  Event.Draw("Y[0]:X[0]>>XAccu","(XT[0]-X[0])*(Fold==2 && E[0]-ET[0]>-0.443 && E[0]-ET[0]<0.956 && abs(ZT[0])<1500)", "colz");
  Event.Draw("Y[0]:X[0]>>NXAccu","            (Fold==2 && E[0]-ET[0]>-0.443 && E[0]-ET[0]<0.956 && abs(ZT[0])<1500)", "colz");

  for( unsigned int nbinx = 1; nbinx<=nbin; nbinx++ ) {
    for( unsigned int nbiny = 1; nbiny<=nbin; nbiny++ ) {
      double A = XAccu->GetBinContent( nbinx, nbiny );
      double N = NXAccu->GetBinContent( nbinx, nbiny );
      double Corr = 0;
      if( N>0 ) Corr = A/N;

      //if( Corr<-2000 ) cout<<nbinx<<" "<<nbiny<<" "<<A<<" "<<N<<" "<<Corr<<endl;                                                                  
      XCorr->SetBinContent( nbinx, nbiny, Corr );
    }
  }

  XCorr->Draw("colz");

  //XCorr->Smooth(1);
  //XCorr->Smooth(1);
  

  f.Write();
}
//-------------------------------------------------------------------------------------------------------------------------------------------
void ComparisonDataMC(TString fileNameData = "Data/efficiency_new.root", TString fileNameSim ="MonteCarlo/efficiency_new.root", Bool_t integrated = kFALSE)
{
  // Open input Data files
  TFile *fileData = new TFile(fileNameData.Data(), "read");
  if (!fileData || !fileData->IsOpen()) {
    printf("cannot open file %s \n",fileNameData.Data());
    return;
  }
  // Open input Sim files
  TFile *fileSim = new TFile(fileNameSim.Data(), "read");
  if (!fileSim || !fileSim->IsOpen()) {
    printf("cannot open file %s \n",fileNameSim.Data());
    return;
  }
  
  TString hname = integrated ? "integratedTracking" : "tracking";
  
  // Get Global Data and Sim graphs
  
//  TGraphAsymmErrors *effVScentData = static_cast<TGraphAsymmErrors*>(fileData->FindObjectAny("trackingEffVscentrality"));
//  if (!effVScentData) {
//    printf("Efficiency vs centrality from data not found\n");
//    return;
//  }
//  TGraphAsymmErrors *effVScentSim = static_cast<TGraphAsymmErrors*>(fileSim->FindObjectAny("trackingEffVscentrality"));
//  if (!effVScentSim) {
//    printf("Efficiency vs centrality from sim not found\n");
//    return;
//  }
  
  TGraphAsymmErrors *effVSrunData = static_cast<TGraphAsymmErrors*>(fileData->FindObjectAny("trackingEffVsRun"));
  if (!effVSrunData) {
    printf("Efficiency vs run from data not found\n");
    return;
  }
  TGraphAsymmErrors *effVSrunSim = static_cast<TGraphAsymmErrors*>(fileSim->FindObjectAny("trackingEffVsRun"));
  if (!effVSrunSim) {
    printf("Efficiency vs run from sim not found\n");
    return;
  }
  
  
  TGraphAsymmErrors *effVSyData = static_cast<TGraphAsymmErrors*>(fileData->FindObjectAny(Form("%sEffVsy",hname.Data())));
  if (!effVSyData) {
    printf("Efficiency vs rapidity from data not found\n");
    return;
  }
  TGraphAsymmErrors *effVSySim = static_cast<TGraphAsymmErrors*>(fileSim->FindObjectAny(Form("%sEffVsy",hname.Data())));
  if (!effVSySim) {
    printf("Efficiency vs rapidity from sim not found\n");
    return;
  }

  
  TGraphAsymmErrors *effVSptData = static_cast<TGraphAsymmErrors*>(fileData->FindObjectAny(Form("%sEffVspt",hname.Data())));
  if (!effVSptData) {
    printf("Efficiency vs pt from data not found\n");
    return;
  }
  TGraphAsymmErrors *effVSptSim = static_cast<TGraphAsymmErrors*>(fileSim->FindObjectAny(Form("%sEffVspt",hname.Data())));
  if (!effVSptSim) {
    printf("Efficiency vs pt from sim not found\n");
    return;
  }
  
  TGraphAsymmErrors *effVSphiData = static_cast<TGraphAsymmErrors*>(fileData->FindObjectAny(Form("%sEffVsphi",hname.Data())));
  if (!effVSphiData) {
    printf("Efficiency vs phi from data not found\n");
    return;
  }
  TGraphAsymmErrors *effVSphiSim = static_cast<TGraphAsymmErrors*>(fileSim->FindObjectAny(Form("%sEffVsphi",hname.Data())));
  if (!effVSphiSim) {
    printf("Efficiency vs phi from sim not found\n");
    return;
  }
  
  // Create an array list with the global ratios
  TObjArray globalRatios;
  
  // Create an array with the global plots of the individual efficencies and the ratios
  TObjArray globalRatiosAndEff;
  
//  globalRatios.Add(CreateRatioGraph("RatioEffVsCent","data/sim tracking efficiency versus centrality",effVScentData,effVScentSim));
  
  //---- Eff vs run
  TGraphAsymmErrors* effVSrunDataCopy = static_cast<TGraphAsymmErrors*>(effVSrunData->Clone()); // We make clones to do not modify them
  TGraphAsymmErrors* effVSrunSimCopy = static_cast<TGraphAsymmErrors*>(effVSrunSim->Clone());
  
  TGraphAsymmErrors *ratioRun = CreateRatioGraph("RatioEffVsRun","data/sim tracking efficiency versus run",*effVSrunData,*effVSrunSim);
  globalRatios.Add(ratioRun);
  
  TGraphAsymmErrors* ratioRunCopy = static_cast<TGraphAsymmErrors*>(ratioRun->Clone());
  
  globalRatiosAndEff.Add(DrawRatio("RatioEffVSRunAndEff","Comparison Data&MC tracking efficiency versus run", effVSrunDataCopy,effVSrunSimCopy,ratioRunCopy));
  //-----
  
  //---- Eff vs y
  TGraphAsymmErrors* effVSyDataCopy = static_cast<TGraphAsymmErrors*>(effVSyData->Clone()); // We make clones to do not modify them
  TGraphAsymmErrors* effVSySimCopy = static_cast<TGraphAsymmErrors*>(effVSySim->Clone());
  
  TGraphAsymmErrors *ratioY = CreateRatioGraph("RatioEffVsY","data/sim tracking efficiency versus rapidity",*effVSyData,*effVSySim);
  globalRatios.Add(ratioY);
  
  TGraphAsymmErrors* ratioYCopy = static_cast<TGraphAsymmErrors*>(ratioY->Clone());
 
  globalRatiosAndEff.Add(DrawRatio("RatioEffVSyAndEff","Comparison Data&MC tracking efficiency versus rapidity", effVSyDataCopy,effVSySimCopy,ratioYCopy));
  //-----

  //-----Eff vs Pt
  TGraphAsymmErrors* effVSptDataCopy = static_cast<TGraphAsymmErrors*>(effVSptData->Clone()); // We make clones to do not modify them
  TGraphAsymmErrors* effVSptSimCopy = static_cast<TGraphAsymmErrors*>(effVSptSim->Clone());

  TGraphAsymmErrors *ratioPt = CreateRatioGraph("RatioEffVsPt","data/sim tracking efficiency versus Pt",*effVSptData,*effVSptSim);
  globalRatios.Add(ratioPt);
  
  TGraphAsymmErrors* ratioPtCopy = static_cast<TGraphAsymmErrors*>(ratioPt->Clone());
  
   globalRatiosAndEff.Add(DrawRatio("RatioEffVSptAndEff","Comparison Data&MC tracking efficiency versus Pt",effVSptDataCopy,effVSptSimCopy,ratioPtCopy));
  //-----
  
  //----Eff vs phi
  TGraphAsymmErrors* effVSphiDataCopy = static_cast<TGraphAsymmErrors*>(effVSphiData->Clone()); // We make clones to do not modify them
  TGraphAsymmErrors* effVSphiSimCopy = static_cast<TGraphAsymmErrors*>(effVSphiSim->Clone());
  
  TGraphAsymmErrors *ratioPhi = CreateRatioGraph("RatioEffVsPhi","data/sim tracking efficiency versus phi",*effVSphiData,*effVSphiSim);
  globalRatios.Add(ratioPhi);
  
  TGraphAsymmErrors* ratioPhiCopy = static_cast<TGraphAsymmErrors*>(ratioPhi->Clone());
  
  globalRatiosAndEff.Add(DrawRatio("RatioEffVSphiAndEff","Comparison Data&MC tracking efficiency versus phi",effVSphiDataCopy,effVSphiSimCopy,ratioPhiCopy));
  //-------
  
  //----Eff vs y vs phi

  TH2F *effVSyVSphiData = static_cast<TH2F*>(fileData->FindObjectAny("trackingEffVsphi-y"));
  if (!effVSyVSphiData) {
    printf("Efficiency vs rapidity vs phi from data not found\n");
    return;
  }
  TH2F *effVSyVSphiSim = static_cast<TH2F*>(fileSim->FindObjectAny("trackingEffVsphi-y"));
  if (!effVSyVSphiSim) {
    printf("Efficiency vs rapidity vs phi from sim not found\n");
    return;
  }
  Int_t nBins2dX = effVSyVSphiData->GetXaxis()->GetNbins();
  Int_t nBins2dY = effVSyVSphiData->GetYaxis()->GetNbins();
  Double_t effData2D,effSim2D,ratio2D;
  
  TH2F *effVSphiVSyRatio = new TH2F("RatioEffVSphiVSy","EffData/EffSim vs phi vs y",nBins2dX, effVSyVSphiData->GetXaxis()->GetBinLowEdge(1), effVSyVSphiData->GetXaxis()->GetBinUpEdge(nBins2dX),nBins2dY, effVSyVSphiData->GetYaxis()->GetBinLowEdge(1), effVSyVSphiData->GetYaxis()->GetBinUpEdge(nBins2dY));
  effVSphiVSyRatio->GetXaxis()->SetTitle("phi");
  effVSphiVSyRatio->GetYaxis()->SetTitle("y");
    
  for (Int_t i = 1 ; i <= nBins2dX ; i++ )
  {
    for (Int_t j = 1 ; j <= nBins2dY ; j++ )
    {
      effData2D = effVSyVSphiData->GetBinContent(i,j);
      effSim2D = effVSyVSphiSim->GetBinContent(i,j);

      if (effData2D > 0. && effSim2D > 0.)
      {
        ratio2D = effData2D/effSim2D;
//        ratio2DErrh = rat*TMath::Sqrt(effDErrh*effDErrh/effD*effD + effSErrl*effSErrl/effS*effS);
//        ratio2DErrl = rat*TMath::Sqrt(effDErrl*effDErrl/effD*effD + effSErrh*effSErrh/effS*effS);
      }
      if (effData2D == 0 && effSim2D == 0)
      {
        ratio2D = 1.;
//        ratio2DErrh = 0.;
//        ratio2DErrl = 0.;
      }
      if (effData2D == 0 && effSim2D > 0.)
      {
        ratio2D = 0.;
//        ratio2DErrh = 0.;
//        ratio2DErrl = 0.;
      }
      if (effData2D > 0. && effSim2D == 0)
      {
        ratio2D = 2.;
//        ratio2DErrh = 0.;
//        ratio2DErrl = 0.;
      }
      effVSphiVSyRatio->SetBinContent(i,j,ratio2D);
    }
  }
  
  
  TH2F *effVSphiVSyRatioRapBins = new TH2F();
  effVSphiVSyRatioRapBins->GetXaxis()->SetTitle("phi");
  effVSphiVSyRatioRapBins->GetYaxis()->SetTitle("y");
  effVSphiVSyRatioRapBins->SetName("RatioEffVSphiVSyRapBins");
  effVSphiVSyRatioRapBins->SetTitle("EffData/EffSim vs phi vs y");

  
  Int_t nxBins = effVSphiVSyRatio->GetXaxis()->GetNbins();
  Int_t nyBins = effVSphiVSyRatio->GetYaxis()->GetNbins();
  
  Double_t xBinEdge[nxBins+1];
  Double_t yBinEdge[nyBins+1];
  
  for (Int_t ybin = 0 ; ybin <= nyBins ; ybin++)
  {
    yBinEdge[ybin] = 2*TMath::ATan(TMath::Exp((effVSphiVSyRatio->GetYaxis()->GetBinLowEdge(ybin+1))));
  }
  for (Int_t xbin = 0 ; xbin <= nxBins ; xbin++)
  {
    xBinEdge[xbin] = effVSphiVSyRatio->GetXaxis()->GetBinLowEdge(xbin+1);
  }
  
  effVSphiVSyRatioRapBins->SetBins(nxBins,xBinEdge,nyBins,yBinEdge);
  
  for (Int_t xbin = 1 ; xbin <= nxBins ; xbin++)
  {
    for (Int_t ybin = 1 ; ybin <= nyBins ; ybin++)
    {
      effVSphiVSyRatioRapBins->SetBinContent(xbin,ybin,effVSphiVSyRatio->GetBinContent(xbin,ybin));
    }
  }
  globalRatiosAndEff.Add(effVSphiVSyRatio);
  globalRatiosAndEff.Add(effVSphiVSyRatioRapBins);

 
  //--------
  
  TString hname2 = integrated ? "IntegratedChamber" : "Chamber";
  
  // Get Chamber and DE Data and Sim graphs
//  TObjArray *listChEffVSrunData = static_cast<TObjArray*>(fileData->FindObjectAny("ChambersEffVSrun"));
//  if (!listChEffVSrunData) {
//    printf("list of Chamber efficiencies vs run from data not found\n");
//    return;
//  }
//  TObjArray *listChEffVSrunSim = static_cast<TObjArray*>(fileSim->FindObjectAny("ChambersEffVSrun"));
//  if (!listChEffVSrunSim) {
//    printf("list of Chamber efficiencies vs run from sim not found\n");
//    return;
//  }

  TObjArray *listChEffVSDEData = static_cast<TObjArray*>(fileData->FindObjectAny(Form("%sEffVsDE",hname2.Data())));
  if (!listChEffVSDEData) {
    printf("list of Chamber efficiencies per DE from data not found\n");
    return;
  }
  TObjArray *listChEffVSDESim = static_cast<TObjArray*>(fileSim->FindObjectAny(Form("%sEffVsDE",hname2.Data())));
  if (!listChEffVSDESim) {
    printf("list of Chamber efficiencies per DE from sim not found\n");
    return;
  }
  
//  TObjArray *listDEEffVSrunData = static_cast<TObjArray*>(fileData->FindObjectAny("DEEffVSrun"));
//  if (!listDEEffVSrunData) {
//    printf("list of DE efficiencies vs run from data not found\n");
//    return;
//  }
//  TObjArray *listDEEffVSrunSim = static_cast<TObjArray*>(fileSim->FindObjectAny("DEEffVSrun"));
//  if (!listDEEffVSrunSim) {
//    printf("list of DE efficiencies vs run from sim not found\n");
//    return;
//  }
  
  // Graph for global efficiency vs run
  TGraphAsymmErrors* gData ;//= static_cast<TGraphAsymmErrors*>(listChEffVSrunData->At(0));
  TGraphAsymmErrors* gSim ;//= static_cast<TGraphAsymmErrors*>(listChEffVSrunSim->At(0));
  
  
  //----Eff vs run  
//  TGraphAsymmErrors *ratioEffvsrRun = CreateRatioGraph("RatioEffVsRun","data/sim tracking efficiency versus run",*gData,*gSim);
//  globalRatios.Add(ratioEffvsrRun);
//  
//  TGraphAsymmErrors* ratioEffvsrRunCopy = static_cast<TGraphAsymmErrors*>(ratioEffvsrRun->Clone());
//  
//  globalRatiosAndEff.Add(DrawRatio("RatioEffVsRunAndEff","Comparison Data&MC tracking efficiency versus run",gData,gSim,ratioEffvsrRunCopy));
  //-------

  //globalRatios.Add(CreateRatioGraph("RatioEffVsRun","data/sim tracking efficiency versus run",*gData,*gSim));
  
  // Create a list with the Chamber and DE ratios
//  TObjArray chamberVSrunRatios;
//  TObjArray deVSrunRatios;
  TObjArray chamberVSdeRatios;
  
//  TObjArray chamberVSrunRatiosAndEff;
//  TObjArray deVSrunRatiosAndEff;
  TObjArray chamberVSdeRatiosAndEff;
  
  // Compute the ratios for Chamber vs run
//  for (Int_t nList = 1 ; nList < listChEffVSrunData->GetEntries() ; nList++)
//  {
//    gData = static_cast<TGraphAsymmErrors*>(listChEffVSrunData->At(nList));
//    gSim = static_cast<TGraphAsymmErrors*>(listChEffVSrunSim->At(nList));
//    if (!gData || !gSim )
//    {
//      printf("Error readig from Chamber efficiency vs run list \n");
//      return;
//    }
//    //----Eff of Chs vs run
//    TString name =  Form("RatioEffCh%dVsRun",nList); TString title = Form("Chamber %d data/sim tracking efficiency versus run",nList);
//    
//    TGraphAsymmErrors *ratioEffChVsrRun = CreateRatioGraph(name.Data(),title.Data(),*gData,*gSim);
//    chamberVSrunRatios.Add(ratioEffChVsrRun);
//    
//    TGraphAsymmErrors* ratioEffChVsrRunCopy = static_cast<TGraphAsymmErrors*>(ratioEffChVsrRun->Clone());
//    
//    TString nameRatio =  Form("RatioEffCh%dVsRunAndEff",nList); TString titleRatio = Form("Comparison Data&MC Ch%d tracking efficiency versus run",nList);
//    chamberVSrunRatiosAndEff.Add(DrawRatio(nameRatio.Data(),titleRatio.Data(),gData,gSim,ratioEffChVsrRunCopy));
//    //-------
//
//    
////    chamberVSrunRatios.Add(CreateRatioGraph(,,*gData,*gSim));
//    
//  }
  
  //Load the mapping for the DE histos
  AliCDBManager::Instance()->SetDefaultStorage("local://$ALICE_ROOT/OCDB");
  AliCDBManager::Instance()->SetRun(0);
  AliMUONCDB::LoadMapping();
  AliMpDEIterator deit;

  // Loop over Chambers
  for (Int_t ich = 0 ; ich < 10 ; ich++)
  {
    // Compute the ratios for DE vs run
    deit.First(ich);
  
//    while ( !deit.IsDone() )
//    {
//      TString currentDEName = Form("EffDE%dVSrun",deit.CurrentDEId());
//      gData = static_cast<TGraphAsymmErrors*>(listDEEffVSrunData->FindObject(currentDEName.Data()));
//      gSim = static_cast<TGraphAsymmErrors*>(listDEEffVSrunSim->FindObject(currentDEName.Data()));
//      
//      TString name =  Form("RatioEffDE%dVsRun",deit.CurrentDEId()); TString title = Form("DE %d data/sim tracking efficiency versus run",deit.CurrentDEId());
//      if (!gData || !gSim )
//      {
//        printf("Error readig from DE efficiency vs run list \n");
//        return;
//      }
//      //----Eff of DEs vs run
//      TGraphAsymmErrors *ratioEffDEvsRun = CreateRatioGraph(name.Data(),title.Data(),*gData,*gSim);
//      deVSrunRatios.Add(ratioEffDEvsRun);
//      
//      TGraphAsymmErrors* ratioEffDEvsRunCopy = static_cast<TGraphAsymmErrors*>(ratioEffDEvsRun->Clone());
//      
//      TString nameRatio =  Form("RatioEffDE%dVsRunAndEff",deit.CurrentDEId()); TString titleRatio = Form("Comparison Data&MC DE%d tracking efficiency versus run",deit.CurrentDEId());
//      deVSrunRatiosAndEff.Add(DrawRatio(nameRatio.Data(),titleRatio.Data(),gData,gSim,ratioEffDEvsRunCopy));
//      //-------
//
////      deVSrunRatios.Add(CreateRatioGraph(name.Data(),title.Data(),*gData,*gSim));
//      
//      deit.Next();
//    }
  
    // Compute the ratios for Ch vs DE
    TString hname3 = integrated ? "integratedEff" : "eff";
    gData = static_cast<TGraphAsymmErrors*>(listChEffVSDEData->FindObject(Form("%sCh%dVsDE",hname3.Data(),ich+1)));
    gSim = static_cast<TGraphAsymmErrors*>(listChEffVSDESim->FindObject(Form("%sCh%dVsDE",hname3.Data(),ich+1)));
    
    if (!gData || !gSim )
    {
      printf("Error reading from Chamber efficiency per DE list \n");
      return;
    }
    TString name =  Form("RatioEffCh%dVsDE",ich+1); TString title = Form("Chamber %d data/sim tracking efficiency versus DE",ich+1);
    //----Eff of CHs vs DE
    TGraphAsymmErrors *ratioEffChvsDE = CreateRatioGraph(name.Data(),title.Data(),*gData,*gSim);
    chamberVSdeRatios.Add(ratioEffChvsDE);
    
    TGraphAsymmErrors* ratioEffChvsDECopy = static_cast<TGraphAsymmErrors*>(ratioEffChvsDE->Clone());
    
    TString nameRatio =  Form("RatioEffCh%dVsDEAndEff",ich+1); TString titleRatio = Form("Comparison Data&MC Ch%d tracking efficiency versus DE",ich+1);
    chamberVSdeRatiosAndEff.Add(DrawRatio(nameRatio.Data(),titleRatio.Data(),gData,gSim,ratioEffChvsDECopy));
    //-------

    
//    chamberVSdeRatios.Add(CreateRatioGraph(name.Data(),title.Data(),*gData,*gSim));
    
  }

  //Beautify graphs
  BeautifyGraphs(globalRatios,"EffData/EffSim");
//  BeautifyGraphs(deVSrunRatios,"EffData/EffSim");
//  BeautifyGraphs(chamberVSrunRatios,"EffData/EffSim");
  BeautifyGraphs(chamberVSdeRatios,"EffData/EffSim");

//  BeautifyGraphs(globalRatiosAndEff,"EffData/EffSim");
//  BeautifyGraphs(deVSrunRatiosAndEff,"EffData/EffSim");
//  BeautifyGraphs(chamberVSrunRatiosAndEff,"EffData/EffSim");
//  BeautifyGraphs(chamberVSdeRatiosAndEff,"EffData/EffSim");

  // set bin labels
//  SetRunLabel(deVSrunRatios,irun,runs);
//  SetRunLabel(chamberVSrunRatios,irun,runs);
//  SetRunLabel(globalRatios,irun,runs,1); //Write it in such a way the number is the position on the list of the graph you want to label
//  
  // save output
  TFile* file = new TFile("EffComparison.root","update");
  
  globalRatios.Write("GlobalEffRatios", TObject::kOverwrite | TObject::kSingleKey);
//  chamberVSrunRatios.Write("ChambersEffVSrunRatios", TObject::kOverwrite | TObject::kSingleKey);
//  deVSrunRatios.Write("DEEffVSrunRatios", TObject::kOverwrite | TObject::kSingleKey);
  chamberVSdeRatios.Write("ChamberEffperDERatios", TObject::kOverwrite | TObject::kSingleKey);
  
  globalRatiosAndEff.Write("GlobalEffRatiosAndEffs", TObject::kOverwrite | TObject::kSingleKey);
//  chamberVSrunRatiosAndEff.Write("ChambersEffVSrunRatiosAndEff", TObject::kOverwrite | TObject::kSingleKey);
//  deVSrunRatiosAndEff.Write("DEEffVSrunRatiosAndEff", TObject::kOverwrite | TObject::kSingleKey);
  chamberVSdeRatiosAndEff.Write("ChamberEffperDERatiosAndEff", TObject::kOverwrite | TObject::kSingleKey);

  
   
  file->Close();
 
  fileData->Close();
  fileSim->Close();
   


}
// ****************************************************************
//XXX: main
int main(int argc, char* argv[])
{
  //
  // **** May 20 2010 update ****
  // Usage: CreateEcalTimingCalibsEE fileWithTree options...
  //

  using namespace std;
  // Ao dependent timing corrections
  timeCorrectionEE_ = new TF1("timeCorrectionEE_","pol4(0)",0,1.2);
  //coefficients obtained in the interval (0, 1.5) from Low eta region < 2.2, run 144011
  timeCorrectionEE_->SetParameters(-0.461192,0.0876435,-0.234752,0.143774,-0.051990);

  // For selection cuts
  string inBxs, inOrbits, inTrig, inTTrig, inLumi, inRuns;
  float avgTimeMin, avgTimeMax;
  float minAmpEB, minAmpEE;
  float maxE1E9, maxSwissCrossNoise;  // EB only, no spikes seen in EE
  float maxHitTimeEE, minHitTimeEE;
  // init to sensible defaults
  avgTimeMin = -1; // in ns
  avgTimeMax = 1; // in ns
  minAmpEB = 5; // GeV
  minAmpEE = 5; // GeV
  maxHitTimeEE = 15; // ns
  minHitTimeEE = -15; // ns
  maxE1E9 = 0.95; // EB only
  maxSwissCrossNoise = 0.95; // EB only
  inBxs = "-1";
  inOrbits = "-1";
  inTrig = "-1";
  inTTrig = "-1";
  inLumi = "-1";
  inRuns = "-1";

  char* infile = argv[1];
  if (!infile)
  {
    cout << " No input file specified !" << endl;
    return -1;
  }

  //TODO: Replace this with the parseArguments function from the pi0 binary
  std::string stringGenericOption    = "--";
  for (int i=1 ; i<argc ; i++) {
    if (argv[i] == std::string("-bxs") && argc>i+1) inBxs = std::string(argv[i+1]);
    if (argv[i] == std::string("-orbits") && argc>i+1) inOrbits = std::string(argv[i+1]);
    if (argv[i] == std::string("-trig") && argc>i+1) inTrig = std::string(argv[i+1]);
    if (argv[i] == std::string("-ttrig") && argc>i+1) inTTrig = std::string(argv[i+1]);
    if (argv[i] == std::string("-lumi") && argc>i+1) inLumi = std::string(argv[i+1]);
    if (argv[i] == std::string("-runs") && argc>i+1) inRuns = std::string(argv[i+1]);
    if (argv[i] == std::string("-ebampmin") && argc>i+1) minAmpEB = atof(argv[i+1]);
    if (argv[i] == std::string("-eeampmin") && argc>i+1) minAmpEE = atof(argv[i+1]);
    if (argv[i] == std::string("-e1e9max") && argc>i+1) maxE1E9 = atof(argv[i+1]);
    if (argv[i] == std::string("-swisskmax") && argc>i+1) maxSwissCrossNoise = atof(argv[i+1]);
    if (argv[i] == std::string("-avgtimemin") && argc>i+1) avgTimeMin = atof(argv[i+1]);
    if (argv[i] == std::string("-avgtimemax") && argc>i+1) avgTimeMax = atof(argv[i+1]);
    if (argv[i] == std::string("-eehittimemax") && argc>i+1) maxHitTimeEE = atof(argv[i+1]);
    if (argv[i] == std::string("-eehittimemin") && argc>i+1) minHitTimeEE = atof(argv[i+1]);
    // handle here the case of multiple arguments for input files
    if (argv[i] == std::string("--i"))// && argc>i+1)
    {
      for (int u=i+1; u<argc; u++)
      {
        if ( 0==std::string(argv[u]).find( stringGenericOption ) )
        {
          if ( 0==listOfFiles_.size())  {std::cout << "no input files listed" << std::cout;}
          else  {std::cout << "no more files listed, found: " << argv[u] << std::cout;}
          break;
        }
        else
        {
          listOfFiles_.push_back(argv[u]);
          i++;
        }
      }// loop on arguments following --i
      continue;
    }//end 'if input files'

  }
  // Open the input files
  if (listOfFiles_.size()==0){
    std::cout << "\tno input file found" << std::endl;
    return(1);
  }
  else{
    std::cout << "\tfound " << listOfFiles_.size() << " input files: " << std::endl;
    for(std::vector<std::string>::const_iterator  file_itr=listOfFiles_.begin(); file_itr!=listOfFiles_.end(); file_itr++){
      std::cout << "\t" << (*file_itr) << std::endl;
    }
  }
  // Tree construction
  TChain* chain = new TChain ("EcalTimeAnalysis") ;
  std::vector<std::string>::const_iterator file_itr;
  for(file_itr=listOfFiles_.begin(); file_itr!=listOfFiles_.end(); file_itr++){
    chain->Add( (*file_itr).c_str() );
  }


  cout << "Running with options: "
    << "avgTimeMin: " << avgTimeMin << " avgTimeMax: " << avgTimeMax
    << " minAmpEB: " << minAmpEB << " minAmpEE: " << minAmpEE
    << " maxHitTimeEE: " << maxHitTimeEE << " minHitTimeEE: " << minHitTimeEE
    << " inTrig: " << inTrig << " inTTrig: " << inTTrig << " inLumi: " << inLumi 
    << " inBxs: " << inBxs << " inRuns: " << inRuns << " inOrbits: " << inOrbits
    << endl;

  // Ignore warnings
  gErrorIgnoreLevel = 2001;

  setBranchAddresses(chain,treeVars_);

  // Generate all the vectors for skipping selections
  std::vector<std::vector<double> > bxIncludeVector;
  std::vector<std::vector<double> > bxExcludeVector;
  std::vector<std::vector<double> > orbitIncludeVector;
  std::vector<std::vector<double> > orbitExcludeVector;
  std::vector<std::vector<double> > trigIncludeVector;
  std::vector<std::vector<double> > trigExcludeVector;
  std::vector<std::vector<double> > ttrigIncludeVector;
  std::vector<std::vector<double> > ttrigExcludeVector;
  std::vector<std::vector<double> > lumiIncludeVector;
  std::vector<std::vector<double> > lumiExcludeVector;
  std::vector<std::vector<double> > runIncludeVector;
  std::vector<std::vector<double> > runExcludeVector;
  //recall: string inBxs, inOrbits, inTrig, inTTrig, inLumi, inRuns;
  genIncludeExcludeVectors(inBxs,bxIncludeVector,bxExcludeVector);
  genIncludeExcludeVectors(inOrbits,orbitIncludeVector,orbitExcludeVector);
  genIncludeExcludeVectors(inTrig,trigIncludeVector,trigExcludeVector);
  genIncludeExcludeVectors(inTTrig,ttrigIncludeVector,ttrigExcludeVector);
  genIncludeExcludeVectors(inLumi,lumiIncludeVector,lumiExcludeVector);
  genIncludeExcludeVectors(inRuns,runIncludeVector,runExcludeVector);

  // Open output file and book hists
  string fileNameBeg = "timingCalibsEE";
  string rootFilename = fileNameBeg+".root";
  TFile* outfile = new TFile(rootFilename.c_str(),"RECREATE");
  outfile->cd();

  TH1F* calibHistEE = new TH1F("timingCalibsEE","timingCalibs EE [ns]",2000,-100,100);
  TH1F* calibErrorHistEE = new TH1F("timingCalibErrorEE","timingCalibError EE [ns]",500,0,5);
  calibHistEE->Sumw2();
  calibErrorHistEE->Sumw2();

  TH2F* calibsVsErrors = new TH2F("timingCalibsAndErrors","TimingCalibs vs. errors [ns]",500,0,5,100,0,10);
  calibsVsErrors->Sumw2();

  //TH2F* calibMapEE = new TH2F("calibMapEE","time calib map EE",360,1,361,170,-86,86);
  //TH2F* calibMapEEFlip = new TH2F("calibMapEEFlip","time calib map EE",170,-86,86,360,1,361);
  //TH2F* calibMapEEPhase = new TH2F("calibMapEEPhase","time calib map EE (phase of Tmax)",360,1,361,170,-86,86);
  
  //TH2F* calibMapEtaAvgEE = new TH2F("calibMapEtaAvgEE","time calibs raw eta avg map EE",360,1,361,170,-86,86);
  //TH1F* calibHistEtaAvgEE = new TH1F("timingCalibsEtaAvgEE","EtaAvgTimingCalibs EE [ns]",2000,-100,100);

  TH2F* hitsPerCryMapEEM = new TH2F("hitsPerCryMapEEM","Hits per cry EEM;ix;iy",100,1,101,100,1,101);
  TH2F* hitsPerCryMapEEP = new TH2F("hitsPerCryMapEEP","Hits per cry EEP;ix;iy",100,1,101,100,1,101);
  TH1F* hitsPerCryHistEEM = new TH1F("hitsPerCryHistEEM","Hits per cry EEM;hashedIndex",14648,0,14648);
  TH1F* hitsPerCryHistEEP = new TH1F("hitsPerCryHistEEP","Hits per cry EEP;hashedIndex",14648,0,14648);
  //TH1C* eventsEEMHist = new TH1C("numEventsEEM","Number of events, EEM",100,0,100);
  //TH1C* eventsEEPHist = new TH1C("numEventsEEP","Number of events, EEP",100,0,100);
  TProfile* ampProfileEEM = new TProfile("ampProfileEEM","Amp. profile EEM;hashedIndex",14648,0,14648);
  TProfile* ampProfileEEP = new TProfile("ampProfileEEP","Amp. profile EEP;hashedIndex",14648,0,14648);
  TProfile2D* ampProfileMapEEP = new TProfile2D("ampProfileMapEEP","Amp. profile EEP;ix;iy",100,1,101,100,1,101);
  TProfile2D* ampProfileMapEEM = new TProfile2D("ampProfileMapEEM","Amp. profile EEM;ix;iy",100,1,101,100,1,101);

  //TH1F* eventsEEHist = new TH1F("numEventsEE","Number of events, EE",100,0,100);
  //TH1F* calibSigmaHist = new TH1F("timingSpreadEE","Crystal timing spread [ns]",1000,-5,5);

  TH1F* sigmaHistEE = new TH1F("sigmaCalibsEE"," Sigma of calib distributions EE [ns]",100,0,1);

  //TH1F* chiSquaredEachEventHist = new TH1F("chi2eachEvent","Chi2 of each event",500,0,500);
  //TH2F* chiSquaredVsAmpEachEventHist = new TH2F("chi2VsAmpEachEvent","Chi2 vs. amplitude of each event",500,0,500,750,0,750);
  //TH2F* chiSquaredHighMap = new TH2F("chi2HighMap","Channels with event #Chi^{2} > 100",360,1,361,170,-86,86);
  //TH1F* chiSquaredTotalHist = new TH1F("chi2Total","Total chi2 of all events in each crystal",500,0,500);
  //TH1F* chiSquaredSingleOverTotalHist = new TH1F("chi2SingleOverTotal","Chi2 of each event over total chi2",100,0,1);
  //TH1F* ampEachEventHist = new TH1F("energyEachEvent","Energy of all events [GeV]",1000,0,10);
  //TH1F* numPointsErasedHist = new TH1F("numPointsErased","Number of points erased per crystal",25,0,25);
  
  //TProfile2D* myAmpProfile = (TProfile2D*)EBampProfile->Clone();
  //myAmpProfile->Write();
  TH1F* expectedStatPresHistEEM = new TH1F("expectedStatPresEEM","Avg. expected statistical precision EEM [ns], all crys",200,0,2);
  TH2F* expectedStatPresVsObservedMeanErrHistEEM = new TH2F("expectedStatPresVsObsEEM","Expected stat. pres. vs. obs. error on mean each event EEM [ns]",200,0,2,200,0,2);
  TH1F* expectedStatPresEachEventHistEEM = new TH1F("expectedStatPresSingleEventEEM","Expected stat. pres. each event EEM [ns]",200,0,2);
  TH1F* expectedStatPresHistEEP = new TH1F("expectedStatPresEEP","Avg. expected statistical precision EEP [ns], all crys",200,0,2);
  TH2F* expectedStatPresVsObservedMeanErrHistEEP = new TH2F("expectedStatPresVsObsEEP","Expected stat. pres. vs. obs. error on mean each event [ns] EEP",200,0,2,200,0,2);
  TH1F* expectedStatPresEachEventHistEEP = new TH1F("expectedStatPresSingleEventEEP","Expected stat. pres. each event EEP [ns]",200,0,2);
  
  TH2F* errorOnMeanVsNumEvtsHist = new TH2F("errorOnMeanVsNumEvts","Error_on_mean vs. number of events",50,0,50,200,0,2);
  errorOnMeanVsNumEvtsHist->Sumw2();
  
  TH1F* calibHistEEM = new TH1F("timingCalibsEEM","timingCalibs EEM [ns]",500,-25,25);
  TH1F* calibHistEEP = new TH1F("timingCalibsEEP","timingCalibs EEP [ns]",500,-25,25);
  TH1F* calibErrorHistEEM = new TH1F("calibErrorEEM","timingCalibError EEM [ns]",250,0,5);
  TH1F* calibErrorHistEEP = new TH1F("calibErrorEEP","timingCalibError EEP [ns]",250,0,5);
  calibHistEEM->Sumw2();
  calibHistEEP->Sumw2();
  calibErrorHistEEM->Sumw2();
  calibErrorHistEEP->Sumw2();

  TH2F* calibMapEEM = new TH2F("calibMapEEM","time calib map EEM",100,1,101,100,1,101);
  TH2F* calibMapEEP = new TH2F("calibMapEEP","time calib map EEP",100,1,101,100,1,101);
  calibMapEEM->Sumw2();
  calibMapEEP->Sumw2();

  TH2F* sigmaMapEEM = new TH2F("sigmaMapEEM","Sigma of time calib map EEM [ns];ix;iy",100,1.,101.,100,1,101);
  TH2F* sigmaMapEEP = new TH2F("sigmaMapEEP","Sigma of time calib map EEP [ns];ix;iy",100,1.,101.,100,1,101);
  TH2F* calibErrorMapEEM = new TH2F("calibErrorMapEEM","Error of time calib map EEM [ns];ix;iy",100,1.,101.,100,1,101);
  TH2F* calibErrorMapEEP = new TH2F("calibErrorMapEEP","Error of time calib map EEP [ns];ix;iy",100,1.,101.,100,1,101);

  TDirectory* cryDirEEP = gDirectory->mkdir("crystalTimingHistsEEP");
  cryDirEEP->cd();
  TH1C* cryTimingHistsEEP[100][100]; // [0][0] = ix 1, iy 1
  for(int x=0; x < 100; ++x)
  {
    for(int y=0; y < 100; ++y)
    {
      if(!EEDetId::validDetId(x+1,y+1,1))
        continue;
      string histname = "EEP_cryTiming_ix";
      histname+=intToString(x+1);
      histname+="_iy";
      histname+=intToString(y+1);
      cryTimingHistsEEP[x][y] = new TH1C(histname.c_str(),histname.c_str(),660,-33,33);
      cryTimingHistsEEP[x][y]->Sumw2();
    }
  }
  outfile->cd();
  TDirectory* cryDirEEM = gDirectory->mkdir("crystalTimingHistsEEM");
  cryDirEEM->cd();
  TH1C* cryTimingHistsEEM[100][100]; // [0][0] = ix 1, iy 1
  for(int x=0; x < 100; ++x)
  {
    for(int y=0; y < 100; ++y)
    {
      if(!EEDetId::validDetId(x+1,y+1,-1))
        continue;
      string histname = "EEM_cryTiming_ix";
      histname+=intToString(x+1);
      histname+="_iy";
      histname+=intToString(y+1);
      cryTimingHistsEEM[x][y] = new TH1C(histname.c_str(),histname.c_str(),660,-33,33);
      cryTimingHistsEEM[x][y]->Sumw2();
    }
  }
  outfile->cd();
  
  cout << "Making calibs..." << endl;

  CrystalCalibration* eeCryCalibs[14648];
  //XXX: Making calibs with weighted/unweighted mean
  for(int i=0; i < 14648; ++i)
    eeCryCalibs[i] = new CrystalCalibration(); //use weighted mean!
    //eeCryCalibs[i] = new CrystalCalibration(false); //don't use weighted mean!

  cout << "Looping over TTree...";

  // Loop over the TTree
  int numEventsUsed = 0;
  int nEntries = chain->GetEntries();
  cout << "Begin loop over TTree." << endl;

  for(int entry = 0; entry < nEntries; ++entry)
  {
    chain->GetEntry(entry);

    // Loop once to calculate average event time
    float sumTime = 0;
    int numCrysEE = 0;
    for(int bCluster=0; bCluster < treeVars_.nClusters; bCluster++)
    {
      if(treeVars_.xtalInBCIEta[bCluster][0] != -999999) continue; // skip EB clusters
      for(int cryInBC=0; cryInBC < treeVars_.nXtalsInCluster[bCluster]; cryInBC++)
      {
        sumTime += treeVars_.xtalInBCTime[bCluster][cryInBC];
        numCrysEE++;
      }
    }
    //debug
    //cout << "Number of EE crys in event: " << numEEcrys << endl;

    //XXX: Event cuts
    if(sumTime/numCrysEE > avgTimeMax || sumTime/numCrysEE < avgTimeMin)
    {
      //cout << "Average event time: " << sumTime/numCrysEE  << " so event rejected." << endl;
      continue;
    }
    // check BX, orbit, lumi, run, L1 tech/phys triggers
    bool keepEvent = includeEvent(treeVars_.bx,bxIncludeVector,bxExcludeVector)
      && includeEvent(treeVars_.orbit,orbitIncludeVector,orbitExcludeVector)
      && includeEvent(treeVars_.lumiSection,lumiIncludeVector,lumiExcludeVector)
      && includeEvent(treeVars_.runId,runIncludeVector,runExcludeVector)
      && includeEvent(treeVars_.l1ActiveTriggers,
          treeVars_.l1NActiveTriggers,trigIncludeVector,trigExcludeVector)
      && includeEvent(treeVars_.l1ActiveTechTriggers,
          treeVars_.l1NActiveTechTriggers,ttrigIncludeVector,ttrigExcludeVector);
    if(!keepEvent)
      continue;
      
    numEventsUsed++;

    // Loop over the EE crys and fill the map
    for(int bCluster=0; bCluster < treeVars_.nClusters; bCluster++)
    {
      if(treeVars_.xtalInBCIEta[bCluster][0] != -999999) continue; // skip EB clusters
      for(int cryInBC=0; cryInBC < treeVars_.nXtalsInCluster[bCluster]; cryInBC++)
      {
        int hashedIndex = treeVars_.xtalInBCHashedIndex[bCluster][cryInBC];
        float cryTime = treeVars_.xtalInBCTime[bCluster][cryInBC];
        float cryTimeError = treeVars_.xtalInBCTimeErr[bCluster][cryInBC];
        float cryAmp = treeVars_.xtalInBCAmplitudeADC[bCluster][cryInBC];
	float Ao = cryAmp/sigmaNoiseEE;
	float AoLog = log10(Ao/25);

        EEDetId det = EEDetId::unhashIndex(hashedIndex);
        if(det==EEDetId()) // make sure DetId is valid
          continue;

        int ix = det.ix();
        int iy = det.iy();

        //XXX: RecHit cuts
        bool keepHit = cryAmp >= minAmpEE
          && cryTime > minHitTimeEE
          && cryTime < maxHitTimeEE
	  && AoLog > 0
          && AoLog < 1.2;
        if(!keepHit)
          continue;

        //cout << "STUPID DEBUG: " << hashedIndex << " cryTime: " << cryTime << " cryTimeError: " << cryTimeError << " cryAmp: " << cryAmp << endl;

	// Timing correction to take out the energy dependence if log10(ampliOverSigOfThis/25)
        // is between 0 and 1.2 (about 1 and 13 GeV)
	// amplitude dependent timing corrections
        float timing = cryTime - timeCorrectionEE_->Eval(AoLog);
        //FIXME
        cryTimeError = 1;
        eeCryCalibs[hashedIndex]->insertEvent(cryAmp,timing,cryTimeError,false);

        //SIC Use when we don't have time_error available
        //eeCryCalibs[hashedIndex]->insertEvent(cryAmp,cryTime,35/(cryAmp/1.2),false);
        if(det.zside() < 0)
        {
          ampProfileEEM->Fill(hashedIndex,cryAmp);
          ampProfileMapEEM->Fill(ix,iy,cryAmp);
        }
        else
        {
          ampProfileEEP->Fill(hashedIndex,cryAmp);
          ampProfileMapEEP->Fill(ix,iy,cryAmp);
        }
      }
    }
  }

  //create output text file
  ofstream fileStream;
  string fileName = fileNameBeg+".calibs.txt";
  fileStream.open(fileName.c_str());
  if(!fileStream.good() || !fileStream.is_open())
  {
    cout << "Couldn't open text file." << endl;
    return -1;
  }
  //create problem channels text file
  ofstream fileStreamProb;
  string fileName2 = fileNameBeg+".problems.txt";
  fileStreamProb.open(fileName2.c_str());
  if(!fileStreamProb.good() || !fileStreamProb.is_open())
  {
    cout << "Couldn't open text file." << endl;
    return -1;
  }

  // Create calibration container objects
  EcalTimeCalibConstants timeCalibConstants;
  EcalTimeCalibErrors timeCalibErrors;

  cout << "Using " << numEventsUsed << " out of " << nEntries << " in the tree." << endl;
  cout << "Creating calibs..." << endl;
  float cryCalibAvg = 0;
  int numCrysCalibrated = 0;
  vector<int> hashesToCalibrateToAvg;
  //Loop over all the crys
  for(int hashedIndex=0; hashedIndex < 14648; ++hashedIndex)
  {
    EEDetId det = EEDetId::unhashIndex(hashedIndex);
    if(det==EEDetId())
      continue;
    CrystalCalibration cryCalib = *(eeCryCalibs[hashedIndex]);
    int x = det.ix();
    int y = det.iy();

    //chiSquaredTotalHist->Fill(cryCalib.totalChi2);
    //expectedStatPresHistEB->Fill(sqrt(1/expectedPresSumEB));
    //expectedStatPresVsObservedMeanErrHistEB->Fill(sigmaM,sqrt(1/expectedPresSumEB));

    //XXX: Filter events at default 0.5*meanE threshold
    cryCalib.filterOutliers();
    
    //numPointsErasedHist->Fill(numPointsErased);
    
    //Write cryTimingHists
    vector<TimingEvent> times = cryCalib.timingEvents;
    for(vector<TimingEvent>::const_iterator timeItr = times.begin();
        timeItr != times.end(); ++timeItr)
    {
      if(det.zside() < 0)
      {
        float weight = 1/((timeItr->sigmaTime)*(timeItr->sigmaTime));
        cryTimingHistsEEM[x-1][y-1]->Fill(timeItr->time,weight);
      }
      else
      {
        float weight = 1/((timeItr->sigmaTime)*(timeItr->sigmaTime));
        cryTimingHistsEEP[x-1][y-1]->Fill(timeItr->time,weight);
      }
    }
    if(det.zside() < 0)
    {
      cryDirEEM->cd();
      cryTimingHistsEEM[x-1][y-1]->Write();
    }
    else
    {
      cryDirEEP->cd();
      cryTimingHistsEEP[x-1][y-1]->Write();
    }
    outfile->cd();

    if(det.zside() < 0)
    {
      hitsPerCryHistEEM->SetBinContent(hashedIndex+1,cryCalib.timingEvents.size());
      hitsPerCryMapEEM->Fill(x,y,cryCalib.timingEvents.size());
    }
    else
    {
      hitsPerCryHistEEP->SetBinContent(hashedIndex+1,cryCalib.timingEvents.size());
      hitsPerCryMapEEP->Fill(x,y,cryCalib.timingEvents.size());
    }
    
    // Make timing calibs
    double p1 = cryCalib.mean;
    double p1err = cryCalib.meanE;
    //cout << "cry ieta: " << ieta << " cry iphi: " << iphi << " p1: " << p1 << " p1err: " << p1err << endl;
    if(cryCalib.timingEvents.size() < 10)
    {
      fileStreamProb << "Cry (only " << cryCalib.timingEvents.size() << " events) was calibrated to avg: " << det.zside() << ", "
                                                                                        << x <<", " << y << ", hash: "
                                                                        << hashedIndex
                                                                          << "\t Calib: " << p1 << "\t Error: " << p1err << std::endl;
      hashesToCalibrateToAvg.push_back(hashedIndex);
      continue;
    }
    // Make it so we can add calib to reco time
    p1*=-1;
    if(p1err < 0.5 && p1err > 0)
    {
      fileStream << "EE\t" << hashedIndex << "\t" << p1 << "\t\t" << p1err << endl;
      if(det.zside() < 0)
      {
        calibHistEEM->Fill(p1);
        //calibMapEEMFlip->Fill(y-85,x+1,p1);
        calibMapEEM->Fill(x,y,p1);
        //calibMapEEMPhase->Fill(x+1,y-85,p1/25-floor(p1/25));
        //errorOnMeanVsNumEvtsHist->Fill(times.size(),p1err);
      }
      else
      {
        calibHistEEP->Fill(p1);
        //calibMapEEPFlip->Fill(y-85,x+1,p1);
        calibMapEEP->Fill(x,y,p1);
        //calibMapEEPPhase->Fill(x+1,y-85,p1/25-floor(p1/25));
        //errorOnMeanVsNumEvtsHist->Fill(times.size(),p1err);
      }
      cryCalibAvg+=p1;
      ++numCrysCalibrated;
      //Store in timeCalibration container
      EcalTimeCalibConstant tcConstant = p1;
      EcalTimeCalibError tcError = p1err;
      uint32_t rawId = EEDetId::unhashIndex(hashedIndex);
      timeCalibConstants[rawId] = tcConstant;
      timeCalibErrors[rawId] = tcError;
    }
    else
    {
      //std::cout << "Cry: " << y <<", " << x << ", hash: " << itr->first
      //  << "\t Calib: " << p1 << "\t Error: " << p1err << std::endl;
      fileStreamProb << "Cry was calibrated to avg: " << x <<", " << y << ", hash: " << hashedIndex
        << "\t Calib: " << p1 << "\t Error: " << p1err << std::endl;
    }

    sigmaHistEE->Fill(cryCalib.stdDev);
    if(det.zside() < 0)
    {
      //calibsVsErrorsEEM->Fill(p1err, p1 > 0 ? p1 : -1*p1);
      calibErrorHistEEM->Fill(p1err);
      calibErrorMapEEM->Fill(x,y,p1err);
      sigmaMapEEM->Fill(x,y,cryCalib.stdDev);
    }
    else
    {
      //calibsVsErrorsEEP->Fill(p1err, p1 > 0 ? p1 : -1*p1);
      calibErrorHistEEP->Fill(p1err);
      calibErrorMapEEP->Fill(x,y,p1err);
      sigmaMapEEP->Fill(x,y,cryCalib.stdDev);
    }
  }
  
  fileStream.close();
  fileStreamProb.close();
  // Calc average
  if(numCrysCalibrated > 0)
    cryCalibAvg/=numCrysCalibrated;
  cryCalibAvg-= 2.0833; // Global phase shift
  // calibrate uncalibratable crys
  for(vector<int>::const_iterator hashItr = hashesToCalibrateToAvg.begin();
      hashItr != hashesToCalibrateToAvg.end(); ++hashItr)
  {
    //Store in timeCalibration container
    EcalTimeCalibConstant tcConstant = cryCalibAvg;
    EcalTimeCalibError tcError = 999;
    uint32_t rawId = EEDetId::unhashIndex(*hashItr);
    timeCalibConstants[rawId] = tcConstant;
    timeCalibErrors[rawId] = tcError;
  }

  //Write XML files
  cout << "Writing XML files." << endl;
  EcalCondHeader header;
  header.method_="testmethod";
  header.version_="testversion";
  header.datasource_="testdata";
  header.since_=123;
  header.tag_="testtag";
  header.date_="Mar 24 1973";
  string timeCalibFile = "EcalTimeCalibsEE.xml";
  string timeCalibErrFile = "EcalTimeCalibErrorsEE.xml";
  // Hack to prevent seg fault
  EcalTimeCalibConstant tcConstant = 0;
  EcalTimeCalibError tcError = 0;
  uint32_t rawId = EBDetId::unhashIndex(0);
  timeCalibConstants[rawId] = tcConstant;
  timeCalibErrors[rawId] = tcError;
  // End hack
  EcalTimeCalibConstantsXMLTranslator::writeXML(timeCalibFile,header,timeCalibConstants);
  EcalTimeCalibErrorsXMLTranslator::writeXML(timeCalibErrFile,header,timeCalibErrors);

  cout << "Writing histograms." << endl;
  outfile->cd();
  calibHistEEM->SetXTitle("timingCalib [ns]");
  calibHistEEM->Write();
  calibHistEEP->SetXTitle("timingCalib [ns]");
  calibHistEEP->Write();
  calibErrorHistEEP->SetXTitle("uncertainty on mean [ns]");
  calibErrorHistEEP->Write();
  calibErrorHistEEM->SetXTitle("uncertainty on mean [ns]");
  calibErrorHistEEM->Write();
  calibErrorMapEEP->Write();
  calibErrorMapEEM->Write();
  sigmaHistEE->Write();
  sigmaMapEEM->Write();
  sigmaMapEEP->Write();

  //can->Print("calibs1D.png");
  //cout << "Writing calibVsErrors" << endl;
  //calibsVsErrors->SetYTitle("AbsCalibConst");
  //calibsVsErrors->SetXTitle("calibConstError");
  //calibsVsErrors->Write();

  //Move empty bins out of the way
  int nxbins = calibMapEEM->GetNbinsX();
  int nybins = calibMapEEM->GetNbinsY();
  for(int i=0;i<=(nxbins+2)*(nybins+2); ++i)
  {
    double binentsM = calibMapEEM->GetBinContent(i);
    if(binentsM==0)
    {
      calibMapEEM->SetBinContent(i,-1000);
    }
    double binentsP = calibMapEEP->GetBinContent(i);
    if(binentsP==0)
    {
      calibMapEEP->SetBinContent(i,-1000);
    }
  }
  calibMapEEM->SetXTitle("ix");
  calibMapEEM->SetYTitle("iy");
  calibMapEEM->Write();
  calibMapEEP->SetXTitle("ix");
  calibMapEEP->SetYTitle("iy");
  calibMapEEP->Write();

  //calibSigmaHist->SetXTitle("#sigma_{cryTime} [ns]");
  //calibSigmaHist->Write();
  
  // Old hist, commented Jun 15 2009
  //avgAmpVsSigmaTHist->SetXTitle("#sigma_{cryTime} [ns]");
  //avgAmpVsSigmaTHist->SetYTitle("Avg. amp. [adc]");
  //avgAmpVsSigmaTHist->Write();
 
  //errorOnMeanVsNumEvtsHist->SetXTitle("Events");
  //errorOnMeanVsNumEvtsHist->SetYTitle("Error_on_mean [ns]");
  //TProfile* theProf = (TProfile*) errorOnMeanVsNumEvtsHist->ProfileX();
  //TF1* myFit = new TF1("myFit","[0]/sqrt(x)+[1]",0,50);
  //myFit->SetRange(0,50);
  ////theProf->Fit("myFit");
  //theProf->Write();
  //errorOnMeanVsNumEvtsHist->Write();
  //
  //chiSquaredEachEventHist->Write();
  //chiSquaredVsAmpEachEventHist->SetXTitle("amplitude [ADC]");
  //chiSquaredVsAmpEachEventHist->SetYTitle("#Chi^{2}");
  //chiSquaredVsAmpEachEventHist->Write();
  //chiSquaredHighMap->SetXTitle("iphi");
  //chiSquaredHighMap->SetYTitle("ieta");
  //chiSquaredHighMap->Write();
  //chiSquaredTotalHist->Write();
  //chiSquaredSingleOverTotalHist->Write();

  expectedStatPresHistEEM->Write();
  expectedStatPresVsObservedMeanErrHistEEM->Write();
  expectedStatPresEachEventHistEEM->Write();
  expectedStatPresHistEEP->Write();
  expectedStatPresVsObservedMeanErrHistEEP->Write();
  expectedStatPresEachEventHistEEP->Write();
  //ampEachEventHist->Write();
  //numPointsErasedHist->Write();
  hitsPerCryHistEEP->Write();
  hitsPerCryMapEEP->Write();
  hitsPerCryHistEEM->Write();
  hitsPerCryMapEEM->Write();
  ampProfileEEP->Write();
  ampProfileMapEEP->Write();
  ampProfileEEM->Write();
  ampProfileMapEEM->Write();
  
  //cout << "All done!  Close input." << endl;
  //f->Close();
  //cout << "Close output and quit!" << endl;
  outfile->Close();
  cout << "done." << endl;
}
//*************************************************************************************************
//Main part of the macro
//*************************************************************************************************
void NormalizeElectronNtuple(const string InputFilename, const string datasetName, 
                             const string OutputFilename, Int_t sampleType, 
                             const string normalizationFile = "") {


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

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

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

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

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

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

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

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

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

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

      useReweightFactor = kTRUE;    
    }

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

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

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

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

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

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

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

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

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

      useReweightFactor = kTRUE;    
    }

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

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



}
void make_SMS_exclusion(TH2F *rawlimits,TH2F *xsec,int scantype,std::string& scanx, bool isobserved) {
  TH2F *limits = prep_histo(rawlimits,scantype); // this is to be independent of the style used at creation time
  //here we get some limits and the cross section; we want to make an exclusion plot!
  TH2F *rellimits = (TH2F*)limits->Clone("rellimits");
  TH2F *rellimitsd3 = (TH2F*)limits->Clone("rellimitsd3"); // one third the cross section ("divided by 3" -> d3)
  TH2F *rellimitst3 = (TH2F*)limits->Clone("rellimitst3"); // three times the cross section ("times 3" -> t3)
  
  if(!xsec ) {
    cout << "Watch out, cross section map is invalid!" << endl;
    delete limits;
    return;
  }
  
  rellimits->Divide(xsec);
  
  
  for(int i=1;i<=rellimits->GetNbinsX();i++) {
    for(int j=1;j<=rellimits->GetNbinsY();j++) {
      rellimitst3->SetBinContent(i,j,(rellimits->GetBinContent(i,j))/3.0);
      rellimitsd3->SetBinContent(i,j,(rellimits->GetBinContent(i,j))*3.0);
    }
  }
  

//  TH2F *exclusionshape = make_exclusion_shape(rellimits,1);
//  TH2F *exclusionshapet3 = make_exclusion_shape(rellimitst3,2);
//  TH2F *exclusionshaped3 = make_exclusion_shape(rellimitsd3,3);
  
  //Now let's produce the plots!
  
  set_range(xsec,scantype,false);
  set_range(limits,scantype,false);
  limits->GetZaxis()->SetRangeUser(limits_lower_bound,limits_upper_bound);
  
  bool drawdoubleline=false; //draw nice thin line on top of thick outer line
  TGraph *exclline = MarcosExclusionLine(rellimits, scantype);
  TGraph *thinexcline = thin_line(exclline);
  
  TGraph *excllinet3 = MarcosExclusionLine(rellimitst3, scantype);
  excllinet3->SetLineStyle(2);
  TGraph *thinexclinet3 = thin_line(excllinet3);

  TGraph *excllined3 = MarcosExclusionLine(rellimitsd3, scantype);
  excllined3->SetLineStyle(3);
  TGraph *thinexclined3 = thin_line(excllined3);

//  produce_extensive_plots(xsec,limits,rellimits, rellimitst3, rellimitsd3,scantype);
  
  TCanvas *finalcanvas = new TCanvas("finalcanvas","finalcanvas");
  finalcanvas->SetLogz(1);
  finalcanvas->cd();
  limits->SetZTitle("95% CL upper limit on #sigma [pb]");
  limits->Draw("COLZ");

  TLine *desertline;
  if(drawefficiencydesertline) {
	desertline = new TLine(375,50,1200,875);
	desertline->SetLineWidth(3);
	//desertline->SetLineWidth(4); // paper style
	desertline->SetLineColor(kBlack);
	desertline->Draw("same");
  }


//  fill_with_text(exclline,excllined3,excllinet3,finalcanvas,scantype,scanx);
  stringstream real;
  real << "Limits/";
  if(!isobserved) real << "expected/expected_";
  real << "final_exclusion__" << limits->GetName();
  
  if(Contains(limits->GetName(),"bestlimits")) {
    cout << "----------> " << limits->GetName() << endl;
    TFile *f = new TFile("limits.root","RECREATE");
    thinexcline->SetName("ExclusionLine");
    limits->SetName("UpperLimits");
    limits->Write();
    thinexcline->Write();
    f->Close();
  }
  
  
  exclline->Draw("l");
  if(drawdoubleline) thinexcline->Draw("");
  excllinet3->Draw("");
  if(drawdoubleline) thinexclinet3->Draw("");
  excllined3->Draw("");
  if(drawdoubleline) thinexclined3->Draw("");
  
  CompleteSave(finalcanvas,real.str());

  
  
  //-------------------------------------- extensive plots 
  
  TCanvas *ca = new TCanvas("ca","ca",2400,1200);
  ca->Divide(4,2);
  ca->cd(1);
  ca->cd(1)->SetLogz(1);
  xsec->GetZaxis()->SetRangeUser(0.001,1000);
  xsec->Draw("COLZ");
  TText *title0 = write_title("Reference Cross Section");
  title0->Draw("same");
  ca->cd(2);
  ca->cd(2)->SetLogz(1);
  limits->GetZaxis()->SetRangeUser(limits_lower_bound,limits_upper_bound);
  limits->Draw("COLZ");
  TText *title = write_title("Cross Section Upper Limit");
  title->Draw("same");
  ca->cd(3);
  ca->cd(3)->SetLogz(1);
  TH2F *limit_ref = (TH2F*)limits->Clone("limit_ref");
  limit_ref->Divide(xsec);
  limit_ref->GetZaxis()->SetRangeUser(limits_ratio_lower_bound,limits_ratio_upper_bound);
  limit_ref->Draw("COLZ");
  TText *title2 = write_title("Cross Section UL / XS");
  title2->Draw("same");
  ca->cd(4);
  ca->cd(4)->SetLogz(1);
  limits->SetTitle("");
  limits->GetZaxis()->SetRangeUser(limits_lower_bound,limits_upper_bound);
  limits->SetZTitle("95% CL upper limit on #sigma [pb]");

  limits->Draw("COLZ");


  ca->cd(4);
  exclline->Draw();
  thinexcline->Draw();
  excllinet3->Draw();
  thinexclinet3->Draw();
  excllined3->Draw();
  thinexclined3->Draw();
  stringstream partial;
  partial << "Limits/";
  if(!isobserved) real << "expected/expected_";
  partial << "exclusion__" << limits->GetName();
  fill_with_text(exclline,excllined3,excllinet3,ca->cd(4),scantype);
//  CompleteSave(ca,partial.str());

  ca->cd(5);
  (hardlimit(rellimitsd3))->Draw("COL");
  TText *c = write_title("Exclusion shape for #sigma_{ref}/3");
  c->Draw();
  excllined3->Draw("same");
  
  ca->cd(6);
  (hardlimit(rellimits))->Draw("COL");
  exclline->Draw("same");
  TText *b = write_title("Exclusion shape for #sigma_{ref}");
  b->Draw();
  
  ca->cd(7);
  (hardlimit(rellimitst3))->Draw("COL");
  excllinet3->Draw("same");
  TText *a = write_title("Exclusion shape for 3x#sigma_{ref}");
  a->Draw();
  
  CompleteSave(ca,partial.str()+"__PlusInfo");
  delete ca;
  delete limits;
  
  //---------------------------------------</extensive plots>
  delete finalcanvas;
}
Exemple #28
0
//------------------------------------------------------------------------------
// DrawIt
//------------------------------------------------------------------------------
void DrawIt(TString filename,
	    TString hname,
	    TString cname,
	    TString title)
{
  TFile* inputfile = TFile::Open("../AuxiliaryFilesWZXS8TeV/" + filename + ".root");

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

  h->SetDirectory(0);

  inputfile->Close();

  TString name = h->GetName();

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

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

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

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

  h->Draw("colz");

  h->SetTitle("");

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

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

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

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

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

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

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

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

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


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

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

  palette->SetLabelFont(42);


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

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

  canvas->SaveAs("pdf/scale_factors/" + name + ".pdf");
  canvas->SaveAs("png/scale_factors/" + name + ".png");
}
void Analyzer::Loop(TChain *t,int type){ //type|=4 : compute lmin,lmax; type|=1 data type |=2 mc

		
		treeVarInt["nvtx"] = -999; t->SetBranchAddress("nvtx",&treeVarInt["nvtx"]);
		treeVar["rho"] = -999; t->SetBranchAddress("rho",&treeVar["rho"]);
		Float_t jetPt[4]; t->SetBranchAddress("jetPt",&jetPt);
		Float_t jetEnergy[4]; t->SetBranchAddress("jetEnergy",&jetEnergy);
		Float_t jetBtag[4]; t->SetBranchAddress("jetBtag",&jetBtag);
		Float_t jetBeta[4]; t->SetBranchAddress("jetBeta",&jetBeta);
		Float_t jetEta[4]; t->SetBranchAddress("jetEta",&jetEta);
		Float_t jetPhi[4]; t->SetBranchAddress("jetPhi",&jetPhi);
		Float_t jetAxis_QC[2][4]; t->SetBranchAddress("jetAxis_QC",&jetAxis_QC);
		Float_t jetAxis[2][4]; t->SetBranchAddress("jetAxis",&jetAxis);
		Float_t jetPtD[4]; t->SetBranchAddress("jetPtD",&jetPtD);
		Float_t jetPtD_QC[4]; t->SetBranchAddress("jetPtD_QC",&jetPtD_QC);
		Int_t jetChgPart_ptcut[4]; t->SetBranchAddress("jetChgPart_ptcut",&jetChgPart_ptcut);
		Int_t jetChgPart_QC[4]; t->SetBranchAddress("jetChgPart_QC",&jetChgPart_QC);
		Int_t jetNeutralPart_ptcut[4]; t->SetBranchAddress("jetNeutralPart_ptcut",&jetNeutralPart_ptcut);
		vector<int> *partonId=0;if(type >1)t->SetBranchAddress("partonId",&partonId);
		vector<int> *partonSt=0;if(type >1)t->SetBranchAddress("partonSt",&partonSt);
		vector<float> *partonPt=0;if(type >1)t->SetBranchAddress("partonPt",&partonPt);
		vector<float> *partonEta=0;if(type >1)t->SetBranchAddress("partonEta",&partonEta);
		vector<float> *partonPhi=0;if(type >1)t->SetBranchAddress("partonPhi",&partonPhi);
		vector<float> *partonE=0;if(type >1)t->SetBranchAddress("partonE",&partonE);
		
		vector<bool> *triggerResult=0;if(type ==1)t->SetBranchAddress("triggerResult",&triggerResult);
		
		
		if(type&4) {lmin=1.0;lmax=0;} //reset lmin-lmax
		if(type&1) {delete h_data; CreateHisto(1);}
		if(type&10) {delete h_mc; CreateHisto(2);} //8+2
		if(type&32) {varAll.clear();} //reset varAll

		for(int i=0;i<t->GetEntries() ;i++)
			{
			t->GetEntry(i);
			treeVar["ptJet0"]=jetPt[0];
			treeVar["etaJet0"]=jetEta[0];
			treeVar["rhoPF"]=treeVar["rho"];
			
			//fprintf(stderr,"A: Pt: %f<%f<%f - Eta: %f<%f<%f: Rho: %f<%f<%f\n",PtMin,treeVar["ptJet0"],PtMax,EtaMin,treeVar["etaJet0"],EtaMax,RhoMin,treeVar["rhoPF"],RhoMax);
			if((treeVar["ptJet0"]<PtMin)||(treeVar["ptJet0"]>PtMax)||(fabs(treeVar["etaJet0"])<EtaMin)||(fabs(treeVar["etaJet0"])>EtaMax)|| (treeVar["rhoPF"]<RhoMin)||(treeVar["rhoPF"]>RhoMax))continue;
			//fprintf(stderr,"-B\n");
			//selection
			double muJet_dphi=deltaPhi(jetPhi[0],jetPhi[1]);
			if(fabs(muJet_dphi)<2.5) continue;
			//fprintf(stderr,"--C\n");
			if( ! (2.0 *jetPt[2]/ (jetPt[0]+jetPt[1])<.3) )continue; 
			//fprintf(stderr,"---D\n");
			if( jetBtag[0] >0.244)continue;
			//fprintf(stderr,"----E\n");
			//trigger --only on data
			if( type==1 && !( triggerResult != NULL && triggerResult->size()>1 && triggerResult->at(1) )) continue;
			
			//parton Matching
			double dR_min=999;
			int pos_min=999;
			//int part_min=5;
			
			//fprintf(stderr,"_______not NULL: %ld = %ld = %ld\n",partonPt,partonEta,partonPhi);
			if(type>1){ //only on MC
			for(int iPart=0;iPart<partonPt->size();iPart++)
				{
				double dR_ipart= deltaR(partonEta->at(iPart),partonPhi->at(iPart),jetEta[0],jetPhi[0]);
				if(dR_ipart< dR_min){dR_min=dR_ipart;pos_min=iPart;}
				}
			}
			if(dR_min<.3){
				//fprintf(stderr,"_______%f<%f\n",pos_min,partonId->size());
				treeVarInt["pdgIdPartJet0"]=partonId->at(pos_min);
				} else treeVarInt["pdgIdPartJet0"]=0;
			
			//fprintf(stderr,"_______E2:pos_min=%d dR=%f\n",pos_min,dR_min);
			map<TString,float> variables_MLP;	
			map<TString,float> variables_corr_MLP;	
			//map<TString,float> variables_QGL;	
			
//			variables_QGL["axis1"]= jetAxis_QC[0][0];
//			variables_QGL["axis2"]= jetAxis_QC[1][0];
//			variables_QGL["ptd"] = jetPtD_QC[0];
//			variables_QGL["mult"] = jetChgPart_QC[0]+jetNeutralPart_ptcut[0];
//			variables_QGL["pt"] = jetPt[0];
//			variables_QGL["eta"] = jetEta[0];
//			variables_QGL["rho"] = rho;
	
			//fprintf(stderr,"_______E3:nvtx: %d\n",treeVarInt["nvtx"]);
			if(fabs(jetEta[0])<2.5 && (jetBeta[0]<(1.0 -0.2*TMath::Log(treeVarInt["nvtx"]-0.67)))) continue;	
			//fprintf(stderr,"-----F\n");
			float sub_data=0.0;
			if(fabs(jetEta[0])>2.5 && type==1)sub_data=1.0;
			//Variables as general variables
			treeVar["mult"]=float(jetChgPart_QC[0]+jetNeutralPart_ptcut[0])-sub_data;
			treeVar["axis1"]=jetAxis_QC[0][0];
			treeVar["axis2"]=jetAxis_QC[1][0];
			treeVar["ptD"]=jetPtD_QC[0];
			//Discriminators - only if needed -  save time
			if(varName=="QGLHisto")treeVar["QGLHisto"] = qgl->computeQGLikelihood2012(jetPt[0],jetEta[0],treeVar["rho"],jetChgPart_QC[0]+jetNeutralPart_ptcut[0]-sub_data,jetPtD_QC[0],jetAxis_QC[1][0]);
			if(varName=="QGLMLP"){	
				variables_MLP["axis1"]=jetAxis_QC[0][0];
				variables_MLP["axis2"]=jetAxis_QC[1][0];
				variables_MLP["ptD"]=jetPtD_QC[0];
				variables_MLP["mult"]=jetChgPart_QC[0];
				
				variables_MLP["pt"]=jetPt[0];
				variables_MLP["eta"]=jetEta[0];
				variables_MLP["rho"]=treeVar["rho"];
				
				if(fabs(jetEta[0])>2.5){
					variables_MLP["axis1"]=jetAxis[0][0];
					variables_MLP["axis2"]=jetAxis[1][0];
					variables_MLP["ptD"]=jetPtD[0];
					variables_MLP["mult"]=jetChgPart_QC[0]+jetNeutralPart_ptcut[0]-sub_data;
					
					}
				
				variables_corr_MLP["axis1"] = variables_MLP["axis1"];
				variables_corr_MLP["axis2"] = variables_MLP["axis2"];
				variables_corr_MLP["ptD"] = variables_MLP["ptD"];
				variables_corr_MLP["mult"] = variables_MLP["mult"];
			
				//variables_corr_MLP=qgmlp->TEST(variables_MLP,variables_corr_MLP);
				
				treeVar["QGLMLP"]=qgmlp->QGvalue(variables_MLP);
			}
			//treeVar["pdgIdPartJet0"];
			//---------------------------
		
			//fprintf(stderr,"------G\n");
			if(type&1){
				//printf("passed selection - type 1 --> %.3f - %.3f\n",treeVar[varName],treeVar[varName+"Fwd"]);
				string var=varName;
			//	if(EtaMin>2.5)var+="Fwd"; //only in data fwd
				alpha=1; beta=0;
					//int bin=puw->FindBin(treeVar["rho"]);
					//int bin2=ptetaw->FindBin(jetPt[0],fabs(jetEta[0]) );
					//float weight=puw->GetBinContent(bin) *  ptetaw->GetBinContent(bin2);
					treeVar["eventWeight"]=1.; //data
					treeVar["PUReWeight"]=1;
				FillHisto(h_data,var);
				}	
			if(type&2){
				//mc
			//fprintf(stderr,"________notNull:%ld %ld %f\n",puw,ptetaw,treeVar["rho"]);
					int bin = puw->FindBin(treeVar["rho"]);
					int bin2 = ptetaw->FindBin(jetPt[0],fabs(jetEta[0]) );
					float weight=puw->GetBinContent(bin) *  ptetaw->GetBinContent(bin2);
			//fprintf(stderr,"________bin:%d,%d, w=%f\n",bin,bin2,weight);
					treeVar["eventWeight"]=weight;treeVar["PUReWeight"]=1;
				FillHisto(h_mc,varName);
				}
			if(type&4){
				string var=varName;
				if(lmin>treeVar[var]) lmin=treeVar[var];
				if(lmax<treeVar[var]) lmax=treeVar[var];
				}
			if(type&8){
				alpha=1;beta=0;
				if( treeVarInt["pdgIdPartJet0"] ==21) {alpha=a_g;beta=b_g;}
				if( fabs(treeVarInt["pdgIdPartJet0"]) < 5) {alpha=a_q;beta=b_q;}
				if( fabs(treeVarInt["pdgIdPartJet0"])== 0) {alpha=1;beta=0;}

				FillHisto(h_mc,varName);
				}
			if(type&16){
				for(int j=0;j<int(alphaFast.size());j++)
					{
					alpha=alphaFast[j];
					beta=betaFast[j];
					FillHisto(h_mcFast[j],varName);
					}
				}
			if(type&32){ 
					int bin=puw->FindBin(treeVar["rho"]);
					int bin2=ptetaw->FindBin(jetPt[0],fabs(jetEta[0]) );
					float weight=puw->GetBinContent(bin) *  ptetaw->GetBinContent(bin2);
					varAll.push_back(TRIO(treeVarInt["pdgIdPartJet0"],treeVar[varName],weight)); //w=-1 default
				}
			}
}
Exemple #30
0
void makeCMSSMCards(){

  //---------------------------------------
  // load TChain
  //---------------------------------------
  
  TChain *ch = new TChain("t");
  ch->Add("output/V00-02-12/highpt/LMscanFall11dil_smallTree.root");
  char* version = "V00-00-08";
  bool doSigCont = true;

  //---------------------------------------
  // selection
  //---------------------------------------

  //TCut weight   ("weight * 4.7 * ndavtxweight * trgeff * lepscale");
  TCut weight   ("weight * 4.7 * ndavtxweight * trgeff * lepscale * ( 1 - sqrt(pow(ksusyup/ksusy-1,2)+0.2*0.2) )");
  //TCut weightkup("weight * 4.7 * ndavtxweight * trgeff * lepscale * ksusyup/ksusy");
  //TCut weightkdn("weight * 4.7 * ndavtxweight * trgeff * lepscale * ksusydn/ksusy");
  TCut presel("pfmet>50 && njets>=2 && ht>100 && !passz");
  TCut preselptll("pfmet>50 && njets>=2 && ht>100 && !passz && ( (leptype==2) || (leptype<2 && pfmet>75) )");
  TCut preseljup("pfmetUp>50   && njetsUp>=2   && htUp>100   && !passz");
  TCut preseljdn("pfmetDown>50 && njetsDown>=2 && htDown>100 && !passz");
  TCut SF("leptype==0 || leptype==1");
  TCut OF("leptype==2");

  TCut sig("(ht>300 && pfmet>275) || (ht>600 && pfmet>200)");  
  TCut sigdn("(htDown>300 && pfmetDown>275) || (htDown>600 && pfmetDown>200)");

  TCut SR1("ht>300 && ht<600 && pfmet>275");
  TCut SR2("ht>600 && pfmet>275");
  TCut SR3("ht>600 && pfmet>200 && pfmet<275");

  TCut SR1ptll("ht>300 && ht<600 && dilpt>275");
  TCut SR2ptll("ht>600 && dilpt>275");
  TCut SR3ptll("ht>600 && dilpt>200 && dilpt<275");

  TCut SR1jup("htUp>300 && htUp<600 && pfmetUp>275");
  TCut SR2jup("htUp>600 && pfmetUp>275");
  TCut SR3jup("htUp>600 && pfmetUp>200 && pfmetUp<275");

  TCut SR1ptlljup("htUp>300 && htUp<600 && dilpt>275");
  TCut SR2ptlljup("htUp>600 && dilpt>275");
  TCut SR3ptlljup("htUp>600 && dilpt>200 && dilpt<275");

  TCut SR1jdn("htDown>300 && htDown<600 && pfmetDown>275");
  TCut SR2jdn("htDown>600 && pfmetDown>275");
  TCut SR3jdn("htDown>600 && pfmetDown>200 && pfmetDown<275");

  TCut SR1ptlljdn("htDown>300 && htDown<600 && dilpt>275");
  TCut SR2ptlljdn("htDown>600 && dilpt>275");
  TCut SR3ptlljdn("htDown>600 && dilpt>200 && dilpt<275");

  //---------------------------------------
  // preselection and SR1,SR2,SR3 yields
  //---------------------------------------

  const int   nm0points    = 100;
  const float m0min        = 20.;
  const float m0max        = 2020.;
  const int   nm12points   = 38;
  const float m12min       = 20.;
  const float m12max       = 780.;

  const unsigned int nbins = 6;

  float KKC[nbins] = { 2.74 , 2.74 , 2.59 , 2.59 , 1.81 , 1.81 };

  TH2F* h[nbins];
  TH2F* hptll[nbins];
  TH2F* hjup[nbins];
  TH2F* hjdn[nbins];
  TH2F* hptlljup[nbins];
  TH2F* hptlljdn[nbins];
  TH2F* hkup[nbins];
  TH2F* hkdn[nbins];

  for( unsigned int i = 0 ; i < nbins ; ++i ){
    h[i]        = new TH2F( Form("h_%i",i)        , Form("h_%i",i)           , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);
    hjup[i]     = new TH2F( Form("hjup_%i",i)     , Form("hjup_%i",i)        , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);
    hjdn[i]     = new TH2F( Form("hjdn_%i",i)     , Form("hjdn_%i",i)        , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);
    hkup[i]     = new TH2F( Form("hkup_%i",i)     , Form("hkup_%i",i)        , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);
    hkdn[i]     = new TH2F( Form("hkdn_%i",i)     , Form("hkdn_%i",i)        , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);
    hptll[i]    = new TH2F( Form("hptll_%i",i)    , Form("hptll_%i",i)       , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);
    hptlljup[i] = new TH2F( Form("hptlljup_%i",i) , Form("hptlljup_%i",i)    , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);
    hptlljdn[i] = new TH2F( Form("hptlljdn_%i",i) , Form("hptlljdn_%i",i)    , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);

    h[i]    ->Sumw2();
    hjup[i] ->Sumw2();
    hjdn[i] ->Sumw2();
    hkup[i] ->Sumw2();
    hkdn[i] ->Sumw2();

    hptll[i]->Sumw2();
    hptlljup[i]->Sumw2();
    hptlljdn[i]->Sumw2();
  }

  TH2F* hall    = new TH2F( "hall"    , "hall"    , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);
  TH2F* hkupall = new TH2F( "hkupall" , "hkupall" , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);
  TH2F* hjdnall = new TH2F( "hjdnall" , "hjdnall" , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);
  TH2F* hkdnall = new TH2F( "hkdnall" , "hkdnall" , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);
  
  hall->Sumw2();
  hkupall->Sumw2();
  hkdnall->Sumw2();

  TCanvas *ctemp = new TCanvas();
  ctemp->cd();

  //nominal
  cout << "Filling nominal histos" << endl;
  ch->Draw("m12:m0>>h_0"        , (presel + SR1 + SF) * weight );
  ch->Draw("m12:m0>>h_1"        , (presel + SR1 + OF) * weight );
  ch->Draw("m12:m0>>h_2"        , (presel + SR2 + SF) * weight );
  ch->Draw("m12:m0>>h_3"        , (presel + SR2 + OF) * weight );
  ch->Draw("m12:m0>>h_4"        , (presel + SR3 + SF) * weight );
  ch->Draw("m12:m0>>h_5"        , (presel + SR3 + OF) * weight );
  ch->Draw("m12:m0>>hall"       , (presel + sig     ) * weight );
  
  ch->Draw("m12:m0>>hptll_0"    , (preselptll + SR1ptll) * weight );
  ch->Draw("m12:m0>>hptll_1"    , (preselptll + SR1ptll) * weight );
  ch->Draw("m12:m0>>hptll_2"    , (preselptll + SR2ptll) * weight );
  ch->Draw("m12:m0>>hptll_3"    , (preselptll + SR2ptll) * weight );
  ch->Draw("m12:m0>>hptll_4"    , (preselptll + SR3ptll) * weight );
  ch->Draw("m12:m0>>hptll_5"    , (preselptll + SR3ptll) * weight );

  //JES up
  cout << "Filling JES up histos" << endl;
  ch->Draw("m12:m0>>hjup_0"     , (preseljup + SR1jup + SF) * weight );
  ch->Draw("m12:m0>>hjup_1"     , (preseljup + SR1jup + OF) * weight );
  ch->Draw("m12:m0>>hjup_2"     , (preseljup + SR2jup + SF) * weight );
  ch->Draw("m12:m0>>hjup_3"     , (preseljup + SR2jup + OF) * weight );
  ch->Draw("m12:m0>>hjup_4"     , (preseljup + SR3jup + SF) * weight );
  ch->Draw("m12:m0>>hjup_5"     , (preseljup + SR3jup + OF) * weight );
  
  //JES down
  cout << "Filling JES dn histos" << endl;
  ch->Draw("m12:m0>>hjdn_0"     , (preseljdn + SR1jdn + SF) * weight );
  ch->Draw("m12:m0>>hjdn_1"     , (preseljdn + SR1jdn + OF) * weight );
  ch->Draw("m12:m0>>hjdn_2"     , (preseljdn + SR2jdn + SF) * weight );
  ch->Draw("m12:m0>>hjdn_3"     , (preseljdn + SR2jdn + OF) * weight );
  ch->Draw("m12:m0>>hjdn_4"     , (preseljdn + SR3jdn + SF) * weight );
  ch->Draw("m12:m0>>hjdn_5"     , (preseljdn + SR3jdn + OF) * weight );
  ch->Draw("m12:m0>>hjdnall"    , (preseljdn + sigdn      ) * weight );
  
  //k-factor up
  // cout << "Filling k up histos" << endl;
  // ch->Draw("m12:m0>>hkup_0"     , (presel + SR1 + SF) * weightkup );
  // ch->Draw("m12:m0>>hkup_1"     , (presel + SR1 + OF) * weightkup );
  // ch->Draw("m12:m0>>hkup_2"     , (presel + SR2 + SF) * weightkup );
  // ch->Draw("m12:m0>>hkup_3"     , (presel + SR2 + OF) * weightkup );
  // ch->Draw("m12:m0>>hkup_4"     , (presel + SR3 + SF) * weightkup );
  // ch->Draw("m12:m0>>hkup_5"     , (presel + SR3 + OF) * weightkup );
  // ch->Draw("m12:m0>>hkupall"    , (presel + sig     ) * weightkup );
  
  //k-factor down
  // cout << "Filling k down histos" << endl;
  // ch->Draw("m12:m0>>hkdn_0"     , (presel + SR1 + SF) * weightkdn );
  // ch->Draw("m12:m0>>hkdn_1"     , (presel + SR1 + OF) * weightkdn );
  // ch->Draw("m12:m0>>hkdn_2"     , (presel + SR2 + SF) * weightkdn );
  // ch->Draw("m12:m0>>hkdn_3"     , (presel + SR2 + OF) * weightkdn );
  // ch->Draw("m12:m0>>hkdn_4"     , (presel + SR3 + SF) * weightkdn );
  // ch->Draw("m12:m0>>hkdn_5"     , (presel + SR3 + OF) * weightkdn );
  // ch->Draw("m12:m0>>hkdnall"    , (presel + sig     ) * weightkdn );

  delete ctemp;

  ofstream* doScript = new ofstream();
  doScript->open(Form("cards/%s/doLimits.sh",version));

  ofstream* doScript_CLs = new ofstream();
  doScript_CLs->open(Form("cards/%s/doLimits_CLs.sh",version));

  ofstream* doScript_CLs1 = new ofstream();
  doScript_CLs1->open(Form("cards/%s/doLimits_CLs1.sh",version));

  ofstream* doScript_CLs2 = new ofstream();
  doScript_CLs2->open(Form("cards/%s/doLimits_CLs2.sh",version));

  ofstream* doScript_CLs3 = new ofstream();
  doScript_CLs3->open(Form("cards/%s/doLimits_CLs3.sh",version));

  ofstream* doScript_CLs4 = new ofstream();
  doScript_CLs4->open(Form("cards/%s/doLimits_CLs4.sh",version));

  ofstream* filelist = new ofstream();
  filelist->open(Form("cards/%s/file_list.txt",version));

  ofstream* filelist_CLs = new ofstream();
  filelist_CLs->open(Form("cards/%s/file_list_CLs.txt",version));

  //------------------------------------------
  // open histogram of #entries/CMSSM point
  //------------------------------------------

  // TFile* corfile = TFile::Open("mSUGRA_m0-20to2000_m12-20to760_tanb-10andA0-0.root");
  // TH2F*  hscan   = (TH2F*) corfile->Get("hscan");
  
  // if( hscan == 0 ){
  //   cout << "Can't find TH2 hscan!!!" << endl;
  //   exit(0);
  // }

  //------------------------------------------
  // loop over CMSSM points
  //------------------------------------------

  int counter = 0;

  for( int m0bin = 1 ; m0bin <= hall->GetXaxis()->GetNbins() ; m0bin++ ){
    for( int m12bin = 1 ; m12bin <= hall->GetYaxis()->GetNbins() ; m12bin++ ){

      //------------------------------------------
      // require nentries = 10
      //------------------------------------------
      
      //int ngen = hscan->GetBinContent(m0bin,m12bin);
      //if( ngen != 10000 )  continue;
      
      int m0  = hall->GetXaxis()->GetBinCenter(m0bin);
      int m12 = hall->GetXaxis()->GetBinCenter(m12bin);

      //if( m0 > 1000 )                                  continue;
      if( hjdnall->GetBinContent(m0bin,m12bin) < 1e-10 ) continue;


      float nom = hall->GetBinContent(m0bin,m12bin);
      float kdn = hkupall->GetBinContent(m0bin,m12bin);
      float kup = hkdnall->GetBinContent(m0bin,m12bin);
	     
      float dup = kup / nom - 1;
      float ddn = 1 - kdn / nom;
      float kerr = 0.5 * ( dup + ddn );

      //---------------------------------------
      // make root file
      //---------------------------------------

      TH1F* histo_CMSSM               = new TH1F( Form("histo_CMSSM_%i_%i"              ,m0bin,m12bin) , Form("histo_CMSSM_%i_%i"              ,m0bin,m12bin) , nbins,0,nbins);
      TH1F* histo_CMSSM_JES_shapeUp   = new TH1F( Form("histo_CMSSM_%i_%i_JES_shapeUp"  ,m0bin,m12bin) , Form("histo_CMSSM_%i_%i_JES_shapeUp"  ,m0bin,m12bin) , nbins,0,nbins);
      TH1F* histo_CMSSM_JES_shapeDown = new TH1F( Form("histo_CMSSM_%i_%i_JES_shapeDown",m0bin,m12bin) , Form("histo_CMSSM_%i_%i_JES_shapeDown",m0bin,m12bin) , nbins,0,nbins);

      float sigtot    = 0;
      float sigtotjdn = 0;

      for( unsigned int ibin = 0 ; ibin < nbins ; ibin++ ){
	float yieldnom = h[ibin]->GetBinContent(m0bin,m12bin);
	float yieldjup = hjup[ibin]->GetBinContent(m0bin,m12bin);
	float yieldjdn = hjdn[ibin]->GetBinContent(m0bin,m12bin);

	if( doSigCont ){
	  float ptll = hptll[ibin]->GetBinContent(m0bin,m12bin) * 0.5 * KKC[ibin];

	  if( ptll < yieldnom ){
	    float scale = (yieldnom-ptll)/yieldnom;
	    yieldnom -= ptll;
	    yieldjup *= scale;
	    yieldjdn *= scale;
	  }
	  
	  else{
	    yieldnom = 0.0;
	    yieldjup = 0.0;
	    yieldjdn = 0.0;
	  }

	}

	sigtot    += yieldnom;
	sigtotjdn += yieldjdn;

	histo_CMSSM->SetBinContent              ( ibin + 1 , yieldnom );
	histo_CMSSM_JES_shapeUp->SetBinContent  ( ibin + 1 , yieldjup );
	histo_CMSSM_JES_shapeDown->SetBinContent( ibin + 1 , yieldjdn );
      }

      if( sigtotjdn < 1e-10 ) continue;
      if( sigtot    < 2     ) continue;
      if( sigtot    > 80    ) continue;

      //float sigtot = hall->GetBinContent(m0bin,m12bin);

      counter++;

      char* fitoptions = "-M Hybrid --freq  --nToysForCLsb 1500 --nToysForCLb 500  --scanRs 1 -vR [0.2,5,x1.1]";
      //char* fitoptions = "-M Hybrid --freq --ExpectationHints Asymptotic --scanRs 1 --freq --nToysForCLsb 3000 --nToysForCLb 1500 --seed 1234 -rMin 0 -rMax 5";

      *doScript << Form("../../../../test/lands.exe -M Bayesian -d CMSSM_%i_%i.txt",m0bin,m12bin)         << endl;

      *doScript_CLs << Form("../../../../test/lands.exe -d CMSSM_%i_%i.txt %s  -n CMSSM_%i_%i",m0bin,m12bin,fitoptions,m0bin,m12bin) << endl;

       if( counter%4 == 0 ) *doScript_CLs1 << Form("../../../../test/lands.exe -d CMSSM_%i_%i.txt %s  -n CMSSM_%i_%i",m0bin,m12bin,fitoptions,m0bin,m12bin) << endl;

       if( counter%4 == 1 ) *doScript_CLs2 << Form("../../../../test/lands.exe -d CMSSM_%i_%i.txt %s  -n CMSSM_%i_%i",m0bin,m12bin,fitoptions,m0bin,m12bin) << endl;

       if( counter%4 == 2 ) *doScript_CLs3 << Form("../../../../test/lands.exe -d CMSSM_%i_%i.txt %s  -n CMSSM_%i_%i",m0bin,m12bin,fitoptions,m0bin,m12bin) << endl;

       if( counter%4 == 3 ) *doScript_CLs4 << Form("../../../../test/lands.exe -d CMSSM_%i_%i.txt %s  -n CMSSM_%i_%i",m0bin,m12bin,fitoptions,m0bin,m12bin) << endl;

      *filelist << Form("cards/%s/CMSSM_%i_%i.txt_Bayesian_bysObsLimit.root",version,m0bin,m12bin)        << endl;

      *filelist_CLs << Form("cards/%s/CMSSM_%i_%i_m2lnQ2.root",version,m0bin,m12bin)        << endl;

      printCard( Form("CMSSM_%i_%i",m0bin,m12bin) , sigtot , 1+kerr , version );
      
      //signal regions                         R1(SF)      R1(OF)    R2(SF)     R2(OF)      R3(SF)   R3(OF)
      int     data_yield[nbins]           = {    9     ,    10    ,    6     ,    5     ,     5    ,    13  };
      float   bkg_yield[nbins]            = {   5.7    ,    5.7   ,   5.2    ,   5.2    ,    5.6   ,   5.6  };
      float   bkg_syst[nbins]             = {   2.8    ,    2.8   ,   1.9    ,   1.9    ,    2.1   ,   2.1  };
      float   bkg_stat[nbins]             = {   5.1    ,    5.1   ,   4.1    ,   4.1    ,    3.4   ,   3.4  };

      TH1F* histo_Data = new TH1F("histo_Data","histo_Data",nbins,0,nbins);

      for( unsigned int ibin = 0 ; ibin < nbins ; ibin++){
	histo_Data->SetBinContent( ibin+1 , data_yield[ibin] );
      }

      TH1F* histo_bkg               = new TH1F("histo_bkg","histo_bkg",nbins,0,nbins);
      TH1F* histo_bkg_statUp        = new TH1F("histo_bkg_statUp"  ,"histo_bkg_statUp"  ,nbins,0,nbins);
      TH1F* histo_bkg_statDown      = new TH1F("histo_bkg_statDown","histo_bkg_statDown",nbins,0,nbins);
      TH1F* histo_bkg_systUp        = new TH1F("histo_bkg_systUp"  ,"histo_bkg_systUp"  ,nbins,0,nbins);
      TH1F* histo_bkg_systDown      = new TH1F("histo_bkg_systDown","histo_bkg_systDown",nbins,0,nbins);
      
      for( unsigned int ibin = 0 ; ibin < nbins ; ibin++){
	histo_bkg               -> SetBinContent(ibin+1,bkg_yield[ibin]);
	histo_bkg_statUp        -> SetBinContent(ibin+1, bkg_yield[ibin] + bkg_stat[ibin] );
	histo_bkg_statDown      -> SetBinContent(ibin+1, TMath::Max(bkg_yield[ibin] - bkg_stat[ibin],(float)0.0) );
	histo_bkg_systUp        -> SetBinContent(ibin+1, bkg_yield[ibin] + bkg_syst[ibin] );
	histo_bkg_systDown      -> SetBinContent(ibin+1, TMath::Max(bkg_yield[ibin] - bkg_syst[ibin],(float)0.0) );
      }


      TFile *f = TFile::Open( Form("rootfiles/%s/CMSSM_%i_%i.root",version,m0bin,m12bin) , "RECREATE");
      f->cd();
      histo_Data->Write();
      histo_bkg->Write();
      histo_bkg_statUp->Write();
      histo_bkg_statDown->Write();
      histo_bkg_systUp->Write();
      histo_bkg_systDown->Write();
      histo_CMSSM->Write();
      histo_CMSSM_JES_shapeUp->Write();
      histo_CMSSM_JES_shapeDown->Write();
      f->Close();

      delete histo_Data;
      delete histo_bkg;
      delete histo_bkg_statUp;
      delete histo_bkg_statDown;
      delete histo_bkg_systUp;
      delete histo_bkg_systDown;
      delete histo_CMSSM;
      delete histo_CMSSM_JES_shapeUp;
      delete histo_CMSSM_JES_shapeDown;
    }
  }

  doScript->close();
  filelist->close();

}