示例#1
0
LjmetEventContent::~LjmetEventContent(){

  // save tree
  mpTree->Write();

  // save histograms
  std::map<std::string,std::map<std::string,LjmetEventContent::HistMetadata> >::iterator iMod;
  std::map<std::string,LjmetEventContent::HistMetadata>::iterator iHist;
  TDirectory * rootDir = mpTree->GetDirectory();
  for (iMod=mDoubleHist.begin();iMod!=mDoubleHist.end();++iMod){
    TDirectory * _dir = 0;
    _dir = rootDir->mkdir( iMod->first.c_str() );
    if (!_dir) rootDir->GetDirectory( iMod->first.c_str() );
    for (iHist=iMod->second.begin();iHist!=iMod->second.end();++iHist){
      std::cout << mLegend
		<< "Saving " << iMod->first << "/"
		<< iHist->second.GetName() << std::endl;
      _dir->cd();
      iHist->second.GetHist( )->SetDirectory(_dir);
      iHist->second.GetHist( )->Print();
      iHist->second.GetHist( )->Write();
    }
  }

}
示例#2
0
void CopyDir(TDirectory *source) {
   //copy all objects and subdirs of directory source as a subdir of the current directory   
   source->ls();
   TDirectory *savdir = gDirectory;
   TDirectory *adir = savdir->mkdir(source->GetName());
   adir->cd();
   //loop on all entries of this directory
   TKey *key;
   TIter nextkey(source->GetListOfKeys());
   while ((key = (TKey*)nextkey())) {
      const char *classname = key->GetClassName();
      TClass *cl = gROOT->GetClass(classname);
      if (!cl) continue;
      if (cl->InheritsFrom(TDirectory::Class())) {
         source->cd(key->GetName());
         TDirectory *subdir = gDirectory;
         adir->cd();
         CopyDir(subdir);
         adir->cd();
      } else if (cl->InheritsFrom(TTree::Class())) {
         TTree *T = (TTree*)source->Get(key->GetName());
         adir->cd();
         TTree *newT = T->CloneTree(-1,"fast");
         newT->Write();
      } else {
         source->cd();
         TObject *obj = key->ReadObj();
         adir->cd();
         obj->Write();
         delete obj;
     }
  }
  adir->SaveSelf(kTRUE);
  savdir->cd();
}
示例#3
0
/**
 * @brief Write all TObjects from a given TCollection into a certain directory structure in the file
 *
 * @param col pointer to a TCollection-based container
 * @param dirname name of a directory inside the output file to which the objects should be written
 * @param subdirname optional name of a subdirectory inside dirname to which the objects should be written
 *
 * This method whites all TObject-based objects contained in the TCollection-based container (see ROOT documentation)
 * into a directory whose name is given by dirname inside the output file. If dirname does not exist
 * in the output file, it will be created. Otherwise, contents of the col collection will be appended to an existing
 * directory.
 *
 * If the optional subdirectory name is specified (subdirname parameter, defaults to empty string) then the
 * contents of the collection will be written to "dirname/subdirname". If the "subdirname" directory does not
 * exist inside the "dirname" directory, it will be created.
 *
 */
void JPetWriter::writeCollection(const TCollection* col, const char* dirname, const char* subdirname)
{

  TDirectory* current =  fFile->GetDirectory(dirname);

  if (!current) {
    current = fFile->mkdir(dirname);
  }

  assert(current);

  // use a subdirectory if requested by user
  if (!std::string(subdirname).empty()) {

    if (current->GetDirectory(subdirname)) {
      current = current->GetDirectory(subdirname);
    } else {
      current = current->mkdir(subdirname);
    }
  }

  assert(current);

  current->cd();

  TIterator* it = col->MakeIterator();

  TObject* obj;
  while ((obj = it->Next())) {
    obj->Write();
  }

  fFile->cd();
}
示例#4
0
文件: store.C 项目: XuQiao/HI
void store(){
	 if (!TClass::GetDict("NBD")) {
                gROOT->ProcessLine(".L /afs/cern.ch/user/q/qixu/CMSSW_6_2_5/src/Centrality/NBD_Glauber_fit/NBD/NBDclass.C+");
        }
	TH1::AddDirectory(kFALSE); 
	int Gth=atoi(getenv("GTH"));
	int sth=atoi(getenv("STH"));
	NBD *l;
	struct para1 var;
        if(sth==0){TString dirname = "std"; var = var1; if(Gth<nGlau) l = new NBD(datafile,stdGlaulist[Gth],histoname);else l = new NBD(datafile,stdGlaulist[0],histoname);}
        else if(sth==1){TString dirname ="Gri055"; var = var2; if(Gth<nGlau) l = new NBD(datafile,Gri055Glaulist[Gth],histoname);else l = new NBD(datafile,Gri055Glaulist[0],histoname);}
        else {TString dirname ="Gri101"; var = var3; if(Gth<nGlau) l = new NBD(datafile,Gri101Glaulist[Gth],histoname);else l = new NBD(datafile,Gri101Glaulist[0],histoname);}
	l->initmu(var.mumin,var.mumax,var.mustep);
     	l->initk(var.kmin,var.kmax,var.kstep);
	if(Gth<nGlau)
        	l->initx(var.xmin,var.xmax);
	else if(Gth-nGlau==0)
		l->initx(var.xmin-binshift,var.xmax);
	else
		l->initx(var.xmin+binshift,var.xmax);
//	l->fit();

 	if(sth==0) l->assign(bestlist1[Gth].mubest,bestlist1[Gth].kbest);
	else if(sth==1) l->assign(bestlist2[Gth].mubest,bestlist2[Gth].kbest);
	else l->assign(bestlist3[Gth].mubest,bestlist3[Gth].kbest);

        l->initN(bin,N,method);
        l->calcvar();
	TFile *outfile = new TFile(outG,"Update");
	if(Gth==0 && sth==0){
	l->dataname.Write("dataname",TObject::kOverwrite);
	l->histoname.Write("histoname",TObject::kOverwrite);
	}
	TDirectory *dir = outfile->GetDirectory(dirname);
	if (!dir) {outfile->mkdir(dirname);	TDirectory *dir = outfile->GetDirectory(dirname);}
	dir->cd();
	TString name;
	if(Gth==0)
		name = "G0";
	else if(Gth<nGlau)
		name = Form("Glau_%d",Gth);
	else
		name = Form("bin_%d",Gth-nGlau+1);
	TDirectory *subdir = dir->GetDirectory(name);
	if(!subdir) {dir->mkdir(name);	TDirectory *subdir = dir->GetDirectory(name);}
	subdir->cd();
	l->method.Write("method",TObject::kOverwrite);
	l->Glaubername.Write("Glaubername",TObject::kOverwrite);
	l->xmin.Write("xmin",TObject::kOverwrite);l->xmax.Write("xmax",TObject::kOverwrite);
	l->mubest.Write("mubest",TObject::kOverwrite);l->kbest.Write("kbest",TObject::kOverwrite);
	l->chis.Write("chis",TObject::kOverwrite);l->Ndf.Write("Ndf",TObject::kOverwrite);
	l->NcollAver.Write("NcollAver",TObject::kOverwrite);l->NpartAver.Write("NpartAver",TObject::kOverwrite);l->BAver.Write("BAver",TObject::kOverwrite);
	l->centbin.Write("centbin",TObject::kOverwrite);	l->kpoint.Write("kpoint",TObject::kOverwrite);
	l->centbin_.Write("centbin_",TObject::kOverwrite);	l->kpoint_.Write("kpoint_",TObject::kOverwrite);
	l->Npartdis->Write();
        l->Grgrid->Write("Grgrid",TObject::kOverwrite);
        outfile->Close();

}
示例#5
0
void	drift_efficiency()
{
	TDirectory	*rootdir = gDirectory;
	TFile	f(gSystem->Getenv("EPECUR_ROOTFILE2"), "READ");
	TTree	*events = (TTree*)f.Get("events");
	rootdir->cd();

	c2.Divide(2, 2);
	c3.Divide(2, 2);

	rootdir->mkdir("lx")->cd();
	make_drift_efficiency_hist('l', 'X', events);
	rootdir->mkdir("ly")->cd();
	make_drift_efficiency_hist('l', 'Y', events);
	rootdir->mkdir("rx")->cd();
	make_drift_efficiency_hist('r', 'X', events);
	rootdir->mkdir("ry")->cd();
	make_drift_efficiency_hist('r', 'Y', events);

	c1.Show();
	c2.Show();
	c3.Show();
}
示例#6
0
void copy(const std::string& src_file, const std::string& src_obj, const std::string& des_file, const std::string& des_path, const std::string& des_obj) {

  gStyle->SetPalette(1,0);

  TFile *old_file = new TFile(src_file.c_str());
  if (!old_file) {
    std::cerr << "Can not open file: " << src_file << std::endl;
    return;
  }

  TObject* old_obj = old_file->Get(src_obj.c_str());
  if (!old_obj) {
    std::cerr << "Can not open object: " << src_obj << " in file " << src_file << std::endl;
    return;
  }

  TFile *new_file = new TFile(des_file.c_str(), "RECREATE");
  TDirectory *cdto = 0;

  std::vector<std::string> tokens;
  splitString(des_path, "/", tokens);
  for (unsigned int i = 0; i < tokens.size(); i++) {
    if (cdto == 0) {
      cdto = new_file->mkdir(tokens.at(i).c_str());
    } else {
      cdto = cdto->mkdir(tokens.at(i).c_str());
    }
    cdto->cd();
  }

  TObject *new_obj = dynamic_cast<TObject*> (old_obj->Clone(des_obj.c_str()));

  if (new_obj->IsA()->InheritsFrom("TH2")) {
    TH2* h2 = (TH2*) new_obj;
    if (h2) {
      if(h2->GetXaxis()->GetXmin() <= 1 && h2->GetXaxis()->GetXmax() >= 36 &&
         h2->GetYaxis()->GetXmin() <= 1 && h2->GetYaxis()->GetXmax() >= 18) {

        //fillCellsWithRowNeighbourAverage(h2);
        fillCellsWithRowAverage(h2);
        h2->Draw("colz");

      }
    }
  }

  new_file->Write();

}
示例#7
0
void importdir(const char *dirname) {
	//Example of script showing how to create a ROOT file with subdirectories.
	//The script scans a given directory tree and recreates the
	//same structure in the ROOT file.
	//All source files of type .h,cxx,c,dat,py are imported as TMacro objects
	//see also other tutorial readCode.C
	//Author: Rene Brun
	                   
	char *slash = (char*)strrchr(dirname,'/');
	char *locdir;
	if (slash) locdir = slash+1;
	else       locdir = (char*)dirname;
	printf("processing dir %s\n",dirname);
	TDirectory *savdir = gDirectory;
	TDirectory *adir = savdir->mkdir(locdir);
	adir->cd();
	void *dirp = gSystem->OpenDirectory(dirname);
	if (!dirp) return;
	char *direntry;
	Long_t id, size,flags,modtime;
	//loop on all entries of this directory
	while ((direntry=(char*)gSystem->GetDirEntry(dirp))) {
		TString afile = Form("%s/%s",dirname,direntry);
		gSystem->GetPathInfo(afile,&id,&size,&flags,&modtime);
		if (direntry[0] == '.')             continue; //forget the "." and ".." special cases
		if (!strcmp(direntry,"CVS"))        continue; //forget some special directories
		if (!strcmp(direntry,"htmldoc"))    continue;
		if (strstr(dirname,"root/include")) continue;
		if (strstr(direntry,"G__"))         continue;
		if (strstr(direntry,".c")    ||
				strstr(direntry,".h")    ||
				strstr(direntry,".dat")  ||
				strstr(direntry,".py")   ||
				strstr(direntry,".C")) {
			TMacro *m = new TMacro(afile);
			m->Write(direntry);
			delete m;
		} else {
			if (flags != 3)                     continue; //must be a directory
			//we have found a valid sub-directory. Process it
			importdir(afile);
		}
	}
	gSystem->FreeDirectory(dirp);
	savdir->cd();
}
void make(TDirectory & out, TObject * o) {
  TDirectory * dir;
  TH1F * th1f;
  TH1D * th1d;
  TH2F * th2f;
  TH2D * th2d;
  out.cd();
  if((dir = dynamic_cast<TDirectory*>(o)) != 0) {
    TDirectory * outDir = out.mkdir(dir->GetName(), dir->GetTitle());
    TIter next(dir->GetListOfKeys());
    TKey *key;
    while( (key = dynamic_cast<TKey*>(next())) ) {
      string className(key->GetClassName());
      string name(key->GetName());
      TObject * obj = dir->Get(name.c_str());
      if(obj == 0) {
	cerr <<"error: key " << name << " not found in directory " << dir->GetName() << endl;
	exit(-1);
      }
      make(*outDir, obj);
    }
  } else if((th1f = dynamic_cast<TH1F*>(o)) != 0) {
    TH1F *h = (TH1F*) th1f->Clone();
    h->Reset();
    h->Sumw2();
    h->SetDirectory(&out);
  } else if((th1d = dynamic_cast<TH1D*>(o)) != 0) {
    TH1D *h = (TH1D*) th1d->Clone();
    h->Reset();
    h->Sumw2();
    h->SetDirectory(&out);
  } else if((th2f = dynamic_cast<TH2F*>(o)) != 0) {
    TH2F *h = (TH2F*) th2f->Clone();
    h->Reset();   
    h->Sumw2();
    h->SetDirectory(&out);
  } else if((th2d = dynamic_cast<TH2D*>(o)) != 0) {
    TH2D *h = (TH2D*) th2d->Clone();
    h->Reset();   
    h->Sumw2();
    h->SetDirectory(&out);
  }
}
示例#9
0
void setPath(string& path, TDirectory* topDir) {

  TDirectory* cdir = dynamic_cast<TDirectory*> (topDir->GetDirectory(path.c_str()));
  if (!cdir) {
    vector<string> names;
    string tag = "/";
    split(path, names, tag);
    cdir = topDir;
    for (unsigned int it = 0; it < names.size();  it++) {
      string name = names[it];
      if (name.size() != 0) {
	TDirectory* td  = dynamic_cast<TDirectory*> (cdir->Get(name.c_str()));
        if (!td) td = cdir->mkdir(name.c_str());
	cdir = td;
      }
    }     
  }
  cdir->cd();
  //cdir->pwd();
}
示例#10
0
void doit()
{
   TFile* base = new TFile("f.db","recreate");
   TDirectory* a = base->mkdir("a","First Level Dir");
   a->cd();
   TH1D* ha = new TH1D("ha","ha",10,0,1);
   TDirectory* aa = a->mkdir("aa","Second Level Dira");
   aa->cd();
   TH1D* haa = new TH1D("haa","haa",10,0,1);
   
   a->ls();
   
   printf(" a: created@ %p  found@ %p\n", a,base->FindObjectAny("a"));
   printf("ha: created@ %p  found@ %p\n",ha,base->FindObjectAny("ha"));
   printf("ha: created@ %p  --found@ %p\n",ha,base->FindObjectAny("a/ha"));
#ifdef ClingWorkAroundMissingImplicitAuto
   TDirectory *k = (TDirectory*)base->FindObjectAny("a");
#else
   k = (TDirectory*)base->FindObjectAny("a");
#endif
   printf("ha: created@ %p  found@ %p\n",ha,k->FindObjectAny("ha"));
   
   printf("aa: created@ %p  found@ %p\n",aa,base->FindObjectAny("aa"));
   printf("aa: created@ %p  --found@ %p\n",aa,base->FindObjectAny("a/aa"));
   printf("aa: created@ %p  found@ %p\n",aa,k->FindObjectAny("aa"));
   
   printf("haa: created@ %p  found@ %p\n",haa,base->FindObjectAny("haa"));
   printf("haa: created@ %p  --found@ %p\n",haa,base->FindObjectAny("aa/haa"));
   printf("haa: created@ %p  --found@ %p\n",haa,base->FindObjectAny("a/aa/haa"));
   printf("haa: created@ %p  found@ %p\n",haa,k->FindObjectAny("haa"));
   printf("haa: created@ %p  --found@ %p\n",haa,k->FindObjectAny("aa/haa"));
#ifdef ClingWorkAroundMissingImplicitAuto
   TDirectory *kk = (TDirectory*)k->FindObjectAny("aa");
#else
   kk = (TDirectory*)k->FindObjectAny("aa");
#endif
   printf("haa: created@ %p  found@ %p\n",haa,kk->FindObjectAny("haa"));
   
   base->Write();
   
}
void ProcYields::Proc_hYW(){
	Info("Proc_hYW()", "");
		
	TDirectory* dirhYW = _fout->mkdir("hYW");
	TH1F* hYW[nVARSET];
	
	TDirectory* dirVarset=NULL;
	for(Int_t iVarset=0;iVarset<nVARSET;iVarset++){
		Info("Proc_hYW()","Varset = Varset%d", iVarset+1);
		dirVarset=dirhYW->mkdir(TString::Format("Varset%d",iVarset+1));
		dirVarset->cd();
		hYW[iVarset] = new TH1F("hYW","hYW", _user.nWbins, _user.Wmin, _user.Wmax);
		hYW[iVarset]->SetXTitle("W[GeV]");
		
		//!Loop over Q2W dirs, get h5Ds and their yields
		TIter nextkey(_fout->GetListOfKeys());
		TKey *key;
		while (key = (TKey*)nextkey()) {
			TString Q2Wdirname = key->GetName();
			if(Q2Wdirname.EqualTo("hYW_Dir") || Q2Wdirname.EqualTo("hYW"))continue;
			Info("Proc_hYW()","Q2Wdir = %s", Q2Wdirname.Data());
			TString wrange = Q2Wdirname.Tokenize("_")->At(1)->GetName();
			TString wlow = wrange.Tokenize(",")->At(0)->GetName();
			wlow.Remove(0,1); //remove "["
			//Float_t w = wlow.Atof();
			Double_t w = wlow.Atof();
									
			sprintf(_hname, "%s/hY5D/Varset%d/hY5D_FULL", Q2Wdirname.Data(),iVarset+1);
			THnSparse* hY5D_FULL = (THnSparse*)_fout->Get(_hname);
			if (hY5D_FULL == NULL) cout <<"could not get h5D" << endl;
			//Float_t yield = getIntegral(hY5D_FULL);
			Double_t yield = getIntegral(hY5D_FULL);
			//hYW[iVarset]->Fill(w, yield);
			hYW[iVarset]->SetBinContent(hYW[iVarset]->FindBin(w+_intrinsic.Wbinw), yield);
			Info("Proc_hYW()","W = %f, bin# = %d, yield = %f\n", w, hYW[iVarset]->FindBin(w+_intrinsic.Wbinw), yield);
		}
	}
	Info("Proc_hYW()", "done\n");
}
//Clone the file excluding the histogram (code stolen from Rene Brun)
void copyDir(TDirectory *source,std::string iSkipHist,bool iFirst=true) { 
  //copy all objects and subdirs of directory source as a subdir of the current directory   
  TDirectory *savdir = gDirectory;
  TDirectory *adir   = savdir;
  if(!iFirst) adir   = savdir->mkdir(source->GetName());
  if(!iFirst) adir->cd();
  //loop on all entries of this directory
  TKey *key;
  TIter nextkey(source->GetListOfKeys());
  while ((key = (TKey*)nextkey())) {
    const char *classname = key->GetClassName();
    TClass *cl = gROOT->GetClass(classname);
    if (!cl) continue;
    if (cl->InheritsFrom(TDirectory::Class())) {
      source->cd(key->GetName());
      TDirectory *subdir = gDirectory;
      adir->cd();
      copyDir(subdir,iSkipHist,false);
      adir->cd();
    } else {
      source->cd();
      TObject *obj = key->ReadObj();
      std::string pFullName = std::string(adir->GetName())+"/"+std::string(obj->GetName());
      std::string iSkipHist2 = iSkipHist;
      std::string fine_binning = "_fine_binning";
      iSkipHist2.replace(iSkipHist2.find(fine_binning), fine_binning.length(),"");
      if(pFullName.find(iSkipHist) != std::string::npos || pFullName.find(iSkipHist2) != std::string::npos) {
	continue;
      }
      adir->cd();
      obj->Write();
      delete obj;
    }
  }
  adir->SaveSelf(kTRUE);
  savdir->cd();
}
示例#13
0
 void Write(TDirectory * dir){
     TDirectory * inDir = dir->mkdir(Name.c_str());
     inDir->cd();
     cosTheta->Write();
     Wmass->Write();
     topMass->Write();
     cosThetaII->Write();
     WmassII->Write();
     topMassII->Write();
     cosTheta2D->Write();
     cosTheta2DII->Write();
     (inDir->mkdir("ttDecayModes"))->cd();
     semiEcosTheta->Write();
     semiTaucosTheta->Write();
     diTaucosTheta->Write();
     diEcosTheta->Write();
     diMucosTheta->Write();
     MuEcosTheta->Write();
     TauEcosTheta->Write();
     MuTaucosTheta->Write();
     fullHadcosTheta->Write();
     inDir->cd();
     dir->cd();
 }
