Ejemplo n.º 1
0
  void WalkerControlBase::start()
  {
    if(MyContext == 0)
    {
      if(dmcStream) delete dmcStream;
      string hname(myComm->getName());
      if (WriteRN) hname.append(".rn.dat");
      else hname.append(".dmc.dat");
      dmcStream= new ofstream(hname.c_str());
      //oa = new boost::archive::binary_oarchive (*dmcStream);
      dmcStream->setf(ios::scientific, ios::floatfield);
      dmcStream->precision(10);
      (*dmcStream) << setw(10) << "# Index "
		   << setw(20) << "LocalEnergy"
		   << setw(20) << "Variance" 
		   << setw(20) << "Weight"
		   << setw(20) << "NumOfWalkers"; 
      if (WriteRN) 
        {
	(*dmcStream) << setw(20) << "RNWalkers" 
		     << setw(20) << "AlternateEnergy";
        }
      (*dmcStream)   << setw(20) << "TrialEnergy" 
		     << setw(20) << "DiffEff";
      if (WriteRN) (*dmcStream)  
        << setw(20) << "LivingFraction";
      (*dmcStream) << endl;
    }
  }
Ejemplo n.º 2
0
/*
 * Resizes a HacheTable to have 'newsize' buckets.
 * This is called automatically when adding or removing items so that the
 * hash table keeps at a sensible scale.
 *
 * FIXME: Halving the size of the hash table is simply a matter of coaelescing
 * every other bucket. Instead we currently rehash (which is slower).
 * Doubling the size of the hash table currently requires rehashing, but this
 * too could be optimised by storing the full 32-bit hash of the key along
 * with the key itself. This then means that it's just a matter of seeing what
 * the next significant bit is. It's a memory vs speed tradeoff though and
 * re-hashing is pretty quick.
 *
 * Returns 0 for success
 *        -1 for failure
 */
int HacheTableResize(HacheTable *h, int newsize) {
    HacheTable *h2;
    int i;

#ifdef DEBUG
    fprintf(stdout, "Resizing HacheTable %s to %d\n", hname(h), newsize);
#endif

    /* Create a new hash table and rehash everything into it */
    h2 = HacheTableCreate(newsize, h->options);
    
    for (i = 0; i < h->nbuckets; i++) {
	HacheItem *hi, *next;
	for (hi = h->bucket[i]; hi; hi = next) {
	    assert(hi->h == h);
	    uint32_t hv = hache(h2->options & HASH_FUNC_MASK,
			       (uint8_t *)hi->key, hi->key_len) & h2->mask;
	    next = hi->next;
	    hi->next = h2->bucket[hv];
	    h2->bucket[hv] = hi;
	}
    }

    /* Swap the links over & free */
    free(h->bucket);
    h->bucket   = h2->bucket;
    h->nbuckets = h2->nbuckets;
    h->mask     = h2->mask;
    if (h2->ordering)
	free(h2->ordering);
    free(h2);
    
    return 0;
}
Ejemplo n.º 3
0
/*
 * Expands the cache size in a hash table. This is only typically required due
 * to too many items being marked as in-use.
 */
int HacheTableExpandCache(HacheTable *h) {
    HacheOrder *newo;
    int i, j = h->cache_size;

    fprintf(stderr, "Cache order %s full, doubling size (%d)!\n",
	    hname(h), h->cache_size*2);

    /* Double size */
    newo = (HacheOrder *)realloc(h->ordering, h->cache_size*2 * sizeof(*newo));
    if (NULL == newo)
	return -1;

    h->cache_size *= 2;
    h->ordering = newo;

    /* Add free entries */
    for (i = j; i < h->cache_size; i++) {
	h->ordering[i].hi = NULL;
	h->ordering[i].next = i == h->cache_size-1 ? -1 : i+1;
	h->ordering[i].prev = i-1;
    }
    if (-1 != h->free) {
	h->ordering[h->cache_size-1].next = h->free;
	h->ordering[h->free].prev = h->cache_size-1;
    }

    h->ordering[j].prev = -1;
    h->free = j;

    return 0;
}
Ejemplo n.º 4
0
SocketAddress
SocketAddress::getAnyLocalHost(UInt16 port)
{
	struct in_addr addr;
	addr.s_addr = hton32(INADDR_ANY);
	SocketAddress rval = getFromNativeForm(addr, port, "localhost");
	char buf[256];
	gethostname(buf, sizeof(buf));
	String hname(buf);
	if (hname.indexOf('.') == String::npos)
	{
#if defined(OW_HAVE_GETHOSTBYNAME_R) && defined(OW_GETHOSTBYNAME_R_ARGUMENTS)
		hostent hostbuf;
		hostent* hent = &hostbuf;
#if (OW_GETHOSTBYNAME_R_ARGUMENTS == 6)
		char local_buf[2048];
		int h_err = 0;
		if (gethostbyname_r(buf, &hostbuf, local_buf, sizeof(local_buf),
							&hent, &h_err) == -1)
		{
			hent = NULL;
		}
#elif (OW_GETHOSTBYNAME_R_ARGUMENTS == 5)

		char local_buf[2048];
		int h_err(0);
		// returns NULL if not successful
		hent = gethostbyname_r(buf, &hostbuf, local_buf, sizeof(local_buf), &h_err);

#elif (OW_GETHOSTBYNAME_R_ARGUMENTS == 3)
		hostent_data hostdata;
		if (gethostbyname_r(buf, &hostbuf, &hostdata) != 0)
		{
			hent = NULL;
		}

#else
#error Not yet supported: gethostbyname_r() with other argument counts.
#endif /* OW_GETHOSTBYNAME_R_ARGUMENTS */
#else	
		MutexLock mlock(gethostbynameMutex);
		hostent* hent = gethostbyname(buf);
#endif
		if (hent && hent->h_name && (strlen(hent->h_name) > 0))
		{
			hname = String(hent->h_name);
		}
	}
	rval.m_name = hname;
	return rval;
}
Ejemplo n.º 5
0
void drawCoeffProfiles1pair(char *infile,
                            char *proc,  // WW or WZ
                            char *varx,  // what we want to call the variables
                            char *vary,
                            char *trvarx, // what the tree calls the variables
                            char *trvary,
                            int nptsx,float xmin,float xmax,
                            int nptsy,float ymin,float ymax,
                            std::vector<TProfile2D*>& outgraphs)
{
    TFile * fin = new TFile(infile);
    TTree* tr = (TTree*) fin->Get("tree");
    for (int i=0; i<=6; i++) {
        TString hname(Form("%s_p%d_%s_%s",proc,i,varx,vary));
        cout << "Drawing " << TString(hname)<<endl;
        TProfile2D* prof2d = new TProfile2D(hname,"",nptsx,xmin,xmax,nptsy,ymin,ymax);
        prof2d->SetTitle(Form("%s;%s;%s;p%d",hname.Data(),varx,vary,i));
        tr->Draw(Form("p%d:%s:%s>>%s",i,trvary,trvarx,hname.Data()),"","goff");
        outgraphs.push_back(prof2d);
    }
}
Ejemplo n.º 6
0
// input: - Input file (result from TMVA),
//        - normal/decorrelated/PCA
//        - use of TMVA plotting TStyle
void variables( TString fin = "TMVA.root", TString dirName = "InputVariables_Id", TString title = "TMVA Input Variables",
                Bool_t isRegression = kFALSE, Bool_t useTMVAStyle = kTRUE )
{
   TString outfname = dirName;
   outfname.ToLower(); outfname.ReplaceAll( "input", ""  );

   // set style and remove existing canvas'
   TMVAGlob::Initialize( useTMVAStyle );

   // obtain shorter histogram title 
   TString htitle = title; 
   htitle.ReplaceAll("variables ","variable");
   htitle.ReplaceAll("and target(s)","");
   htitle.ReplaceAll("(training sample)","");

   // checks if file with name "fin" is already open, and if not opens one
   TFile* file = TMVAGlob::OpenFile( fin );

   TDirectory* dir = (TDirectory*)file->Get( dirName );
   if (dir==0) {
      cout << "No information about " << title << " available in directory " << dirName << " of file " << fin << endl;
      return;
   }
   dir->cd();

   // how many plots are in the directory?
   Int_t noPlots = TMVAGlob::GetNumberOfInputVariables( dir ) +
      TMVAGlob::GetNumberOfTargets( dir );

   // define Canvas layout here!
   // default setting
   Int_t xPad;  // no of plots in x
   Int_t yPad;  // no of plots in y
   Int_t width; // size of canvas
   Int_t height;
   switch (noPlots) {
   case 1:
      xPad = 1; yPad = 1; width = 550; height = 0.90*width; break;
   case 2:
      xPad = 2; yPad = 1; width = 600; height = 0.50*width; break;
   case 3:
      xPad = 3; yPad = 1; width = 900; height = 0.4*width; break;
   case 4:
      xPad = 2; yPad = 2; width = 600; height = width; break;
   default:
//       xPad = 3; yPad = 2; width = 800; height = 0.55*width; break;
     xPad = 1; yPad = 1; width = 550; height = 0.90*width; break;
   }

   Int_t noPadPerCanv = xPad * yPad ;

   // counter variables
   Int_t countCanvas = 0;
   Int_t countPad    = 0;

   // loop over all objects in directory
   TCanvas* canv = 0;
   TKey*    key  = 0;
   Bool_t   createNewFig = kFALSE;
   TIter next(dir->GetListOfKeys());
   while ((key = (TKey*)next())) {
      if (key->GetCycle() != 1) continue;

      if (!TString(key->GetName()).Contains("__Signal") && 
          !(isRegression && TString(key->GetName()).Contains("__Regression"))) continue;

      // make sure, that we only look at histograms
      TClass *cl = gROOT->GetClass(key->GetClassName());
      if (!cl->InheritsFrom("TH1")) continue;
      TH1 *sig = (TH1*)key->ReadObj();
      TString hname(sig->GetName());

      //normalize to 1
      NormalizeHist(sig);      

      // create new canvas
      if (countPad%noPadPerCanv==0) {
         ++countCanvas;
         canv = new TCanvas( Form("canvas%d", countCanvas), title,
                             countCanvas*50+50, countCanvas*20, width, height );
         canv->Divide(xPad,yPad);
         canv->SetFillColor(kWhite);
         canv->Draw();
      }

      TPad* cPad = (TPad*)canv->cd(countPad++%noPadPerCanv+1);
      cPad->SetFillColor(kWhite);

      // find the corredponding backgrouns histo
      TString bgname = hname;
      bgname.ReplaceAll("__Signal","__Background");
      TH1 *bgd = (TH1*)dir->Get(bgname);
      if (bgd == NULL) {
         cout << "ERROR!!! couldn't find background histo for" << hname << endl;
         exit;
      }
      //normalize to 1
      NormalizeHist(bgd);


      // this is set but not stored during plot creation in MVA_Factory
      TMVAGlob::SetSignalAndBackgroundStyle( sig, (isRegression ? 0 : bgd) );            

      sig->SetTitle( TString( htitle ) + ": " + sig->GetTitle() );
      TMVAGlob::SetFrameStyle( sig, 1.2 );

      // normalise both signal and background
//       if (!isRegression) TMVAGlob::NormalizeHists( sig, bgd );
//       else {
//          // change histogram title for target
//          TString nme = sig->GetName();
//          if (nme.Contains( "_target" )) {
//             TString tit = sig->GetTitle();
//             sig->SetTitle( tit.ReplaceAll("Input variable", "Regression target" ) );
//          }
//       }
      sig->SetTitle( "" );            
      

      // finally plot and overlay
      Float_t sc = 1.1;
      if (countPad == 1) sc = 1.3;
      sig->SetMaximum( TMath::Max( sig->GetMaximum(), bgd->GetMaximum() )*sc );
      sig->Draw( "hist" );
      cPad->SetLeftMargin( 0.17 );

      sig->GetYaxis()->SetTitleOffset( 1.50 );
      if (!isRegression) {
         bgd->Draw("histsame");
         TString ytit = TString("(1/N) ") + sig->GetYaxis()->GetTitle();
         ytit = TString("Fraction of Events");
         sig->GetYaxis()->SetTitle( ytit ); // histograms are normalised
      }

      if (countPad == 1) sig->GetXaxis()->SetTitle("Leading Lepton p_{T} [GeV/c]");
      if (countPad == 2) sig->GetXaxis()->SetTitle("Trailing Lepton p_{T} [GeV/c]");
      if (countPad == 3) sig->GetXaxis()->SetTitle("#Delta#phi(l,l)");
      if (countPad == 4) sig->GetXaxis()->SetTitle("#Delta R(l,l)");
      if (countPad == 5) sig->GetXaxis()->SetTitle("Dilepton Mass [GeV/c^{2}]");
      if (countPad == 6) sig->GetXaxis()->SetTitle("Dilepton Flavor Final State");
      if (countPad == 7) sig->GetXaxis()->SetTitle("M_{T} (Higgs) [GeV/c^{2}]");
      if (countPad == 8) sig->GetXaxis()->SetTitle("#Delta#phi(Dilepton System, MET)");
      if (countPad == 9) sig->GetXaxis()->SetTitle("#Delta#phi(Dilepton System, Jet)");


      // Draw legend
//       if (countPad == 1 && !isRegression) {
         TLegend *legend= new TLegend( cPad->GetLeftMargin(), 
                                       1-cPad->GetTopMargin()-.15, 
                                       cPad->GetLeftMargin()+.4, 
                                       1-cPad->GetTopMargin() );

         if(countPad == 1 || countPad == 2 ||countPad == 3 ||countPad == 4 ||countPad == 5 ||countPad == 7  ) {
           legend= new TLegend( 0.50, 
                                1-cPad->GetTopMargin()-.15, 
                                0.90, 
                                1-cPad->GetTopMargin() );
         }

         legend->SetFillStyle(0);
         legend->AddEntry(sig,"Signal","F");
         legend->AddEntry(bgd,"Background","F");
         legend->SetBorderSize(0);
         legend->SetMargin( 0.3 );
         legend->SetTextSize( 0.03 );
         legend->Draw("same");
//       } 

      // redraw axes
      sig->Draw("sameaxis");

      // text for overflows
      Int_t    nbin = sig->GetNbinsX();
      Double_t dxu  = sig->GetBinWidth(0);
      Double_t dxo  = sig->GetBinWidth(nbin+1);
      TString uoflow = "";
      if (isRegression) {
         uoflow = Form( "U/O-flow: %.1f%% / %.1f%%", 
                        sig->GetBinContent(0)*dxu*100, sig->GetBinContent(nbin+1)*dxo*100 );
      }
      else {
         uoflow = Form( "U/O-flow (S,B): (%.1f, %.1f)%% / (%.1f, %.1f)%%", 
                        sig->GetBinContent(0)*dxu*100, bgd->GetBinContent(0)*dxu*100,
                        sig->GetBinContent(nbin+1)*dxo*100, bgd->GetBinContent(nbin+1)*dxo*100 );
      }
  
      TText* t = new TText( 0.98, 0.14, uoflow );
      t->SetNDC();
      t->SetTextSize( 0.040 );
      t->SetTextAngle( 90 );
//       t->AppendPad();    

      // save canvas to file
      if (countPad%noPadPerCanv==0) {
         TString fname = Form( "plots/%s_c%i", outfname.Data(), countCanvas );
         TMVAGlob::plot_logo();
         TMVAGlob::imgconv( canv, fname );
         createNewFig = kFALSE;
      }
      else {
         createNewFig = kTRUE;
      }
   }
   
   if (createNewFig) {
      TString fname = Form( "plots/%s_c%i", outfname.Data(), countCanvas );
      TMVAGlob::plot_logo();
      TMVAGlob::imgconv( canv, fname );
      createNewFig = kFALSE;
   }

   return;
}
Ejemplo n.º 7
0
 * keys will be considered to be owned by the hash table. In this case
 * the key will be freed when the table is destroyed regardless of
 * whether the HASH_NONVOLATILE_KEYS option was used to allocate its
 * own private copy.
 *
 * Returns:
 *    The HacheItem created (or matching if a duplicate) on success
 *    NULL on failure
 */