示例#14
0
//________________________________________________________________________________
void MergeComplexHistogramFile( const Char_t *TargetName=0, const Char_t *inputFilesPattern=0) 
{
  if (TargetName && TargetName[0] && inputFilesPattern && inputFilesPattern[0] ) {
    printf(" An experimental version of macro.\n");
    TStopwatch time;
    Int_t fileCounter = 0;
    Int_t dirCounter = 0;
    Int_t treeCounter = 0;
    Int_t histogramCounter = 0;
     // Create the output file
     TFile *outFile = TFile::Open(TargetName,"RECREATE");
     TDirectory *outDir = outFile;
     TDirIter listOfFiles(inputFilesPattern);
     const char *fileName = 0;
     while ( (fileName =  listOfFiles.NextFile() ) ) {
        Int_t currentDirDepth = 0;
        printf(".");
        fileCounter++;
        StFileIter file(fileName);
        TObject *obj = 0;
        while ( (obj = *file) ) {
           Int_t depth = file.GetDepth();
           while (depth < currentDirDepth) {
                outDir = outDir->GetMotherDir();
                currentDirDepth--;
           }
           if ( obj->IsA()->InheritsFrom(TH1::Class()) ) {
              // descendant of TH1 -> merge it
              // printf("Merging histogram: %s\n",obj->GetName() ); 
//              std::cout << "Merging histogram " << obj->GetName() << std::endl;
              TH1 *h1 = (TH1*)obj;
              TH1 *dstHistogram = 0;
              // Check whether we found the new histogram
              if ( (dstHistogram = (TH1 *)outDir->FindObject(h1->GetName()))) {
                 // Accumulate  the  histogram
                  dstHistogram->Add(h1);
                  delete h1;  // Optional, to reduce the memory consumption
                  printf("h");
              } else {
                // First time - move the histogram
                h1->SetDirectory(outDir);
                printf(" The new Histogram found: %s \n", h1->GetName() );
                histogramCounter++;
              }
           } else  if ( obj->IsA()->InheritsFrom(TTree::Class()) ) {
              // descendant of TTree  -> merge it
              // printf("Merging Tree %p:%s\n",obj, obj->GetName() ); 
              TTree *tree = (TTree*)obj;
              TTree *dstTree = 0;
              // Check whether we found the new histogram
              if ( (dstTree = (TTree *)outDir->FindObject(tree->GetName()))) {
                   // printf("Merging %p:%s with the existing Tree %p:%s\n"
                   //       ,tree,tree->GetName(),dstTree, dstTree->GetName() ); 
                  // Merge  the  tree
                  TList *nextTree = new TList(); nextTree->Add(tree); 
                  dstTree->Merge(nextTree);
                  delete tree;  // Optional, to reduce the memory consumption
                  delete nextTree;
                  printf("t");
              } else {
                // First time - move the TTree
                TDirectory *saveDir = 0;
                if (outDir != gDirectory) {
                   saveDir = gDirectory;
                   outDir->cd();
                }
                TList *nextTree = new TList(); nextTree->Add(tree);               
                dstTree = TTree::MergeTrees(nextTree);
                if (saveDir) saveDir->cd();
                // printf(" The new TTree found: %p:%s \n",tree, tree->GetName() );
                // printf(" Create the destination Tree %p:%s\n\n",dstTree, dstTree->GetName() );
                delete tree;  // Optional, to reduce the memory consumption
                delete nextTree;
                treeCounter++;
              }
           } else if ( obj->IsA()->InheritsFrom(TDirectory::Class()) ) {
               printf("The input sub-TDirectory object: %s depth=%d\n",obj->GetName(), depth); 
               TDirectory *d =  (TDirectory *)outDir->FindObject(obj->GetName());
               if (!d) {
                  d = outDir->mkdir(obj->GetName());
                  dirCounter++;
                  printf("The new TDirectory object: %s depth=%d\n",d->GetPathStatic(), depth); 
               }
               if (d) {
                  outDir = d;                  
                  printf("The output sub-TDirectory object: %s depth=%d\n",outDir->GetPathStatic(), depth); 

               }
           } else {
              printf("I have no idea how to merge the %s objects of the %s class. Skipping .... \n",obj->GetName(), obj->ClassName() ); 
           }
           ++file;
        }
              
     }
     printf("\n Finishing  . . . \n");
     outFile->Write();  // this creates a second copy of the TTree ???
     outFile->Close();     
     delete outFile;
     if (fileCounter)      printf(" Total files merged: %d \n", fileCounter);
     if (dirCounter)       printf(" Total TDirectory objects merged: %d \n", dirCounter);
     if (histogramCounter) printf(" Total histograms merged: %d \n", histogramCounter);
     if (treeCounter)      printf(" Total TTree\'s merged: %d \n",treeCounter);
     if (dirCounter || treeCounter) printf(" You have used the experimental version of the program. Please check the output file\n");
        
     time.Print("Merge");
  } else {
     printf("\nUsage: root MergeHistogramFile.C(\"DestinationFileName\",\"InputFilesPattern\")\n");     
     printf("------        where InputFilesPattern  ::= <regexp_pattern_for_the_input_files>|@indirect_file_list\n");
     printf("                    indirect_file_list ::= a text file with the list of the files\n");
     printf("                    indirect_file_list can be create by the shell command:\n");
     printf("                         ls -1 *.root>indirect_file_list \n\n");
  }
}
示例#15
0
文件: getResVsub.C 项目: XuQiao/HI
void getResVsub(){
	string SumorProd = getenv("SUMORPROD");

//------------------------Deal with the number and get the output stored in txt files and root files
	double Vmax[nbin], eps[nbin];
	string dir = getenv("DIR");
	for(int ibin=0; ibin<nbin ;ibin++){
        	Vmax[ibin]=0.065*(trkbin[ibin]+30);
        	eps[ibin]=0.00025*(trkbin[ibin]+30);
	}
	ofstream  fstrV;
	double theta[ntheta];
	TVectorD Nevent[nbin], totmultall[nbin];
	TVectorD avgmult[nbin], avgpt[nbin], totmult[nbin], totpt[nbin];
	TVectorD Qx1[nbin], Qy1[nbin], Q2[nbin];
	TVectorD Gmod2[nbin][nptV][ntheta];
	TVectorD sigma2[nbin][nptV],deltaV[nbin][nptV];
	TVectorD sigma2_[nbin],chi_[nbin];
	TVectorD deltaVmean[nbin], Vmean[nbin];
	TVectorD Vmeanmean, deltaVmeanmean, sigmaVmeanmean;
	TVectorD r[nbin];
	TVectorD r0[nbin][nptV], r01[nbin][nptV], V[nbin][nptV], chi[nbin][nptV];
	TVectorD GRe[nbin][nptV][ntheta]; TVectorD* GRe_t[nbin][nptV][ntheta];
	TVectorD GIm[nbin][nptV][ntheta]; TVectorD* GIm_t[nbin][nptV][ntheta];
	TVectorD IFILE[nbin];
	TComplex G[nbin][nptV][ntheta][nstepr];
	if(SumorProd=="Sum")	fstrV.open("V_Sum_sub.txt");
	else	fstrV.open("V_Prod_sub.txt");
	if(SumorProd=="Sum")       TString outname = "mergedV_Sum_sub.root";
        else    TString outname="mergedV_Prod_sub.root";
      	TFile *outf = new TFile(outname,"Recreate");
	TFile *f[nFileAll];
	TVectorD Nevent_;	Nevent_.ResizeTo(nbin);  Nevent_.Zero();

	Vmeanmean.ResizeTo(nbin);  Vmeanmean.Zero();
	deltaVmeanmean.ResizeTo(nbin);  deltaVmeanmean.Zero();
	sigmaVmeanmean.ResizeTo(nbin);  sigmaVmeanmean.Zero();
 
	for(int ibin=0; ibin<nbin; ibin++){
		r[ibin].ResizeTo(nstepr);
                for(int ir=0; ir<nstepr; ir++){
        if(isSimple==0)  r[ibin][ir]=j01/(Vmax[ibin]-eps[ibin]*ir);	
	else		 r[ibin][ir]=0.00025*20*(ir+1);
		}
         
	for(int ifile=0; ifile<nFileAll; ifile++){
	if(SumorProd=="Sum") f[ifile] = TFile::Open(Form("/scratch/xuq7/flow/pbsjoboutput/tracknormcpt03to6/%s/AnaV_Sum_%d.root",dir.c_str(),ifile));
        else f[ifile] = TFile::Open(Form("/scratch/xuq7/flow/pbsjoboutput/tracknormcpt03to6/%s/AnaV_Prod_%d.root",dir.c_str(),ifile));
        TVectorD* Nevent_t =  (TVectorD*)f[ifile]->Get(Form("Nevent"));
	Nevent_[ibin]+=(*Nevent_t)[ibin];
	f[ifile]->Close();
	}
      
	IFILE[ibin].ResizeTo(nsamples);
	Nevent[ibin].ResizeTo(nsamples);  Nevent[ibin].Zero();
	totmultall[ibin].ResizeTo(nsamples);      totmultall[ibin].Zero();
        TDirectory *dir0 = outf->mkdir(Form("D_%d",ibin));

	for(int isample=0;isample<nsamples;isample++){
		TVectorD Nevent0;	Nevent0.ResizeTo(nbin);  Nevent0.Zero();
	
	for(int itheta=0;itheta<ntheta;itheta++)
        	theta[itheta]=itheta*TMath::Pi()/ntheta/nn;

		for(int iptbin=0;iptbin<nptV;iptbin++){
			r0[ibin][iptbin].ResizeTo(ntheta);
			r01[ibin][iptbin].ResizeTo(ntheta);
			sigma2[ibin][iptbin].ResizeTo(ntheta);
			V[ibin][iptbin].ResizeTo(ntheta);
			deltaV[ibin][iptbin].ResizeTo(ntheta);
			chi[ibin][iptbin].ResizeTo(ntheta);
                        for(int itheta=0;itheta<ntheta;itheta++){
				Gmod2[ibin][iptbin][itheta].ResizeTo(nstepr);
				GRe[ibin][iptbin][itheta].ResizeTo(nstepr);
				GRe[ibin][iptbin][itheta].Zero();
				GIm[ibin][iptbin][itheta].ResizeTo(nstepr);
				GIm[ibin][iptbin][itheta].Zero();
			}
		}

		avgmult[ibin].ResizeTo(nptV);	deltaVmean[ibin].ResizeTo(nptV);	Vmean[ibin].ResizeTo(nptV);
		deltaVmean[ibin].Zero();	Vmean[ibin].Zero();
		Vmean[ibin].Zero();	deltaVmean[ibin].Zero();
		totpt[ibin].ResizeTo(nptV);	totpt[ibin].Zero();
		totmult[ibin].ResizeTo(nptV);	totmult[ibin].Zero();
		avgpt[ibin].ResizeTo(nptV);
                Qx1[ibin].ResizeTo(nptV);     Qx1[ibin].Zero();
                Qy1[ibin].ResizeTo(nptV);     Qy1[ibin].Zero();
                Q2[ibin].ResizeTo(nptV);     Q2[ibin].Zero();
		sigma2_[ibin].ResizeTo(nptV);sigma2_[ibin].Zero();
		chi_[ibin].ResizeTo(nptV);chi_[ibin].Zero();

	for(int ifile=0; ifile<nFileAll; ifile++){
		if(SumorProd=="Sum") f[ifile] = TFile::Open(Form("/scratch/xuq7/flow/pbsjoboutput/tracknormcpt03to6/%s/AnaV_Sum_%d.root",dir.c_str(),ifile));
		else f[ifile] = TFile::Open(Form("/scratch/xuq7/flow/pbsjoboutput/tracknormcpt03to6/%s/AnaV_Prod_%d.root",dir.c_str(),ifile));
		TVectorD* Nevent_t =  (TVectorD*)f[ifile]->Get(Form("Nevent"));
		TVectorD* totmultall_t =  (TVectorD*)f[ifile]->Get(Form("totmultall"));
		Nevent0[ibin] += (*Nevent_t)[ibin];
		double start=isample*Nevent_[ibin]/nsamples;
		double end=(isample+1)*Nevent_[ibin]/nsamples;
		if(Nevent0[ibin]>start && Nevent0[ibin]<=end){
			IFILE[ibin][isample]=(double)ifile;
			Nevent[ibin][isample] += (*Nevent_t)[ibin];
			for(int iptbin=0;iptbin<nptV;iptbin++){
					for(int itheta=0;itheta<ntheta;itheta++){
					GRe_t[ibin][iptbin][itheta] = (TVectorD*)f[ifile]->Get(Form("GRe_%d_%d_%d",ibin,iptbin,itheta));
					GIm_t[ibin][iptbin][itheta] = (TVectorD*)f[ifile]->Get(Form("GIm_%d_%d_%d",ibin,iptbin,itheta));
					for(ir=0; ir<nstepr; ir++){
						GRe[ibin][iptbin][itheta][ir] += (*GRe_t[ibin][iptbin][itheta])[ir];
						GIm[ibin][iptbin][itheta][ir] += (*GIm_t[ibin][iptbin][itheta])[ir];
					}
				}
			}
			TVectorD* Qx1_t =  (TVectorD*)f[ifile]->Get(Form("Qx1_%d",ibin));
			TVectorD* Qy1_t =  (TVectorD*)f[ifile]->Get(Form("Qy1_%d",ibin));
			TVectorD* Q2_t =  (TVectorD*)f[ifile]->Get(Form("Q2_%d",ibin));
			TVectorD* totmult_t =  (TVectorD*)f[ifile]->Get(Form("totmult_%d",ibin));
			TVectorD* totpt_t =  (TVectorD*)f[ifile]->Get(Form("totpt_%d",ibin));
			for(int iptbin=0;iptbin<nptV;iptbin++){
				Qx1[ibin][iptbin] += (*Qx1_t)[iptbin];
				Qy1[ibin][iptbin] += (*Qy1_t)[iptbin];
				Q2[ibin][iptbin] += (*Q2_t)[iptbin];
				totmult[ibin][iptbin] += (*totmult_t)[iptbin];
				totpt[ibin][iptbin] += (*totpt_t)[iptbin];
			}
			totmultall[ibin][isample] += (*totmultall_t)[ibin];	
		}
		f[ifile]->Close();
	}//file loop
		
	fstrV<<setprecision(4)<<fixed;
	fstrV<<"ibin"<<"\t"<<"iptbin"<<"\t"<<"itheta"<<"\t"<<"r0"<<"\t"<<"V"<<"\t"<<"sigma2"<<"\t"<<"chi"<<"\t"<<"Vn Errors"<<endl;
		for(int iptbin=0;iptbin<nptV;iptbin++){
			for(int itheta=0;itheta<ntheta;itheta++){
				for(ir=0; ir<nstepr; ir++){
					G[ibin][iptbin][itheta][ir]=TComplex(GRe[ibin][iptbin][itheta][ir],GIm[ibin][iptbin][itheta][ir]);	
					G[ibin][iptbin][itheta][ir]/=Nevent[ibin][isample];
					Gmod2[ibin][iptbin][itheta][ir]=TMath::Power(TComplex::Abs(G[ibin][iptbin][itheta][ir]),2);
				}
				for(ir=0; ir<nstepr-1; ir++)
					if(ir!=0 && Gmod2[ibin][iptbin][itheta][ir]<=Gmod2[ibin][iptbin][itheta][ir-1] && Gmod2[ibin][iptbin][itheta][ir]<=Gmod2[ibin][iptbin][itheta][ir+1]) break;
				if(ir!=0 && ir<nstepr-1)	r01[ibin][iptbin][itheta]=r[ibin][ir];
				else if(ir==0)	{cout<<"ibin="<<ibin<<"\t"<<"iptbin="<<iptbin<<"\t"<<"itheta="<<itheta<<"\tminimum lies on ir = 0, please select proper range!"<<endl;	continue;}
				else 	{cout<<"ibin="<<ibin<<"\t"<<"iptbin="<<iptbin<<"\t"<<"itheta="<<itheta<<"\tminimum lies on ir = maximum "<<nstepr-1<<", please select proper range!"<<endl;	continue;}
				avgmult[ibin][iptbin]=1.0*totmult[ibin][iptbin]/Nevent[ibin][isample];
				avgpt[ibin][iptbin]=1.0*totpt[ibin][iptbin]/totmult[ibin][iptbin];
				if(isSimple==0)	V[ibin][iptbin][itheta]=Vmax[ibin]-ir*eps[ibin]+eps[ibin]*(Gmod2[ibin][iptbin][itheta][ir+1]-Gmod2[ibin][iptbin][itheta][ir-1])/2./(Gmod2[ibin][iptbin][itheta][ir-1]-2*Gmod2[ibin][iptbin][itheta][ir]+Gmod2[ibin][iptbin][itheta][ir+1]);
				else V[ibin][iptbin][itheta]=j01/r0[ibin][iptbin][itheta]; //simple method
				r0[ibin][iptbin][itheta]=j01/V[ibin][iptbin][itheta];
				V[ibin][iptbin][itheta]/=avgmult[ibin][iptbin];
				//sigma2[ibin][iptbin][itheta]=Q2[ibin][iptbin]/Nevent[ibin]-(Qx1[ibin][iptbin]/Nevent[ibin])*(Qx1[ibin][iptbin]/Nevent[ibin])-(Qy1[ibin][iptbin]/Nevent[ibin])*(Qy1[ibin][iptbin]/Nevent[ibin])-(V[ibin][iptbin][itheta]*avgmult[ibin][iptbin])*(V[ibin][iptbin][itheta]*avgmult[ibin][iptbin]);
				sigma2[ibin][iptbin][itheta]=Q2[ibin][iptbin]/Nevent[ibin][isample]-(Qx1[ibin][iptbin]/Nevent[ibin][isample])*(Qx1[ibin][iptbin]/Nevent[ibin][isample])-(Qy1[ibin][iptbin]/Nevent[ibin][isample])*(Qy1[ibin][iptbin]/Nevent[ibin][isample]);
				sigma2_[ibin][iptbin]+=sigma2[ibin][iptbin][itheta];
				Vmean[ibin][iptbin]+=V[ibin][iptbin][itheta];
				chi[ibin][iptbin][itheta]=V[ibin][iptbin][itheta]*avgmult[ibin][iptbin]/TMath::Sqrt(sigma2[ibin][iptbin][itheta]);
				//deltaV[ibin][iptbin][itheta]=V[ibin][iptbin][itheta]/j01/TMath::BesselJ1(j01)*TMath::Sqrt((TMath::Exp(j01*j01/2./chi[ibin][iptbin][itheta]/chi[ibin][iptbin][itheta])+TMath::Exp(-j01*j01/2./chi[ibin][iptbin][itheta]/chi[ibin][iptbin][itheta])*TMath::BesselJ0(2*j01))/2./Nevent[ibin]);
				}
			sigma2_[ibin][iptbin]/=ntheta;
			Vmean[ibin][iptbin]/=ntheta;
			sigma2_[ibin][iptbin]-=TMath::Power(Vmean[ibin][iptbin]*avgmult[ibin][iptbin],2);
			chi_[ibin][iptbin]=Vmean[ibin][iptbin]*avgmult[ibin][iptbin]/TMath::Sqrt(sigma2_[ibin][iptbin]);
			//deltaVmean[ibin][iptbin]+=TMath::Exp(j01*j01/2./chi[ibin][iptbin][itheta]/chi[ibin][iptbin][itheta]*TMath::Cos(nn*theta[itheta]))*TMath::BesselJ0(2*j01*TMath::Sin(nn*theta[itheta]/2.))+TMath::Exp(-j01*j01/2./chi[ibin][iptbin][itheta]/chi[ibin][iptbin][itheta]*TMath::Cos(nn*theta[itheta]))*TMath::BesselJ0(2*j01*TMath::Cos(nn*theta[itheta]/2.));
			for(int itheta=0;itheta<ntheta;itheta++){
			deltaV[ibin][iptbin][itheta]=V[ibin][iptbin][itheta]/j01/TMath::BesselJ1(j01)*TMath::Sqrt((TMath::Exp(j01*j01/2./chi_[ibin][iptbin]/chi_[ibin][iptbin])+TMath::Exp(-j01*j01/2./chi_[ibin][iptbin]/chi_[ibin][iptbin])*TMath::BesselJ0(2*j01))/2./Nevent[ibin][isample]);
			deltaVmean[ibin][iptbin]+=TMath::Exp(j01*j01/2./chi_[ibin][iptbin]/chi_[ibin][iptbin]*TMath::Cos(nn*theta[itheta]))*TMath::BesselJ0(2*j01*TMath::Sin(nn*theta[itheta]/2.))+TMath::Exp(-j01*j01/2./chi_[ibin][iptbin]/chi_[ibin][iptbin]*TMath::Cos(nn*theta[itheta]))*TMath::BesselJ0(2*j01*TMath::Cos(nn*theta[itheta]/2.));
			fstrV<<ibin<<"\t"<<iptbin<<"\t"<<itheta<<"\t"<<r0[ibin][iptbin][itheta]<<"\t"<<V[ibin][iptbin][itheta]<<"\t"<<sigma2[ibin][iptbin][itheta]<<"\t"<<chi[ibin][iptbin][itheta]<<"\t"<<deltaV[ibin][iptbin][itheta]<<endl;
			}
			fstrV<<endl;
			deltaVmean[ibin][iptbin]=Vmean[ibin][iptbin]/j01/TMath::BesselJ1(j01)*TMath::Sqrt(deltaVmean[ibin][iptbin]/ntheta/2./Nevent[ibin][isample]);
		}
	fstrV<<endl;

	fstrV<<"ibin"<<"\t"<<"iptbin"<<"\t"<<"avgmult"<<"\t"<<"avgpt"<<"\t"<<"Vn mean"<<"\t"<<"Vn mean Error"<<endl;
		for(int iptbin=0;iptbin<nptV;iptbin++){
			fstrV<<ibin<<"\t"<<iptbin<<"\t"<<avgmult[ibin][iptbin]<<"\t"<<avgpt[ibin][iptbin]<<"\t"<<Vmean[ibin][iptbin]<<"\t"<<deltaVmean[ibin][iptbin]<<endl;
		}
	fstrV<<endl;
		
		TDirectory *dirsample = dir0->mkdir(Form("s_%d",isample)); dirsample->cd();
		r[ibin].Write("r");
		Qx1[ibin].Write("Qx1");
                Qy1[ibin].Write("Qy1");
                Q2[ibin].Write("Q2");
		totmult[ibin].Write("totmult");
		totpt[ibin].Write("totpt");
		avgmult[ibin].Write("avgmult");
		avgpt[ibin].Write("avgpt");
		Vmean[ibin].Write("Vmean");
		deltaVmean[ibin].Write("deltaVmean");
		Vmeanmean[ibin]+=Vmean[ibin][0]/nsamples;
		deltaVmeanmean[ibin]+=deltaVmean[ibin][0]/nsamples;
		sigmaVmeanmean[ibin]+=TMath::Power(Vmean[ibin][0]/nsamples,2);
		chi_[ibin].Write("chi");

		for(int iptbin=0;iptbin<nptV;iptbin++){
                        TDirectory *dir1 = dirsample->mkdir(Form("D_%d",iptbin));dir1->cd();
			sigma2[ibin][iptbin].Write("sigma2");	chi[ibin][iptbin].Write("chi0");	deltaV[ibin][iptbin].Write("deltaV");
			r0[ibin][iptbin].Write("r0");	r01[ibin][iptbin].Write("r01");	V[ibin][iptbin].Write("V");

        		for(int itheta=0;itheta<ntheta;itheta++){
                        	TDirectory *dir2 = dir1->mkdir(Form("D_%d",itheta));dir2->cd();
                        	GRe[ibin][iptbin][itheta].Write(Form("GRe"));
                        	GIm[ibin][iptbin][itheta].Write(Form("GIm"));
                        	Gmod2[ibin][iptbin][itheta].Write(Form("G2"));
                	}
        	}
	}//subsample loop
	dir0->cd();
        IFILE[ibin].Write("IFILE");
        Nevent[ibin].Write("Nevent");
        totmultall[ibin].Write("totmultall");
	sigmaVmeanmean[ibin]=TMath::Sqrt(sigmaVmeanmean[ibin]*nsamples-Vmeanmean[ibin]*Vmeanmean[ibin])/TMath::Sqrt(nsamples);
	}//ntrk bin loop
	outf->cd();
	Vmeanmean.Write("Vmeanmean");
	deltaVmeanmean.Write("deltaVmeanmean");
	sigmaVmeanmean.Write("sigmaVmeanmean");
	outf->Close();
}
示例#16
0
int MakeHistos(int iSample = 0, int iSR = 6){
  TH1::SetDefaultSumw2(true);
  if(pcp)cout<<"going to set inputs"<<endl;
    
  TString mainDir = "/home/fcostanz/Bonsai/ControlPlots/";

  TFile* cutFile = new TFile( "Optimization-2Step.root", "READ"); 
  TTree* cutTree;  
  cutFile->GetObject( "Optimization", cutTree);

  Float_t mtCut = 0.;
  Float_t nJetCut = 0.;
  Float_t topnessCut = 0.;
  Float_t mt2wCut = 0.;
  Float_t yCut = 0.;
  Float_t dphiCut = 0.;
  Float_t drlblCut = 0.;
  Float_t drlbgCut = 0.;
  Float_t chi2Cut = 0.;
  Float_t metCut = 0.;
  Float_t m3Cut = 0.;
  Float_t centralityCut = 0.;
  Float_t mlbCut = 0.;

  cutTree->SetBranchAddress( "mtCut", &mtCut);
  cutTree->SetBranchAddress( "njetCut", &nJetCut);
  cutTree->SetBranchAddress( "topnessCut", &topnessCut);
  cutTree->SetBranchAddress( "mt2wCut", &mt2wCut);
  cutTree->SetBranchAddress( "yCut", &yCut);
  cutTree->SetBranchAddress( "dphiCut", &dphiCut);
  cutTree->SetBranchAddress( "drlblCut", &drlblCut);
  cutTree->SetBranchAddress( "drlbgCut", &drlbgCut);
  cutTree->SetBranchAddress( "chi2Cut", &chi2Cut);
  cutTree->SetBranchAddress( "metCut", &metCut);
  cutTree->SetBranchAddress( "m3Cut", &m3Cut);
  cutTree->SetBranchAddress( "centralityCut", &centralityCut);
  cutTree->SetBranchAddress( "mlbCut", &mlbCut);

  cutTree->GetEntry(iSR);
  /*
  mtCut = 120.;
  nJetCut = 3;
  topnessCut = -20;
  mt2wCut = 200;
  yCut = 0.;
  dphiCut = 1.;
  drlblCut = 5.;
  drlbgCut = 0.;
  chi2Cut = 9999999999.;
  metCut = 250.;
  m3Cut = 0.;
  centralityCut = 0.6;
  mlbCut =9999999999. ;*/

  cout<<"mtCut = "<<mtCut<<endl;
  cout<<"nJetCut = "<<nJetCut<<endl;
  cout<<"topnessCut = "<<topnessCut<<endl;
  cout<<"mt2wCut = "<<mt2wCut<<endl;
  cout<<"yCut = "<<yCut<<endl;
  cout<<"dphiCut = "<<dphiCut<<endl;
  cout<<"drlblCut = "<<drlblCut<<endl;
  cout<<"drlbgCut = "<<drlbgCut<<endl;
  cout<<"chi2Cut = "<<chi2Cut<<endl;
  cout<<"metCut = "<<metCut<<endl;
  cout<<"m3Cut = "<<m3Cut<<endl;
  cout<<"centralityCut = "<<centralityCut<<endl;
  cout<<"mlbCut = "<<mlbCut<<endl;

  const int NSamples = 11;  
  const int NSignals = 4;
  const int NControlRegions = 6;
  const int NLeps = 3;
  const int NDirs = NControlRegions * NLeps;

  TString sample[NSamples];
  sample[0] = "Data";
  sample[1] = "DiLep";
  sample[2] = "OneLep";
  sample[3] = "WJets";
  sample[4] = "Rare";
  sample[5] = "QCD";
  sample[6] = "DrellYan";
  sample[7] = "T2tb-mStop175mLSP50";
  sample[8] = "T2tb-mStop200mLSP25";
  sample[9] = "T2tb-mStop325mLSP100";
  sample[10] = "T2tb-mStop550mLSP1";

  double lumi=19500.;
  double weight = 1.;

  bool lepFlag;
  TString lep[NLeps];
  lep[0] = "El";
  lep[1] = "Mu";
  lep[2] = "ElAndMu";

  TString controlRegion[NControlRegions];
  controlRegion[0] = "Preselection";
  controlRegion[1] = "SearchRegionPreIsoTrackVeto";
  controlRegion[2] = "SearchRegionPostIsoTrackVeto";
  controlRegion[3] = "CR1";
  controlRegion[4] = "CR4";
  controlRegion[5] = "CR5";

  bool flag[NDirs];
  TString controlDirName[NDirs];
  TDirectory* controlDir[NDirs];

  for (int ilep = 0; ilep < NLeps; ilep++){
    for ( int iControlRegion = 0; iControlRegion < NControlRegions; iControlRegion++){
      controlDirName[ilep * NControlRegions + iControlRegion ] = lep[ilep];
      controlDirName[ilep * NControlRegions + iControlRegion ] += "-";
      controlDirName[ilep * NControlRegions + iControlRegion ] += controlRegion[iControlRegion];
    }
  }

  /////////////////////////////////////////////////////
  //  Input Definition
  /////////////////////////////////////////////////////  
  std::cout<<"Running over Sample "<<sample[iSample]<<std::endl;

  TString inFileName = mainDir; inFileName += sample[iSample]; inFileName +=".root";
  TFile* inFile = new TFile(inFileName,"READ");
  if (!inFile->IsOpen()){
    std::cout<<"not open"<<std::endl;
  }

  /////////////////////////////////////////////////////
  //  Tree Definition
  /////////////////////////////////////////////////////  
  TTree* tree;
  tree= (TTree*)inFile->Get("NoSystematic/bonsai");
  int N = tree->GetEntries();  cout<<"THERE ARE "<<N<<" EVENTS IN "<<inFileName<<endl;
  
  Float_t globalWeight = 0.;
  Float_t triggerWeight = 0.;
  Float_t npv = 0.;
  Float_t ngoodpv = 0.;
  Float_t puWeight = 0.;
  Float_t isrWeight = 0.;
  Float_t topPtWeight = 0.;

  Float_t lepFromTop = 0.;
  Float_t charginos = 0.;

  Float_t njets = 0.;
  Float_t jet1 = 0.;
  Float_t jet2 = 0.;
  Float_t jet3 = 0.;
  Float_t jet4 = 0.;

  Float_t nbjets = 0.;
  Float_t bjet1 = 0.;
  Float_t bjetHighestDisc = 0.;
  Float_t bdiscH = 0.;

  Float_t lPt = 0.;
  Float_t lEta = 0.;
  Float_t lRelIso = 0.;

  Float_t isoTrack = 0.;
  Float_t tauVeto = 0.;
  
  Float_t rawmet = 0.;
  Float_t typeImet = 0.;
  Float_t phiCorrMet = 0.;
  
  Float_t ht = 0.;
  Float_t ht3 = 0.;
  Float_t ht4 = 0.;
  Float_t ht5 = 0.;
  Float_t htRatio = 0.;
  Float_t meff = 0.;
  Float_t y = 0.;
  
  Float_t mt = 0.;
  Float_t mlb1 = 0.;
  Float_t mlb = 0.;
  Float_t m3b = 0.;
  Float_t m3 = 0.;
  Float_t centrality = 0.;  
  Float_t mt2w = 0.;
  Float_t hadChi2 = 0.;
  Float_t topness = 0.;

  Float_t dphimin = 0.;
  Float_t drlb1 = 0.;
  Float_t drlbmin = 0.;

  Int_t pdgIdLep1 = 0;
  Int_t pdgIdLep2 = 0;

  Char_t kinRegion = false;
  Char_t searchRegionPre = false;
  Char_t searchRegionPost = false;
  Char_t CR1 = false;
  Char_t CR4 = false;
  Char_t CR5 = false;

  tree->SetBranchAddress( "GlobalWeight", &globalWeight);
  tree->SetBranchAddress( "TriggerWeight", &triggerWeight);
  tree->SetBranchAddress( "NPV", &npv);
  tree->SetBranchAddress( "NgoodPV", &ngoodpv);
  tree->SetBranchAddress( "PUWeight", &puWeight);
  tree->SetBranchAddress( "isrWeight", &isrWeight);
  tree->SetBranchAddress( "topPtWeight", &topPtWeight);

  tree->SetBranchAddress( "LepFromTop", &lepFromTop);
  tree->SetBranchAddress( "Charginos", &charginos);

  tree->SetBranchAddress( "njets", &njets);
  tree->SetBranchAddress( "jet1", &jet1);
  tree->SetBranchAddress( "jet2", &jet2);
  tree->SetBranchAddress( "jet3", &jet3);
  tree->SetBranchAddress( "jet4", &jet4);

  tree->SetBranchAddress( "nbjets", &nbjets);
  tree->SetBranchAddress( "bjet1", &bjet1);
  tree->SetBranchAddress( "bjetHighestDisc", &bjetHighestDisc);
  tree->SetBranchAddress( "discH", &bdiscH);

  tree->SetBranchAddress( "lPt", &lPt);
  tree->SetBranchAddress( "lEta", &lEta);
  tree->SetBranchAddress( "lRelIso", &lRelIso);

  tree->SetBranchAddress( "phiCorrMet", &phiCorrMet);
  
  tree->SetBranchAddress( "ht", &ht);
  tree->SetBranchAddress( "ht3", &ht3);
  tree->SetBranchAddress( "ht4", &ht4);
  tree->SetBranchAddress( "ht5", &ht5);
  tree->SetBranchAddress( "htRatio", &htRatio);
  tree->SetBranchAddress( "meff", &meff);
  tree->SetBranchAddress( "y", &y);

  tree->SetBranchAddress( "mt", &mt);
  tree->SetBranchAddress( "mlb1", &mlb1);
  tree->SetBranchAddress( "mlb", &mlb);
  tree->SetBranchAddress( "m3b", &m3b);
  tree->SetBranchAddress( "m3", &m3);
  tree->SetBranchAddress( "centrality", &centrality);
  tree->SetBranchAddress( "mt2w", &mt2w);
  tree->SetBranchAddress( "hadChi2", &hadChi2);
  tree->SetBranchAddress( "topness", &topness);

  tree->SetBranchAddress( "dphimin", &dphimin);
  tree->SetBranchAddress( "drlb1", &drlb1);
  tree->SetBranchAddress( "drlbmin", &drlbmin);

  tree->SetBranchAddress("pdgIdLep1",&pdgIdLep1);
  tree->SetBranchAddress("pdgIdLep2",&pdgIdLep2);

  tree->SetBranchAddress("kinRegion",&kinRegion);
  tree->SetBranchAddress("searchRegionPre",&searchRegionPre);
  tree->SetBranchAddress("searchRegionPost",&searchRegionPost);
  tree->SetBranchAddress("CR1",&CR1);
  tree->SetBranchAddress("CR4",&CR4);
  tree->SetBranchAddress("CR5",&CR5);

  /////////////////////////////////////////////////////
  //  Output Definition
  /////////////////////////////////////////////////////

  //Branching Ratio
 
  TFile* outFile = new TFile( "./MakeHistos/"+sample[iSample]+".root", "Update");
  outFile->cd();

  TH1D* npvh[NDirs];
  TH1D* ngoodpvh[NDirs];

  TH1D* lpth[NDirs];
  TH1D* letah[NDirs];
  TH1D* lrelisoh[NDirs];

  TH1D* njetsh[NDirs];
  TH1D* jet1h[NDirs];
  TH1D* jet2h[NDirs];
  TH1D* jet3h[NDirs];
  TH1D* jet4h[NDirs];

  TH1D* nbjetsh[NDirs];
  TH1D* bjet1h[NDirs];
  TH1D* bjetHighDh[NDirs];
  TH1D* bdiscHh[NDirs];
  
  TH1D* hth[NDirs];
  TH1D* ht3h[NDirs];
  TH1D* ht4h[NDirs];
  TH1D* ht5h[NDirs];
  TH1D* htratioh[NDirs];
  TH1D* meth[NDirs];
  TH1D* meffh[NDirs];
  TH1D* yh[NDirs];

  TH1D* mth[NDirs];
  TH1D* mlb1h[NDirs];
  TH1D* mlbh[NDirs];
  TH1D* m3bh[NDirs];
  TH1D* m3h[NDirs];
  TH1D* centralityh[NDirs];
  TH1D* mt2wh[NDirs];
  TH1D* hadchi2h[NDirs];
  TH1D* topnessh[NDirs];

  TH1D* dphiminh[NDirs];
  TH1D* drlb1h[NDirs];
  TH1D* drlbminh[NDirs];

  TString dirName = ""; dirName += iSR;
  if (outFile->GetDirectory(dirName)) outFile->Delete(dirName + ";*");
  outFile->mkdir( dirName);
  TDirectory* SRDir = outFile->GetDirectory( dirName);
  SRDir->cd();
  
  for ( int iDir = 0; iDir < NDirs; iDir++){    
    SRDir->mkdir( controlDirName[iDir]);
    controlDir[iDir] = SRDir->GetDirectory( controlDirName[iDir]);
    controlDir[iDir]->cd();

    npvh[iDir] = new TH1D( "npv", "NPV", 51, -0.5, 50.5);
    ngoodpvh[iDir] = new TH1D( "ngoodpv", "NgoodPV", 51, -0.5, 50.5);

    lpth[iDir]     = new TH1D( "lpt", "lep p_{T} [GeV]",  12, 25., 500.);
    letah[iDir]    = new TH1D( "leta", "lep #Eta", 30, -3., 3.);
    lrelisoh[iDir] = new TH1D( "lRelIso", "lep RelIso", 30, 0., 1.);
    
    njetsh[iDir] = new TH1D(  "njets", "jets multiplicity",    10, -0.5, 9.5);
    jet1h[iDir]  = new TH1D(  "jet1", "1st jet p_{T} [GeV]",   25, 0., 500.);
    jet2h[iDir]  = new TH1D(  "jet2", "2nd jet p_{T} [GeV]",   25, 0., 500.);
    jet3h[iDir]  = new TH1D(  "jet3", "3rd jet p_{T} [GeV]",   25, 0., 500.);
    jet4h[iDir]  = new TH1D(  "jet4", "4th jet p_{T} [GeV]",   25, 0., 500.);
    
    nbjetsh[iDir]    = new TH1D( "nbjets", "b jets multiplicity",  6, -0.5, 5.5);  
    bjet1h[iDir]     = new TH1D(     "bjet1", "Leading b jet p_{T} [GeV]", 25, 0., 500.);
    bjetHighDh[iDir] = new TH1D( "bjetHighD", "p_{T} of the highest b disc jet [GeV]",  12, 0., 500.);
    bdiscHh[iDir]    = new TH1D( "bdisc", "bdisc",  20, 0., 1.);  

    meth[iDir] = new TH1D( "MET", "MET [GeV]", 12, 0., 400.);
    
    hth[iDir]      = new TH1D(   "Ht",   "Ht [GeV]",  20, 0., 1000.);
    ht3h[iDir]     = new TH1D(   "Ht3",   "Ht3 [GeV]",  20, 0., 1000.);
    ht4h[iDir]     = new TH1D(   "Ht4",   "Ht4 [GeV]",  20, 0., 1000.);
    ht5h[iDir]     = new TH1D(   "Ht5",   "Ht5 [GeV]",  20, 0., 1000.);
    htratioh[iDir] = new TH1D(   "HtRatio",   "HtRatio",  20, 0., 1.);
    meffh[iDir]    = new TH1D( "Meff", "Meff [GeV]",  40, 0., 1000.);
    yh[iDir]       = new TH1D(    "Y",    "Y [GeV^{1/2}]",  15, 0.,   30.);
    
    mth[iDir]      = new TH1D(  "Mt",  "Mt [GeV]", 30, 0., 300.);
    mlb1h[iDir]    = new TH1D(      "mlb1",     "Mlb1 [GeV]", 10, 0., 500.);
    mlbh[iDir]     = new TH1D(  "mlb", "Mlb [GeV]", 10, 0., 500.);
    m3bh[iDir]     = new TH1D(       "m3b",      "M3b [GeV]", 15, 0., 500.);
    m3h[iDir]      = new TH1D(        "m3",       "M3 [GeV]", 15, 0., 500.);
    centralityh[iDir] = new TH1D( "centrality", "centrality", 10, 0., 1.);
    mt2wh[iDir]    = new TH1D(      "mt2w",     "MT2W [GeV]", 15, 0.,  500.);
    hadchi2h[iDir] = new TH1D(      "hadChi2",     "hadChi2 [GeV]", 20, 0., 10.);
    topnessh[iDir] = new TH1D(      "topness",     "topness [GeV]", 30, -15., 15.);
    
    dphiminh[iDir] = new TH1D( "dphimin", "min dPhi (MET, jet1/2)", 17, 0., TMath::Pi() * 17./16.);
    drlb1h[iDir]   = new TH1D(    "drlb1", "dR(lep, bjet1)", 20, 0., 5.);
    drlbminh[iDir] = new TH1D(    "drlbmin", "min dR(lep, bjet)", 20, 0., 5.);
  }
  outFile->cd();

  for (int ievt=0;ievt<N;++ievt){    
    tree->GetEntry(ievt);
    
    //if (ievt%13453 == 0) cout<<"Event number "<<ievt<<"\r"<<flush;    

    if (iSample == 0) weight = 1.;
    else weight = globalWeight * triggerWeight * puWeight * topPtWeight * lumi;

    if ( (iSample - NSamples + NSignals) > -0.01 ) weight *= isrWeight;

    if (lRelIso > 0.1) continue;
    
    for (int ilep = 0; ilep < NLeps; ilep++){
      lepFlag = true;
      if (ilep == 0) lepFlag = (abs(pdgIdLep1) == 11);
      if (ilep == 1) lepFlag = (abs(pdgIdLep1) == 13);

      flag[ilep * NControlRegions + 0] = (searchRegionPost || CR1) && lepFlag;
      flag[ilep * NControlRegions + 1] = searchRegionPre && lepFlag;
      flag[ilep * NControlRegions + 2] = searchRegionPost && lepFlag;
      flag[ilep * NControlRegions + 3] = CR1 && lepFlag;
      flag[ilep * NControlRegions + 4] = CR4 && lepFlag;
      flag[ilep * NControlRegions + 5] = CR5 && lepFlag;
    }
    
    for ( int iDir = 0; iDir < NDirs; iDir++){
      if (!flag[iDir])
	continue;
      
      /////////////////////////////////////////////////////
      //  Histo Filling
      /////////////////////////////////////////////////////
      
      bool allCuts    = (njets - nJetCut) > -0.0001 && mt2w > mt2wCut && y > yCut && dphimin > dphiCut && drlb1 < drlblCut && phiCorrMet > metCut && m3 > m3Cut;
      bool allButMt2w = (njets - nJetCut) > -0.0001 &&                   y > yCut && dphimin > dphiCut && drlb1 < drlblCut && phiCorrMet > metCut && m3 > m3Cut;
      bool allButY    = (njets - nJetCut) > -0.0001 && mt2w > mt2wCut &&             dphimin > dphiCut && drlb1 < drlblCut && phiCorrMet > metCut && m3 > m3Cut;
      bool allButDphi = (njets - nJetCut) > -0.0001 && mt2w > mt2wCut && y > yCut &&                      drlb1 < drlblCut && phiCorrMet > metCut && m3 > m3Cut;
      bool allButDrlb = (njets - nJetCut) > -0.0001 && mt2w > mt2wCut && y > yCut && dphimin > dphiCut &&                     phiCorrMet > metCut && m3 > m3Cut;
      bool allButMet  = (njets - nJetCut) > -0.0001 && mt2w > mt2wCut && y > yCut && dphimin > dphiCut && drlb1 < drlblCut &&                        m3 > m3Cut;
      bool allButM3   = (njets - nJetCut) > -0.0001 && mt2w > mt2wCut && y > yCut && dphimin > dphiCut && drlb1 < drlblCut && phiCorrMet > metCut              ;

      bool allButCentrality = allCuts && mlb1 < mlbCut;
      bool allButMlb        = allCuts && centrality > centralityCut;

      allCuts    &= centrality > centralityCut && mlb1 < mlbCut;
      allButMt2w &= centrality > centralityCut && mlb1 < mlbCut;
      allButY    &= centrality > centralityCut && mlb1 < mlbCut; 
      allButDphi &= centrality > centralityCut && mlb1 < mlbCut; 
      allButDrlb &= centrality > centralityCut && mlb1 < mlbCut; 
      allButMet  &= centrality > centralityCut && mlb1 < mlbCut;
      allButM3   &= centrality > centralityCut && mlb1 < mlbCut; 
    
      if (iDir%NControlRegions == 0 || iDir%NControlRegions == 1 || iDir%NControlRegions == 2 ){
 	if ( mt > 80.){
	  if (iSample != 0 && allCuts) mth[iDir]->Fill( mt, weight);
          continue;
	}
	if (mt < 50.) {
	  if (allCuts) mth[iDir]->Fill( mt, weight);
	  continue;
	}
      }
      
      if (allButMt2w) mt2wh[iDir]->Fill( mt2w, weight);
      if (allButY) yh[iDir]->Fill( y, weight);
      if (allButDphi) dphiminh[iDir]->Fill( dphimin, weight);
      if (allButDrlb) drlb1h[iDir]->Fill( drlb1, weight);
      if (allButMet) meth[iDir]->Fill( phiCorrMet, weight);
      if (allButM3) m3h[iDir]->Fill( m3, weight);
      if (allButCentrality) centralityh[iDir]->Fill( centrality, weight);
      if (allButMlb) mlb1h[iDir]->Fill( mlb1, weight);
  
      if (allCuts) {
	npvh[iDir]->Fill( npv, weight);
	ngoodpvh[iDir]->Fill( ngoodpv, weight);

	lpth[iDir]->Fill( lPt, weight);
	letah[iDir]->Fill( lEta, weight);
	lrelisoh[iDir]->Fill( lRelIso, weight);
	
	njetsh[iDir]->Fill( njets, weight);
	jet1h[iDir]->Fill( jet1, weight);
	jet2h[iDir]->Fill( jet2, weight);
	jet3h[iDir]->Fill( jet3, weight);
	jet4h[iDir]->Fill( jet4, weight);
	
	nbjetsh[iDir]->Fill( nbjets, weight);
	bjet1h[iDir]->Fill( bjet1, weight);
	bjetHighDh[iDir]->Fill( bjetHighestDisc, weight);
	bdiscHh[iDir]->Fill( bdiscH, weight);
	
	hth[iDir]->Fill( ht, weight);
	ht3h[iDir]->Fill( ht3, weight);
	ht4h[iDir]->Fill( ht4, weight);
	ht5h[iDir]->Fill( ht5, weight);
	htratioh[iDir]->Fill( htRatio, weight);
	meffh[iDir]->Fill( meff, weight);
      
	mth[iDir]->Fill( mt, weight);
	mlb1h[iDir]->Fill( mlb1, weight);
	m3bh[iDir]->Fill( m3b, weight);
	hadchi2h[iDir]->Fill( hadChi2, weight);
	topnessh[iDir]->Fill( topness, weight);
      
	drlbminh[iDir]->Fill( drlbmin, weight);
      }
    }
  }
  
  outFile->Write();
  outFile->Close();
  
  inFile->Close();
  
  return 0;
}
示例#17
0
文件: store.C 项目: XuQiao/HI
void store(int type, int sth=0, int Gth=0){
	TH1::AddDirectory(kFALSE); 
	NBD *l;
	struct para1 var;
        TString dirname;
        double sss=0.1;
	if(sth==0){
	dirname = "std";
	if(Gth<nGlau)
            l = new NBD(datafile,stdGlaulist[Gth],histoname);
	else
            l = new NBD(datafile,stdGlaulist[0],histoname);
	var = var1[Gth];
	l->initmu(bestlist1[Gth].mubest-sss,bestlist1[Gth].mubest+sss,sss/5);
	l->initk(bestlist1[Gth].kbest-sss,bestlist1[Gth].kbest+sss,sss/5);
	l->initf(bestlist1[Gth].fbest-sss,bestlist1[Gth].fbest+sss,sss/5);
	}
        
	else if(sth==1){
	dirname ="Gri055"; 
	if(Gth<nGlau)
            l = new NBD(datafile,Gri055Glaulist[Gth],histoname);
	else
            l = new NBD(datafile,Gri055Glaulist[0],histoname);
	var = var2[Gth];
	l->initmu(bestlist2[Gth].mubest-sss,bestlist2[Gth].mubest+sss,sss/5);
	l->initk(bestlist2[Gth].kbest-sss,bestlist2[Gth].kbest+sss,sss/5);
	l->initf(bestlist2[Gth].fbest-sss,bestlist2[Gth].fbest+sss,sss/5);
	}
        
	else {
	dirname ="Gri101";
	if(Gth<nGlau)
            l = new NBD(datafile,Gri101Glaulist[Gth],histoname);
	else
            l = new NBD(datafile,Gri101Glaulist[0],histoname);
        var = var3[Gth];
	l->initmu(bestlist3[Gth].mubest-sss,bestlist3[Gth].mubest+sss,sss/5);
	l->initk(bestlist3[Gth].kbest-sss,bestlist3[Gth].kbest+sss,sss/5);
	l->initf(bestlist3[Gth].fbest-sss,bestlist3[Gth].fbest+sss,sss/5);
	}

	//l->initmu(var.mumin,var.mumax,var.mustep);
    	//l->initk(var.kmin,var.kmax,var.kstep);
    	//l->initf(var.fmin,var.fmax,var.fstep);
	if(Gth<nGlau)
        	l->initx(var.xmin,var.xmax);
	else if(Gth-nGlau==0)
		l->initx(var.xmin-binshift,var.xmax);
	else
		l->initx(var.xmin+binshift,var.xmax);
if(type==0)
	l->fit();	
if(type==1){
 	if(sth==0) l->assign(bestlist1[Gth].mubest,bestlist1[Gth].kbest,bestlist1[Gth].fbest);
	else if(sth==1) l->assign(bestlist2[Gth].mubest,bestlist2[Gth].kbest,bestlist2[Gth].fbest);
	else l->assign(bestlist3[Gth].mubest,bestlist3[Gth].kbest,bestlist3[Gth].fbest);

        l->initN(bin,N,method);
        l->calcvar();
	TFile *outfile = new TFile(outG,"Update");
	if(Gth==0 && sth==0){
	l->dataname.Write("dataname",TObject::kOverwrite);
	l->histoname.Write("histoname",TObject::kOverwrite);
	}
	TDirectory *dir = (TDirectory*)outfile->GetDirectory(dirname);
	if (!dir) {outfile->mkdir(dirname);	dir = (TDirectory*)outfile->GetDirectory(dirname);}
	dir->cd();
	TString name;
	if(Gth==0)
		name = "G0";
	else if(Gth<nGlau)
		name = Form("Glau_%d",Gth);
	else
		name = Form("bin_%d",Gth-nGlau+1);
	TDirectory *subdir = (TDirectory*)dir->GetDirectory(name);
	if(!subdir) {dir->mkdir(name);	subdir = (TDirectory*)dir->GetDirectory(name);}
	subdir->cd();
	l->method.Write("method",TObject::kOverwrite);
	l->Glaubername.Write("Glaubername",TObject::kOverwrite);
	l->xmin.Write("xmin",TObject::kOverwrite);l->xmax.Write("xmax",TObject::kOverwrite);
	l->mubest.Write("mubest",TObject::kOverwrite);l->kbest.Write("kbest",TObject::kOverwrite);l->fbest.Write("fbest",TObject::kOverwrite);
	l->chis.Write("chis",TObject::kOverwrite);l->Ndf.Write("Ndf",TObject::kOverwrite);
	l->NcollAver.Write("NcollAver",TObject::kOverwrite);l->NpartAver.Write("NpartAver",TObject::kOverwrite);l->BAver.Write("BAver",TObject::kOverwrite);
	l->centbin.Write("centbin",TObject::kOverwrite);	l->kpoint.Write("kpoint",TObject::kOverwrite);
	l->centbin_.Write("centbin_",TObject::kOverwrite);	l->kpoint_.Write("kpoint_",TObject::kOverwrite);
	l->Npartdis->Write("Npartdis",TObject::kSingleKey | TObject::kOverwrite);
	l->Grgrid->Write("Grgrid",TObject::kOverwrite);
        outfile->Close();
}
}
示例#18
0
void SubtractBgndRuns(TDirectory *fbg,
                      TDirectory *fprod,
                      const Char_t *foutname="",
                      const std::string& bl_list="")
{
    std::set<UInt_t> blacklist = GetBlackedChannels(bl_list);

    string basename = FindBaseName(fprod->GetName());

    vector<TH1*> histbg   = ROOTUtils::GetAllTH1InDirectory(fbg);
    ROOTUtils::EnforceProperOrdering(histbg);
    //GetAllHists(*fbg, false);
    FilterOutTDC(histbg);
    vector<TH1*> histprod = ROOTUtils::GetAllTH1InDirectory(fprod,
                                                            Form("^((%s[0-9]+_shifted_norm_vclk)|(%s[0-9]+_norm_vclk_shifted))$",basename.data(),basename.data()));
    ROOTUtils::EnforceProperOrdering(histprod);
    //GetAllHists(*fprod, true);
    //  for_each(histprod.begin(), histprod.end(), InspectSingleHistErrors);
    FilterOutTDC(histprod);

    EnforceAxisRangeConsistency(histbg, histprod);

    TDirectory *fout=0;
    string foname = foutname;
    if (foname.length()>0)
    {

        fout = TFile::Open(foname.data(),"UPDATE");
    }
    else
    {
        TDirectory *basedir = GetBaseDir(fprod);
        if (dynamic_cast<TDirectoryFile*>(basedir)==0)
        {
            std::cerr << "Cannot identify the file" << std::endl;
            return;
        }

        string dname = FormOutputSubDirName(fprod->GetName());
        fout = basedir->GetDirectory(dname.data());
        if (fout==0)
            fout = basedir->mkdir(dname.data());

    }

    TH1 *hbg=0, *h=0, *h_cl=0;
    for (UInt_t i=0; i<min(histbg.size(), histprod.size()); i++)
    {
        hbg = histbg.at(i);
        h   = histprod.at(i);


        h_cl = static_cast<TH1*>(h->Clone(Form("normed_bgsubbed_%s%i",basename.data(), i)));

        if (blacklist.find(i)==blacklist.end())
        {
            cout << histbg.at(i)->GetName() << " subbed from " << histprod.at(i)->GetName() << endl;
            h_cl->SetTitle(Form("Overnight Bgnd Subtracted ADC%i",i));
            h_cl->Add(hbg,-1.0);
            // The next line is only valid if Sumw2 is not turned on
            //  CalcErrors(h_cl, hbg, h);
        }
        else
        {
            cout << histbg.at(i)->GetName() << " blacklisted ... no subtraction" << endl;
            h_cl->SetTitle(Form("ADC%i Without Subtraction",i));
        }

        fout->cd();
        h_cl->Write("",TObject::kOverwrite);
    }
    
    std::cout << "Results saved in " << fout->GetName() << std::endl;

    if (foname.length()>0)
        fout->Close();

}
示例#19
0
int main(int argc, char *argv[]){

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

  //some varaibles
  char filenames[500];
  vector<string> filesVec;
  ifstream fin(InRootList.c_str());
  TChain *sample_AUX = new TChain("TreeMaker2/PreSelection");

  char tempname[200];
  vector<TH1D > vec;
  map<int, string> eventType;
  map<string , vector<TH1D> > cut_histvec_map;
  map<string, map<string , vector<TH1D> > > map_map;
  map<string, histClass> histobjmap;
  histClass histObj;

  //build a vector of histograms
  TH1D weight_hist = TH1D("weight", "Weight Distribution", 5,0,5);
  vec.push_back(weight_hist);
  TH1D RA2HT_hist = TH1D("HT","HT Distribution",50,0,5000);
  RA2HT_hist.Sumw2();
  vec.push_back(RA2HT_hist);
  TH1D RA2MHT_hist = TH1D("MHT","MHT Distribution",100,0,5000);
  RA2MHT_hist.Sumw2();
  vec.push_back(RA2MHT_hist);
  TH1D RA2NJet_hist = TH1D("NJet","Number of Jets Distribution",20,0,20);
  RA2NJet_hist.Sumw2();
  vec.push_back(RA2NJet_hist);
  TH1D RA2NBtag_hist = TH1D("NBtag","Number of Btag Distribution",20,0,20);
  RA2NBtag_hist.Sumw2();
  vec.push_back(RA2NBtag_hist);
  int Nhists=((int)(vec.size())-1);//-1 is because weight shouldn't be counted.

  ///read the file names from the .txt files and load them to a vector.
  while(fin.getline(filenames, 500) ){filesVec.push_back(filenames);}

  cout<< "\nProcessing " << subSampleKey << " ... " << endl;

  for(unsigned int in=0; in<filesVec.size(); in++){ sample_AUX->Add(filesVec.at(in).c_str()); }

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

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

  // Get a pointer to the Selection class  
  Selection2 * sel = new Selection2();

  // For each selection, cut, make a vector containing the same histograms as those in vec
  for(int i=0; i<(int) sel->cutName().size();i++){
    cut_histvec_map[sel->cutName()[i]]=vec;
  }

  // Define different event categories 
  eventType[0]="allEvents";

  //initialize a map between string and maps. copy the map of histvecs into each
  for(int i=0; i< eventType.size();i++){
    map_map[eventType[i]]=cut_histvec_map;
  }

  //initialize histobjmap
  for(map<string , vector<TH1D> >::iterator it=cut_histvec_map.begin(); it!=cut_histvec_map.end();it++){
    histobjmap[it->first]=histObj;
  }

  TH1D* TauIDhist = new TH1D("yield_tauId","Yield after tau Id",200,0.,200.);
  TH1D* TauIDhist_trk = new TH1D("yield_tauId_trk","Yield after trk veto and tau Id",200,0.,200.);
  map <int,string> idMap;
  int IdNum_=0;
  for(int iPile=0;iPile<4;iPile++){
    for(int iIso=0;iIso<4;iIso++){
      for(int iMu=0;iMu<3;iMu++){
        for(int iElec=0;iElec<4;iElec++){
          IdNum_++;
          ostringstream binS_;
          binS_ << (1+iPile)+10*(1+iIso)+100*(1+iMu)+1000*(1+iElec);
          idMap[IdNum_]=binS_.str();
          TauIDhist->GetXaxis()->SetBinLabel(IdNum_,binS_.str().c_str());
          TauIDhist_trk->GetXaxis()->SetBinLabel(IdNum_,binS_.str().c_str());
        }
      }
    }
  }



  // Introduce cutflow histogram to monior event yields for early preselection
  TH1D* cutflow_preselection = new TH1D("cutflow_preselection","cutflow_preselectoion",
                                       11,0.,11.);
  cutflow_preselection->GetXaxis()->SetBinLabel(1,"All Events");
  cutflow_preselection->GetXaxis()->SetBinLabel(2,"Sample based gen-selection");
  cutflow_preselection->GetXaxis()->SetBinLabel(3,"HBHEIsoNoiseFilter");
  cutflow_preselection->GetXaxis()->SetBinLabel(4,"eeBadScFilter");
  cutflow_preselection->GetXaxis()->SetBinLabel(5,"HBHENoiseFilter");
  cutflow_preselection->GetXaxis()->SetBinLabel(6,"GoodVtx");
  cutflow_preselection->GetXaxis()->SetBinLabel(7,"JetID Cleaning");

  int sampletype=-1;
  if(subSampleKey.find("TTbar_Inclusive")!=string::npos)sampletype=0; //TTbar_Inclusive
  else if(subSampleKey.find("TTbar_Tbar_SingleLep")!=string::npos || subSampleKey.find("TTbar_T_SingleLep")!=string::npos)sampletype=1;
  else if(subSampleKey.find("TTbar_DiLept")!=string::npos)sampletype=2;
  else if(subSampleKey.find("TTbar_HT_600_800")!=string::npos)sampletype=3;
  else if(subSampleKey.find("TTbar_HT_800_1200")!=string::npos)sampletype=4;
  else if(subSampleKey.find("TTbar_HT_1200_2500")!=string::npos)sampletype=5;
  else if(subSampleKey.find("TTbar_HT_2500_Inf")!=string::npos)sampletype=6;
  else if(subSampleKey.find("TTbar")!=string::npos){
    cout << " TT sample is not known. Please check the second input \n " ;
    return 2;
  }

  int TotNEve_ = utils2::TotNEve(subSampleKey);
  // Loop over the events (tree entries)
  int eventN=0;
  while( evt->loadNext() ){

  //if(eventN>1000)break;
    // Total weight
    //double totWeight = evt->weight()*1.;
    double totWeight = 10000.*evt->XS()/TotNEve_;
    //printf(" XS: %g NEvents: %d weight: %g \n ",evt->XS(),TotNEve_,totWeight);

    cutflow_preselection->Fill(0.,totWeight); // keep track of all events processed

    if(!evt->DataBool_()){

      if(sampletype==0){
        if(evt->gen_ht()>600||evt->GenElecPtVec_().size()>0||evt->GenMuPtVec_().size()>0||evt->GenTauPtVec_().size()>0)continue;
      }

      if(sampletype==1){
        if(evt->gen_ht()>600)continue;
      }

      if(sampletype==2){
        if(evt->gen_ht()>600)continue;
      }

    }

    cutflow_preselection->Fill(1.,totWeight);
    if(evt->HBHEIsoNoiseFilter_()==0)continue;
    cutflow_preselection->Fill(2.,totWeight);
    if(evt->eeBadScFilter_()==0)continue;
    cutflow_preselection->Fill(3.,totWeight);
    if(evt->HBHENoiseFilter_()==0)continue;
    cutflow_preselection->Fill(4.,totWeight);
    if(!(evt->NVtx_() >0))continue;
    cutflow_preselection->Fill(5.,totWeight);
    // Through out an event that contains HTjets with bad id
    if(evt->JetId()==0)continue;
    cutflow_preselection->Fill(6.,totWeight); // events passing JetID event cleaning


  vector<TLorentzVector> genTauJetLorVec;
  for(int i=0;i<evt->GenTauLorVec()->size();i++){
    TLorentzVector tempVec(evt->GenTauLorVec()->at(i).Px()-evt->GenTauNuLorVec()->at(i).Px(),
                           evt->GenTauLorVec()->at(i).Py()-evt->GenTauNuLorVec()->at(i).Py(),
                           evt->GenTauLorVec()->at(i).Pz()-evt->GenTauNuLorVec()->at(i).Pz(),
                           evt->GenTauLorVec()->at(i).Energy()-evt->GenTauNuLorVec()->at(i).Energy()
                          );
    genTauJetLorVec.push_back(tempVec);
  }

  if(verbose!=0){
    printf(" ############# \n Number of gen tau: %d \n ",evt->GenTauPtVec_().size());
    for(int i=0; i < genTauJetLorVec.size(); i++){
      if(evt->GenTauHadVec_()[i]==1 && genTauJetLorVec.at(i).Pt() > 18.){
        printf(" genTauJet: Pt: %g Eta: %g Phi: %g \n ",genTauJetLorVec.at(i).Pt(),genTauJetLorVec.at(i).Eta(),genTauJetLorVec.at(i).Phi());
        for(int i=0; i<evt->TauLorVec_()->size(); i++){
          printf(" \n patTau: pt: %g eta: %g phi: %g \n ",evt->TauLorVec_()->at(i).Pt(),evt->TauLorVec_()->at(i).Eta(),evt->TauLorVec_()->at(i).Phi());
          printf(" Tauid => id1: %g id2: %g id3: %g id4: %g id5: %g id6: %g id7: %g id8: %g id9: %g id10: %g id11: %g \n ",evt->tauId1()->at(i),evt->tauId2()->at(i),evt->tauId3()->at(i),evt->tauId4()->at(i),evt->tauId5()->at(i),evt->tauId6()->at(i),evt->tauId7()->at(i),evt->tauId8()->at(i),evt->tauId9()->at(i),evt->tauId10()->at(i),evt->tauId11()->at(i));
        }
      }
    }
  }

    //printf("nTau=> 2233: %d 2243: %d 2333: %d 4333: %d 1333: %d \n ",evt->nTauMap()[2233],evt->nTauMap()[2243],evt->nTauMap()[2333],evt->nTauMap()[4333],evt->nTauMap()[1333]);

    // Print out some information
    if(verbose!=0){
      printf(" ########################### \n event #: %d \n",eventN);
      printf(" ht: %g mht: %g nJets: %d nBtags: %d nIsoElec: %d nIsoMu: %d nIsoPion: %d nLeptons: %d \n ",evt->ht(),evt->mht(),evt->nJets(),evt->nBtags(),evt->nIsoElec(),evt->nIsoMu(),evt->nIsoPion(),evt->nLeptons());
      printf(" @@@@\n Jets section: \n Njets: %d \n ", evt->nJets());
      for(int i=0;i<evt->JetsPtVec_().size();i++){
        printf("jet#: %d pt: %g eta: %g phi: %g \n ",i+1,evt->JetsPtVec_()[i],evt->JetsEtaVec_()[i],evt->JetsPhiVec_()[i]);
      }
      printf(" @@@@\n Muons section: \n Nmuons: %d \n ", evt->MuPtVec_().size());
      for(int i=0;i<evt->MuPtVec_().size();i++){
        printf("Muon#: %d pt: %g eta: %g phi: %g \n ",i+1,evt->MuPtVec_()[i],evt->MuEtaVec_()[i],evt->MuPhiVec_()[i]);
      }
    }


    //printf(" mu from tau: %d elec from tau : %d hadronicTau: %d \n ", evt->GenMu_GenMuFromTau_(), evt->GenElec_GenElecFromTau_(),evt->GenTau_GenTauHad_());
    //printf(" #Mu: %d #Tau: %d \n ", evt->GenMuPtVec_().size(), evt->GenTauPtVec_().size());

    // count the number of taus for all possible combinations of tau id s
    vector<int> NtauVec(200,0);

    // apply the baseline cuts here to study the tau id s
    if(sel->nolep(evt->nLeptons())&&sel->Njet_4(evt->nJets())&&sel->ht_500(evt->ht())&&
       sel->mht_200(evt->mht())&&sel->MuIsoTrk(evt->nIsoMu())&&sel->ElecIsoTrk(evt->nIsoElec())&&
       sel->dphi(evt->deltaPhi1(),evt->deltaPhi2(),evt->deltaPhi3(),evt->deltaPhi4()))
    {
      for(int i=0; i<evt->TauLorVec_()->size(); i++){
        // 4 categories of tau id. First is anti-elec which has 3 id's. We also insert a 1 which means non of them are applied. 
        // the following 4 lines correspond whith each of the categories in the tau id. 
        int tauIdElec[4]={1,(int)evt->tauId1()->at(i),(int)evt->tauId2()->at(i),(int)evt->tauId3()->at(i)};
        int tauIdMu[3]  ={1,(int)evt->tauId4()->at(i),(int)evt->tauId5()->at(i)};
        int tauIdIso[4] ={1,(int)evt->tauId6()->at(i),(int)evt->tauId7()->at(i),(int)evt->tauId8()->at(i)};
        int tauIdPile[4]={1,(int)evt->tauId9()->at(i),(int)evt->tauId10()->at(i),(int)evt->tauId11()->at(i)};
        /*
        printf(" id1: %d id2: %d id3: %d id4: %d id5: %d id6: %d id7: %d id8: %d id9: %d id10: %d id11: %d \n",
              (int)evt->tauId1()->at(i),(int)evt->tauId2()->at(i),(int)evt->tauId3()->at(i),(int)evt->tauId4()->at(i),
              (int)evt->tauId5()->at(i),(int)evt->tauId6()->at(i),(int)evt->tauId7()->at(i),(int)evt->tauId8()->at(i),
              (int)evt->tauId9()->at(i),(int)evt->tauId10()->at(i),(int)evt->tauId11()->at(i));      
        */
        int IdNum=0;

        for(int iPile=0;iPile<(sizeof(tauIdPile)/sizeof(tauIdPile[0]));iPile++){
          for(int iIso=0;iIso<(sizeof(tauIdIso)/sizeof(tauIdIso[0]));iIso++){
            for(int iMu=0;iMu<(sizeof(tauIdMu)/sizeof(tauIdMu[0]));iMu++){
              for(int iElec=0;iElec<(sizeof(tauIdElec)/sizeof(tauIdElec[0]));iElec++){
                IdNum++;
                if(tauIdElec[iElec]==1&&tauIdMu[iMu]==1&&tauIdIso[iIso]==1&&tauIdPile[iPile]==1)NtauVec[IdNum]++;
                  //printf(" iPile: %d => %d iIso: %d => %d iMu: %d => %d iElec: %d => %d \n",iPile,tauIdPile[iPile],iIso,tauIdIso[iIso],iMu,tauIdMu[iMu],iElec,tauIdElec[iElec]);
                  //printf(" id #: %d nTau: %d \n ",IdNum,NtauVec[IdNum]);
              }
            }
          }
        }
      } 

      for(int iId=0; iId<NtauVec.size();iId++){
        //printf(" @ \n iId: %d -> %s \n ",iId,idMap[iId].c_str());
        if(NtauVec[iId]==0){
          TauIDhist->Fill(iId-1,totWeight); 
          //cout << " filled \n ";
          if(sel->PionIsoTrk(evt->nIsoPion()))TauIDhist_trk->Fill(iId-1,totWeight);
        }
      }
    }
    // Build and array that contains the quantities we need a histogram for.
    // Here order is important and must be the same as RA2nocutvec
    double eveinfvec[] = {totWeight,(double) evt->ht(),(double) evt->mht() ,(double) evt->nJets(),(double) evt->nBtags()}; //the last one gives the RA2 defined number of jets.     


    //loop over all the different backgrounds: "allEvents", "Wlv", "Zvv"
    for(map<string, map<string , vector<TH1D> > >::iterator itt=map_map.begin(); itt!=map_map.end();itt++){//this will be terminated after the cuts

      ////determine what type of background should pass
      if(itt->first=="allEvents"){//all the cuts are inside this

        //Cuts//Cuts//Cuts//Cuts//Cuts//Cuts//Cuts//Cuts//Cuts//Cuts//Cuts//Cuts//Cuts//Cuts//Cuts//Cuts//Cuts//Cuts//Cuts//Cuts

        //////loop over cut names and fill the histograms
        for(map<string , vector<TH1D> >::iterator ite=cut_histvec_map.begin(); ite!=cut_histvec_map.end();ite++){

          if(sel->checkcut(ite->first,evt->ht(),evt->mht(),evt->deltaPhi1(),evt->deltaPhi2(),evt->deltaPhi3(),evt->deltaPhi4(),evt->nJets(),evt->nBtags(),evt->nLeptons(),evt->nIsoElec(),evt->nIsoMu(),evt->nIsoPion(),evt->nTauMap()[2233],evt->nTauMap()[2243],evt->nTauMap()[2333],evt->nTauMap()[4333],evt->nTauMap()[1333])==true){
             histobjmap[ite->first].fill(Nhists,&eveinfvec[0] ,&itt->second[ite->first][0]);
           } 
        }//end of loop over cut names

        ////EndOfCuts//EndOfCuts//EndOfCuts//EndOfCuts//EndOfCuts//EndOfCuts//EndOfCuts//EndOfCuts//EndOfCuts//EndOfCuts

      }//end of bg_type determination
    }//end of loop over all the different backgrounds: "allEvents", "Wlv", "Zvv"

    eventN++;
  } // End of loop over events


  //open a file to write the histograms
  sprintf(tempname,"%s/results_%s_%s.root",Outdir.c_str(),subSampleKey.c_str(),inputnumber.c_str());
  TFile *resFile = new TFile(tempname, "RECREATE");
  TDirectory *cdtoitt;
  TDirectory *cdtoit;

  cutflow_preselection->Write();
  TauIDhist->Write();
  TauIDhist_trk->Write();

  // Loop over different event categories (e.g. "All events, Wlnu, Zll, Zvv, etc")
  for(int iet=0;iet<(int)eventType.size();iet++){
    for(map<string, map<string , vector<TH1D> > >::iterator itt=map_map.begin(); itt!=map_map.end();itt++){
      if (eventType[iet]==itt->first){
        //KH
        ////std::cout << (itt->first).c_str() << std::endl;
        cdtoitt = resFile->mkdir((itt->first).c_str());
        cdtoitt->cd();
        for(int i=0; i< (int)sel->cutName().size();i++){
          for(map<string , vector<TH1D> >::iterator it=itt->second.begin(); it!=itt->second.end();it++){
            if (sel->cutName()[i]==it->first){
              cdtoit = cdtoitt->mkdir((it->first).c_str());
              cdtoit->cd();
              int nHist = it->second.size();
              for(int i=0; i<nHist; i++){//since we only have 4 type of histograms
                sprintf(tempname,"%s_%s_%s",it->second[i].GetName(),(it->first).c_str(),(itt->first).c_str());
                it->second[i].Write(tempname);
              }
              cdtoitt->cd();
            }
          }
        }
      }
    }
  }




}
示例#20
0
文件: getResVsub.C 项目: XuQiao/HI
//------------------------Deal with the number and get the output stored in txt files and root files
void getResVsub(){
	double Vmax[nbin], eps[nbin];
	for(int ibin=0; ibin<nbin ;ibin++){
        	Vmax[ibin]=0.065*(trkbin[ibin]+30);
        	eps[ibin]=0.00025*(trkbin[ibin]+30);
	}
	ofstream  fstrV;
	double theta[ntheta];
	TVectorD avgmult[nbin], avgpt[nbin], totmult[nbin], totpt[nbin];
	TVectorD Qx1[nbin], Qy1[nbin], Q2[nbin];
	TVectorD Gmod2[nbin][nptV][ntheta];
	TVectorD sigma2[nbin][nptV],deltaV[nbin][nptV];
	TVectorD sigma2_[nbin],chi_[nbin];
	TVectorD deltaVmean[nbin], Vmean[nbin];
	TVectorD deltaVmeanmean, Vmeanmean, sigmaVmeanmean;
	TVectorD r[nbin];
	TVectorD r0[nbin][nptV], r01[nbin][nptV], V[nbin][nptV], chi[nbin][nptV];
	TVectorD GRe[nbin][nptV][ntheta]; TVectorD* GRe_t[nbin][nptV][ntheta];
	TVectorD GIm[nbin][nptV][ntheta]; TVectorD* GIm_t[nbin][nptV][ntheta];
	TComplex G[nbin][nptV][ntheta][nstepr];
	if(isSum)	fstrV.open("V_Sum_sub.txt");
	else	fstrV.open("V_Prod_sub.txt");
	if(isSum)       TString outname = "mergedV_Sum_sub.root";
        else    TString outname="mergedV_Prod_sub.root";
        TFile *outf = new TFile(outname,"Recreate");
        int subsample = (int)(nFileAll/nsamples);
	TFile *f[nFileAll];

        for(int ibin=0; ibin<nbin; ibin++){
		r[ibin].ResizeTo(nstepr);
                for(int ir=0; ir<nstepr; ir++){
        if(isSimple==0)  r[ibin][ir]=j01/(Vmax[ibin]-eps[ibin]*ir);	
	else		 r[ibin][ir]=0.00025*20*(ir+1);
		}
	}
               
	Vmeanmean.ResizeTo(nbin);  Vmeanmean.Zero();
	deltaVmeanmean.ResizeTo(nbin);  deltaVmeanmean.Zero();
	sigmaVmeanmean.ResizeTo(nbin);  sigmaVmeanmean.Zero();
	for(int isample=0;isample<nsamples;isample++){
	cout<<"start with "<<isample<<"\t";
        int start=isample*subsample;
        int end=(isample+1)*subsample;
	TVectorD Nevent;	Nevent.ResizeTo(nbin);  Nevent.Zero();
        TVectorD totmultall;	totmultall.ResizeTo(nbin);      totmultall.Zero();
	
	for(int itheta=0;itheta<ntheta;itheta++)
        	theta[itheta]=itheta*TMath::Pi()/ntheta/nn;

	for(int ibin=0;ibin<nbin;ibin++){
		for(int iptbin=0;iptbin<nptV;iptbin++){
			r0[ibin][iptbin].ResizeTo(ntheta);
			r01[ibin][iptbin].ResizeTo(ntheta);
			sigma2[ibin][iptbin].ResizeTo(ntheta);
			V[ibin][iptbin].ResizeTo(ntheta);
			deltaV[ibin][iptbin].ResizeTo(ntheta);
			chi[ibin][iptbin].ResizeTo(ntheta);
                        for(int itheta=0;itheta<ntheta;itheta++){
				Gmod2[ibin][iptbin][itheta].ResizeTo(nstepr);
				GRe[ibin][iptbin][itheta].ResizeTo(nstepr);
				GRe[ibin][iptbin][itheta].Zero();
				GIm[ibin][iptbin][itheta].ResizeTo(nstepr);
				GIm[ibin][iptbin][itheta].Zero();
			}
		}

		avgmult[ibin].ResizeTo(nptV);	deltaVmean[ibin].ResizeTo(nptV);	Vmean[ibin].ResizeTo(nptV);
		deltaVmean[ibin].Zero();	Vmean[ibin].Zero();
		Vmean[ibin].Zero();	deltaVmean[ibin].Zero();
		totpt[ibin].ResizeTo(nptV);	totpt[ibin].Zero();
		totmult[ibin].ResizeTo(nptV);	totmult[ibin].Zero();
		avgpt[ibin].ResizeTo(nptV);
                Qx1[ibin].ResizeTo(nptV);     Qx1[ibin].Zero();
                Qy1[ibin].ResizeTo(nptV);     Qy1[ibin].Zero();
                Q2[ibin].ResizeTo(nptV);     Q2[ibin].Zero();
		sigma2_[ibin].ResizeTo(nptV);sigma2_[ibin].Zero();
		chi_[ibin].ResizeTo(nptV);chi_[ibin].Zero();
	}

	for(int ifile=start; ifile<end; ifile++){
		if(isSum) f[ifile] = TFile::Open(Form("/lio/lfs/cms/store/user/qixu/flow/pbsjoboutput/pPbDataV205m185/AnaV_Sum_%d.root",ifile));
		else f[ifile] = TFile::Open(Form("/lio/lfs/cms/store/user/qixu/flow/pbsjoboutput/pPbDataV205m185/AnaV_Prod_%d.root",ifile));
		TVectorD* Nevent_t =  (TVectorD*)f[ifile]->Get(Form("Nevent"));
		TVectorD* totmultall_t =  (TVectorD*)f[ifile]->Get(Form("totmultall"));
		for(int ibin=0;ibin<nbin;ibin++){
			for(int iptbin=0;iptbin<nptV;iptbin++){
					for(int itheta=0;itheta<ntheta;itheta++){
					GRe_t[ibin][iptbin][itheta] = (TVectorD*)f[ifile]->Get(Form("GRe_%d_%d_%d",ibin,iptbin,itheta));
					GIm_t[ibin][iptbin][itheta] = (TVectorD*)f[ifile]->Get(Form("GIm_%d_%d_%d",ibin,iptbin,itheta));
					for(ir=0; ir<nstepr; ir++){
						GRe[ibin][iptbin][itheta][ir] += (*GRe_t[ibin][iptbin][itheta])[ir];
						GIm[ibin][iptbin][itheta][ir] += (*GIm_t[ibin][iptbin][itheta])[ir];
					}
				}
			}
			TVectorD* Qx1_t =  (TVectorD*)f[ifile]->Get(Form("Qx1_%d",ibin));
			TVectorD* Qy1_t =  (TVectorD*)f[ifile]->Get(Form("Qy1_%d",ibin));
			TVectorD* Q2_t =  (TVectorD*)f[ifile]->Get(Form("Q2_%d",ibin));
			TVectorD* totmult_t =  (TVectorD*)f[ifile]->Get(Form("totmult_%d",ibin));
			TVectorD* totpt_t =  (TVectorD*)f[ifile]->Get(Form("totpt_%d",ibin));
			for(int iptbin=0;iptbin<nptV;iptbin++){
				Qx1[ibin][iptbin] += (*Qx1_t)[iptbin];
				Qy1[ibin][iptbin] += (*Qy1_t)[iptbin];
				Q2[ibin][iptbin] += (*Q2_t)[iptbin];
				totmult[ibin][iptbin] += (*totmult_t)[iptbin];
				totpt[ibin][iptbin] += (*totpt_t)[iptbin];
			}
			Nevent[ibin] += (*Nevent_t)[ibin];
			totmultall[ibin] += (*totmultall_t)[ibin];	
		}
		f[ifile]->Close();
	}
		
	fstrV<<setprecision(4)<<fixed;
	fstrV<<"ibin"<<"\t"<<"itheta"<<"\t"<<"r0"<<"\t"<<"V"<<"\t"<<"sigma2"<<"\t"<<"chi"<<"\t"<<"Vn Errors"<<endl;
	for(int ibin=0;ibin<nbin;ibin++){
		for(int iptbin=0;iptbin<nptV;iptbin++){
			for(int itheta=0;itheta<ntheta;itheta++){
				for(ir=0; ir<nstepr; ir++){
					G[ibin][iptbin][itheta][ir]=TComplex(GRe[ibin][iptbin][itheta][ir],GIm[ibin][iptbin][itheta][ir]);	
					G[ibin][iptbin][itheta][ir]/=Nevent[ibin];
					Gmod2[ibin][iptbin][itheta][ir]=TMath::Power(TComplex::Abs(G[ibin][iptbin][itheta][ir]),2);
				}
				for(ir=0; ir<nstepr-1; ir++)
					if(ir!=0 && Gmod2[ibin][iptbin][itheta][ir]<=Gmod2[ibin][iptbin][itheta][ir-1] && Gmod2[ibin][iptbin][itheta][ir]<=Gmod2[ibin][iptbin][itheta][ir+1]) break;
				if(ir!=0 && ir<nstepr-1)	r01[ibin][iptbin][itheta]=r[ibin][ir];
				else if(ir==0)	{cout<<"ibin="<<ibin<<"\t"<<"iptbin="<<iptbin<<"\t"<<"itheta="<<itheta<<"\tminimum lies on ir = 0, please select proper range!"<<endl;	continue;}
				else 	{cout<<"ibin="<<ibin<<"\t"<<"iptbin="<<iptbin<<"\t"<<"itheta="<<itheta<<"\tminimum lies on ir = maximum "<<nstepr-1<<", please select proper range!"<<endl;	continue;}
				avgmult[ibin][iptbin]=1.0*totmult[ibin][iptbin]/Nevent[ibin];
				avgpt[ibin][iptbin]=1.0*totpt[ibin][iptbin]/totmult[ibin][iptbin];
				if(isSimple==0)	V[ibin][iptbin][itheta]=Vmax[ibin]-ir*eps[ibin]+eps[ibin]*(Gmod2[ibin][iptbin][itheta][ir+1]-Gmod2[ibin][iptbin][itheta][ir-1])/2./(Gmod2[ibin][iptbin][itheta][ir-1]-2*Gmod2[ibin][iptbin][itheta][ir]+Gmod2[ibin][iptbin][itheta][ir+1]);
				else V[ibin][iptbin][itheta]=j01/r0[ibin][iptbin][itheta]; //simple method
				r0[ibin][iptbin][itheta]=j01/V[ibin][iptbin][itheta];
				V[ibin][iptbin][itheta]/=avgmult[ibin][iptbin];
				//sigma2[ibin][iptbin][itheta]=Q2[ibin][iptbin]/Nevent[ibin]-(Qx1[ibin][iptbin]/Nevent[ibin])*(Qx1[ibin][iptbin]/Nevent[ibin])-(Qy1[ibin][iptbin]/Nevent[ibin])*(Qy1[ibin][iptbin]/Nevent[ibin])-(V[ibin][iptbin][itheta]*avgmult[ibin][iptbin])*(V[ibin][iptbin][itheta]*avgmult[ibin][iptbin]);
				sigma2[ibin][iptbin][itheta]=Q2[ibin][iptbin]/Nevent[ibin]-(Qx1[ibin][iptbin]/Nevent[ibin])*(Qx1[ibin][iptbin]/Nevent[ibin])-(Qy1[ibin][iptbin]/Nevent[ibin])*(Qy1[ibin][iptbin]/Nevent[ibin]);
				sigma2_[ibin][iptbin]+=sigma2[ibin][iptbin][itheta];
				Vmean[ibin][iptbin]+=V[ibin][iptbin][itheta];
				chi[ibin][iptbin][itheta]=V[ibin][iptbin][itheta]*avgmult[ibin][iptbin]/TMath::Sqrt(sigma2[ibin][iptbin][itheta]);
				//deltaV[ibin][iptbin][itheta]=V[ibin][iptbin][itheta]/j01/TMath::BesselJ1(j01)*TMath::Sqrt((TMath::Exp(j01*j01/2./chi[ibin][iptbin][itheta]/chi[ibin][iptbin][itheta])+TMath::Exp(-j01*j01/2./chi[ibin][iptbin][itheta]/chi[ibin][iptbin][itheta])*TMath::BesselJ0(2*j01))/2./Nevent[ibin]);
				}
			sigma2_[ibin][iptbin]/=ntheta;
			Vmean[ibin][iptbin]/=ntheta;
			sigma2_[ibin][iptbin]-=TMath::Power(Vmean[ibin][iptbin]*avgmult[ibin][iptbin],2);
			chi_[ibin][iptbin]=Vmean[ibin][iptbin]*avgmult[ibin][iptbin]/TMath::Sqrt(sigma2_[ibin][iptbin]);
			//deltaVmean[ibin][iptbin]+=TMath::Exp(j01*j01/2./chi[ibin][iptbin][itheta]/chi[ibin][iptbin][itheta]*TMath::Cos(nn*theta[itheta]))*TMath::BesselJ0(2*j01*TMath::Sin(nn*theta[itheta]/2.))+TMath::Exp(-j01*j01/2./chi[ibin][iptbin][itheta]/chi[ibin][iptbin][itheta]*TMath::Cos(nn*theta[itheta]))*TMath::BesselJ0(2*j01*TMath::Cos(nn*theta[itheta]/2.));
			for(int itheta=0;itheta<ntheta;itheta++){
			deltaV[ibin][iptbin][itheta]=V[ibin][iptbin][itheta]/j01/TMath::BesselJ1(j01)*TMath::Sqrt((TMath::Exp(j01*j01/2./chi_[ibin][iptbin]/chi_[ibin][iptbin])+TMath::Exp(-j01*j01/2./chi_[ibin][iptbin]/chi_[ibin][iptbin])*TMath::BesselJ0(2*j01))/2./Nevent[ibin]);
			deltaVmean[ibin][iptbin]+=TMath::Exp(j01*j01/2./chi_[ibin][iptbin]/chi_[ibin][iptbin]*TMath::Cos(nn*theta[itheta]))*TMath::BesselJ0(2*j01*TMath::Sin(nn*theta[itheta]/2.))+TMath::Exp(-j01*j01/2./chi_[ibin][iptbin]/chi_[ibin][iptbin]*TMath::Cos(nn*theta[itheta]))*TMath::BesselJ0(2*j01*TMath::Cos(nn*theta[itheta]/2.));
			fstrV<<ibin<<"\t"<<itheta<<"\t"<<r0[ibin][iptbin][itheta]<<"\t"<<V[ibin][iptbin][itheta]<<"\t"<<sigma2[ibin][iptbin][itheta]<<"\t"<<chi[ibin][iptbin][itheta]<<"\t"<<deltaV[ibin][iptbin][itheta]<<endl;
			}
			fstrV<<endl;
			deltaVmean[ibin][iptbin]=Vmean[ibin][iptbin]/j01/TMath::BesselJ1(j01)*TMath::Sqrt(deltaVmean[ibin][iptbin]/ntheta/2./Nevent[ibin]);
		}
		fstrV<<endl;
	}

	fstrV<<"ibin"<<"\t"<<"avgmult"<<"\t"<<"avgpt"<<"\t"<<"Vn mean"<<"\t"<<"Vn mean Error"<<endl;
	for(int ibin=0;ibin<nbin;ibin++){
		for(int iptbin=0;iptbin<nptV;iptbin++){
			fstrV<<ibin<<"\t"<<avgmult[ibin][iptbin]<<"\t"<<avgpt[ibin][iptbin]<<"\t"<<Vmean[ibin][iptbin]<<"\t"<<deltaVmean[ibin][iptbin]<<endl;
		}
		fstrV<<endl;
	}
	
        TDirectory *dirsample = outf->mkdir(Form("s_%d",isample));
        dirsample->cd();
        Nevent.Write("Nevent");
       	totmultall.Write("totmultall");
        
	for(int ibin=0;ibin<nbin;ibin++){
                TDirectory *dir0 = dirsample->mkdir(Form("D_%d",ibin));dir0->cd();
		r[ibin].Write("r");
		Qx1[ibin].Write("Qx1");
                Qy1[ibin].Write("Qy1");
                Q2[ibin].Write("Q2");
		totmult[ibin].Write("totmult");
		totpt[ibin].Write("totpt");
		avgmult[ibin].Write("avgmult");
		avgpt[ibin].Write("avgpt");
		Vmean[ibin].Write("Vmean");
		deltaVmean[ibin].Write("deltaVmean");
		Vmeanmean[ibin]+=Vmean[ibin][0]/nsamples;
		deltaVmeanmean[ibin]+=deltaVmean[ibin][0]/nsamples;
		sigmaVmeanmean[ibin]+=TMath::Power(Vmean[ibin][0]/nsamples,2);
		chi_[ibin].Write("chi");

		for(int iptbin=0;iptbin<nptV;iptbin++){
                        TDirectory *dir1 = dir0->mkdir(Form("D_%d",iptbin));dir1->cd();
			sigma2[ibin][iptbin].Write("sigma2");	chi[ibin][iptbin].Write("chi0");	deltaV[ibin][iptbin].Write("deltaV");
			r0[ibin][iptbin].Write("r0");	r01[ibin][iptbin].Write("r01");	V[ibin][iptbin].Write("V");

        		for(int itheta=0;itheta<ntheta;itheta++){
                        	TDirectory *dir2 = dir1->mkdir(Form("D_%d",itheta));dir2->cd();
                        	GRe[ibin][iptbin][itheta].Write(Form("GRe"));
                        	GIm[ibin][iptbin][itheta].Write(Form("GIm"));
                        	Gmod2[ibin][iptbin][itheta].Write(Form("G2"));
                	}
        	}
	}
	}
	fstrV<<"ibin"<<"\t"<<"Vn mean mean"<<"\t"<<"Vn mean mean Error"<<"\t"<<"Vn mean deviation"<<endl;
	for(int ibin=0;ibin<nbin;ibin++){
		sigmaVmeanmean[ibin]=TMath::Sqrt(sigmaVmeanmean[ibin]*nsamples-Vmeanmean[ibin]*Vmeanmean[ibin]);
		fstrV<<endl<<ibin<<"\t"<<Vmeanmean[ibin]<<"\t"<<deltaVmeanmean[ibin]<<"\t"<<sigmaVmeanmean[ibin]<<endl;
	}
	outf->cd();
	Vmeanmean.Write("Vmeanmean");
	deltaVmeanmean.Write("deltaVmeanmean");
	sigmaVmeanmean.Write("sigmaVmeanmean");	
	
	cout<<endl;
	
	outf->Close();
}
示例#21
0
mainClass(int luminosity=5000){ // luminosity is in /pb unit



  cutname[0]="nocut";cutname[1]="Njet_4";cutname[2]="ht_500" ;cutname[3]="mht_200";
  cutname[4]="delphi";cutname[5]="iso";
  cutname[6]="CSVM_0";
  cutname[7]="CSVM_1";
  cutname[8]="CSVM_2";
  cutname[9]="CSVM_3";

  WJtype[0]="EventsWith_1RecoMuon_0RecoElectron";
  TTbartype[0]="EventsWith_1RecoMuon_0RecoElectron";



// .....................................................................................................................................................//
// WJ Section
// .....................................................................................................................................................//

  //build a vector of scale factors
  //first load the cross sections into a vector
  vector<double> WJ_xs_vec;

  WJ_xs_vec.push_back(1817.0); // HT 100-200
  WJ_xs_vec.push_back(471.6);  // HT 200-400
  WJ_xs_vec.push_back(55.61);  // HT 400-600
  WJ_xs_vec.push_back(18.81);  // HT 600-Inf

  const int wjnHT = (int) WJ_xs_vec.size();   // Total number of HT bin samples

  for(int i=1; i<=wjnHT ; i++){
    if(i==1)sprintf(tempname,"../Results/results_WJ_HT-100to200_.root");
    else if(i==2)sprintf(tempname,"../Results/results_WJ_HT-200to400_.root");
    else if(i==3)sprintf(tempname,"../Results/results_WJ_HT-400to600_.root");
    else if(i==4)sprintf(tempname,"../Results/results_WJ_HT-600toInf_.root");
    else{cout << " Error!! There are only 4 WJet ht binned sample " << endl;}
    file = new TFile(tempname, "R");
    sprintf(tempname,"allEvents/nocut/MHT_nocut_allEvents");
    tempvalue = (luminosity*WJ_xs_vec[i-1])/((* (TH1D* ) file->Get(tempname)).GetEntries());

printf("Scale: %g, N: %g, Lum: %d, XS: %g \n ",tempvalue,((* (TH1D* ) file->Get(tempname)).GetEntries()),luminosity,WJ_xs_vec[i-1]);

    WJ_scalevec.push_back(tempvalue);
  }//end of loop over HTbins 
  std::cout << "WJ normalization scale factor determination done \n " << std::endl;




//..........................................//
// main histograms like HT, MHT, ...
//..........................................//

  // Load the files to a vector 
  // These are the HT, MHT, .. variables
  for(int i=1; i<=wjnHT ; i++){
    if(i==1)sprintf(tempname,"HadTauEstimation_WJ_HT-100to200_.root");
    else if(i==2)sprintf(tempname,"HadTauEstimation_WJ_HT-200to400_.root");
    else if(i==3)sprintf(tempname,"HadTauEstimation_WJ_HT-400to600_.root");
    else if(i==4)sprintf(tempname,"HadTauEstimation_WJ_HT-600toInf_.root");
    else{cout << " Error!! There are only 4 WJet ht binned sample " << endl;}
    WJ_inputfilevec.push_back(TFile::Open(tempname,"R"));
  }//end of loop over HTbins 

  // Stack
  tempstack = new THStack("stack","Binned Sample Stack");
  sprintf(tempname,"HadTauEstimation_WJ_stacked.root");
  file = new TFile(tempname,"RECREATE");
  histname.clear();
  histname[0]="weight";
  histname[1]="HT";
  histname[2]="MHT";
  histname[3]="NJet";
  histname[4]="NBtag";
  histname[5]="MuonPt";
  histname[6]="MtW";

  for(map<int , string >::iterator itt=WJtype.begin(); itt!=WJtype.end();itt++){        // loop over different event types

    cdtoitt = file->mkdir((itt->second).c_str());
    cdtoitt->cd();

    for(map<int , string >::iterator it=cutname.begin(); it!=cutname.end();it++){   // loop over different cutnames

      cdtoit =  cdtoitt->mkdir((it->second).c_str());
      cdtoit->cd();

      for(int j=0; j<histname.size(); j++){                                        // loop over different histograms

        for(int i=0; i<wjnHT ; i++){                                                  // loop over different HT bins

          //cout << "================================" << endl;
          //cout << "HT#: " <<i << ", WJtype: " << itt->second << ", cutname: " << it->second << ", hist#: " << j << endl;  
          sprintf(tempname,"%s/%s/%s_%s_%s",(itt->second).c_str(),(it->second).c_str(),(histname[j]).c_str(),(it->second).c_str(),(itt->second).c_str());
          temphist = (TH1D *) WJ_inputfilevec.at(i)->Get(tempname)->Clone();
          temphist->Scale(WJ_scalevec[i]);
          temphist->SetFillColor(i+2);
          tempstack->Add(temphist);

        }//end of loop over HTbins 1..7

        sprintf(tempname,"%s_%s_%s",histname[j].c_str(),(it->second).c_str(),(itt->second).c_str());
        tempstack->Write(tempname);

        delete tempstack;
        tempstack = new THStack("stack","Binned Sample Stack");

      }//end of loop over histograms

    }//end of loop over cutnames 

  }//end of loop over event types

  file->Close();
  printf("WJ main histograms stacked \n ");






// .....................................................................................................................................................//
// TTbar Section
// .....................................................................................................................................................//

  //build a vector of scale factors
  //first load the cross sections into a vector
  vector<double> TTbar_xs_vec;

  TTbar_xs_vec.push_back(806.1); // 

  const int ttbarnHT = (int) TTbar_xs_vec.size();   // Total number of HT bin samples

  for(int i=1; i<=ttbarnHT ; i++){
    if(i==1)sprintf(tempname,"../Results/results_TTbar_.root");
    else{cout << " Error!! There are only 1 TTbaret ht binned sample " << endl;}
    file = new TFile(tempname, "R");
    sprintf(tempname,"allEvents/nocut/MHT_nocut_allEvents");
    tempvalue = (luminosity*TTbar_xs_vec[i-1])/((* (TH1D* ) file->Get(tempname)).GetEntries());

printf("Scale: %g, N: %g, Lum: %d, XS: %g \n ",tempvalue,((* (TH1D* ) file->Get(tempname)).GetEntries()),luminosity,TTbar_xs_vec[i-1]);

    TTbar_scalevec.push_back(tempvalue);
  }//end of loop over HTbins 
  std::cout << "TTbar normalization scale factor determination done \n " << std::endl;
  



//..........................................//
// main histograms like HT, MHT, ...
//..........................................//

  // Load the files to a vector 
  // These are the HT, MHT, .. variables
  for(int i=1; i<=ttbarnHT ; i++){
    if(i==1)sprintf(tempname,"HadTauEstimation_TTbar_.root");
    else{cout << " Error!! There are only 1 TTbaret ht binned sample " << endl;}
    TTbar_inputfilevec.push_back(TFile::Open(tempname,"R"));
  }//end of loop over HTbins 

  // Stack
  tempstack = new THStack("stack","Binned Sample Stack");
  sprintf(tempname,"HadTauEstimation_TTbar_stacked.root");
  file = new TFile(tempname,"RECREATE");
  histname.clear();
  histname[0]="weight";
  histname[1]="HT";
  histname[2]="MHT";
  histname[3]="NJet";
  histname[4]="NBtag";
  histname[5]="MuonPt";
  histname[6]="MtW";

  for(map<int , string >::iterator itt=TTbartype.begin(); itt!=TTbartype.end();itt++){        // loop over different event types

    cdtoitt = file->mkdir((itt->second).c_str());
    cdtoitt->cd();

    for(map<int , string >::iterator it=cutname.begin(); it!=cutname.end();it++){   // loop over different cutnames

      cdtoit =  cdtoitt->mkdir((it->second).c_str());
      cdtoit->cd();

      for(int j=0; j<histname.size(); j++){                                        // loop over different histograms

        for(int i=0; i<ttbarnHT ; i++){                                                  // loop over different HT bins

          //cout << "================================" << endl;
          //cout << "HT#: " <<i << ", TTbartype: " << itt->second << ", cutname: " << it->second << ", hist#: " << j << endl;  
          sprintf(tempname,"%s/%s/%s_%s_%s",(itt->second).c_str(),(it->second).c_str(),(histname[j]).c_str(),(it->second).c_str(),(itt->second).c_str());
          temphist = (TH1D *) TTbar_inputfilevec.at(i)->Get(tempname)->Clone();
          temphist->Scale(TTbar_scalevec[i]);
          temphist->SetFillColor(i+2);
          tempstack->Add(temphist);

        }//end of loop over HTbins 1..7

        sprintf(tempname,"%s_%s_%s",histname[j].c_str(),(it->second).c_str(),(itt->second).c_str());
        tempstack->Write(tempname);
        delete tempstack;
        tempstack = new THStack("stack","Binned Sample Stack");

      }//end of loop over histograms

    }//end of loop over cutnames 

  }//end of loop over event types

  file->Close();
  printf("TTbar main histograms stacked \n ");



// ..................................................................................................................................................... //
// Stack main histograms from TTbar and WJet
// ..................................................................................................................................................... //

  // There are two contributors 1-TTbar and 2-WJ
  int NSamples=2;

  // A vector that contains all the samples
  vector<TFile*> sample_inputfilevec;

  THStack * tempstack2 = new THStack("stack","Binned Sample Stack");

  // Load the files to a vector 
  // These are the HT, MHT, .. variables
  for(int i=1; i<=NSamples ; i++){
    if(i==1)sprintf(tempname,"HadTauEstimation_TTbar_stacked.root");
    else if(i==2)sprintf(tempname,"HadTauEstimation_WJ_stacked.root");
    else{cout << " Error!! There are only 2 contributors! " << endl;}
    sample_inputfilevec.push_back(TFile::Open(tempname,"R"));
  }//end of loop over HTbins 

  // Stack
  delete tempstack;
  tempstack = new THStack("stack","Binned Sample Stack");
  sprintf(tempname,"HadTauEstimation_stacked.root");
  file = new TFile(tempname,"RECREATE");
  histname.clear();
  histname[0]="weight";
  histname[1]="HT";
  histname[2]="MHT";
  histname[3]="NJet";
  histname[4]="NBtag";
  histname[5]="MuonPt";
  histname[6]="MtW";

  for(map<int , string >::iterator itt=WJtype.begin(); itt!=WJtype.end();itt++){        // loop over different event types

    cdtoitt = file->mkdir((itt->second).c_str());
    cdtoitt->cd();

    for(map<int , string >::iterator it=cutname.begin(); it!=cutname.end();it++){   // loop over different cutnames

      cdtoit =  cdtoitt->mkdir((it->second).c_str());
      cdtoit->cd();


      for(int j=0; j<histname.size(); j++){                                        // loop over different histograms

        for(int i=0; i<NSamples ; i++){                                                  // loop over different HT bins

          //cout << "================================" << endl;
          //cout << "HT#: " <<i << ", WJtype: " << itt->second << ", cutname: " << it->second << ", hist#: " << j << endl;  
          sprintf(tempname,"%s/%s/%s_%s_%s",(itt->second).c_str(),(it->second).c_str(),(histname[j]).c_str(),(it->second).c_str(),(itt->second).c_str());
          tempstack2 = (THStack *) sample_inputfilevec.at(i)->Get(tempname)->Clone();
          temphist = (TH1D*)tempstack2->GetStack()->Last(); 
          
          temphist->SetFillColor(i+2);
          tempstack->Add(temphist);

        }//end of loop over HTbins 1..7

        sprintf(tempname,"%s_%s_%s",histname[j].c_str(),(it->second).c_str(),(itt->second).c_str());
        tempstack->Write(tempname);
        delete tempstack;
        tempstack = new THStack("stack","Binned Sample Stack");

      }//end of loop over histograms

    }//end of loop over cutnames 

  }//end of loop over event types

  file->Close();
  printf("All samples main histograms stacked \n ");






} // End of the constructor 
示例#22
0
void pixel_scurve() {
    std::cout << "In pixel_scurve" << std::endl;

    //Set the fed/channel ids you want to analyze
    unsigned int fedmin = 33;
    unsigned int fedmax = fedmin;
    //to avoid memory problems do not run more than 12 channels per time
    unsigned int fedchanmin[] = {13} ; //{fedchanmin(fedmin),...,fedchanmin(fedmax)}
    unsigned int fedchanmax[] = {24} ; //{fedchanmax(fedmin),...,fedchanmax(fedmax)}

    //set the rocs you want to analyze
    unsigned int rocmin;
    unsigned int rocmax;
    rocmin=1;
    rocmax=24;

    //set the rows and cols you want to analyze
    int rowmin = 35;
    int rowmax = 44;
    int colmin = 21;
    int colmax = 30;

    //open the data file (please edit it with the correct name)
    std::ifstream in;
    in.open("SCurve_283.dmp",ios::binary|ios::in);
    assert(in.good());

    //open the error log file
    fstream out;
    char errFileName[20];
    if (fedmin==fedmax)  sprintf(errFileName,"FED%d_Channel%d-%d_PixSCurvesErrors.txt",fedmin,fedchanmin[0],fedchanmax[0]) ;
    else sprintf(errFileName,"FED%d-%d_PixSCurvesErrors.txt",fedmin,fedmax);
    out.open(errFileName,fstream::out);


    // for releases pos_2_4_3 and later
    // first 64 bits of dmp file gives run number
    uint64_t run_num;
    in.read((char*)&run_num,8);
    cout << "Run number=" << run_num<<endl;

    //instance the PixelCalib class: it gets all info needed from calib.dat and translation.dat files (please edit them with the correct name)
    PixelCalib calib("calib_SCurve_283.dat","translation.dat");

    //get the list of panel types associated to the disk, blade, panel numbers and the fed and the channel (according to translation.dat)
    std::vector<std::pair<vector<int>,std::string> > panelTypes;
    panelTypes = calib.getPanelTypesAndFEDInfo() ;

    int ntrig=calib.nTriggersPerPattern();

    cout << " ntriggers per pattern=" << ntrig;

    int nvcal=calib.nScanPoints("Vcal" );

    cout << " # scan points=" << nvcal ;

    int vcalmin=int(calib.scanValueMin("Vcal"));
    int vcalmax=int(calib.scanValueMax("Vcal"));
    cout << " min=" << vcalmin << " max=" << vcalmax << endl;

    pixel::SLinkData pixeldata;

    //compute the number of feds, channel and rocs to be analyzed
    unsigned int nOfFed  = fedmax-fedmin+1;
    unsigned int nOfChan[nOfFed];
    unsigned int maxNOfChan = 0;
    for (unsigned int pp=0; pp<nOfFed; ++pp) {
        nOfChan[pp] = fedchanmax[pp]-fedchanmin[pp]+1;
        if (maxNOfChan<fedchanmax[pp]-fedchanmin[pp]+1) maxNOfChan=fedchanmax[pp]-fedchanmin[pp]+1;
    }
    unsigned int nOfROCS = rocmax - rocmin +1;

    //create the matrix with the scurves plots
    pixelROCscurve roceff[nOfFed][maxNOfChan][nOfROCS];

    //initialize expected fed links and all rocs
    cout << "initialize expected fed links and all rocs...";
    for(unsigned int fedid=0; fedid<nOfFed; fedid++) {
        for(unsigned int linkid=0; linkid<nOfChan[fedid]; linkid++) {
            for(unsigned int rocid=0; rocid<nOfROCS; rocid++) { //init all rocs
                //cout << "init link="<<linkid+fedchanmin[fedid]<< " roc="<<rocid+1<<"...";
                roceff[fedid][linkid][rocid].init(linkid+fedchanmin[fedid],rocid+rocmin,nvcal,vcalmin,vcalmax,ntrig);
            }
        }
    }
    cout << " success!" << endl;


    std::vector<unsigned int> const *rows=0;
    std::vector<unsigned int> const *cols=0;

    int nEvent=0;

    //set the maximum naumber of events to be processed
    int maxevent=2000000;
    //maxevent=15000;

    unsigned int vcalvalue=0;

    //event loop: read data
    cout << "Starting event loop..." << endl;
    while(pixeldata.load(in)&&nEvent<maxevent) {
        //cout << "begin of event" << endl;

        if (nEvent%10000==0) cout << "nEvent:"<<nEvent<<endl;

        if (nEvent%(ntrig*nvcal*calib.getNumberOfFeds())==0) {
            cout << "new pattern" <<endl;

            //new pattern: get the rows and columns of this pattern
            calib.getRowsAndCols(nEvent/(ntrig*calib.getNumberOfFeds()),rows,cols);

            assert(rows!=0);
            assert(cols!=0);

            cout << "Event:"<<nEvent<<" Rows:";
            for( unsigned int i=0; i<rows->size(); i++) {
                cout << (*rows)[i]<<" ";
            }
            cout <<" Cols:";
            for( unsigned int i=0; i<cols->size(); i++) {
                cout << (*cols)[i]<<" ";
            }
            cout <<endl;
        }

        if(nEvent%(ntrig)==0) {
            vcalvalue= calib.scanValue("Vcal",nEvent/(ntrig*calib.getNumberOfFeds()));
        }

        //get fedid and skip if not in [fedmin,fedmax]
        int fed = pixeldata.getHeader().getSource_id();
        if ( fed<((int)fedmin) || fed>((int)fedmax) ) {
            nEvent++;
            continue;
        }
        int fedn = fed-fedmin;

        std::vector<pixel::SLinkHit> hits=pixeldata.getHits();
        std::vector<pixel::SLinkHit>::iterator ihit=hits.begin();

        //loop over the hits in the event
        for (; ihit!=hits.end(); ++ihit) {
            //cout << "begin of hits loop" << endl;

            //get channel, roc, row, col
            unsigned int linkid=ihit->get_link_id();
            unsigned int rocid=ihit->get_roc_id();
            unsigned int row=ihit->get_row();
            unsigned int col=ihit->get_col();
            /*       cout << "fed=" << fed << " linkid=" << linkid */
            /* 	  << " rocid=" << rocid */
            /* 	  << " row=" << row */
            /* 	  << " col=" << col << endl; */

            //continue if not in [fedchanmin,fedchanmax] and [rocmin,rocmax]
            if (linkid<fedchanmin[fedn]||linkid>fedchanmax[fedn]) {
                continue;
            }
            if (rocid<rocmin||rocid>rocmax) {
                continue;
            }

            if (row>=80||col>=52) {
                out << "Row or column outside limits (fed,link,roc,row,col):"<<
                    fed<<","<<linkid<<","<<rocid<<"," << row<<","<<col<<endl;
                continue;
            }

            assert(linkid>0&&linkid<37);
            assert(rocid<25);
            assert(row<80);
            assert(col<52);

            bool valid_row=false;
            bool valid_col=false;

            for (unsigned int i=0; i<rows->size(); i++) {
                if (row==(*rows)[i]) valid_row=true;
            }

            for (unsigned int i=0; i<cols->size(); i++) {
                if (col==(*cols)[i]) valid_col=true;
            }

            //fill histograms
            if (valid_row&&valid_col) {
                assert(linkid>=1&&linkid<=36);
                assert(rocid>=1&&rocid<=24);
                //cout << "filling:" << fedn << " "<< linkid-fedchanmin[fedn] << " " << rocid <<" "<< row<<" " << col << endl;
                roceff[fedn][linkid-fedchanmin[fedn]][rocid-rocmin].fill(row,col,vcalvalue);
            }
            else {
                out << "Not valid row or column (fed,link,roc,row,col):"<<
                    fed<<","<<linkid<<","<<rocid<<"," << row<<","<<col<<endl;
            }
            //cout << "end of hits loop" << endl;
        }
        nEvent++;
        //cout << "end of event" << endl;
    }
    cout << "...Processed:"<<nEvent<<" triggers"<<endl;

    // fits
    cout << "Fitting..." ;
    for(unsigned int fedid=0; fedid<nOfFed; fedid++) {
        for(unsigned int channel=0; channel<nOfChan[fedid]; channel++) {
            for(unsigned int roc=0; roc<nOfROCS; roc++) {
                for(int row = rowmin; row<=rowmax; row++) {
                    for(int col = colmin; col<=colmax; col++) {
                        //cout << "fit array pos=" << fedid << " " << channel << " " << roc << " " << row << " " << col << endl;
                        roceff[fedid][channel][roc].fit(row,col);
                    }  //col
                } //row
            } //roc
        } //chan
    }
    cout << "done!" << endl;

    //save plots
    cout << "Making FULL plots" << endl;

    //create output file
    char outFileName[20];
    if (fedmin==fedmax)  sprintf(outFileName,"FED%d_Ch%d-%d_SCurves.root",fedmin,fedchanmin[0],fedchanmax[0]) ;
    else sprintf(outFileName,"FED%d-%d_PixSCurves.root",fedmin,fedmax);
    TFile * f = new TFile(outFileName,"RECREATE") ;

    TDirectory * dirSP = f->mkdir("SummaryPlots");
    dirSP->cd();
    TH1F * hMeanNoise = new TH1F("MeanNoise","MeanNoise",100,0,10);
    TH1F * hMeanThreshold = new TH1F("MeanThreshold","MeanThreshold",100,0,200);

    char title[20] ;

    //these are the kind of plots we save
    TString plotType[] = {"noise","threshold","prob","noiseMap","thresholdMap","probMap"};

    int disk = 0;
    int blade = 0;
    int panel = 0;
    unsigned int myfed = 0;
    unsigned int mycha = 0;
    TString panelType = "";
    TString myPanelType = "";

    //for every panel (=every channel) create a directory and fill it with canvases
    //(one canvas per kind of plots per plaquette)
    for (unsigned int it=0; it<panelTypes.size(); it++) {

        disk  = panelTypes[it].first[0];
        blade = panelTypes[it].first[1];
        panel = panelTypes[it].first[2];
        myfed = panelTypes[it].first[3];
        mycha = panelTypes[it].first[4];
        myPanelType = panelTypes[it].second;

        myfed+=32;

        if (myfed<fedmin||myfed>fedmax) continue;
        unsigned int fedid=myfed-fedmin;
        if (mycha<fedchanmin[fedid]||mycha>fedchanmax[fedid]) continue;
        unsigned int channelId=mycha-fedchanmin[fedid];
        cout << "FED="<< fedmin+fedid <<" Channel " << channelId+fedchanmin[fedid]<<" panelType="<<myPanelType<<endl;

        if(myPanelType=="4L") {
            sprintf(title,"FED%d_Channel%d",fedmin+fedid,channelId+fedchanmin[fedid]) ;
            TDirectory * dir = f->mkdir(title);
            TDirectory * dirNC = dir->mkdir("NoisyCells");
            TDirectory * dirEC = dir->mkdir("ErrorCells");
            for (int kk=0; kk<6; ++kk) { //loop over the kind of plots, i.e. plotType[]
                dir->cd() ;
                panelType = "4L1x2";
                TCanvas * c4L1x2 = new TCanvas(plotType[kk]+panelType, "4L - 1x2", 500,300) ;
                c4L1x2->Divide(2,1) ;
                c4L1x2->cd(1) ;
                roceff[fedid][channelId][1].draw(kk);
                c4L1x2->cd(2) ;
                roceff[fedid][channelId][0].draw(kk);
                c4L1x2->Write() ;

                panelType = "4L2x3";
                TCanvas * c4L2x3 = new TCanvas(plotType[kk]+panelType, "4L - 2x3", 750,600) ;
                c4L2x3->Divide(3,2) ;
                c4L2x3->cd(1) ;
                roceff[fedid][channelId][7].draw(kk);
                c4L2x3->cd(2) ;
                roceff[fedid][channelId][6].draw(kk);
                c4L2x3->cd(3) ;
                roceff[fedid][channelId][5].draw(kk);
                c4L2x3->cd(4) ;
                roceff[fedid][channelId][2].draw(kk);
                c4L2x3->cd(5) ;
                roceff[fedid][channelId][3].draw(kk);
                c4L2x3->cd(6) ;
                roceff[fedid][channelId][4].draw(kk);
                c4L2x3->Write() ;

                panelType = "4L2x4";
                TCanvas * c4L2x4 = new TCanvas(plotType[kk]+panelType, "4L - 2x4", 1000,600) ;
                c4L2x4->Divide(4,2) ;
                c4L2x4->cd(1) ;
                roceff[fedid][channelId][15].draw(kk);
                c4L2x4->cd(2) ;
                roceff[fedid][channelId][14].draw(kk);
                c4L2x4->cd(3) ;
                roceff[fedid][channelId][13].draw(kk);
                c4L2x4->cd(4) ;
                roceff[fedid][channelId][12].draw(kk);
                c4L2x4->cd(5) ;
                roceff[fedid][channelId][8].draw(kk);
                c4L2x4->cd(6) ;
                roceff[fedid][channelId][9].draw(kk);
                c4L2x4->cd(7) ;
                roceff[fedid][channelId][10].draw(kk);
                c4L2x4->cd(8) ;
                roceff[fedid][channelId][11].draw(kk);
                c4L2x4->Write() ;

                panelType = "4L1x5";
                TCanvas * c4L1x5 = new TCanvas(plotType[kk]+panelType, "4L - 1x5", 1250,300) ;
                c4L1x5->Divide(5,1) ;
                c4L1x5->cd(1) ;
                roceff[fedid][channelId][20].draw(kk);
                c4L1x5->cd(2) ;
                roceff[fedid][channelId][19].draw(kk);
                c4L1x5->cd(3) ;
                roceff[fedid][channelId][18].draw(kk);
                c4L1x5->cd(4) ;
                roceff[fedid][channelId][17].draw(kk);
                c4L1x5->cd(5) ;
                roceff[fedid][channelId][16].draw(kk);
                c4L1x5->Write() ;
            }

            dirNC->cd() ;
            for(unsigned int roc=0; roc<nOfROCS; roc++) {
                if (roc>20) break;
                std::vector<pair<unsigned int, unsigned int> > noisyCells = roceff[fedid][channelId][roc].getNoisyCells();
                for (unsigned int jj=0; jj<noisyCells.size(); ++jj) {
                    unsigned int row = noisyCells[jj].first;
                    unsigned int col = noisyCells[jj].second;
                    TString name = "ROC";
                    name+=(roc+rocmin);
                    name+="_ROW";
                    name+=(row);
                    name+="_COL";
                    name+=(col);
                    TCanvas * cc = new TCanvas(name,"noisyCell" , 250,300) ;
                    roceff[fedid][channelId][roc].draw(row,col);
                    cc->Write();
                }
            }
            dirEC->cd() ;
            for(unsigned int roc=0; roc<nOfROCS; roc++) {
                if (roc>20) break;
                std::vector<pair<unsigned int, unsigned int> > errorCells = roceff[fedid][channelId][roc].getErrorCells();
                for (unsigned int jj=0; jj<errorCells.size(); ++jj) {
                    unsigned int row = errorCells[jj].first;
                    unsigned int col = errorCells[jj].second;
                    TString name = "ROC";
                    name+=(roc+rocmin);
                    name+="_ROW";
                    name+=(row);
                    name+="_COL";
                    name+=(col);
                    TCanvas * cc = new TCanvas(name,"errorCell" , 250,300) ;
                    roceff[fedid][channelId][roc].draw(row,col);
                    cc->Write();
                }
            }
        }
        else if(myPanelType=="3L") {
            sprintf(title,"FED%d_Channel%d",fedmin+fedid,channelId+fedchanmin[fedid]) ;
            TDirectory * dir = f->mkdir(title);
            TDirectory * dirNC = dir->mkdir("NoisyCells");
            TDirectory * dirEC = dir->mkdir("ErrorCells");
            for (int kk=0; kk<6; ++kk) { //loop over the kind of plots, i.e. plotType[]
                dir->cd() ;
                panelType = "3L2x3";
                TCanvas * c3L2x3 = new TCanvas(plotType[kk]+panelType, "3L - 2x3", 750,600) ;
                c3L2x3->Divide(3,2) ;
                c3L2x3->cd(1) ;
                roceff[fedid][channelId][5].draw(kk);
                c3L2x3->cd(2) ;
                roceff[fedid][channelId][4].draw(kk);
                c3L2x3->cd(3) ;
                roceff[fedid][channelId][3].draw(kk);
                c3L2x3->cd(4) ;
                roceff[fedid][channelId][0].draw(kk);
                c3L2x3->cd(5) ;
                roceff[fedid][channelId][1].draw(kk);
                c3L2x3->cd(6) ;
                roceff[fedid][channelId][2].draw(kk);
                c3L2x3->Write() ;

                panelType = "3L2x4";
                TCanvas * c3L2x4 = new TCanvas(plotType[kk]+panelType, "3L - 2x4", 1000,600) ;
                c3L2x4->Divide(4,2) ;
                c3L2x4->cd(1) ;
                roceff[fedid][channelId][13].draw(kk);
                c3L2x4->cd(2) ;
                roceff[fedid][channelId][12].draw(kk);
                c3L2x4->cd(3) ;
                roceff[fedid][channelId][11].draw(kk);
                c3L2x4->cd(4) ;
                roceff[fedid][channelId][10].draw(kk);
                c3L2x4->cd(5) ;
                roceff[fedid][channelId][6].draw(kk);
                c3L2x4->cd(6) ;
                roceff[fedid][channelId][7].draw(kk);
                c3L2x4->cd(7) ;
                roceff[fedid][channelId][8].draw(kk);
                c3L2x4->cd(8) ;
                roceff[fedid][channelId][9].draw(kk);
                c3L2x4->Write() ;

                panelType = "3L2x5";
                TCanvas * c3L2x5 = new TCanvas(plotType[kk]+panelType, "3L - 2x5", 1250,600) ;
                c3L2x5->Divide(5,2) ;
                c3L2x5->cd(1) ;
                roceff[fedid][channelId][23].draw(kk);
                c3L2x5->cd(2) ;
                roceff[fedid][channelId][22].draw(kk);
                c3L2x5->cd(3) ;
                roceff[fedid][channelId][21].draw(kk);
                c3L2x5->cd(4) ;
                roceff[fedid][channelId][20].draw(kk);
                c3L2x5->cd(5) ;
                roceff[fedid][channelId][19].draw(kk);
                c3L2x5->cd(6) ;
                roceff[fedid][channelId][14].draw(kk);
                c3L2x5->cd(7) ;
                roceff[fedid][channelId][15].draw(kk);
                c3L2x5->cd(8) ;
                roceff[fedid][channelId][16].draw(kk);
                c3L2x5->cd(9) ;
                roceff[fedid][channelId][17].draw(kk);
                c3L2x5->cd(10) ;
                roceff[fedid][channelId][18].draw(kk);
                c3L2x5->Write() ;
            }

            dirNC->cd() ;
            for(unsigned int roc=0; roc<nOfROCS; roc++) {
                std::vector<pair<unsigned int, unsigned int> > noisyCells = roceff[fedid][channelId][roc].getNoisyCells();
                for (unsigned int jj=0; jj<noisyCells.size(); ++jj) {
                    unsigned int row = noisyCells[jj].first;
                    unsigned int col = noisyCells[jj].second;
                    TString name = "ROC";
                    name+=(roc+rocmin);
                    name+="_ROW";
                    name+=(row);
                    name+="_COL";
                    name+=(col);
                    TCanvas * cc = new TCanvas(name,"noisyCell" , 250,300) ;
                    roceff[fedid][channelId][roc].draw(row,col);
                    cc->Write();
                }
            }
            dirEC->cd() ;
            for(unsigned int roc=0; roc<nOfROCS; roc++) {
                std::vector<pair<unsigned int, unsigned int> > errorCells = roceff[fedid][channelId][roc].getErrorCells();
                for (unsigned int jj=0; jj<errorCells.size(); ++jj) {
                    unsigned int row = errorCells[jj].first;
                    unsigned int col = errorCells[jj].second;
                    TString name = "ROC";
                    name+=(roc+rocmin);
                    name+="_ROW";
                    name+=(row);
                    name+="_COL";
                    name+=(col);
                    TCanvas * cc = new TCanvas(name,"errorCell" , 250,300) ;
                    roceff[fedid][channelId][roc].draw(row,col);
                    cc->Write();
                }
            }
        }
        if(myPanelType=="4R") {
            sprintf(title,"FED%d_Channel%d",fedmin+fedid,channelId+fedchanmin[fedid]) ;
            TDirectory * dir = f->mkdir(title);
            TDirectory * dirNC = dir->mkdir("NoisyCells");
            TDirectory * dirEC = dir->mkdir("ErrorCells");
            for (int kk=0; kk<6; ++kk) { //loop over the kind of plots, i.e. plotType[]
                dir->cd() ;
                panelType = "4R1x2";
                TCanvas * c4R1x2 = new TCanvas(plotType[kk]+panelType, "4R - 1x2", 500,300) ;
                c4R1x2->Divide(2,1) ;
                c4R1x2->cd(1) ;
                roceff[fedid][channelId][20].draw(kk);
                c4R1x2->cd(2) ;
                roceff[fedid][channelId][19].draw(kk);
                c4R1x2->Write() ;

                panelType = "4R2x3";
                TCanvas * c4R2x3 = new TCanvas(plotType[kk]+panelType, "4R - 2x3", 750,600) ;
                c4R2x3->Divide(3,2) ;
                c4R2x3->cd(1) ;
                roceff[fedid][channelId][15].draw(kk);
                c4R2x3->cd(2) ;
                roceff[fedid][channelId][14].draw(kk);
                c4R2x3->cd(3) ;
                roceff[fedid][channelId][13].draw(kk);
                c4R2x3->cd(4) ;
                roceff[fedid][channelId][16].draw(kk);
                c4R2x3->cd(5) ;
                roceff[fedid][channelId][17].draw(kk);
                c4R2x3->cd(6) ;
                roceff[fedid][channelId][18].draw(kk);
                c4R2x3->Write() ;

                panelType = "4R2x4";
                TCanvas * c4R2x4 = new TCanvas(plotType[kk]+panelType, "4R - 2x4", 1000,600) ;
                c4R2x4->Divide(4,2) ;
                c4R2x4->cd(1) ;
                roceff[fedid][channelId][8].draw(kk);
                c4R2x4->cd(2) ;
                roceff[fedid][channelId][7].draw(kk);
                c4R2x4->cd(3) ;
                roceff[fedid][channelId][6].draw(kk);
                c4R2x4->cd(4) ;
                roceff[fedid][channelId][5].draw(kk);
                c4R2x4->cd(5) ;
                roceff[fedid][channelId][9].draw(kk);
                c4R2x4->cd(6) ;
                roceff[fedid][channelId][10].draw(kk);
                c4R2x4->cd(7) ;
                roceff[fedid][channelId][11].draw(kk);
                c4R2x4->cd(8) ;
                roceff[fedid][channelId][12].draw(kk);
                c4R2x4->Write() ;

                panelType = "4R1x5";
                TCanvas * c4R1x5 = new TCanvas(plotType[kk]+panelType, "4R - 1x5", 1250,300) ;
                c4R1x5->Divide(5,1) ;
                c4R1x5->cd(1) ;
                roceff[fedid][channelId][4].draw(kk);
                c4R1x5->cd(2) ;
                roceff[fedid][channelId][3].draw(kk);
                c4R1x5->cd(3) ;
                roceff[fedid][channelId][2].draw(kk);
                c4R1x5->cd(4) ;
                roceff[fedid][channelId][1].draw(kk);
                c4R1x5->cd(5) ;
                roceff[fedid][channelId][0].draw(kk);
                c4R1x5->Write() ;
            }
            dirNC->cd() ;
            for(unsigned int roc=0; roc<nOfROCS; roc++) {
                if (roc>20) break;
                std::vector<pair<unsigned int, unsigned int> > noisyCells = roceff[fedid][channelId][roc].getNoisyCells();
                for (unsigned int jj=0; jj<noisyCells.size(); ++jj) {
                    unsigned int row = noisyCells[jj].first;
                    unsigned int col = noisyCells[jj].second;
                    TString name = "ROC";
                    name+=(roc+rocmin);
                    name+="_ROW";
                    name+=(row);
                    name+="_COL";
                    name+=(col);
                    TCanvas * cc = new TCanvas(name,"noisyCell" , 250,300) ;
                    roceff[fedid][channelId][roc].draw(row,col);
                    cc->Write();
                }
            }
            dirEC->cd() ;
            for(unsigned int roc=0; roc<nOfROCS; roc++) {
                if (roc>20) break;
                std::vector<pair<unsigned int, unsigned int> > errorCells = roceff[fedid][channelId][roc].getErrorCells();
                for (unsigned int jj=0; jj<errorCells.size(); ++jj) {
                    unsigned int row = errorCells[jj].first;
                    unsigned int col = errorCells[jj].second;
                    TString name = "ROC";
                    name+=(roc+rocmin);
                    name+="_ROW";
                    name+=(row);
                    name+="_COL";
                    name+=(col);
                    TCanvas * cc = new TCanvas(name,"errorCell" , 250,300) ;
                    roceff[fedid][channelId][roc].draw(row,col);
                    cc->Write();
                }
            }
        }
        else if(myPanelType=="3R") {
            sprintf(title,"FED%d_Channel%d",fedmin+fedid,channelId+fedchanmin[fedid]) ;
            TDirectory * dir = f->mkdir(title);
            TDirectory * dirNC = dir->mkdir("NoisyCells");
            TDirectory * dirEC = dir->mkdir("ErrorCells");
            for (int kk=0; kk<6; ++kk) { //loop over the kind of plots, i.e. plotType[]
                dir->cd() ;
                panelType = "3R2x3";
                TCanvas * c3R2x3 = new TCanvas(plotType[kk]+panelType, "3R - 2x3"+plotType[kk], 750,600) ;
                c3R2x3->Divide(3,2) ;
                c3R2x3->cd(1) ;
                roceff[fedid][channelId][20].draw(kk);
                c3R2x3->cd(2) ;
                roceff[fedid][channelId][19].draw(kk);
                c3R2x3->cd(3) ;
                roceff[fedid][channelId][18].draw(kk);
                c3R2x3->cd(4) ;
                roceff[fedid][channelId][21].draw(kk);
                c3R2x3->cd(5) ;
                roceff[fedid][channelId][22].draw(kk);
                c3R2x3->cd(6) ;
                roceff[fedid][channelId][23].draw(kk);
                c3R2x3->Write() ;

                panelType = "3R2x4";
                TCanvas * c3R2x4 = new TCanvas(plotType[kk]+panelType, "3R - 2x4"+plotType[kk], 1000,600) ;
                c3R2x4->Divide(4,2) ;
                c3R2x4->cd(1) ;
                roceff[fedid][channelId][13].draw(kk);
                c3R2x4->cd(2) ;
                roceff[fedid][channelId][12].draw(kk);
                c3R2x4->cd(3) ;
                roceff[fedid][channelId][11].draw(kk);
                c3R2x4->cd(4) ;
                roceff[fedid][channelId][10].draw(kk);
                c3R2x4->cd(5) ;
                roceff[fedid][channelId][14].draw(kk);
                c3R2x4->cd(6) ;
                roceff[fedid][channelId][15].draw(kk);
                c3R2x4->cd(7) ;
                roceff[fedid][channelId][16].draw(kk);
                c3R2x4->cd(8) ;
                roceff[fedid][channelId][17].draw(kk);
                c3R2x4->Write() ;

                panelType = "3R2x5";
                TCanvas * c3R2x5 = new TCanvas(plotType[kk]+panelType, "3R - 2x5"+plotType[kk], 1250,600) ;
                c3R2x5->Divide(5,2) ;
                c3R2x5->cd(1) ;
                roceff[fedid][channelId][4].draw(kk);
                c3R2x5->cd(2) ;
                roceff[fedid][channelId][3].draw(kk);
                c3R2x5->cd(3) ;
                roceff[fedid][channelId][2].draw(kk);
                c3R2x5->cd(4) ;
                roceff[fedid][channelId][1].draw(kk);
                c3R2x5->cd(5) ;
                roceff[fedid][channelId][0].draw(kk);
                c3R2x5->cd(6) ;
                roceff[fedid][channelId][5].draw(kk);
                c3R2x5->cd(7) ;
                roceff[fedid][channelId][6].draw(kk);
                c3R2x5->cd(8) ;
                roceff[fedid][channelId][7].draw(kk);
                c3R2x5->cd(9) ;
                roceff[fedid][channelId][8].draw(kk);
                c3R2x5->cd(10) ;
                roceff[fedid][channelId][9].draw(kk);
                c3R2x5->Write() ;
            }
            dirNC->cd() ;
            for(unsigned int roc=0; roc<nOfROCS; roc++) {
                std::vector<pair<unsigned int, unsigned int> > noisyCells = roceff[fedid][channelId][roc].getNoisyCells();
                for (unsigned int jj=0; jj<noisyCells.size(); ++jj) {
                    unsigned int row = noisyCells[jj].first;
                    unsigned int col = noisyCells[jj].second;
                    TString name = "ROC";
                    name+=(roc+rocmin);
                    name+="_ROW";
                    name+=(row);
                    name+="_COL";
                    name+=(col);
                    TCanvas * cc = new TCanvas(name,"noisyCell" , 250,300) ;
                    roceff[fedid][channelId][roc].draw(row,col);
                    cc->Write();
                }
            }
            dirEC->cd() ;
            for(unsigned int roc=0; roc<nOfROCS; roc++) {
                std::vector<pair<unsigned int, unsigned int> > errorCells = roceff[fedid][channelId][roc].getErrorCells();
                for (unsigned int jj=0; jj<errorCells.size(); ++jj) {
                    unsigned int row = errorCells[jj].first;
                    unsigned int col = errorCells[jj].second;
                    TString name = "ROC";
                    name+=(roc+rocmin);
                    name+="_ROW";
                    name+=(row);
                    name+="_COL";
                    name+=(col);
                    TCanvas * cc = new TCanvas(name,"errorCell" , 250,300) ;
                    roceff[fedid][channelId][roc].draw(row,col);
                    cc->Write();
                }
            }
        }
        //summary plots
        for (unsigned int roc=0; roc<nOfROCS; roc++) {
            if ((myPanelType=="4R"||myPanelType=="4L")&&roc>20) break;
            if (roceff[fedid][channelId][roc].isValid()) {
                //cout << "filling summary plot: fedid=" << fedid << " channelId=" << channelId << " roc=" << roc << endl;
                double meanSig = roceff[fedid][channelId][roc].getMeanNoise();
                double meanThr = roceff[fedid][channelId][roc].getMeanThreshold();
                hMeanNoise->Fill(meanSig);
                hMeanThreshold->Fill(meanThr);
                if (meanSig>3)   out << "FED=" << fedid+fedmin << " channel=" << channelId+fedchanmin[fedid]
                                         << " ROC="<< roc+rocmin <<" Mean Noise=" << meanSig << endl;
                if (meanThr>130) out << "FED=" << fedid+fedmin << " channel=" << channelId+fedchanmin[fedid]
                                         << " ROC="<< roc+rocmin <<" Mean Threshold=" << meanThr << endl;
            }
        }
    }
    dirSP->cd();
    hMeanNoise->Write();
    hMeanThreshold->Write();
    f->Close() ;



    /*   TCanvas* c=0; */
    /*   if(false)   {// summary plots */
    /*     cout << "Making plots" << endl; */
    /*     for(unsigned int channel=chanmin; channel<=chanmax; channel++) { */
    /*       for(unsigned int roc=rocmin; roc<=rocmax; roc++) { */

    /* 	c= new TCanvas("ROC_Scurve_Results","ROC Scurve Results", 700, 800); */
    /* 	c->Divide(2,3); */
    /* 	c->cd(1); */
    /* 	roceff[channel][roc].drawThresholds(); */
    /* 	c->cd(2); */
    /* 	roceff[channel][roc].drawThreshold(); */
    /* 	c->cd(3); */
    /* 	roceff[channel][roc].drawNoises(); */
    /* 	c->cd(4); */
    /* 	roceff[channel][roc].drawNoise(); */
    /* 	c->cd(5); */
    /* 	roceff[channel][roc].drawFitProbs(); */
    /* 	c->cd(6); */
    /* 	roceff[channel][roc].drawFitProb(); */

    /* 	TString name="SCurveResults"; */
    /* 	name=name+"_Channel"; */
    /* 	name+=(channel+1); */
    /* 	name+="_ROC"; */
    /* 	name+=(roc+1); */
    /* 	name+=".pdf"; */
    /* 	c->Print(name); */

    /* 	int plotnumber=0; */

    /* 	bool plotted=false; */
    /* 	for(int row = 35;row<45;row++){ */
    /* 	  for(int col = 21; col<31;col++) { */

    /* 	    if (plotnumber%12==0){ */
    /* 	      TString name="SCurve"; */
    /* 	      name=name+TString(plotnumber/12+1); */
    /* 	      c=new TCanvas(name,name, 700,800); */
    /* 	      c->Divide(3 ,4); */
    /* 	    } */

    /* 	    if (roceff[channel][roc].filled(row,col)){ */
    /* 	      c->cd(plotnumber%12+1); */
    /* 	      roceff[channel][roc].draw(row,col); */
    /* 	      plotted=true; */
    /* 	      plotnumber++; */
    /* 	    } */

    /* 	    if (plotted&&(plotnumber%12==0)){ */
    /* 	      TString name="SCurves"; */
    /* 	      name=name+"_Channel"; */
    /* 	      name+=(channel+1); */
    /* 	      name+="_ROC"; */
    /* 	      name+=(roc+1); */
    /* 	      name+=".ps"; */
    /* 	      if(plotnumber==12) name+="("; */
    /* 	      c->Print(name); */
    /* 	      plotted=false; */
    /* 	    } //new page */
    /* 	  } // loop col */
    /* 	} // loop row */
    /* 	if (plotted) { */
    /* 	  TString name="SCurves"; */
    /* 	  name=name+"_Channel"; */
    /* 	  name+=(channel+1); */
    /* 	  name+="_ROC"; */
    /* 	  name+=(roc+1); */
    /* 	  name+=".ps)"; */
    /* 	  c->Print(name); */
    /* 	} */
    /*       } // roc */
    /*     } // channel */
    /*   } // make plots   */

}  // void pixel_scurve()
示例#23
0
int ScanChain( TChain* chain, bool fast = true, int nEvents = -1, string skimFilePrefix = "test") {

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

  // Example Histograms
  TDirectory *rootdir = gDirectory->GetDirectory("Rint:");
  // samplehisto->SetDirectory(rootdir);

  TH1F *h_muonCount = new TH1F("h_muonCount", "Number of Muons in this event", 90, 0, 5);

  // MuonTagAndProbe: define the trigger to check here
  vector<string> triggerNames;
  triggerNames.push_back("HLT_IsoMu24");
  triggerNames.push_back("HLT_IsoTkMu24");
  // triggerNames.push_back("HLT_IsoMu20");
  // triggerNames.push_back("HLT_IsoTkMu20");
  // triggerNames.push_back("HLT_Ele27_eta2p1_WPLoose_Gsf");
  // triggerNames.push_back("HLT_Ele22_eta2p1_WPLoose_Gsf");

  // Separate vector to store the pt cut to be used for eta and phi
  vector<float> triggerPtCuts(triggerNames.size(), 50);
  // triggerPtCuts[2] = 25;
  // triggerPtCuts[3] = 25;

  vector<map<histType,TH1F*>> muonHists = creatMuonHists(triggerNames);
  vector<map<histType,TH1F*>> muonHists1 = creatMuonHists(triggerNames, "_1");
  vector<map<histType,TH1F*>> muonHists2 = creatMuonHists(triggerNames, "_2");
  vector<map<histType,TH1F*>> muonHists3 = creatMuonHists(triggerNames, "_3");

  // 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() );
    TTree *tree = (TTree*)file.Get("t");
    if (fast) TTreeCache::SetLearnEntries(10);
    if (fast) tree->SetCacheSize(128*1024*1024);
    t.Init(tree);

    int evt_num = -1;
    int nMuonCount = 0;
    int isTriggerMuon = 0;
    LorentzVector p4mu;
    LorentzVector tag_p4mu;

    vector<TBranch*> trigBranches = setupTriggerBranches(triggerNames, tree);
    vector<TBranch*> tagTrigBranches = setupTagTriggerBranches(triggerNames, tree);

    // 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);
      t.GetEntry(event);
      ++nEventsTotal;

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

      // Analysis Code

      if (evt_isRealData() && evt_run() < 273423) continue;  // Get runs after fixing the L1 interface problem

      int nevt = evt_event();
      if (nevt != evt_num) {
        h_muonCount->Fill(nMuonCount);
        nMuonCount = 0;
        isTriggerMuon = 0;
      }

      // --- New Tag & Probe ---
      if (abs(id()) != 13) continue;
      if (p4().pt() < 10) continue;
      if (fabs(p4().eta()) > 2.4 ) continue;
      if (charge()*tag_charge() > 0) continue;
      if (tag_p4().pt() < 25) continue;
      if (tag_RelIso03EA() > 0.1) continue;
      if (dilep_mass() < 81.2 || dilep_mass() > 101.2) continue;
      if (!pid_PFMuon()) continue;

      ++nMuonCount;
      // if (nMuonCount > 2) continue;

      for (unsigned int i=0; i<triggerNames.size(); i++) {
        if (getTriggerValue(tagTrigBranches[i], event) <= 0) continue;

        fillTagMuonHists(muonHists[i],  triggerPtCuts[i]);
        if (passes_IsoCut() && passes_leptonID())
          fillProbeMuonHists(muonHists[i], trigBranches[i], event, triggerPtCuts[i]);

        fillTagMuonHists(muonHists1[i], triggerPtCuts[i]);
        fillTagMuonHists(muonHists2[i], triggerPtCuts[i]);
        fillTagMuonHists(muonHists3[i], triggerPtCuts[i]);

        fillDenMuonHists(muonHists1[i], triggerPtCuts[i]);
        if (passes_IsoCut() && passes_leptonID())
          fillNumMuonHists(muonHists1[i], triggerPtCuts[i]);

        if (passes_IsoCut()) {
          fillDenMuonHists(muonHists2[i], triggerPtCuts[i]);
          if (passes_leptonID())
            fillNumMuonHists(muonHists2[i], triggerPtCuts[i]);
        }

        if (passes_leptonID()) {
          fillDenMuonHists(muonHists3[i], triggerPtCuts[i]);
          if (passes_IsoCut())
            fillNumMuonHists(muonHists3[i], triggerPtCuts[i]);
        }
      }

      // End of Analysis Code
    }

    // Clean Up
    delete tree;
    file.Close();
  }
  if ( nEventsChain != nEventsTotal ) {
    cout << Form( "ERROR: number of events from files (%d) is not equal to total number of events (%d)", nEventsChain, nEventsTotal ) << endl;
  }

  // return
  bmark->Stop("benchmark");

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

  for (unsigned int i=0; i<triggerNames.size(); i++) {
    TDirectory * dir = (TDirectory*) outfile->mkdir(triggerNames[i].c_str());
    dir->cd();
    TDirectory * dir2 = (TDirectory*) dir->mkdir("trigeff");
    dir2->cd();
    writeEfficiencyPlots(muonHists[i], triggerNames[i], outfile);
    dir2 = (TDirectory*) dir->mkdir("ID+ISO");
    dir2->cd();
    writeEfficiencyPlots(muonHists1[i], triggerNames[i], outfile);
    dir2 = (TDirectory*) dir->mkdir("ID");
    dir2->cd();
    writeEfficiencyPlots(muonHists2[i], triggerNames[i], outfile);
    dir2 = (TDirectory*) dir->mkdir("ISO");
    dir2->cd();
    writeEfficiencyPlots(muonHists3[i], triggerNames[i], outfile);
  }

  h_muonCount->Write();

  outfile->Close();

  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;
}
int main(int argc, char** argv)
{ 
 TDRStyle();
 
 gStyle->SetPadTopMargin(0.11);
 gStyle->SetPadLeftMargin(0.07);
 gStyle->SetPadRightMargin(0.23);
 gStyle->cd(); 
 
 
 std::cout << " " << std::endl;
 std::cout << " " << std::endl;
 std::cout << "   ___|                                       _)                           \\  |   ___|         /      __ \\     \\  __ __|   \\     " << std::endl;
 std::cout << "  |       _ \\   __ `__ \\   __ \\    _` |   __|  |   __|   _ \\   __ \\       |\\/ |  |            /       |   |   _ \\    |    _ \\    " << std::endl;
 std::cout << "  |      (   |  |   |   |  |   |  (   |  |     | \\__ \\  (   |  |   |      |   |  |           /        |   |  ___ \\   |   ___ \\   " << std::endl;
 std::cout << " \\____| \\___/  _|  _|  _|  .__/  \\__,_| _|    _| ____/ \\___/  _|  _|     _|  _| \\____|     _/        ____/ _/    _\\ _| _/    _\\  " << std::endl;
 std::cout << "                          _|                                                                                                     " << std::endl;
 std::cout << " " << std::endl;
 std::cout << " " << std::endl;
 std::cout << "     ___ \\   __ \\        " << std::endl;
 std::cout << "       ) |  |   |          " << std::endl;
 std::cout << "      __/   |   |          " << std::endl;
 std::cout << "    _____| ____/           " << std::endl;
 std::cout << " " << std::endl;
 std::cout << " " << std::endl;
 
 
 
 char normal[] = { 0x1b, '[', '0', ';', '3', '9', 'm', 0 };
 char black[] = { 0x1b, '[', '0', ';', '3', '0', 'm', 0 };
 char red[] = { 0x1b, '[', '0', ';', '3', '1', 'm', 0 };
 char green[] = { 0x1b, '[', '0', ';', '3', '2', 'm', 0 };
 char yellow[] = { 0x1b, '[', '0', ';', '3', '3', 'm', 0 };
 char blue[] = { 0x1b, '[', '0', ';', '3', '4', 'm', 0 };
 char purple[] = { 0x1b, '[', '0', ';', '3', '5', 'm', 0 };
 char cyan[] = { 0x1b, '[', '0', ';', '3', '6', 'm', 0 };
 char Lgray[] = { 0x1b, '[', '0', ';', '3', '7', 'm', 0 };
 char Dgray[] = { 0x1b, '[', '0', ';', '3', '8', 'm', 0 };
 char Bred[] = { 0x1b, '[', '1', ';', '3', '1', 'm', 0 };
 //for bold colors, just change the 0 after the [ to a 1
 
 EColor vColor[1000] = {
  (EColor) (kRed+1),
  (EColor) (kRed+3),
  (EColor) (kGray+1),
  (EColor) (kAzure-2),
  (EColor) (kAzure-9),
  (EColor) (kYellow),
  (EColor) (kGreen+2),
//   
  kGreen,
  //kMagenta,(EColor) (kMagenta+1),(EColor) (kMagenta+2),
  kTeal,//(EColor) (kTeal+1),
  kRed,
  kGray,
  kOrange,(EColor) (kOrange+1),
  kBlue,//(EColor)(kBlue+1),(EColor) (kBlue+2),
  (EColor) (kPink+2),//(EColor) (kPink+1),(EColor) (kPink+2),
  kViolet,
  kYellow,
  kGray,(EColor) (kGray+1),(EColor) (kViolet),(EColor) (kYellow),(EColor) (kGray)
 };
 
 
 
 
 //Check if all nedeed arguments to parse are there                                                                                                                               
 if(argc != 2)
 {
  std::cerr << ">>>>> analysis.cpp::usage: " << argv[0] << " configFileName" << std::endl ;
  return 1;
 }


 // Parse the config file                                                                                                          
 parseConfigFile (argv[1]) ;
 
 std::string treeName  = gConfigParser -> readStringOption("Input::treeName");
 std::string treeNameSelections = gConfigParser -> readStringOption("Input::treeNameSelections");
 std::string fileSamples = gConfigParser -> readStringOption("Input::fileSamples");
 std::string inputDirectory = gConfigParser -> readStringOption("Input::inputDirectory");
 
 std::string inputBeginningFile = "out_NtupleProducer_"; 
 try {
  inputBeginningFile = gConfigParser -> readStringOption("Input::inputBeginningFile");
 }
 catch (char const* exceptionString){
  std::cerr << " exception = " << exceptionString << std::endl;
 }
 std::cout << ">>>>> Input::inputBeginningFile  " << inputBeginningFile  << std::endl;  
 
 double LUMI = gConfigParser -> readDoubleOption("Input::Lumi");
 
 double LumiSyst = gConfigParser -> readDoubleOption("Input::LumiSyst");
 
 double Discovery = gConfigParser -> readDoubleOption("Input::Discovery");
 
 int Normalize = gConfigParser -> readIntOption("Input::Normalize");
 
 std::vector<std::string> SignalName;
 if (Discovery == 1) SignalName = gConfigParser -> readStringListOption("Input::SignalName");
 
 
 ///==== PU reweight (begin) ====
 bool doWeightFromFile = false; 
 try {
  doWeightFromFile = gConfigParser -> readStringOption("PU::doWeightFromFile");
 }
 catch (char const* exceptionString){
  std::cerr << " exception = " << exceptionString << std::endl;
 }
 std::cout << ">>>>> PU::doWeightFromFile  " << doWeightFromFile  << std::endl;  
 
 std::vector<double> PUMC;
 std::vector<double> PUDATA;
 PUclass PU;
 double sumPUMC = 0;
 double sumPUDATA = 0;
 TH1F* hPUMC;
 TH1F* hPUDATA;
 TH1F* hPUWeight;
 
 
 
 std::string nameWeight = "weight"; 
 if (doWeightFromFile) {
  try {
   nameWeight = gConfigParser -> readStringOption("PU::nameWeight");
  }
  catch (char const* exceptionString){
   std::cerr << " exception = " << exceptionString << std::endl;
  }
  std::cout << ">>>>> PU::nameWeight  " << nameWeight  << std::endl;  
 }
 
 if (!doWeightFromFile) {
  
  PUMC   = gConfigParser -> readDoubleListOption("PU::PUMC");
  PUDATA = gConfigParser -> readDoubleListOption("PU::PUDATA");
  
  std::cout << " PUMC.size()   = " << PUMC.size()   << std::endl;
  std::cout << " PUDATA.size() = " << PUDATA.size() << std::endl;
  
  if (PUMC.size() != PUDATA.size()) {
   std::cerr << " ERROR " << std::endl;
   return 1;
  }
  
  for (int itVPU = 0; itVPU < PUMC.size(); itVPU++ ){
   sumPUMC += PUMC.at(itVPU);  
  }
  for (int itVPU = 0; itVPU < PUDATA.size(); itVPU++ ){
   sumPUDATA += PUDATA.at(itVPU);  
  } 
  
  for (int itVPU = 0; itVPU < PUMC.size(); itVPU++ ){
   PU.PUWeight.push_back(PUDATA.at(itVPU) / PUMC.at(itVPU) * sumPUMC / sumPUDATA);
  }
  
  PU.Write("autoWeight.cxx");
  gROOT->ProcessLine(".L autoWeight.cxx");
  
  ///==== save PU distribution in TH1F ====
  hPUMC   = new TH1F("hPUMC","hPUMC",PUMC.size(),0,PUMC.size());
  hPUDATA = new TH1F("hPUDATA","hPUDATA",PUDATA.size(),0,PUDATA.size());
  hPUWeight = new TH1F("hPUWeight","hPUWeight",PUDATA.size(),0,PUDATA.size());
  
  for (int itVPU = 0; itVPU < PUMC.size(); itVPU++ ){
   hPUMC     -> SetBinContent(itVPU+1,PUMC.at(itVPU) / sumPUMC);
   hPUDATA   -> SetBinContent(itVPU+1,PUDATA.at(itVPU) / sumPUDATA);
   hPUWeight -> SetBinContent(itVPU+1,PUDATA.at(itVPU) / PUMC.at(itVPU) * sumPUMC / sumPUDATA);
  }
  
 }
 
 ///==== PU reweight (end) ====
 
 ///==== pT Higgs reweight (begin) ====
 std::string nameptHWeight; 
 try {
  nameptHWeight = gConfigParser -> readStringOption("Input::nameptHWeight");
 }
 catch (char const* exceptionString){
  std::cerr << " exception = " << exceptionString << std::endl;
 }
 std::cout << ">>>>> input::nameptHWeight  " << nameptHWeight  << std::endl;  
 if (nameptHWeight != ""){
  TString toLoad;
  //   toLoad = Form("cp %s ./",nameptHWeight.c_str());
  //   gROOT->ProcessLine(toLoad.Data());
  toLoad = Form(".L %s",nameptHWeight.c_str());
  gROOT->ProcessLine(toLoad.Data());
 }
 
 std::string nameptHWeightSample; 
 try {
  nameptHWeight = gConfigParser -> readStringOption("Input::nameptHWeightSample");
 }
 catch (char const* exceptionString){
  std::cerr << " exception = " << exceptionString << std::endl;
 }
 std::cout << ">>>>> input::nameptHWeightSample  " << nameptHWeightSample  << std::endl;  
 
 
 ///==== pT Higgs reweight (end) ====
 
 TTree *treeEffVect[100];
 TTree *treeJetLepVect[100];
 

 
  //  [iCut][iVar] 
 TString* infoString[20][30];
 TLatex *infoLatex[20][30]; 
 TCanvas* ccCanvas[20][30];
 TCanvas* ccCanvasPull[20][30];
 TCanvas* ccCanvasPullTrace[20][30];
 TH2F* histoSumMC[20][30];
 //  [iName][iCut][iVar]
 TH2F* histo[100][30][30];
 TH2F* histo_temp[100][20][30];

 //  [iName][iCut]
 double numEvents[100][30];
 
 char *nameSample[1000];
 char *nameHumanReadable[1000];
 char* xsectionName[1000];
 
 double Normalization[1000];
 double xsection[1000];
 char nameFileIn[1000];
 sprintf(nameFileIn,"%s",fileSamples.c_str());

 int numberOfSamples = ReadFile(nameFileIn, nameSample, nameHumanReadable, xsectionName); 
 
 ///==== list of variables to plot ====
 std::vector<std::pair<double, double> > vMin;
 std::vector<std::pair<double, double> > vMax;
 std::vector<std::pair<int, int> > vNBin;
 std::vector<std::pair<std::string, std::string> > vVarName;
 std::vector<std::pair<std::string, std::string> > vVarNameHR;
 std::string VarFile = gConfigParser -> readStringOption("Plot::VarFile");
 
 int numVar = ReadFileVar2D(VarFile,vMin,vMax,vNBin,vVarName,vVarNameHR);
  
 
//  double XSection  = gConfigParser -> readDoubleOption("Plot::XSection");
 
 ///==== list of selections to perform (NOT sequential additive selections) ====
 std::string CutFile = gConfigParser -> readStringOption("Selections::CutFile");

 std::string CutHRFile = "";
 try {
  CutHRFile = gConfigParser -> readStringOption("Selections::CutHRFile");
 }
 catch (char const* exceptionString){
  std::cerr << " exception = " << exceptionString << std::endl;
 }
 
 std::vector<std::string> vCut;
 std::vector<std::string> vCutHR;
 
 std::cout << " nCuts   = " << ReadFileCut(CutFile, vCut) << std::endl;
 if (CutHRFile != "") {
  std::cout << " nCutsHR = " << ReadFileCutHR(CutHRFile, vCutHR) << std::endl;
 }
 
 
 if (vCutHR.size() < vCut.size()) {
  int size1 = vCut.size();
  int size2 = vCutHR.size();
  for (int i=0; i<(size1-size2+2); i++) {
   vCutHR.push_back("test");
  }
 }
 
 ///==== output file ====
 std::string OutFileName    = gConfigParser -> readStringOption("Output::outFileName");
 std::cout << ">>>>> Output::outFileName  " << OutFileName  << std::endl;  
 
 TFile outFile(OutFileName.c_str(),"RECREATE");
 outFile.cd();
 
 ///==== Latinos flag ==== 
 bool  Latinos = false; 
 try {
  Latinos = gConfigParser -> readBoolOption("Input::Latinos");
 }
 catch (char const* exceptionString){
  std::cerr << " exception = " << exceptionString << std::endl;
 }
 std::cout << ">>>>> input::Latinos  " << Latinos  << std::endl;  
 
 ///==== debug flag ====
 
 bool  debug = false; 
 try {
  debug = gConfigParser -> readBoolOption("Input::debug");
 }
 catch (char const* exceptionString){
  std::cerr << " exception = " << exceptionString << std::endl;
 }
 std::cout << ">>>>> input::debug  " << debug  << std::endl;  
 
 ///==== program ====
 
 
 double start, end;
 start = clock();
 
 
 for (int iSample=0; iSample<numberOfSamples; iSample++){
  xsection[iSample] = atof(xsectionName[iSample]);
 }
 for (int iSample=0; iSample<numberOfSamples; iSample++){
  
  char nameFile[20000];
  sprintf(nameFile,"%s/%s%s.root",inputDirectory.c_str(),inputBeginningFile.c_str(),nameSample[iSample]);  
  TFile* f = new TFile(nameFile, "READ");
  
  treeEffVect[iSample] = (TTree*) f->Get(treeNameSelections.c_str());
  if (treeEffVect[iSample] != 0) {
   char nameTreeEff[100];
   sprintf(nameTreeEff,"treeEff_%d",iSample); 
   treeEffVect[iSample]->SetName(nameTreeEff);      
  }
  
  treeJetLepVect[iSample] = (TTree*) f->Get(treeName.c_str());
  char nameTreeJetLep[100];
  sprintf(nameTreeJetLep,"treeJetLep_%d",iSample); 
  treeJetLepVect[iSample]->SetName(nameTreeJetLep);
 }
 
 ///===== create map for joint sample ====
 
 std::vector<int> join_samples;
 std::vector<std::string> name_samples;
 for (int iSample=0; iSample<numberOfSamples; iSample++){
  name_samples.push_back(nameHumanReadable[iSample]);
  join_samples.push_back(-1);
 }
 
 
 std::vector<std::string> reduced_name_samples;
 std::vector<int>         reduced_name_samples_flag;
 for (int iSample = (numberOfSamples-1); iSample>= 0; iSample--){
  bool flag_name = false;
  for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
   if (reduced_name_samples.at(iName) == name_samples.at(iSample)) flag_name = true;
  }
  if (flag_name == false) {
   reduced_name_samples.push_back(name_samples.at(iSample));
   reduced_name_samples_flag.push_back(-1);
  }
 }
 
 std::cout << " numberOfSamples = " << numberOfSamples << std::endl;
 
 for (int iSample = (numberOfSamples-1); iSample>= 0; iSample--){
  double XSection;
  int numEntriesBefore;
  double preselection_efficiency;
  if (treeEffVect[iSample] != 0) {   
   treeEffVect[iSample]->SetBranchAddress("XSection",&XSection);
   treeEffVect[iSample]->SetBranchAddress("numEntriesBefore",&numEntriesBefore);
   treeEffVect[iSample]->SetBranchAddress("preselection_efficiency",&preselection_efficiency);  
   treeEffVect[iSample]->GetEntry(0);
  }
  
  std::cout << " Xsection = " << XSection << " ~~~> " << xsection[iSample] << std::endl;
  XSection = xsection[iSample];
  
  if (numEntriesBefore != 0) {
   Normalization[iSample] = LUMI * XSection * preselection_efficiency / numEntriesBefore;
  }
  else {
   Normalization[iSample] = 0; 
  }    
  
  if (Latinos) Normalization[iSample] = XSection * LUMI / 1000.;
 }
 
 
 
 TLegend* leg = new TLegend(0.8,0.25,0.98,0.78);
 bool LegendBuilt = false;

 TString lumiName = Form("#splitline{L = %.1f pb^{-1}}{#splitline{#sqrt{s} = 7}{CMS preliminary}}", LUMI);
//  TString lumiName = Form("#sqrt{s}=7 TeV   L=%.1f pb^{-1}", LUMI);
 TLatex *latex = new TLatex(0.80, 0.90, lumiName); 
 latex->SetTextAlign(12);
 latex->SetNDC();
 latex->SetTextFont(42);
 latex->SetTextSize(0.03);
  
 ///==== get number in sample list that correspond to DATA ====
 int numDATA = -1;
 for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
  if (reduced_name_samples.at(iName) == "DATA") {
   numDATA = iName;
  }
 }
 
 
 if (debug) std::cout << " Cut size = " << vCut.size() << " ~~ " << std::endl;
 std::cout.precision (2) ;
 
 ///==== cicle on selections ====
 for (unsigned int iCut = 0; iCut<vCut.size(); iCut++){
  TString Cut = Form ("%s",vCut.at(iCut).c_str());
  if (debug) std::cout << " Cut[" << iCut << ":" << vCut.size() << "] = " << Cut.Data() << " ~~ " << std::endl;
  ///==== cicle on variables to plot ====
  for (unsigned int iVar = 0; iVar<vVarName.size(); iVar++){  
   if (debug) std::cout << " Var[" << iVar << ":" << vVarName.size() << "] = " << vVarName.at(iVar).first << " && " << vVarName.at(iVar).second << " ~~ " << std::endl;
   ///==== initialize ====
   for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
    reduced_name_samples_flag.at(iName) = -1;
   }
   
   ///==== cicle on samples ====
   for (int iSample = (numberOfSamples-1); iSample>= 0; iSample--){
    if (debug) std::cout << " Sample[" << iSample << ":" << numberOfSamples << "] = " << nameSample[iSample] << " ~~ " << std::endl;
    TString name_histo_temp = Form("%s_%d_%d_temp",nameSample[iSample], iCut, iVar);
    histo_temp[iSample][iCut][iVar] = new TH2F(name_histo_temp,name_histo_temp,vNBin.at(iVar).first,vMin.at(iVar).first, vMax.at(iVar).first,vNBin.at(iVar).second,vMin.at(iVar).second, vMax.at(iVar).second);
    char toDraw[1000];
    sprintf(toDraw,"%s:%s >> %s",vVarName.at(iVar).second.c_str(),vVarName.at(iVar).first.c_str(),name_histo_temp.Data());      

    histo_temp[iSample][iCut][iVar] -> Sumw2(); //---- così mette l'errore giusto!
    
    TString CutExtended;
    bool isData = false;
    for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
     if (name_samples.at(iSample) == reduced_name_samples.at(iName)){
      if (iName == numDATA) {
       isData = true;
      }
     }
    }  
    if (!isData) {
     if (nameptHWeight != "" && name_samples.at(iSample) == nameptHWeightSample){
      if (!doWeightFromFile) {
       CutExtended = Form ("(%s) * autoWeight(numPUMC) * ptHWeight(ptH)",Cut.Data());    
      }
      else {
       CutExtended = Form ("(%s) * ptHWeight(ptH) * (%s)",Cut.Data(),nameWeight.c_str());    
      }
     }
     else {
      if (!doWeightFromFile) {
       CutExtended = Form ("(%s) * autoWeight(numPUMC)",Cut.Data());    
      }
      else {
       CutExtended = Form ("(%s) * (%s)",Cut.Data(),nameWeight.c_str());    
      }
     }
     //      CutExtended = Form ("(%s) * autoWeight(numPUMC) * ptHWeight(ptH)",Cut.Data());    
    }
    else {
     CutExtended = Form ("(%s)",Cut.Data());    
    }
    treeJetLepVect[iSample]->Draw(toDraw,CutExtended,"");
    
    if (Normalization[iSample]>0) { 
//      histo_temp[iSample][iCut][iVar] -> Sumw2();
     histo_temp[iSample][iCut][iVar] -> Scale(Normalization[iSample]); 
    }
    
//     std::cout << "Processing: " << blue << (((double) numberOfSamples - iSample)/numberOfSamples) << "% \r"  << normal << std::flush;
   } ///==== end cicle on samples ====