HacheItem *HacheTableAdd(HacheTable *h, char *key, int key_len, HacheData data,
			 int *new) {
    uint32_t hv;
    HacheItem *hi;

#ifdef DEBUG
    printf("HacheTableAdd %s %d data.p %p\n", hname(h), *(int *)key, data.p);
#endif

    if (!key_len)
	key_len = strlen(key);

    hv = hache(h->options & HASH_FUNC_MASK, (uint8_t *)key, key_len) & h->mask;
    
    /* Already exists? */
    if (!(h->options & HASH_ALLOW_DUP_KEYS)) {
	for (hi = h->bucket[hv]; hi; hi = hi->next) {
	    if (key_len == hi->key_len &&
		memcmp(key, hi->key, key_len) == 0) {
		if (new) *new = 0;
		return hi;
	    }
Ejemplo n.º 8
0
int main(int argc, const char* argv[]){

  gErrorIgnoreLevel = kError;

  gSystem->Load("libTree");

  bool   _ttbar_cat = false;
  bool   _syst      = false;
  const char * _output   = 0;
  const char * _input    = 0;
  // TopTrees directory
  const char * _dir      = "../Files_v7-6-3/";
  const char * _syst_var = 0;
  const char * _ttbar_id = "";

  // Arguments used
  //std::set<int> usedargs;
  //Parsing input options
  if(argc == 1){
    display_usage();
    return -1;
  }

  else{
      //Argumet 1 must be a valid input fileName
      for (int i = 1; i < argc; i++){
	if( strcmp(argv[i],"-i") == 0 ){
	  _input = argv[i+1];
	  i++;
	}
	if( strcmp(argv[i],"-d") == 0 ){
	  _dir = argv[i+1];
	  i++;
	}
	if( strcmp(argv[i],"-o") == 0 ){
	  _output= argv[i+1];
	  i++;
	}
	if( strcmp(argv[i],"-cat") == 0 ){
	  _ttbar_cat = true;
	  _ttbar_id  = argv[i+1];
	  i++;
	}
	if( strcmp(argv[i],"-s") == 0 ){
	  _syst= true;
	  _syst_var = argv[i+1];
	}
	if( strcmp(argv[i],"-h") == 0 ||
	    strcmp(argv[i],"--help") == 0 ){
	  display_usage();
	  return 0;
	}
      }
  }//else
  if( _input ==0 ){
    std::cerr << "\033[1;31mskimfile ERROR:\033[1;m The '-i' option is mandatory!"
	      << std::endl;
    display_usage();
    return -1;
  }
  
  // reassigning
  TString fname(_input);
  TString hname(_output);
  TString fdir(_dir);
  TString ttbar_id(_ttbar_id);
  TString syst_varname(_syst_var);
  
  TChain theTree("ttbbLepJets/gentree"); 
  
  std::cout << "---------------------------------------------------------------------------------" << std::endl;
  std::cout << "Signal: ";
  std::cout << fname + ".root" << std::endl;

  theTree.Add(fdir + fname + ".root");

  int Channel;
  float GENWeight; 
  std::vector<float> *ScaleWeight=0;
  float Lep_pT, Lep_eta;
  std::vector<float> *Jet_px=0, *Jet_py=0, *Jet_pz=0, *Jet_pT=0, *Jet_E=0;
  std::vector<int> *Jet_Mom=0;

  std::vector<int>   *Jet_partonFlavour=0;

  // Categorization
  int  GenCat_ID;
  std::vector<int> *GenConeCat=0; 
 /*********************************
           Tree Branches
  **********************************/
  
  theTree.SetBranchAddress( "genweight",     &GENWeight  );
  theTree.SetBranchAddress( "scaleweight",   &ScaleWeight);
  theTree.SetBranchAddress( "genchannel",    &Channel    );
  theTree.SetBranchAddress( "genhiggscatid", &GenCat_ID  );
  theTree.SetBranchAddress( "genconecatid",  &GenConeCat );


  theTree.SetBranchAddress( "genlepton_pT",  &Lep_pT );
  theTree.SetBranchAddress( "genlepton_eta", &Lep_eta);
  theTree.SetBranchAddress( "genjet_px",     &Jet_px );
  theTree.SetBranchAddress( "genjet_py",     &Jet_py );
  theTree.SetBranchAddress( "genjet_pz",     &Jet_pz );
  theTree.SetBranchAddress( "genjet_E",      &Jet_E  );

  theTree.SetBranchAddress( "genjet_mom",     &Jet_Mom);


  /*********************************
         Output Tree: MVA     
  **********************************/
  float b_pTjj, b_Mjj, b_DRjj, b_DPhijj;    

  TTree *MVASignaltree;
  MVASignaltree = new TTree("MVASignaltree","Dijets from W decay");
  MVASignaltree->Branch("pTjj",   &b_pTjj,   "pTjj/F");
  MVASignaltree->Branch("Mjj",    &b_Mjj,    "Mjj/F");
  MVASignaltree->Branch("DRjj",   &b_DRjj,   "DRjj/F");
  MVASignaltree->Branch("DPhijj", &b_DPhijj, "DPhijj/F");

  TTree *MVAtree;
  MVAtree = new TTree("MVAtree","All Dijets");
  MVAtree->Branch("pTjj",   &b_pTjj,   "pTjj/F");
  MVAtree->Branch("Mjj",    &b_Mjj,    "Mjj/F");
  MVAtree->Branch("DRjj",   &b_DRjj,   "DRjj/F");
  MVAtree->Branch("DPhijj", &b_DPhijj, "DPhijj/F");

  TTree *MVABkgtree;
  MVABkgtree = new TTree("MVABkgtree","All Dijets but W decay");
  MVABkgtree->Branch("pTjj",   &b_pTjj,   "pTjj/F");
  MVABkgtree->Branch("Mjj",    &b_Mjj,    "Mjj/F");
  MVABkgtree->Branch("DRjj",   &b_DRjj,   "DRjj/F");
  MVABkgtree->Branch("DPhijj", &b_DPhijj, "DPhijj/F");

  /*********************************
             Histograms
  **********************************/

  //Correct Statistical Uncertainty Treatment
  //TH1::SetDefaultSumw2(kTRUE);  
  
  TH1F *hNJets[2];
  TH1F *hJetMatch[2];
  TH2F *h2DJetMjjID_I[2], *h2DJetMjjID_II[2];

  TH1F *hJetPt[6][2], *hOJetPt[4][2], *hWJetPt[2][2];

  TH1F *hpTJet [5][6][2], *hMassJet [5][6][2], *hDRJet [5][6][2], *hDPhiJet [5][6][2];
  TH1F *hOpTJet[3][4][2], *hOMassJet[3][4][2], *hODRJet[3][4][2], *hODPhiJet[3][4][2];

  TH1F *hpTWjj[2],*hInvMassWjj[2],*hDRWjj[2], *hDPhiWjj[2];
  TH1F *hpTOjj[2],*hInvMassOjj[2],*hDROjj[2], *hDPhiOjj[2];

  TH1F *hpTminjj [2], *hpTmaxjj [2], *hInvMassjj [2], *hDRminjj [2], *hDRmaxjj [2], *hDPhiminjj [2], *hDPhimaxjj [2];
  TH1F *hOpTminjj[2], *hOpTmaxjj[2], *hOInvMassjj[2], *hODRminjj[2], *hODRmaxjj[2], *hODPhiminjj[2], *hODPhimaxjj[2];

  TString namech[2];
  namech[0]="mujets";
  namech[1]="ejets";
  
  TString titlenamech[2];
  titlenamech[0]="#mu+Jets";
  titlenamech[1]="e+Jets";
  
  for(int i=0; i<2; i++){ // Channel
    hNJets[i]      = new TH1F("hNJets_" + namech[i], "Jet multiplicity " + titlenamech[i],9,-0.5,8.5);
    hNJets[i]->GetXaxis()->SetTitle("Number of jets");      
    hNJets[i]->GetXaxis()->SetBinLabel(1,"0");
    hNJets[i]->GetXaxis()->SetBinLabel(2,"1");
    hNJets[i]->GetXaxis()->SetBinLabel(3,"2");
    hNJets[i]->GetXaxis()->SetBinLabel(4,"3");
    hNJets[i]->GetXaxis()->SetBinLabel(5,"4");
    hNJets[i]->GetXaxis()->SetBinLabel(6,"5");
    hNJets[i]->GetXaxis()->SetBinLabel(7,"6");
    hNJets[i]->GetXaxis()->SetBinLabel(8,"7");
    hNJets[i]->GetXaxis()->SetBinLabel(9,"#geq 8");
        

    hJetMatch[i] = new TH1F("hJetMatch_" + namech[i], "W Jet Match " + titlenamech[i],13,0,13);
    hJetMatch[i]->GetXaxis()->SetBinLabel(1,"Total # Evt");
    hJetMatch[i]->GetXaxis()->SetBinLabel(2,"#Delta Mjj is Wjj");
    hJetMatch[i]->GetXaxis()->SetBinLabel(3,"Min #Delta R_{jj} is Wjj");
    hJetMatch[i]->GetXaxis()->SetBinLabel(4,"Max #Delta R_{jj} is Wjj");
    hJetMatch[i]->GetXaxis()->SetBinLabel(5,"Min #Delta #Phi_{jj} is Wjj");
    hJetMatch[i]->GetXaxis()->SetBinLabel(6,"Max #Delta #Phi_{jj} is Wjj");
    hJetMatch[i]->GetXaxis()->SetBinLabel(7,"At least 1 ->");
    hJetMatch[i]->GetXaxis()->SetBinLabel(8, "#Delta Mjj is Wjj");
    hJetMatch[i]->GetXaxis()->SetBinLabel(9, "Min #Delta R_{jj} is Wjj");
    hJetMatch[i]->GetXaxis()->SetBinLabel(10,"Max #Delta R_{jj} is Wjj");
    hJetMatch[i]->GetXaxis()->SetBinLabel(11,"Min #Delta #Phi_{jj} is Wjj");
    hJetMatch[i]->GetXaxis()->SetBinLabel(12,"Max #Delta #Phi_{jj} is Wjj");
    hJetMatch[i]->GetXaxis()->SetBinLabel(13,"#Delta Mjj && Min #Delta R_{jj} is Wjj");

    h2DJetMjjID_I[i] = new TH2F("h2DJetMjjID1_" + namech[i], "Index ID " + titlenamech[i], 6, 0, 6, 6, 0, 6);
    h2DJetMjjID_I[i]->GetXaxis()->SetTitle("W Index");      
    h2DJetMjjID_I[i]->GetYaxis()->SetTitle("Mjj Index");      

    h2DJetMjjID_II[i] = new TH2F("h2DJetMjjID2_" + namech[i], "Index ID " + titlenamech[i],6, 0, 6, 6, 0, 6);
    h2DJetMjjID_II[i]->GetXaxis()->SetTitle("W Index");      
    h2DJetMjjID_II[i]->GetYaxis()->SetTitle("Mjj Index");      


    TString jetn[6];
    jetn[0]= "Jet-0"; 
    jetn[1]= "Jet-1"; 
    jetn[2]= "Jet-2"; 
    jetn[3]= "Jet-3"; 
    jetn[4]= "Jet-4"; 
    jetn[5]= "Jet-5"; 
    
    for(int ij=0; ij<2; ij++){
      hWJetPt[ij][i] = new TH1F("hWJetPt_" + jetn[ij] + "_" + namech[i], "p_{T}^{Jet} " + jetn[ij] + " " + titlenamech[i],40,0,200);
      hWJetPt[ij][i]->GetXaxis()->SetTitle("p_{T}[GeV]");      
    }
    for(int ij=0; ij<6; ij++){
      hJetPt[ij][i] = new TH1F("hJetPt_" + jetn[ij] + "_" + namech[i], "p_{T}^{Jet} " + jetn[ij] + " " + titlenamech[i],40,0,200);
      hJetPt[ij][i]->GetXaxis()->SetTitle("p_{T}[GeV]");      
    }
    for(int ij=0; ij<4; ij++){
      hOJetPt[ij][i] = new TH1F("hOJetPt_" + jetn[ij] + "_" + namech[i], "p_{T}^{Jet} " + jetn[ij] + " " + titlenamech[i],40,0,200);
      hOJetPt[ij][i]->GetXaxis()->SetTitle("p_{T}[GeV]");      
    }

    
    TString dijetname[5][6];
    dijetname[0][1] = "Jet01";
    dijetname[0][2] = "Jet02";
    dijetname[0][3] = "Jet03";
    dijetname[0][4] = "Jet04";
    dijetname[0][5] = "Jet05";
    dijetname[1][2] = "Jet12";
    dijetname[1][3] = "Jet13";
    dijetname[1][4] = "Jet14";
    dijetname[1][5] = "Jet15";
    dijetname[2][3] = "Jet23";
    dijetname[2][4] = "Jet24";
    dijetname[2][5] = "Jet25";
    dijetname[3][4] = "Jet34";
    dijetname[3][5] = "Jet35";
    dijetname[4][5] = "Jet45";
    
    for(int ja=0; ja<5; ja++){
      for(int jb=ja+1; jb<6; jb++){
	hpTJet[ja][jb][i]   = new TH1F("hpTJet_"   + dijetname[ja][jb] + "_" + namech[i], "transverse pT of Dijets "   + dijetname[ja][jb] + " " + titlenamech[i],80,0,400);
	hMassJet[ja][jb][i] = new TH1F("hMassJet_" + dijetname[ja][jb] + "_" + namech[i], "transverse Mass of Dijets " + dijetname[ja][jb] + " " + titlenamech[i],80,0,400);
	hDRJet[ja][jb][i]   = new TH1F("hDRJet_"   + dijetname[ja][jb] + "_" + namech[i], "#Delta R of Dijets "        + dijetname[ja][jb] + " " + titlenamech[i],50,0,5);
	hDPhiJet[ja][jb][i] = new TH1F("hDPhiJet_" + dijetname[ja][jb] + "_" + namech[i], "#Delta #phi of Dijets "     + dijetname[ja][jb] + " " + titlenamech[i],80,0,4);
      }
    }
    
    for(int ja=0; ja<3; ja++){
      for(int jb=ja+1; jb<4; jb++){
	hOpTJet[ja][jb][i]   = new TH1F("hOpTJet_"   + dijetname[ja][jb] + "_" + namech[i], "transverse pT of Dijets "   + dijetname[ja][jb] + " " + titlenamech[i],80,0,400);
	hOMassJet[ja][jb][i] = new TH1F("hOMassJet_" + dijetname[ja][jb] + "_" + namech[i], "transverse Mass of Dijets " + dijetname[ja][jb] + " " + titlenamech[i],80,0,400);
	hODRJet[ja][jb][i]   = new TH1F("hODRJet_"   + dijetname[ja][jb] + "_" + namech[i], "#Delta R of Dijets "        + dijetname[ja][jb] + " " + titlenamech[i],50,0,5);
	hODPhiJet[ja][jb][i] = new TH1F("hODPhiJet_" + dijetname[ja][jb] + "_" + namech[i], "#Delta #phi of Dijets "     + dijetname[ja][jb] + " " + titlenamech[i],80,0,4);
      }
    }
    
    hpTWjj[i]      = new TH1F("hpTWjj_"      + namech[i] ,"pT jets coming from W "                  + titlenamech[i], 80, 0, 400);
    hInvMassWjj[i] = new TH1F("hInvMassWjj_" + namech[i] ,"Inv. Mass of jets coming from W "        + titlenamech[i], 80, 0, 400);
    hDRWjj[i]      = new TH1F("hDRWjj_"      + namech[i] ,"#Delta R_{jj} of jets coming from W "    + titlenamech[i], 50, 0, 5);
    hDPhiWjj[i]    = new TH1F("hDPhiWjj_"    + namech[i] ,"#Delta #phi_{jj} of jets coming from W " + titlenamech[i], 80, 0, 4);

    hpTOjj[i]      = new TH1F("hpTOjj_"      + namech[i] ,"pT jets coming from W "                  + titlenamech[i], 80, 0, 400);
    hInvMassOjj[i] = new TH1F("hInvMassOjj_" + namech[i] ,"Inv. Mass of jets coming from W "        + titlenamech[i], 80, 0, 400);
    hDROjj[i]      = new TH1F("hDROjj_"      + namech[i] ,"#Delta R_{jj} of jets coming from W "    + titlenamech[i], 50, 0, 5);
    hDPhiOjj[i]    = new TH1F("hDPhiOjj_"    + namech[i] ,"#Delta #phi_{jj} of jets coming from W " + titlenamech[i], 80, 0, 4);
    
    hpTminjj[i]   = new TH1F("hpTminjj_"      + namech[i] ,"Minimum pT^{jj} "          + titlenamech[i], 80, 0, 400);
    hpTmaxjj[i]   = new TH1F("hpTmaxjj_"      + namech[i] ,"Maximum pT^{jj} "          + titlenamech[i], 80, 0, 400);
    hInvMassjj[i] = new TH1F("hInvMassjj_" + namech[i] ,"Compatible Inv. Mass "     + titlenamech[i], 80, 0, 400);
    hDRminjj[i]   = new TH1F("hDRminjj_"   + namech[i] ,"Minimum #Delta R_{jj} "    + titlenamech[i], 50, 0, 5);
    hDRmaxjj[i]   = new TH1F("hDRmaxjj_"   + namech[i] ,"Maximum #Delta R_{jj} "    + titlenamech[i], 50, 0, 5);
    hDPhiminjj[i] = new TH1F("hDPhiminjj_" + namech[i] ,"Minimum #Delta #Phi_{jj} " + titlenamech[i], 80, 0, 4);
    hDPhimaxjj[i] = new TH1F("hDPhimaxjj_" + namech[i] ,"Maximum #Delta #Phi_{jj} " + titlenamech[i], 80, 0, 4);
    
    hOpTminjj[i]   = new TH1F("hOpTminjj_"   + namech[i] ,"Minimum pT^{jj} "          + titlenamech[i], 80, 0, 400);
    hOpTmaxjj[i]   = new TH1F("hOpTmaxjj_"   + namech[i] ,"Maximum pT^{jj} "          + titlenamech[i], 80, 0, 400);
    hOInvMassjj[i] = new TH1F("hOInvMassjj_" + namech[i] ,"Compatible Inv. Mass "     + titlenamech[i], 80, 0, 400);
    hODRminjj[i]   = new TH1F("hODRminjj_"   + namech[i] ,"Minimum #Delta R_{jj} "    + titlenamech[i], 50, 0, 5);
    hODRmaxjj[i]   = new TH1F("hODRmaxjj_"   + namech[i] ,"Maximum #Delta R_{jj} "    + titlenamech[i], 50, 0, 5);
    hODPhiminjj[i] = new TH1F("hODPhiminjj_" + namech[i] ,"Minimum #Delta #Phi_{jj} " + titlenamech[i], 80, 0, 4);
    hODPhimaxjj[i] = new TH1F("hODPhimaxjj_" + namech[i] ,"Maximum #Delta #Phi_{jj} " + titlenamech[i], 80, 0, 4);

  }//for(i)
  
  
  TStopwatch sw;
  sw.Start(kTRUE);

  ///////////////////////////////////////
  // Please, IGNORE. Temporal solution //
  ///////////////////////////////////////
  TCanvas *mydummycanvas=new TCanvas();// 
  ///////////////////////////////////////
  // Number de events for acceptance
  //          [Channel]
  float fAccEvent_full_ttbb[2] = {0.0,0.0};
  float fAccEvent_full_ttjj[2] = {0.0,0.0};  
  float fAccEvent_vis_ttbb [2] = {0.0,0.0};
  float fAccEvent_vis_ttjj [2] = {0.0,0.0};

  int AccEvent_full_ttbb[2] = {0,0};
  int AccEvent_full_ttjj[2] = {0,0};
  int AccEvent_vis_ttbb [2] = {0,0};
  int AccEvent_vis_ttjj [2] = {0,0};

  // Uncertainties file name
  if(_syst) fname += "_SYS_" + syst_varname;

  /********************************
             Event Loop
  ********************************/
  std::cout << "--- Processing: " << theTree.GetEntries() << " events" << std::endl;
  
  for (Long64_t ievt=0; ievt<theTree.GetEntries();ievt++) {
    
    theTree.GetEntry(ievt);  
    print_progress(theTree.GetEntries(), ievt);
    
    // Jets 
    int NJets;
    NJets     = 0;    
    std::vector<TLorentzVector> vjets, vOjets, vWjets, vTjets;
    std::vector<int> vIndex, vWIndex, vOIndex, vTIndex;

    for(int ijet=0; ijet < Jet_px->size(); ijet++){
      
      TLorentzVector gjet;
      gjet.SetPxPyPzE((*Jet_px)[ijet], (*Jet_py)[ijet], (*Jet_pz)[ijet], (*Jet_E)[ijet]);

      if(gjet.Pt()>25 && std::abs(gjet.Eta())<2.5){

	vjets.push_back(gjet); // All Jets
	vIndex.push_back(ijet);

	if ((*Jet_Mom)[ijet] == 24){
	  vWjets.push_back(gjet); // Jets coming from W	
	  vWIndex.push_back(ijet);	  
	}	
	else if ((*Jet_Mom)[ijet] == 6){
	  vTjets.push_back(gjet); // Jets coming from W	
	  vTIndex.push_back(ijet);	  
	}	
	else{
	  vOjets.push_back(gjet); // Other Jets
	  vOIndex.push_back(ijet);
	}
      } // if(jet.pT > 25)
    }// for(jets)
    
        
    /***************************
       Categorization GenTop
    ***************************/

    int cone_channel = (*GenConeCat)[0];

    // Visible Phase Space:
    // pT(jet) > 20GeV && |eta(Jet)| < 2.5
    int cone_NJets  = (*GenConeCat)[1];
    int cone_NbJets = (*GenConeCat)[2];
    int cone_NcJets = (*GenConeCat)[3];
    
    int cone_NbJetsNoTop = (*GenConeCat)[4];
    
    // Full Phase Space:
    // pT(jet) > 20GeV && |eta(Jet)| < 2.5
    int cone_NaddJets  = (*GenConeCat)[5];
    int cone_NaddbJets = (*GenConeCat)[6];

    /*******************************************
          Categorization to use W Jets 
    *******************************************/

  TString CatEvt = "";
  // if (_ttbar_cat){
  if (cone_NaddJets == 0 && ttbar_category("tt", GenCat_ID) && vWjets.size() == 2){
    if      (ttbar_Wjjcategory(GenCat_ID).Contains("bb_") && vTjets.size() == 2) CatEvt = "bbWjj"; // Two b-jets from top inside acceptance
    else if (ttbar_Wjjcategory(GenCat_ID).Contains("b_" ) && vTjets.size() == 1) CatEvt = "bWbjj"; // One b-jet  from top inside acceptance
    else if ((ttbar_Wjjcategory(GenCat_ID) == "_LF" || ttbar_Wjjcategory(GenCat_ID) == "_c") && vTjets.size() == 0) CatEvt = "Wjj";   // No b-jets  from top inside acceptance
	
  }
  // }
  /*******************************************
             Dijet Invariant Mass 
  *******************************************/
    
  if (vWjets.size() == 2 && 
      (CatEvt == "bbWjj" || CatEvt == "bWjj" || CatEvt == "Wjj")){
  // if (vWjets.size() == 2 && vjets.size() == 6 && vTjets.size() == 2 && cone_NaddJets == 2){
      
      NJets = vjets.size();
      
      float pTWjj, MWjj, DRWjj, DPhiWjj;
      
      // Jets from W
      if(vWjets.size() == 2){
	TLorentzVector jet_WI  = vWjets[0];
	TLorentzVector jet_WII = vWjets[1];
	hWJetPt[0][Channel]->Fill(jet_WI.Pt());
	hWJetPt[1][Channel]->Fill(jet_WII.Pt());
	
	pTWjj   = (vWjets.at(0) + vWjets.at(1)).Pt();
	MWjj    = (vWjets.at(0) + vWjets.at(1)).M();
	DRWjj   = vWjets.at(0).DeltaR(vWjets.at(1));
	DPhiWjj = std::abs(vWjets.at(0).DeltaPhi(vWjets.at(1)));
	
	hpTWjj[Channel]     ->Fill(pTWjj); 
	hInvMassWjj[Channel]->Fill(MWjj); 
	hDRWjj[Channel]     ->Fill(DRWjj);   
	hDPhiWjj[Channel]   ->Fill(DPhiWjj);   

 	// MVA Bkg TREE
	b_pTjj   = pTWjj;
	b_Mjj    = MWjj;
	b_DRjj   = DRWjj;
	b_DPhijj = DPhiWjj;
	
	MVASignaltree->Fill();	

      }

    std::vector<TLorentzVector> seljets;
      
      for(int coljet = 0; coljet < 2; coljet++){
	
	if(coljet == 0) seljets = vjets; 
	else seljets = vOjets; 
	
	// Estimation of all the the paramenters of the dijet
	int pTminIndex[2], pTmaxIndex[2], InvMassIndex[2], DRminIndex[2], DRmaxIndex[2], DPhiminIndex[2], DPhimaxIndex[2];
	float minpTjj = 9999., maxpTjj = 0., Mjj = 0., minDeltaMjj = 9999.,  minDeltaRjj = 9999., maxDeltaRjj = 0., minDeltaPhijj = 9999., maxDeltaPhijj = 0.;
	
	// Loop over the first Jet
	for(int ijet=0; ijet < seljets.size(); ijet++){
	  
	  TLorentzVector jet_i = seljets[ijet];
	  
	  // Loop over the second Jet
	  for(int jjet=ijet+1; jjet < seljets.size(); jjet++){
	    
	    TLorentzVector jet_j = seljets[jjet];
	    
	    float DijetpT = (jet_i+jet_j).Pt(); 
	    
	    if(minpTjj > DijetpT){
	      minpTjj = DijetpT;
	      pTminIndex[0] = vIndex[ijet];
	      pTminIndex[1] = vIndex[jjet];
	    }
	    
	    if(maxpTjj < DijetpT){
	      maxpTjj = DijetpT;
	      pTmaxIndex[0] = vIndex[ijet]; pTmaxIndex[1] = vIndex[jjet];
	    }
	    
	    float DijetInvMass = (jet_i+jet_j).M(); 
	    float DeltaMjj = std::abs(DijetInvMass-80.3);
	    
	    if(minDeltaMjj > DeltaMjj){
	      minDeltaMjj = DeltaMjj;
	      Mjj = DijetInvMass;
	      InvMassIndex[0] = vIndex[ijet]; InvMassIndex[1] = vIndex[jjet];
	    }
	    
	    float DijetDeltaR  = jet_i.DeltaR(jet_j); 
	    
	    if(minDeltaRjj > DijetDeltaR){
	      minDeltaRjj = DijetDeltaR;
	      DRminIndex[0] = ijet; DRminIndex[1] = jjet;
	    }
	    
	    if(maxDeltaRjj < DijetDeltaR){
	      maxDeltaRjj = DijetDeltaR;
	      DRmaxIndex[0] = vIndex[ijet]; DRmaxIndex[1] = vIndex[jjet];
	    }
	    
	    float DijetDeltaPhi  = std::abs(jet_i.DeltaPhi(jet_j)); 
	    
	    if(minDeltaPhijj > DijetDeltaPhi){
	      minDeltaPhijj = DijetDeltaPhi;
	      DPhiminIndex[0] = vIndex[ijet]; DPhiminIndex[1] = vIndex[jjet];
	    }
	    
	    if(maxDeltaPhijj < DijetDeltaPhi){
	      maxDeltaPhijj = DijetDeltaPhi;
	      DPhimaxIndex[0] = vIndex[ijet]; DPhimaxIndex[1] = vIndex[jjet];
	    }
	    
	    // Dijet Variables
	    if(coljet == 0){
	      hpTJet   [ijet][jjet][Channel]->Fill(DijetpT);
	      hMassJet [ijet][jjet][Channel]->Fill(DijetInvMass);  
	      hDRJet   [ijet][jjet][Channel]->Fill(DijetDeltaR);
	      hDPhiJet [ijet][jjet][Channel]->Fill(DijetDeltaPhi);

	      // MVA TREE
	      b_pTjj   = DijetpT;
	      b_Mjj    = DijetInvMass;
	      b_DRjj   = DijetDeltaR;
	      b_DPhijj = DijetDeltaPhi;

	      MVAtree->Fill();
	    }
	    else{
	      hOpTJet   [ijet][jjet][Channel]->Fill(DijetpT);
	      hOMassJet [ijet][jjet][Channel]->Fill(DijetInvMass);  
	      hODRJet   [ijet][jjet][Channel]->Fill(DijetDeltaR);
	      hODPhiJet [ijet][jjet][Channel]->Fill(DijetDeltaPhi);	  


	      hpTOjj[Channel]     ->Fill(DijetpT); 
	      hInvMassOjj[Channel]->Fill(DijetInvMass); 
	      hDROjj[Channel]     ->Fill(DijetDeltaR);   
	      hDPhiOjj[Channel]   ->Fill(DijetDeltaPhi);   

	      // MVA Bkg TREE
	      b_pTjj   = DijetpT;
	      b_Mjj    = DijetInvMass;
	      b_DRjj   = DijetDeltaR;
	      b_DPhijj = DijetDeltaPhi;

	      MVABkgtree->Fill();
	    }
	  }// for(jjets)

	  if(coljet == 0) hJetPt[ijet][Channel]->Fill(jet_i.Pt());
	  else hOJetPt[ijet][Channel]->Fill(jet_i.Pt());
	}// for(ijet)
	
	
	if(coljet == 0){
	  hpTminjj[Channel]  ->Fill(minpTjj);   
	  hpTmaxjj[Channel]  ->Fill(maxpTjj);   
	  hInvMassjj[Channel]->Fill(Mjj); 
	  hDRminjj[Channel]  ->Fill(minDeltaRjj);   
	  hDRmaxjj[Channel]  ->Fill(maxDeltaRjj);   
	  hDPhiminjj[Channel]->Fill(minDeltaPhijj);   
	  hDPhimaxjj[Channel]->Fill(maxDeltaPhijj);   
	}
	else{
	  hOpTminjj[Channel]  ->Fill(minpTjj);   
	  hOpTmaxjj[Channel]  ->Fill(maxpTjj);   
	  hOInvMassjj[Channel]->Fill(Mjj); 
	  hODRminjj[Channel]  ->Fill(minDeltaRjj);   
	  hODRmaxjj[Channel]  ->Fill(maxDeltaRjj);   
	  hODPhiminjj[Channel]->Fill(minDeltaPhijj);   
	  hODPhimaxjj[Channel]->Fill(maxDeltaPhijj);   
	}
      }// for(coljet)
      hNJets[Channel]->Fill(NJets); 
    }// if(vWjets.size() == 0)
    
    //------------------------------------------------------------------------------------------------
    //------------------------------------------------------------------------------------------------
    //------------------------------------------------------------------------------------------------
    //------------------------------------------------------------------------------------------------

    /******************
      Scale Weights
    ******************/
    int scaleSysPar;
    if     (_syst && syst_varname.Contains("ScaleRnF_Up"))   scaleSysPar = 0; // muR=Nom,  muF=Up
    else if(_syst && syst_varname.Contains("ScaleRnF_Down")) scaleSysPar = 1; // muR=Nom,  muF=Down
    else if(_syst && syst_varname.Contains("ScaleRuF_Nom"))  scaleSysPar = 2; // muR=Up,   muF=Nom
    else if(_syst && syst_varname.Contains("ScaleRuF_Up"))   scaleSysPar = 3; // muR=Up,   muF=Up
    else if(_syst && syst_varname.Contains("ScaleRdF_Nom"))  scaleSysPar = 4; // muR=Down, muF=Nom
    else if(_syst && syst_varname.Contains("ScaleRdF_Down")) scaleSysPar = 5; // muR=Down, muF=Down

    float EvtStep = GENWeight;
    
    if (_syst && syst_varname.Contains("ScaleR"))
      EvtStep = EvtStep*(*ScaleWeight)[scaleSysPar];

     /******************
         Acceptace
    ******************/
    if(cone_NaddJets  > 1) fAccEvent_full_ttjj[Channel]+=EvtStep;
    if(cone_NaddbJets > 1) fAccEvent_full_ttbb[Channel]+=EvtStep;

    if(Lep_pT > 30 && abs(Lep_eta) < 2.4){
      if(cone_NbJets > 1 && cone_NJets > 5) fAccEvent_vis_ttjj[Channel]+=EvtStep;
      if(cone_NbJets > 3 && cone_NJets > 5) fAccEvent_vis_ttbb[Channel]+=EvtStep;    
    }
    

    /******************
        Histograms
    ******************/
  
  }//for(events)

  AccEvent_full_ttjj[0] = fAccEvent_full_ttjj[0];
  AccEvent_full_ttbb[0] = fAccEvent_full_ttbb[0];

  AccEvent_vis_ttjj[0] = fAccEvent_vis_ttjj[0];
  AccEvent_vis_ttbb[0] = fAccEvent_vis_ttbb[0];

  AccEvent_full_ttjj[1] = fAccEvent_full_ttjj[1];
  AccEvent_full_ttbb[1] = fAccEvent_full_ttbb[1];

  AccEvent_vis_ttjj[1] = fAccEvent_vis_ttjj[1];
  AccEvent_vis_ttbb[1] = fAccEvent_vis_ttbb[1];
  
  // Get elapsed time
  sw.Stop();
  std::cout << "==================================================] 100% " << std::endl;
  std::cout << "--- End of event loop: "; sw.Print();
  
  
  //Acceptance-Efficiency
  std::cout << "--------  Acceptace Full Ph-Sp  --------" << std::endl;
  std::cout << "Number of RAW-mu+Jets events:" << std::endl;
  std::cout << "ttjj Acceptance Full Ph-Sp: " << AccEvent_full_ttjj[0] << std::endl;
  std::cout << "ttbb Acceptance Full Ph-Sp: " << AccEvent_full_ttbb[0] << std::endl;
  std::cout << "ttbb/ttjj Full Ph-Sp: " << 1.0*AccEvent_full_ttbb[0]/AccEvent_full_ttjj[0] << std::endl;
  std::cout << "-----------------------------" << std::endl;
  std::cout << "Number of RAW-e+Jets events:" << std::endl;
  std::cout << "ttjj Acceptance Full Ph-Sp: " << AccEvent_full_ttjj[1] << std::endl;
  std::cout << "ttbb Acceptance: Full Ph-Sp: " << AccEvent_full_ttbb[1] << std::endl;
  std::cout << "ttbb/ttjj Full Ph-Sp: " << 1.0*AccEvent_full_ttbb[1]/AccEvent_full_ttjj[1] << std::endl;
  std::cout << "-----------------------------" << std::endl;
  std::cout << "Number of RAW-l+Jets events:" << std::endl;
  std::cout << "ttjj Acceptance Full Ph-Sp: " << AccEvent_full_ttjj[0] + AccEvent_full_ttjj[1] << std::endl;
  std::cout << "ttbb Acceptance Full Ph-Sp: " << AccEvent_full_ttbb[0] + AccEvent_full_ttbb[1] << std::endl;
  std::cout << "ttbb/ttjj Full Ph-Sp: " << 1.0*(AccEvent_full_ttbb[0] + AccEvent_full_ttbb[1])/(AccEvent_full_ttjj[0] + AccEvent_full_ttjj[1]) << std::endl;
  std::cout << "-----------------------------" << std::endl;
  std::cout << "-----------------------------" << std::endl;
  std::cout << "-----------------------------" << std::endl;
  std::cout << "--------  Acceptace Visible Ph-Sp  --------" << std::endl;
  std::cout << "Number of RAW-mu+Jets events:" << std::endl;
  std::cout << "ttjj Acceptance Visible Ph-Sp: " << AccEvent_vis_ttjj[0] << std::endl;
  std::cout << "ttbb Acceptance Visible Ph-Sp: " << AccEvent_vis_ttbb[0] << std::endl;
  std::cout << "ttbb/ttjj Visible Ph-Sp: " << 1.0*AccEvent_vis_ttbb[0]/AccEvent_vis_ttjj[0] << std::endl;
  std::cout << "-----------------------------" << std::endl;
  std::cout << "Number of RAW-e+Jets events:" << std::endl;
  std::cout << "ttjj Acceptance Visible Ph-Sp: " << AccEvent_vis_ttjj[1] << std::endl;
  std::cout << "ttbb Acceptance: Visible Ph-Sp: " << AccEvent_vis_ttbb[1] << std::endl;
  std::cout << "ttbb/ttjj Visible Ph-Sp: " << 1.0*AccEvent_vis_ttbb[1]/AccEvent_vis_ttjj[1] << std::endl;
  std::cout << "-----------------------------" << std::endl;
  std::cout << "Number of RAW-l+Jets events:" << std::endl;
  std::cout << "ttjj Acceptance Visible Ph-Sp: " << AccEvent_vis_ttjj[0] + AccEvent_vis_ttjj[1] << std::endl;
  std::cout << "ttbb Acceptance Visible Ph-Sp: " << AccEvent_vis_ttbb[0] + AccEvent_vis_ttbb[1] << std::endl;
  std::cout << "ttbb/ttjj Visible Ph-Sp: " << 1.0*(AccEvent_vis_ttbb[0] + AccEvent_vis_ttbb[1])/(AccEvent_vis_ttjj[0] + AccEvent_vis_ttjj[1]) << std::endl;
  std::cout << "-----------------------------" << std::endl;
  std::cout << "-----------------------------" << std::endl;
  std::cout << "-----------------------------" << std::endl;
  std::cout << "--------  ttbb Acceptace  --------" << std::endl;
  std::cout << "ttbb Acceptance (mu+Jets): " << 1.0*AccEvent_vis_ttbb[0]/AccEvent_full_ttbb[0] << std::endl;
  std::cout << "ttbb Acceptance (e+Jets): "  << 1.0*AccEvent_vis_ttbb[1]/AccEvent_full_ttbb[1] << std::endl;
  std::cout << "ttbb Acceptance (l+Jets): "  << 1.0*(AccEvent_vis_ttbb[0] + AccEvent_vis_ttbb[1])/(AccEvent_full_ttbb[0] + AccEvent_full_ttbb[1]) << std::endl;
  std::cout << "--------  ttjj Acceptace  --------" << std::endl;
  std::cout << "ttjj Acceptance (mu+Jets): " << 1.0*AccEvent_vis_ttjj[0]/AccEvent_full_ttjj[0] << std::endl;
  std::cout << "ttjj Acceptance (e+Jets): "  << 1.0*AccEvent_vis_ttjj[1]/AccEvent_full_ttjj[1] << std::endl;
  std::cout << "ttjj Acceptance (l+Jets): "  << 1.0*(AccEvent_vis_ttjj[0] + AccEvent_vis_ttjj[1])/(AccEvent_full_ttjj[0] + AccEvent_full_ttjj[1]) << std::endl;

  //Output Dir
  TString dirname="TopResults";   
  // make a dir if it does not exist!!
  struct stat st;
  if(stat(dirname,&st) != 0) system("mkdir " + dirname);
  

  // Sample name identification
  TString samplename="";
  bool matchsamplename=false;
  
  for(int i=0; i<fname.Sizeof(); i++){
    if (i>2){
      if (fname[i-3]=='-' && 
	  fname[i-2]=='1' && 
	  fname[i-1]=='_') matchsamplename=true;
    }
    if (matchsamplename) samplename.Append(fname[i]);
  }
    
  // --- Write histograms
  TString outfname=dirname + "/hAcc-" + hname + "_" + fname  + ".root";
  //TString outfname=dirname + "/hAcc-" + hname + "_" + fname + ttbar_id + ".root";
  TFile *target  = new TFile(outfname,"RECREATE" );  
  
  for(int i=0; i<2; i++){    
    hNJets[i]->Write();

    // pT for EACH jet 
    for(int ij=0; ij<2; ij++) hWJetPt[ij][i]->Write();
    for(int ij=0; ij<6; ij++) hJetPt[ij][i] ->Write();
    for(int ij=0; ij<4; ij++) hOJetPt[ij][i]->Write();
    
    
    // pT for EACH dijet 
    for(int ja=0; ja<5; ja++){
      for(int jb=ja+1; jb<6; jb++) hpTJet[ja][jb][i]  ->Write();
    }      
    for(int ja=0; ja<5; ja++){
      for(int jb=ja+1; jb<6; jb++) hMassJet[ja][jb][i]->Write();
    }      
    for(int ja=0; ja<5; ja++){
      for(int jb=ja+1; jb<6; jb++) hDRJet[ja][jb][i]  ->Write();
    }      
    for(int ja=0; ja<5; ja++){
      for(int jb=ja+1; jb<6; jb++) hDPhiJet[ja][jb][i]->Write();
    }      
    
    for(int ja=0; ja<3; ja++){
      for(int jb=ja+1; jb<4; jb++) hOpTJet[ja][jb][i]  ->Write();
    }      
    for(int ja=0; ja<3; ja++){
      for(int jb=ja+1; jb<4; jb++) hOMassJet[ja][jb][i]->Write();
    }      
    for(int ja=0; ja<3; ja++){
      for(int jb=ja+1; jb<4; jb++) hODRJet[ja][jb][i]  ->Write();
    }      
    for(int ja=0; ja<3; ja++){
      for(int jb=ja+1; jb<4; jb++) hODPhiJet[ja][jb][i]->Write();
    }      
    
    // MAX and MIN parameter per event
    hpTWjj[i]     ->Write(); 
    hInvMassWjj[i]->Write(); 
    hDRWjj[i]     ->Write();   
    hDPhiWjj[i]   ->Write();   
    
    hpTminjj[i]  ->Write();
    hpTmaxjj[i]  ->Write();
    hInvMassjj[i]->Write();
    hDRminjj[i]  ->Write();
    hDRmaxjj[i]  ->Write();
    hDPhiminjj[i]->Write();
    hDPhimaxjj[i]->Write();
    
    hpTOjj[i]     ->Write(); 
    hInvMassOjj[i]->Write(); 
    hDROjj[i]     ->Write();   
    hDPhiOjj[i]   ->Write();   

    hOpTminjj[i]  ->Write();
    hOpTmaxjj[i]  ->Write();
    hOInvMassjj[i]->Write();
    hODRminjj[i]  ->Write();
    hODRmaxjj[i]  ->Write();
    hODPhiminjj[i]->Write();
    hODPhimaxjj[i]->Write();
    
    hJetMatch[i] ->Write();
    
    h2DJetMjjID_I [i] ->Write();
    h2DJetMjjID_II[i] ->Write();
  }//for(i)

  MVASignaltree->Write();
  MVAtree      ->Write();
  MVABkgtree   ->Write();
  
  target->Close();

  std::cout << "File saved as " << outfname << std::endl;
  
}
void likelihoodrefs( TDirectory *lhdir ) {
   Bool_t newCanvas = kTRUE;
   
   const UInt_t maxCanvas = 200;
   TCanvas** c = new TCanvas*[maxCanvas];
   Int_t width  = 670;
   Int_t height = 380;

   // avoid duplicated printing
   std::vector<std::string> hasBeenUsed;
   const TString titName = lhdir->GetName();
   UInt_t ic = -1;   

   TIter next(lhdir->GetListOfKeys());
   TKey *key;
   while ((key = TMVAGlob::NextKey(next,"TH1"))) { // loop over all TH1
      TH1 *h = (TH1*)key->ReadObj();
      TH1F *b( 0 );
      TString hname( h->GetName() );

      // avoid duplicated plotting
      Bool_t found = kFALSE;
      for (UInt_t j = 0; j < hasBeenUsed.size(); j++) {
         if (hasBeenUsed[j] == hname.Data()) found = kTRUE;
      }
      if (!found) {

         // draw original plots
         if (hname.EndsWith("_sig_nice")) {

            if (newCanvas) {
               char cn[20];
               sprintf( cn, "cv%d_%s", ic+1, titName.Data() );
               ++ic;
               TString n = hname;	  
               c[ic] = new TCanvas( cn, Form( "%s reference for variable: %s", 
                                              titName.Data(),(n.ReplaceAll("_sig","")).Data() ), 
                                    ic*50+50, ic*20, width, height ); 
               c[ic]->Divide(2,1);
               newCanvas = kFALSE;
            }      

            // signal
            Int_t color = 4; 
            TPad * cPad = (TPad*)c[ic]->cd(1);
            TString plotname = hname;

            h->SetMaximum(h->GetMaximum()*1.3);
            h->SetMinimum( 0 );
            h->SetMarkerColor(color);
            h->SetMarkerSize( 0.7 );
            h->SetMarkerStyle( 24 );
            h->SetLineWidth(1);
            h->SetLineColor(color);
            color++;
            h->Draw("e1");
            Double_t hSscale = 1.0/(h->GetSumOfWeights()*h->GetBinWidth(1));

            TLegend *legS= new TLegend( cPad->GetLeftMargin(), 
                                        1-cPad->GetTopMargin()-.14, 
                                        cPad->GetLeftMargin()+.77, 
                                        1-cPad->GetTopMargin() );
            legS->SetBorderSize(1);
            legS->AddEntry(h,"Input data (signal)","p");

            // background
            TString bname( hname );	
            b = (TH1F*)lhdir->Get( bname.ReplaceAll("_sig","_bgd") );
            cPad = (TPad*)c[ic]->cd(2);
            color = 2;
            b->SetMaximum(b->GetMaximum()*1.3);
            b->SetMinimum( 0 );
            b->SetLineWidth(1);
            b->SetLineColor(color);
            b->SetMarkerColor(color);
            b->SetMarkerSize( 0.7 );
            b->SetMarkerStyle( 24 );
            b->Draw("e1");       
            Double_t hBscale = 1.0/(b->GetSumOfWeights()*b->GetBinWidth(1));
            TLegend *legB= new TLegend( cPad->GetLeftMargin(), 
                                        1-cPad->GetTopMargin()-.14, 
                                        cPad->GetLeftMargin()+.77, 
                                        1-cPad->GetTopMargin() );
            legB->SetBorderSize(1);
            legB->AddEntry(b,"Input data (backgr.)","p");

            // register
            hasBeenUsed.push_back( bname.Data() );

            // the PDFs --------------

            // check for splines
            h = 0;
            b = 0;
            TString pname = hname; pname.ReplaceAll("_nice","");            
            for (int i=0; i<= 5; i++) {
               TString hspline = pname + Form( "_smoothed_hist_from_spline%i", i );
               h = (TH1F*)lhdir->Get( hspline );
               if (h) {
                  b = (TH1F*)lhdir->Get( hspline.ReplaceAll("_sig","_bgd") );
                  break;
               }
            }

            // check for KDE
            if (h == 0 && b == 0) {
               TString hspline = pname +"_smoothed_hist_from_KDE";
               h = (TH1F*)lhdir->Get( hspline );
               if (h) {
                  b = (TH1F*)lhdir->Get( hspline.ReplaceAll("_sig","_bgd") );
               }
            }
               
            // found something ?
            if (h == 0 || b == 0) {
               cout << "--- likelihoodrefs.C: did not find spline for histogram: " << pname.Data() << endl;
            }
            else {
               
               Double_t pSscale = 1.0/(h->GetSumOfWeights()*h->GetBinWidth(1));
               h->Scale( pSscale/hSscale );
               color = 4;
               c[ic]->cd(1);
               h->SetLineWidth(2);
               h->SetLineColor(color);
               legS->AddEntry(h,"Estimated PDF (norm. signal)","l");
               h->Draw("histsame");
               legS->Draw();
	  
               Double_t pBscale = 1.0/(b->GetSumOfWeights()*b->GetBinWidth(1));
               b->Scale( pBscale/hBscale );
               color = 2;
               c[ic]->cd(2);
               b->SetLineColor(color);
               b->SetLineWidth(2);
               legB->AddEntry(b,"Estimated PDF (norm. backgr.)","l");
               b->Draw("histsame");

               // draw the legends
               legB->Draw();
	  
               hasBeenUsed.push_back( pname.Data() );
            }	  

            c[ic]->Update();

            // write to file
            TString fname = Form( "root_mva/plots/%s_refs_c%i", titName.Data(), ic+1 );
            TMVAGlob::imgconv( c[ic], fname );
            //	c[ic]->Update();

            newCanvas = kTRUE;
            hasBeenUsed.push_back( hname.Data() );
         }
      }
   }
}
/*
 * this script takes 2 TStrings as root filenames as a parameters
 * basic functionality:
 * loop through all directories (the mass bins) in the root file
 * -> create difference plots
 * -> create global plots
 * -> create 2D diff vs mass plots
 * -> etc...
 */
void plotGlobalWeightedEvts_Kpipi(TString input_filename, TString output_filename) {
  setupBookies();

  gROOT->SetStyle("Plain");
  gStyle->SetTitleFont(10*13+2,"xyz");
  gStyle->SetTitleSize(0.06, "xyz");
  gStyle->SetTitleOffset(1.3,"y");
  gStyle->SetTitleOffset(1.3,"z");
  gStyle->SetLabelFont(10*13+2,"xyz");
  gStyle->SetLabelSize(0.06,"xyz");
  gStyle->SetLabelOffset(0.009,"xyz");
  gStyle->SetPadBottomMargin(0.16);
  gStyle->SetPadTopMargin(0.16);
  gStyle->SetPadLeftMargin(0.16);
  gStyle->SetPadRightMargin(0.16);
  gStyle->SetOptTitle(0);
  gStyle->SetOptStat(0);
  gROOT->ForceStyle();
  gStyle->SetFrameFillColor(0);
  gStyle->SetFrameFillStyle(0);
  TGaxis::SetMaxDigits(3);
  //IsPhDStyle = true;

  int massbins =0;
  double mass= 0.0, massstart =1000.0, massend=0.0;
  std::map<std::string, std::pair<double, std::pair<double, double> > > diffbounds;

  TFile* infile = TFile::Open(input_filename, "READ");
  TFile* outfile = new TFile(output_filename, "RECREATE");
  outfile->mkdir("global");

  TList *dirlist = infile->GetListOfKeys();
  massbins = dirlist->GetSize();
  infile->cd();
  TIter diriter(dirlist);
  TDirectory *dir;

  std::cout<< "scanning directories and creating overview canvases..." <<std::endl;
  while ((dir = (TDirectory *)diriter())) {
    std::string dirname = dir->GetName();
    // check if directory is mass bin dir
    unsigned int pointpos = dirname.find(".");
    if(pointpos == 0 || pointpos == dirname.size()) continue;
    std::string masslow = dirname.substr(0, pointpos+1);
    std::string masshigh = dirname.substr(pointpos+1);
    double massstarttemp = atof(masslow.c_str())/1000;
    double massendtemp = atof(masshigh.c_str())/1000;
    if((int)(massendtemp - massstarttemp) != massbinwidth)
      massbinwidth = (int)(massendtemp - massstarttemp);
    mass = (massstarttemp + massendtemp)/2;
    if(massstart > massstarttemp) massstart = massstarttemp;
    if(massend < massendtemp) massend = massendtemp;

    outfile->cd();
    outfile->mkdir(dir->GetName());
    infile->cd(dir->GetName());

    // make list of MC Histograms
    TList mclist;
    TList *histlist = gDirectory->GetListOfKeys();
    TIter histiter(histlist);
    TObject *obj;
    while ((obj = histiter())) {
      TString s(obj->GetName());
      if(s.EndsWith("MC"))
        mclist.Add(obj);
      else if(s.Contains("MC_"))
        mclist.Add(obj);
    }
    make1DOverviewCanvas(infile, outfile, &mclist, dirname);
    histiter = TIter(&mclist);
    TH1D *diffhist, *mchist;
    while ((mchist = (TH1D*)histiter())) {
      // generate difference histograms
      std::string hnamemc(mchist->GetName());
      // create new string with MC exchanged for Diff
      std::string hnamediff(hnamemc);
      int pos = hnamemc.find("MC");
      hnamediff.erase(pos, 2);
      hnamediff.insert(pos, "Diff");

      infile->GetObject((std::string(dir->GetName())+"/"+hnamediff).c_str(), diffhist);

      if (diffhist) {
        // get diff min max values
        std::pair<double, std::pair<double, double> > p;

        bool change =false;
        double maxdiff = diffhist->GetMaximum();
        double maxdifftemp = diffhist->GetMinimum();
        if(abs(maxdifftemp) > maxdiff) maxdiff = maxdifftemp;

        double diffmintemp = diffhist->GetXaxis()->GetXmin();
        double diffmaxtemp = diffhist->GetXaxis()->GetXmax();
        std::map<std::string, std::pair<double, std::pair<double, double> > >::iterator iter = diffbounds.find(
            diffhist->GetName());
        if (iter != diffbounds.end()) {
          p.first = iter->second.first;
          p.second.first = iter->second.second.first;
          p.second.second = iter->second.second.second;

          if (iter->second.first < maxdiff) {
            change = true;
            p.first = maxdiff;
          }
          if (iter->second.second.first > diffmintemp) {
            change = true;
            p.second.first = diffmintemp;
          }
          if (iter->second.second.second < diffmaxtemp) {
            change = true;
            p.second.second = diffmaxtemp;
          }

          if (change) {
            diffbounds[diffhist->GetName()] = p;
          }
        }
        else {
          p.first = maxdiff;
          p.second.first = diffmintemp;
          p.second.second = diffmaxtemp;
          diffbounds.insert(std::pair<std::string, std::pair<double, std::pair<double, double> > >(diffhist->GetName(),
              p));
        }
      }
    }
    histiter = TIter(&mclist);
    TH2D *reldiffhist2d, *diffhist2d, *mchist2d, *datahist2d;
    while ((mchist2d = (TH2D*) histiter())) {
      // generate difference histograms
      std::string hnamemc(mchist2d->GetName());
      // create new string with MC exchanged for Diff
      std::string hnamediff(hnamemc);
      int pos = hnamemc.find("MC");
      hnamediff.erase(pos, 2);
      hnamediff.insert(pos, "Diff");
      // create new string with MC exchanged for RelDiff
      std::string hnamereldiff(hnamemc);
      hnamereldiff.erase(pos, 2);
      hnamereldiff.insert(pos, "RelDiff");
      // create new string with MC exchanged for Data
      std::string hnamedata(hnamemc);
      hnamedata.erase(pos, 2);
      hnamedata.insert(pos, "Data");

      infile->GetObject((std::string(dir->GetName()) + "/" + hnamereldiff).c_str(), reldiffhist2d);
      infile->GetObject((std::string(dir->GetName()) + "/" + hnamediff).c_str(), diffhist2d);
      infile->GetObject((std::string(dir->GetName()) + "/" + hnamedata).c_str(), datahist2d);
      infile->GetObject((std::string(dir->GetName()) + "/" + hnamemc).c_str(), mchist2d);

      outfile->cd(dir->GetName());
      make2DOverviewCanvas(mchist2d, datahist2d, diffhist2d, reldiffhist2d, mass);
    }
  }

  dirlist = infile->GetListOfKeys();
  infile->cd();
  diriter = TIter(dirlist);

  std::cout << "creating global histograms and 2D diff vs mass plots..." << std::endl;
  while ((dir = (TDirectory *) diriter())) {
    std::string dirname = dir->GetName();
    // check if directory is mass bin dir
    unsigned int pointpos = dirname.find(".");
    if (pointpos == 0 || pointpos == dirname.size())
      continue;

    infile->cd(dir->GetName());

    // make list of MC Histograms
    TList mclist;
    TList *histlist = gDirectory->GetListOfKeys();
    TIter histiter(histlist);
    TObject *obj;
    while ((obj = histiter())) {
      TString s(obj->GetName());
      if (s.EndsWith("MC"))
        mclist.Add(obj);
      else if (s.Contains("MC_"))
        mclist.Add(obj);
    }
    histiter = TIter(&mclist);
    TH1D *hist;
    TH1D *diffhist, *mchist, *datahist;
    while ((hist = (TH1D*) histiter())) {
      // generate difference histograms
      std::string hnamemc(hist->GetName());
      // create new string with MC exchanged for Diff
      std::string hname(hnamemc);
      int pos = hnamemc.find("MC");
      hname.erase(pos, 2);
      hname.insert(pos, "Diff");
      // create new string with MC exchanged for Data
      std::string hnamedata(hnamemc);
      hnamedata.erase(pos, 2);
      hnamedata.insert(pos, "Data");
      // create new string for MC Global Histogram
      std::string hnamemcglob(hnamemc);
      hnamemcglob.insert(pos + 2, "Global");
      // create new string for MC Global Histogram
      std::string hnamedataglob(hnamemc);
      hnamedataglob.erase(pos, 2);
      hnamedataglob.insert(pos, "DataGlobal");

      infile->GetObject((std::string(dir->GetName()) + "/" + hname + ";1").c_str(), diffhist);
      infile->GetObject((std::string(dir->GetName()) + "/" + hnamedata + ";1").c_str(), datahist);
      infile->GetObject((std::string(dir->GetName()) + "/" + hnamemc + ";1").c_str(), mchist);
      if (datahist) {
        // make global histograms in global folder
        outfile->cd("global");
        TH1D* hmcglob = (TH1D*) outfile->Get(std::string("global/"+hnamemcglob).c_str());
        if (hmcglob == NULL)
          hmcglob = new TH1D(hnamemcglob.c_str(), mchist->GetTitle(), mchist->GetNbinsX(),
              mchist->GetXaxis()->GetXmin(), mchist->GetXaxis()->GetXmax());
        hmcglob->Add(mchist);
        TH1D* hdataglob = (TH1D*) outfile->Get(std::string("global/"+hnamedataglob).c_str());
        if (hdataglob == NULL)
          hdataglob = new TH1D(hnamedataglob.c_str(), datahist->GetTitle(), datahist->GetNbinsX(),
              datahist->GetXaxis()->GetXmin(), datahist->GetXaxis()->GetXmax());
        hdataglob->Add(datahist);

        // make diff vs. mass plots
        fillDiffvsMassPlot(diffhist, dir->GetName(), massbins, massstart, massend, diffbounds, outfile);
      }
    }
    histiter = TIter(&mclist);
    TH2D *mchist2d, *datahist2d;
    while ((mchist2d = (TH2D*) histiter())) {
      // generate difference histograms
      std::string hnamemc(mchist2d->GetName());
      // create new string with MC exchanged for Diff
      std::string hnamediff(hnamemc);
      int pos = hnamemc.find("MC");
      hnamediff.erase(pos, 2);
      hnamediff.insert(pos, "Diff");
      // create new string with MC exchanged for Data
      std::string hnamedata(hnamemc);
      hnamedata.erase(pos, 2);
      hnamedata.insert(pos, "Data");
      // create new string for MC Global Histogram
      std::string hnamemcglob(hnamemc);
      hnamemcglob.insert(pos + 2, "Global");
      // create new string for MC Global Histogram
      std::string hnamedataglob(hnamemc);
      hnamedataglob.erase(pos, 2);
      hnamedataglob.insert(pos, "DataGlobal");

      infile->GetObject((std::string(dir->GetName()) + "/" + hnamedata + ";1").c_str(), datahist2d);
      infile->GetObject((std::string(dir->GetName()) + "/" + hnamemc + ";1").c_str(), mchist2d);
      if (datahist2d) {
        // make global histograms in global folder
        outfile->cd("global");
        TH2D* hmcglob = (TH2D*) outfile->Get(std::string("global/" + hnamemcglob).c_str());
        if (hmcglob == NULL) {
          hmcglob = new TH2D(hnamemcglob.c_str(), mchist2d->GetTitle(), mchist->GetNbinsX(),
              mchist2d->GetXaxis()->GetXmin(), mchist2d->GetXaxis()->GetXmax(), mchist2d->GetNbinsY(),
              mchist2d->GetYaxis()->GetXmin(), mchist2d->GetYaxis()->GetXmax());
          hmcglob->SetXTitle(mchist2d->GetXaxis()->GetTitle());
          hmcglob->SetYTitle(mchist2d->GetYaxis()->GetTitle());
        }
        hmcglob->Add(mchist2d);
        TH2D* hdataglob = (TH2D*) outfile->Get(std::string("global/" + hnamedataglob).c_str());
        if (hdataglob == NULL) {
          hdataglob = new TH2D(hnamedataglob.c_str(), datahist2d->GetTitle(), datahist2d->GetNbinsX(),
              datahist2d->GetXaxis()->GetXmin(), datahist2d->GetXaxis()->GetXmax(), datahist2d->GetNbinsY(),
              datahist2d->GetYaxis()->GetXmin(), datahist2d->GetYaxis()->GetXmax());
          hdataglob->SetXTitle(datahist2d->GetXaxis()->GetTitle());
          hdataglob->SetYTitle(datahist2d->GetYaxis()->GetTitle());
        }
        hdataglob->Add(datahist2d);
      }
    }
  }

  makeBookies();

  std::cout<< "saving to disk..." <<std::endl;
  outfile->Write();
  std::cout<< "done!" <<std::endl;

  /*// ok lets make a canvas and plug some plots into it -> add to booky
  TCanvas* c = new TCanvas("KineValidate" + massbin, "Weighted Events", 10, 10, 600, 800);
  c->Divide(4, 4);

  // first column contains neutral isobar histograms
  c->cd(1);

  double totMC = GJHB_neutral_isobar.isobar_mass[0]->Integral();
  double totDATA = GJHB_neutral_isobar.isobar_mass[1]->Integral();

  if (totMC != 0)
    GJHB_neutral_isobar.isobar_mass[0]->Scale(totDATA / totMC);
  GJHB_neutral_isobar.isobar_mass[0]->SetLineColor(kRed);
  GJHB_neutral_isobar.isobar_mass[0]->SetFillColor(kRed);
  GJHB_neutral_isobar.isobar_mass[0]->Draw("E4");

  TH1D* hDiffMIsobar = new TH1D(*GJHB_neutral_isobar.isobar_mass[0]);
  hDiffMIsobar->Add(GJHB_neutral_isobar.isobar_mass[1], -1.);
  GJHB_neutral_isobar.isobar_mass[1]->Draw("same");
  hDiffMIsobar->SetLineColor(kOrange - 3);
  hDiffMIsobar->Draw("same");

  GJHB_neutral_isobar.isobar_mass[0]->GetYaxis()->SetRangeUser(hDiffMIsobar->GetMinimum() * 1.5,
      GJHB_neutral_isobar.isobar_mass[0]->GetMaximum() * 1.2);
  gPad->Update();

  c->cd(5);
  totMC = GJHB_neutral_isobar.costheta_GJF[0]->Integral();
  totDATA = GJHB_neutral_isobar.costheta_GJF[1]->Integral();
  if (totMC != 0)
    GJHB_neutral_isobar.costheta_GJF[0]->Scale(totDATA / totMC);
  GJHB_neutral_isobar.costheta_GJF[0]->SetLineColor(kRed);
  GJHB_neutral_isobar.costheta_GJF[0]->SetFillColor(kRed);
  GJHB_neutral_isobar.costheta_GJF[0]->Draw("E4");

  GJHB_neutral_isobar.costheta_GJF[1]->Draw("same E");

  totMC = GJHB_neutral_isobar.costheta_GJF_MC_raw->Integral();
  GJHB_neutral_isobar.costheta_GJF_MC_raw->Scale(totDATA / totMC);
  GJHB_neutral_isobar.costheta_GJF_MC_raw->Draw("same");

  GJHB_neutral_isobar.costheta_GJF[0]->GetYaxis()->SetRangeUser(0, GJHB_neutral_isobar.costheta_GJF[0]->GetMaximum() * 1.5);
  gPad->Update();

  c->cd(9);
  totMC = GJHB_neutral_isobar.phi_GJF[0]->Integral();
  totDATA = GJHB_neutral_isobar.phi_GJF[1]->Integral();
  GJHB_neutral_isobar.phi_GJF[0]->Sumw2();
  if (totMC != 0)
    GJHB_neutral_isobar.phi_GJF[0]->Scale(totDATA / totMC);
  GJHB_neutral_isobar.phi_GJF[0]->SetLineColor(kRed);
  GJHB_neutral_isobar.phi_GJF[0]->SetFillColor(kRed);
  GJHB_neutral_isobar.phi_GJF[0]->Draw("E4");

  GJHB_neutral_isobar.phi_GJF[1]->Draw("same E");
  GJHB_neutral_isobar.phi_GJF[0]->GetYaxis()->SetRangeUser(0, GJHB_neutral_isobar.phi_GJF[0]->GetMaximum() * 1.5);
  gPad->Update();

  c->cd(13);
  totMC = HHB_neutral_isobar.costheta_HF[0]->Integral();
  totDATA = HHB_neutral_isobar.costheta_HF[1]->Integral();
  HHB_neutral_isobar.costheta_HF[0]->Sumw2();
  if (totMC != 0)
    HHB_neutral_isobar.costheta_HF[0]->Scale(totDATA / totMC);
  HHB_neutral_isobar.costheta_HF[0]->SetLineColor(kRed);
  HHB_neutral_isobar.costheta_HF[0]->SetFillColor(kRed);
  HHB_neutral_isobar.costheta_HF[0]->Draw("E4");

  HHB_neutral_isobar.costheta_HF[1]->Draw("same E");
  HHB_neutral_isobar.costheta_HF[0]->GetYaxis()->SetRangeUser(0,
      HHB_neutral_isobar.costheta_HF[0]->GetMaximum() * 1.5);
  gPad->Update();

  c->cd(15);
  totMC = HHB_neutral_isobar.phi_HF[0]->Integral();
  totDATA = HHB_neutral_isobar.phi_HF[1]->Integral();
  HHB_neutral_isobar.phi_HF[0]->Sumw2();
  if (totMC != 0)
    HHB_neutral_isobar.phi_HF[0]->Scale(totDATA / totMC);
  HHB_neutral_isobar.phi_HF[0]->SetLineColor(kRed);
  HHB_neutral_isobar.phi_HF[0]->SetFillColor(kRed);
  HHB_neutral_isobar.phi_HF[0]->Draw("E4");

  HHB_neutral_isobar.phi_HF[1]->Draw("same E");
  HHB_neutral_isobar.phi_HF[0]->GetYaxis()->SetRangeUser(0,
      HHB_neutral_isobar.phi_HF[0]->GetMaximum() * 1.5);
  gPad->Update();

  c->cd(2);

  totMC = GJHB_charged_isobar.isobar_mass[0]->Integral();
  totDATA = GJHB_charged_isobar.isobar_mass[1]->Integral();

  if (totMC != 0)
    GJHB_charged_isobar.isobar_mass[0]->Scale(totDATA / totMC);
  GJHB_charged_isobar.isobar_mass[0]->SetLineColor(kRed);
  GJHB_charged_isobar.isobar_mass[0]->SetFillColor(kRed);
  GJHB_charged_isobar.isobar_mass[0]->Draw("E4");

  TH1D* hDiffMIsobar2 = new TH1D(*GJHB_charged_isobar.isobar_mass[0]);
  hDiffMIsobar2->Add(GJHB_charged_isobar.isobar_mass[1], -1.);
  GJHB_charged_isobar.isobar_mass[1]->Draw("same");
  hDiffMIsobar2->SetLineColor(kOrange - 3);
  hDiffMIsobar2->Draw("same");

  GJHB_charged_isobar.isobar_mass[0]->GetYaxis()->SetRangeUser(hDiffMIsobar->GetMinimum() * 1.5,
      GJHB_charged_isobar.isobar_mass[0]->GetMaximum() * 1.2);
  gPad->Update();

  c->cd(6);
  totMC = GJHB_charged_isobar.costheta_GJF[0]->Integral();
  totDATA = GJHB_charged_isobar.costheta_GJF[1]->Integral();
  //hGJ[0]->Sumw2();
  if (totMC != 0)
    GJHB_charged_isobar.costheta_GJF[0]->Scale(totDATA / totMC);
  GJHB_charged_isobar.costheta_GJF[0]->SetLineColor(kRed);
  GJHB_charged_isobar.costheta_GJF[0]->SetFillColor(kRed);
  GJHB_charged_isobar.costheta_GJF[0]->Draw("E4");

  GJHB_charged_isobar.costheta_GJF[1]->Draw("same E");

  totMC = GJHB_charged_isobar.costheta_GJF_MC_raw->Integral();
  GJHB_charged_isobar.costheta_GJF_MC_raw->Scale(totDATA / totMC);
  GJHB_charged_isobar.costheta_GJF_MC_raw->Draw("same");

  GJHB_charged_isobar.costheta_GJF[0]->GetYaxis()->SetRangeUser(0, GJHB_charged_isobar.costheta_GJF[0]->GetMaximum() * 1.5);
  gPad->Update();

  c->cd(10);
  totMC = GJHB_charged_isobar.phi_GJF[0]->Integral();
  totDATA = GJHB_charged_isobar.phi_GJF[1]->Integral();
  GJHB_charged_isobar.phi_GJF[0]->Sumw2();
  if (totMC != 0)
    GJHB_charged_isobar.phi_GJF[0]->Scale(totDATA / totMC);
  GJHB_charged_isobar.phi_GJF[0]->SetLineColor(kRed);
  GJHB_charged_isobar.phi_GJF[0]->SetFillColor(kRed);
  GJHB_charged_isobar.phi_GJF[0]->Draw("E4");

  GJHB_charged_isobar.phi_GJF[1]->Draw("same E");
  GJHB_charged_isobar.phi_GJF[0]->GetYaxis()->SetRangeUser(0, GJHB_charged_isobar.phi_GJF[0]->GetMaximum() * 1.5);
  gPad->Update();

  c->cd(14);
  totMC = HHB_charged_isobar.costheta_HF[0]->Integral();
  totDATA = HHB_charged_isobar.costheta_HF[1]->Integral();
  HHB_charged_isobar.costheta_HF[0]->Sumw2();
  if (totMC != 0)
    HHB_charged_isobar.costheta_HF[0]->Scale(totDATA / totMC);
  HHB_charged_isobar.costheta_HF[0]->SetLineColor(kRed);
  HHB_charged_isobar.costheta_HF[0]->SetFillColor(kRed);
  HHB_charged_isobar.costheta_HF[0]->Draw("E4");

  HHB_charged_isobar.costheta_HF[1]->Draw("same E");
  HHB_charged_isobar.costheta_HF[0]->GetYaxis()->SetRangeUser(0,
      HHB_charged_isobar.costheta_HF[0]->GetMaximum() * 1.5);
  gPad->Update();

  c->cd(16);
  totMC = HHB_charged_isobar.phi_HF[0]->Integral();
  totDATA = HHB_charged_isobar.phi_HF[1]->Integral();
  HHB_charged_isobar.phi_HF[0]->Sumw2();
  if (totMC != 0)
    HHB_charged_isobar.phi_HF[0]->Scale(totDATA / totMC);
  HHB_charged_isobar.phi_HF[0]->SetLineColor(kRed);
  HHB_charged_isobar.phi_HF[0]->SetFillColor(kRed);
  HHB_charged_isobar.phi_HF[0]->Draw("E4");

  HHB_charged_isobar.phi_HF[1]->Draw("same E");
  HHB_charged_isobar.phi_HF[0]->GetYaxis()->SetRangeUser(0,
      HHB_charged_isobar.phi_HF[0]->GetMaximum() * 1.5);
  gPad->Update();

  // add global diagrams

  c->cd(1);
  TLatex* Label = new TLatex();
  Label->PaintLatex(2, GJHB_neutral_isobar.isobar_mass[0]->GetMaximum() * 0.8, 0, 0.1, massbin.Data());

  c->Update();

  TList* Hlist = gDirectory->GetList();
  Hlist->Remove(mctr);
  Hlist->Remove(datatr);
  //Hlist->Remove("hWeights");

  TFile* outfile = TFile::Open(outfilename, "UPDATE");
  TString psFileName = outfilename;
  psFileName.ReplaceAll(".root", massbin);
  psFileName.Append(".ps");

  if (totMC != 0) {
    // get mass-integrated plots (or create them if not there)

    // neutral isobar
    TH1D* hMIsobarMCGlob = (TH1D*) outfile->Get("hMIsobarMCGlob");
    if (hMIsobarMCGlob == NULL)
      hMIsobarMCGlob = new TH1D("hMIsobarMCGlob", "2#pi neutral Isobar Mass (MC)", nbninsm, 0.2, 2.5);
    hMIsobarMCGlob->Add(GJHB_neutral_isobar.isobar_mass[0]);
    hMIsobarMCGlob->Write();
    TH1D* hMIsobarDataGlob = (TH1D*) outfile->Get("hMIsobarDataGlob");
    if (hMIsobarDataGlob == NULL)
      hMIsobarDataGlob = new TH1D("hMIsobarDataGlob", "2#pi neutral Isobar Mass (DATA)", nbninsm, 0.2, 2.5);
    hMIsobarDataGlob->Add(GJHB_neutral_isobar.isobar_mass[1]);
    hMIsobarDataGlob->Write();

    TH1D* hGJMCGlob = (TH1D*) outfile->Get("hGJMCGlob");
    if (hGJMCGlob == NULL)
      hGJMCGlob = new TH1D("hGJMCGlob", "Gottfried-Jackson Theta (MC)", nbinsang, -1, 1);
    hGJMCGlob->Add(GJHB_neutral_isobar.costheta_GJF[0]);
    hGJMCGlob->Write();
    TH1D* hGJDataGlob = (TH1D*) outfile->Get("hGJDataGlob");
    if (hGJDataGlob == NULL)
      hGJDataGlob = new TH1D("hGJDataGlob", "Gottfried-Jackson Theta (Data)", nbinsang, -1, 1);
    hGJDataGlob->Add(GJHB_neutral_isobar.costheta_GJF[1]);
    hGJDataGlob->Write();

    TH1D* hTYMCGlob = (TH1D*) outfile->Get("hTYMCGlob");
    if (hTYMCGlob == NULL)
      hTYMCGlob = new TH1D("hTYMCGlob", "Treiman-Yang Phi (MC)", nbinsang, -TMath::Pi(),TMath::Pi());
    hTYMCGlob->Add(GJHB_neutral_isobar.phi_GJF[0]);
    hTYMCGlob->Write();
    TH1D* hTYDataGlob = (TH1D*) outfile->Get("hTYDataGlob");
    if (hTYDataGlob == NULL)
      hTYDataGlob = new TH1D("hTYDataGlob", "Treiman-Yang Phi (Data)", nbinsang, -TMath::Pi(),TMath::Pi());
    hTYDataGlob->Add(GJHB_neutral_isobar.phi_GJF[1]);
    hTYDataGlob->Write();

    c->cd(3);
    hMIsobarMCGlob->SetLineColor(kRed);
    hMIsobarMCGlob->SetFillColor(kRed);
    hMIsobarMCGlob->Draw("E4");
    hMIsobarDataGlob->Draw("E SAME");

    c->cd(7);
    hGJMCGlob->SetLineColor(kRed);
    hGJMCGlob->SetFillColor(kRed);
    hGJMCGlob->Draw("E4");
    hGJDataGlob->Draw("E SAME");

    c->cd(11);
    hTYMCGlob->SetLineColor(kRed);
    hTYMCGlob->SetFillColor(kRed);
    hTYMCGlob->Draw("E4");
    hTYDataGlob->Draw("E SAME");


    // charged isobar
    TH1D* hMIsobarMCGlob2 = (TH1D*) outfile->Get("hMIsobarMCGlob2");
    if (hMIsobarMCGlob2 == NULL)
      hMIsobarMCGlob2 = new TH1D("hMIsobarMCGlob2", "2#pi charged Isobar Mass (MC)", nbninsm, 0.2,
          2.5);
    hMIsobarMCGlob2->Add(GJHB_charged_isobar.isobar_mass[0]);
    hMIsobarMCGlob2->Write();
    TH1D* hMIsobarDataGlob2 = (TH1D*) outfile->Get("hMIsobarDataGlob2");
    if (hMIsobarDataGlob2 == NULL)
      hMIsobarDataGlob2 = new TH1D("hMIsobarDataGlob2", "2#pi charged Isobar mass (DATA)", nbninsm,
          0.2, 2.5);
    hMIsobarDataGlob2->Add(GJHB_charged_isobar.isobar_mass[1]);
    hMIsobarDataGlob2->Write();

    TH1D* hGJMCGlob2 = (TH1D*) outfile->Get("hGJMCGlob2");
    if (hGJMCGlob2 == NULL)
      hGJMCGlob2 = new TH1D("hGJMCGlob2", "Gottfried-Jackson Theta (MC)", nbinsang, -1, 1);
    hGJMCGlob2->Add(GJHB_charged_isobar.costheta_GJF[0]);
    hGJMCGlob2->Write();
    TH1D* hGJDataGlob2 = (TH1D*) outfile->Get("hGJDataGlob2");
    if (hGJDataGlob2 == NULL)
      hGJDataGlob2 = new TH1D("hGJDataGlob2", "Gottfried-Jackson Theta (Data)", nbinsang, -1, 1);
    hGJDataGlob2->Add(GJHB_charged_isobar.costheta_GJF[1]);
    hGJDataGlob2->Write();

    TH1D* hTYMCGlob2 = (TH1D*) outfile->Get("hTYMCGlob2");
    if (hTYMCGlob2 == NULL)
      hTYMCGlob2 = new TH1D("hTYMCGlob2", "Treiman-Yang Phi (MC)", nbinsang, -TMath::Pi(),TMath::Pi());
    hTYMCGlob2->Add(GJHB_charged_isobar.phi_GJF[0]);
    hTYMCGlob2->Write();
    TH1D* hTYDataGlob2 = (TH1D*) outfile->Get("hTYDataGlob2");
    if (hTYDataGlob2 == NULL)
      hTYDataGlob2 = new TH1D("hTYDataGlob2", "Treiman-Yang Phi (Data)", nbinsang, -TMath::Pi(),TMath::Pi());
    hTYDataGlob2->Add(GJHB_charged_isobar.phi_GJF[1]);
    hTYDataGlob2->Write();

    c->cd(4);
    hMIsobarMCGlob2->SetLineColor(kRed);
    hMIsobarMCGlob2->SetFillColor(kRed);
    hMIsobarMCGlob2->Draw("E4");
    hMIsobarDataGlob2->Draw("E SAME");

    c->cd(8);
    hGJMCGlob2->SetLineColor(kRed);
    hGJMCGlob2->SetFillColor(kRed);
    hGJMCGlob2->Draw("E4");
    hGJDataGlob2->Draw("E SAME");

    c->cd(12);
    hTYMCGlob2->SetLineColor(kRed);
    hTYMCGlob2->SetFillColor(kRed);
    hTYMCGlob2->Draw("E4");
    hTYDataGlob2->Draw("E SAME");
  }

  c->Write();
  TCanvas dummyCanv("dummy", "dummy");
  c->Print((psFileName));*/
}
Ejemplo n.º 11
0
int main(int argc, const char* argv[]){

  gSystem->Load("libTree");

  bool   _syst      = false;
  bool	 _tr_unc    = false;
  bool	 _idiso_unc = false;
  const char * _output   = 0;
  const char * _input    = 0;
  const char * _dir      = "/home/brochero/ttbar/TopTrees_CATuples/";
  const char * _tr       = 0;
  const char * _idiso    = 0;

  // Arguments used
  //std::set<int> usedargs;
  //Parsing input options
  if(argc == 1){
    display_usage();
    return -1;
  }

  else{
      //Argumet 1 must be a valid input fileName
      for (int i = 1; i < argc; i++){
	if( strcmp(argv[i],"-i") == 0 ){
	  _input = argv[i+1];
	  i++;
	}
	if( strcmp(argv[i],"-d") == 0 ){
	  _dir = argv[i+1];
	  i++;
	}
	if( strcmp(argv[i],"-o") == 0 ){
	  _output= argv[i+1];
	  i++;
	}
	if( strcmp(argv[i],"-h") == 0 ||
	    strcmp(argv[i],"--help") == 0 ){
	  display_usage();
	  return 0;
	}
      }
  }//else
  if( _input ==0 ){
    std::cerr << "\033[1;31mskimfile ERROR:\033[1;m The '-i' option is mandatory!"
	      << std::endl;
    display_usage();
    return -1;
  }
  
  // reassigning
  TString fname(_input);
  TString hname(_output);
  TString fdir(_dir);

  
  TChain theTree("ttbarSingleLepton/AnalysisTree"); 
  
  std::cout << "-----------------------------------------" << std::endl;
  std::cout << "-----------------------------------------" << std::endl;
  std::cout << "Signal: ";
  std::cout << fname + ".root" << std::endl;
  
  theTree.Add(fdir + fname + ".root");

  
  int Event,Channel,PV,GoodPV;
  float PUWeight; // Temporal
  float MET,MET_Phi;

  float Lep_px, Lep_py, Lep_pz, Lep_E;
  std::vector<float> *Jet_px=0, *Jet_py=0, *Jet_pz=0, *Jet_E=0;
  std::vector<bool>  *Jet_LooseID=0;
  std::vector<float> *Jet_CSV=0;
  
  theTree.SetBranchAddress( "event",    &Event );
  theTree.SetBranchAddress( "PUWeight", &PUWeight );
  theTree.SetBranchAddress( "channel",  &Channel );

  theTree.SetBranchAddress( "PV",     &PV );
  theTree.SetBranchAddress( "GoodPV",  &GoodPV );

  theTree.SetBranchAddress( "MET",     &MET );
  theTree.SetBranchAddress( "MET_phi", &MET_Phi );

  theTree.SetBranchAddress( "lepton_px", &Lep_px );
  theTree.SetBranchAddress( "lepton_py", &Lep_py );
  theTree.SetBranchAddress( "lepton_pz", &Lep_pz );
  theTree.SetBranchAddress( "lepton_E",  &Lep_E );

  theTree.SetBranchAddress( "jet_px", &Jet_px );
  theTree.SetBranchAddress( "jet_py", &Jet_py );
  theTree.SetBranchAddress( "jet_pz", &Jet_pz );
  theTree.SetBranchAddress( "jet_E",  &Jet_E );
  theTree.SetBranchAddress( "jet_LooseID",  &Jet_LooseID );

  theTree.SetBranchAddress( "jet_CSV",  &Jet_CSV );

  
  /*********************************
             Histograms
  **********************************/
  
  TH1F *hPV[4][2];
  TH1F *hMET[4][2],*hMET_Phi[4][2];
  TH1F *hLepPt[4][2],*hLepEta[4][2],*hLepPhi[4][2];
  TH1F *hNJets[4][2],*hHT[4][2],*hNBtagJets[4][2];
  TH1F *CSV[4][4][2];

  TString namech[2];
  namech[0]="mujets";
  namech[1]="ejets";

  TString namecut[4];
  namecut[0]="lepton";
  namecut[1]="4Jets";
  namecut[2]="MET";
  namecut[3]="2btag";

  TString titlenamech[2];
  titlenamech[0]="#mu+Jets";
  titlenamech[1]="e+Jets";
  
  for(int j=0; j<4; j++){   // Cut
    for(int i=0; i<2; i++){ // Channel
      hPV[j][i]         = new TH1F("hPV_"+namech[i]+"_"+namecut[j],"PV Distribution  " + titlenamech[i],30,0,30);
      
      hMET[j][i]        = new TH1F("hMET_"+namech[i]+"_"+namecut[j],"#slash{E}_{T} " + titlenamech[i],40,0,200);
      hMET_Phi[j][i]    = new TH1F("hMET_Phi_"+namech[i]+"_"+namecut[j],"#Phi_{#slash{E}_{T}} " + titlenamech[i],160,-4,4);
      
      hLepPt [j][i]    = new TH1F("hLepPt_"  +namech[i] + "_" + namecut[j], "Lepton p_{T} " + titlenamech[i],50,0.0,250.0);
      hLepEta[j][i]    = new TH1F("hLepEta_" +namech[i] + "_" + namecut[j], "#eta_{Lep} " + titlenamech[i],50,-2.5,2.5);
      hLepPhi[j][i]    = new TH1F("hLepPhi_" +namech[i] + "_" + namecut[j], "#phi_{Lep} " + titlenamech[i],100,-5,5);
      
      hNJets[j][i]      = new TH1F("hNJets_"+namech[i]+"_"+namecut[j],"Jet multiplicity " + titlenamech[i],9,-0.5,8.5);

      hNBtagJets[j][i]  = new TH1F("hNBtagJets_"+namech[i]+"_"+namecut[j],"b-tag jet multiplicity " + titlenamech[i],9,-0.5,8.5);

      hHT[j][i]         = new TH1F("hHT_"+namech[i]+"_"+namecut[j],"H_{T} " + titlenamech[i],300,0,600);

      TString jetn[4];
      jetn[0]= "Jet0"; 
      jetn[1]= "Jet1"; 
      jetn[2]= "Jet2"; 
      jetn[3]= "Jet3"; 

      for(int ij=0; ij<4; ij++){
	CSV[ij][j][i]         = new TH1F("hCSV_" + jetn[ij] + "_" + namech[i] + "_" + namecut[j],"CSV " + jetn[ij] + " " + titlenamech[i],80,0,1);
      }
    }//for(i)
  }//for(j)


  TStopwatch sw;
  sw.Start(kTRUE);

  // Number de events for <pT Reweight>
  //          [Cut][Channel]
  float SF_pTweight[4][2]={0,0,0,0,
			   0,0,0,0};

  // Number de events for acceptance
  //          [Cut][Channel]
  int AccEvent[4][2]={0,0,0,0,
		      0,0,0,0};
  // Number de events for acceptance
  //          [Cut][Channel]
  float EffEvent[4][2]={0.0,0.0,0.0,0.0,
			0.0,0.0,0.0,0.0};
  


  std::cout << "--- Processing: " << theTree.GetEntries() << " events" << std::endl;
  for (Long64_t ievt=0; ievt<theTree.GetEntries();ievt++) {
     
    theTree.GetEntry( ievt ); 
    //////////////////////////////////////////////////////
    int step = theTree.GetEntries()/50;
    if (ievt%(step) == 0){
      float progress=(ievt)/(theTree.GetEntries()*1.0);
      int barWidth = 50;
      
      std::cout << "[";
      int pos = barWidth * progress;
    
      for (int i = 0; i < barWidth; ++i) {
      	if (i < pos) std::cout << "=";
      	else if (i == pos) std::cout << ">";
      	else std::cout << " ";
      }
      
      std::cout << "] " << int(progress * 100.0) << " %\r";
      std::cout.flush();
    }
    ////////////////////////////////////////////////////////

    int NJets,NBtagJets;
    
    TLorentzVector Lep;
    std::vector<TLorentzVector> Jet;
    std::vector<TLorentzVector> bJet;
         
    Lep.SetPxPyPzE(Lep_px,Lep_py,Lep_pz,Lep_E);
    if(Lep.Pt()<30) continue; // Lep pT >30GeV

    // Jets 
    NJets     = 0;
    NBtagJets = 0;

    for(int ijet=0; ijet < Jet_px->size(); ijet++){

      TLorentzVector jet;
      jet.SetPxPyPzE((*Jet_px)[ijet],(*Jet_py)[ijet],(*Jet_pz)[ijet],(*Jet_E)[ijet]);
      
      if(jet.Pt()>25 &&         // Jet pT > 25GeV
	 !(*Jet_LooseID)[ijet]){ // Loose ID
	
	Jet.push_back(jet);
	NJets++; // Number of jets
	
	if((*Jet_CSV)[ijet] > 0.814){ // CSVM. Luca b-tagging code to apply SF?
	  bJet.push_back(jet);
	  NBtagJets++; // Number of b-tagged jets
	} // if(b-tag)
      } // if(Jet_pT)
    }// for(jets)

          
    /***************************
            Selection
    ***************************/
    int                                    cut=0; // Single Lepton
    if(NJets>3)                            cut=1; // + 4Jets 
    if(NJets>3 && MET>30.0)                cut=2; // + MET
    if(NJets>3 && MET>30.0 && NBtagJets>1) cut=3; // + 2 Btag


   // /*******************
   //    Fill Histograms
   //  ******************/
     
    float PUWeight_event=PUWeight;

    for(int icut=0; icut<cut+1; icut++){

      // PUWeight reset for each cut
      PUWeight=PUWeight_event;
  
      /************************************************************
       Scale Factors (Luminosity)
      *************************************************************/
      // Number of events from https://cmsweb.cern.ch/das
      // Cross Sections at 13 TeV:
      // - ttbar from https://twiki.cern.ch/twiki/bin/view/Sandbox/FullNNLOcrossSections 
      //              https://twiki.cern.ch/twiki/bin/view/LHCPhysics/TtbarNNLO
      // - backgrounds from https://twiki.cern.ch/twiki/bin/view/CMS/StandardModelCrossSectionsat13TeV

      int Lumi=1000; //pb
      // PUWeight = PUWeight*Lumi*(1.0/N_Gen_events)*(Xsec)*(Br)
      if(fname.Contains("QCD"))   PUWeight = PUWeight * Lumi * (1.0/4777926.0)  * (866600000.0) * (0.00044);     // [pb] (cross section) * (Filter Eff)
      if(fname.Contains("ZJets")) PUWeight = PUWeight * Lumi * (1.0/2829164.0)  * (3591.6) * (0.03*3);           // [pb]
      if(fname.Contains("WJets")) PUWeight = PUWeight * Lumi * (1.0/10017930)   * (61526.7) * (0.1*3);           // [pb]
      if(fname.Contains("tW"))    PUWeight = PUWeight * Lumi * (1.0/986100.0)   * (35.6);                        // [pb]
      if(fname.Contains("tbarW")) PUWeight = PUWeight * Lumi * (1.0/971800.0)   * (35.6);                        // [pb]
      if(fname.Contains("ttbar")) PUWeight = PUWeight * Lumi * (1.0/25446993.0) * (827.1) * (0.108*3) * (0.67);  // [pb]

      /*************************************************************/

      /******************
          Acceptace
      ******************/
      AccEvent[icut][Channel]++;
      EffEvent[icut][Channel] = EffEvent[icut][Channel] + PUWeight;


      hPV[icut][Channel]->Fill(PV,PUWeight);
      
      hMET[icut][Channel]->Fill(MET,PUWeight);
      hMET_Phi[icut][Channel]->Fill(MET_Phi,PUWeight);
      
      hLepPt[icut][Channel]->Fill(Lep.Pt(),PUWeight);
      hLepEta[icut][Channel]->Fill(Lep.Eta(),PUWeight);
      hLepPhi[icut][Channel]->Fill(Lep.Phi(),PUWeight);
      
      hNJets[icut][Channel]->Fill(NJets,PUWeight); 
      hNBtagJets[icut][Channel]->Fill(NBtagJets,PUWeight);

    for(int ijet=0; ijet < Jet_px->size(); ijet++){
      if (ijet<4) CSV[ijet][icut][Channel]->Fill((*Jet_CSV)[ijet],PUWeight);
    }

    }//for(icuts) 
    
  Jet.clear();    
  bJet.clear();    

  }//for(events)


  delete Jet_px;
  delete Jet_py; 
  delete Jet_pz;
  delete Jet_E;
  delete Jet_CSV;

  // Get elapsed time
  sw.Stop();
  std::cout << "==================================================] 100% " << std::endl;
  std::cout << "--- End of event loop: "; sw.Print();
  

  //Acceptance-Efficiency
  std::cout << "--------  Acceptace  --------" << std::endl;
  std::cout << "Number of RAW-mu+Jets events:" << std::endl;
  std::cout << "lepton: "   << AccEvent[0][0] << std::endl;
  std::cout << "4 Jets: "   << AccEvent[1][0] << std::endl;
  std::cout << "MET: "      << AccEvent[2][0] << std::endl;
  std::cout << "2 btag: "   << AccEvent[3][0] << std::endl;

  std::cout << "--------  Efficiency  --------" << std::endl;
  std::cout << "Number of Weigthed-mu+Jets events:" << std::endl;
  std::cout << "lepton: "   << EffEvent[0][0] << " +/- " << sqrt(AccEvent[0][0])*EffEvent[0][0]/AccEvent[0][0] << std::endl;
  std::cout << "4 Jets: "   << EffEvent[1][0] << " +/- " << sqrt(AccEvent[1][0])*EffEvent[1][0]/AccEvent[1][0] << std::endl;
  std::cout << "MET: "      << EffEvent[2][0] << " +/- " << sqrt(AccEvent[2][0])*EffEvent[2][0]/AccEvent[2][0] << std::endl;
  std::cout << "2 btag: "   << EffEvent[3][0] << " +/- " << sqrt(AccEvent[3][0])*EffEvent[3][0]/AccEvent[3][0] << std::endl;
  
  std::cout << "--------  Acceptace  --------" << std::endl;
  std::cout << "Number of RAW-e+Jets events:" << std::endl;
  std::cout << "lepton: "   << AccEvent[0][1] << std::endl;
  std::cout << "4 Jets: "   << AccEvent[1][1] << std::endl;
  std::cout << "MET: "      << AccEvent[2][1] << std::endl;
  std::cout << "2 btag: "   << AccEvent[3][1] << std::endl;

  std::cout << "--------  Efficiency  --------" << std::endl;
  std::cout << "Number of Weigthed-e+Jets events: " << std::endl;
  std::cout << "lepton: "   << EffEvent[0][1] << " +/- " << sqrt(AccEvent[0][1])*EffEvent[0][1]/AccEvent[0][1] << std::endl;
  std::cout << "4 Jets: "   << EffEvent[1][1] << " +/- " << sqrt(AccEvent[1][1])*EffEvent[1][1]/AccEvent[1][1] << std::endl;
  std::cout << "MET: "      << EffEvent[2][1] << " +/- " << sqrt(AccEvent[2][1])*EffEvent[2][1]/AccEvent[2][1] << std::endl;
  std::cout << "2 btag: "   << EffEvent[3][1] << " +/- " << sqrt(AccEvent[3][1])*EffEvent[3][1]/AccEvent[3][1] << std::endl;
  
  //Output Dir
  TString dirname="TopResults";   
  // make a dir if it does not exist!!
  struct stat st;
  if(stat(dirname,&st) != 0) system("mkdir " + dirname);
  
  TString systname="";
  bool matchname=false;
  
  TString temp_fname=fname + ".root";
  for(int i=0;i<temp_fname.Sizeof();i++){
    if (i>2){
      if (temp_fname[i-3]=='-' && 
  	  temp_fname[i-2]=='1' && 
  	  temp_fname[i-1]=='_') matchname=true;
    }
    if (temp_fname[i]=='.') matchname=false;
    if (matchname) systname.Append(temp_fname[i]);
  }
  
  // Yields
  TString Yieldfile=dirname + "/Yields_" + hname + ".h";
  FILE* fyields = fopen(Yieldfile, "a");
  
  fprintf(fyields,"// %s Sample on %s \n", (fname + ".root").Data() , currentDateTime().Data());
  fprintf(fyields,"// %s version \n", hname.Data());
  fprintf(fyields,"float  %s[2][4];//[channel][Cut] \n", systname.Data());
  fprintf(fyields,"float  err_%s[2][4]; //[channel][Cut] \n", systname.Data());
  fprintf(fyields,"// Channel: [0]=mu+Jets [1]=e+Jets \n");
  fprintf(fyields,"// Cut [0]=lepton [1]= Jets [2]=MET [3]=btag \n");
  for(int ch=0;ch<2;ch++){
    for(int cut=0;cut<4;cut++){
      fprintf(fyields,"%s[%i][%i] = %.3f ; \n", systname.Data(), ch, cut, EffEvent[cut][ch]);
      if(AccEvent[cut][ch]!=0.0) fprintf(fyields,"err_%s[%i][%i] = %.3f ; \n", systname.Data(), ch, cut, sqrt(AccEvent[cut][ch])*EffEvent[cut][ch]/AccEvent[cut][ch]);
      else fprintf(fyields,"err_%s[%i][%i] = 0.0 ; \n", systname.Data(), ch, cut);
    }
  }
  fclose(fyields);
  
  std::cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << std::endl;
  std::cout << "Yields saved into " << Yieldfile << " file" << std::endl;
  std::cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << std::endl;    
  
  // --- Write histograms
  
  TString outfname=dirname + "/hSF-" + hname + "_" + fname + ".root";
  TFile *target  = new TFile(outfname,"RECREATE" );  

  for(int j=0; j<4; j++){
    for(int i=0; i<2; i++){
      
      hPV[j][i]->Write();
    
      hMET[j][i]->Write();
      hMET_Phi[j][i]->Write();
      
      hLepPt[j][i]->Write();
      hLepEta[j][i]->Write();
      hLepPhi[j][i]->Write();

      hNJets[j][i]->Write();
      hNBtagJets[j][i]->Write();            

      for(int ij=0; ij<4; ij++){
        CSV[ij][j][i]->Write();
      }

    }//for(i)

  }//for(j)
  
  std::cout << "File saved as " << outfname << std::endl;

}
Ejemplo n.º 12
0
void bdtcontrolplots( TDirectory *bdtdir ) {

   const Int_t nPlots = 6;

   Int_t width  = 900;
   Int_t height = 600;
   char cn[100], cn2[100];
   const TString titName = bdtdir->GetName();
   sprintf( cn, "cv_%s", titName.Data() );
   TCanvas *c = new TCanvas( cn,  Form( "%s Control Plots", titName.Data() ),
                             width, height ); 
   c->Divide(3,2);




   TString hname[nPlots]={"BoostMonitor","BoostWeight","BoostWeightVsTree","ErrFractHist","NodesBeforePruning",titName+"_FOMvsIterFrame"};

   Bool_t BoostMonitorIsDone=kFALSE;

   for (Int_t i=0; i<nPlots; i++){
      Int_t color = 4; 
      TPad * cPad;
      cPad = (TPad*)c->cd(i+1);
      TH1 *h = (TH1*) bdtdir->Get(hname[i]);
      
      if (h){
         h->SetMaximum(h->GetMaximum()*1.3);
         h->SetMinimum( 0 );
         h->SetMarkerColor(color);
         h->SetMarkerSize( 0.7 );
         h->SetMarkerStyle( 24 );
         h->SetLineWidth(1);
         h->SetLineColor(color);
         if(hname[i]=="NodesBeforePruning")h->SetTitle("Nodes before/after pruning");
         h->Draw();
         if(hname[i]=="NodesBeforePruning"){
            TH1 *h2 = (TH1*) bdtdir->Get("NodesAfterPruning");
            h2->SetLineWidth(1);
            h2->SetLineColor(2);
            h2->Draw("same");
         }
         if(hname[i]=="BoostMonitor"){ // a plot only available in case DoBoostMontior option has bee set
            TGraph *g = (TGraph*) bdtdir->Get("BoostMonitorGraph");
            g->Draw("LP*");
            BoostMonitorIsDone = kTRUE;
         }
         if(hname[i]==titName+"_FOMvsIterFrame"){ // a plot only available in case DoBoostMontior option has bee set
            TGraph *g = (TGraph*) bdtdir->Get(titName+"_FOMvsIter");
            g->Draw();
         }
         c->Update();
      }
   }
   
   
   TCanvas *c2 = NULL;
   if (BoostMonitorIsDone){
      sprintf( cn2, "cv2_%s", titName.Data() );
      c2 = new TCanvas( cn2,  Form( "%s BoostWeights", titName.Data() ),
                                 1200, 1200 ); 
      c2->Divide(5,5);
      Int_t ipad=1;
      
      TIter keys( bdtdir->GetListOfKeys() );
      TKey *key;
      //      gDirectory->ls();
      while ( (key = (TKey*)keys.Next()) && ipad < 26) {
         TObject *obj=key->ReadObj();
         if (obj->IsA()->InheritsFrom(TH1::Class())){   
            TH1F *hx = (TH1F*)obj;
            TString hname(Form("%s",obj->GetTitle()));
            if (hname.Contains("BoostWeightsInTreeB")){ 
               c2->cd(ipad++);
               hx->SetLineColor(4);
               hx->Draw();
               hname.ReplaceAll("TreeB","TreeS");
               bdtdir->GetObject(hname.Data(),hx);
               if (hx) {
                  hx->SetLineColor(2);
                  hx->Draw("same");
               }
            }
            c2->Update();
         }
      }
               
   }

   // write to file
   TString fname = Form( "plots/%s_ControlPlots", titName.Data() );
   TMVAGlob::imgconv( c, fname );
   
   if (c2){
      fname = Form( "plots/%s_ControlPlots2", titName.Data() );
      TMVAGlob::imgconv( c2, fname );
   }

   TCanvas *c3 = NULL;
   if (BoostMonitorIsDone){
      sprintf( cn2, "cv3_%s", titName.Data() );
      c3 = new TCanvas( cn2,  Form( "%s Variables", titName.Data() ),
                        1200, 1200 ); 
      c3->Divide(5,5);
      Int_t ipad=1;
      
      TIter keys( bdtdir->GetListOfKeys() );
      TKey *key;
      //      gDirectory->ls();
      while ( (key = (TKey*)keys.Next()) && ipad < 26) {
         TObject *obj=key->ReadObj();
         if (obj->IsA()->InheritsFrom(TH1::Class())){   
            TH1F *hx = (TH1F*)obj;
            TString hname(Form("%s",obj->GetTitle()));
            if (hname.Contains("SigVar0AtTree")){ 
               c3->cd(ipad++);
               hx->SetLineColor(4);
               hx->Draw();
               hname.ReplaceAll("Sig","Bkg");
               bdtdir->GetObject(hname.Data(),hx);
               if (hx) {
                  hx->SetLineColor(2);
                  hx->Draw("same");
               }
            }
            c3->Update();
         }
      }
               
   }


}