//    std::cout << "###";
  std::cout << "Processing: " << blue << (((double) iCut)/vCut.size())*100. << "% "  << normal <<  " -- " <<  blue << (((double) iVar)/vVarName.size())*100. << "% \r"  << normal << std::flush;   
  } ///==== end cicle on variables to plot ====
  //   std::cout << "***";
 } ///==== end cicle on selections ====
 std::cout << std::endl; 
 
 

 
 ///---- create "big" histos ----
 for (unsigned int iCut = 0; iCut<vCut.size(); iCut++){
  for (unsigned int iVar = 0; iVar<vVarName.size(); iVar++){
   ///---- initialize (begin) ----
   for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
    reduced_name_samples_flag.at(iName) = -1;
   }
   ///---- initialize (end) ----
   for (int iSample = (numberOfSamples-1); iSample>= 0; iSample--){    
    for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
     if (name_samples.at(iSample) == reduced_name_samples.at(iName) && iName == numDATA){
      if (reduced_name_samples_flag.at(iName) == -1){
       TString name_histoTot_temp = Form("%s_%d_%d_Tot_temp",reduced_name_samples.at(iName).c_str(),iCut, iVar);
       TString name_HR_histoTot_temp = Form("%s vs %s @ %s",vVarNameHR.at(iVar).second.c_str(),vVarNameHR.at(iVar).first.c_str(), vCutHR.at(iCut).c_str());
       //        TString name_HR_histoTot_temp = Form("%s %d %s",vVarNameHR.at(iVar).c_str(), iCut, reduced_name_samples.at(iName).c_str());
       histo[iName][iCut][iVar] = new TH2F(name_histoTot_temp,name_HR_histoTot_temp,vNBin.at(iVar).first,vMin.at(iVar).first, vMax.at(iVar).first,vNBin.at(iVar).second,vMin.at(iVar).second, vMax.at(iVar).second);
       histo[iName][iCut][iVar] -> Sumw2(); //---- così mette l'errore giusto!
       reduced_name_samples_flag.at(iName) = 1;
      }
      histo[iName][iCut][iVar] -> Add(histo_temp[iSample][iCut][iVar]);
     }
    }
   }
  }
 }
 
 
 if (Normalize == 1) { //---- normalize to Data ----
 for (unsigned int iCut = 0; iCut<vCut.size(); iCut++){
  for (unsigned int iVar = 0; iVar<vVarName.size(); iVar++){
   ///---- initialize (begin) ----
   for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
    reduced_name_samples_flag.at(iName) = -1;
   }
   ///---- initialize (end) ----
   double data_int = histo[numDATA][iCut][iVar] -> Integral();
   double mc_int = 0;
   
   for (int iSample = (numberOfSamples-1); iSample>= 0; iSample--){
    for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
     if (name_samples.at(iSample) == reduced_name_samples.at(iName) && iName != numDATA){
      mc_int += histo_temp[iSample][iCut][iVar] -> Integral();
     }
    }
   }
   
   std::cout << " data_int / mc_int = " << data_int / mc_int << std::endl;
   for (int iSample = (numberOfSamples-1); iSample>= 0; iSample--){ 
    histo_temp[iSample][iCut][iVar] -> Scale (data_int / mc_int);
    
    for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
     if (name_samples.at(iSample) == reduced_name_samples.at(iName)  && iName != numDATA){
      if (reduced_name_samples_flag.at(iName) == -1){
       TString name_histoTot_temp = Form("%s_%d_%d_Tot_temp",reduced_name_samples.at(iName).c_str(),iCut, iVar);
       TString name_HR_histoTot_temp = Form("%s vs %s @ %s",vVarNameHR.at(iVar).second.c_str(),vVarNameHR.at(iVar).first.c_str(), vCutHR.at(iCut).c_str());
       //        TString name_HR_histoTot_temp = Form("%s %d %s",vVarNameHR.at(iVar).c_str(), iCut, reduced_name_samples.at(iName).c_str());
       histo[iName][iCut][iVar] = new TH2F(name_histoTot_temp,name_HR_histoTot_temp,vNBin.at(iVar).first,vMin.at(iVar).first, vMax.at(iVar).first,vNBin.at(iVar).second,vMin.at(iVar).second, vMax.at(iVar).second);
       histo[iName][iCut][iVar] -> Sumw2(); //---- così mette l'errore giusto!
       reduced_name_samples_flag.at(iName) = 1;
      }
      histo[iName][iCut][iVar] -> Add(histo_temp[iSample][iCut][iVar]);
     }
    }
   }
  }
 }
 
 }
 else { //---- normalize to Lumi
  
  for (unsigned int iCut = 0; iCut<vCut.size(); iCut++){
   for (unsigned int iVar = 0; iVar<vVarName.size(); iVar++){
    ///---- initialize (begin) ----
    for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
     reduced_name_samples_flag.at(iName) = -1;
    }
    ///---- initialize (end) ----
    for (int iSample = (numberOfSamples-1); iSample>= 0; iSample--){
     
     for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
      if (name_samples.at(iSample) == reduced_name_samples.at(iName) && iName != numDATA ){
       if (reduced_name_samples_flag.at(iName) == -1){
	TString name_histoTot_temp = Form("%s_%d_%d_Tot_temp",reduced_name_samples.at(iName).c_str(),iCut, iVar);
	TString name_HR_histoTot_temp = Form("%s vs %s @ %s",vVarNameHR.at(iVar).second.c_str(),vVarNameHR.at(iVar).first.c_str(), vCutHR.at(iCut).c_str());
	//        TString name_HR_histoTot_temp = Form("%s %d %s",vVarNameHR.at(iVar).c_str(), iCut, reduced_name_samples.at(iName).c_str());
	histo[iName][iCut][iVar] = new TH2F(name_histoTot_temp,name_HR_histoTot_temp,vNBin.at(iVar).first,vMin.at(iVar).first, vMax.at(iVar).first,vNBin.at(iVar).second,vMin.at(iVar).second, vMax.at(iVar).second);
	histo[iName][iCut][iVar] -> Sumw2(); //---- così mette l'errore giusto!
	reduced_name_samples_flag.at(iName) = 1;
       }
       histo[iName][iCut][iVar] -> Add(histo_temp[iSample][iCut][iVar]);
      }
     }
    }
   }
  }
 }
 
 
 //  [iCut][iVar]
 THStack* hs[100][100];
 
 std::cout << std::endl;
 
 ///==== cicle on selections ====
 for (unsigned int iCut = 0; iCut<vCut.size(); iCut++){
  ///==== cicle on variables to plot ====
  for (unsigned int iVar = 0; iVar<vVarName.size(); iVar++){
   TString nameStack = Form("%d_%d_stack",iCut,iVar);
   hs[iCut][iVar] = new THStack(nameStack,nameStack);
   
   for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
    histo[iName][iCut][iVar]->GetXaxis()->SetTitle(vVarNameHR.at(iVar).first.c_str());
    histo[iName][iCut][iVar]->GetYaxis()->SetTitle(vVarNameHR.at(iVar).second.c_str());
    histo[iName][iCut][iVar]->SetMarkerColor(vColor[iName]);
    histo[iName][iCut][iVar]->SetLineColor(vColor[iName]);
    histo[iName][iCut][iVar]->SetFillColor(vColor[iName]);
    histo[iName][iCut][iVar]->SetLineWidth(2);
    histo[iName][iCut][iVar]->SetFillStyle(3001);
    
    bool isSig = false;
    for (std::vector<std::string>::const_iterator itSig = SignalName.begin(); itSig != SignalName.end(); itSig++){
     if (reduced_name_samples.at(iName) == *itSig) isSig = true;
    }
    
    if (!isSig && reduced_name_samples.at(iName) != "DATA") {
     hs[iCut][iVar]->Add(histo[iName][iCut][iVar]);
    }
    else {
     if (!isSig) {
      histo[iName][iCut][iVar]->SetMarkerStyle(20);
      histo[iName][iCut][iVar]->SetMarkerSize(1);
      histo[iName][iCut][iVar]->SetMarkerColor(kBlack);
      histo[iName][iCut][iVar]->SetLineColor(kBlack);
      histo[iName][iCut][iVar]->SetFillColor(kBlack);
      histo[iName][iCut][iVar]->SetLineWidth(2);
      histo[iName][iCut][iVar]->SetFillStyle(3001);  
     }
     else {
      histo[iName][iCut][iVar]->SetMarkerStyle(21);
      histo[iName][iCut][iVar]->SetMarkerSize(1);
      histo[iName][iCut][iVar]->SetLineWidth(2);
      histo[iName][iCut][iVar]->SetFillStyle(3001);  
     }
    }
   }
   ///==== histo sum MC ====    
   ///==== Add systrematic error ====
//    AddError(hs[iCut][iVar],LumiSyst);
   histoSumMC[iCut][iVar] = ((TH2F*)(hs[iCut][iVar]->GetStack()->Last()));
    
   ///==== legend ====
   if (!LegendBuilt){
    for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
     leg->AddEntry(histo[iName][iCut][iVar],reduced_name_samples.at(iName).c_str(),"pf");    
     LegendBuilt = true;
    }
   }
  }
 }
 std::cout << std::endl << std::endl;
 
 
 
 LumiSyst = 0; ///---- bug fix
 

//  [iName][iCut][iVar]
 TCanvas* cCanvasAll[100][30][30];

 TCanvas* cCompareCut[100];
 TCanvas* cCompareVar[100];
 
 for (unsigned int iCut = 0; iCut<vCut.size(); iCut++){
  TString nameCanvas = Form("%d_Cut_Canvas",iCut);
  cCompareCut[iCut] = new TCanvas(nameCanvas,nameCanvas,400 * vVarName.size(),400);
  cCompareCut[iCut] -> Divide (vVarName.size(),1);
 }
 
 for (unsigned int iVar = 0; iVar<vVarName.size(); iVar++){ ///==== cicle on variables to plot ====
   TString nameCanvas = Form("%d_Var_Canvas",iVar);
   cCompareVar[iVar] = new TCanvas(nameCanvas,nameCanvas,400,400 * vCut.size());
   cCompareVar[iVar] -> Divide (1,vCut.size());
 }
 
 
 for (unsigned int iCut = 0; iCut<vCut.size(); iCut++){
  for (unsigned int iVar = 0; iVar<vVarName.size(); iVar++){
   TString nameCanvas = Form("%d_%d_Canvas",iCut,iVar);
   ccCanvas[iCut][iVar] = new TCanvas(nameCanvas,nameCanvas,400,400);
   for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
    TString nameCanvasName = Form("%d_%d_%d_Canvas",iCut,iVar,iName);
    cCanvasAll[iName][iCut][iVar] = new TCanvas(nameCanvasName,nameCanvasName,400,400);
   }
  }
 } 
 
 ///==== cicle on selections ====
 for (unsigned int iCut = 0; iCut<vCut.size(); iCut++){
  ///==== cicle on variables to plot ====
  for (unsigned int iVar = 0; iVar<vVarName.size(); iVar++){
   ///==== draw in canvas ====
   
   for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
    cCanvasAll[iName][iCut][iVar]->cd();
    gPad->SetLeftMargin(0.14);
    gPad->SetRightMargin(0.23);
    histo[iName][iCut][iVar]->Draw();
    histo[iName][iCut][iVar]->GetXaxis()->SetTitle(vVarNameHR.at(iVar).first.c_str());
    histo[iName][iCut][iVar]->GetYaxis()->SetTitle(vVarNameHR.at(iVar).second.c_str());
    gPad->SetLogz();
    gPad->SetGrid();
    leg->Draw();
    latex->Draw();
   }
   
   cCompareCut[iCut] -> cd(iVar+1);
   hs[iCut][iVar] ->Draw();
   hs[iCut][iVar]->GetXaxis()->SetTitle(vVarNameHR.at(iVar).first.c_str());
   hs[iCut][iVar]->GetYaxis()->SetTitle(vVarNameHR.at(iVar).second.c_str());
   gPad->SetLogz();
   gPad->SetGrid();
   leg->Draw();
   latex->Draw();
   
   cCompareVar[iVar] -> cd(iCut+1);
   hs[iCut][iVar] ->Draw("LEGO");
   hs[iCut][iVar]->GetXaxis()->SetTitle(vVarNameHR.at(iVar).first.c_str());
   hs[iCut][iVar]->GetYaxis()->SetTitle(vVarNameHR.at(iVar).second.c_str());
   gPad->SetLogz();
   gPad->SetGrid();
   leg->Draw();
   latex->Draw();

   ccCanvas[iCut][iVar]-> cd();
   hs[iCut][iVar]->Draw("LEGO");
   hs[iCut][iVar]->GetXaxis()->SetTitle(vVarNameHR.at(iVar).first.c_str());
   hs[iCut][iVar]->GetYaxis()->SetTitle(vVarNameHR.at(iVar).second.c_str());
   gPad->SetLogz();
   gPad->SetGrid();
   leg->Draw();
   latex->Draw();

   for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
    
    bool isSig = false;
    for (std::vector<std::string>::const_iterator itSig = SignalName.begin(); itSig != SignalName.end(); itSig++){
     if (reduced_name_samples.at(iName) == *itSig) isSig = true;
    }
    
    if (isSig || reduced_name_samples.at(iName) == "DATA") {
     cCompareCut[iCut] -> cd(iVar+1);
//      histo[iName][iCut][iVar]->Draw("EsameB");
//      histo[iName][iCut][iVar]->Draw("same");
     
     cCompareVar[iVar] -> cd(iCut+1);
//      histo[iName][iCut][iVar]->Draw("EsameB");
//      histo[iName][iCut][iVar]->Draw("same");
     
     ccCanvas[iCut][iVar]-> cd();
//      histo[iName][iCut][iVar]->Draw("EsameB");
//      histo[iName][iCut][iVar]->Draw("same");
    }
   }
   
   cCompareCut[iCut] -> cd(iVar+1);
   leg->Draw();
   cCompareVar[iVar] -> cd(iCut+1);
   leg->Draw();
   ccCanvas[iCut][iVar]-> cd();
   leg->Draw();
   
  } ///==== end cicle on variables to plot ====
 } ///==== end cicle on selections ====
 
 std::cerr << " ******************************************* end *******************************************" << std::endl;
 end = clock();
 std::cout <<"Time = " <<  ((double) (end - start)) << " (a.u.)" << std::endl;  
 
 
 
 ///==== save output ====
 outFile.cd();
 
 outFile.cd();
 outFile.mkdir("PU");
 outFile.cd("PU");
 
 if (!doWeightFromFile) { 
  hPUMC     -> Write();
  hPUDATA   -> Write();
  hPUWeight -> Write();
 }
 
 outFile.cd();
 outFile.mkdir("Cut");
 outFile.cd("Cut");
 for (unsigned int iCut = 0; iCut<vCut.size(); iCut++){
  cCompareCut[iCut] -> Write();
  TString nameCut = Form ("Cut_%d",iCut);
  TString Cut = Form ("%s",vCut.at(iCut).c_str());
  TNamed nameCutNamed (nameCut,Cut);
  nameCutNamed.Write();
 }
 
 outFile.cd();
 outFile.mkdir("Var");
 outFile.cd("Var");
 for (unsigned int iVar = 0; iVar<vVarName.size(); iVar++){
  cCompareVar[iVar] -> Write();
 }
 
 outFile.cd();
 TDirectory* cdAll = (TDirectory*) outFile.mkdir("All");
 cdAll->mkdir("Var");
 outFile.cd("All/Var");
 for (unsigned int iCut = 0; iCut<vCut.size(); iCut++){
  for (unsigned int iVar = 0; iVar<vVarName.size(); iVar++){
   ccCanvas[iCut][iVar]-> Write();
  }
 }
 
 
 outFile.cd();
 outFile.mkdir("Data");
 outFile.cd("Data");
 for (unsigned int iCut = 0; iCut<vCut.size(); iCut++){
  for (unsigned int iVar = 0; iVar<vVarName.size(); iVar++){
   hs[iCut][iVar] -> Write() ;
   for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
    histo[iName][iCut][iVar] -> Write();
    //     bool isSig = false;
    //     for (std::vector<std::string>::const_iterator itSig = SignalName.begin(); itSig != SignalName.end(); itSig++){
     //      if (reduced_name_samples.at(iName) == *itSig) isSig = true;
    //     }
    //     if (isSig || reduced_name_samples.at(iName) == "DATA") {
     //      histo[iName][iCut][iVar] -> Write();
    //     }
   }
   //    ((TH1F*)(hs[iCut][iVar] ->GetStack()->Last()))->Write() ;
   TH1F* tempH =  ((TH1F*)(hs[iCut][iVar] ->GetStack()->Last())) ;
   TString name = Form("All_%d_%d",iCut,iVar);
   tempH -> SetName(name);
   tempH -> Write();
  }
 }
 
 
 outFile.cd();
 cdAll->mkdir("CutVar");
 outFile.cd("All/CutVar");
 ///==== cicle on selections ====
 for (unsigned int iCut = 0; iCut<vCut.size(); iCut++){
  ///==== cicle on variables to plot ====
  for (unsigned int iVar = 0; iVar<vVarName.size(); iVar++){
   for (unsigned int iName=0; iName<reduced_name_samples.size(); iName++){
    cCanvasAll[iName][iCut][iVar]->Write();
   }
  }
 }
 outFile.cd();
   
 
 
 
 
 
 
 
 leg->Write();
 
}
int main(  int argc, char * argv[] )
{

  // Load libraries
  gSystem->Load( "libFWCoreFWLite" );
  AutoLibraryLoader::enable();

  // Check configuration file
  if ( argc < 2 ) {
    std::cout << argv[ 0 ] << " --> Usage:" << std::endl
              << "    " << argv[ 0 ] << " [CONFIG_FILE.py]" << std::endl;
    return 0;
  }
  boost::shared_ptr< edm::ParameterSet > parameterSet_( edm::readPSetsFrom( argv[ 1 ] ) );
  if ( ! parameterSet_->existsAs< edm::ParameterSet >( "process" ) ) {
    std::cout << argv[ 0 ] << " --> ERROR:" << std::endl
              << "   cms.PSet 'process' missing in " << argv[ 1 ] << std::endl;
    return 1;
  }

  // Get the configurations
  const edm::ParameterSet &              process_( parameterSet_->getParameter< edm::ParameterSet >( "process" ) );
  const unsigned                         verbosity_( process_.getParameter< unsigned >( "verbosity" ) );
  const edm::ParameterSet &              exist_( process_.getParameter< edm::ParameterSet >( "existing" ) );
  const std::vector< double >            objLimits_( exist_.getParameter< std::vector< double > >( "objectPtLimits" ) );          // object upper edge of p_t range to display
  const std::vector< std::string >       kinProps_( exist_.getParameter< std::vector< std::string > >( "kinematicProperties" ) ); // kinematic variables
  const std::vector< edm::ParameterSet > resolutions_( process_.getParameter< std::vector< edm::ParameterSet > >( "resolutions" ) );
  const std::string                      outFile_( exist_.getParameter< std::string >( "outputFile" ) );

  // Constants
  const std::string paramBin_( "bin" );

  // Open output file
  TFile * outFile( TFile::Open( outFile_.c_str(), "RECREATE" ) );

  // Loop over resolutions

  for ( unsigned iRes = 0; iRes < resolutions_.size(); ++iRes ) {
    const edm::ParameterSet resolution( resolutions_.at( iRes ) );
    const std::string label( resolution.getParameter< std::string >( "label" ) );
    if ( verbosity_ > 0 ) std::cout << "Resolution set: " << label << std::endl;

    TDirectory * dirRes( outFile->mkdir( label.c_str(), label.c_str() ) );

    const std::vector< edm::ParameterSet > functions( resolution.getParameter< std::vector< edm::ParameterSet > >( "functions" ) );
    for ( unsigned iBin = 0; iBin < functions.size(); ++iBin ) {
      const edm::ParameterSet binFunctions( functions.at( iBin) );
      const std::string binEta( "Eta" + boost::lexical_cast< std::string >( iBin ) );
      std::string titleBin;
      if ( binFunctions.exists( paramBin_ ) ) {
        titleBin = binFunctions.getParameter< std::string >( paramBin_ );
        if ( verbosity_ > 1 ) {
          std::cout << "  bin " << iBin << ": " << titleBin << std::endl;
        }
      }
      else {
        titleBin = "0" ;
        if ( verbosity_ > 1 ) {
          std::cout << "  bin 0: no eta binning" << std::endl;
        }
      }

      for ( unsigned iProp = 0; iProp < kinProps_.size(); ++iProp ) {
        const std::string kinProp( kinProps_.at( iProp ) );
        std::string kinParam( kinProp );
        boost::to_lower( kinParam );
        std::string formula( binFunctions.getParameter< std::string >( kinParam ) );
        if ( verbosity_ > 2 ) {
          std::cout << "    " << kinParam << ": " << formula << std::endl;
        }

        boost::replace_all( formula, "et", "x" );
        std::string name( "fitExist_" + kinProp + "_" + binEta );
        TDirectory * dirProp;
        dirRes->GetObject( kinProp.c_str(), dirProp );
        if ( ! dirProp ) dirProp = dirRes->mkdir( kinProp.c_str(), kinProp.c_str() );
        TDirectory * dirEta( dirProp->mkdir( binEta.c_str(), binEta.c_str() ) );
        dirEta->cd();
        TF1 * func( new TF1( name.c_str(), formula.c_str(), 0., objLimits_.at( iRes ) ) );
        func->Write();
        if ( kinProp == "Et" ) {
          TF1 * funcRel( new TF1( std::string( name + "_Rel" ).c_str(), std::string( "(" + formula + ")/x" ).c_str(), 0., objLimits_.at( iRes ) ) );
          funcRel->Write();
        }
      }
    }

  }

    // Close output file
    outFile->Write();
    outFile->Close();

  return 0;

}
示例#26
0
int testFindObjectAny() 
{ 
   TDirectory* db = gROOT->mkdir("db","db"); 
   TDirectory* a = db->mkdir("a","a"); 
   TDirectory* aa = a->mkdir("aa","aa"); 
   aa->cd(); 
   TH1D* haa_new = new TH1D("haa","haa",10,0,1); 
   TH1D* haa_find = (TH1D*)db->FindObjectAny("haa");
#ifdef ClingWorkAroundMissingDynamicScope
   TH1D* haa = haa_find;
#endif
   if (!haa) {
      cout << "haa missing\n";
   } else if (haa_new != haa_find) {
      cout << "haa not found correctly!\n";
   }
   
   TFile* base = new TFile("fdb.root","recreate");
#ifdef ClingReinstateRedeclarationAllowed
   TDirectory* a = base->mkdir("a","First Level Dir");
#else
   a = base->mkdir("a","First Level Dir");
#endif
   a->cd();
   TH1D* ha = new TH1D("ha","ha",10,0,1);
#ifdef ClingReinstateRedeclarationAllowed
   TDirectory* aa = a->mkdir("aa","Second Level Dira");
#else
   aa = a->mkdir("aa","Second Level Dira");
#endif
   aa->cd();
#ifdef ClingWorkAroundMissingDynamicScope
   haa = new TH1D("haa","haa",10,0,1);
#else
   TH1D* haa = new TH1D("haa","haa",10,0,1);
#endif
   
   testing(   a, base->FindObjectAny("a"));
   testing(  ha, base->FindObjectAny("ha"));
   testing(  ha,    a->FindObjectAny("ha"));
   testing(  aa, base->FindObjectAny("aa"));
   testing(  aa,    a->FindObjectAny("aa"));
   testing( haa, base->FindObjectAny("haa"));
   testing( haa,    a->FindObjectAny("haa"));
   testing( haa,   aa->FindObjectAny("haa"));   
   base->Write();
   
   delete base;
   base = TFile::Open("fdb.root","READ");
   testing(   0, base->FindObjectAny("a"));
   testing(   0, base->FindObjectAny("ha"));
   a = (TDirectory*)base->FindObjectAny("a");
   testing(   0,    a->FindObjectAny("ha"));
   testing(   0, base->FindObjectAny("aa"));
   testing(   0,    a->FindObjectAny("aa"));
   testing(   0, base->FindObjectAny("haa"));
   testing(   0,    a->FindObjectAny("haa"));
   aa = (TDirectory*)base->FindObjectAny("aa");
   testing(   0,   aa->FindObjectAny("haa"));
   
   return 0;
}
int main () 
{
//open input file
 //TFile *f=TFile::Open("input_rootfile/PhotonJet_G_PFlowAK5chs.root");
   //TFile *f=TFile::Open("input_rootfile/PhotonJet_QCD_PFlowAK5chs.root");
   TFile *f=TFile::Open("input_rootfile/PhotonJet_MC_TOT_PFlowAK5chs.root");

 	
  	

//*****************************************************************************************************
//
//                                      histograms definition
//
//*****************************************************************************************************
	QGSyst qgsyst;
	//qgsyst.ReadDatabase("SystDatabase.txt");
	qgsyst.ReadDatabaseDoubleMin("SystDatabase_doubleMin.txt");
	qgsyst.SetTagger("QGLHisto");

	ptBinning myPtBinning;
	int isFor2DTagging = 1;
	ptBinning my2DTaggingPtBinning(isFor2DTagging);
	
//usefull variables
	Double_t xlow = getHistoXlow();
	Double_t xup = getHistoXup();
	//Double_t    binrange = 0.1;
	//Int_t    nbinsx = (xup - xlow)/binrange;
	Int_t    nbinsx = getHistoNbinsx();
	
	Double_t xlow2D = 0;
	Double_t xup2D = 1;
	Int_t    nbinsx2D = 20;
	Double_t ylow2D = 0;
	Double_t yup2D = 1;
	Int_t    nbinsy2D = 20;

	int nzones = getZoneNumber();
	int nflavours = getFlavourNumber(); //uds, g, c, b, noMatched, all
	int n2DTaggingPtBins = my2DTaggingPtBinning.getSize();

	vector<TMatrixF> v4x4MatrixPt = buildSquareMatrixPtVector(my2DTaggingPtBinning);
	vector<TMatrixF> v6x4MatrixPt = buildMatrixPtVector(my2DTaggingPtBinning);

//vectors for 2D tagging study
  // gammapt per flavour per zone
  std::vector<std::vector<TH1F*> > vGammaPt_ZoneFlavour = buildZoneFlavourVectorH1("Gammapt",30,0,800);
  std::vector<std::vector<TH1F*> > vFirstJetPt_ZoneFlavour = buildZoneFlavourVectorH1("FirstJetPt",160,0,800);

	//flavour fractions per pt
	vector<TH1F*> vFractionHisto_Pt = buildPtVectorH1(my2DTaggingPtBinning,"FractionHisto",nflavours-1,0,nflavours-1) ;

	//responses per zone per pt
	vector<vector<TH1F*> > vRmpf_ZonePt = buildZonePtVectorH1(my2DTaggingPtBinning,"Rmpf",nbinsx,xlow,xup) ;

	vector<vector<TH1F*> > vRtrue_ZonePt = buildZonePtVectorH1(my2DTaggingPtBinning,"Rtrue",nbinsx,xlow,xup) ;


	//QG-likelihood per flavour per pt
	vector<vector<TH1F*> > vQGL_FlavourPt = buildFlavourPtVectorH1(my2DTaggingPtBinning,"QGL",nbinsx2D,xlow2D,xup2D) ;

	//Btag-CSV per flavour per pt
	vector<vector<TH1F*> > vCSV_FlavourPt = buildFlavourPtVectorH1(my2DTaggingPtBinning,"CSV",nbinsx2D,xlow2D,xup2D) ;

	//responses per flavour per pt
	vector<vector<TH1F*> > vRmpf_FlavourPt = buildFlavourPtVectorH1(my2DTaggingPtBinning,"Rmpf",nbinsx,xlow,xup) ;

	vector<vector<TH1F*> > vRtrue_FlavourPt = buildFlavourPtVectorH1(my2DTaggingPtBinning,"Rtrue",nbinsx,xlow,xup) ;

	//responses per flavour per pt when we are in one of the 2D tagging zones
	vector<vector<TH1F*> > vRmpf_in2DTaggingZone_FlavourPt = buildFlavourPtVectorH1(my2DTaggingPtBinning,"Rmpf_in2DTaggingZone",nbinsx,xlow,xup) ;

	vector<vector<TH1F*> > vRtrue_in2DTaggingZone_FlavourPt = buildFlavourPtVectorH1(my2DTaggingPtBinning,"Rtrue_in2DTaggingZone",nbinsx,xlow,xup) ;

	
	//Gammapt per flavour 
	vector<TH1F*> vGammapt_Flavour = buildFlavourVectorH1("Gammapt",30,0,800);


	//responses per zone per flavour per pt
	vector<vector<vector<TH1F*> > > vRmpf_ZoneFlavourPt = buildZoneFlavourPtVectorH1(my2DTaggingPtBinning,"Rmpf",nbinsx,xlow,xup) ;

	vector<vector<vector<TH1F*> > > vRtrue_ZoneFlavourPt = buildZoneFlavourPtVectorH1(my2DTaggingPtBinning,"Rtrue",nbinsx,xlow,xup) ;

	
	//2D tagging plans per flavour per pt
	vector<vector<TH2F*> > v2DTaggingPlan_FlavourPt = buildFlavourPtVectorH2(my2DTaggingPtBinning,"2DTaggingPlan",nbinsx2D,xlow2D,xup2D,nbinsy2D,ylow2D,yup2D) ;

	vector<vector<TH2F*> > v2DTaggingPlan_FlavourPt_divided = buildFlavourPtVectorH2(my2DTaggingPtBinning,"2DTaggingPlan_divided",nbinsx2D,xlow2D,xup2D,nbinsy2D,ylow2D,yup2D) ;

	//flavour number per zone per flavour per pt
	vector<vector<vector<float> > > vFlavourNumber = build_fraction_ZoneFlavourPtVector(my2DTaggingPtBinning) ;

	//flavour number per zone per flavour per pt
	vector<vector<vector<float> > > vFlavourFraction = build_fraction_ZoneFlavourPtVector(my2DTaggingPtBinning) ;

	
	for(int j=0; j<n2DTaggingPtBins; j++) {
		vFractionHisto_Pt[j]->Sumw2();
		for(int i=0; i<nzones; i++) {
			vRmpf_ZonePt[i][j]->Sumw2();
			vRtrue_ZonePt[i][j]->Sumw2();
		}
		for(int k=0; k<nflavours; k++) {
			vRmpf_FlavourPt[k][j]->Sumw2();
			vRtrue_FlavourPt[k][j]->Sumw2();
			vRmpf_in2DTaggingZone_FlavourPt[k][j]->Sumw2();
			vRtrue_in2DTaggingZone_FlavourPt[k][j]->Sumw2();
			v2DTaggingPlan_FlavourPt[k][j]->Sumw2();
			vQGL_FlavourPt[k][j]->Sumw2();
			vCSV_FlavourPt[k][j]->Sumw2();
			for(int l=0; l<nzones; l++) {
				vRmpf_ZoneFlavourPt[l][k][j]->Sumw2();
				vRtrue_ZoneFlavourPt[l][k][j]->Sumw2();
			}
		}
	}
	
	for(int k=0; k<nflavours; k++) {
		vGammapt_Flavour[k]->Sumw2();
    for(int l=0; l<nzones; l++) {
		  vGammaPt_ZoneFlavour[l][k]->Sumw2();
		  vFirstJetPt_ZoneFlavour[l][k]->Sumw2();
		}
	}
	

	TH1F* hGammaPt=new TH1F("hGammaPt","hGammaPt",40,40,800);
	hGammaPt->SetXTitle("p_{T}^{#gamma} [GeV/c]");
	hGammaPt->Sumw2();

	TH1F* hFirstJetPt=new TH1F("hFirstJetPt","hFirstJetPt",50,0,1400);
	hFirstJetPt->SetXTitle("1^{st} jet p_{T} [GeV/c]");
	hFirstJetPt->Sumw2();

	TH1F* hSecondJetPt=new TH1F("hSecondJetPt","hSecondJetPt",50,0,200);
	hSecondJetPt->SetXTitle("2^{nd} jet p_{T} [GeV/c]");
	hSecondJetPt->Sumw2();
	
	TH1F* hMetPt=new TH1F("hMetPt","hMetPt",50,0,620);
	hMetPt->SetXTitle("MET p_{T} [GeV/c]");
	hMetPt->Sumw2();
	
	TH1F* hParalleleMetPt=new TH1F("hParalleleMetPt","hParalleleMetPt",50,-200,200);
	hParalleleMetPt->SetXTitle("parallele MET p_{T} [GeV/c]");
	hParalleleMetPt->Sumw2();
	
	TH1F* hPerpendicularMetPt=new TH1F("hPerpendicularMetPt","hPerpendicularMetPt",50,-140,140);
	hPerpendicularMetPt->SetXTitle("perpendicular MET p_{T} [GeV/c]");
	hPerpendicularMetPt->Sumw2();
	
	TH1F* hAlpha=new TH1F("hAlpha","hAlpha",10,0.,1.);
	hAlpha->SetXTitle("p_{T}^{2^{nd} jet}/p_{T}^{#gamma}");
	hAlpha->Sumw2();
	
	TH1F* hDeltaPhi_j1gamma=new TH1F("hDeltaPhi_j1gamma","hDeltaPhi_j1gamma",40,0,4);
	hDeltaPhi_j1gamma->SetXTitle("|#Delta#phi (#gamma,1^{st}jet)|");
	hDeltaPhi_j1gamma->Sumw2();

	TH1F* hDeltaPhi_j2gamma=new TH1F("hDeltaPhi_j2gamma","hDeltaPhi_j2gamma",40,0,4);
	hDeltaPhi_j2gamma->SetXTitle("|#Delta#phi (#gamma,2^{nd}jet)|");
	hDeltaPhi_j2gamma->Sumw2();
	
	TH1F* hDeltaPhi_j1j2=new TH1F("hDeltaPhi_j1j2","hDeltaPhi_j1j2",40,0,4);
	hDeltaPhi_j1j2->SetXTitle("|#Delta#phi (1^{st} jet,2^{nd} jet)|");
	hDeltaPhi_j1j2->Sumw2();
	
	TH1F* hDeltaR_j1gamma=new TH1F("hDeltaR_j1gamma","hDeltaR_j1gamma",40,0,8);
	hDeltaR_j1gamma->SetXTitle("|#DeltaR (#gamma,1^{st} jet)|");
	hDeltaR_j1gamma->Sumw2();
	
	TH1F* hDeltaR_j2gamma=new TH1F("hDeltaR_j2gamma","hDeltaR_j2gamma",40,0,8);
	hDeltaR_j2gamma->SetXTitle("|#DeltaR (#gamma,2^{nd} jet)|");
	hDeltaR_j2gamma->Sumw2();
	
	TH1F* hDeltaR_j1j2=new TH1F("hDeltaR_j1j2","hDeltaR_j1j2",40,0,8);
	hDeltaR_j1j2->SetXTitle("|#DeltaR (1^{st} jet,2^{nd} jet)|");
	hDeltaR_j1j2->Sumw2();




//*****************************************************************************************************
//
//                                      reading the root file 
//
//*****************************************************************************************************

//retrieve the trees
	TTree* t_firstjet=(TTree*)f->Get("first_jet");
	TTree* t_firstjetraw=(TTree*)f->Get("first_jet_raw");
	TTree* t_firstjetgen=(TTree*)f->Get("first_jet_gen");
	TTree* t_secondjetgen=(TTree*)f->Get("second_jet_gen");
	TTree* t_secondjet=(TTree*)f->Get("second_jet");
	TTree* t_electron=(TTree*)f->Get("electrons");
	TTree* t_muon=(TTree*)f->Get("muons");
	TTree* t_met=(TTree*)f->Get("met");
	TTree* t_gamma=(TTree*)f->Get("photon");
	TTree* t_gammagen=(TTree*)f->Get("photon_gen");
	TTree* t_misc=(TTree*)f->Get("misc");
	TTree* t_rho=(TTree*)f->Get("rho");
	//TTree* t_gen_particles=(TTree*)f->Get("gen_particles");

//retrieve the variables
	//First jet
	float firstjetpt;
	t_firstjet->SetBranchAddress("pt",&firstjetpt);
	float firstjetpx;
	t_firstjet->SetBranchAddress("px",&firstjetpx);
	float firstjetpy;
	t_firstjet->SetBranchAddress("py",&firstjetpy);
	float firstjetphi;
	t_firstjet->SetBranchAddress("phi",&firstjetphi);
	float firstjeteta;
	t_firstjet->SetBranchAddress("eta",&firstjeteta);
	float firstjetbtag_csv;
	t_firstjet->SetBranchAddress("btag_csv",&firstjetbtag_csv);
	float firstjetqg_tag_mlp;
	t_firstjet->SetBranchAddress("qg_tag_mlp",&firstjetqg_tag_mlp);
	float firstjetqg_tag_likelihood;
	t_firstjet->SetBranchAddress("qg_tag_likelihood",&firstjetqg_tag_likelihood);
	
	//First jet raw
	float firstjetrawpt;
	t_firstjetraw->SetBranchAddress("pt",&firstjetrawpt);
	float firstjetrawphi;
	t_firstjetraw->SetBranchAddress("phi",&firstjetrawphi);
	float firstjetraweta;
	t_firstjetraw->SetBranchAddress("eta",&firstjetraweta);
	
	//First jet generated
	gROOT->ProcessLine("#include <vector>"); 
	float firstjetgenpt;
	t_firstjetgen->SetBranchAddress("pt",&firstjetgenpt);
	float firstjetgenpx;
	t_firstjetgen->SetBranchAddress("px",&firstjetgenpx);
	float firstjetgenpy;
	t_firstjetgen->SetBranchAddress("py",&firstjetgenpy);
	float firstjetgenphi;
	t_firstjetgen->SetBranchAddress("phi",&firstjetgenphi);
	float firstjetgeneta;
	t_firstjetgen->SetBranchAddress("eta",&firstjetgeneta);
	int firstjetgenpdgid;
  t_firstjetgen->SetBranchAddress("parton_pdg_id",&firstjetgenpdgid); // physics definition
   //t_firstjetgen->SetBranchAddress("parton_flavour",&firstjetgenpdgid); // algorithmic definition
// 	TClonesArray *aneutrino_4vect = 0;
// 	t_firstjetgen->SetBranchAddress("neutrinos",&aneutrino_4vect);

	
	//Second jet generated
	float secondjetgenpt;
	t_secondjetgen->SetBranchAddress("pt",&secondjetgenpt);
	float secondjetgenphi;
	t_secondjetgen->SetBranchAddress("phi",&secondjetgenphi);
	float secondjetgeneta;
	t_secondjetgen->SetBranchAddress("eta",&secondjetgeneta);
	
	//misc
	float miscevent_weight;
	t_misc->SetBranchAddress("event_weight",&miscevent_weight);

	//Second jet
	float secondjetpt;
	t_secondjet->SetBranchAddress("pt",&secondjetpt);
	float secondjetphi;
	t_secondjet->SetBranchAddress("phi",&secondjetphi);
	float secondjeteta;
	t_secondjet->SetBranchAddress("eta",&secondjeteta);
	
	//Gamma (reco)
	float gammapt;
	t_gamma->SetBranchAddress("pt",&gammapt);
	float gammaphi;
	t_gamma->SetBranchAddress("phi",&gammaphi);
	float gammaeta;
	t_gamma->SetBranchAddress("eta",&gammaeta);
	float gammapx;
	t_gamma->SetBranchAddress("px",&gammapx);
	float gammapy;
	t_gamma->SetBranchAddress("py",&gammapy);
	float gammapz;
	t_gamma->SetBranchAddress("pz",&gammapz);
	bool gamma_has_pixel_seed;
	t_gamma->SetBranchAddress("has_pixel_seed",&gamma_has_pixel_seed);
	
	//Gamma gen
	float gammagenpt;
	t_gammagen->SetBranchAddress("pt",&gammagenpt);
	float gammagenpx;
	t_gammagen->SetBranchAddress("px",&gammagenpx);
	float gammagenpy;
	t_gammagen->SetBranchAddress("py",&gammagenpy);

	
	//electron
	float electronpt[100];
	t_electron->SetBranchAddress("pt",&electronpt);
	float electronphi[100];
	t_electron->SetBranchAddress("phi",&electronphi);
	float electroneta[100];
	t_electron->SetBranchAddress("eta",&electroneta);
	int electronn;
	t_electron->SetBranchAddress("n",&electronn);
	float electronisolation[100];
	t_electron->SetBranchAddress("isolation",&electronisolation);
	
	//muon
	float muonpt[100];
	t_muon->SetBranchAddress("pt",&muonpt);
	float muonphi[100];
	t_muon->SetBranchAddress("phi",&muonphi);
	float muoneta[100];
	t_muon->SetBranchAddress("eta",&muoneta);
	int muonn;
	t_muon->SetBranchAddress("n",&muonn);
	float muonisolation[100];
	t_muon->SetBranchAddress("relative_isolation",&muonisolation);
	
	//met
	float metpt;
	t_met->SetBranchAddress("pt",&metpt);
	float metpx;
	t_met->SetBranchAddress("px",&metpx);
	float metpy;
	t_met->SetBranchAddress("py",&metpy);
	float metpz;
	t_met->SetBranchAddress("pz",&metpz);
	float metphi;
	t_met->SetBranchAddress("phi",&metphi);
	
	//rho
	double rho;
	t_rho->SetBranchAddress("rho",&rho);
	

	
	//Usefull variables
	float Rmpf;
	float Rtrue;
	float alpha;
	float metParal;
	float metPerpend;
	Double_t DeltaPhi_j1gamma;
	Double_t DeltaPhi_j2gamma;
	Double_t DeltaPhi_j1j2;	
	Double_t DeltaPhi_j1met;
	Double_t DeltaR_j1gamma;
	Double_t DeltaR_j2gamma;
	Double_t DeltaR_j1j2;	
	Double_t DeltaEta_j1gamma;
	Double_t DeltaEta_j2gamma;
	Double_t DeltaEta_j1j2;
	Double_t DeltaPhi_j1j2_gen;
	Double_t DeltaEta_j1j2_gen;
	Double_t DeltaR_j1j2_gen;

	int binPt;//bin en pt
	int bin2DTaggingPt;//gros bins en pt pour l etude 2D tagging
	int binZone;// 2D tagging zone bin
	int binFlavour;
	
	bool dropEvent=false;
	
	//count events in the tree
	unsigned int nEvents = (int)t_firstjet->GetEntries();
	
	string type;
	
	//loop over them
	for(unsigned int ievt=0; ievt<nEvents; ievt++) {
		t_firstjet->GetEntry(ievt);
		t_firstjetraw->GetEntry(ievt);
		t_secondjet->GetEntry(ievt);
		t_electron->GetEntry(ievt);
		t_muon->GetEntry(ievt);
		t_gamma->GetEntry(ievt);
		t_gammagen->GetEntry(ievt);
		t_met->GetEntry(ievt);
		t_misc->GetEntry(ievt);
		t_firstjetgen->GetEntry(ievt);
		t_secondjetgen->GetEntry(ievt); 
		t_rho->GetEntry(ievt);   
		//t_gen_particles->GetEntry(ievt);
	
//*********************************************************************************************************
		
		dropEvent=false;
		
		if(gamma_has_pixel_seed == true) continue;
		  	
		binPt = myPtBinning.getPtBin(gammapt);
		if(binPt == -1) continue;

		bin2DTaggingPt = my2DTaggingPtBinning.getPtBin(gammapt);		

		if(TMath::Abs(firstjetgenpdgid) == 21) {
			type = "gluon";
		}
		else if(TMath::Abs(firstjetgenpdgid) == 4) {//c
			type = "quark";
		}
		else if(TMath::Abs(firstjetgenpdgid) == 5) {//b
			type = "quark";
		}
		else if(TMath::Abs(firstjetgenpdgid) == 1 || TMath::Abs(firstjetgenpdgid) == 2 || TMath::Abs(firstjetgenpdgid) == 3) {
			type = "quark";
		}
		else {
			type = "gluon";
		}
		
		firstjetqg_tag_likelihood = qgsyst.Smear(firstjetpt, firstjeteta, rho, firstjetqg_tag_likelihood, type);

		binZone = getZoneBin(firstjetbtag_csv, firstjetqg_tag_likelihood);
		//if(binZone == -1) continue;	
		binFlavour = getFlavourBin(firstjetgenpdgid);
		//if(binFlavour == -1) continue;
		
		Rmpf = 1 + (gammapx*metpx + gammapy*metpy)/(pow(gammapt,2));		
		alpha = (secondjetpt)/(gammapt);
		Rtrue = (firstjetpt)/(firstjetgenpt);

		
//*****************************************************************************************************
//
//                                      deltaPhi calculation
//
//*****************************************************************************************************


//DeltaPhi between the 1st jet and the gamma calculation
    	DeltaPhi_j1gamma = TMath::Abs((gammaphi) - (firstjetphi));
    	if(DeltaPhi_j1gamma>TMath::Pi()){
    	  DeltaPhi_j1gamma = 2*TMath::Pi()-DeltaPhi_j1gamma;
    	}
    	
//DeltaPhi between the 2nd jet and the gamma calculation
    	DeltaPhi_j2gamma = TMath::Abs((gammaphi) - (secondjetphi));
    	if(DeltaPhi_j2gamma>TMath::Pi()){
    	  DeltaPhi_j2gamma = 2*TMath::Pi()-DeltaPhi_j2gamma;
    	}


//DeltaPhi between the first jet and the second jet calculation
    	DeltaPhi_j1j2 = TMath::Abs((secondjetphi) - (firstjetphi));
    	if(DeltaPhi_j1j2>TMath::Pi()){
      	DeltaPhi_j1j2 = 2*TMath::Pi()-DeltaPhi_j1j2;
    	}
    	
//DeltaPhi between the first jetgen and the second jetgen calculation
    	DeltaPhi_j1j2_gen = TMath::Abs((secondjetgenphi) - (firstjetgenphi));
    	if(DeltaPhi_j1j2_gen>TMath::Pi()){
    	  DeltaPhi_j1j2_gen = 2*TMath::Pi()-DeltaPhi_j1j2_gen;
    	}
    	
 //DeltaPhi between the first jet and the met
    	DeltaPhi_j1met = TMath::Abs((metphi) - (firstjetphi));
    	
    	
//*****************************************************************************************************
//
//                                      deltaEta calculation 
//
//*****************************************************************************************************

//DeltaEta between the first jet and the gamma calculation
    	DeltaEta_j1gamma = TMath::Abs((gammaeta) - (firstjeteta));

//DeltaEta between the second jet and the gamma calculation
    	DeltaEta_j2gamma = TMath::Abs((gammaeta) - (secondjeteta));
    	
//DeltaEta between the first jet and the second jet calculation
    	DeltaEta_j1j2 = TMath::Abs((secondjeteta) - (firstjeteta));
    	
 //DeltaEta between the first jetgen and the second jetgen calculation
    	DeltaEta_j1j2_gen = TMath::Abs((secondjetgeneta) - (firstjetgeneta));
    	    	
//*****************************************************************************************************
//
//                                      deltaR calculation 
//
//*****************************************************************************************************


//DeltaR between the first jet and the gamma calculation
    	DeltaR_j1gamma = sqrt ( pow(DeltaEta_j1gamma,2) + pow(DeltaPhi_j1gamma,2) );
    	
//DeltaR between the second jet and the gamma calculation
    	DeltaR_j2gamma = sqrt ( pow(DeltaEta_j2gamma,2) + pow(DeltaPhi_j2gamma,2) );

//DeltaR between the first jet and the second jet calculation
    	DeltaR_j1j2 = sqrt ( pow(DeltaEta_j1j2,2) + pow(DeltaPhi_j1j2,2) );
    	
//DeltaR between the first jetgen and the second jetgen calculation
    	DeltaR_j1j2_gen = sqrt ( pow(DeltaEta_j1j2_gen,2) + pow(DeltaPhi_j1j2_gen,2) );
    	
//*****************************************************************************************************
//
//                                      met parallele calculation 
//
//*****************************************************************************************************

		metParal = metpt * TMath::Cos(DeltaPhi_j1met);

//*****************************************************************************************************
//
//                                      met perpendicular calculation 
//
//*****************************************************************************************************

		metPerpend = metpt * TMath::Sin(DeltaPhi_j1met);

//*****************************************************************************************************
//
//                                      filling histogramms 
//
//*****************************************************************************************************

	
		//if(fabs(firstjetpt)>12. && DeltaPhi_j1gamma>2.8 && fabs(firstjeteta)<1.3 && (alpha<0.3 || secondjetpt<10)) {
		if(fabs(firstjetpt)>12. && DeltaPhi_j1gamma>2.8 && fabs(firstjeteta)<1.3) {
			if(muonn==0){
				if(electronn==0) {
					if(gammapt>200.) {
						hAlpha->Fill(alpha,miscevent_weight);
					}
					if((alpha<0.3 || secondjetpt<10)) {
						vGammapt_Flavour[binFlavour]->Fill(gammapt,miscevent_weight);	
						vGammapt_Flavour[nflavours-1]->Fill(gammapt,miscevent_weight);
		
		
						hGammaPt->Fill(gammapt,miscevent_weight);
						hFirstJetPt->Fill(firstjetpt,miscevent_weight);
						hMetPt->Fill(metpt,miscevent_weight);
						hParalleleMetPt->Fill(metParal,miscevent_weight);
						hPerpendicularMetPt->Fill(metPerpend,miscevent_weight);
						hSecondJetPt->Fill(secondjetpt,miscevent_weight);
						hDeltaPhi_j1gamma->Fill(DeltaPhi_j1gamma,miscevent_weight);
						hDeltaPhi_j2gamma->Fill(DeltaPhi_j2gamma,miscevent_weight);
						hDeltaPhi_j1j2->Fill(DeltaPhi_j1j2,miscevent_weight);
						hDeltaR_j1gamma->Fill(DeltaR_j1gamma,miscevent_weight);
						hDeltaR_j2gamma->Fill(DeltaR_j2gamma,miscevent_weight);
						hDeltaR_j1j2->Fill(DeltaR_j1j2,miscevent_weight);	

		
						if((firstjetbtag_csv>=0 && firstjetbtag_csv<=1) && (firstjetqg_tag_likelihood>=0 && firstjetqg_tag_likelihood<=1)) { 
		//protection contre les jets non matches
	
							vQGL_FlavourPt[binFlavour][bin2DTaggingPt]->Fill(firstjetqg_tag_likelihood,miscevent_weight);
							vCSV_FlavourPt[binFlavour][bin2DTaggingPt]->Fill(firstjetbtag_csv,miscevent_weight);
							vQGL_FlavourPt[nflavours-1][bin2DTaggingPt]->Fill(firstjetqg_tag_likelihood,miscevent_weight);
							vCSV_FlavourPt[nflavours-1][bin2DTaggingPt]->Fill(firstjetbtag_csv,miscevent_weight);
	
							if(binZone!=-1) {
                vGammaPt_ZoneFlavour[binZone][binFlavour]->Fill(gammapt,miscevent_weight);
                vGammaPt_ZoneFlavour[binZone][nflavours-1]->Fill(gammapt,miscevent_weight);

                if(gammapt>200.) {
                  vFirstJetPt_ZoneFlavour[binZone][binFlavour]->Fill(firstjetpt,miscevent_weight);
                  vFirstJetPt_ZoneFlavour[binZone][nflavours-1]->Fill(firstjetpt,miscevent_weight);
                }

								vRmpf_ZonePt[binZone][bin2DTaggingPt]->Fill(Rmpf,miscevent_weight);
								vRtrue_ZonePt[binZone][bin2DTaggingPt]->Fill(Rtrue,miscevent_weight);

								vRmpf_ZoneFlavourPt[binZone][binFlavour][bin2DTaggingPt]->Fill(Rmpf,miscevent_weight);
								vRtrue_ZoneFlavourPt[binZone][binFlavour][bin2DTaggingPt]->Fill(Rtrue,miscevent_weight);
								vRmpf_ZoneFlavourPt[binZone][nflavours-1][bin2DTaggingPt]->Fill(Rmpf,miscevent_weight);
								vRtrue_ZoneFlavourPt[binZone][nflavours-1][bin2DTaggingPt]->Fill(Rtrue,miscevent_weight);
	
								vRmpf_in2DTaggingZone_FlavourPt[binFlavour][bin2DTaggingPt]->Fill(Rmpf,miscevent_weight);
								vRtrue_in2DTaggingZone_FlavourPt[binFlavour][bin2DTaggingPt]->Fill(Rtrue,miscevent_weight);
								vRmpf_in2DTaggingZone_FlavourPt[nflavours-1][bin2DTaggingPt]->Fill(Rmpf,miscevent_weight);
								vRtrue_in2DTaggingZone_FlavourPt[nflavours-1][bin2DTaggingPt]->Fill(Rtrue,miscevent_weight);
	
								vFlavourNumber[binZone][binFlavour][bin2DTaggingPt] = vFlavourNumber[binZone][binFlavour][bin2DTaggingPt] + miscevent_weight;
								vFlavourNumber[binZone][nflavours-1][bin2DTaggingPt] = vFlavourNumber[binZone][nflavours-1][bin2DTaggingPt] + miscevent_weight;
							}
							vRmpf_FlavourPt[binFlavour][bin2DTaggingPt]->Fill(Rmpf,miscevent_weight);
							vRtrue_FlavourPt[binFlavour][bin2DTaggingPt]->Fill(Rtrue,miscevent_weight);
							vRmpf_FlavourPt[nflavours-1][bin2DTaggingPt]->Fill(Rmpf,miscevent_weight);
							vRtrue_FlavourPt[nflavours-1][bin2DTaggingPt]->Fill(Rtrue,miscevent_weight);
	// 						vQGL_FlavourPt[binFlavour][bin2DTaggingPt]->Fill(firstjetqg_tag_likelihood,miscevent_weight);
	// 						vCSV_FlavourPt[binFlavour][bin2DTaggingPt]->Fill(firstjetbtag_csv,miscevent_weight);
	// 						vQGL_FlavourPt[nflavours-1][bin2DTaggingPt]->Fill(firstjetqg_tag_likelihood,miscevent_weight);
	// 						vCSV_FlavourPt[nflavours-1][bin2DTaggingPt]->Fill(firstjetbtag_csv,miscevent_weight);
							v2DTaggingPlan_FlavourPt[binFlavour][bin2DTaggingPt]->Fill(firstjetbtag_csv,firstjetqg_tag_likelihood,miscevent_weight);
							v2DTaggingPlan_FlavourPt[nflavours-1][bin2DTaggingPt]->Fill(firstjetbtag_csv,firstjetqg_tag_likelihood,miscevent_weight);//nflavours-1 : corresponds to total
						}
					}	
				}
			}
		}
	}
    
	

	
//*****************************************************************************************************
//
//                                      2D Tagging Plans
//
//*****************************************************************************************************

//v2DTaggingPlan_FlavourPt[binFlavour][bin2DTaggingPt]
	std::string name2DTaggingPlan; 
	std::string name2DTaggingPlan_check; 
	std::string nameHisto;
	std::string nameHisto_check;
	TCanvas *cLikelihood_vs_csv = new TCanvas();
	cLikelihood_vs_csv->cd();
	string histoName;
	for(int j=0; j<n2DTaggingPtBins; j++) {
		for(int i=0; i<nflavours-1; i++) {//divide flavour distri by total distri
			cLikelihood_vs_csv->Clear();
			histoName = "images2DTagging/2DTaggingZones/beforeDividing/" + getFlavourBinName(i) + "_" + my2DTaggingPtBinning.getName(j) + ".pdf";
			//name2DTaggingPlan_check = ("images2DTagging/2DTaggingZones/beforeDividing/");

			v2DTaggingPlan_FlavourPt[i][j]->Draw("colz");
			v2DTaggingPlan_FlavourPt[i][j]->SetStats(0);
			v2DTaggingPlan_FlavourPt[i][j]->GetXaxis()->SetRangeUser(0.,1.);
			v2DTaggingPlan_FlavourPt[i][j]->GetXaxis()->SetLabelOffset(0.005);
			v2DTaggingPlan_FlavourPt[i][j]->GetXaxis()->SetLabelFont(42);
			v2DTaggingPlan_FlavourPt[i][j]->GetXaxis()->SetLabelSize(0.045);
			v2DTaggingPlan_FlavourPt[i][j]->GetXaxis()->SetTitleOffset(1.15);
			v2DTaggingPlan_FlavourPt[i][j]->GetXaxis()->SetTitleSize(0.04);
			v2DTaggingPlan_FlavourPt[i][j]->GetXaxis()->SetTitleFont(42);
			v2DTaggingPlan_FlavourPt[i][j]->GetXaxis()->SetTitle("btag_csv");
			v2DTaggingPlan_FlavourPt[i][j]->GetYaxis()->SetRangeUser(0.,1.);
			v2DTaggingPlan_FlavourPt[i][j]->GetYaxis()->SetLabelOffset(0.005);
			v2DTaggingPlan_FlavourPt[i][j]->GetYaxis()->SetLabelFont(42);
			v2DTaggingPlan_FlavourPt[i][j]->GetYaxis()->SetLabelSize(0.045);	
			v2DTaggingPlan_FlavourPt[i][j]->GetYaxis()->SetTitleOffset(1.2);
			v2DTaggingPlan_FlavourPt[i][j]->GetYaxis()->SetTitleFont(42);
			v2DTaggingPlan_FlavourPt[i][j]->GetYaxis()->SetTitleSize(0.04);	
			v2DTaggingPlan_FlavourPt[i][j]->GetYaxis()->SetTitle("QG_likelihood");
			v2DTaggingPlan_FlavourPt[i][j]->GetZaxis()->SetLabelSize(0.03);
			//nameHisto_check = v2DTaggingPlan_FlavourPt[i][j]->GetTitle();
			//name2DTaggingPlan_check += nameHisto;
			//name2DTaggingPlan_check += ".pdf";
			//cLikelihood_vs_csv->SaveAs(name2DTaggingPlan_check.c_str());
			cLikelihood_vs_csv->SaveAs(histoName.c_str());

			v2DTaggingPlan_FlavourPt_divided[i][j] = (TH2F*)v2DTaggingPlan_FlavourPt[i][j]->Clone(v2DTaggingPlan_FlavourPt[i][j]->GetTitle());

			v2DTaggingPlan_FlavourPt_divided[i][j]->Divide(v2DTaggingPlan_FlavourPt[nflavours-1][j]);

			name2DTaggingPlan = ("images2DTagging/2DTaggingZones/");

			cLikelihood_vs_csv->Clear();
	
			v2DTaggingPlan_FlavourPt_divided[i][j]->Draw("colz");
			v2DTaggingPlan_FlavourPt_divided[i][j]->SetStats(0);
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetXaxis()->SetRangeUser(0.,1.);
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetXaxis()->SetLabelOffset(0.005);
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetXaxis()->SetLabelFont(42);
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetXaxis()->SetLabelSize(0.045);
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetXaxis()->SetTitleOffset(1.15);
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetXaxis()->SetTitleSize(0.04);
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetXaxis()->SetTitleFont(42);
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetXaxis()->SetTitle("btag_csv");
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetYaxis()->SetRangeUser(0.,1.);
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetYaxis()->SetLabelOffset(0.005);
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetYaxis()->SetLabelFont(42);
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetYaxis()->SetLabelSize(0.045);	
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetYaxis()->SetTitleOffset(1.2);
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetYaxis()->SetTitleFont(42);
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetYaxis()->SetTitleSize(0.04);	
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetYaxis()->SetTitle("QG_likelihood");
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetZaxis()->SetLabelSize(0.03);
			nameHisto = v2DTaggingPlan_FlavourPt[i][j]->GetTitle();
			name2DTaggingPlan += nameHisto;
			name2DTaggingPlan += ".pdf";
			cLikelihood_vs_csv->SaveAs(name2DTaggingPlan.c_str());
			nameHisto = "";
			name2DTaggingPlan = "";

      name2DTaggingPlan = ("images2DTagging/2DTaggingZones/");
      nameHisto = v2DTaggingPlan_FlavourPt[i][j]->GetTitle();
			name2DTaggingPlan += nameHisto;
			name2DTaggingPlan += ".C";
			cLikelihood_vs_csv->SaveAs(name2DTaggingPlan.c_str());
			nameHisto = "";
			name2DTaggingPlan = "";
// 			nameHisto_check = "";
// 			name2DTaggingPlan_check = "";
			histoName = "";
				}
	}





//*****************************************************************************************************
//
//                                      Jet flavour fraction
//
//*****************************************************************************************************

	float Nuds,Ng,Nc,Nb,NnoMatched,Ntot;
	std::string nameFraction;
	std::string nameHistoFraction;
	
	for(int j=0;j<n2DTaggingPtBins; j++) {
		for(int i=0; i<nzones; i++) {
			nameFraction = ("images2DTagging/FlavourFractions/");
			Nuds       = vFlavourNumber[i][0][j];
			Ng         = vFlavourNumber[i][1][j];
			Nc         = vFlavourNumber[i][2][j];
			Nb         = vFlavourNumber[i][3][j];
			NnoMatched = vFlavourNumber[i][4][j];
			Ntot       = vFlavourNumber[i][5][j];
			//Ntot       = vFlavourNumber[i][0][j]+vFlavourNumber[i][1][j]+vFlavourNumber[i][2][j]+vFlavourNumber[i][3][j];
			nameHistoFraction = vFractionHisto_Pt[j]->GetName();
			nameFraction += nameHistoFraction ;
			nameFraction += ".pdf";
			computeFlavourRatio(Nuds, Ng, Nc, Nb, NnoMatched, Ntot,vFractionHisto_Pt[j], nameFraction, my2DTaggingPtBinning, i, j);
			nameFraction = "";
			nameHistoFraction = "";
		}
	} 

	for(int j=0;j<n2DTaggingPtBins; j++) {
		for(int i=0; i<nzones; i++) {
			Nuds       = vFlavourNumber[i][0][j];
			Ng         = vFlavourNumber[i][1][j];
			Nc         = vFlavourNumber[i][2][j];
			Nb         = vFlavourNumber[i][3][j];
			NnoMatched = vFlavourNumber[i][4][j];
			Ntot       = vFlavourNumber[i][5][j];
			printLatexTableFlavourRatio(Nuds, Ng, Nc, Nb, NnoMatched, Ntot,vFractionHisto_Pt[j], nameFraction, my2DTaggingPtBinning, i, j);
		}
	}

	for(int k=0; k<n2DTaggingPtBins; k++) {
		for(int j=0; j<nflavours ; j++) {
			for(int i=0; i<nzones; i++) {
				vFlavourFraction[i][j][k] = vFlavourNumber[i][j][k];
			}
		}
	}

	cout<<""<<endl<<endl;

	for(int k=0; k<n2DTaggingPtBins; k++) {
		for(int j=0; j<nflavours ; j++) {
			for(int i=0; i<nzones; i++) {
				//Ntot       = vFlavourNumber[i][0][k]+vFlavourNumber[i][1][k]+vFlavourNumber[i][2][k]+vFlavourNumber[i][3][k];
				//vFlavourFraction[i][j][k] = vFlavourFraction[i][j][k]/Ntot;
				vFlavourFraction[i][j][k] = vFlavourFraction[i][j][k]/vFlavourFraction[i][nflavours-1][k];
				cout<<"vFlavourFraction["<<i<<"]["<<j<<"]["<<k<<"] : "<<vFlavourFraction[i][j][k]*100.<<" %"<<endl;
			}
		}
	}

//**********************************************************************************************************
//
//                                      filling the matrix with the flavour fractions per zone
//
//**********************************************************************************************************

	cout<<""<<endl<<endl;

	//filling the matrices
	for(int k=0; k<n2DTaggingPtBins; k++) {
		for(int j=0; j<nflavours-2; j++) {
			for(int i=0; i<nzones-2; i++) {
				v4x4MatrixPt[k](i,j) = vFlavourFraction[i][j][k];
				cout<<"v4x4MatrixPt["<<k<<"]("<<i<<","<<j<<") :  "<<v4x4MatrixPt[k](i,j)*100.<<" %"<<endl;
			}
		}
	}

	cout<<""<<endl<<endl;

	for(int k=0; k<n2DTaggingPtBins; k++) {
		for(int j=0; j<nflavours-2; j++) {
			for(int i=0; i<nzones; i++) {
				v6x4MatrixPt[k](i,j) = vFlavourFraction[i][j][k];
				cout<<"v6x4MatrixPt["<<k<<"]("<<i<<","<<j<<") : "<<v6x4MatrixPt[k](i,j)*100.<<" %"<<endl;
			}
		}
	}

	//write into the output matrix rootfile
	TFile *out_matrix = new TFile("output_rootfile/outputMatrix2DTagging_MC_G.root", "recreate");
// 	TFile *out_matrix = new TFile("output_rootfile/outputMatrix2DTagging_MC_TOT.root", "recreate");
// 	TFile *out_matrix = new TFile("output_rootfile/outputMatrix2DTagging_MC_QCD.root", "recreate");

	out_matrix->cd();
	TDirectory *matrixDir = out_matrix->mkdir("matrix","matrix");
	matrixDir->cd();
	for(int k=0; k<n2DTaggingPtBins; k++) {
		string matrix6x4Name;
		string matrix4x4Name;
		matrix6x4Name = "matrix6x4_" + my2DTaggingPtBinning.getName(k);
		matrix4x4Name = "matrix4x4_" + my2DTaggingPtBinning.getName(k);
		v6x4MatrixPt[k].Write(matrix6x4Name.c_str());
		v4x4MatrixPt[k].Write(matrix4x4Name.c_str());
	}
	out_matrix->Close();

//*****************************************************************************************************
//
//                                      Output file
//
//*****************************************************************************************************

  //TFile *out_mikko = new TFile("output_rootfile/output2DTagging_MC_G_forMikko_L5Corr_physics.root", "recreate");
  //TFile *out_mikko = new TFile("output_rootfile/output2DTagging_MC_QCD_forMikko_L5Corr_physics.root", "recreate");
  TFile *out_mikko = new TFile("output_rootfile/output2DTagging_MC_TOT_forMikko_L5Corr_physics.root", "recreate");

	out_mikko->cd();	

  TDirectory *firstJetPtPtDir = out_mikko->mkdir("firstJetPtPerZonePerFlavour","firstJetPtPerZonePerFlavour");
  firstJetPtPtDir->cd();
  for(int k=0; k<nflavours; k++) {
    for(int l=0; l<nzones; l++) {
		  vFirstJetPt_ZoneFlavour[l][k]->Write();
		}
	}

 /* TDirectory *response_Zone_FlavourDir = out_mikko->mkdir("response_perZone_perFlavour","response_perZone_perFlavour");*/
	//TDirectory *Rmpf_Zone_FavourDir = response_Zone_FlavourDir->mkdir("Rmpf","Rmpf");
	//Rmpf_Zone_FavourDir->cd();
		//for(int k=0; k<nflavours; k++) {
			//for(int l=0; l<nzones; l++) {
				//vRmpf_ZoneFlavourPt[l][k][n2DTaggingPtBins-1]->Write();
			//}
		//}
	//TDirectory *Rtrue_Zone_FavourDir = response_Zone_FlavourDir->mkdir("Rtrue","Rtrue");
	//Rtrue_Zone_FavourDir->cd();
		//for(int k=0; k<nflavours; k++) {
			//for(int l=0; l<nzones; l++) {
				//vRtrue_ZoneFlavourPt[l][k][n2DTaggingPtBins-1]->Write();
			//}
		//}

//TDirectory *response_Zone_PtDir_mikko = out_mikko->mkdir("response_perZone","response_perZone");
	//TDirectory *Rmpf_Zone_PtDir_mikko = response_Zone_PtDir_mikko->mkdir("Rmpf","Rmpf");
	//Rmpf_Zone_PtDir_mikko->cd();
      //for(int i=0; i<nzones; i++) {
			//vRmpf_ZonePt[i][n2DTaggingPtBins-1]->Write();
		/*}*/
  out_mikko->Close();

	//write into the output file
  //TFile *out = new TFile("output_rootfile/output2DTagging_MC_G_physics.root", "recreate");
   TFile *out = new TFile("output_rootfile/output2DTagging_MC_TOT_physics.root", "recreate");
   //TFile *out = new TFile("output_rootfile/output2DTagging_MC_QCD_physics.root", "recreate");

	out->cd();	
	TDirectory *response_Zone_PtDir = out->mkdir("response_Zone_Pt","response_Zone_Pt");
	TDirectory *Rmpf_Zone_PtDir = response_Zone_PtDir->mkdir("Rmpf","Rmpf");
	Rmpf_Zone_PtDir->cd();
	for(int j=0; j<n2DTaggingPtBins; j++) {
		for(int i=0; i<nzones; i++) {
			vRmpf_ZonePt[i][j]->Write();
		}
	}
	TDirectory *Rtrue_Zone_PtDir = response_Zone_PtDir->mkdir("Rtrue","Rtrue");
	Rtrue_Zone_PtDir->cd();
	for(int j=0; j<n2DTaggingPtBins; j++) {
		for(int i=0; i<nzones; i++) {
			vRtrue_ZonePt[i][j]->Write();
		}
	}


	TDirectory *response_Flavour_PtDir = out->mkdir("response_Flavour_Pt","response_Flavour_Pt");
	TDirectory *Rmpf_Flavour_PtDir = response_Flavour_PtDir->mkdir("Rmpf","Rmpf");
	Rmpf_Flavour_PtDir->cd();
	for(int j=0; j<n2DTaggingPtBins; j++) {
		for(int k=0; k<nflavours; k++) {
			vRmpf_FlavourPt[k][j]->Write();
			vRmpf_in2DTaggingZone_FlavourPt[k][j]->Write();
		}
	}
	TDirectory *Rtrue_Flavour_PtDir = response_Flavour_PtDir->mkdir("Rtrue","Rtrue");
	Rtrue_Flavour_PtDir->cd();
	for(int j=0; j<n2DTaggingPtBins; j++) {
		for(int k=0; k<nflavours; k++) {
			vRtrue_FlavourPt[k][j]->Write();
			vRtrue_in2DTaggingZone_FlavourPt[k][j]->Write();
		}
	}

	TDirectory *response_Zone_Flavour_PtDir = out->mkdir("response_Zone_Flavour_Pt","response_Zone_Flavour_Pt");
	TDirectory *Rmpf_Zone_Flavour_PtDir = response_Zone_Flavour_PtDir->mkdir("Rmpf","Rmpf");
	Rmpf_Zone_Flavour_PtDir->cd();
	for(int j=0; j<n2DTaggingPtBins; j++) {
		for(int k=0; k<nflavours; k++) {
			for(int l=0; l<nzones; l++) {
				vRmpf_ZoneFlavourPt[l][k][j]->Write();
			}
		}
	}
	TDirectory *Rtrue_Zone_Flavour_PtDir = response_Zone_Flavour_PtDir->mkdir("Rtrue","Rtrue");
	Rtrue_Zone_Flavour_PtDir->cd();
	for(int j=0; j<n2DTaggingPtBins; j++) {
		for(int k=0; k<nflavours; k++) {
			for(int l=0; l<nzones; l++) {
				vRtrue_ZoneFlavourPt[l][k][j]->Write();
			}
		}
	}

	TDirectory *tagger_Flavour_PtDir = out->mkdir("tagger_Flavour_Pt","tagger_Flavour_Pt");
	TDirectory *CSV_Flavour_PtDir = tagger_Flavour_PtDir->mkdir("CSV","CSV");
	CSV_Flavour_PtDir->cd();
	for(int j=0; j<n2DTaggingPtBins; j++) {
		for(int k=0; k<nflavours; k++) {
			vCSV_FlavourPt[k][j]->Write();
		}
	}
	TDirectory *QGL_Flavour_PtDir = tagger_Flavour_PtDir->mkdir("QGL","QGL");
	QGL_Flavour_PtDir->cd();
	for(int j=0; j<n2DTaggingPtBins; j++) {
		for(int k=0; k<nflavours; k++) {
			vQGL_FlavourPt[k][j]->Write();
		}
	}
	
	TDirectory *gammapt_FlavourDir = out->mkdir("gammapt_Flavour","gammapt_Flavour");
	gammapt_FlavourDir->cd();
	for(int k=0; k<nflavours; k++) {
		vGammapt_Flavour[k]->Write();
	}
	
	
	TDirectory *variablesDir = out->mkdir("variables","variables");
	variablesDir->cd();
	hGammaPt->Write();
	hFirstJetPt->Write();
	hSecondJetPt->Write();
	hMetPt->Write();
	hParalleleMetPt->Write();
	hPerpendicularMetPt->Write();
	hAlpha->Write();
	hDeltaPhi_j1gamma->Write();
	hDeltaPhi_j2gamma->Write();
	hDeltaPhi_j1j2->Write();
	hDeltaR_j1gamma->Write();
	hDeltaR_j2gamma->Write();
	hDeltaR_j1j2->Write();
  TDirectory *gammaPtDir = variablesDir->mkdir("gammaPtPerZonePerFlavour","gammaPtPerZonePerFlavour");
  gammaPtDir->cd();
  for(int k=0; k<nflavours; k++) {
    for(int l=0; l<nzones; l++) {
		  vGammaPt_ZoneFlavour[l][k]->Write();
		}
	}



	TDirectory *plan2DTaggingDir = out->mkdir("plan2DTagging","plan2DTagging");
	plan2DTaggingDir->cd();
	for(int j=0; j<n2DTaggingPtBins; j++) {
		for(int i=0; i<nflavours; i++) {//divide flavour distri by total distri
			v2DTaggingPlan_FlavourPt[i][j]->Write();
			v2DTaggingPlan_FlavourPt_divided[i][j]->Write();	
		}
	}
	
	out->Close();
	
	return 0;
}
示例#28
0
int InputForLimits(){
  TH1::SetDefaultSumw2(true);
  if(pcp)cout<<"going to set inputs"<<endl;

  Int_t NBR = 3;
  Float_t BR[] = { 1., 0.75, 0.5};

  TFile* bkgFile = new TFile( "../../BkgPrediction/BkgPrediction.root", "READ"); 
  TTree* bkgTree;
  bkgFile->GetObject( "ElAndMu", bkgTree);
  
  Float_t bkg = 0.;
  Float_t bkgTotUnc = 0.;

  Float_t obs = 0.;

  bkgTree->SetBranchAddress( "srData", &obs);
  bkgTree->SetBranchAddress( "srAllBkgCorr", &bkg);
  bkgTree->SetBranchAddress( "TotUnc", &bkgTotUnc);

  TFile* sigFile = new TFile( "../../SignalSystematics/SignalSys.root", "READ"); 

  std::vector<std::vector<TString> > sysColl;
  std::vector<TString> sys;
  sys.push_back(TString("JES_Up"));
  sys.push_back(TString("JES_Down"));
  sysColl.push_back(sys);

  sys.clear();
  sys.push_back(TString("BTagReweight_UpBC"));
  sys.push_back(TString("BTagReweight_DownBC"));
  sysColl.push_back(sys);

  sys.clear();
  sys.push_back(TString("BTagReweight_UpLight"));
  sys.push_back(TString("BTagReweight_DownLight"));
  sysColl.push_back(sys);

  std::vector<TString> decayMode;
  decayMode.push_back(TString("tt"));
  decayMode.push_back(TString("tb"));
  decayMode.push_back(TString("bb"));
		      
  Systematics* systematics[3];
  TString dirname;
  TString histoname;

  TDirectory* srDir;
  TDirectory* histoDir;

  TFile* outFile = new TFile( "InputForLimits.root", "RECREATE");
  TDirectory* outBRDir;
  TDirectory* outSRDir;

  TH1F* datah = new TH1F( "data", "data", 1, 0., 1.);
  TH1F* bkgh = new TH1F( "bkg", "bkg", 1, 0., 1.);

  TH2F* sigh;
  TH2F* sig_toth;
  TH2F* effh;
  
  TH2F* sigLh;
  TH2F* effLh;

  TH2F* sigRh;
  TH2F* effRh;
  
  TH2F* jesh;
  TH2F* btagBCh;
  TH2F* btagLighth;
  TH2F* btagh;
  
  TH2F* sysh;

  TH2F* unch;

  TH2F* jesPercenth;
  TH2F* btagBCPercenth;
  TH2F* btagLightPercenth;
  TH2F* btagPercenth;
  
  TH2F* sysPercenth;

  TH2F* uncPercenth;

  Float_t sig = 0.;
  Float_t stat = 0.;

  Float_t jes = 0.;
  Float_t bc = 0.;
  Float_t light = 0.;
  
  Float_t unc = 0.;

  int N = bkgTree->GetEntries();

  for ( int ibr = 0; ibr < NBR; ibr++){
    dirname = ""; dirname += BR[ibr];
    outFile->mkdir(dirname);
    outBRDir = outFile->GetDirectory(dirname);

    for ( int iSR = 0; iSR < 9; iSR++){
      bkgTree->GetEntry(iSR);      
      datah->SetBinContent( 1, obs);
      bkgh->SetBinContent( 1, bkg);
      bkgh->SetBinError( 1, bkgTotUnc);

      dirname = ""; dirname += iSR;
      outBRDir->mkdir(dirname);
      outSRDir = outBRDir->GetDirectory(dirname);
      
      dirname = ""; dirname += iSR; dirname += ".root";      
      srDir = sigFile->GetDirectory( dirname);
      for ( int isys = 0; isys < (int) sysColl.size(); isys++){
	systematics[isys] = new Systematics();
	systematics[isys]->BR = BR[ibr];

	histoDir = srDir->GetDirectory( "NoSystematic");
	for ( int idecay = 0; idecay < (int) decayMode.size(); idecay++){
	  histoDir->GetObject( decayMode.at(idecay), systematics[isys]->h[idecay]);
	  histoDir->GetObject( decayMode.at(idecay) + "l", systematics[isys]->Lh);
	  histoDir->GetObject( decayMode.at(idecay) + "r", systematics[isys]->Rh);
	}
	histoDir->GetObject( decayMode.at(0) + "l", systematics[isys]->Lh);
	histoDir->GetObject( decayMode.at(0) + "r", systematics[isys]->Rh);
	histoDir->GetObject( "sig_tot", systematics[isys]->sig_toth);

	for ( int ishift = 0; ishift < 2; ishift++){
	  histoDir = srDir->GetDirectory(sysColl.at(isys).at(ishift));
	  for ( int idecay = 0; idecay < (int) decayMode.size(); idecay++){
	    histoDir->GetObject( decayMode.at(idecay), systematics[isys]->shifth[ishift][idecay]);
	  }
	}
	systematics[isys]->Calc();
      }
      sig_toth = new TH2F( *systematics[0]->sig_toth);
      sig_toth->SetName("sig_tot");
      sig_toth->SetTitle("sig_tot");    

      sigh = new TH2F( *systematics[0]->sigh);
      sigh->SetName("sig");
      sigh->SetTitle("sig");

      effh = new TH2F( *systematics[0]->effh);
      effh->SetName("eff");
      effh->SetTitle("eff");

      sigLh = new TH2F( *systematics[0]->sigRh);
      sigLh->SetName("sigL");
      sigLh->SetTitle("sigL");

      effLh = new TH2F( *systematics[0]->effLh);
      effLh->SetName("effL");
      effLh->SetTitle("effL");

      sigRh = new TH2F( *systematics[0]->sigRh);
      sigRh->SetName("sigR");
      sigRh->SetTitle("sigR");

      effRh = new TH2F( *systematics[0]->effRh);
      effRh->SetName("effR");
      effRh->SetTitle("effR");

      jesh = new TH2F( *systematics[0]->sysh);
      jesh->SetName("jes");
      jesh->SetTitle("jes");

      btagBCh = new TH2F( *systematics[1]->sysh);
      btagBCh->SetName("btagBC");
      btagBCh->SetTitle("btagBC");
      
      btagLighth = new TH2F( *systematics[2]->sysh);
      btagLighth->SetName("btagLight");
      btagLighth->SetTitle("btagLight");
      
      btagh = new TH2F( *btagBCh);
      btagh->Reset();
      btagh->SetName("btag");
      btagh->SetTitle("btag");
 
      sysh = new TH2F( *jesh);
      sysh->Reset();
      sysh->SetName("sys");
      sysh->SetTitle("sys");

      unch = new TH2F( *jesh);
      unch->Reset();
      unch->SetName("unc");
      unch->SetTitle("unc");


      jesPercenth = new TH2F( *systematics[0]->sysh);
      jesPercenth->SetName("jesPercent");
      jesPercenth->SetTitle("jesPercent");
      jesPercenth->Divide( sigh);
      jesPercenth->Scale( 100.);      

      btagBCPercenth = new TH2F( *systematics[1]->sysh);
      btagBCPercenth->SetName("btagBCPercent");
      btagBCPercenth->SetTitle("btagBCPercent");
      btagBCPercenth->Divide( sigh);
      btagBCPercenth->Scale( 100.);   

      btagLightPercenth = new TH2F( *systematics[2]->sysh);
      btagLightPercenth->SetName("btagLightPercent");
      btagLightPercenth->SetTitle("btagLightPercent");
      btagLightPercenth->Divide( sigh);
      btagLightPercenth->Scale( 100.);   

      btagPercenth = new TH2F( *btagBCh);
      btagPercenth->Reset();
      btagPercenth->SetName("btagPercent");
      btagPercenth->SetTitle("btagPercent");
 
      sysPercenth = new TH2F( *jesh);
      sysPercenth->Reset();
      sysPercenth->SetName("sysPercent");
      sysPercenth->SetTitle("sysPercent");

      uncPercenth = new TH2F( *jesh);
      uncPercenth->Reset();
      uncPercenth->SetName("uncPercent");
      uncPercenth->SetTitle("uncPercent");

      for (int ibin = 0; ibin < sigh->GetSize(); ibin++){	
	sig = sigh->GetBinContent( ibin);
	stat = sigh->GetBinError( ibin);

	jes = jesh->GetBinContent(ibin);
	bc = btagBCh->GetBinContent(ibin);
	light = btagLighth->GetBinContent(ibin);
    
	unc = sqrt( bc * bc + light * light);
	btagh->SetBinContent( ibin, unc);
	btagPercenth->SetBinContent( ibin, unc / sig * 100.);
	
	unc = sqrt( jes * jes + bc * bc + light * light +
		    sig * sig * (0.044 * 0.044 + // Lumi
				 0.03  * 0.03  + // Trigger
				 0.05  * 0.05    // Lep Id
				 )
		    );       
	sysh->SetBinContent( ibin, unc);
	sysPercenth->SetBinContent( ibin, unc / sig * 100.);
	
	unc = sqrt( jes * jes + bc * bc + light * light + stat * stat +  
		    sig * sig * (0.044 * 0.044 + // Lumi
				 0.03  * 0.03  + // Trigger
				 0.05  * 0.05    // Lep Id
				 )
		    );	
	unch->SetBinContent( ibin, unc);
	uncPercenth->SetBinContent( ibin, unc / sig * 100.);
      }
      outSRDir->cd();

      datah->Write();
      bkgh->Write();

      sig_toth->Write();
      sigh->Write();
      effh->Write();
      
      sigLh->Write();
      effLh->Write();

      sigRh->Write();
      effRh->Write();

      jesh->Write();
      btagBCh->Write(); 
      btagLighth->Write();
      btagh->Write();
      
      sysh->Write();
      unch->Write();

      jesPercenth->Write();
      btagBCPercenth->Write(); 
      btagLightPercenth->Write();
      btagPercenth->Write();
      
      sysPercenth->Write();
      uncPercenth->Write();
    }
  }

  delete systematics[0];
  delete systematics[1];
  delete systematics[2];

  outFile->Close();
  sigFile->Close();
  bkgFile->Close();

  return 0;
}
示例#29
0
///
///________________________________________________________________________________
///
UEJetAreaHistograms::UEJetAreaHistograms( const char* fileName, string *triggerNames )
{
  //  cout << "UEJetAreaHistograms::UEJetAreaHistograms( const char* fileName, string *triggerNames )" << endl;

  ///
  /// Constructor for histogram filler.
  ///

  char buffer[200];

  cout << "[UEJetAreaHistograms] Create file " << fileName << endl;
  file = TFile::Open( fileName, "recreate" );

  TDirectory*  dir = file->mkdir( "UEJetArea" );
  subdir           = new TDirectory*[12];

  ///
  /// Reserve space for histograms.
  ///
  h_pTAllJets            = new TH1D*[12]; // all jets
  h_etaAllJets           = new TH1D*[12];
  h_areaAllJets          = new TH1D*[12];
  h_ptByAreaAllJets      = new TH1D*[12];
  h_nConstituentsAllJets = new TH1D*[12];
  h2d_pTAllJets_vs_pTjet            = new TH2D*[12];
  h2d_areaAllJets_vs_pTjet          = new TH2D*[12];
  h2d_ptByAreaAllJets_vs_pTjet      = new TH2D*[12];
  h2d_nConstituentsAllJets_vs_pTjet = new TH2D*[12];

  h_pTJet                = new TH1D*[12]; // leading jet
  h_etaJet               = new TH1D*[12];
  h_areaJet              = new TH1D*[12];
  h_ptByAreaJet          = new TH1D*[12];
  h_nConstituentsJet     = new TH1D*[12];
  h2d_areaJet_vs_pTjet          = new TH2D*[12];
  h2d_ptByAreaJet_vs_pTjet      = new TH2D*[12];
  h2d_nConstituentsJet_vs_pTjet = new TH2D*[12];

  h_medianPt        = new TH1D*[12]; // event-by-event medians
  h_medianArea      = new TH1D*[12];
  h_medianPtByArea = new TH1D*[12];
  h2d_medianPt_vs_pTjet       = new TH2D*[12];
  h2d_medianArea_vs_pTjet     = new TH2D*[12];
  h2d_medianPtByArea_vs_pTjet = new TH2D*[12];

  ///
  /// 11 HLT bits :
  /// 4 Min-Bias (Pixel, Hcal, Ecal, general), Zero-Bias, 6 Jet (30, 50, 80, 110, 180, 250)
  ///
  unsigned int iHLTbit(0);
  for ( ; iHLTbit<11; ++iHLTbit )
    {
      HLTBitNames[iHLTbit] = triggerNames[iHLTbit];

      subdir[iHLTbit] = dir->mkdir( triggerNames[iHLTbit].c_str() );
      sprintf ( buffer, "UEJetArea/%s", triggerNames[iHLTbit].c_str() );
      file->cd( buffer );

      ///
      /// Initialize histograms.
      ///

      h_pTJet    [iHLTbit] = new TH1D("h_pTJet"    , "h_pTJet;p_{T}(leading jet) (GeV/c);", 300, 0., 600. );
      h_pTAllJets[iHLTbit] = new TH1D("h_pTAllJets", "h_pTAllJets;p_{T}(jet) (GeV/c);"    , 300, 0., 600. );

      h_etaJet    [iHLTbit] = new TH1D("h_etaJet"    , "h_etaJet;#eta(leading jet);", 100, -2., 2. );
      h_etaAllJets[iHLTbit] = new TH1D("h_etaAllJets", "h_etaAllJets;#eta(jet);"    , 100, -2., 2. );

      h_areaJet    [iHLTbit] = new TH1D("h_areaJet"    , "h_areaJet;Leading jet area A;", 100, 0., 2. );
      h_areaAllJets[iHLTbit] = new TH1D("h_areaAllJets", "h_areaAllJets;Jet area A;"    , 100, 0., 2. );

      h_ptByAreaJet    [iHLTbit] = new TH1D("h_ptByAreaJet"    , "h_ptByAreaJet;Leading jet p_{T}/A;", 1000, 0., 200. );
      h_ptByAreaAllJets[iHLTbit] = new TH1D("h_ptByAreaAllJets", "h_ptByAreaAllJets;Jet p_{T}/A;"    , 1000, 0., 200. );

      h_nConstituentsJet    [iHLTbit] = new TH1D("h_nConstituentsJet"    , 
						 "h_nConstituentsJet;N(leading jet constituents);", 50, 0.5, 50.5 );
      h_nConstituentsAllJets[iHLTbit] = new TH1D("h_nConstituentsAllJets", 
						 "h_nConstituentsAllJets;N(jet constituents);"    , 50, 0.5, 50.5 );

      h2d_pTAllJets_vs_pTjet[iHLTbit] = new TH2D( "h2d_pTAllJets_vs_pTjet",
						  "h2d_pTAllJets_vs_pTjet;p_{T}(leading jet) (GeV/c);p_{T}(jet) (GeV/c)",
						  300, 0., 600., 300, 0., 600. );

      h2d_areaJet_vs_pTjet    [iHLTbit]	
	= new TH2D("h2d_areaJet_vs_pTjet",
		   "h2d_areaJet_vs_pTjet;p_{T}(leading jet) (GeV/c);Leading Jet area A /rad", 300, 0., 600., 100, 0., 2. );
      h2d_areaAllJets_vs_pTjet[iHLTbit]	
	= new TH2D("h2d_areaAllJets_vs_pTjet",
		   "h2d_areaAllJets_vs_pTjet;p_{T}(leading jet) (GeV/c);Jet area A /rad", 300, 0., 600., 100, 0., 2. );

      h2d_ptByAreaJet_vs_pTjet    [iHLTbit] = 
	new TH2D("h2d_ptByAreaJet_vs_pTjet",
		 "h2d_ptByAreaJet_vs_pTjet;p_{T}(leading jet) (GeV/c);Leading Jet p_{T}/A (GeV/c rad^{-1})", 300, 0., 600., 1000, 0., 200. );
      h2d_ptByAreaAllJets_vs_pTjet[iHLTbit]	
	= new TH2D("h2d_ptByAreaAllJets_vs_pTjet",
		   "h2d_ptByAreaAllJets_vs_pTjet;p_{T}(leading jet) (GeV/c);Jet area p_{T}/A (GeV/c rad^{-1})", 300, 0., 600., 1000, 0., 200. );

      h2d_nConstituentsJet_vs_pTjet[iHLTbit]
	= new TH2D("h2d_nConstituentsJet_vs_pTjet",
		   "h2d_nConstituentsJet_vs_pTjet;p_{T}(leading jet) (GeV/c);N(leading jet constituents)",
		   300, 0., 600., 50, 0.5, 50.5 );
      h2d_nConstituentsAllJets_vs_pTjet[iHLTbit]
	= new TH2D("h2d_nConstituentsAllJets_vs_pTjet",
		   "h2d_nConstituentsAllJets_vs_pTjet;p_{T}(leading jet) (GeV/c);N(jet constituents)",
		   300, 0., 600., 50, 0.5, 50.5 );
      
      h_medianPt      [iHLTbit] = new TH1D("h_medianPt"  , "h_medianPt;#mu_{1/2}({p_{Ti}}) (GeV/c);", 300, 0., 600. );
      h_medianArea    [iHLTbit] = new TH1D("h_medianArea", "h_medianArea;#mu_{1/2}({A_{Ti}}) (rad);", 100, 0., 2.   );
      h_medianPtByArea[iHLTbit] = new TH1D("h_medianPtByArea",
					   "h_medianPtByArea;#mu_{1/2}({p_{Ti}/A_{i}}) (GeV/c rad^{-1});",
					   1000, 0., 200. );

      h2d_medianPt_vs_pTjet[iHLTbit] = 
	new TH2D("h2d_medianPt_vs_pTjet", 
		 "h2d_medianPt_vs_pTjet;p_{T}(leading jet) (GeV/c);#mu_{1/2}({p_{Ti}}) (GeV/c)", 300, 0., 600., 300, 0., 600. );
      h2d_medianArea_vs_pTjet[iHLTbit] = 
	new TH2D("h2d_medianArea_vs_pTjet", 
		 "h2d_medianArea_vs_pTjet;p_{T}(leading jet) (GeV/c);#mu_{1/2}({A_{Ti}}) (rad)", 300, 0., 600., 100, 0., 2. );
      h2d_medianPtByArea_vs_pTjet[iHLTbit]
	= new TH2D("h2d_medianPtByArea_vs_pTjet",
		   "h2d_medianPtByArea_vs_pTjet;p_{T}(leading jet) (GeV/c);#mu_{1/2}({p_{Ti}/A_{i}}) (GeV/c rad^{-1})",
		   300, 0., 600., 100, 0., 20. );

    }

  ///
  /// Hadron level
  ///
  iHLTbit         = 11;
  subdir[iHLTbit] = dir->mkdir( "Gen" );
  file->cd( "UEJetArea/Gen" );


  h_pTJet    [iHLTbit] = new TH1D("h_pTJet"    , "h_pTJet;p_{T}(leading jet) (GeV/c);", 300, 0., 600. );
  h_pTAllJets[iHLTbit] = new TH1D("h_pTAllJets", "h_pTAllJets;p_{T}(jet) (GeV/c);"    , 300, 0., 600. );
  
  h_etaJet    [iHLTbit] = new TH1D("h_etaJet"    , "h_etaJet;#eta(leading jet);", 100, -2., 2. );
  h_etaAllJets[iHLTbit] = new TH1D("h_etaAllJets", "h_etaAllJets;#eta(jet);"    , 100, -2., 2. );
  
  h_areaJet    [iHLTbit] = new TH1D("h_areaJet"    , "h_areaJet;Leading jet area A;", 100, 0., 2. );
  h_areaAllJets[iHLTbit] = new TH1D("h_areaAllJets", "h_areaAllJets;Jet area A;"    , 100, 0., 2. );

  h_ptByAreaJet    [iHLTbit] = new TH1D("h_ptByAreaJet"    , "h_ptByAreaJet;Leading jet p_{T}/A;", 1000, 0., 200. );
  h_ptByAreaAllJets[iHLTbit] = new TH1D("h_ptByAreaAllJets", "h_ptByAreaAllJets;Jet p_{T}/A;"    , 1000, 0., 200. );

  h_nConstituentsJet    [iHLTbit] = new TH1D("h_nConstituentsJet"    ,
					     "h_nConstituentsJet;N(leading jet constituents);", 50, 0.5, 50.5 );
  h_nConstituentsAllJets[iHLTbit] = new TH1D("h_nConstituentsAllJets",
					     "h_nConstituentsAllJets;N(jet constituents);"    , 50, 0.5, 50.5 );

  h2d_pTAllJets_vs_pTjet[iHLTbit] = new TH2D( "h2d_pTAllJets_vs_pTjet",
					      "h2d_pTAllJets_vs_pTjet;p_{T}(leading jet) (GeV/c);p_{T}(jet) (GeV/c)",
					      300, 0., 600., 300, 0., 600. );

  h2d_areaJet_vs_pTjet    [iHLTbit]
    = new TH2D("h2d_areaJet_vs_pTjet",
	       "h2d_areaJet_vs_pTjet;p_{T}(leading jet) (GeV/c);Leading Jet area A /rad", 300, 0., 600., 100, 0., 2. );
  h2d_areaAllJets_vs_pTjet[iHLTbit]
    = new TH2D("h2d_areaAllJets_vs_pTjet",
	       "h2d_areaAllJets_vs_pTjet;p_{T}(leading jet) (GeV/c);Jet area A /rad", 300, 0., 600., 100, 0., 2. );
  
  h2d_ptByAreaJet_vs_pTjet    [iHLTbit] =
    new TH2D("h2d_ptByAreaJet_vs_pTjet",
	     "h2d_ptByAreaJet_vs_pTjet;p_{T}(leading jet) (GeV/c);Leading Jet p_{T}/A (GeV/c rad^{-1})", 300, 0., 600., 1000, 0., 200. );
  h2d_ptByAreaAllJets_vs_pTjet[iHLTbit]
    = new TH2D("h2d_ptByAreaAllJets_vs_pTjet",
	       "h2d_ptByAreaAllJets_vs_pTjet;p_{T}(leading jet) (GeV/c);Jet area p_{T}/A (GeV/c rad^{-1})", 300, 0., 600., 1000, 0., 200. );
  
  h2d_nConstituentsJet_vs_pTjet[iHLTbit]
    = new TH2D("h2d_nConstituentsJet_vs_pTjet",
	       "h2d_nConstituentsJet_vs_pTjet;p_{T}(leading jet) (GeV/c);N(leading jet constituents)",
	       300, 0., 600., 50, 0.5, 50.5 );
  h2d_nConstituentsAllJets_vs_pTjet[iHLTbit]
    = new TH2D("h2d_nConstituentsAllJets_vs_pTjet",
	       "h2d_nConstituentsAllJets_vs_pTjet;p_{T}(leading jet) (GeV/c);N(jet constituents)",
	       300, 0., 600., 50, 0.5, 50.5 );
  
  h_medianPt      [iHLTbit] = new TH1D("h_medianPt"  , "h_medianPt;#mu_{1/2}({p_{Ti}}) (GeV/c);", 300, 0., 600. );
  h_medianArea    [iHLTbit] = new TH1D("h_medianArea", "h_medianArea;#mu_{1/2}({A_{Ti}}) (rad);", 100, 0., 2.   );
  h_medianPtByArea[iHLTbit] = new TH1D("h_medianPtByArea",
				       "h_medianPtByArea;#mu_{1/2}({p_{Ti}/A_{i}}) (GeV/c rad^{-1});",
				       1000, 0., 200. );
  
  h2d_medianPt_vs_pTjet[iHLTbit] =
    new TH2D("h2d_medianPt_vs_pTjet",
	     "h2d_medianPt_vs_pTjet;p_{T}(leading jet) (GeV/c);#mu_{1/2}({p_{Ti}}) (GeV/c)", 300, 0., 600., 300, 0., 600. );
  h2d_medianArea_vs_pTjet[iHLTbit] =
    new TH2D("h2d_medianArea_vs_pTjet",
	     "h2d_medianArea_vs_pTjet;p_{T}(leading jet) (GeV/c);#mu_{1/2}({A_{Ti}}) (rad)", 300, 0., 600., 100, 0., 2. );
  h2d_medianPtByArea_vs_pTjet[iHLTbit]
    = new TH2D("h2d_medianPtByArea_vs_pTjet",
	       "h2d_medianPtByArea_vs_pTjet;p_{T}(leading jet) (GeV/c);#mu_{1/2}({p_{Ti}/A_{i}}) (GeV/c rad^{-1})",
	       300, 0., 600., 100, 0., 20. );
  
}
示例#30
0
mainClass(int luminosity){//constructor
//Importnat
//make sure this initialization of the 
//maps is the same as that in main.cpp
     cutname[0]="RA2nocut";
    cutname[1]="RA2Asys";
    cutname[2]="RA2Inc3Jetcut";
    cutname[3]="RA2HT500cut";
    cutname[4]="RA2MHT200cut";
    cutname[5]="RA2delphicut";
    cutname[6]="RA2noleptoncut";
    cutname[7]="noPhotoncut";
    cutname[8]="RA2Inc4Jetcut";
    cutname[9]="RA2Inc5Jetcut";
    cutname[10]="RA2Inc6Jetcut";
    cutname[11]="RA2allbutHT2500cut";
    cutname[12]="RA2allbutMHT1000cut";
    cutname[13]="RA2allcut";
    cutname[14]="RA2noleptoncutMHT1000";
    cutname[15]="RA2noleptoncutBtag2";
    cutname[16]="RA2noleptoncutBtag2MHT1000";
    cutname[17]="RA2Inc4JetcutMHT1000";
    cutname[18]="RA2Inc4JetcutBtag2";
    cutname[19]="RA2Inc4JetcutBtag2MHT1000";
    cutname[20]="RA2Inc5JetcutMHT1000";
    cutname[21]="RA2Inc5JetcutBtag2";
    cutname[22]="RA2Inc5JetcutBtag2MHT1000";
    cutname[23]="RA2Inc6JetcutMHT1000";
    cutname[24]="RA2Inc6JetcutBtag2";
    cutname[25]="RA2Inc6JetcutBtag2MHT1000";


    sigtype[0]="allEvents";
    sigtype[1]="glgl";

    BJtype[0]="allEvents";
    BJtype[1]="W";
    BJtype[2]="Wlv";
    BJtype[3]="Wjj";
    BJtype[4]="Z";
    BJtype[5]="Zll";
    BJtype[6]="Zvv";
    BJtype[7]="Zjj";
    BJtype[8]="photon";
    BJtype[9]="H";

   TTtype[0]="allEvents";
   TTtype[1]="TTbar";
   TTtype[2]="TTSingLep";
   TTtype[3]="TTdiLep";
   TTtype[4]="TThadronic";



  //KH
  histname[0]="weight";
  histname[1]="HT";
  histname[2]="MHT";
  histname[3]="NJet";
  histname[4]="NBtagLoose";
  histname[5]="NBtagTight";
  histname[6]="BtagLoose1Pt";
histname[7]="BtagLoose1Eta";
histname[8]="BtagLoose1Phi";
histname[9]="BtagLoose2Pt";
histname[10]="BtagLoose2Eta";
histname[11]="BtagLoose2Phi";
histname[12]="BtagTight1Pt";
histname[13]="BtagTight1Eta";
histname[14]="BtagTight1Phi";
histname[15]="BtagTight2Pt";
histname[16]="BtagTight2Eta";
histname[17]="BtagTight2Phi";

  ///end of initialization of the maps

yieldmap.clear();



//Signal Section//Signal Section//Signal Section//Signal Section//Signal Section//Signal Section//Signal Section//Signal Section

  //build a vector of scale factors
  //first load the cross sections into a vector
//Sig_xs_vec.push_back(0.757); /// v1
//Sig_xs_vec.push_back(1.12); // v2
//Sig_xs_vec.push_back(1.15); // v3
//Sig_xs_vec.push_back(1.14); // M(Stop,LSP)=(450,410) and also M(Stop,LSP)=(450,440)
//Sig_xs_vec.push_back(2.18); // M(Stop,LSP)=(400,390) and also M(Stop,LSP)=(400,360)
//Sig_xs_vec.push_back(4.41); // M(Stop,LSP)=(350,340) and also M(Stop,LSP)=(350,310)
//Sig_xs_vec.push_back(0.009635); //STOCv4
Sig_xs_vec.push_back(1.58); //StauC

  double Sig_numberofevents =0;//this will use GetSumOfWeights() 
  const int Sig_nHT = 1;   // Total number of HT bin samples
  const int nHist = 18; // Number of histograms in each TDirectory


  for(int i=1; i<=Sig_nHT ; i++){
//sprintf(tempname,"../Results/results_PhaseII4_Stop_CharmLSP_14TEV_140PileUp_00.root");
//sprintf(tempname,"../Results/results_PhaseII4_Stop_CharmLSPv2_14TEV_140PileUp_00.root");
//sprintf(tempname,"../Results/results_PhaseII4_Stop_CharmLSPv3_14TEV_140PileUp_00.root");
//sprintf(tempname,"../Results/results_PhaseII4_t2cc450410_14TEV_140PileUp_00.root");  
//sprintf(tempname,"../Results/results_PhaseII4_t2cc450440_14TEV_140PileUp_00.root");
//sprintf(tempname,"../Results/results_PhaseII4_t2cc400390_14TEV_140PileUp_00.root");
//sprintf(tempname,"../Results/results_PhaseII4_t2cc400360_14TEV_140PileUp_00.root");
//sprintf(tempname,"../Results/results_PhaseII4_t2cc350340_14TEV_140PileUp_00.root");
//sprintf(tempname,"../Results/results_PhaseII4_t2cc350310_14TEV_140PileUp_00.root");
//sprintf(tempname,"../Results/results_PhaseII4_Stop_CharmLSPv4_14TEV_140PileUp_00.root");
sprintf(tempname,"../Results/results_PhaseII4_StauC_14TEV_140PileUp.root");
  file = new TFile(tempname, "R");
    sprintf(tempname,"allEvents/RA2nocut/MHT_RA2nocut_allEvents");
    tempvalue = (luminosity*Sig_xs_vec[i-1])/((* (TH1D* ) file->Get(tempname)).GetEntries());
    Sig_scalevec.push_back(tempvalue);
  }//end of loop over HTbins 
  std::cout << "normalization scale factor determination done" << std::endl;
for(int i=1; i<=Sig_nHT; i++){
//sprintf(tempname,"../Results/results_PhaseII4_Stop_CharmLSP_14TEV_140PileUp_00.root");
//sprintf(tempname,"../Results/results_PhaseII4_Stop_CharmLSPv2_14TEV_140PileUp_00.root");
//sprintf(tempname,"../Results/results_PhaseII4_Stop_CharmLSPv3_14TEV_140PileUp_00.root");
//sprintf(tempname,"../Results/results_PhaseII4_t2cc450410_14TEV_140PileUp_00.root");  
//sprintf(tempname,"../Results/results_PhaseII4_t2cc450440_14TEV_140PileUp_00.root");
//sprintf(tempname,"../Results/results_PhaseII4_t2cc400390_14TEV_140PileUp_00.root");
//sprintf(tempname,"../Results/results_PhaseII4_t2cc400360_14TEV_140PileUp_00.root");
//sprintf(tempname,"../Results/results_PhaseII4_t2cc350340_14TEV_140PileUp_00.root");
//sprintf(tempname,"../Results/results_PhaseII4_t2cc350310_14TEV_140PileUp_00.root");
//sprintf(tempname,"../Results/results_PhaseII4_Stop_CharmLSPv4_14TEV_140PileUp_00.root");
sprintf(tempname,"../Results/results_PhaseII4_StauC_14TEV_140PileUp.root");
Sig_inputfilevec.push_back(TFile::Open(tempname,"R"));
}

tempstack = new THStack("stack","Binned Sample Stack");
//sprintf(tempname,"PhaseII4_Stop_CharmLSP_14TEV_140PileUp_00.root");
//sprintf(tempname,"PhaseII4_Stop_CharmLSPv2_14TEV_140PileUp_00.root");
//sprintf(tempname,"PhaseII4_Stop_CharmLSPv3_14TEV_140PileUp_00.root");
//sprintf(tempname,"PhaseII4_t2cc450410_14TEV_140PileUp_00.root");  
//sprintf(tempname,"PhaseII4_t2cc450440_14TEV_140PileUp_00.root");
//sprintf(tempname,"PhaseII4_t2cc400390_14TEV_140PileUp_00.root");
//sprintf(tempname,"PhaseII4_t2cc400360_14TEV_140PileUp_00.root");
//sprintf(tempname,"PhaseII4_t2cc350340_14TEV_140PileUp_00.root");
//sprintf(tempname,"PhaseII4_t2cc350310_14TEV_140PileUp_00.root");
//sprintf(tempname,"PhaseII4_Stop_CharmLSPv4_14TEV_140PileUp_00.root");
sprintf(tempname,"PhaseII4_StauC_14TEV_140PileUp.root");
file = new TFile(tempname,"RECREATE");
 for(map<int , string >::iterator itt=sigtype.begin(); itt!=sigtype.end();itt++){        // loop over different event types
    cdtoitt = file->mkdir((itt->second).c_str());
    cdtoitt->cd();
int c=0;
    for(map<int , string >::iterator it=cutname.begin(); it!=cutname.end();it++){   // loop over different cutnames
      cdtoit =  cdtoitt->mkdir((it->second).c_str());
      cdtoit->cd();
      for(int j=0; j<histname.size(); j++){                                        // loop over different histograms
        for(int i=0; i<Sig_nHT ; i++){                                                  // loop over different HT bins
sprintf(tempname,"%s/%s/%s_%s_%s",(itt->second).c_str(),(it->second).c_str(),(histname[j]).c_str(),(it->second).c_str(),(itt->second).c_str());
temphist = (TH1D *) Sig_inputfilevec.at(i)->Get(tempname)->Clone();
temphist->Scale(Sig_scalevec[i]);
if(histname[j]=="MHT"){
Sig_numberofevents+=(double)temphist->GetSumOfWeights();
} 
temphist->SetFillColor(i+2);
tempstack->Add(temphist);


               }//end of loop over HTbins 1..7
if(histname[j]=="MHT"){
if(itt->second=="allEvents"){
yieldmap[c].push_back(Sig_numberofevents);
}

}
Sig_numberofevents=0;
        sprintf(tempname,"%s_%s_%s",histname[j].c_str(),(it->second).c_str(),(itt->second).c_str());
        tempstack->Write(tempname);
        delete tempstack;
        tempstack = new THStack("stack","Binned Sample Stack");
      }//end of loop over histograms
 c+=1;   }//end of loop over cutnames
  }//end of loop over event types
file->Close();

//BJ Section//BJ Section//BJ Section//BJ Section//BJ Section//BJ Section//BJ Section//BJ Section//BJ Section//BJ Section//BJ Section

 //build a vector of scale factors
  //first load the cross sections into a vector
  BJ_xs_vec.push_back(34409.92339);
  BJ_xs_vec.push_back(2642.85309);
  BJ_xs_vec.push_back(294.12311);
  BJ_xs_vec.push_back(25.95000);
  BJ_xs_vec.push_back(2.42111);
  BJ_xs_vec.push_back(0.22690);
  BJ_xs_vec.push_back(0.02767);

  double BJ_numberofevents =0;
  const int bjnHT = 7;   // Total number of HT bin samples


  for(int i=1; i<=bjnHT ; i++){
    sprintf(tempname,"../Results/results_PhaseII4_BJ_14TEV_HT%d_140PileUp.root",i);
    file = new TFile(tempname, "R");
    sprintf(tempname,"allEvents/RA2nocut/MHT_RA2nocut_allEvents");
    tempvalue = (luminosity*BJ_xs_vec[i-1])/((* (TH1D* ) file->Get(tempname)).GetEntries());
    BJ_scalevec.push_back(tempvalue);
  }//end of loop over HTbins 
  std::cout << "normalization scale factor determination done" << std::endl;
for(int i=1; i<=bjnHT; i++){
sprintf(tempname,"../Results/results_PhaseII4_BJ_14TEV_HT%d_140PileUp.root",i);
BJ_inputfilevec.push_back(TFile::Open(tempname,"R"));
}

//tempstack = new THStack("stack","Binned Sample Stack");
sprintf(tempname,"PhaseII4_BJ_14TEV_140PileUp.root");
//file = new TFile(tempname,"RECREATE");
 for(map<int , string >::iterator itt=BJtype.begin(); itt!=BJtype.end();itt++){        // loop over different event types
//    cdtoitt = file->mkdir((itt->second).c_str());
//    cdtoitt->cd();
int c=0;
    for(map<int , string >::iterator it=cutname.begin(); it!=cutname.end();it++){   // loop over different cutnames
//      cdtoit =  cdtoitt->mkdir((it->second).c_str());
//      cdtoit->cd();
      for(int j=0; j<histname.size(); j++){                                        // loop over different histograms
        for(int i=0; i<bjnHT ; i++){                                                  // loop over different HT bins
//cout << "================================" << endl;
//cout << "HT#: " <<i << ", BJtype: " << itt->second << ", cutname: " << it->second << ", hist#: " << j << endl;  
sprintf(tempname,"%s/%s/%s_%s_%s",(itt->second).c_str(),(it->second).c_str(),(histname[j]).c_str(),(it->second).c_str(),(itt->second).c_str());
temphist = (TH1D *) BJ_inputfilevec.at(i)->Get(tempname)->Clone();
temphist->Scale(BJ_scalevec[i]);
if(histname[j]=="MHT"){
BJ_numberofevents+=(double)temphist->GetSumOfWeights();
}
temphist->SetFillColor(i+2);
//tempstack->Add(temphist);
               }//end of loop over HTbins 1..7
if(histname[j]=="MHT"){
if(itt->second=="Wlv" || itt->second=="Zvv"){
yieldmap[c].push_back(BJ_numberofevents);
}

}
BJ_numberofevents=0;
        sprintf(tempname,"%s_%s_%s",histname[j].c_str(),(it->second).c_str(),(itt->second).c_str());
  //      tempstack->Write(tempname);
  //      delete tempstack;
  //      tempstack = new THStack("stack","Binned Sample Stack");
      }//end of loop over histograms
c+=1;    }//end of loop over cutnames
  }//end of loop over event types
//file->Close();


//TTbar Section//TTbar Section//TTbar Section//TTbar Section//TTbar Section//TTbar Section//TTbar Section//TTbar Section

  //build a vector of scale factors
  //first load the cross sections into a vector
  TT_xs_vec.push_back(530.89358);
  TT_xs_vec.push_back(42.55351);
  TT_xs_vec.push_back(4.48209);
  TT_xs_vec.push_back(0.52795);
  TT_xs_vec.push_back(0.05449);

  double TT_numberofevents =0;
  const int ttnHT = 5;   // Total number of HT bin samples


  for(int i=1; i<=ttnHT ; i++){
    sprintf(tempname,"../Results/results_PhaseII4_TT_14TEV_HT%d_140PileUp.root",i);
    file = new TFile(tempname, "R");
    sprintf(tempname,"allEvents/RA2nocut/MHT_RA2nocut_allEvents");
    tempvalue = (luminosity*TT_xs_vec[i-1])/((* (TH1D* ) file->Get(tempname)).GetEntries());
    TT_scalevec.push_back(tempvalue);
  }//end of loop over HTbins 
  std::cout << "normalization scale factor determination done" << std::endl;
for(int i=1; i<=ttnHT; i++){
sprintf(tempname,"../Results/results_PhaseII4_TT_14TEV_HT%d_140PileUp.root",i);
TT_inputfilevec.push_back(TFile::Open(tempname,"R"));
}

//tempstack = new THStack("stack","Binned Sample Stack");
sprintf(tempname,"PhaseII4_TT_14TEV_140PileUp.root");
//file = new TFile(tempname,"RECREATE");
 for(map<int , string >::iterator itt=TTtype.begin(); itt!=TTtype.end();itt++){        // loop over different event types
//    cdtoitt = file->mkdir((itt->second).c_str());
//    cdtoitt->cd();
int c=0;
    for(map<int , string >::iterator it=cutname.begin(); it!=cutname.end();it++){   // loop over different cutnames
//      cdtoit =  cdtoitt->mkdir((it->second).c_str());
//      cdtoit->cd();
      for(int j=0; j<histname.size(); j++){                                        // loop over different histograms
        for(int i=0; i<ttnHT ; i++){                                                  // loop over different HT bins
sprintf(tempname,"%s/%s/%s_%s_%s",(itt->second).c_str(),(it->second).c_str(),(histname[j]).c_str(),(it->second).c_str(),(itt->second).c_str());
temphist = (TH1D *) TT_inputfilevec.at(i)->Get(tempname)->Clone();
temphist->Scale(TT_scalevec[i]);
if(histname[j]=="MHT"){
TT_numberofevents+=(double)temphist->GetSumOfWeights();
}
temphist->SetFillColor(i+2);
//tempstack->Add(temphist);
               }//end of loop over HTbins 1..5
if(histname[j]=="MHT"){
if(itt->second=="allEvents"){
yieldmap[c].push_back(TT_numberofevents);
}

}
TT_numberofevents=0;
        sprintf(tempname,"%s_%s_%s",histname[j].c_str(),(it->second).c_str(),(itt->second).c_str());
//        tempstack->Write(tempname);
//        delete tempstack;
//        tempstack = new THStack("stack","Binned Sample Stack");
      }//end of loop over histograms
c+=1;   }//end of loop over cutnames
  }//end of loop over event types
//file->Close();



///write the output in a file
fstream ff;
ff.open("CutFlow.txt", std::fstream::out);
ff << " Cut Name,    " << "  Signal,      " << "  Wlv,      " << "  Zvv,     " << "  TTbar,      "<< "    Total BG,   " << " % Signal/Background,   "  <<  "    Significance " << endl; 
double totalBG=0, delWlv=0, delZvv=0, delTT=0, delB=0, delBsquare=0;
for(int i=0; i<yieldmap.size(); i++){
totalBG=(double) (yieldmap[i].at(1)+yieldmap[i].at(2)+yieldmap[i].at(3));
delWlv= 0.08*yieldmap[i].at(1);///uncrtainty for Wlv is 8%
delZvv= 0.05*yieldmap[i].at(2);
delTT= 0.5*yieldmap[i].at(3);///uncrtainty for TTbar is 50%
delBsquare=pow(delWlv,2)+pow(delZvv,2)+pow(delTT,2);///delta_background = sqrt(delWlv^2+delZvv^2+delTT^2)
ff << "  " <<cutname[i]<<",     " << yieldmap[i].at(0) << ",     " << yieldmap[i].at(1) <<",     " << yieldmap[i].at(2) <<",     " <<yieldmap[i].at(3) << ",      "<< totalBG << ",      " << yieldmap[i].at(0)/totalBG*100  <<  ",       " << yieldmap[i].at(0)/sqrt(delBsquare+totalBG+yieldmap[i].at(0))  <<endl;  
}
ff.close();

/*
///write the output in a file
fstream ff;
ff.open("CutFlow.txt", std::fstream::out);
ff << " Cut Name,    " << "  Signal,      "  << endl; 
for(int i=0; i<yieldmap.size(); i++){
ff << "  " <<cutname[i]<<",     " << yieldmap[i].at(0) << endl;  
}
ff.close();
*/
}//end of the constructor