void combineHistos(std::string type) {

    bool _dt = (type == "DATA");
    bool _mc = !_dt;

    TDirectory *curdir = gDirectory;

    // Input file: normalized pT spectra
    TFile *fin = 
        new TFile(Form("outputs/output-%s-2a.root", type.c_str()), "READ");
    assert(fin && !fin->IsZombie());
    
    // Top-level directory
    _top = gDirectory;

    // Output file: combined spectra 
    TFile *fout =
        new TFile(Form("outputs/output-%s-2b.root", type.c_str()), "RECREATE");
    assert(fout && !fout->IsZombie());


    std::cout << "Calling combineHistos(" << type << ");" << std::endl;
    std::cout << "Input file " << fin->GetName() << std::endl;
    std::cout << "Output file " << fout->GetName() << std::endl;
    std::cout << "Starting recursions. These may take a few seconds" << std::endl;

    // Store pT ranges to a nice map
    for (int itrg = 0; itrg != _jp_ntrigger; ++itrg) {

        std::string name = _jp_triggers[itrg];
        double lower = _jp_trigranges[itrg][0];
        double upper = _jp_trigranges[itrg][1];

        _ptranges[name] = pair<double, double>(lower, upper);
    }


    // Loop over all the directories recursively
    recurseFile(fin, fout, "hpt");
    recurseFile(fin, fout, "hpt_pre");
    if (_dt)
        recurseFile(fin, fout, "hlumi");
    if (_mc)
        recurseFile(fin, fout, "hpt_g0tw");

    curdir->cd();

    std::cout << std::endl << "Output stored in " << fout->GetName() << std::endl;
    
    // Close files
    fout->Close();
    fout->Delete();
    std::cout << "Output file closed" << std::endl;

    fin->Close();
    fin->Delete();
    std::cout << "Input file closed" << std::endl;
}
Example #2
0
void normalizeHistos(string type) {

  assert(type==_jp_type);
  _nh_mc = (type=="MC" || type=="HW");
  _nh_dt = (type=="DATA");
  assert((_nh_mc || _nh_dt) && !(_nh_mc && _nh_dt));

  TFile *fin = new TFile(Form("output-%s-1.root",type.c_str()),"READ");
  assert(fin && !fin->IsZombie());

  TFile *fout = new TFile(Form("output-%s-2a.root",type.c_str()),"RECREATE");
  assert(fout && !fout->IsZombie());

  if (_lumiscale!=1 && !_nh_mc)
    cout << "Attention! : Scaling luminosity to the new estimate"
         << " by multiplying with " << _lumiscale << endl;

  if (_jp_usetriglumi) {
    cout << "Reading trigger luminosity from settings.h" << endl;
    for (int i = 0; i != _jp_ntrigger; ++i) {
      double lumi = _jp_triglumi[i]/1e6; // /ub to /pb
      cout << Form(" *%s: %1.3f /pb", _jp_triggers[i].c_str(),lumi) << endl;
      triglumi[_jp_triggers[i]] = lumi;
    }
  }

  cout << "Calling normalizeHistos("<<type<<");" << endl;
  cout << "Input file " << fin->GetName() << endl;
  cout << "Output file " << fout->GetName() << endl;
  cout << "Starting recursive loop. This may take a minute" << endl << flush;

  // Loop over all the directories recursively
  recurseFile(fin, fout);

  cout << endl;
  cout << "Recursive loop done." << endl;
  cout << "Writing output to " << fout->GetName() << endl;
  cout << "This may again take a minute" << endl << flush;
  fout->Write();
  cout << "Output written in " << fout->GetName() << endl;
  fout->Close();
  cout << "Output file closed" << endl;
  fout->Delete();
  cout << "Output file pointer deleted" << endl << flush;


  fin->Close();
  fin->Delete();

} // normalizeHistos
Example #3
0
void func(const char * name) {

   TFile *g = new TFile("temp.root","UPDATE");

   // delete any pre-existing trees of the same name

   char nameCycle[100];
   sprintf(nameCycle,"%s;*",name);
   g->Delete(nameCycle);

   TTree *tree1 = new TTree(name,name);

   Float_t flt = 1;
   tree1->Branch("branch",&flt,"temp/F");

   for(int i; i < 500; i++) {
      tree1->Fill();
   }

   g->Write();
   tree1->Reset();
   delete tree1;
   tree1 = 0;

   g->Close();
   delete g;
   g = 0;

}
void make_scan_results()
{
  TFile *f = TFile::Open("scan_results.root", "UPDATE");

  f->Delete("SR;*");

  T = new TTree("SR", "Scanning results");

  TClonesArray* ts = new TClonesArray("IlcESDtrack", 32);
  TBranch * tb = T->Branch("T", &ts);
  delete ts;

  IlcMultiplicity *ms = 0;
  TBranch *mb = T->Branch("M", &ms);

  for (Int_t v = 0; v < 3; ++v)
  {
    vvv[v].vert   = 0;
    vvv[v].branch = T->Branch(vvv[v].bname, &vvv[v].vert);
  }

  for (Int_t i=0; i<=9999; ++i)
  {
    TString name;

    name.Form("Tracks_%04d", i);
    ts = (TClonesArray*) f->Get(name);
    if (ts == 0)
      continue;

    name.Form("Tracklets_%04d", i);
    ms = (IlcMultiplicity*) f->Get(name);
    if (ms == 0)
      Error("make_scan_results", "'%s' not found.", name.Data());

    tb->SetAddress(&ts);
    mb->SetAddress(&ms);

    for (Int_t v = 0; v < 3; ++v)
    {
      name.Form("%s_%04d", vvv[v].oname, i);
      vvv[v].vert = (IlcESDVertex*) f->Get(name);
      if (vvv[v].vert == 0)
        Error("make_scan_results", "'%s' not found.", name.Data());
      vvv[v].branch->SetAddress(&vvv[v].vert);
    }

    T->Fill();

    delete ts;
    delete ms;
    for (Int_t v = 0; v < 3; ++v) delete vvv[v].vert;
  }

  T->Write();

  f->Close();
  delete f;
}
void ChangeDataTreeName(std::string suffix){

  // Define names
  TString filename = "", treename = "", histname = "";
  filename.Form("central_%s.root",suffix.c_str());
  treename.Form("id_%s",suffix.c_str());
  histname.Form("sumOfMcWeights_%s",suffix.c_str());

  TString _pathFile(string(getenv("WORKAREA")) + "/histoAna" + "/SusyAna/histos_110312_13fb_n0111_DD_MMtrial9_SYS_HFT/HFTOutputs_merge/");
  filename = _pathFile+filename;
  cout << "open " << filename << endl;

  // Open file
  TFile* file         = new TFile(filename,"UPDATE");
  if(file->IsOpen()==kFALSE){
    cerr << "Cannot open file " << filename << endl;
    abort();
  }
  file->ls();
  TTree* treeOriginal = (TTree*) file->Get(treename);
  TH1D*  histOriginal = (TH1D*)  file->Get(histname);
  TTree* treeNew      = (TTree*) treeOriginal->Clone();
  TH1D*  histNew      = (TH1D*)  histOriginal->Clone();

  // Set-Write-Delete
  histNew->SetName ("sumOfMcWeights_Data" );
  histNew->SetTitle("sumOfMcWeights_Data" );
  histNew->Write   ("",TObject::kOverwrite);
  treeNew->SetName ("id_Data"             );
  treeNew->SetTitle("id_Data"             );
  treeNew->Write   ("",TObject::kOverwrite);
  file->Delete     (histname+";1"         );
  file->Delete     (treename+";1"         );

  // Close file
  file->Close();
}
Example #6
0
void testweight::Loop(bool cs)
{
//   In a ROOT session, you can do:
//      Root > .L testweight.C
//      Root > testweight t
//      Root > t.GetEntry(12); // Fill t data members with entry number 12
//      Root > t.Show();       // Show values of entry 12
//      Root > t.Show(16);     // Read and show values of entry 16
//      Root > t.Loop();       // Loop on all entries
//

//     This is the loop skeleton where:
//    jentry is the global entry number in the chain
//    ientry is the entry number in the current Tree
//  Note that the argument to GetEntry must be:
//    jentry for TChain::GetEntry
//    ientry for TTree::GetEntry and TBranch::GetEntry
//
//       To read only selected branches, Insert statements like:
// METHOD1:
//    fChain->SetBranchStatus("*",0);  // disable all branches
//    fChain->SetBranchStatus("branchname",1);  // activate branchname
// METHOD2: replace line
//    fChain->GetEntry(jentry);       //read all branches
//by  b_branchname->GetEntry(ientry); //read only this branch
   if (fChain == 0) return;

   TFile * hOutputFile   = new TFile("spectrumrew.root", "RECREATE" ) ;
   TH1D* pt_rew =  new TH1D("pt_rew","pt_rew",50,20,100);
   TH1D* pt_norew =   new TH1D("pt_norew","pt_norew",50,20,100);
   TH1D* mass_rew =  new TH1D("mass_rew","mass_rew",40,100,180);
   TH1D* mass_norew =  new TH1D("mass_norew","mass_norew",40,100,180);
   TH2D* pt2d_norew = new TH2D("pt2d_norew","pt2d_norew",15,25,100,15,55,160);
   TH2D* pt2d_rew = new TH2D("pt2d_rew","pt2d_rew",15,25,100,15,55,160);

   getweights();

   Long64_t nentries = fChain->GetEntriesFast();

   Long64_t nbytes = 0, nb = 0;
   for (Long64_t jentry=0; jentry<nentries;jentry++) {
      Long64_t ientry = LoadTree(jentry);
      if (ientry < 0) break;
      nb = fChain->GetEntry(jentry);   nbytes += nb;
      // if (Cut(ientry) < 0) continue;
      
      if(massggnewvtx<90 || massggnewvtx>190) continue;
      //if(massggnewvtx<100 || massggnewvtx>180) continue;
      
      if((TMath::Abs(etascphot1)>1.4442&&TMath::Abs(etascphot1)<1.566)||(TMath::Abs(etascphot2)>1.4442&&TMath::Abs(etascphot2)<1.566)
	 || TMath::Abs(etascphot1)>2.5 || TMath::Abs(etascphot2)>2.5) continue;  // acceptance
      
      if(ptphot1<55) continue; //pt first photon
      if(ptphot2<25) continue; //pt second photon
      
      //      if(ptcorrjet1<30 || TMath::Abs(etajet1)>4.7) continue; //pt first jet

      bool idphot1 = (idcicphot1 >= 4);
      bool idphot2 = (idcicphot2 >= 4);

      if(!cs){ // photon id no control sample

	if(!(idphot1)) continue;
	if(!(idphot2)) continue;
  
      }else{ // photon id for control sample
	
	if( !( (idphot1 && !idphot2 && !pid_hasMatchedPromptElephot2) || (idphot2 && !idphot1 && !pid_hasMatchedPromptElephot1) ) ) continue; 

      }

      pt_norew->Fill(ptphot2);
      mass_norew->Fill(massggnewvtx);

      double minptsublead(25), maxptsublead(100);
      double minptlead(55), maxptlead(160);
      double sizex = (maxptsublead - minptsublead)/15.;
      double sizey = (maxptlead - minptlead)/15.;
      int i = int((ptphot2-25)/sizex);
      int j = int((ptphot1-55)/sizey);
      if(i<0) i=0;
      if(j>14) j=14;
      if(i<0) i=0;
      if(j>14) j=14;
      if(i>-1 && i<15 && j>-1 && j<15){
	pt_rew->Fill(ptphot2,weights_[i][j]);
	mass_rew->Fill(massggnewvtx,weights_[i][j]);
	pt2d_norew->Fill(ptphot2,ptphot1,1);
	pt2d_rew->Fill(ptphot2,ptphot1,weights_[i][j]);
      }
      //      else  pt_rew->Fill(ptphot2,1.);
   }
   
   hOutputFile->Write() ;
   hOutputFile->Close() ;
   hOutputFile->Delete();
     
}
Example #7
0
void theory(string type) {


  //TFile *fin = new TFile(Form("output-%s-3a.root",type.c_str()),"READ");
  TFile *fin = new TFile(Form("output-%s-2b.root",type.c_str()),"READ");
  assert(fin && !fin->IsZombie());

  // LO Pythia MC prediction
  TFile *fmc = new TFile("output-MC-2b.root","READ");
  assert(fmc && !fmc->IsZombie());

  // NB: central PDF is chosen later
  /*
  TFile *fnlo_cteq = (_algo=="AK7" ?
		      new TFile("fastnlo/fnl2332d_ct10-nlo_aspdf.root",
				"READ") :
		      new TFile("fastnlo/fnl2342b_ct10_aspdf.root","READ"));
  assert(fnlo_cteq && !fnlo_cteq->IsZombie());

  // CT10 from Gregory Soyez
  TFile *fnlo_ct10 = (_algo=="AK7" ?
		      new TFile("fastnlo/lhc7.root","READ") :
		      new TFile("fastnlo/lhc5.root","READ"));
  assert(fnlo_ct10 && !fnlo_ct10->IsZombie());

  TFile *fnlo_mstw = (_algo=="AK7" ?
		      new TFile("fastnlo/fnl2332d_mstw2008-nlo_aspdf.root",
				"READ") :
		      new TFile("fastnlo/fnl2342b_mstw2008nlo_aspdf.root",
				"READ"));
  assert(fnlo_mstw && !fnlo_mstw->IsZombie());

  TFile *fnlo_nnpdf = (_algo=="AK7" ?
		       new TFile("fastnlo/fnl2332d_nnpdf21-nlo_aspdf.root",
				 "READ") :
		       new TFile("fastnlo/fnl2342b_nnpdf21100_aspdf.root",
				 "READ"));
  assert(fnlo_nnpdf && !fnlo_nnpdf->IsZombie());

  // HERA10,15 empty for AK7?
  TFile *fnlo_hera = (_algo=="AK7" ?
		      new TFile("fastnlo/fnl2332d_hera10all_aspdf.root",
				"READ") :
		      new TFile("fastnlo/fnl2342b_hera10all_aspdf.root",
				"READ"));
  assert(fnlo_hera && !fnlo_hera->IsZombie());

  // Alpha-s variation
  TFile *fnlo_as = new TFile(_algo=="AK7" ?
			     "pdf4lhc/fnl2342a_ct10as_as-2.root" :
			     "pdf4lhc/fnl2342a_ct10as_as-2.root", "READ");
  assert(fnlo_as && !fnlo_as->IsZombie());

  TFile *fnp = new TFile(Form("fastnlo/NPcor%s.root",_algo.c_str()));
  assert(fnp && !fnp->IsZombie());
  */

  TFile *fout = new TFile(Form("output-%s-2c.root",type.c_str()),"RECREATE");
  assert(fout && !fout->IsZombie());

  // Select top category
  assert(fin->cd("Standard"));
  fin->cd("Standard");
  TDirectory *din0 = gDirectory;

  assert(fmc->cd("Standard"));
  fmc->cd("Standard");
  TDirectory *dmc0 = gDirectory;

  fout->mkdir("Standard");
  assert(fout->cd("Standard"));
  fout->cd("Standard");
  TDirectory *dout0 = gDirectory;

  // Automatically go through the list of keys (directories)
  TList *keys = din0->GetListOfKeys();
  TListIter itkey(keys);
  TObject *key, *obj;

  while ( (key = itkey.Next()) ) {

    obj = ((TKey*)key)->ReadObj(); assert(obj);
    
    // Found a subdirectory
    if (obj->InheritsFrom("TDirectory")
	&& string(obj->GetName())!="Eta_0.0-1.3"
	&& string(obj->GetName())!="Eta_3.0-3.2"
	&& string(obj->GetName())!="Eta_3.2-4.7") {

      assert(din0->cd(obj->GetName()));
      din0->cd(obj->GetName());
      TDirectory *din = gDirectory;

      assert(dmc0->cd(obj->GetName()));
      dmc0->cd(obj->GetName());
      TDirectory *dmc = gDirectory;
      /*
      assert(fnlo_cteq->cd());
      TDirectory *dnlo_cteq = gDirectory;
      assert(fnlo_ct10->cd());
      TDirectory *dnlo_ct10 = gDirectory;
      assert(fnlo_mstw->cd());
      TDirectory *dnlo_mstw = gDirectory;
      assert(fnlo_nnpdf->cd());
      TDirectory *dnlo_nnpdf = gDirectory;
      assert(fnlo_hera->cd());
      TDirectory *dnlo_hera = gDirectory;
      //
      assert(fnlo_as->cd());
      TDirectory *das = gDirectory;

      assert(fnp->cd());
      TDirectory *dnp = gDirectory;
      */

      dout0->mkdir(obj->GetName());
      assert(dout0->cd(obj->GetName()));
      dout0->cd(obj->GetName());
      TDirectory *dout = gDirectory;
      
      // Process subdirectory
      //theoryBin(din, dnlo_cteq, dnp, dnlo_ct10, dnlo_mstw, dnlo_nnpdf,
      //	dnlo_hera,
      //	das, dout);
      theoryBin(din, dmc, dout);
      //dataBin(din, dout);
    } // inherits TDirectory
  } // while

  cout << "Output stored in " << fout->GetName() << endl;
  fout->Write();
  fout->Close();
  fout->Delete();

  fin->Close();
  fin->Delete();

  fmc->Close();
  /*
  fnlo_cteq->Close();
  fnlo_cteq->Delete();
  fnlo_ct10->Close();
  fnlo_ct10->Delete();
  fnlo_mstw->Close();
  fnlo_mstw->Delete();
  fnlo_nnpdf->Close();
  fnlo_nnpdf->Delete();
  fnlo_as->Close();
  fnlo_as->Delete();
  */

  // Empty work space so that next steps won't get messed up
  //if (gROOT->IsBatch()) {
  //gROOT->Clear();
  //}
} // theory
Example #8
0
void compClusHitsMod2(int nev=-1)
{
  
  const int kSplit=0x1<<22;
  const int kSplCheck=0x1<<23;
  //
  gSystem->Load("libITSUpgradeBase");
  gSystem->Load("libITSUpgradeSim");
  gSystem->Load("libITSUpgradeRec");
  gROOT->SetStyle("Plain");

  AliCDBManager* man = AliCDBManager::Instance();
  man->SetDefaultStorage("local://$ALICE_ROOT/OCDB");
  man->SetSpecificStorage("GRP/GRP/Data",
        Form("local://%s",gSystem->pwd()));
  man->SetSpecificStorage("ITS/Align/Data",
        Form("local://%s",gSystem->pwd()));
  man->SetSpecificStorage("ITS/Calib/RecoParam",
        Form("local://%s",gSystem->pwd()));
  man->SetRun(0);

  TH1F* hL0A = new TH1F("hL0A", "Layer 0, polar angle", 20, 0, TMath::PiOver2());
  hL0A->SetDirectory(0);
  hL0A->GetXaxis()->SetTitle("#alpha");
  TH1F* hL0B = new TH1F("hL0B", "Layer 0, azimuthal angle", 20, 0, TMath::PiOver2());
  hL0B->SetDirectory(0);
  hL0B->GetXaxis()->SetTitle("#beta");

  TH1F* hL1A = new TH1F("hL1A", "Layer 1, polar angle", 20, 0, TMath::PiOver2());
  hL1A->SetDirectory(0);
  hL1A->GetXaxis()->SetTitle("#alpha");
  TH1F* hL1B = new TH1F("hL1B", "Layer 1, azimuthal angle", 20, 0, TMath::PiOver2());
  hL1B->SetDirectory(0);
  hL1B->GetXaxis()->SetTitle("#beta");

  TH1F* hL2A = new TH1F("hL2A", "Layer 2, polar angle", 20, 0, TMath::PiOver2());
  hL2A->SetDirectory(0);
  hL2A->GetXaxis()->SetTitle("#alpha");
  TH1F* hL2B = new TH1F("hL2B", "Layer 2, azimuthal angle", 20, 0, TMath::PiOver2());
  hL2B->SetDirectory(0);
  hL2B->GetXaxis()->SetTitle("#beta");

  TH1F* hL3A = new TH1F("hL3A", "Layer 3, polar angle", 20, 0, TMath::PiOver2());
  hL3A->SetDirectory(0);
  hL3A->GetXaxis()->SetTitle("#alpha");
  TH1F* hL3B = new TH1F("hL3B", "Layer 3, azimuthal angle", 20, 0, TMath::PiOver2());
  hL3B->SetDirectory(0);
  hL3B->GetXaxis()->SetTitle("#beta");

  TH1F* hL4A = new TH1F("hL4A", "Layer 4, polar angle", 20, 0, TMath::PiOver2());
  hL4A->SetDirectory(0);
  hL4A->GetXaxis()->SetTitle("#alpha");
  TH1F* hL4B = new TH1F("hL4B", "Layer 4, azimuthal angle", 20, 0, TMath::PiOver2());
  hL4B->SetDirectory(0);
  hL4B->GetXaxis()->SetTitle("#beta");

  TH1F* hL5A = new TH1F("hL5A", "Layer 5, polar angle", 20, 0, TMath::PiOver2());
  hL5A->SetDirectory(0);
  hL5A->GetXaxis()->SetTitle("#alpha");
  TH1F* hL5B = new TH1F("hL5B", "Layer 5, azimuthal angle", 20, 0, TMath::PiOver2());
  hL5B->SetDirectory(0);
  hL5B->GetXaxis()->SetTitle("#beta");

  TH1F* hL6A = new TH1F("hL6A", "Layer 6, polar angle", 20, 0, TMath::PiOver2());
  hL6A->SetDirectory(0);
  hL6A->GetXaxis()->SetTitle("#alpha");
  TH1F* hL6B = new TH1F("hL6B", "Layer 6, azimuthal angle", 20, 0, TMath::PiOver2());
  hL6B->SetDirectory(0);
  hL6B->GetXaxis()->SetTitle("#beta");

  gAlice=NULL;
  AliRunLoader* runLoader = AliRunLoader::Open("galice.root");
  runLoader->LoadgAlice();

  gAlice = runLoader->GetAliRun();

  runLoader->LoadHeader();
  runLoader->LoadKinematics();
  runLoader->LoadRecPoints();
  runLoader->LoadSDigits();
  runLoader->LoadHits();

  AliLoader *dl = runLoader->GetDetectorLoader("ITS");

  AliGeomManager::LoadGeometry("geometry.root");
  TObjArray algITS;
  AliGeomManager::LoadAlignObjsFromCDBSingleDet("ITS",algITS);
  AliGeomManager::ApplyAlignObjsToGeom(algITS);
  //
  AliITSUGeomTGeo* gm = new AliITSUGeomTGeo(kTRUE);
  AliITSMFTClusterPix::SetGeom(gm);
  //
  AliITSURecoDet *its = new AliITSURecoDet(gm, "ITSinterface");
  its->CreateClusterArrays();
  //
  Double_t xg1,yg1,zg1=0.,xg0,yg0,zg0=0.,tg0;
  Double_t xExit,yExit,zExit,xEnt,yEnt,zEnt,tof1;

  //
  TTree *cluTree = 0x0;
  TTree *hitTree = 0x0;
  TClonesArray *hitList=new TClonesArray("AliITSMFTHit");
  //
  Float_t xyzClGloF[3];
  Double_t xyzClGlo[3],xyzClTr[3];
  Int_t labels[3];
  int nLab = 0;
  int nlr=its->GetNLayersActive();
  int ntotev = (Int_t)runLoader->GetNumberOfEvents();

  printf("N Events : %i \n",ntotev);
  if (nev>0) ntotev = TMath::Min(nev,ntotev);
  //
  
  // output tree
  TFile* flOut = TFile::Open("clInfo.root","recreate");
  TTree* trOut = new TTree("clitsu","clitsu");
  clSumm cSum;
  trOut->Branch("evID", &cSum.evID ,"evID/I");
  trOut->Branch("volID",&cSum.volID,"volID/I");
  trOut->Branch("lrID", &cSum.lrID ,"lrID/I");  
  trOut->Branch("clID", &cSum.clID ,"clID/I");  
  trOut->Branch("nPix", &cSum.nPix ,"nPix/I");
  trOut->Branch("nX"  , &cSum.nX   ,"nX/I");
  trOut->Branch("nZ"  , &cSum.nZ   ,"nZ/I");
  trOut->Branch("q"   , &cSum.q    ,"q/I");
  trOut->Branch("pt"  , &cSum.pt   ,"pt/F");  
  trOut->Branch("eta"  ,&cSum.eta  ,"eta/F");  
  trOut->Branch("phi"  , &cSum.phi  ,"phi/F");  
  trOut->Branch("xyz",   cSum.xyz,  "xyz[3]/F");  
  trOut->Branch("dX"  , &cSum.dX   ,"dX/F");
  trOut->Branch("dY"  , &cSum.dY   ,"dY/F");
  trOut->Branch("dZ"  , &cSum.dZ   ,"dZ/F");  
  trOut->Branch("split",&cSum.split,"split/O");
  trOut->Branch("prim", &cSum.prim, "prim/O");
  trOut->Branch("pdg",  &cSum.pdg,  "pdg/I");
  trOut->Branch("ntr",  &cSum.ntr,  "ntr/I");
  trOut->Branch("alpha", &cSum.alpha, "alpha/F");
  trOut->Branch("beta", &cSum.beta, "beta/F");
  trOut->Branch("nRowPatt", &cSum.nRowPatt, "nRowPatt/I");
  trOut->Branch("nColPatt", &cSum.nColPatt, "nColPatt/I");

  TopDatabase DB;
  
  for (Int_t iEvent = 0; iEvent < ntotev; iEvent++) {
    printf("\n Event %i \n",iEvent);
    runLoader->GetEvent(iEvent);
    AliStack *stack = runLoader->Stack();
    cluTree=dl->TreeR();
    hitTree=dl->TreeH();
    hitTree->SetBranchAddress("ITS",&hitList);
    // 
    // read clusters
    for (int ilr=nlr;ilr--;) {
      TBranch* br = cluTree->GetBranch(Form("ITSRecPoints%d",ilr));
      if (!br) {printf("Did not find cluster branch for lr %d\n",ilr); exit(1);}
      br->SetAddress(its->GetLayerActive(ilr)->GetClustersAddress());
    }
    cluTree->GetEntry(0);
    its->ProcessClusters();
    //
    // read hits
    for(Int_t iEnt=0;iEnt<hitTree->GetEntries();iEnt++){//entries loop of the hits
      hitTree->GetEntry(iEnt);
      int nh = hitList->GetEntries();
      for(Int_t iHit=0; iHit<nh;iHit++){
        AliITSMFTHit *pHit = (AliITSMFTHit*)hitList->At(iHit);
        int mcID = pHit->GetTrack();
	//printf("MCid: %d %d %d Ch %d\n",iEnt,iHit, mcID, pHit->GetChip());
        TClonesArray* harr = arrMCTracks.GetEntriesFast()>mcID ? (TClonesArray*)arrMCTracks.At(mcID) : 0;
        if (!harr) {
          harr = new TClonesArray("AliITSMFTHit"); // 1st encounter of the MC track
          arrMCTracks.AddAtAndExpand(harr,mcID);
        }
        //
        new ( (*harr)[harr->GetEntriesFast()] ) AliITSMFTHit(*pHit);
      }
    }
    //    return;
    //
    // compare clusters and hits
    //
    printf(" tree entries: %lld\n",cluTree->GetEntries());
    //
    for (int ilr=0;ilr<nlr;ilr++) {
      AliITSURecoLayer* lr = its->GetLayerActive(ilr);
      TClonesArray* clr = lr->GetClusters();
      int nClu = clr->GetEntries();
      //printf("Layer %d : %d clusters\n",ilr,nClu);
      //
      for (int icl=0;icl<nClu;icl++) {
        AliITSMFTClusterPix *cl = (AliITSMFTClusterPix*)clr->At(icl);
        int modID = cl->GetVolumeId();

        //------------ check if this is a split cluster
        int sInL = modID - gm->GetFirstChipIndex(ilr);
        if (!cl->TestBit(kSplCheck)) {
          cl->SetBit(kSplCheck);
          // check if there is no other cluster with same label on this module
          AliITSURecoSens* sens = lr->GetSensor(sInL);
          int nclSn = sens->GetNClusters();
          int offs = sens->GetFirstClusterId();
          //  printf("To check for %d (mod:%d) N=%d from %d\n",icl,modID,nclSn,offs);
          for (int ics=0;ics<nclSn;ics++) {
            AliITSMFTClusterPix* clusT = (AliITSMFTClusterPix*)lr->GetCluster(offs+ics); // access to clusters
            if (clusT==cl) continue;
            for (int ilb0=0;ilb0<3;ilb0++) {
              int lb0 = cl->GetLabel(ilb0); if (lb0<=-1) break;
              for (int ilb1=0;ilb1<3;ilb1++) {
                int lb1 = clusT->GetLabel(ilb1); if (lb1<=-1) break;
                if (lb1==lb0) {
                  cl->SetBit(kSplit);
                  clusT->SetBit(kSplit);
                  /*
                  printf("Discard clusters of module %d:\n",modID);
                  cl->Print();
                  clusT->Print();
                  */
                  break;
                }
              }
            }
          }
        }
        //------------
        const AliITSMFTSegmentationPix* segm = gm->GetSegmentation(ilr);
        //
        cl->GetGlobalXYZ(xyzClGloF);
        int clsize = cl->GetNPix();
        for (int i=3;i--;) xyzClGlo[i] = xyzClGloF[i];
        const TGeoHMatrix* mat = gm->GetMatrixSens(modID);
        if (!mat) {printf("failed to get matrix for module %d\n",cl->GetVolumeId());}
        mat->MasterToLocal(xyzClGlo,xyzClTr);
        //
        int col,row;
        segm->LocalToDet(xyzClTr[0],xyzClTr[2],row,col); // effective col/row
        nLab = 0;
        for (int il=0;il<3;il++) {
          if (cl->GetLabel(il)>=0) labels[nLab++] = cl->GetLabel(il);
          else break;
        }
        // find hit info
        for (int il=0;il<nLab;il++) {
          TClonesArray* htArr = (TClonesArray*)arrMCTracks.At(labels[il]);
	  //printf("check %d/%d LB %d  %p\n",il,nLab,labels[il],htArr);
	  if (!htArr) {printf("did not find MChits for label %d ",labels[il]); cl->Print(); continue;}
          //
          int nh = htArr->GetEntriesFast();
          AliITSMFTHit *pHit=0;
          for (int ih=nh;ih--;) {
            AliITSMFTHit* tHit = (AliITSMFTHit*)htArr->At(ih);
            if (tHit->GetChip()!=modID) continue;
            pHit = tHit;
            break;
          }
          if (!pHit) {
            printf("did not find MChit for label %d on module %d ",il,modID); 
            cl->Print(); 
            htArr->Print();
            continue;
          }
          //
          pHit->GetPositionG(xg1,yg1,zg1);
          pHit->GetPositionG0(xg0,yg0,zg0,tg0);
          //
          double txyzH[3],gxyzH[3] = { (xg1+xg0)/2, (yg1+yg0)/2, (zg1+zg0)/2 };
          mat->MasterToLocal(gxyzH,txyzH);

          double rcl = TMath::Sqrt(xyzClTr[0]*xyzClTr[0]+xyzClTr[1]*xyzClTr[1]);
          double rht = TMath::Sqrt(txyzH[0]*txyzH[0]+txyzH[1]*txyzH[1]);
          //
          //Angles determination

          pHit->GetPositionL(xExit,yExit,zExit,gm);
          pHit->GetPositionL0(xEnt,yEnt,zEnt,tof1,gm);

          Double_t dirHit[3]={(xExit-xEnt),(yExit-yEnt),(zExit-zEnt)};

          /*double PG[3] = {(double)pHit->GetPXG(), (double)pHit->GetPYG(), (double)pHit->GetPZG()}; //Momentum at hit-point in Global Frame
          double PL[3];
          if (TMath::Abs(PG[0])<10e-7 && TMath::Abs(PG[1])<10e-7) {
            pHit->Dump();
            int lb = pHit->GetTrack();
            stack->Particle(lb)->Print();
            continue;
          }
          mat->MasterToLocalVect(PG,PL); //Momentum in local Frame
          //printf(">> %e %e   %e %e   %e %e\n",PG[0],PL[0],PG[1],PL[1],PG[2],PL[2]);*/

          Double_t alpha1 = TMath::ACos(TMath::Abs(dirHit[1])/TMath::Sqrt(dirHit[0]*dirHit[0]+dirHit[1]*dirHit[1]+dirHit[2]*dirHit[2])); //Polar Angle
          Float_t alpha2 = (Float_t) alpha1; //convert to float
          cSum.alpha = alpha2;

          Double_t beta1;
          beta1 = TMath::ATan2(dirHit[0],dirHit[2]); //Azimuthal angle, values from -Pi to Pi
          Float_t beta2 = (Float_t) beta1;
          cSum.beta = beta2;

	  if(ilr==0){
	    hL0A->Fill(alpha2);
	    hL0B->Fill(beta2);
	  }
	  
	  if(ilr==1){
	    hL1A->Fill(alpha2);
	    hL1B->Fill(beta2);
	  }

	  if(ilr==2){
	    hL2A->Fill(alpha2);
	    hL2B->Fill(beta2);
	  }

	  if(ilr==3){
	    hL3A->Fill(alpha2);
	    hL3B->Fill(beta2);
	  }

	  if(ilr==4){
	    hL4A->Fill(alpha2);
	    hL4B->Fill(beta2);
	  }

	  if(ilr==5){
	    hL5A->Fill(alpha2);
	    hL5B->Fill(beta2);
	  }

	  if(ilr==6){
	    hL6A->Fill(alpha2);
	    hL6B->Fill(beta2);
	  }
          
          GetHistoClSize(clsize,kDR,&histoArr)->Fill((rht-rcl)*1e4);
          if (cl->TestBit(kSplit)) {
            if (col%2) GetHistoClSize(clsize,kDTXoddSPL,&histoArr)->Fill((txyzH[0]-xyzClTr[0])*1e4);
            else       GetHistoClSize(clsize,kDTXevenSPL,&histoArr)->Fill((txyzH[0]-xyzClTr[0])*1e4);
            GetHistoClSize(clsize,kDTZSPL,&histoArr)->Fill((txyzH[2]-xyzClTr[2])*1e4);
            GetHistoClSize(0,kNPixSPL,&histoArr)->Fill(clsize);
          }
          if (col%2) GetHistoClSize(clsize,kDTXodd,&histoArr)->Fill((txyzH[0]-xyzClTr[0])*1e4);
          else       GetHistoClSize(clsize,kDTXeven,&histoArr)->Fill((txyzH[0]-xyzClTr[0])*1e4);
          GetHistoClSize(clsize,kDTZ,&histoArr)->Fill((txyzH[2]-xyzClTr[2])*1e4);
          GetHistoClSize(0,kNPixAll,&histoArr)->Fill(clsize);
          //
          cSum.evID = iEvent;
          cSum.volID = cl->GetVolumeId();
          cSum.lrID = ilr;
          cSum.clID = icl;
          cSum.nPix = cl->GetNPix();
          cSum.nX   = cl->GetNx();
          cSum.nZ   = cl->GetNz();
          cSum.q    = cl->GetQ();
          cSum.split = cl->TestBit(kSplit);
          cSum.dX = (txyzH[0]-xyzClTr[0])*1e4;
          cSum.dY = (txyzH[1]-xyzClTr[1])*1e4;
          cSum.dZ = (txyzH[2]-xyzClTr[2])*1e4;
          cSum.nRowPatt = cl-> GetPatternRowSpan();
          cSum.nColPatt = cl-> GetPatternColSpan();
	  DB.AccountTopology(*cl, cSum.dX, cSum.dZ, cSum.alpha, cSum.beta);
          
          GetHistoClSize(clsize,kDR,&histoArr)->Fill((rht-rcl)*1e4);
          if (cl->TestBit(kSplit)) {
            if (col%2) GetHistoClSize(clsize,kDTXoddSPL,&histoArr)->Fill((txyzH[0]-xyzClTr[0])*1e4);
            else       GetHistoClSize(clsize,kDTXevenSPL,&histoArr)->Fill((txyzH[0]-xyzClTr[0])*1e4);
            GetHistoClSize(clsize,kDTZSPL,&histoArr)->Fill((txyzH[2]-xyzClTr[2])*1e4);
            GetHistoClSize(0,kNPixSPL,&histoArr)->Fill(clsize);
          }
          if (col%2) GetHistoClSize(clsize,kDTXodd,&histoArr)->Fill((txyzH[0]-xyzClTr[0])*1e4);
          else       GetHistoClSize(clsize,kDTXeven,&histoArr)->Fill((txyzH[0]-xyzClTr[0])*1e4);
          GetHistoClSize(clsize,kDTZ,&histoArr)->Fill((txyzH[2]-xyzClTr[2])*1e4);
          GetHistoClSize(0,kNPixAll,&histoArr)->Fill(clsize);
          //
          cSum.evID = iEvent;
          cSum.volID = cl->GetVolumeId();
          cSum.lrID = ilr;
          cSum.clID = icl;
          cSum.nPix = cl->GetNPix();
          cSum.nX   = cl->GetNx();
          cSum.nZ   = cl->GetNz();
          cSum.q    = cl->GetQ();
          cSum.split = cl->TestBit(kSplit);
          cSum.dX = (txyzH[0]-xyzClTr[0])*1e4;
          cSum.dY = (txyzH[1]-xyzClTr[1])*1e4;
          cSum.dZ = (txyzH[2]-xyzClTr[2])*1e4;
          cSum.nRowPatt = cl-> GetPatternRowSpan();
          cSum.nColPatt = cl-> GetPatternColSpan();
 
                    
          int label = cl->GetLabel(0);
          TParticle* part = 0;
          if (label>=0 && (part=stack->Particle(label)) ) {
            cSum.pdg = part->GetPdgCode();
            cSum.eta = part->Eta();
            cSum.pt  = part->Pt();
            cSum.phi = part->Phi();
            cSum.prim = stack->IsPhysicalPrimary(label);
          } 
          cSum.ntr = 0;
          for (int ilb=0;ilb<3;ilb++) if (cl->GetLabel(ilb)>=0) cSum.ntr++;
          for (int i=0;i<3;i++) cSum.xyz[i] = xyzClGloF[i];
          //
          trOut->Fill();
          /*
          if (clsize==5) {
            printf("\nL%d(%c) Mod%d, Cl:%d | %+5.1f %+5.1f (%d/%d)|H:%e %e %e | C:%e %e %e\n",ilr,cl->TestBit(kSplit) ? 'S':'N',
             modID,icl,(txyzH[0]-xyzClTr[0])*1e4,(txyzH[2]-xyzClTr[2])*1e4, row,col,
             gxyzH[0],gxyzH[1],gxyzH[2],xyzClGlo[0],xyzClGlo[1],xyzClGlo[2]);
            cl->Print();
            pHit->Print();
            //
            double a0,b0,c0,a1,b1,c1,e0;
            pHit->GetPositionL0(a0,b0,c0,e0);
            pHit->GetPositionL(a1,b1,c1);
            float cloc[3];
            cl->GetLocalXYZ(cloc);
            printf("LocH: %e %e %e | %e %e %e\n",a0,b0,c0,a1,b1,c1);
            printf("LocC: %e %e %e | %e %e %e\n",cloc[0],cloc[1],cloc[2],xyzClTr[0],xyzClTr[1],xyzClTr[2]);
          }
          */
          //
        }
      }
    }
    
    //    layerClus.Clear();
    //
    arrMCTracks.Delete();
  }//event loop
  //
  DB.EndAndSort();
  DB.SetThresholdCumulative(0.95);
  cout << "Over threshold: : "<< DB.GetOverThr()<<endl;
  DB.Grouping(10,10);
  DB.PrintDB("Database1.txt"); 
  flOut->cd();
  trOut->Write();
  delete trOut;
  flOut->Close();
  flOut->Delete();
  DrawReport("clinfo.ps",&histoArr);
  TFile* flDB = TFile::Open("TopologyDatabase.root", "recreate");
  flDB->WriteObject(&DB,"DB","kSingleKey");
  flDB->Close();
  delete flDB;

  TCanvas* cnv123 = new TCanvas("cnv123","cnv123");
  cnv123->Divide(1,2);
  cnv123->Print("anglesdistr.pdf[");
  cnv123->cd(1);
  hL0A->Draw();
  cnv123->cd(2);
  hL0B->Draw();
  cnv123->Print("anglesdistr.pdf");
  cnv123->cd(1);
  hL1A->Draw();
  cnv123->cd(2);
  hL1B->Draw();
  cnv123->Print("anglesdistr.pdf");
  cnv123->cd(1);
  hL2A->Draw();
  cnv123->cd(2);
  hL2B->Draw();
  cnv123->Print("anglesdistr.pdf");
  cnv123->cd(1);
  hL3A->Draw();
  cnv123->cd(2);
  hL3B->Draw();
  cnv123->Print("anglesdistr.pdf");
  cnv123->cd(1);
  hL4A->Draw();
  cnv123->cd(2);
  hL4B->Draw();
  cnv123->Print("anglesdistr.pdf");
  cnv123->cd(1);
  hL5A->Draw();
  cnv123->cd(2);
  hL5B->Draw();
  cnv123->Print("anglesdistr.pdf");
  cnv123->cd(1);
  hL6A->Draw();
  cnv123->cd(2);
  hL6B->Draw();
  cnv123->Print("anglesdistr.pdf");
  cnv123->Print("anglesdistr.pdf]");
  //
}
Example #9
0
//--------------------------------------------------------------------------------------------------
// Do Fake Rate Computation From WJets sample
//--------------------------------------------------------------------------------------------------
void computeElectronFakeRatesWithTrackDenominatorFromWJets( char *FakeRateFilename ,bool fitFakeRate, int chargetype, int eventType ) {

  string fakeTypeString = "";
  //Samples
  vector<string> madgraphDatasetFiles;
  vector<string> madgraphDatasetNames;
  vector<string> pythiaDatasetFiles;
  vector<string> pythiaDatasetNames;

  //*****************************************************************************************
  //Do FakeRate Computation 
  //*****************************************************************************************

  //Create root file to store fake rates
  TFile *file = new TFile(FakeRateFilename, "UPDATE");
  file->cd();

  //for different charges
  string chargeTypeName = "";
  if (chargetype == -1)
    chargeTypeName = "Minus";
  else if (chargetype == 1)
    chargeTypeName = "Plus";

  string eventTypeName = "";
  if (eventType == -1)
    eventTypeName = "MinusW";
  else if (eventType == 1)
    eventTypeName = "PlusW";


  //do both muon and electrons
  Double_t maxY = 1.0;
  for (int faketype=11 ; faketype <= 11; faketype+=2) {
    if (faketype == 11) {
      fakeTypeString = "Electron";
      maxY = 0.1;
    } else if (faketype == 13) {
      fakeTypeString = "Muon";
      maxY = 0.01;
    } else {
      cerr << "Error: faketype = " << faketype << " not recognized.\n";
      assert(false);
    }
    
    //*****************************************************************************************
    //Load input histogram files
    //*****************************************************************************************
    madgraphDatasetFiles.clear(); 
    madgraphDatasetNames.clear();
    pythiaDatasetFiles.clear();
    pythiaDatasetNames.clear();
    
    //Madgraph WJets
    madgraphDatasetFiles.push_back("/home/sixie/hist/Compute" + fakeTypeString + "FakeRate/filler/006/Compute" + fakeTypeString + "FakeRate_f8-wjets-mg-id9.root");
    madgraphDatasetNames.push_back("f8-wjets-mg-id9");
    //Pythia WJets
    pythiaDatasetFiles.push_back("/home/sixie/hist/Compute" + fakeTypeString + "FakeRate/filler/006/Compute" + fakeTypeString + "FakeRate_s8-we-id9.root");
    pythiaDatasetNames.push_back("s8-we-id9");
    pythiaDatasetFiles.push_back("/home/sixie/hist/Compute" + fakeTypeString + "FakeRate/filler/006/Compute" + fakeTypeString + "FakeRate_s8-wm-id9.root");
    pythiaDatasetNames.push_back("s8-wm-id9");
    pythiaDatasetFiles.push_back("/home/sixie/hist/Compute" + fakeTypeString + "FakeRate/filler/006/Compute" + fakeTypeString + "FakeRate_s8-wtau-id9.root");
    pythiaDatasetNames.push_back("s8-wtau-id9");

    //*****************************************************************************************
    //Construct the fake rate Histgrams. Fit with function.
    //*****************************************************************************************
    vector<TH1F*> fakeRateHistograms; fakeRateHistograms.clear();
    vector<TF1*> fakeRateFits; fakeRateFits.clear();
    vector<string> fakeRateLegendNames; fakeRateLegendNames.clear();

    //pythia version
    TH1F *FakeRatePt_pythia = createFakeRatePtHist(pythiaDatasetFiles, pythiaDatasetNames, 1, faketype, chargetype, eventType,
                                                   (chargeTypeName + fakeTypeString + eventTypeName + "TrackDenominatorFakeRate_Pt_PythiaWJets").c_str());
    FakeRatePt_pythia->GetYaxis()->SetTitle((chargeTypeName + fakeTypeString + eventTypeName + "TrackDenominator Fake Rate").c_str());    
    TF1 *FakeRateFitFunction_pythia = NULL;
    if (fitFakeRate) {
      FakeRateFitFunction_pythia = fitFakeRatePtHist(FakeRatePt_pythia);
      FakeRateFitFunction_pythia->SetName((chargeTypeName + fakeTypeString + eventTypeName + "TrackDenominatorFakeRateFunction_Pt_PythiaWJets").c_str());
      fakeRateFits.push_back(FakeRateFitFunction_pythia);
    }
    fakeRateHistograms.push_back(FakeRatePt_pythia);
    fakeRateLegendNames.push_back((chargeTypeName + fakeTypeString + eventTypeName + "TrackDenominator Pythia W+Jets").c_str());

    //madgraph version
//     TH1F *FakeRatePt_madgraph = createFakeRatePtHist(
//       madgraphDatasetFiles, madgraphDatasetNames,1,faketype, chargetype,eventType,
//       (chargeTypeName + fakeTypeString + eventTypeName + "TrackDenominator FakeRate_Pt_MadgraphWJets").c_str());
//     FakeRatePt_madgraph->GetYaxis()->SetTitle((chargeTypeName + fakeTypeString + eventTypeName + "TrackDenominator Fake Rate").c_str());    

//     TF1 *FakeRateFitFunction_madgraph = NULL;
//     if (fitFakeRate) {
//       FakeRateFitFunction_madgraph = fitFakeRatePtHist(FakeRatePt_madgraph);
//       FakeRateFitFunction_madgraph->SetName(
//       (chargeTypeName + fakeTypeString + eventTypeName + "TrackDenominatorFakeRateFunction_Pt_MadgraphWJets").c_str());
//     }
//     if (fitFakeRate) fakeRateFits.push_back(FakeRateFitFunction_madgraph);
//     fakeRateHistograms.push_back(FakeRatePt_madgraph);
//     fakeRateLegendNames.push_back(chargeTypeName + fakeTypeString + eventTypeName + "TrackDenominator Madgraph W+Jets");
    
    //*****************************************************************************************
    //Draw the plots
    //*****************************************************************************************
    drawFakeRatePlots(fakeRateHistograms,fakeRateFits,fakeRateLegendNames,
                      (chargeTypeName + fakeTypeString + eventTypeName + "TrackDenominatorFakeRatePt").c_str(),maxY);

    //*****************************************************************************************
    //save them to the output file
    //*****************************************************************************************
    for (UInt_t i=0; i<fakeRateHistograms.size();i++) {
      //write the histograms. delete any existing one with the same name
      if (file->FindObjectAny(fakeRateHistograms[i]->GetName())) {
        string tmpname = fakeRateHistograms[i]->GetName();        
        file->Delete((tmpname+";*").c_str());
      }

      fakeRateHistograms[i]->SetDirectory(file);
      file->WriteTObject(fakeRateHistograms[i]);

      //write the fit functions. delete any existing one with the same name
      if (fitFakeRate) {
        if (file->FindObjectAny(fakeRateFits[i]->GetName())) {
          string tmpname = fakeRateFits[i]->GetName();        
          file->Delete((tmpname+";*").c_str());
        }
        file->WriteTObject(fakeRateFits[i]);
      }
    }
  }

  file->Close();
  return;

}
/*************************************************************************************
 * createMFOutfile: moves the MLB distributions into an output file for use in 
 *                  R. Nally's MassFit.C code.
 *  input:  the main() arguments array
 *  output: writes to an output file the histograms, in a MassFit.C-readable format 
 *
 *  Structure-wise: can be implemented into class easily.
 ***********************************/
void createMFOutfile(const char* argv[]) {
  TFile *f = new TFile(argv[2]);

  //create the output file we'd like to write histograms to
  TFile *output = new TFile(outfileName, "RECREATE");
  
  //get the filesystem information from the file
  f->cd();
  TList *alokDirs = (TList*) f->GetListOfKeys();

  //create a list of "All" histograms and initialize (TODO)
  TList *allHists = new TList;

  //loop through the directories in the input file
  for(int idir=0; alokDirs->At(idir-1) != alokDirs->Last(); idir++) {
    //if it's not mlb, we don't care
    if(!TString(alokDirs->At(idir)->GetName()).Contains("_Mlb")) continue;
    
    //get the file directory information, its histograms
    TDirectory *cDir  = (TDirectory*) f->Get(alokDirs->At(idir)->GetName());
    TList *alokHistos = (TList*)      cDir->GetListOfKeys();

    //loop through the histograms in the current directory 
    for(int ihisto=0; alokHistos->At(ihisto-1) != alokHistos->Last(); ihisto++) {
      // don't consider the graph objects
      if(TString(alokHistos->At(ihisto)->GetName()).Contains("Graph_")) continue; 

      // clone the histogram, give it a new name
      TString cloneName = formatName(alokHistos->At(ihisto)->GetName(),nominalWidth);
      TH1F *thisto = (TH1F*) cDir->Get(alokHistos->At(ihisto)->GetName());
      TH1F *tclone = (TH1F*) thisto->Clone(cloneName);

      // open the outfile and write the histo in
      output->cd();
      TList *outkeys = (TList*) output->GetListOfKeys();

      // if the histogram already exists, add thisto to the existing one
      // messy, but removes the need for magic
      for(int iout=0; outkeys->At(iout-1) != outkeys->Last(); iout++) {
        if(outkeys->At(iout)->GetName() == cloneName) {
          cout<<" - found another histogram in output with name "<<cloneName<<endl;
          TH1F *theHisto = (TH1F*) output->Get(cloneName);
          cout<<" - got the same histogram from the output file"<<endl;
          TH1F *tHclone  = (TH1F*) theHisto->Clone(cloneName);
          cout<<" - cloned the histogram"<<endl;

          cout<<" - adding in clone"<<endl;
          tclone->Add(tHclone);

          cout<<" - deleting the original histogram from the output file"<<endl;
          output->Delete(cloneName + TString(";1"));
          cout<<" - deleted thing from output file"<<endl;
          cout<<" - tclone looks like "<<tclone<<endl;
        }
      }
      cout<<" - writing the tclone to file"<<endl;
      tclone->Write();

      // reopen the input root file and clean up
      f->cd();
      delete thisto;
      delete tclone;
    }
  }

  f->Close();
  output->cd();
  output->Close();

  // if we want to interpolate, start making more histograms
  if(interpolate) {
    // Have to reopen the outfile because ROOT is odd
    TFile *output2 = new TFile(outfileName, "UPDATE");
    output2->cd();

    std::pair<double,TString> maxPair = *moreFiles.begin();
    double maxWidth = maxPair.first;

    // check that it makes sense to interpolate with our settings
    if(maxWidth <= nominalWidth) {
      cout<<"\n\nERROR: Max width is less than or equal to the nominal width! Exiting."<<endl;
      exit(EXIT_FAILURE);
    }

    // open the input file and loop through the relevant directories
    TFile *maxFile = new TFile(maxPair.second);
    for(int i=0; i<lepsSize; i++) {
      // change directory and get the name of the folder we want to access
      maxFile->cd();
      char a[128];
      sprintf(a, "mlbwa_%s_Mlb", leps[i]);
      TDirectory *tDir = (TDirectory*) maxFile->Get(a);
      TList *alok = tDir->GetListOfKeys();

      // get the maxWidth histogram in this folder, clone and rename it
      TString maxHName = alok->First()->GetName();
      TString maxCloneName = formatName(maxHName, maxWidth);
      TH1F *maxHisto = (TH1F*) tDir->Get(maxHName);
      TH1F *maxClone = (TH1F*) maxHisto->Clone(maxCloneName);

      // write this max histogram to the outfile
      output2->cd();
      maxClone->Write();

      // get the corresponding nominal histogram from the outfile
      TH1F *nomHisto = (TH1F*) output2->Get(formatName(maxHName,nominalWidth));

      TCanvas *c = new TCanvas("");
      nomHisto->Draw();
      c->SaveAs(formatName(maxHName,nominalWidth)+TString(".pdf"));


      // for each interpolation, create a morphed histogram and write to outfile
      for(int i=interpolations; i>0; i--) {
        double tWidth = nominalWidth + i*(maxWidth - nominalWidth)/(interpolations+1);
        TString interpName = formatName(maxHName, tWidth);
        TH1F *interpHisto = (TH1F*) th1fmorph(interpName, interpName,nomHisto,maxHisto,
                                               nominalWidth,maxWidth,tWidth,nomHisto->Integral(),1);
        interpHisto->Write();
      }
    }

    maxFile->cd();
    maxFile->Close();
    output2->cd();
    output2->Close();

    // Otherwise, we want to collect signal histograms of different weights
  } else {
    // Have to reopen the outfile because ROOT is odd
    TFile *output2 = new TFile(outfileName, "UPDATE");
    output2->cd();

    // Loop through the additional files
    for(std::vector<std::pair<double, TString> >::const_iterator pf=moreFiles.begin();
                                                                 pf!=moreFiles.end();
                                                                 pf++) {

        // This is the current file and width
        TFile *curFile = new TFile(pf->second, "READ");
        double curWid  = pf->first;

        // Loop through lepton final states
        for(int i=0; i<lepsSize; i++) {
            curFile->cd();

            // Get the desired directory
            char dirName[128];
            sprintf(dirName, "mlbwa_%s_Mlb", leps[i]);
            TDirectory *curDir = (TDirectory*) curFile->Get(dirName);

            // Get the names of the first histogram in the directory
            //     (we don't want more than one additional signal histo per extra file)
            // Format it with the usual method
            TString histName   = TString(curDir->GetListOfKeys()->First()->GetName());
            TString cloneName  = formatName(histName,curWid);
            
            // Get the mlb histo
            TH1D *curHisto = (TH1D*) curDir->Get(histName)->Clone(cloneName);

            // Write to the outfile
            output2->cd();
            curHisto->Write();
        }

        curFile->Close();
    }

    output2->cd();
    output2->Close();
  }

}
Example #11
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;
}
void prepareDatacardsFast(TString folder, TString template_folder, TString SignalSample, int generated_PDF_set=1, int generated_PDF_member=0, TString WorZ="W", int RecoilCorrVarDiagoParU1orU2fromDATAorMC=0){

  const int m_start = WMass::RecoilCorrIniVarDiagoParU1orU2fromDATAorMC_[RecoilCorrVarDiagoParU1orU2fromDATAorMC];
  const int m_end = WMass::RecoilCorrNVarDiagoParU1orU2fromDATAorMC_[RecoilCorrVarDiagoParU1orU2fromDATAorMC];

  cout << "m_start= " << m_start << " m_end= " << m_end << endl;

  TString original;
  std::vector<TString> tokenized;
  original = WorZ;

  TObjArray* LineColumns = original.Tokenize(",");

  for(int j=0;j<LineColumns->GetEntriesFast();j++)
  {
    tokenized.push_back(((TObjString *)LineColumns->At(j))->GetString());
    // cout << "tokenized["<<j<<"]= " << tokenized[j] << endl;
  }

  for(unsigned int itoken=0; itoken<tokenized.size(); itoken++){

    static const int Nsamples=23;
    enum                             {  DATA, WJetsPowPlus,  WJetsPowNeg,  WJetsMadSig,  WJetsMadFake,  DYJetsPow,  DYJetsMadSig,  DYJetsMadFake,   TTJets,   ZZJets,   WWJets,  WZJets,  QCD, T_s, T_t, T_tW, Tbar_s, Tbar_t, Tbar_tW, EWK, EWKTT, MCDATALIKEPOW, MCDATALIKEMAD  };
    TString samples_str[Nsamples]  = { "DATA" , "WJetsPowPlus", "WJetsPowNeg", "WJetsMadSig", "WJetsMadFake", "DYJetsPow", "DYJetsMadSig", "DYJetsMadFake",  "TTJets",  "ZZJets",  "WWJets", "WZJets",   "QCD", "T_s", "T_t", "T_tW", "Tbar_s", "Tbar_t", "Tbar_tW", "EWK", "EWKTT", "MCDATALIKEPOW", "MCDATALIKEMAD" };
    TString WCharge_str[]={"Pos","Neg"};

    cout << "folder= " << folder << endl;
    cout << "SignalSample= " << SignalSample << endl;

    WorZ = tokenized.at(itoken); // "Z" or "W"
    TString Wlike = WorZ.Contains("W")?"":"like";
    int charge_start = (WMass::WlikeCharge==1 || WorZ.Contains("W"))?0:1;
    int charge_end   = (WMass::WlikeCharge==1)                      ?1:2;
    cout << "WorZ= " << WorZ << endl;

    // TOKENIZE SAMPLES
    TFile* finTemplatesW[Nsamples];
    TH1D *TemplatesW_NonScaled[2][m_end][WMass::KalmanNvariations][WMass::PDF_members][WMass::NFitVar][Nsamples][WMass::etaMuonNSteps][2*WMass::WMassNSteps+1];
    TH2D *TemplatesW_NonScaled_2d[2][m_end][WMass::KalmanNvariations][WMass::PDF_members][WMass::NFitVar-1][Nsamples][WMass::etaMuonNSteps][2*WMass::WMassNSteps+1];

    cout << "LOAD ALL THE HISTOS FROM THE VARIOUS FILES IN MEMORY" << endl;
    for(int isample=0; isample<Nsamples;isample++){
      finTemplatesW[isample] = new TFile(Form("%s/output_%s/%sanalysisOnDATA.root",folder.Data(),samples_str[isample].Data(),WorZ.Data()));
      finTemplatesW[isample]->Print();
      for(int ieta=0; ieta<WMass::etaMuonNSteps; ieta++){
        TString eta_str = Form("%.1f",WMass::etaMaxMuons[ieta]); eta_str.ReplaceAll(".","p");
        for(int jmass=0; jmass<2*WMass::WMassNSteps+1; jmass++){
          // int jWmass = WMass::WMassCentral_MeV-(WMass::WMassNSteps-jmass)*WMass::WMassStep_MeV;
          int jWmass = WorZ.Contains("Z")? WMass::Zmass_values_array[jmass] : WMass::Wmass_values_array[jmass];

          for(int h=0; h<WMass::PDF_members; h++){
            for(int m=m_start; m<m_end; m++){
              for(int n=0; n<WMass::KalmanNvariations; n++){
                int histo2dcounter = 0;
                for(int k=0;k<WMass::NFitVar;k++){
                  for(int c=charge_start;c<charge_end;c++){
                    // TemplatesW[c][m][n][h][k][isample][ieta][jmass] = (TH1D*) finTemplatesW[isample]->Get(Form("hW%s%s_%sNonScaled_8_JetCut_pdf%d-%d%s_eta%s_%d",Wlike.Data(),WCharge_str[c].Data(),WMass::FitVar_str[k].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h, RecoilCorrVarDiagoParU1orU2fromDATAorMC>0?Form("_RecoilCorrVar%d",m):"",eta_str.Data(),jWmass));
                    
                    // cout << "[charge="<<c<<"][recoil_var="<<m<<"][kalman_Var="<<n<<"][pdf="<<h<<"][fitvar="<<k<<"][sample="<<samples_str[isample]<<"][eta="<<ieta<<"][mass="<<jmass<<"]"<<endl;
                    
                    TemplatesW_NonScaled[c][m][n][h][k][isample][ieta][jmass] = (TH1D*) finTemplatesW[isample]->Get(Form("hW%s%s_%sNonScaled_8_JetCut_pdf%d-%d%s%s_eta%s_%d",Wlike.Data(),WCharge_str[c].Data(),WMass::FitVar_str[k].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h, RecoilCorrVarDiagoParU1orU2fromDATAorMC>0?Form("_RecoilCorrVar%d",m):"",WMass::KalmanNvariations>1?Form("_KalmanVar%d",n):"",eta_str.Data(),jWmass));
                    // if(TemplatesW_NonScaled[c][m][n][h][k][isample][ieta][jmass]) TemplatesW_NonScaled[c][m][n][h][k][isample][ieta][jmass]->Print();
                    
                    for(int k2=k+1;k2<WMass::NFitVar-1;k2++){
                      if(k==k2 || k==3) continue;
                      // cout << "searching for " << Form("hWlike%s_%svs%s_8_JetCut_pdf%d-%d%s%s_eta%s_%d",WCharge_str[c].Data(),WMass::FitVar_str[k].Data(),WMass::FitVar_str[k2].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h,RecoilCorrVarDiagoParU1orU2fromDATAorMC>0?Form("_RecoilCorrVar%d",m):"",WMass::KalmanNvariations>1?Form("_KalmanVar%d",n):"",eta_str.Data(),jWmass) << endl;
                      TemplatesW_NonScaled_2d[c][m][n][h][k][isample][ieta][jmass] = (TH2D*) finTemplatesW[isample]->Get(Form("hWlike%s_%svs%s_8_JetCut_pdf%d-%d%s%s_eta%s_%d",WCharge_str[c].Data(),WMass::FitVar_str[k].Data(),WMass::FitVar_str[k2].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h,RecoilCorrVarDiagoParU1orU2fromDATAorMC>0?Form("_RecoilCorrVar%d",m):"",WMass::KalmanNvariations>1?Form("_KalmanVar%d",n):"",eta_str.Data(),jWmass));
                      if(TemplatesW_NonScaled_2d[c][m][n][h][k][isample][ieta][jmass]){
                        cout << "k= " << k << endl;
                        TemplatesW_NonScaled_2d[c][m][n][h][k][isample][ieta][jmass]->Print();
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }

    cout << "RESCALE ALL THE HISTOS IN MEMORY" << endl;
    for(int isample=0; isample<Nsamples;isample++){
      for(int ieta=0; ieta<WMass::etaMuonNSteps; ieta++){
        for(int jmass=0; jmass<2*WMass::WMassNSteps+1; jmass++){
          for(int h=0; h<WMass::PDF_members; h++){
            for(int m=m_start; m<m_end; m++){
              for(int n=0; n<WMass::KalmanNvariations; n++){
                for(int k=0;k<WMass::NFitVar;k++){
                  for(int c=charge_start;c<charge_end;c++){

                    if(TemplatesW_NonScaled[c][m][n][h][k][isample][ieta][jmass]){
                      double int_hist_data = 0;
                      if(TemplatesW_NonScaled[c][m_start][0][0][k][isample][ieta][WMass::WMassNSteps])
                        int_hist_data =TemplatesW_NonScaled[c][m_start][0][0][k][isample][ieta][WMass::WMassNSteps]->Integral();
                      double int_hist_mcdatalike = TemplatesW_NonScaled[c][m][n][h][k][isample][ieta][jmass]->Integral();
                      double norm_factor_to_match_data = int_hist_mcdatalike>0 && int_hist_data>0 ? int_hist_data/int_hist_mcdatalike : 1;

                      TemplatesW_NonScaled[c][m][n][h][k][isample][ieta][jmass]->Scale(norm_factor_to_match_data);
                      cout <<"1 c "<<c<<" m "<<m<<" n "<<n<<" h "<<h<<" k "<<k<<" isample "<<samples_str[isample]<<" ieta "<<ieta<<" jmass "<<jmass<<" norm "<<norm_factor_to_match_data<<endl;
                      // TemplatesW_NonScaled[c][m][n][h][k][isample][ieta][jmass]->Print();
                    }
                    for(int k2=k+1;k2<WMass::NFitVar-1;k2++){
                      if(k==k2 || k==3) continue;
                      if(TemplatesW_NonScaled_2d[c][m][n][h][k][isample][ieta][jmass]){
                        double int_hist_data = 0;
                        if(TemplatesW_NonScaled_2d[c][m_start][0][0][k][isample][ieta][WMass::WMassNSteps])
                          int_hist_data =TemplatesW_NonScaled_2d[c][m_start][0][0][k][isample][ieta][WMass::WMassNSteps]->Integral();
                        double int_hist_mcdatalike = TemplatesW_NonScaled_2d[c][m][n][h][k][isample][ieta][jmass]->Integral();
                        double norm_factor_to_match_data = int_hist_mcdatalike>0 && int_hist_data>0 ? int_hist_data/int_hist_mcdatalike : 1;

                        TemplatesW_NonScaled_2d[c][m][n][h][k][isample][ieta][jmass]->Scale(norm_factor_to_match_data);
                        cout <<"2 c "<<c<<" m "<<m<<" n "<<n<<" h "<<h<<" k "<<k<<" isample "<<samples_str[isample]<<" ieta "<<ieta<<" jmass "<<jmass<<" norm "<<norm_factor_to_match_data<<endl;
                        // TemplatesW_NonScaled_2d[c][m][n][h][k][isample][ieta][jmass]->Print();
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }

    int histcounter = 0;
    int dcardcounter = 0;

    cout << "PROCESS THE HISTOS AND STORE THEM IN A SUITABLE FILE, STORE NORMALIZATIONS IN A SEPARATE TEXT FILE" << endl;
    TFile *foutDATA = new TFile(Form("%s/DataCards/datacards_DATA%s.root",folder.Data(),WorZ.Contains("W")?"":"_Wlike"),"RECREATE");

    for(int c=charge_start; c<charge_end; c++){
      ofstream outTXTfile;
      outTXTfile.open(Form("%s/DataCards/datacard_Wmass_Mu%s%s_normalizations.txt",folder.Data(),Wlike.Data(),WCharge_str[c].Data()));

      // LOOP OVER MAX-ETA BINS

      for(int ieta=0; ieta<WMass::etaMuonNSteps; ieta++){
        TString eta_str = Form("%.1f",WMass::etaMaxMuons[ieta]); eta_str.ReplaceAll(".","p");
        outTXTfile << "-----------------------" << endl;
        outTXTfile << "-----------------------" << endl;
        outTXTfile << "Mu"<<Wlike.Data()<<WCharge_str[c].Data()<< " with |eta| < " << WMass::etaMaxMuons[ieta] << endl;
        outTXTfile << "-----------------------" << endl;
        outTXTfile << "-----------------------" << endl;
        outTXTfile << endl;
        TDirectory *channel_dir = foutDATA->mkdir(Form("Mu%s%s_eta%s",Wlike.Data(),WCharge_str[c].Data(),eta_str.Data()));
        foutDATA->cd(Form("Mu%s%s_eta%s",Wlike.Data(),WCharge_str[c].Data(),eta_str.Data()));

        //LOOP OVER w MASS BINS
        for(int jmass=0; jmass<2*WMass::WMassNSteps+1; jmass++){
          // int jWmass = WMass::WMassCentral_MeV-(WMass::WMassNSteps-jmass)*WMass::WMassStep_MeV;
          int jWmass = WorZ.Contains("Z")? WMass::Zmass_values_array[jmass] : WMass::Wmass_values_array[jmass];

          // double fitrange_Scaling = 1;

          cout << "W"<<Wlike.Data()<<WCharge_str[c]<<" eta cut " << WMass::etaMaxMuons[ieta]<< " jWmass= " << jWmass; fflush(stdout);
          TDirectory *mass_dir = channel_dir->mkdir(Form("%d",jWmass));
          mass_dir->cd();

          for(int h=0; h<WMass::PDF_members; h++){
            cout << " PDF " << (WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets) << "-" << h << endl;
            for(int m=m_start; m<m_end; m++){
              for(int n=0; n<WMass::KalmanNvariations; n++){
                if(RecoilCorrVarDiagoParU1orU2fromDATAorMC>0) cout << "Recoil eigen " << m << '\t'; fflush(stdout);
                if(WMass::KalmanNvariations>1) cout << "KalmanVar " << n << '\t'; fflush(stdout);
                // gDirectory->pwd();
                outTXTfile << "-----------------------" << endl;
                outTXTfile << "Mass hypothesis  " << jWmass << " PDF " << Form("%d-%d%s",WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h,RecoilCorrVarDiagoParU1orU2fromDATAorMC>0?Form(" RecoilCorrVar%d",m):"") << endl;
                outTXTfile << "-----------------------" << endl;
                outTXTfile << endl;

                TString Z_histoname[2*Nsamples], W_histoname[2*Nsamples];
                TString Z_histoname_NonScaled[2*Nsamples], W_histoname_NonScaled[2*Nsamples], W_histoname_NonScaled_2d[2*Nsamples];
                // double Z_integrals[2*Nsamples];
                double W_integrals[2*Nsamples];

                //LOOP OVER THE SAMPLES
                for(int isample=0; isample<Nsamples;isample++){
                  for(int k=0;k<WMass::NFitVar;k++){

                    if(!TemplatesW_NonScaled[c][m][n][h][k][isample][ieta][jmass]) continue;
                    histcounter++;

                    // DECLARE NEW HISTOS
                    TH1D* Wtempl_NonScaled;

                    // To BE CHECKED
                    // W_histoname[isample] = samples_str[isample] == "DATA" ? Form("data_obs_W%s%s_%s",Wlike.Data(),WCharge_str[c].Data(),WMass::FitVar_str[k].Data()) : Form("W%s%s_%s_%s_pdf%d-%d%s",Wlike.Data(),WCharge_str[c].Data(),samples_str[isample].Data(),WMass::FitVar_str[k].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h, RecoilCorrVarDiagoParU1orU2fromDATAorMC>0?Form("_RecoilCorrVar%d",m):"");
                    // Wtempl=new TH1D(W_histoname[isample],W_histoname[isample],TemplatesW[c][m][n][h][k][isample][ieta][jmass]->GetXaxis()->FindBin(xmax*fitrange_Scaling)-TemplatesW[c][m][n][h][k][isample][ieta][jmass]->GetXaxis()->FindBin(xmin*fitrange_Scaling),xmin*fitrange_Scaling,xmax*fitrange_Scaling);
                    W_histoname_NonScaled[isample] = samples_str[isample] == "DATA" ? Form("data_obs_W%s%s_%sNonScaled",Wlike.Data(),WCharge_str[c].Data(),WMass::FitVar_str[k].Data()) : Form("W%s%s_%s_%sNonScaled_pdf%d-%d%s%s",Wlike.Data(),WCharge_str[c].Data(),samples_str[isample].Data(),WMass::FitVar_str[k].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h, RecoilCorrVarDiagoParU1orU2fromDATAorMC>0?Form("_RecoilCorrVar%d",m):"",WMass::KalmanNvariations>1?Form("_KalmanVar%d",n):"");
                    // Wtempl_NonScaled=new TH1D(W_histoname_NonScaled[isample],W_histoname_NonScaled[isample],50, WMass::fit_xmin[k],WMass::fit_xmax[k]);
                    Wtempl_NonScaled=(TH1D*)TemplatesW_NonScaled[c][m][n][h][k][isample][ieta][jmass]->Clone(W_histoname_NonScaled[isample]);
                    Wtempl_NonScaled->SetName(W_histoname_NonScaled[isample]);
                    cout << "W_histoname_NonScaled[isample]="<<W_histoname_NonScaled[isample]<<endl;
                    Wtempl_NonScaled->SetTitle(W_histoname_NonScaled[isample]);

                    Wtempl_NonScaled->Write();

                    int nspaces1 = 50 - W_histoname_NonScaled[isample].Length();
                    // outTXTfile << Wtempl->GetName();
                    outTXTfile << Wtempl_NonScaled->GetName();
                    for(int ispace=0;ispace<nspaces1;ispace++) outTXTfile << " ";
                    // W_integrals[isample] = Wtempl->Integral();
                    W_integrals[isample] = Wtempl_NonScaled->Integral();
                    outTXTfile << W_integrals[isample] << endl;

                    Wtempl_NonScaled->Delete();

                    // 2D
                    for(int k2=k+1;k2<WMass::NFitVar-1;k2++){
                      if(k==k2 || k==3) continue;
                      if(TemplatesW_NonScaled_2d[c][m][n][h][k][isample][ieta][jmass]){
                        
                        // DECLARE NEW HISTOS

                        W_histoname_NonScaled_2d[isample] = samples_str[isample] == "DATA" ? Form("data_obs_W%s%s_%svs%s",Wlike.Data(),WCharge_str[c].Data(),WMass::FitVar_str[k].Data(),WMass::FitVar_str[k2].Data()) : Form("W%s%s_%s_%svs%s_pdf%d-%d%s%s",Wlike.Data(),WCharge_str[c].Data(),samples_str[isample].Data(),WMass::FitVar_str[k].Data(),WMass::FitVar_str[k2].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h, RecoilCorrVarDiagoParU1orU2fromDATAorMC>0?Form("_RecoilCorrVar%d",m):"",WMass::KalmanNvariations>1?Form("_KalmanVar%d",n):"");
                        cout << "W_histoname_NonScaled_2d[isample]= " << W_histoname_NonScaled_2d[isample] << endl;
                        // Wtempl_NonScaled_2d_unrolled=(TH2D*)TemplatesW_NonScaled_2d[c][m][n][h][k][isample][ieta][jmass]->Clone(W_histoname_NonScaled_2d[isample]);
                        int binsx = TemplatesW_NonScaled_2d[c][m][n][h][k][isample][ieta][jmass]->GetNbinsX();
                        int binsy = TemplatesW_NonScaled_2d[c][m][n][h][k][isample][ieta][jmass]->GetNbinsY();
                        cout << "binsx= " << binsx << " binsy= " << binsy << " binsx*binsy= " << binsx*binsy << endl;
                        TH1D* Wtempl_NonScaled_2d_unrolled = new TH1D(W_histoname_NonScaled_2d[isample],W_histoname_NonScaled_2d[isample],(binsx*binsy), 0, (binsx*binsy) );
                        cout << "Wtempl_NonScaled_2d_unrolled->GetNbinsX()= " << Wtempl_NonScaled_2d_unrolled->GetNbinsX() << endl;
                        cout << "Wtempl_NonScaled_2d_unrolled->GetNbinsY()= " << Wtempl_NonScaled_2d_unrolled->GetNbinsX() << endl;
                        cout << "TemplatesW_NonScaled_2d[c][m][n][h][k][isample][ieta][jmass]->GetNbinsX()= " << TemplatesW_NonScaled_2d[c][m][n][h][k][isample][ieta][jmass]->GetNbinsX() << endl;
                        cout << "TemplatesW_NonScaled_2d[c][m][n][h][k][isample][ieta][jmass]->GetNbinsY()= " << TemplatesW_NonScaled_2d[c][m][n][h][k][isample][ieta][jmass]->GetNbinsX() << endl;
                        int new_bin=1;
                        for(int biny=1; biny<binsy+1; biny++){
                          for(int binx=1; binx<binsx+1; binx++){
                            Wtempl_NonScaled_2d_unrolled->SetBinContent(new_bin,TemplatesW_NonScaled_2d[c][m][n][h][k][isample][ieta][jmass]->GetBinContent(binx,biny));
                            new_bin++;
                          }
                        }
                        // cout << "W_histoname_NonScaled_2d[isample]="<<W_histoname_NonScaled_2d[isample]<<endl;

                        Wtempl_NonScaled_2d_unrolled->Print();
                        Wtempl_NonScaled_2d_unrolled->Write();
                        TemplatesW_NonScaled_2d[c][m][n][h][k][isample][ieta][jmass]->SetName(Form("%s_2d",W_histoname_NonScaled_2d[isample].Data()));
                        TemplatesW_NonScaled_2d[c][m][n][h][k][isample][ieta][jmass]->Write();

                        int nspaces2 = 50 - W_histoname_NonScaled_2d[isample].Length();
                        outTXTfile << Wtempl_NonScaled_2d_unrolled->GetName();
                        for(int ispace=0;ispace<nspaces2;ispace++) outTXTfile << " ";
                        W_integrals[isample] = Wtempl_NonScaled_2d_unrolled->Integral();
                        outTXTfile << W_integrals[isample] << endl;

                        Wtempl_NonScaled_2d_unrolled->Delete();
                      }
                    }
                  }
                }
                outTXTfile << endl;

              }
            }
          }
        }
        cout << endl;
        outTXTfile << endl;
        outTXTfile << endl;
      }


      for(int ieta=0; ieta<WMass::etaMuonNSteps; ieta++){
        TString eta_str = Form("%.1f",WMass::etaMaxMuons[ieta]); eta_str.ReplaceAll(".","p");
        for(int jmass=0; jmass<2*WMass2::WMassNSteps+1; jmass++){
          int jWmass = WorZ.Contains("Z")? WMass2::Zmass_values_array[jmass] : WMass2::Wmass_values_array[jmass];
          for(int h=0; h<WMass::PDF_members; h++){
            for(int m=m_start; m<m_end; m++){
              for(int n=0; n<WMass::KalmanNvariations; n++){

                // PREPARE DATACARD
                TString SigSample_str = "MadSig";
                // PowPlus,  PowNeg,  MadSig,  Pow,  MadSig
                if(SignalSample.Contains("POWHEG")){
                  SigSample_str = "Pow";
                    if(WorZ.Contains("W")) SigSample_str+=WCharge_str[c];
                }

                // PREPARE DATACARD NON SCALED WITH BACKGROUND WITHOUT Z DATADRIVEN
                for(int k=0;k<WMass::NFitVar;k++){

                  ofstream Datacard;
                  cout << "datacard " << Form("%s/DataCards/dummy_datacard_Wmass_Mu%s%s_pdf%d-%d%s%s_eta%s_%d_%sNonScaled.txt",folder.Data(),Wlike.Data(),WCharge_str[c].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h, RecoilCorrVarDiagoParU1orU2fromDATAorMC>0?Form("_RecoilCorrVar%d",m):"",WMass::KalmanNvariations>1?Form("_KalmanVar%d",n):"",eta_str.Data(),jWmass,WMass::FitVar_str[k].Data()) << endl;
                  Datacard.open(Form("%s/DataCards/dummy_datacard_Wmass_Mu%s%s_pdf%d-%d%s%s_eta%s_%d_%sNonScaled.txt",folder.Data(),Wlike.Data(),WCharge_str[c].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h, RecoilCorrVarDiagoParU1orU2fromDATAorMC>0?Form("_RecoilCorrVar%d",m):"",WMass::KalmanNvariations>1?Form("_KalmanVar%d",n):"",eta_str.Data(),jWmass,WMass::FitVar_str[k].Data()));

                  if(template_folder.Length()<5){
                    Datacard << "shapes   *          *   datacards_DATA"<<(WorZ.Contains("W")?"":"_Wlike")<<".root $CHANNEL/$MASS/$PROCESS $CHANNEL/$MASS/$PROCESS_$SYSTEMATIC" << endl;
                  }else{
                    Datacard << "shapes   *          *   "<<Form("../%s/DataCards/datacards_DATA%s.root",template_folder.Data(),WorZ.Contains("W")?"":"_Wlike") << " $CHANNEL/$MASS/$PROCESS $CHANNEL/$MASS/$PROCESS_$SYSTEMATIC" << endl;
                  }

                  // Datacard << "shapes   data_obs   *   datacards_DATA"<<(WorZ.Contains("W")?"":"_Wlike")<<".root $CHANNEL/"<<(WMass2::WMassCentral_MeV)<<Form("/W%s%s_MCDATALIKE%s_%sNonScaled_pdf%d-%d%s",Wlike.Data(),WCharge_str[c].Data(),SignalSample.Contains("POWHEG")?"POW":"MAD",WMass::FitVar_str[k].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h, RecoilCorrVarDiagoParU1orU2fromDATAorMC>0?Form("_RecoilCorrVar%d",m):"") << endl;
                  Datacard << "shapes   data_obs   *   datacards_DATA"<<(WorZ.Contains("W")?"":"_Wlike")<<".root $CHANNEL/"<<(WorZ.Contains("W") ? WMass2::WMassCentral_MeV : WMass2::ZMassCentral_MeV)<<Form("/W%s%s_MCDATALIKE%s_%sNonScaled_pdf%d-%d%s%s",Wlike.Data(),WCharge_str[c].Data(),SignalSample.Contains("POWHEG")?"POW":"MAD",WMass::FitVar_str[k].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h, RecoilCorrVarDiagoParU1orU2fromDATAorMC>0?Form("_RecoilCorrVar%d",m):"",WMass::KalmanNvariations>1?Form("_KalmanVar%d",n):"") << endl;

                  if(template_folder.Length()<5){
                    // Datacard << Form("shapes   W%s%s_%sJets%s_%sNonScaled_ALT   *   datacards_DATA%s.root $CHANNEL/",Wlike.Data(),WCharge_str[c].Data(),WorZ.Contains("W")?"W":"DY",SigSample_str.Data(),WMass::FitVar_str[k].Data(),WorZ.Contains("W")?"":"_Wlike")<<(WMass2::WMassCentral_MeV-WMass2::WMassNSteps*WMass2::WMassStep_MeV)<<Form("/W%s%s_%sJets%s_%sNonScaled_pdf%d-%d%s",Wlike.Data(),WCharge_str[c].Data(),WorZ.Contains("W")?"W":"DY",SigSample_str.Data(),WMass::FitVar_str[k].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,0, RecoilCorrVarDiagoParU1orU2fromDATAorMC>0?Form("_RecoilCorrVar%d",m):"") << endl;
                    Datacard << Form("shapes   W%s%s_%sJets%s_%sNonScaled_ALT   *   datacards_DATA%s.root $CHANNEL/",Wlike.Data(),WCharge_str[c].Data(),WorZ.Contains("W")?"W":"DY",SigSample_str.Data(),WMass::FitVar_str[k].Data(),WorZ.Contains("W")?"":"_Wlike")<<(WorZ.Contains("Z")? WMass::Zmass_values_array[0] : WMass::Wmass_values_array[0])<<Form("/W%s%s_%sJets%s_%sNonScaled_pdf%d-%d%s",Wlike.Data(),WCharge_str[c].Data(),WorZ.Contains("W")?"W":"DY",SigSample_str.Data(),WMass::FitVar_str[k].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,0, "") << endl;
                  }else{
                    // Datacard << Form("shapes   W%s%s_%sJets%s_%sNonScaled_ALT   *   ../%s/DataCards/datacards_DATA%s.root $CHANNEL/",Wlike.Data(),WCharge_str[c].Data(),WorZ.Contains("W")?"W":"DY",SigSample_str.Data(),WMass::FitVar_str[k].Data(),template_folder.Data(),WorZ.Contains("W")?"":"_Wlike")<<(WMass2::WMassCentral_MeV-WMass2::WMassNSteps*WMass2::WMassStep_MeV)<<Form("/W%s%s_%sJets%s_%sNonScaled_pdf%d-%d%s",Wlike.Data(),WCharge_str[c].Data(),WorZ.Contains("W")?"W":"DY",SigSample_str.Data(),WMass::FitVar_str[k].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,0, "") << endl;
                    Datacard << Form("shapes   W%s%s_%sJets%s_%sNonScaled_ALT   *   ../%s/DataCards/datacards_DATA%s.root $CHANNEL/",Wlike.Data(),WCharge_str[c].Data(),WorZ.Contains("W")?"W":"DY",SigSample_str.Data(),WMass::FitVar_str[k].Data(),template_folder.Data(),WorZ.Contains("W")?"":"_Wlike")<<(WorZ.Contains("Z")? WMass::Zmass_values_array[0] : WMass::Wmass_values_array[0])<<Form("/W%s%s_%sJets%s_%sNonScaled_pdf%d-%d%s",Wlike.Data(),WCharge_str[c].Data(),WorZ.Contains("W")?"W":"DY",SigSample_str.Data(),WMass::FitVar_str[k].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,0, "") << endl;

                  }

                  Datacard << "---------------------------------------------------------------------------------" << endl;
                  Datacard << "bin            Mu"<<Wlike.Data()<<WCharge_str[c].Data()<<"_eta"<<eta_str<< endl;
                  Datacard << "observation          -1 " << endl;
                  Datacard << "---------------------------------------------------------------------------------" << endl;
                  Datacard << "bin            Mu"<<Wlike.Data()<<WCharge_str[c].Data()<<"_eta"<<eta_str<<"          Mu"<<Wlike.Data()<<WCharge_str[c].Data()<<"_eta"<<eta_str<<"         Mu"<<Wlike.Data()<<WCharge_str[c].Data()<<"_eta"<<eta_str<< endl;
                  Datacard << Form("process        W%s%s_%sJets%s_%sNonScaled_pdf%d-%d%s        W%s%s_%sJets%s_%sNonScaled_ALT        W%s%s_EWKTT_%sNonScaled_pdf%d-%d%s        ",Wlike.Data(),WCharge_str[c].Data(),WorZ.Contains("W")?"W":"DY",SigSample_str.Data(),WMass::FitVar_str[k].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,0, "",Wlike.Data(),WCharge_str[c].Data(),WorZ.Contains("W")?"W":"DY",SigSample_str.Data(),WMass::FitVar_str[k].Data(),Wlike.Data(),WCharge_str[c].Data(),WMass::FitVar_str[k].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,0, "") << endl;
                  Datacard << "process              -1                            0                            1" << endl;
                  Datacard << "rate                 -1                           -1                           -1" << endl;
                  Datacard.close();

                  dcardcounter++;
                  
                  // datacards for 2d fits
                  for(int k2=k+1;k2<WMass::NFitVar-1;k2++){
                    if(k==k2 || k==3) continue;
                    
                    // ofstream Datacard;
                    cout << "datacard2d = " << Form("%s/DataCards/dummy_datacard_Wmass_Mu%s%s_pdf%d-%d%s%s_eta%s_%d_%svs%s.txt",folder.Data(),Wlike.Data(),WCharge_str[c].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h, RecoilCorrVarDiagoParU1orU2fromDATAorMC>0?Form("_RecoilCorrVar%d",m):"",WMass::KalmanNvariations>1?Form("_KalmanVar%d",n):"",eta_str.Data(),jWmass,WMass::FitVar_str[k].Data(),WMass::FitVar_str[k2].Data()) << endl;
                    Datacard.open(Form("%s/DataCards/dummy_datacard_Wmass_Mu%s%s_pdf%d-%d%s%s_eta%s_%d_%svs%s.txt",folder.Data(),Wlike.Data(),WCharge_str[c].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h, RecoilCorrVarDiagoParU1orU2fromDATAorMC>0?Form("_RecoilCorrVar%d",m):"",WMass::KalmanNvariations>1?Form("_KalmanVar%d",n):"",eta_str.Data(),jWmass,WMass::FitVar_str[k].Data(),WMass::FitVar_str[k2].Data()));

                    if(template_folder.Length()<5){
                      Datacard << "shapes   *          *   datacards_DATA"<<(WorZ.Contains("W")?"":"_Wlike")<<".root $CHANNEL/$MASS/$PROCESS $CHANNEL/$MASS/$PROCESS_$SYSTEMATIC" << endl;
                    }else{
                      Datacard << "shapes   *          *   "<<Form("../%s/DataCards/datacards_DATA%s.root",template_folder.Data(),WorZ.Contains("W")?"":"_Wlike") << " $CHANNEL/$MASS/$PROCESS $CHANNEL/$MASS/$PROCESS_$SYSTEMATIC" << endl;
                    }

                    Datacard << "shapes   data_obs   *   datacards_DATA"<<(WorZ.Contains("W")?"":"_Wlike")<<".root $CHANNEL/"<<(WorZ.Contains("W") ? WMass2::WMassCentral_MeV : WMass2::ZMassCentral_MeV)<<Form("/W%s%s_MCDATALIKE%s_%svs%s_pdf%d-%d%s%s",Wlike.Data(),WCharge_str[c].Data(),SignalSample.Contains("POWHEG")?"POW":"MAD",WMass::FitVar_str[k].Data(),WMass::FitVar_str[k2].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h, RecoilCorrVarDiagoParU1orU2fromDATAorMC>0?Form("_RecoilCorrVar%d",m):"",WMass::KalmanNvariations>1?Form("_KalmanVar%d",n):"") << endl;

                    if(template_folder.Length()<5){
                      Datacard << Form("shapes   W%s%s_%sJets%s_%svs%s_ALT   *   datacards_DATA%s.root $CHANNEL/",Wlike.Data(),WCharge_str[c].Data(),WorZ.Contains("W")?"W":"DY",SigSample_str.Data(),WMass::FitVar_str[k].Data(),WMass::FitVar_str[k2].Data(),WorZ.Contains("W")?"":"_Wlike")<<(WorZ.Contains("Z")? WMass::Zmass_values_array[0] : WMass::Wmass_values_array[0])<<Form("/W%s%s_%sJets%s_%svs%s_pdf%d-%d%s",Wlike.Data(),WCharge_str[c].Data(),WorZ.Contains("W")?"W":"DY",SigSample_str.Data(),WMass::FitVar_str[k].Data(),WMass::FitVar_str[k2].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,0, "") << endl;
                    }else{
                      Datacard << Form("shapes   W%s%s_%sJets%s_%svs%s_ALT   *   ../%s/DataCards/datacards_DATA%s.root $CHANNEL/",Wlike.Data(),WCharge_str[c].Data(),WorZ.Contains("W")?"W":"DY",SigSample_str.Data(),WMass::FitVar_str[k].Data(),WMass::FitVar_str[k2].Data(),template_folder.Data(),WorZ.Contains("W")?"":"_Wlike")<<(WorZ.Contains("Z")? WMass::Zmass_values_array[0] : WMass::Wmass_values_array[0])<<Form("/W%s%s_%sJets%s_%s_pdf%d-%d%s",Wlike.Data(),WCharge_str[c].Data(),WorZ.Contains("W")?"W":"DY",SigSample_str.Data(),WMass::FitVar_str[k].Data(),WMass::FitVar_str[k2].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,0, "") << endl;

                    }

                    Datacard << "---------------------------------------------------------------------------------" << endl;
                    Datacard << "bin            Mu"<<Wlike.Data()<<WCharge_str[c].Data()<<"_eta"<<eta_str<< endl;
                    Datacard << "observation          -1 " << endl;
                    Datacard << "---------------------------------------------------------------------------------" << endl;
                    Datacard << "bin            Mu"<<Wlike.Data()<<WCharge_str[c].Data()<<"_eta"<<eta_str<<"          Mu"<<Wlike.Data()<<WCharge_str[c].Data()<<"_eta"<<eta_str<<"         Mu"<<Wlike.Data()<<WCharge_str[c].Data()<<"_eta"<<eta_str<< endl;
                    Datacard << Form("process        W%s%s_%sJets%s_%svs%s_pdf%d-%d%s        W%s%s_%sJets%s_%svs%s_ALT        W%s%s_EWKTT_%svs%s_pdf%d-%d%s        ",Wlike.Data(),WCharge_str[c].Data(),WorZ.Contains("W")?"W":"DY",SigSample_str.Data(),WMass::FitVar_str[k].Data(),WMass::FitVar_str[k2].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,0, "",Wlike.Data(),WCharge_str[c].Data(),WorZ.Contains("W")?"W":"DY",SigSample_str.Data(),WMass::FitVar_str[k].Data(),WMass::FitVar_str[k2].Data(),Wlike.Data(),WCharge_str[c].Data(),WMass::FitVar_str[k].Data(),WMass::FitVar_str[k2].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,0, "") << endl;
                    Datacard << "process              -1                            0                            1" << endl;
                    Datacard << "rate                 -1                           -1                           -1" << endl;
                    Datacard.close();
                  }
                }
              }
            }
          }
        }
      }

      outTXTfile.close();
    }

    foutDATA->Write();
    foutDATA->Close();
    foutDATA->Delete();

    cout << "Program ended, " << histcounter << " histograms found and " << dcardcounter << " datacards written" << endl;

  }
}
void merge_results(int generated_PDF_set=1, int generated_PDF_member=0){

  TString     WCharge_str[]={"Pos","Neg"};
  TRandom3 *initmass = new TRandom3(0); 

  gStyle->SetOptStat(0);
  
  TFile *fout = new TFile(Form("likelihood_results.root"),"RECREATE");
  
    TGraph *result;
    TCanvas*c_chi2;
    TF1*ffit[3][2];
    // TGraph *result_NonScaled[WMass::PDF_members][3];
    TGraph *result_NonScaled[WMass::NtoysMomCorr][WMass::PDF_members][3][2];
    double deltaM[WMass::NtoysMomCorr][WMass::PDF_members][3][2];
    double deltaMmin[3][2]={{0}},deltaMmax[3][2]={{0}};
    double deltaMnegSummed[3][2]={{0}},deltaMposSummed[3][2]={{0}},deltaMSummed[3][2]={{0}},deltaMJuan[3][2]={{0}};
    TH1D*h_deltaM_PDF[3][2];
    TGraphErrors*g_deltaM_PDF[3][2];

  for(int c=0; c<2; c++){
    cout <<"merging W " << WCharge_str[c].Data() << endl;
    
    if(WMass::PDF_members>1 || WMass::NtoysMomCorr>1){
      for(int k=0;k<3;k++){
        TString eta_str = Form("%.1f",WMass::etaMaxMuons[0]); eta_str.ReplaceAll(".","p");

        g_deltaM_PDF[k][c] = new TGraphErrors();
        g_deltaM_PDF[k][c]->SetName(Form("g_deltaM_PDF_W%s_%sNonScaled_eta%s",WCharge_str[c].Data(),WMass::FitVar_str[k].Data(),eta_str.Data()));
        g_deltaM_PDF[k][c]->SetTitle(Form("g_deltaM_PDF_W%s_%sNonScaled_eta%s",WCharge_str[c].Data(),WMass::FitVar_str[k].Data(),eta_str.Data()));
        g_deltaM_PDF[k][c]->SetMarkerStyle(20);
        h_deltaM_PDF[k][c] = new TH1D(Form("h_deltaM_PDF_W%s_%sNonScaled_eta%s",WCharge_str[c].Data(),WMass::FitVar_str[k].Data(),eta_str.Data()),Form("h_deltaM_PDF_%sNonScaled_eta%s",WMass::FitVar_str[k].Data(),eta_str.Data()),200,-50,50);

      }
    }
    
    for(int h=0; h<WMass::PDF_members; h++){
      for(int m=0; m<WMass::NtoysMomCorr; m++){
        TString toys_str = "";
        if(WMass::NtoysMomCorr>1) toys_str = Form("_MomCorrToy%d",m);
        // for(int i=0; i<WMass::etaMuonNSteps; i++){
        cout << "using pdf " << (WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets) << "-"<<h<< endl;
        
        for(int i=0; i<1; i++){
          TString eta_str = Form("%.1f",WMass::etaMaxMuons[i]); eta_str.ReplaceAll(".","p");
          cout << "merging pdf eta bin= " << i << endl;
          
          for(int k=0;k<3;k++){

            cout << "variable= " << k << endl;
          
            int npoint=0;

            // result = new TGraph();
            // result->SetName(Form("likelihood_results_%s_eta%s",WMass::FitVar_str[k].Data(),eta_str.Data()));
            // result->SetTitle(Form("likelihood_results_%s_eta%s",WMass::FitVar_str[k].Data(),eta_str.Data()));

            result_NonScaled[m][h][k][c] = new TGraph();
            result_NonScaled[m][h][k][c]->SetName(Form("likelihood_result_W%s_%sNonScaled_pdf%d-%d%s_eta%s",WCharge_str[c].Data(),WMass::FitVar_str[k].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h,toys_str.Data(),eta_str.Data()));
            result_NonScaled[m][h][k][c]->SetTitle(Form("likelihood_result_W%s_%sNonScaled_pdf%d-%d%s_eta%s",WCharge_str[c].Data(),WMass::FitVar_str[k].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h,toys_str.Data(),eta_str.Data()));

            std::vector<double> l_res;
            double lmin=0, lmax=0, deriv1=0, deriv2=0, deriv3=0;

            for(int j=0; j<2*WMass::WMassNSteps+1; j++){
              int jWmass = WMass::WMassCentral_MeV-(WMass::WMassNSteps-j)*WMass::WMassStep_MeV;
          
              // std::ifstream fileNames(Form("dummy_datacard_Wmass_MuPos_eta%s_%d.log",eta_str.Data(),jWmass));
              string StringFromFile;
              TString TStringFromFile;
              double likelihood_val;
              int ncol;
              // while (!fileNames.eof()){
                // getline (fileNames,StringFromFile);
                // TStringFromFile = StringFromFile.c_str();
                // if(TStringFromFile.Contains("nll S+B ->")){
                  // break;
                // }
              // }
              // TObjArray* LineColumns = TStringFromFile.Tokenize(" ");
              // ncol = LineColumns->GetEntries();
              // if(ncol<3){
                // cout << Form("problem while analyzing fit result in dummy_datacard_Wmass_MuPos_eta%s_%d.log",eta_str.Data(),jWmass) << endl;
                // return;
              // }
              // TString str_icol = ((TObjString *)LineColumns->At(3))->GetString();
              // likelihood_val = (double) (str_icol.Atof());
              // if(likelihood_val<0) result->SetPoint(npoint,jWmass,likelihood_val);
              
              // cout << Form("dummy_datacard_Wmass_MuPos_pdf%d-%d%s_eta%s_%d_%sNonScaled.log",WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h,(WMass::NtoysMomCorr>1?Form("_MomCorrToy%d",m):""),eta_str.Data(),jWmass,WMass::FitVar_str[k].Data()) << endl;
              TString test1 = Form("dummy_datacard_Wmass_Mu%s_pdf%d-%d%s_eta%s_%d_%sNonScaled.log",WCharge_str[c].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h,(WMass::NtoysMomCorr>1?Form("_MomCorrToy%d",m):""),eta_str.Data(),jWmass,WMass::FitVar_str[k].Data());
              // cout << test1 << endl;
              std::ifstream fileNames_NonScaled(test1.Data());
              // string StringFromFile;
              // TString TStringFromFile;
              while (!fileNames_NonScaled.eof()){
                getline (fileNames_NonScaled,StringFromFile);
                TStringFromFile = StringFromFile.c_str();
                // if(TStringFromFile.Contains("nll S+B ->")){
                if(TStringFromFile.Contains("-2 ln Q_{TEV}")){
                  break;
                }
              }
              TObjArray* LineColumns = TStringFromFile.Tokenize(" ");
              ncol = LineColumns->GetEntries();
              // str_icol = ((TObjString *)LineColumns->At(3))->GetString();
              TString str_icol = ((TObjString *)LineColumns->At(4))->GetString();
              likelihood_val = (double) (str_icol.Atof());
              // cout << jWmass << " LIKELIHOOD VALUE= "<<likelihood_val << " lmin= " << lmin << " lmax=" << lmax << endl;
              cout << " " << jWmass << " LIKELIHOOD VALUE= "<<likelihood_val; fflush(stdout);
              l_res.push_back(likelihood_val);
              if(likelihood_val<lmin) lmin=likelihood_val;
              if(likelihood_val>lmax) lmax=likelihood_val;
              
              if(npoint==0) deriv1=likelihood_val;
              else if(npoint==WMass::WMassNSteps) deriv2=likelihood_val;
              else if(npoint==2*WMass::WMassNSteps) deriv3=likelihood_val;

              npoint++;
          
            }
            cout << endl;

            double l_offset;
            if(lmax>0)
              l_offset=-lmax;
            else
              l_offset=-lmin;
            // cout << "lmin= " << lmin << " lmax= " << lmax << endl;  
            for(int j=0; j<2*WMass::WMassNSteps+1; j++){
              int jWmass = WMass::WMassCentral_MeV-(WMass::WMassNSteps-j)*WMass::WMassStep_MeV;
              // cout << "result_NonScaled[h][k]->SetPoint("<<j<<","<<jWmass<<","<<(lmax>0 ? -l_res.at(j) -l_offset : l_res.at(j) -l_offset) <<");"<<endl;
              result_NonScaled[m][h][k][c]->SetPoint(j,jWmass,deriv3-2*deriv2+deriv1<0 ? -l_res.at(j) -l_offset : l_res.at(j) -l_offset );
            }
            // cout << "second derivative= " << (deriv3-2*deriv2+deriv1) << endl;
            
            
            // result->SetMarkerStyle(20);
            // result->SetMarkerSize(1);
            // result->Write();
            result_NonScaled[m][h][k][c]->SetMarkerStyle(20);
            result_NonScaled[m][h][k][c]->SetMarkerSize(1);
            result_NonScaled[m][h][k][c]->Write();
            
            c_chi2=new TCanvas(Form("c_chi2_W%s_%s_pdf%d-%d%s_eta%s",WCharge_str[c].Data(),WMass::FitVar_str[k].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h,WMass::NtoysMomCorr>1?Form("_MomCorrToy%d",m):"",eta_str.Data()),Form("c_chi2_W%s_%s_pdf%d-%d%s_eta%s",WCharge_str[c].Data(),WMass::FitVar_str[k].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h,WMass::NtoysMomCorr>1?Form("_MomCorrToy%d",m):"",eta_str.Data()));
            ffit[k][c]=new TF1(Form("ffit_W%s_%s_pdf%d-%d%s_eta%s",WCharge_str[c].Data(),WMass::FitVar_str[k].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h,WMass::NtoysMomCorr>1?Form("_MomCorrToy%d",m):"",eta_str.Data()),Form("[0]+TMath::Power((x-[1])/[2],2)"),70,100);
            ffit[k][c]->SetParameter(0,result_NonScaled[m][h][k][c]->GetMinimum());
            ffit[k][c]->SetParameter(1,80410);
            ffit[k][c]->SetParameter(2,10); // IF FIT DOES NOT CONVERGE, CHANGE THIS PARAMETER BY LOOKING AT THE CHI2 VS MASS DISTRIBUTION (~value for which Delta_chi2 = 1)
            // ffit[k]->SetParameter(2,1e4); // IF FIT DOES NOT CONVERGE, CHANGE THIS PARAMETER BY LOOKING AT THE CHI2 VS MASS DISTRIBUTION (~value for which Delta_chi2 = 1)
            ffit[k][c]->SetLineColor(2);
            ffit[k][c]->SetLineWidth(1);
            int fires = result_NonScaled[m][h][k][c]->Fit(Form("ffit_W%s_%s_pdf%d-%d%s_eta%s",WCharge_str[c].Data(),WMass::FitVar_str[k].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h,WMass::NtoysMomCorr>1?Form("_MomCorrToy%d",m):"",eta_str.Data()),"WEM");
            cout << "fitres= " << fires << " chi2= " << ffit[k][c]->GetChisquare() << " ndof= " << ffit[k][c]->GetNDF() << " chi2/ndof= " << (ffit[k][c]->GetChisquare()/ffit[k][c]->GetNDF()) << endl;
            int attempts=0;
            while((ffit[k][c]->GetChisquare()/ ffit[k][c]->GetNDF())>1 && attempts<10){
              double rmass = initmass->Gaus(80410, 200);
              ffit[k][c]->SetParameter(1, rmass );
              ffit[k][c]->SetParameter(2,10); // IF FIT DOES NOT CONVERGE, CHANGE THIS PARAMETER BY LOOKING AT THE CHI2 VS MASS DISTRIBUTION (~value for which Delta_chi2 = 1)
              ffit[k][c]->SetLineColor(2);
              ffit[k][c]->SetLineWidth(1);
              result_NonScaled[m][h][k][c]->Fit(Form("ffit_W%s_%s_pdf%d-%d%s_eta%s",WCharge_str[c].Data(),WMass::FitVar_str[k].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h,WMass::NtoysMomCorr>1?Form("_MomCorrToy%d",m):"",eta_str.Data()),"WEM");
              cout << "refitted with init mass: " << rmass << " chi2 norm: " << (ffit[k][c]->GetChisquare()/ ffit[k][c]->GetNDF()) << endl;
              attempts++;
            }
            
            result_NonScaled[m][h][k][c]->Draw("ap");
            TLatex *text,*text2;
            text = new TLatex(0.25,0.7,Form("Best M_{W} with %s= %.0f #pm %.0f MeV", WMass::FitVar_str[k].Data(),ffit[k][c]->GetParameter(1),ffit[k][c]->GetParameter(2)));
            text->SetNDC();
            text->Draw();
            text = new TLatex(0.25,0.6,Form("#DeltaM_{W} = %.0f MeV", (ffit[k][c]->GetParameter(1) - WMass::WMassCentral_MeV )));
            text->SetNDC();
            text->Draw();
            // text2 = new TLatex(0.25,0.6,Form("Best #chi^{2} ratio = %.1f", ffit[k]->GetParameter(0) ));
            // text2->SetNDC();
            // text2->Draw();
            cout << Form("Best M_W value with %s = %.0f +/- %.0f MeV, DeltaM_W = %.0f",WMass::FitVar_str[k].Data(), ffit[k][c]->GetParameter(1), ffit[k][c]->GetParameter(2), (ffit[k][c]->GetParameter(1) - WMass::WMassCentral_MeV)) << endl;
            // cout << "Best chi2 ratio value = " << ffit[k]->GetParameter(0) << endl;
            // cout << "Measured mass points chi2 min = " << chi2min << " max = " << chi2max << endl;
            
            c_chi2->Write();
            
            // result_NonScaled[h][k]->Delete();
            // result->Delete();
            
          }
       
          TCanvas *c_summary=new TCanvas(Form("c_summary_W%s_pdf%d-%d%s_eta%s",WCharge_str[c].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h,WMass::NtoysMomCorr>1?Form("_MomCorrToy%d",m):"",eta_str.Data()),Form("c_summary_pdf%d-%d%s_eta%s",WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h,WMass::NtoysMomCorr>1?Form("_MomCorrToy%d",m):"",eta_str.Data())); 
          c_summary->SetGridy();
          c_summary->SetGridx();
          TH2D*frame=new TH2D("frame",Form("pdf %d-%d %s eta %s;M_{W} (MeV); -2ln(L/L_{ref})",WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h,WMass::NtoysMomCorr>1?Form("_MomCorrToy%d",m):"",eta_str.Data()),2*WMass::WMassStep_MeV+1,WMass::WMassCentral_MeV-(WMass::WMassNSteps)*WMass::WMassStep_MeV,WMass::WMassCentral_MeV+(WMass::WMassNSteps)*WMass::WMassStep_MeV,10,0,5);
          frame->Draw();
          TLine *l=new TLine(WMass::WMassCentral_MeV,0,WMass::WMassCentral_MeV,5);
          l->SetLineStyle(6);
          l->SetLineColor(4);
          l->SetLineWidth(2);
          l->Draw();

          TLegend *leg1 = new TLegend(0.51,0.7,0.89,0.89);
          leg1->SetFillColor(10);  leg1->SetBorderSize(1);
          leg1->SetTextSize(0.035);
          leg1->AddEntry(l, Form("gen M_{W} (%d MeV)",WMass::WMassCentral_MeV), "l");

          TF1*f[3];
          for(int k=0;k<3;k++){
            // cout << result_NonScaled[h][k]->GetParameter(1) << " " << ffit[k]->GetParameter(2) << endl;
            // ffit[k]->Draw("");
            f[k] = (TF1*) result_NonScaled[m][h][k][c]->GetFunction(Form("ffit_W%s_%s_pdf%d-%d%s_eta%s",WCharge_str[c].Data(),WMass::FitVar_str[k].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h,WMass::NtoysMomCorr>1?Form("_MomCorrToy%d",m):"",eta_str.Data()));
            f[k]->SetLineColor(k+1);
            f[k]->SetLineWidth(2);
            f[k]->Draw("same");
            leg1->AddEntry(f[k], Form("%s Fit (#DeltaM_{W} = %.0f #pm %0.f MeV)",WMass::FitVar_str[k].Data(), (f[k]->GetParameter(1) - WMass::WMassCentral_MeV),f[k]->GetParameter(2)), "l");
            // result_NonScaled[h][k]->Draw("l same");
            // ffit[k]->SetLineColor(4);
            // ffit[k]->SetLineWidth(4);
            // ffit[k]->Draw(k>0?"same":"");
            // result_NonScaled[h][k]->SaveAs("test_func");
            deltaM[m][h][k][c]=f[k]->GetParameter(1) - WMass::WMassCentral_MeV;
            if(deltaM[m][h][k][c]<deltaMmin[k][c]) deltaMmin[k][c]=deltaM[m][h][k][c];
            if(deltaM[m][h][k][c]>deltaMmax[k][c]) deltaMmax[k][c]=deltaM[m][h][k][c];

            if(h>0){
              if(deltaM[m][h][k][c]<0) deltaMnegSummed[k][c] = TMath::Sqrt(deltaMnegSummed[k][c]*deltaMnegSummed[k][c] + deltaM[m][h][k][c]*deltaM[m][h][k][c]);
              if(deltaM[m][h][k][c]>0) deltaMposSummed[k][c] = TMath::Sqrt(deltaMposSummed[k][c]*deltaMposSummed[k][c] + deltaM[m][h][k][c]*deltaM[m][h][k][c]);
              deltaMSummed[k][c] = TMath::Sqrt(deltaMSummed[k][c]*deltaMSummed[k][c] + deltaM[m][h][k][c]*deltaM[m][h][k][c]);
              if(h%2==0)
                deltaMJuan[k][c] = TMath::Sqrt( deltaMJuan[k][c]*deltaMJuan[k][c] + (deltaM[m][h][k][c]-deltaM[m][h-1][k][c])*(deltaM[m][h][k][c]-deltaM[m][h-1][k][c]));
            }
            
            if(WMass::PDF_members>1){
              g_deltaM_PDF[k][c]->SetPoint(h,h,deltaM[m][h][k][c]);
              g_deltaM_PDF[k][c]->SetPointError(h,0,f[k]->GetParameter(2));
              h_deltaM_PDF[k][c]->Fill(deltaM[m][h][k][c]);
            }else if(WMass::NtoysMomCorr>1){
              g_deltaM_PDF[k][c]->SetPoint(m,m,deltaM[m][h][k][c]);
              g_deltaM_PDF[k][c]->SetPointError(m,0,f[k]->GetParameter(2));
              h_deltaM_PDF[k][c]->Fill(deltaM[m][h][k][c]);
            }
          }
          leg1->Draw("same");
          c_summary->Write();

        }
      }
    }
    
    for(int k=0;k<3;k++){
      if(WMass::PDF_members>1){

        cout << endl;
        int usedpdf = WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets;
        cout << Form("PDF %d with %s: #DeltaM_{W, min}= %.0f MeV, #DeltaM_{W,max}= %.0f MeV", WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets, WMass::FitVar_str[k].Data(), deltaMmin[k][c], deltaMmax[k][c]) << endl;
        double denominator = 1;

        TCanvas*c1= new TCanvas(Form("c_deltaM_PDF_W%s_%s",WCharge_str[c].Data(),WMass::FitVar_str[k].Data()),Form("c_deltaM_PDF_W%s_%s",WCharge_str[c].Data(),WMass::FitVar_str[k].Data()));
        
        g_deltaM_PDF[k][c]->Draw("ape");
        TLatex *text;
        text = new TLatex(0.2,0.85,Form("W%s, PDF %d with %s: #DeltaM_{W, min}= %.0f MeV, #DeltaM_{W,max}= %.0f MeV", WCharge_str[c].Data(), WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets, WMass::FitVar_str[k].Data(), deltaMmin[k][c], deltaMmax[k][c]));
        text->SetTextSize(0.035);
        text->SetNDC();
        text->Draw();
        
        if(usedpdf==232000){ // NNPDF, see ref. http://arxiv.org/pdf/1301.6754v1.pdf formulae 2.23 and 2.25
          // cout << Form("PDF %d with %s: #DeltaM_{W} square summed = -%.0f MeV, #DeltaM_{W} square summed = %.0f MeV", WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets, WMass::FitVar_str[k].Data(), deltaMnegSummed[k]/denominator, deltaMposSummed[k]/denominator) << endl;
          denominator = TMath::Sqrt(WMass::PDF_members/2-1);
          cout << Form("PDF %d with %s: #DeltaM_{W} square summed = %.0f MeV", WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets, WMass::FitVar_str[k].Data(), deltaMSummed[k][c]/denominator) << endl;
          text = new TLatex(0.2,0.8,Form("PDF %d with %s: #DeltaM_{W} square summed = %.0f MeV", WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets, WMass::FitVar_str[k].Data(), deltaMSummed[k][c]/denominator));
          text->SetTextSize(0.035);
          text->SetNDC();
          text->Draw();
        }else{
          cout << Form("PDF %d with %s: #DeltaM_{W} as of J. Rojo = %.0f MeV", WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets, WMass::FitVar_str[k].Data(), (deltaMJuan[k][c]/2/denominator)) << endl;
          text = new TLatex(0.2,0.8,Form("PDF %d with %s: #DeltaM_{W} as of J. Rojo = %.0f MeV", WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets, WMass::FitVar_str[k].Data(), (deltaMJuan[k][c]/2/denominator)));
          text->SetTextSize(0.035);
          text->SetNDC();
          text->Draw();
        }

        g_deltaM_PDF[k][c]->Write();
        h_deltaM_PDF[k][c]->Write();
        c1->Write();
        
        // mean = TMath::Mean(n, &v[0]);
        // vector<double> v;
        // // std::generate(v.begin(), v.end(), 1);
        // if(k==1)
          // for(int h=0; h<WMass::PDF_members; h++){
            // // v.push_back(deltaM[h][k]);
            // cout << deltaM[h][k] << endl;
          // }
        // double meanWmass= TMath::Mean(v.begin(), v.end());
        // cout << "meanWmass= " << meanWmass << endl;
      }
      if(WMass::NtoysMomCorr>1){
        cout << endl;
        // int usedpdf = WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets;
        cout << Form("MomCorr toys with %s: #DeltaM_{W, min}= %.0f MeV, #DeltaM_{W,max}= %.0f MeV", WMass::FitVar_str[k].Data(), deltaMmin[k][c], deltaMmax[k][c]) << endl;
        double denominator = 1;

        TCanvas*c1= new TCanvas(Form("c_deltaM_PDF_%s",WMass::FitVar_str[k].Data()),Form("c_deltaM_PDF_%s",WMass::FitVar_str[k].Data()));
        g_deltaM_PDF[k][c]->Draw("ape");
        TLatex *text;
        text = new TLatex(0.2,0.85,Form("MomCorr toys with %s: #DeltaM_{W, min}= %.0f MeV, #DeltaM_{W,max}= %.0f MeV", WMass::FitVar_str[k].Data(), deltaMmin[k][c], deltaMmax[k][c]));
        text->SetTextSize(0.035);
        text->SetNDC();
        text->Draw();
        
        // if(usedpdf==232000){ // NNPDF, see ref. http://arxiv.org/pdf/1301.6754v1.pdf formulae 2.23 and 2.25
          // cout << Form("PDF %d with %s: #DeltaM_{W} square summed = -%.0f MeV, #DeltaM_{W} square summed = %.0f MeV", WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets, WMass::FitVar_str[k].Data(), deltaMnegSummed[k]/denominator, deltaMposSummed[k]/denominator) << endl;
          denominator = TMath::Sqrt(WMass::NtoysMomCorr/2-1);
          cout << Form("MomCorr toys with %s: #DeltaM_{W} square summed = %.0f MeV", WMass::FitVar_str[k].Data(), deltaMSummed[k][c]/denominator) << endl;
          text = new TLatex(0.2,0.8,Form("MomCorr toys with %s: #DeltaM_{W} square summed = %.0f MeV", WMass::FitVar_str[k].Data(), deltaMSummed[k][c]/denominator));
          text->SetTextSize(0.035);
          text->SetNDC();
          text->Draw();
        // }else{
          // cout << Form("MomCorr toys with %s: #DeltaM_{W} as of J. Rojo = %.0f MeV", WMass::FitVar_str[k].Data(), (deltaMJuan[k]/2/denominator)) << endl;
          // text = new TLatex(0.2,0.8,Form("MomCorr toys with %s: #DeltaM_{W} as of J. Rojo = %.0f MeV", WMass::FitVar_str[k].Data(), (deltaMJuan[k]/2/denominator)));
          // text->SetTextSize(0.035);
          // text->SetNDC();
          // text->Draw();
        // }

        g_deltaM_PDF[k][c]->Write();
        h_deltaM_PDF[k][c]->Write();
        c1->Write();

      }
    }
  }
    
    fout->Write();
    
    fout->Delete();
}
Example #14
0
//--------------------------------------------------------------------------------------------------
// Do Fake Rate Computation From WCD sample
//--------------------------------------------------------------------------------------------------
void computeFakeRatesFromQCD(char *FakeRateFilename ,bool fitFakeRate, int chargetype = 0, int eventType = 0) {

  //Samples
  vector<string> madgraphQCDDatasetFiles;
  vector<string> madgraphQCDDatasetNames;
  vector<string> pythiaQCDemDatasetFiles;
  vector<string> pythiaQCDemDatasetNames;
  vector<string> pythiaInclMuonDatasetFiles;
  vector<string> pythiaInclMuonDatasetNames;

  //*****************************************************************************************
  //Do FakeRate Computation 
  //*****************************************************************************************

  //Create root file to store fake rates
  TFile *file = new TFile(FakeRateFilename, "UPDATE");
  file->cd();

  //different charges
  string chargeTypeName = "";
  if (chargetype == -1)
    chargeTypeName = "Minus";
  else if (chargetype == 1)
    chargeTypeName = "Plus";

  string eventTypeName = "";
  if (eventType == -1)
    eventTypeName = "MinusW";
  else if (eventType == 1)
    eventTypeName = "PlusW";

  //do both muon and electrons
  string fakeTypeString = "";
  Double_t maxY = 1.0;
  for (int faketype=11 ; faketype <= 13; faketype+=2) {
    if (faketype == 11) {
      fakeTypeString = "Electron";
      maxY = 0.5;
    } else if (faketype == 13) {
      fakeTypeString = "Muon";
      maxY = 0.5;
    } else {
      cerr << "Error: faketype = " << faketype << " not recognized.\n";
      assert(false);
    }
    
    //*****************************************************************************************
    //Load input histogram files
    //*****************************************************************************************
    madgraphQCDDatasetFiles.clear(); 
    madgraphQCDDatasetNames.clear();
    pythiaQCDemDatasetFiles.clear();
    pythiaQCDemDatasetNames.clear();
    pythiaInclMuonDatasetFiles.clear();
    pythiaInclMuonDatasetNames.clear();
    
    //Madgraph QCD
    madgraphQCDDatasetFiles.push_back("/home/sixie/hist/Compute" + fakeTypeString + "FakeRate/filler/006/Compute" + fakeTypeString + "FakeRate_s8-qcd_250_500-mg-id9.root");
    madgraphQCDDatasetNames.push_back("s8-qcd_250_500-mg-id9");

    //Pythia QCDEM
    pythiaQCDemDatasetFiles.push_back("/home/sixie/hist/Compute" + fakeTypeString + "FakeRate/filler/006/Compute" + fakeTypeString + "FakeRate_s8-qcdem_20_30-id9.root");
    pythiaQCDemDatasetNames.push_back("s8-qcdem_20_30-id9");
    pythiaQCDemDatasetFiles.push_back("/home/sixie/hist/Compute" + fakeTypeString + "FakeRate/filler/006/Compute" + fakeTypeString + "FakeRate_s8-qcdem_30_80-id9.root");
    pythiaQCDemDatasetNames.push_back("s8-qcdem_30_80-id9");
    pythiaQCDemDatasetFiles.push_back("/home/sixie/hist/Compute" + fakeTypeString + "FakeRate/filler/006/Compute" + fakeTypeString + "FakeRate_s8-qcdem_80_170-id9.root");
    pythiaQCDemDatasetNames.push_back("s8-qcdem_80_170-id9");

    //Pythia InclusiveMuon
    pythiaInclMuonDatasetFiles.push_back("/home/sixie/hist/Compute" + fakeTypeString + "FakeRate/filler/006/Compute" + fakeTypeString + "FakeRate_s8-incmu_15-id9.root");
    pythiaInclMuonDatasetNames.push_back("s8-incmu_15-id9");
    pythiaInclMuonDatasetFiles.push_back("/home/sixie/hist/Compute" + fakeTypeString + "FakeRate/filler/006/Compute" + fakeTypeString + "FakeRate_s8-incmu_5_50-id9.root");
    pythiaInclMuonDatasetNames.push_back("s8-incmu_5_50-id9");


    //*****************************************************************************************
    //Construct the fake rate Histgrams. Fit with function.
    //*****************************************************************************************
    vector<TH1F*> fakeRateHistograms; fakeRateHistograms.clear();
    vector<TF1*> fakeRateFits; fakeRateFits.clear();
    vector<string> fakeRateLegendNames; fakeRateLegendNames.clear();

    //pythia version
    TH1F *FakeRatePt_pythia = NULL;
    if (faketype == 11)
      FakeRatePt_pythia = createFakeRatePtHist(pythiaQCDemDatasetFiles, pythiaQCDemDatasetNames,
                                               0,faketype, chargetype,eventType,
                                               (chargeTypeName + fakeTypeString + eventTypeName + "FakeRate_Pt_PythiaQCDEM").c_str());
    else if (faketype == 13) {
      //FakeRatePt_pythia = createFakeRatePtHist(pythiaInclMuonDatasetFiles, pythiaInclMuonDatasetNames, 
      //                                         0,faketype,chargetype,eventType,
      //                                         (chargeTypeName + fakeTypeString + eventTypeName + "FakeRate_Pt_PythiaInclMuon").c_str());
      FakeRatePt_pythia = createFakeRatePtHist(pythiaQCDemDatasetFiles, pythiaQCDemDatasetNames, 
                                               0,faketype, chargetype,eventType,
                                               (chargeTypeName + fakeTypeString + eventTypeName + "FakeRate_Pt_PythiaQCDEM").c_str());
    } else {
      cerr << "faketype out of range\n";
      assert(false);
    }
    FakeRatePt_pythia->GetYaxis()->SetTitle((chargeTypeName + fakeTypeString + eventTypeName + " Fake Rate").c_str());    
      
    TF1 *FakeRateFitFunction_pythia = NULL;
    if (fitFakeRate) {
      TF1 *FakeRateFitFunction_pythia = fitFakeRatePtHist(FakeRatePt_pythia);
      if (faketype == 11)
        FakeRateFitFunction_pythia->SetName((chargeTypeName + fakeTypeString + eventTypeName + "FakeRateFunction_Pt_PythiaQCDEM").c_str());
      else if (faketype == 13) {
      FakeRateFitFunction_pythia->SetName((chargeTypeName + fakeTypeString + eventTypeName + "FakeRateFunction_Pt_PythiaQCDEM").c_str());    
      }
    }

    fakeRateHistograms.push_back(FakeRatePt_pythia);
    if (fitFakeRate) fakeRateFits.push_back(FakeRateFitFunction_pythia);
    if (faketype == 11)
      fakeRateLegendNames.push_back(chargeTypeName + fakeTypeString + eventTypeName + " Pythia QCDEM");
    else if (faketype == 13)
      fakeRateLegendNames.push_back(chargeTypeName + fakeTypeString + eventTypeName + " Pythia QCDEM");
    else {
      cerr << "faketype out of range\n";
      assert(false);
    }

    //madgraph version
    TH1F *FakeRatePt_madgraph = createFakeRatePtHist(
      madgraphQCDDatasetFiles, madgraphQCDDatasetNames,0,faketype,chargetype,eventType,
      (chargeTypeName + fakeTypeString + "FakeRate_Pt_MadgraphQCD").c_str());
    FakeRatePt_madgraph->GetYaxis()->SetTitle((chargeTypeName +fakeTypeString + eventTypeName + " Fake Rate").c_str());    

    TF1 *FakeRateFitFunction_madgraph = NULL;
    if (fitFakeRate) {
      FakeRateFitFunction_madgraph = fitFakeRatePtHist(FakeRatePt_madgraph);
      FakeRateFitFunction_madgraph->SetName(
        (chargeTypeName + fakeTypeString + eventTypeName + "FakeRateFunction_Pt_MadgraphQCD").c_str());      
    }
    
    fakeRateHistograms.push_back(FakeRatePt_madgraph);
    if (fitFakeRate) fakeRateFits.push_back(FakeRateFitFunction_madgraph);
    fakeRateLegendNames.push_back(chargeTypeName + fakeTypeString + eventTypeName + " Madgraph QCD");
    
    //*****************************************************************************************
    //Draw the plots
    //*****************************************************************************************
    drawFakeRatePlots(fakeRateHistograms,fakeRateFits,fakeRateLegendNames,
                      (chargeTypeName + fakeTypeString + eventTypeName + "FakeRatePt").c_str(),maxY);

    //*****************************************************************************************
    //save them to the output file
    //*****************************************************************************************
    for (UInt_t i=0; i<fakeRateHistograms.size();i++) {
      //write the histograms. delete any existing one with the same name
      if (file->FindObjectAny(fakeRateHistograms[i]->GetName())) {
        string tmpname = fakeRateHistograms[i]->GetName();        
        file->Delete((tmpname+";*").c_str());
      }

      fakeRateHistograms[i]->SetDirectory(file);
      file->WriteTObject(fakeRateHistograms[i]);

      //write the fit functions. delete any existing one with the same name
      if (fitFakeRate){
        if (file->FindObjectAny(fakeRateFits[i]->GetName())) {
          string tmpname = fakeRateFits[i]->GetName();        
          file->Delete((tmpname+";*").c_str());
        }
        file->WriteTObject(fakeRateFits[i]);
      }
    }
  }
  file->Close();
  return;
}
Example #15
0
void reconstruction(TString infile = "../build/reco_spr.root", 
					int num_events = 10000, 
					char *runtype = "data", 
					double tdiff = 1.5)
{
	gErrorIgnoreLevel = kWarning; // ignore 'Info in...' messages
	gStyle->SetOptFit(1111); // show fit parameters
	gStyle->SetOptStat(0);   // remove stats box
	TGaxis::SetMaxDigits(4); // put axis in scientific notation

	TFile *f = TFile::Open(infile); 
	TTree *t = (TTree*)f->Get("reco"); //Lee's Tree
	TTree *d = (TTree*)f->Get("dirc"); //Roman's Tree

	// set value of lens and alpha from dirc tree
	int lens(0);
	double angle(0),beam(0),yield(0),nph(0);
	d->SetBranchAddress("lens",&lens);
	d->SetBranchAddress("theta",&angle);
	d->SetBranchAddress("beam",&beam);
	d->SetBranchAddress("yield",&yield);
	d->SetBranchAddress("nph",&nph);
	d->GetEntry(0);

	// get time-expt peak value
	TH1D *diff = new TH1D("diff","diff",100,-5,5);
	t->Project("diff","diff");
	double diffmax = diff->GetBinCenter(diff->GetMaximumBin());

	// define cuts and save path
	char *sim_cut  = Form("abs(diff-%f)<%f",diffmax,tdiff);
	char *data_cut = Form("abs(diff-%f)<%f",diffmax,tdiff);
	char *savepath = "../macro/timecuts";

	// define cut and project from tree to histogram w/ proper cuts
	theta = new TH1D("theta","theta",100,0.6,1.0);
	if(runtype=="data") // do all the data things
	{
		// make counter histograms for cut
		TH1D *tof1 = new TH1D("time-tof1","time-tof1",1000,0,1000);
		TH1D *tof2 = new TH1D("time-tof2","time-tof2",1000,0,1000);
		TH1D *trig = new TH1D("time-trig","time-trig",1000,0,1000);

		// project onto counter histograms
		t->Project("time-tof1","time-tof1");
		t->Project("time-tof2","time-tof2");
		t->Project("time-trig","time-trig");
	
		// make cuts w/ counters
		cntrCut(tof1, data_cut, "time-tof1");
		cntrCut(tof2, data_cut, "time-tof2");
		cntrCut(trig, data_cut, "time-trig");
		//cout << "data cut\t" << data_cut << endl;

		/*
		// make counter hists pretty (and distinguishable)
		tof1->SetTitle(data_cut);
		tof1->SetTitleSize(0.5);
		tof1->SetLineColor(kBlue);
		tof2->SetLineColor(kRed);
		trig->SetLineColor(kGreen);

		// draw histograms and save canvas
		char *cname = Form("%s/reco_%s_%d_%d_ccuts.png",
					  savepath,runtype,lens,(int)angle);
		TCanvas *ccanv = new TCanvas();
		gPad->SetLogy();
		tof1->Draw();
		tof2->Draw("same");
		trig->Draw("same");
		ccanv->Print(cname);
		*/

		t->Project("theta","theta",data_cut);
	}
	else
		t->Project("theta","theta",sim_cut);

	// preliminary paramters for fit of theta
	double height = theta->GetMaximum();
	double center = theta->GetBinCenter(theta->GetMaximumBin());
	double sigma  = 0.015;
	double slope  = 1.0;
	double shift  = height/3;

	// define custom fit, set parameters, and fit to data
	TF1 *gaus0 = new TF1("gaus0", "gaus+[3]*x+[4]", 
						 center-0.05, center+0.05);
	gaus0->SetParameters(height,center,sigma,slope,shift);
	gaus0->SetParNames("height","mean","sigma","slope","const");
	theta->Fit("gaus0","QR");
	double truesig = 1000*gaus0->GetParameter("sigma");
	
	// define strings for picture and root file names
	char *namt = Form("theta_{c} lens %d angle %d diff %1.2f",
					  lens,(int)angle,tdiff);
	char *pict = Form("%s/reco_%s_%d_%d_%1.2f.png",
					  savepath,runtype,lens,(int)angle,tdiff);

	/*
	// format histogram for saving
	TCanvas *c1 = new TCanvas();
	c1->cd();
	double max = 1.1*theta->GetMaximum();
	theta->SetTitle("");
	theta->GetXaxis()->SetLabelSize(0.06);
	theta->GetYaxis()->SetLabelSize(0.06);
	theta->GetXaxis()->SetRangeUser(0.61,1);
	theta->GetYaxis()->SetRangeUser(0,max);
	theta->Draw();
	c1->Print(pict);

	// save histogram again without fit parameters
   	gStyle->SetOptFit(0);
	c1->cd();
	theta->Draw();
	pict = Form("%s/reco_%s_%d_%d_%1.2f_nofit.png",
				savepath,runtype,lens,(int)angle,tdiff);
	c1->Print(pict);
	*/

	// print relevant info to screen and file
	char *outnm = Form("../macro/timecut_%s.tsv",runtype);
	ofstream out;
	out.open(outnm, fstream::in | fstream::out | fstream::app);
	out << angle 
		<< "\t" << lens  
		<< "\t" << tdiff
		<< "\t" << truesig
		<< "\t" << yield 
		<< "\t" << nph << endl;
	out.close();
	cout << "\033[1;31m" 
		 << "\nangle:\t" << angle
		 << "\nlens:\t"  << lens
		 << "\ndiff:\t"  << tdiff
		 << "\npeak:\t"  << diffmax
		 << "\nsigma:\t" << truesig
		 << "\nhits/e:\t" << nph
		 << "\nphts/e:\t" << yield 
		 << "\033[0m" <<  endl;
	TFile *tfile = new TFile(Form("timecut_%1.1f_%d_%1.2f.root",
								  angle,lens,tdiff),"create");
	TTree *ttree = new TTree("tcut","tcut");
	ttree->Branch("angle",&angle,"angle/D");
	ttree->Branch("lens",&lens,"lens/I");
	ttree->Branch("tcut",&tdiff,"tcut/D");
	ttree->Branch("sigma",&truesig,"truesig/D");
	ttree->Branch("nph",&yield,"yield/D");

	ttree->Fill();
	ttree->Write();
	tfile->Delete();
}
//*******MAIN*******************************************************************                                                                                  
int main (int argc, char** argv)
{
  std::cout<<"-----------COMPUTING CHARGE TRESHOLDS FOR EACH CHANNEL------------"<<std::endl;
  std::cout<<"NB: MCP is analyzed only if HV>treshold and PC is ON---------"<<std::endl;

  int SBTreshold=1000;
  int nChannels=9;
  int HVtresh=2000;
  //  int doPlot=0;

  std::string inputFileName = argv[1];  
  std::cout<<"\nReading file: "<<inputFileName<<std::endl;

  if (argc > 2) {
    SBTreshold = atoi(argv[2]);  //desired treshold (e.g. S/B=1000)
    nChannels = atoi(argv[3]);  //nChannels in the reco tree
    HVtresh = atoi(argv[4]);   //HV treshold
  }

  std::cout << " SBTreshold = " << SBTreshold << std::endl;
  std::string outputFileName = "cfg/treshold_SB1000_ft.txt";
  std::ofstream outputFile ((outputFileName).c_str(), std::ofstream::out);
  std::string outputFileName3s = "cfg/treshold_3s_ft.txt";
  std::ofstream outputFile3s ((outputFileName3s).c_str(), std::ofstream::out);
  std::string outputFileName5s = "cfg/treshold_5s_ft.txt";
  std::ofstream outputFile5s ((outputFileName5s).c_str(), std::ofstream::out);

  //-----get the run list and the list of channel to analyze------

  TLegend* leg = new TLegend(0.88,0.45,0.98,0.65);
  TGraph* g_SoB[20];

  TF1* base[10];
  TF1* baseAmp[10];

  TCanvas* baseFit[10];


  ////////////// pedestal
  TFile *inputFilePed = new TFile ("/gwteray/users/brianza/ntuple_reco_iMCP_H4_Template/reco_pedestal.root"); 
  TTree *inputTreePed = (TTree*)inputFilePed->Get("reco_tree");
  InitRecoTree(inputTreePed);  
  inputTreePed->SetDirectory(0);
  inputFilePed->Close();
  inputFilePed->Delete();
  std::cout << " inputTreePed->GetEntries() = " << inputTreePed->GetEntries() << std::endl;

  ////////////// signal
  TFile *inputFile = new TFile ((inputFileName).c_str()); 
  TTree *inputTree = (TTree*)inputFile->Get("reco_tree");
  InitRecoTree(inputTree);  
  std::cout << " inputTree->GetEntries() = " << inputTree->GetEntries() << std::endl;

  Fill_inverted_MCPList();
  std::cout << " inverted_MCPList.size() = " << inverted_MCPList.size() << std::endl;

  TH1F** hS = new TH1F*[10];
  TH1F** hB = new TH1F*[10];
  TH1F** hBFit = new TH1F*[10];

  TH1F** hAmpS = new TH1F*[10];
  TH1F** hAmpB = new TH1F*[10];
  TGraph** gAmpSoB = new TGraph*[10];

  //------analyze the good channels and compute the charge tresholds--------
  std::cout<<"\n--------------------------------\n-->OK, now computing tresholds:"<<std::endl;
  for (int iCh=0; iCh<nChannels; iCh++)
	{
	  char hSName[100], hBName[100], hBNameFit[100], fitName[100];
	  sprintf(hSName, "hS_%d", iCh);
	  sprintf(hBName, "hB_%d", iCh);
	  sprintf(hBNameFit, "hBFit_%d", iCh);
	  sprintf(fitName, "gausFit_%d", iCh);

	  hS[iCh] = new TH1F(hSName,hSName, 1000, -5000, 50000);
	  hB[iCh] = new TH1F(hBName,hBName, 1000, -5000, 50000);
	  hBFit[iCh] = new TH1F(hBNameFit,hBNameFit, 1000, -5000, 50000);

	  base[iCh] = new TF1(fitName,"gaus",-1000,1000);
	      
	  char hSDraw[100], hBDraw[100], hBDrawFit[100];
	  sprintf(hSDraw, "(charge[%d]+(baseline[%d]*25)) >>%s", iCh, iCh,  hSName);
	  sprintf(hBDraw, "(charge[%d]+(baseline[%d]*25))>>%s", iCh, iCh, hBName);
	  sprintf(hBDrawFit, "(charge[%d]+(baseline[%d]*25.))>>%s", iCh, iCh, hBNameFit);

	  char cut[300];
	  //	  if(inverted_MCPList.at(iCh) == "enSEE") HVtresh = 2000;
	  //	  sprintf(cut, "isPCOn[%d]!=2 && HV[%d]>=%d && tdcX > -8 && tdcX < 0 && tdcY >-2 && tdcY < 6 && time_OT[%d] < 0.", iCh, iCh, HVtresh, iCh); 
	  sprintf(cut, "isPCOn[%d]!=2 && HV[%d]>=%d && tdcX > -8 && tdcX < 0 && tdcY >-2 && tdcY < 6", iCh, iCh, HVtresh); 

	  char cutPed[300];
	  //	  sprintf(cut, "isPCOn[%d]!=2 && tdcX > -8 && tdcX < 0 && tdcY >-2 && tdcY < 6 && time_OT[iCh] < 0.", iCh, iCh); 
	  sprintf(cutPed, "time_OT[%d] < 0. && charge_corr[%d] > -1.1 && charge_corr[%d] < -0.9", iCh, iCh, iCh); 

	  inputTree->Draw(hSDraw, cutPed);
// 	  inputTreePed->Draw(hBDraw,cut);
// 	  inputTreePed->Draw(hBDrawFit,cut);
 	  inputTreePed->Draw(hBDraw, cutPed);
 	  inputTreePed->Draw(hBDrawFit, cutPed);
	  //	  inputTreePed->Draw(hBDraw, cutPed);      
	  //	  inputTreePed->Draw(hBDrawFit, cutPed);   



	  baseAmp[iCh] = new TF1(Form("baseAmp_%d",iCh),"gaus",-30.,30.);
	  hAmpS[iCh] = new TH1F(Form("hAmpS_%d",iCh), "", 2500, -1000, 10000);
	  hAmpB[iCh] = new TH1F(Form("hAmpB_%d",iCh), "", 2500, -1000, 10000);

	  inputTree->Draw(Form("amp_max[%d]>>%s",iCh,Form("hAmpS_%d",iCh)), cutPed);
	  inputTreePed->Draw(Form("amp_max[%d]>>%s",iCh,Form("hAmpB_%d",iCh)), cutPed);


	  std::cout << " iCh = " << iCh << std::endl;
	  std::cout << " hAmpS->GetEntries() = " << hAmpS[iCh]->GetEntries() << std::endl;
	  std::cout << " hAmpB->GetEntries() = " << hAmpB[iCh]->GetEntries() << std::endl;

	  char canvasName[50];
	  sprintf(canvasName, "plots/baseline/baseFit_%d.pdf", iCh);
	  baseFit[iCh] = new TCanvas();
	  baseFit[iCh]->cd();

	  base[iCh]->SetParameters(hBFit[iCh]->GetMean(), hBFit[iCh]->GetRMS());
     	  hBFit[iCh]->Fit(base[iCh]);
	  std::cout << "Charge sigma == " << base[iCh]->GetParameter(2) << std::endl;
	  outputFile3s << iCh << "  " << (int)(base[iCh]->GetParameter(2)*3) << std::endl;
	  outputFile5s << iCh << "  " << (int)(base[iCh]->GetParameter(2)*5) << std::endl;

	  hBFit[iCh]->Draw();
	  base[iCh]->Draw("same");
	  baseFit[iCh]->Print(canvasName,"pdf");
	  sprintf(canvasName, "plots/baseline/baseFit_%d.png", iCh);
	  baseFit[iCh]->Print(canvasName,"png");

	  //	  baseAmp[iCh]->SetParameters(hAmpB[iCh]->GetMean(),hAmpB[iCh]->GetRMS());
	  baseAmp[iCh]->SetParameters(0., hAmpB[iCh]->GetRMS());
	  hAmpB[iCh]->Fit(baseAmp[iCh], "R");
	  float sigmaAmp = baseAmp[iCh]->GetParameter(2);
	  std::cout << "Ampl sigma == " << sigmaAmp << std::endl;


	  g_SoB[iCh] = new TGraph();
	  gAmpSoB[iCh] = new TGraph();

	  int SBvalue = 0;
	  int nBinsAmpHisto = hAmpS[iCh]->GetNbinsX();
	  int nBinsHisto = hS[iCh]->GetNbinsX();
	  //	  float intTot_Sc = hS[iCh]->Integral(1, nBinsHisto);
	  //	  float intTot_Bc = hB[iCh]->Integral(1, nBinsHisto);
	  float intTot_Sa = hAmpS[iCh]->Integral(1, nBinsAmpHisto);
	  float intTot_Ba = hAmpB[iCh]->Integral(1, nBinsAmpHisto);

	  for (int iBin=1; iBin<=std::max(nBinsHisto, nBinsAmpHisto); ++iBin)
	    {

	      if(iBin <= nBinsHisto){
		double S = hS[iCh]->Integral(iBin, nBinsHisto);
		double B = hB[iCh]->Integral(iBin, nBinsHisto);
		double SoverB = 2000;
		if (B!=0)    SoverB = S/B;
		//		g_SoB[iCh]->SetPoint(iBin,hS[iCh]->GetBinCenter(iBin),B);
		g_SoB[iCh]->SetPoint(iBin,hS[iCh]->GetBinCenter(iBin),SoverB);
	      }

	       if(iBin <= nBinsAmpHisto){
		 double Samp = hAmpS[iCh]->Integral(iBin, nBinsAmpHisto)/intTot_Sa;
		 double Bamp = hAmpB[iCh]->Integral(iBin, nBinsAmpHisto)/intTot_Ba;
		 if(hAmpS[iCh]->GetBinCenter(iBin) == sigmaAmp * 5.) std::cout << " >>>> Samp/Bamp = " << Samp/Bamp << std::endl;
		 double SoBamp = 2000;
		 if(Bamp!=0) SoBamp = Samp/Bamp;
		 gAmpSoB[iCh]->SetPoint(iBin,hAmpS[iCh]->GetBinCenter(iBin),Samp);
		 // gAmpSoB[iCh]->SetPoint(iBin,hAmpS[iCh]->GetBinCenter(iBin),Bamp);
		 gAmpSoB[iCh]->SetPoint(iBin,hAmpS[iCh]->GetBinCenter(iBin),SoBamp);
	       }


// 	       if (SoverB > SBTreshold) 
// 	         {
// 		   std::cout<<" Channel: "<<iCh<<" ("<<inverted_MCPList.at(iCh)<<")   Treshold Value: "<<iBin<<std::endl;
// 		   outputFile<<iCh<<" "<<iBin<<std::endl;
// 		   SBvalue = iBin;
// 	           break;
// 	         }       
	    }

	  
	  g_SoB[iCh]->SetLineColor(iCh+1);
	  g_SoB[iCh]->SetMarkerColor(iCh+1);
	  if (iCh==0)   g_SoB[iCh]->Draw("APL");
      	  else          g_SoB[iCh]->Draw("pl,same");

	  //	    g_SoB[iCh]->GetXaxis()->SetLimits(0,600);
	  //	    g_SoB[iCh]->SetMinimum(0);
	  //	    g_SoB[iCh]->SetMaximum(1001);
	  g_SoB[iCh]->GetXaxis()->SetTitle("charge");
	  g_SoB[iCh]->GetYaxis()->SetTitle("S/B");

	  TLine* tl = new TLine(SBvalue, 0, SBvalue, 1000);
	  tl->SetLineColor(iCh+1);
	  tl->Draw("same");
	  
	  leg->AddEntry(g_SoB[iCh],inverted_MCPList.at(iCh).c_str(),"l");
	  
	}
  TCanvas* SoB = new TCanvas("SoB", "SoB", 800, 800);  
  leg->SetFillColor(0);
  SoB->cd();
  g_SoB[0]->Draw("ap");
  for(int iCh=1; iCh<nChannels; ++iCh)g_SoB[iCh]->Draw("p, same");
  leg->Draw("same");
  SoB->Print("plots/SoverB.pdf","pdf");

  TFile outThresh("outThresh.root", "recreate");
  outThresh.cd();
  for(int iCh=0; iCh<nChannels; ++iCh){
    g_SoB[iCh]->Write(Form("gSoB_%d",iCh));
    hS[iCh]->Write(Form("hS_%d",iCh));
    hB[iCh]->Write(Form("hB_%d",iCh));
    hBFit[iCh]->Write(Form("hBFit_%d",iCh));
    hAmpS[iCh]->Write(Form("hAmpS_%d",iCh));
    hAmpB[iCh]->Write(Form("hAmpB_%d",iCh));
    gAmpSoB[iCh]->Write(Form("gAmpSoB_%d",iCh));
  }
  outThresh.Close();  

  /*  TCanvas* ch_baseline = new TCanvas("ch_baseline", "ch_baseline", 800, 800);  
  ch_baseline->cd();
  hBFit->Draw("");
  base->Draw("same");
  ch_baseline->Print("plots/baseline_ch0.pdf","pdf");
  */  
  std::cout<<"\nS/B=1000: treshold values printed in "<<outputFileName<<std::endl;
  std::cout<<"\n3sigma:   treshold values printed in "<<outputFileName3s<<std::endl;
  std::cout<<"\n5sigma:   treshold values printed in "<<outputFileName5s<<std::endl;
  inputFile->Close();
  return 0;
}
Example #17
0
int main( int argc ,char *argv[] ){
  
  DataObject areas;
  areas.getDataFromFile("resources/static_resources/area_noise_CMSSW_IDS.txt",2);
  
  map<string, double> areaMap;
  
  for (int i=1; i<= areas.getLenght(); i++){
    double area = atof(areas.getElementFromPropertyContainer(i,2).c_str());
    string roll = areas.getElementFromPropertyContainer(i,1);
    areaMap[roll] = area;
  }

  //Syntax:
  //EndCap RE(WDN)_SECTOR_RID
  //Barrel W(WDN)_RID_SECTOR

  if (argc < 5) {
    
    cout << "Usage: " << argv[0] << " Zone Wheel Sector RollID [OutFile]" << endl;
    cout << endl;
    cout << "  Conventions:"<< endl;
    cout << "    Barrel: W(WDN)_RID_SECTOR" << endl;
    cout << "    EndCap: RE(WDN)_SECTOR_RID" << endl;
    cout << endl;
    return 0;
  }
  bool corrected = true;
  /*  string zone = "EndCapPlus";
  string RollID = "10";
  int Sector = 2;
  int WheelDiskNo = 2;
  */

  string zone = argv[1];                                                                                                                                                  
  string RollID = argv[4]; 
  int Sector = atoi(argv[3]);                                                                                                                                          
  int WheelDiskNo = atoi(argv[2]);                                                                                                                                                            
  string optionalID = argv[5];

  string ContainerName = "ContainerRun2011.root";
  string jsonFile = "./jsonFilesMu/Cert_160404-180252_7TeV_PromptReco_Collisions11_JSON.txt";
  //Create a new Acquisition Registry

  TFile* contFile = TFile::Open( ContainerName.c_str() );
  
	Acquisition Run2011(contFile);
/*	ifstream json(jsonFile.c_str());
	Run2011.LoadJSON(json);*/


  DataObject filterRun;
  filterRun.getDataFromFile("filters/moreThan100.csv",1);  
  Run2011.LoadSelectionByDO(&filterRun, 1);

      TFile* f;
      if (argc >= 6){
	f = new TFile(argv[6], "RECREATE");
          cout << "Writing results on: " << argv[6] << endl;
}
      else{
	f = new TFile("Outputs/OutputFile.root", "RECREATE");
	cout << "Writing results on: Outputs/OutputFile.root"  << endl;
}

  TGraph* plot = new TGraph();
  TGraph* plotRun = new TGraph();

  plot->SetName("RateVsLumi");
  plotRun->SetName("RateVsRun");

  plot->SetMarkerStyle(21);
  contFile->Close();
    int k=0;    
    int emptyStrip = 0;

	cout << "Analysis of: " << zone << " - Wheel/Disk No." << WheelDiskNo << " ; Sector: " << Sector << " ; ID:" << RollID << endl;
	cout << "Correction activated: " << corrected<< endl;
	cout << "Dataset: " << ContainerName << endl;
	cout << "JSON File: " << jsonFile << endl;

// Run2011.PrintValidRuns();
  cout << "Number of runs: " << Run2011.numberOfRuns() << endl;
  while (Run2011.hasNext()){
    
    double NormalizedRate = 0;
    
    Run* currentRun = Run2011.next();

    //run selection
//    if ( currentRun->getID() > 163289 && currentRun->getID() < 163340 ) continue;
//    if (currentRun->getID() < 170000) continue;
//    if (currentRun->getLumiSection() < 100) continue;
//    if (currentRun->getID() < 178420) continue;
    if (!Run2011.isValid(currentRun, false)) continue;
    
    //Filling
      contFile = TFile::Open( ContainerName.c_str() );

    currentRun->FillFromContainer(contFile, areaMap);

        
    double TotRate = 0;
    double TotArea = 0;
    int totAmount = 0;
    if (currentRun->isFilled() == false){
	cout << "Not filled: " << currentRun->getID() << endl;
    }
    if (currentRun->isFilled() == true){

      map<string,ExRoll* > barrelMap;

      if (zone == "Barrel")
	barrelMap = currentRun->GetBarrel();

      else if (zone == "EndCapPlus")
	barrelMap = currentRun->GetEndCapPlus();

      else if (zone == "EndCapMinus")
	barrelMap = currentRun->GetEndCapMinus();

      for (map<string,ExRoll* >::const_iterator it = barrelMap.begin(); it != barrelMap.end(); it++){

	if (RollID != "-9")
	  if (it->second->getRollID().c_str() != RollID) continue;

	if (Sector != -9)
	  if (it->second->getSector() != Sector) continue;

	if (WheelDiskNo != -9)
	  if (it->second->getWheel_Disk_Number() != WheelDiskNo) continue;

	//When we will decide to plot partition by partition
	if (optionalID != "-9"){
//	cout << optionalID << endl;
//	cout << it->second->getOptionalRollID() << endl;
                if ( it->second->getOptionalRollID().compare(optionalID) ) continue;
	}

      
        emptyStrip += it->second->getEmptyStrip();
//	if ( it->second->getOptionalRollID().compare("B") ) continue;
//	cout << "SEC " << it->second->getSector()  << endl;
/*	cout << "OPT: " << it->second-> getOptionalRollID() << endl;
	cout << "RAW: " << it->second->getRawIDofClone(1) << endl;*/
//	cout << "PASS: "******"VALUE: " << nAnalyzer.HealCloneByClone(it->second) << endl;
        double rollArea = it->second->getRollArea();
        TotArea += rollArea;	
      }

      //Free RAM
      for (map<string,ExRoll* >::const_iterator it = barrelMap.begin(); it != barrelMap.end(); it++){
	delete it->second;
      }

      double NormalizedRate = TotRate / TotArea;
//       cout << NormalizedRate << endl;	      
  string zone = argv[1];                                                                                                                                                  
  string RollID = argv[4]; 
  int Sector = atoi(argv[3]);                                                                                                                                          
  int WheelDiskNo = atoi(argv[2]);     


        if (TotRate != 0 && TotArea != 0 && currentRun->getDelivered() != 0 && currentRun->isFilled()){
//	currentRun->PrintStatistics();	
             
             cout << currentRun->getID() <<
	     "\t" << currentRun->getLumiSection() << "\t" << currentRun->getDelivered() 
	     << "\t" << currentRun->getLumi() <<
	     "\t" << TotRate << "\t" << TotArea << "\t" << NormalizedRate/2 << endl;
		
// 	plot->SetBinContent(plot->FindBin(currentRun->getLumi()), NormalizedRate);
	cout << "POINT: " << k << " "  << currentRun->getLumi()<< " " << NormalizedRate / 2 << endl;; 
	plot->SetPoint(k , currentRun->getLumi(), NormalizedRate / 2);
	plotRun->SetPoint(k, currentRun->getID(), NormalizedRate / 2);
	k++;
	}
    }
    delete currentRun;
    contFile->Close();  
    contFile->Delete();
  }

  plot->SetDrawOption("P");
  f->WriteObject(plotRun, plotRun->GetName());
  f->WriteObject(plot, plot->GetName());

  
  return 0;
}
Example #18
0
//*******MAIN*******************************************************************
int main (int argc, char** argv)
{  
    std::cout<<"--------DUMPER TEMPLATE FIT: READ RAW DATA AND PRODUCE RECO TREE--------"<<std::endl;

    //-----this map tells how the MCPs will be order in the output tree. The names should match the cfg file----
    Fill_MCPList();  //look into the MCPMap.h class
    
    //--------Read Options--------------------------------
    ifstream inputCfg (argv[1], ios::in);

    std::string inputFolder = argv[2];
    int nChannels = atoi (argv[3]);
    std::string outputFile = argv[4];
    std::string ProMedioFile = argv[5];

    TProfile** wf_promed = new TProfile*[10];
    TH1F** templateHisto = new TH1F*[10];
    double pro_medio_CF[10] = {0., 0., 0., 0., 0., 0., 0., 0., 0., 0.};
    double pro_medio_Charge[10] = {0., 0., 0., 0., 0., 0., 0., 0., 0., 0.};
    TFile* inF = TFile::Open(ProMedioFile.c_str(),"read");                                                                
    for(int iCh=0; iCh<10; ++iCh) {
      wf_promed[iCh] = (TProfile*)inF->Get(Form("wf_promed_%d",iCh));                                                        
      wf_promed[iCh]->SetDirectory(0);                                                                                       
    }
    inF->Close();
    inF->Delete();                       
    for(int iCh=0; iCh<10; ++iCh) {                                                                                       
      templateHisto[iCh] = new TH1F(Form("templateHisto_%d",iCh), "", 1024, 0., 1024.);                                      
      for(int iBins=1; iBins<=1024; ++iBins) {
	if(iBins <= 100) templateHisto[iCh]->SetBinContent(iBins, wf_promed[iCh]->GetBinContent(iBins+150));  
	else if(iBins > 100 && iBins < 250) templateHisto[iCh]->SetBinContent(iBins, templateHisto[iCh]->GetBinContent(iBins-100));  
	else templateHisto[iCh]->SetBinContent(iBins, wf_promed[iCh]->GetBinContent(iBins));
      }
      double amp = 0.5;
      TimeConstFrac_ProMedio(templateHisto[iCh], amp, pro_medio_CF[iCh]);
      pro_medio_Charge[iCh] = templateHisto[iCh]->Integral(pro_medio_CF[iCh]-5, pro_medio_CF[iCh]+20);
      wf_promed[iCh]->Delete();                                                                                              
      //            std::cout << " iCh = " << iCh << " pro_medio_CF[iCh] = " << pro_medio_CF[iCh] << " pro_medio_Charge[iCh] = " << pro_medio_Charge[iCh] << std::endl;
    }                                                                                                                     


    // for(int iCh=0; iCh<10; ++iCh) std::cout << " templateHisto[iCh]->GetEntries() = " << templateHisto[iCh]->GetEntries() << std::endl;
    //    return 500;                                                                                            


    //---------output tree----------------
    TFile* outROOT = TFile::Open(("ntuples/reco_"+outputFile+".root").c_str(),"recreate");  
    outROOT->cd();
    
    TTree* outTree = new TTree("reco_tree", "reco_tree");
    outTree->SetDirectory(0);
    SetOutTree(outTree);
    
   
    int run=0, chNumber=0, HVtemp=0, PC=0;
    float X0temp=0.;
    std::string name, trig1, trig2;

    //---------definitions-----------
    std::map<int, int> PCOn;
    std::map<int, int> HVVal; 
    std::map<int, std::string> MCPName; 

    int start=0;
    //-------start to read the cfg file--------
    while(!inputCfg.eof())  
    {
      PCOn.clear();
      HVVal.clear();
      MCPName.clear();

      if (start==0) {   //read trigger chambers
	inputCfg >> trig1 >> trig2;
	start=1;
      }

      //-----fill maps--------
      for (int count=0; count<nChannels; count++)   //read exactly nChannels lines of the cfg file -> be careful to give the right number in input!!!!
	{
	  inputCfg >> run >> chNumber >> HVtemp >> X0temp >> PC >> name;

	  PCOn.insert(std::make_pair(chNumber,PC)); 
	  HVVal.insert(std::make_pair(chNumber,HVtemp)); 
	  MCPName.insert(std::make_pair(chNumber,name)); 
	}

      //-----Definitions
      vector<float> digiCh[10];
      float timeCF[10], timeCFcorr[10];
      float timeOT[10];
      float timeMax[10];
      float intBase[10], intSignal[10], intSignalcorr[10], ampMax[10];
      ///int fibreX[8], hodoYchannels[8];
      
      TH1F** wfHisto = new TH1F*[10];
      TF1** f_templateFit = new TF1*[10];      

      //--reading wire chamber from other tree --
      TChain* t1 = new TChain("outputTree");
      InitTree2(t1);

      //---Chain
      TChain* chain = new TChain("H4tree");
      InitTree(chain);

      char command1[300];
      sprintf(command1, "find  %s/%d/*/dqmPlotstotal.root > listTemp_%s_%d.txt", (inputFolder).c_str(), run, outputFile.c_str(), run);
      system(command1);
      char command2[300];
      sprintf(command2, "find  %s/%d/[0-9]*.root > listTemp2_%s_%d.txt", (inputFolder).c_str(), run, outputFile.c_str(), run);
      system(command2);

      char list1[200];
      char list2[200];
      sprintf (list1, "listTemp_%s_%d.txt", outputFile.c_str(), run);
      sprintf (list2, "listTemp2_%s_%d.txt", outputFile.c_str(), run);

      ifstream rootList (list1);
      ifstream rootList2 (list2);

      while (!rootList.eof() && !rootList2.eof())
	{
	  char iRun_tW[70];
	  rootList >> iRun_tW;
	  char iRun_str[70];
	  rootList2 >> iRun_str;
	  
	  TChain* tTemp = new TChain("outputTree");
	  tTemp->Add(iRun_tW);
	  TChain* tTempH4 = new TChain("H4tree");
	  tTempH4->Add(iRun_str);
	  
	  if (tTemp->GetEntries() == tTempH4->GetEntries())
	    {
	      t1->Add(iRun_tW);	
	      chain->Add(iRun_str);	
	    }
	  else
	    std::cout<<"Bad spill found.. Skipped"<<std::endl;
	  tTemp->Delete();
	  tTempH4->Delete();
	}

      char command3[300];
      sprintf(command3, "rm listTemp_%s_%d.txt", outputFile.c_str(), run);
      char command4[300];
      sprintf(command4, "rm listTemp2_%s_%d.txt", outputFile.c_str(), run);
      
      system(command3);
      system(command4);
      
      std::cout<<"start reading run: "<<run<<std::endl;
      
      //-----Data loop--------------------------------------------------------
      for(int iEntry=0; iEntry<chain->GetEntries(); iEntry++){
	//      for(int iEntry=7; iEntry<8; iEntry++){    //RA
	if(iEntry % 1000 == 0)	cout << "read entry: " << iEntry << endl;
            //-----Unpack data--------------------------------------------------
            for(int iCh=0; iCh<nChannels; iCh++)
            {
                digiCh[iCh].clear();
		wfHisto[iCh] = new TH1F(Form("wfHisto_%d", iCh), "", 1024, 0., 1024.);
            }

            //---Read the entry
            chain->GetEntry(iEntry);
 
	    unsigned int spill=spillNumber;
	    unsigned int event=evtNumber;

	    /*	    for(unsigned int iCh=0; iCh<nAdcChannels; iCh++)
		{
                    if(adcBoard[iCh] == 1 && adcChannel[iCh] == 0) 
                        sci_front_adc = adcData[iCh];
		    if(adcBoard[iCh] == 1 && adcChannel[iCh] >= HODOX_ADC_START_CHANNEL &&
		       adcChannel[iCh] <= HODOX_ADC_END_CHANNEL)
			fibreX[(adcChannel[iCh]-HODOX_ADC_START_CHANNEL)] = adcData[iCh];
		    if(adcBoard[iCh] == 1 && adcChannel[iCh] >= HODOY_ADC_START_CHANNEL &&
		       adcChannel[iCh] <= HODOY_ADC_END_CHANNEL)
			fibreY[(adcChannel[iCh]-HODOY_ADC_START_CHANNEL)] = adcData[iCh];
		}
	    */
	    int tStart[10] = {0,0,0,0,0,0,0,0,0,0};
	    int tStop[10] = {0,0,0,0,0,0,0,0,0,0};
	    int tMax[10] = {0,0,0,0,0,0,0,0,0,0};
	    float aMax[10] = {10000., 10000., 10000., 10000., 10000., 10000., 10000., 10000., 10000., 10000.};
	    float bLine[10] = {0.,0.,0.,0.,0., 0.,0.,0.,0.,0.};
	    //---Read digitizer samples
	    for(unsigned int iSample=0; iSample<nDigiSamples; iSample++){
	      if(iSample > 1024*10 - 1) break;
	      if (digiGroup[iSample] == 1 && digiChannel[iSample] == 0){
		digiCh[9].push_back(digiSampleValue[iSample]);
		wfHisto[9]->SetBinContent((iSample%1024) + 1, digiSampleValue[iSample]);

		int iBin = (iSample%1024) + 1;
		float value = digiSampleValue[iSample];
		if((iBin >= 10 && iBin < 30) || (iBin >= 500 && iBin < 1000)) bLine[9] += value/520;
		//		if(digiChannel[iSample] == 9) std::cout << " value = " << value << std::endl;
		if(value < aMax[9]) { aMax[9] = value; tMax[9] = iBin; }
		if(iBin > 50 && value < 500. && tStart[9] == 0) tStart[9] = iBin;
		if(iBin > 50 && value > 500. && tStart[9] != 0 && tStop[9] == 0) tStop[9] = iBin;		
	      }
	      else{
		digiCh[digiChannel[iSample]].push_back(digiSampleValue[iSample]);
		wfHisto[digiChannel[iSample]]->SetBinContent((iSample%1024) + 1, digiSampleValue[iSample]); 

		int iBin = (iSample%1024) + 1;
		float value = digiSampleValue[iSample];
		if((iBin >= 10 && iBin < 30) || (iBin >= 500 && iBin < 1000)) bLine[digiChannel[iSample]] += value/520;
		if(digiChannel[iSample] == 9) std::cout << " value = " << value << std::endl;
		if(value < aMax[digiChannel[iSample]]) { aMax[digiChannel[iSample]] = value; tMax[digiChannel[iSample]] = iBin;}
		if(iBin > 50 && value < 500. && tStart[digiChannel[iSample]] == 0) tStart[digiChannel[iSample]] = iBin;
		if(iBin > 50 && value > 500. && tStart[digiChannel[iSample]] != 0 && 
		   tStop[digiChannel[iSample]] == 0) tStop[digiChannel[iSample]] = iBin;
	      }
	    }

	    //---loop over MPC's channels  
            for(int iCh=0; iCh<nChannels; iCh++){
	      if(iCh < 4) continue;
	      if(iCh == 8) continue;

	      // std::cout << " loop over MCP iCh = " << iCh  << std::endl;
	      // std::cout << " bLine[iCh] = " << bLine[iCh] << std::endl;
	      // std::cout << " aMax[iCh] = " << aMax[iCh] << std::endl;
	      // std::cout << " tMax[iCh] = " << tMax[iCh] << std::endl;
	      // std::cout << " tStart[iCh] = " << tStart[iCh] << std::endl;
	      // std::cout << " tStop[iCh] = " << tStop[iCh] << std::endl;

	      tMax[iCh] -= 300;

	      double scale = 0.;
	      double scaleErr = 0.;
	      double baseL = 0.;
	      double baseLErr = 0.;
	      double xTime = 0.;
	      double xTimeErr = 0.;
	      
	      FindTemplateFit(scale, scaleErr, baseL, baseLErr, xTime, xTimeErr, tStart[iCh], tStop[iCh], tMax[iCh], aMax[iCh], bLine[iCh], templateHisto[iCh], wfHisto[iCh], &(f_templateFit[iCh]));

	      float par0 = f_templateFit[iCh]->GetParameter(0);
	      float par1 = f_templateFit[iCh]->GetParameter(1);
	      float par2 = f_templateFit[iCh]->GetParameter(2);
	      float par3 = f_templateFit[iCh]->GetParameter(3);

	      ampMax[iCh] = par0;
	      //tMax
	      timeMax[iCh] = (300. / par1) + par2;
	      timeCF[iCh] = (pro_medio_CF[iCh] / par1) + par2;
	      intSignal[iCh] = pro_medio_Charge[iCh] * par0/par1 + par3/par1 * 25;
	      intBase[iCh] = par3;

	      timeOT[iCh] = par2;
	      intSignalcorr[iCh] = par1;
	      timeCFcorr[iCh] = timeCF[iCh];

	      // std::cout << " >> timeMax[iCh] = " << timeMax[iCh] << std::endl;
	      // std::cout << " >> timeCF[iCh] = " << timeCF[iCh] << std::endl;
	      // std::cout << " >> f_templateFit[iCh]->GetParameter(0) = " << f_templateFit[iCh]->GetParameter(0) << std::endl;

	      /*
	      if(iCh == 4){
		TCanvas* c1 = new TCanvas();
		templateHisto[iCh]->Draw();
		f_templateFit[iCh]->Draw("same");
		c1->Print("pippo.png", "png");

		TCanvas* c2 = new TCanvas();
		wfHisto[iCh]->Draw();
		f_templateFit[iCh]->Draw("same");
		c2->Print("pippo2.png", "png");
		
		TFile outFile_template("outFile_template.root", "recreate");
		outFile_template.cd();
		iCh = 4;
		templateHisto[iCh]->Write(Form("promedio_%d", iCh));
		wfHisto[iCh]->Write(Form("wfHisto_%d", iCh));
		f_templateFit[iCh]->Write(Form("func_%d", iCh));
		outFile_template.Close();
	      }
	      */
	    }

	    /*	    
	    TFile outFile_template("outFile_template.root", "recreate");
	    outFile_template.cd();
	    for(int iCh=0; iCh<nChannels; iCh++){
	      if(iCh < 4) continue;
	      if(iCh == 8) continue;

	      templateHisto[iCh]->Write(Form("promedio_%d", iCh));
	      wfHisto[iCh]->Write(Form("wfHisto_%d", iCh));
	      f_templateFit[iCh]->Write(Form("func_%d", iCh));
	    }
	    outFile_template.Close();
	    return 100;
	    */

	    //--------dump ntuple - impulses are negative, invert the sign
	    for (int iCh=0; iCh<nChannels; iCh++)
	      {
		    time_CF[MCPList.at(MCPName.at(iCh))]   = timeCF[iCh];
		    time_CF_corr[MCPList.at(MCPName.at(iCh))]   = timeCFcorr[iCh];
		    time_OT[MCPList.at(MCPName.at(iCh))]   = timeOT[iCh];
		    time_Max[MCPList.at(MCPName.at(iCh))]   = timeMax[iCh];
		    amp_max[MCPList.at(MCPName.at(iCh))]   = ampMax[iCh];
		    amp_max_corr[MCPList.at(MCPName.at(iCh))]   = ampMax[iCh];
		    charge[MCPList.at(MCPName.at(iCh))]    = -intSignal[iCh];
		    charge_corr[MCPList.at(MCPName.at(iCh))]    = -intSignalcorr[iCh];
		    baseline[MCPList.at(MCPName.at(iCh))]  = intBase[iCh];

		    isPCOn[MCPList.at(MCPName.at(iCh))]      = PCOn.at(iCh);
		    HV[MCPList.at(MCPName.at(iCh))]          = HVVal.at(iCh);
		    if (strcmp((MCPName.at(iCh)).c_str(),trig1.c_str())==0)          isTrigger[MCPList.at(MCPName.at(iCh))] = 1;
		    //		    else if (strcmp((MCPName.at(iCh)).c_str(),trig2.c_str())==0)     isTrigger[MCPList.at(MCPName.at(iCh))] = 2;
		    else                                           isTrigger[MCPList.at(MCPName.at(iCh))] = 0;
		      
		    wfHisto[iCh]->Delete();
		  }
	    
      	     run_id = run;
	     X0     = X0temp;

	     t1->GetEntry(iEntry);
	     tdcX = (*TDCreco)[0];
	     tdcY = (*TDCreco)[1];

	     if (spill!=spillNumber || event!=evtNumber) {
	       std::cout<<"PROBLEM: non-coherent read"<<std::endl;
	       continue;
	     }

	     outTree->Fill();    
	     
      }
 
       //---Get ready for next run
        chain->Delete();
	t1->Delete();
    }
vector <double> finalize2012_gammaJets(double int_exp_2012_30, double int_exp_2012_50, double int_exp_2012_75, double int_exp_2012_90, double pt1min_30=30, double pt1min_50=50, double pt1min_75=75, double pt1min_90=90, double pt1max_30=30, double pt1max_50=50, double pt1max_75=75, double pt1max_90=90, int eb = 1, int r9 = 1, string variableMC = "massgg", string variableData = "massgg", int nbin = 200, double min = 90, double max = 190, string axis = "m(#gamma#gamma)[GeV]"){
  
  gROOT->SetStyle("Plain");
  gStyle->SetPalette(1);
  gStyle->SetOptStat(1111111);  
  gStyle->SetOptFit(111110); 
  gStyle->SetOptFile(1); 
  gStyle->SetMarkerStyle(20);
  gStyle->SetMarkerSize(.3);
  gStyle->SetMarkerColor(1);
  
  TCanvas* c0 = new TCanvas("c0"," ",200,10,500,500);
  c0->Clear();
  
  // input files
  string mcnames[16];
  mcnames[0]  = "QCD, 20-30";
  mcnames[1]  = "QCD, 30-80";
  mcnames[2]  = "QCD, 80-170";
  mcnames[3]  = "QCD, 170-250";
  mcnames[4]  = "QCD, 250-350";
  mcnames[5]  = "QCD, >350";
  mcnames[6]  = "gjet, 0-15";
  mcnames[7]  = "gjet, 15-30";
  mcnames[8]  = "gjet, 30-50";
  mcnames[9]  = "gjet, 50-80";
  mcnames[10] = "gjet, 80-120";
  mcnames[11] = "gjet, 120-170";
  mcnames[12] = "gjet, 170-300";
  // 
  mcnames[13] = "gjet, 470-800";
  mcnames[14] = "gjet, 800-1400";
  mcnames[15] = "gjet, 1400-1800";

  TFile* mc_2012[16];            // [16] = MC samples

  TString redntpDir= "/xrootdfs/cms/local/crovelli/GammaJets/reduced";

  // full 2012                                     
  TFile* data = TFile::Open(redntpDir+"/redntp.53xv2_data.cicpfloose.noCorrections.GammaJets_newNtuples_v5/merged/all2012.root");
  
  // mc signal and backgrounds   
  if( int_exp_2012_30 > 0 ){
    
    // QCD samples
    mc_2012[0] = TFile::Open(redntpDir+"/redntp.53xv2.cicpfloose.noCorrections.GammaJets_newNtuples_v5/merged/redntp_QCD_Pt_20_30_EMEnriched_TuneZ2star_8TeV_pythia6.root");
    mc_2012[1] = TFile::Open(redntpDir+"/redntp.53xv2.cicpfloose.noCorrections.GammaJets_newNtuples_v5/merged/redntp_QCD_Pt_30_80_EMEnriched_TuneZ2star_8TeV_pythia6.root");
    mc_2012[2] = TFile::Open(redntpDir+"/redntp.53xv2.cicpfloose.noCorrections.GammaJets_newNtuples_v5/merged/redntp_QCD_Pt_80_170_EMEnriched_TuneZ2star_8TeV_pythia6.root");
    mc_2012[3] = TFile::Open(redntpDir+"/redntp.53xv2.cicpfloose.noCorrections.GammaJets_newNtuples_v5/merged/redntp_QCD_Pt_170_250_EMEnriched_TuneZ2star_8TeV_pythia6.root");
    mc_2012[4] = TFile::Open(redntpDir+"/redntp.53xv2.cicpfloose.noCorrections.GammaJets_newNtuples_v5/merged/redntp_QCD_Pt_250_350_EMEnriched_TuneZ2star_8TeV_pythia6.root");
    mc_2012[5] = TFile::Open(redntpDir+"/redntp.53xv2.cicpfloose.noCorrections.GammaJets_newNtuples_v5/merged/redntp_QCD_Pt_350_EMEnriched_TuneZ2star_8TeV_pythia6.root");
    // gjet samples 
    mc_2012[6]  = TFile::Open(redntpDir+"/redntp.53xv2.cicpfloose.noCorrections.GammaJets_newNtuples_v5/merged/redntp_G_Pt-0to15_TuneZ2star_8TeV_pythia6.root");
    mc_2012[7]  = TFile::Open(redntpDir+"/redntp.53xv2.cicpfloose.noCorrections.GammaJets_newNtuples_v5/merged/redntp_G_Pt-15to30_TuneZ2star_8TeV_pythia6.root");
    mc_2012[8]  = TFile::Open(redntpDir+"/redntp.53xv2.cicpfloose.noCorrections.GammaJets_newNtuples_v5/merged/redntp_G_Pt-30to50_TuneZ2star_8TeV_pythia6.root");
    mc_2012[9]  = TFile::Open(redntpDir+"/redntp.53xv2.cicpfloose.noCorrections.GammaJets_newNtuples_v5/merged/redntp_G_Pt-50to80_TuneZ2star_8TeV_pythia6.root");
    mc_2012[10] = TFile::Open(redntpDir+"/redntp.53xv2.cicpfloose.noCorrections.GammaJets_newNtuples_v5/merged/redntp_G_Pt-80to120_TuneZ2star_8TeV_pythia6.root");
    mc_2012[11] = TFile::Open(redntpDir+"/redntp.53xv2.cicpfloose.noCorrections.GammaJets_newNtuples_v5/merged/redntp_G_Pt-120to170_TuneZ2star_8TeV_pythia6.root");
    mc_2012[12] = TFile::Open(redntpDir+"/redntp.53xv2.cicpfloose.noCorrections.GammaJets_newNtuples_v5/merged/redntp_G_Pt-170to300_TuneZ2star_8TeV_pythia6.root");
    mc_2012[13] = TFile::Open(redntpDir+"/redntp.53xv2.cicpfloose.noCorrections.GammaJets_newNtuples_v5/merged/redntp_G_Pt-470to800_TuneZ2star_8TeV_pythia6.root");
    mc_2012[14] = TFile::Open(redntpDir+"/redntp.53xv2.cicpfloose.noCorrections.GammaJets_newNtuples_v5/merged/redntp_G_Pt-800to1400_TuneZ2star_8TeV_pythia6.root");
    mc_2012[15] = TFile::Open(redntpDir+"/redntp.53xv2.cicpfloose.noCorrections.GammaJets_newNtuples_v5/merged/redntp_G_Pt-1400to1800_TuneZ2star_8TeV_pythia6.root");
  }
  
  // k factors 
  double kfactorqcd    = 1.;   
  double kfactorgamjet = 1.3;           //  chiara: still valid?

  // cross sections at 8 TeV - all from PREP
  double cross_mc[16];
  cross_mc[0]  = 288600000 * 0.0101 * kfactorqcd;         
  cross_mc[1]  = 74330000 * 0.0621 * kfactorqcd;         
  cross_mc[2]  = 1191000 * 0.1539 * kfactorqcd;         
  cross_mc[3]  = 30990 * 0.148 * kfactorqcd;         
  cross_mc[4]  = 4250 * 0.131 * kfactorqcd;         
  cross_mc[5]  = 810 * 0.11 * kfactorqcd;          
  cross_mc[6]  = 90601456 * kfactorgamjet;          
  cross_mc[7]  = 200061.7 * kfactorgamjet;          
  cross_mc[8]  = 19931.62 * kfactorgamjet;          
  cross_mc[9]  = 3322.309 * kfactorgamjet;          
  cross_mc[10] = 558.2865 * kfactorgamjet;          
  cross_mc[11] = 108.0068 * kfactorgamjet;          
  cross_mc[12] = 30.12207 * kfactorgamjet;          
  cross_mc[13] = 0.2119244 * kfactorgamjet;          
  cross_mc[14] = 0.007077847 * kfactorgamjet;          
  cross_mc[15] = 4.510327 * 0.00001 * kfactorgamjet;          

  // getting the number of original events in each sample (processed with CMSSW)
  int n_mc_2012[16];   
  for(int i=0; i<16; i++){
    n_mc_2012[i] = 0;
    if(int_exp_2012_30>0) n_mc_2012[i] = ((TH1D*)mc_2012[i]->Get("ptphotgen1"))->GetEntries();  
  }

  // setting the scaling factor to actual lumi 
  double scale_mc_2012_30[16];
  double scale_mc_2012_50[16];
  double scale_mc_2012_75[16];
  double scale_mc_2012_90[16];

  for(int i=0; i<16; i++){
    scale_mc_2012_30[i] = 0; 
    scale_mc_2012_50[i] = 0; 
    scale_mc_2012_75[i] = 0; 
    scale_mc_2012_90[i] = 0; 
    if(int_exp_2012_30>0) scale_mc_2012_30[i] = cross_mc[i] * int_exp_2012_30 / n_mc_2012[i];
    if(int_exp_2012_50>0) scale_mc_2012_50[i] = cross_mc[i] * int_exp_2012_50 / n_mc_2012[i];
    if(int_exp_2012_75>0) scale_mc_2012_75[i] = cross_mc[i] * int_exp_2012_75 / n_mc_2012[i];
    if(int_exp_2012_90>0) scale_mc_2012_90[i] = cross_mc[i] * int_exp_2012_90 / n_mc_2012[i];
  }

  // char for output name
  char name[1000];
  
  // output root file
  sprintf(name,"results_gammaJ/histo.root");
  TFile * hOutputFile = new TFile(name, "RECREATE" ) ;

  // histograms needed by the machinery
  TH1D* vardata_30 = new TH1D("vardata_30", "vardata_30", nbin,min,max);
  TH1D* vardata_50 = new TH1D("vardata_50", "vardata_50", nbin,min,max);
  TH1D* vardata_75 = new TH1D("vardata_75", "vardata_75", nbin,min,max);
  TH1D* vardata_90 = new TH1D("vardata_90", "vardata_90", nbin,min,max);

  vardata_30->Sumw2();
  vardata_50->Sumw2();
  vardata_75->Sumw2();
  vardata_90->Sumw2();

  TH1D* var_mc_2012_30[16];     // 16 = MC samples we have 
  TH1D* var_mc_2012_50[16];     // 16 = MC samples we have 
  TH1D* var_mc_2012_75[16];     // 16 = MC samples we have 
  TH1D* var_mc_2012_90[16];     // 16 = MC samples we have 

  TH1D* var_30[2];              // 2  = number of species
  TH1D* var_50[2];              // 2  = number of species
  TH1D* var_75[2];              // 2  = number of species
  TH1D* var_90[2];              // 2  = number of species

  for (int i=0; i<2; i++) {
    sprintf(name,"%s%d","var_30",i);
    var_30[i] = new TH1D(name,name,nbin,min,max);
    var_30[i]->Sumw2();          
    sprintf(name,"%s%d","var_50",i);
    var_50[i] = new TH1D(name,name,nbin,min,max);
    var_50[i]->Sumw2();          
    sprintf(name,"%s%d","var_75",i);
    var_75[i] = new TH1D(name,name,nbin,min,max);
    var_75[i]->Sumw2();          
    sprintf(name,"%s%d","var_90",i);
    var_90[i] = new TH1D(name,name,nbin,min,max);
    var_90[i]->Sumw2();          
 }

  for (int i=0; i<16; i++) {
    sprintf(name,"%s%d","var_mc_2012_30_",i);
    var_mc_2012_30[i] = new TH1D(name,name,nbin,min,max);
    var_mc_2012_30[i]->Sumw2();  
    sprintf(name,"%s%d","var_mc_2012_50_",i);
    var_mc_2012_50[i] = new TH1D(name,name,nbin,min,max);
    var_mc_2012_50[i]->Sumw2();  
    sprintf(name,"%s%d","var_mc_2012_75_",i);
    var_mc_2012_75[i] = new TH1D(name,name,nbin,min,max);
    var_mc_2012_75[i]->Sumw2();  
    sprintf(name,"%s%d","var_mc_2012_90_",i);
    var_mc_2012_90[i] = new TH1D(name,name,nbin,min,max);
    var_mc_2012_90[i]->Sumw2();  
  }




  // 1) HLT = 30
  cout << endl;
  cout << "------------------- HLT = 30 -------------------" << endl; 

  // creating the fillers and setting cuts: data
  fillPlot2012_gammaJets data_fill_30((TTree*)data->Get("AnaTree"));
  data_fill_30.Setcuts(pt1min_30,pt1max_30,eb,r9,30);  

  // analysis, data, HLT = 30 
  cout << "running over " << ((TTree*)data->Get("AnaTree"))->GetEntries("") << " data events for HLT 30" <<  endl;
  sprintf(name,"results_gammaJ/events_HLT30.root");
  data_fill_30.WriteRoot(name);
  vardata_30->Add(data_fill_30.Plot(variableData,"data", nbin, min, max, 100)); 
  std::cout << "Selected events on data " << vardata_30->GetEntries() << " with HLT = 30" << std::endl;

  // creating the fillers and setting cuts: MC, HLT = 30
  fillPlot2012_gammaJets* mc_2012_fill_30[16];
  for (int i=0; i<16; i++){
    if(int_exp_2012_30>0) mc_2012_fill_30[i] = new fillPlot2012_gammaJets((TTree*)mc_2012[i]->Get("AnaTree"));   
    if(int_exp_2012_30>0) mc_2012_fill_30[i]->Setcuts(pt1min_30,pt1max_30,eb,r9,30); 
    mc_2012_fill_30[i]->DoPuReweight();
  }

  // analysis, MC, HLT = 30 
  for (int i=0; i<16; i++){ 
    sprintf(name,"%s%s",mcnames[i].c_str()," 2012");
    if(int_exp_2012_30>0) {
      cout << "running over " << ((TTree*)mc_2012[i]->Get("AnaTree"))->GetEntries("") << " " << name << " events for HLT 30" <<  endl;   
      sprintf(name,"%s%s%s","results_gammaJ/events_",mcnames[i].c_str(),"_2012_HLT30.root");
      mc_2012_fill_30[i]->WriteRoot(name);             
      var_mc_2012_30[i]->Add( mc_2012_fill_30[i]->Plot(variableMC, name, nbin, min, max, i) );  
      std::cout << "Selected events on mc2012 " << name << " for HLT=30 " << var_mc_2012_30[i]->GetEntries() << std::endl;
    }
  }
  cout << endl;


  // 2) HLT = 50
  cout << endl;
  cout << "------------------- HLT = 50 -------------------" << endl; 

  // creating the fillers and setting cuts: data
  fillPlot2012_gammaJets data_fill_50((TTree*)data->Get("AnaTree"));
  data_fill_50.Setcuts(pt1min_50,pt1max_50,eb,r9,50);  

  // analysis, data, HLT = 50 
  cout << "running over " << ((TTree*)data->Get("AnaTree"))->GetEntries("") << " data events for HLT 50" <<  endl;
  sprintf(name,"results_gammaJ/events_HLT50.root");
  data_fill_50.WriteRoot(name);
  vardata_50->Add(data_fill_50.Plot(variableData,"data", nbin, min, max, 100)); 
  std::cout << "Selected events on data " << vardata_50->GetEntries() << " with HLT = 50" << std::endl;

  // creating the fillers and setting cuts: MC, HLT = 50
  fillPlot2012_gammaJets* mc_2012_fill_50[16];
  for (int i=0; i<16; i++){
    if(int_exp_2012_50>0) mc_2012_fill_50[i] = new fillPlot2012_gammaJets((TTree*)mc_2012[i]->Get("AnaTree"));   
    if(int_exp_2012_50>0) mc_2012_fill_50[i]->Setcuts(pt1min_50,pt1max_50,eb,r9,50); 
    mc_2012_fill_50[i]->DoPuReweight();
  }

  // analysis, MC, HLT = 50 
  for (int i=0; i<16; i++){ 
    sprintf(name,"%s%s",mcnames[i].c_str()," 2012");
    if(int_exp_2012_50>0) {
      cout << "running over " << ((TTree*)mc_2012[i]->Get("AnaTree"))->GetEntries("") << " " << name << " events for HLT 50" <<  endl;   
      sprintf(name,"%s%s%s","results_gammaJ/events_",mcnames[i].c_str(),"_2012_HLT50.root");
      mc_2012_fill_50[i]->WriteRoot(name);             
      var_mc_2012_50[i]->Add( mc_2012_fill_50[i]->Plot(variableMC, name, nbin, min, max, i) );  
      std::cout << "Selected events on mc2012 " << name << " for HLT=50 " << var_mc_2012_50[i]->GetEntries() << std::endl;
    }
  }
  cout << endl;


  // 1) HLT = 75
  cout << endl;
  cout << "------------------- HLT = 75 -------------------" << endl; 

  // creating the fillers and setting cuts: data
  fillPlot2012_gammaJets data_fill_75((TTree*)data->Get("AnaTree"));
  data_fill_75.Setcuts(pt1min_75,pt1max_75,eb,r9,75);  

  // analysis, data, HLT = 75 
  cout << "running over " << ((TTree*)data->Get("AnaTree"))->GetEntries("") << " data events for HLT 75" <<  endl;
  sprintf(name,"results_gammaJ/events_HLT75.root");
  data_fill_75.WriteRoot(name);
  vardata_75->Add(data_fill_75.Plot(variableData,"data", nbin, min, max, 100)); 
  std::cout << "Selected events on data " << vardata_75->GetEntries() << " with HLT = 75" << std::endl;

  // creating the fillers and setting cuts: MC, HLT = 75
  fillPlot2012_gammaJets* mc_2012_fill_75[16];
  for (int i=0; i<16; i++){
    if(int_exp_2012_75>0) mc_2012_fill_75[i] = new fillPlot2012_gammaJets((TTree*)mc_2012[i]->Get("AnaTree"));   
    if(int_exp_2012_75>0) mc_2012_fill_75[i]->Setcuts(pt1min_75,pt1max_75,eb,r9,75); 
    mc_2012_fill_75[i]->DoPuReweight();
  }

  // analysis, MC, HLT = 75 
  for (int i=0; i<16; i++){ 
    sprintf(name,"%s%s",mcnames[i].c_str()," 2012");
    if(int_exp_2012_75>0) {
      cout << "running over " << ((TTree*)mc_2012[i]->Get("AnaTree"))->GetEntries("") << " " << name << " events for HLT 75" <<  endl;   
      sprintf(name,"%s%s%s","results_gammaJ/events_",mcnames[i].c_str(),"_2012_HLT75.root");
      mc_2012_fill_75[i]->WriteRoot(name);             
      var_mc_2012_75[i]->Add( mc_2012_fill_75[i]->Plot(variableMC, name, nbin, min, max, i) );  
      std::cout << "Selected events on mc2012 " << name << " for HLT=75 " << var_mc_2012_75[i]->GetEntries() << std::endl;
    }
  }
  cout << endl;

  // 1) HLT = 90
  cout << endl;
  cout << "------------------- HLT = 90 -------------------" << endl; 

  // creating the fillers and setting cuts: data
  fillPlot2012_gammaJets data_fill_90((TTree*)data->Get("AnaTree"));
  data_fill_90.Setcuts(pt1min_90,pt1max_90,eb,r9,90);  

  // analysis, data, HLT = 90 
  cout << "running over " << ((TTree*)data->Get("AnaTree"))->GetEntries("") << " data events for HLT 90" <<  endl;
  sprintf(name,"results_gammaJ/events_HLT90.root");
  data_fill_90.WriteRoot(name);
  vardata_90->Add(data_fill_90.Plot(variableData,"data", nbin, min, max, 100)); 
  std::cout << "Selected events on data " << vardata_90->GetEntries() << " with HLT = 90" << std::endl;

  // creating the fillers and setting cuts: MC, HLT = 90
  fillPlot2012_gammaJets* mc_2012_fill_90[16];
  for (int i=0; i<16; i++){
    if(int_exp_2012_90>0) mc_2012_fill_90[i] = new fillPlot2012_gammaJets((TTree*)mc_2012[i]->Get("AnaTree"));   
    if(int_exp_2012_90>0) mc_2012_fill_90[i]->Setcuts(pt1min_90,pt1max_90,eb,r9,90); 
    mc_2012_fill_90[i]->DoPuReweight();
  }

  // analysis, MC, HLT = 90 
  for (int i=0; i<16; i++){ 
    sprintf(name,"%s%s",mcnames[i].c_str()," 2012");
    if(int_exp_2012_90>0) {
      cout << "running over " << ((TTree*)mc_2012[i]->Get("AnaTree"))->GetEntries("") << " " << name << " events for HLT 90" <<  endl;   
      sprintf(name,"%s%s%s","results_gammaJ/events_",mcnames[i].c_str(),"_2012_HLT90.root");
      mc_2012_fill_90[i]->WriteRoot(name);             
      var_mc_2012_90[i]->Add( mc_2012_fill_90[i]->Plot(variableMC, name, nbin, min, max, i) );  
      std::cout << "Selected events on mc2012 " << name << " for HLT=90 " << var_mc_2012_90[i]->GetEntries() << std::endl;
    }
  }
  cout << endl;


  // scale mc to equivalent lumi for each HLT path
  for (int i=0; i<16; i++){
    if(int_exp_2012_30>0) var_mc_2012_30[i]->Scale(scale_mc_2012_30[i]);  
    if(int_exp_2012_50>0) var_mc_2012_50[i]->Scale(scale_mc_2012_50[i]);  
    if(int_exp_2012_75>0) var_mc_2012_75[i]->Scale(scale_mc_2012_75[i]);  
    if(int_exp_2012_90>0) var_mc_2012_90[i]->Scale(scale_mc_2012_90[i]);  
  }

  // counting number of events passing selection (scaled)   
  double num_mc_2012_30[16], num_uns_mc_2012_30[16]; 
  double num_mc_2012_50[16], num_uns_mc_2012_50[16]; 
  double num_mc_2012_75[16], num_uns_mc_2012_75[16]; 
  double num_mc_2012_90[16], num_uns_mc_2012_90[16]; 

  for (int i=0; i<16; i++){ 
    num_mc_2012_30[i] = 0;
    if(int_exp_2012_30>0) num_mc_2012_30[i] = var_mc_2012_30[i]->Integral();        
    num_mc_2012_50[i] = 0;
    if(int_exp_2012_50>0) num_mc_2012_50[i] = var_mc_2012_50[i]->Integral();        
    num_mc_2012_75[i] = 0;
    if(int_exp_2012_75>0) num_mc_2012_75[i] = var_mc_2012_75[i]->Integral();        
    num_mc_2012_90[i] = 0;
    if(int_exp_2012_90>0) num_mc_2012_90[i] = var_mc_2012_90[i]->Integral();        
    // 
    num_uns_mc_2012_30[i] = 0;
    if(int_exp_2012_30>0) num_uns_mc_2012_30[i] = var_mc_2012_30[i]->Integral();        
    num_uns_mc_2012_50[i] = 0;
    if(int_exp_2012_50>0) num_uns_mc_2012_50[i] = var_mc_2012_50[i]->Integral();        
    num_uns_mc_2012_75[i] = 0;
    if(int_exp_2012_75>0) num_uns_mc_2012_75[i] = var_mc_2012_75[i]->Integral();        
    num_uns_mc_2012_90[i] = 0;
    if(int_exp_2012_90>0) num_uns_mc_2012_90[i] = var_mc_2012_90[i]->Integral();        
  }

  // scale control sample
  double num_data_30 = vardata_30->Integral();
  double num_data_50 = vardata_50->Integral();
  double num_data_75 = vardata_75->Integral();
  double num_data_90 = vardata_90->Integral();

  for (int j=0; j<2; j++){   
    int offset(0);
    if(j>0) offset = 9;    // to add gamma+jets contributions up 
    for (int k=0 ; k<16-j-offset; k++){   
      if(int_exp_2012_30>0) var_30[j]->Add(var_mc_2012_30[k]);
      if(int_exp_2012_50>0) var_50[j]->Add(var_mc_2012_50[k]);
      if(int_exp_2012_75>0) var_75[j]->Add(var_mc_2012_75[k]);
      if(int_exp_2012_90>0) var_90[j]->Add(var_mc_2012_90[k]);
    }	
  }

  // final plots
  char ytitle_30[100], ytitle_50[100], ytitle_75[100], ytitle_90[100];
  sprintf(ytitle_30,"%s%d%s","N_{ev}/",int(int_exp_2012_30),"pb^{-1}");
  sprintf(ytitle_50,"%s%d%s","N_{ev}/",int(int_exp_2012_50),"pb^{-1}");
  sprintf(ytitle_75,"%s%d%s","N_{ev}/",int(int_exp_2012_75),"pb^{-1}");
  sprintf(ytitle_90,"%s%d%s","N_{ev}/",int(int_exp_2012_90),"pb^{-1}");
  for(int i=0; i<2; i++){
    var_30[i]->SetTitle("");
    var_30[i]->SetStats(0);
    var_30[i]->SetTitleOffset(1.25,"Y");
    var_30[i]->SetYTitle(ytitle_30);
    var_30[i]->SetXTitle(axis.c_str());
    var_30[i]->SetLineColor(kBlack);
    var_30[i]->SetLineWidth(2);
    //
    var_50[i]->SetTitle("");
    var_50[i]->SetStats(0);
    var_50[i]->SetTitleOffset(1.25,"Y");
    var_50[i]->SetYTitle(ytitle_50);
    var_50[i]->SetXTitle(axis.c_str());
    var_50[i]->SetLineColor(kBlack);
    var_50[i]->SetLineWidth(2);
    //
    var_75[i]->SetTitle("");
    var_75[i]->SetStats(0);
    var_75[i]->SetTitleOffset(1.25,"Y");
    var_75[i]->SetYTitle(ytitle_75);
    var_75[i]->SetXTitle(axis.c_str());
    var_75[i]->SetLineColor(kBlack);
    var_75[i]->SetLineWidth(2);
    //
    var_90[i]->SetTitle("");
    var_90[i]->SetStats(0);
    var_90[i]->SetTitleOffset(1.25,"Y");
    var_90[i]->SetYTitle(ytitle_90);
    var_90[i]->SetXTitle(axis.c_str());
    var_90[i]->SetLineColor(kBlack);
    var_90[i]->SetLineWidth(2);
  }


  // ----------------------------------------
  TLegendEntry *legge;
  TLegend *leg;
  leg = new TLegend(0.6,0.6,0.85,0.85);
  leg->SetFillStyle(0); leg->SetBorderSize(0); leg->SetTextSize(0.05);
  leg->SetFillColor(0);
  legge = leg->AddEntry(var_30[0], "gamma+jets", "f");
  legge = leg->AddEntry(var_30[1], "QCD", "f");

  // mc only plot: data vs background, HLT=30
  var_30[0]->SetFillColor(kBlue-9);
  var_30[0]->Draw("hist");
  var_30[1]->SetFillColor(kMagenta-9);
  var_30[1]->Draw("samehist");
  leg->Draw();
  sprintf(name,"%s%s%s","results_gammaJ/mc_",variableData.c_str(),"_HLT-30.png");
  c0->SaveAs(name);
  sprintf(name,"%s%s%s","results_gammaJ/mc_",variableData.c_str(),"_HLT-30.root");
  c0->SaveAs(name);

  // mc only plot: data vs background, HLT=50
  var_50[0]->SetFillColor(kBlue-9);
  var_50[0]->Draw("hist");
  var_50[1]->SetFillColor(kMagenta-9);
  var_50[1]->Draw("samehist");
  leg->Draw();
  sprintf(name,"%s%s%s","results_gammaJ/mc_",variableData.c_str(),"_HLT-50.png");
  c0->SaveAs(name);
  sprintf(name,"%s%s%s","results_gammaJ/mc_",variableData.c_str(),"_HLT-50.root");
  c0->SaveAs(name);

  // mc only plot: data vs background, HLT=75
  var_75[0]->SetFillColor(kBlue-9);
  var_75[0]->Draw("hist");
  var_75[1]->SetFillColor(kMagenta-9);
  var_75[1]->Draw("samehist");
  leg->Draw();
  sprintf(name,"%s%s%s","results_gammaJ/mc_",variableData.c_str(),"_HLT-75.png");
  c0->SaveAs(name);
  sprintf(name,"%s%s%s","results_gammaJ/mc_",variableData.c_str(),"_HLT-75.root");
  c0->SaveAs(name);

  // mc only plot: data vs background, HLT=90
  var_90[0]->SetFillColor(kBlue-9);
  var_90[0]->Draw("hist");
  var_90[1]->SetFillColor(kMagenta-9);
  var_90[1]->Draw("samehist");
  leg->Draw();
  sprintf(name,"%s%s%s","results_gammaJ/mc_",variableData.c_str(),"_HLT-90.png");
  c0->SaveAs(name);
  sprintf(name,"%s%s%s","results_gammaJ/mc_",variableData.c_str(),"_HLT-90.root");
  c0->SaveAs(name);

  // all together, mc only
  TH1D* var_all_0 = (TH1D*) var_30[0]->Clone("var_all_0");
  TH1D* var_all_1 = (TH1D*) var_30[1]->Clone("var_all_1");
  var_all_0->Add(var_50[0]);
  var_all_0->Add(var_75[0]);
  var_all_0->Add(var_90[0]);
  var_all_1->Add(var_50[1]);
  var_all_1->Add(var_75[1]);
  var_all_1->Add(var_90[1]);
  var_all_0->SetFillColor(kBlue-9);
  var_all_0->Draw("hist");
  var_all_1->SetFillColor(kMagenta-9);
  var_all_1->Draw("samehist");
  leg->Draw();
  sprintf(name,"%s%s%s","results_gammaJ/mc_",variableData.c_str(),"_all.png");
  c0->SaveAs(name);
  sprintf(name,"%s%s%s","results_gammaJ/mc_",variableData.c_str(),"_all.root");
  c0->SaveAs(name);  

  // ------------------------------------
  // data only plot, HLT = 30
  vardata_30->SetXTitle(axis.c_str());
  vardata_30->SetTitle("");
  vardata_30->SetStats(0);
  vardata_30->SetMarkerStyle(8);
  vardata_30->SetMarkerSize(.9);
  vardata_30->SetTitleOffset(1.25,"Y");
  vardata_30->Draw("pe");
  sprintf(name,"%s%s%s","results_gammaJ/data_",variableData.c_str(),"_HLT-30.png");
  c0->SaveAs(name);

  // data only plot, HLT = 50
  vardata_50->SetXTitle(axis.c_str());
  vardata_50->SetTitle("");
  vardata_50->SetStats(0);
  vardata_50->SetMarkerStyle(8);
  vardata_50->SetMarkerSize(.9);
  vardata_50->SetTitleOffset(1.25,"Y");
  vardata_50->Draw("pe");
  sprintf(name,"%s%s%s","results_gammaJ/data_",variableData.c_str(),"_HLT-50.png");
  c0->SaveAs(name);

  // data only plot, HLT = 75
  vardata_75->SetXTitle(axis.c_str());
  vardata_75->SetTitle("");
  vardata_75->SetStats(0);
  vardata_75->SetMarkerStyle(8);
  vardata_75->SetMarkerSize(.9);
  vardata_75->SetTitleOffset(1.25,"Y");
  vardata_75->Draw("pe");
  sprintf(name,"%s%s%s","results_gammaJ/data_",variableData.c_str(),"_HLT-75.png");
  c0->SaveAs(name);

  // data only plot, HLT = 90
  vardata_90->SetXTitle(axis.c_str());
  vardata_90->SetTitle("");
  vardata_90->SetStats(0);
  vardata_90->SetMarkerStyle(8);
  vardata_90->SetMarkerSize(.9);
  vardata_90->SetTitleOffset(1.25,"Y");
  vardata_90->Draw("pe");
  sprintf(name,"%s%s%s","results_gammaJ/data_",variableData.c_str(),"_HLT-90.png");
  c0->SaveAs(name);

  // all together
  TH1D* vardata_all = (TH1D*) vardata_30->Clone("vardata_all");
  vardata_all->Add(vardata_50);
  vardata_all->Add(vardata_75);
  vardata_all->Add(vardata_90);
  vardata_all->SetXTitle(axis.c_str());
  vardata_all->SetTitle("");
  vardata_all->SetStats(0);
  vardata_all->SetMarkerStyle(8);
  vardata_all->SetMarkerSize(.9);
  vardata_all->SetTitleOffset(1.25,"Y");
  vardata_all->Draw("pe");
  sprintf(name,"%s%s%s","results_gammaJ/data_",variableData.c_str(),"_all.png");
  c0->SaveAs(name);

  // -----------------------------------------------
  // data overlaid to mc
  legge = leg->AddEntry(vardata_30, "data", "p");

  double themax_30 = vardata_30->GetMaximum();
  if(var_30[0]->GetMaximum()>themax_30) themax_30 = var_30[0]->GetMaximum();
  if (themax_30>0) {  
    if ( variableData == "etaphot1" || variableData == "phiphot1" ) 
      vardata_30->SetMaximum(themax_30*2.0);
    else
      vardata_30->SetMaximum(themax_30*1.1);
    vardata_30->SetMinimum(0.000001);
  } else {
    vardata_30->SetMaximum(0.00001);
  }

  double themax_50 = vardata_50->GetMaximum();
  if(var_50[0]->GetMaximum()>themax_50) themax_50 = var_50[0]->GetMaximum();
  if (themax_50>0) {  
    if ( variableData == "etaphot1" || variableData == "phiphot1" ) 
      vardata_50->SetMaximum(themax_50*2.0);
    else
      vardata_50->SetMaximum(themax_50*1.1);
    vardata_50->SetMinimum(0.000001);
  } else {
    vardata_50->SetMaximum(0.00001);
  }

  double themax_75 = vardata_75->GetMaximum();
  if(var_75[0]->GetMaximum()>themax_75) themax_75 = var_75[0]->GetMaximum();
  if (themax_75>0) {  
    if ( variableData == "etaphot1" || variableData == "phiphot1" ) 
      vardata_75->SetMaximum(themax_75*2.0);
    else
      vardata_75->SetMaximum(themax_75*1.1);
    vardata_75->SetMinimum(0.000001);
  } else {
    vardata_75->SetMaximum(0.00001);
  }

  double themax_90 = vardata_90->GetMaximum();
  if(var_90[0]->GetMaximum()>themax_90) themax_90 = var_90[0]->GetMaximum();
  if (themax_90>0) {
    if ( variableData == "etaphot1" || variableData == "phiphot1" ) 
      vardata_90->SetMaximum(themax_90*2.0);
    else
      vardata_90->SetMaximum(themax_90*1.1);
    vardata_90->SetMinimum(0.000001);
  } else {
    vardata_90->SetMaximum(0.00001);
  }

  double themax_all = vardata_all->GetMaximum();
  if(var_all_0->GetMaximum()>themax_all) themax_all = var_all_0->GetMaximum();
  if (themax_all>0) {
    if ( variableData == "etaphot1" || variableData == "phiphot1" ) 
      vardata_all->SetMaximum(themax_all*2.0);
    else
      vardata_all->SetMaximum(themax_all*1.1);
    vardata_all->SetMinimum(0.000001);
  } else {
    vardata_all->SetMaximum(0.00001);
  }

  for(int ii=0; ii<2; ii++) var_30[ii]->SetMinimum(0.000001);
  for(int ii=0; ii<2; ii++) var_50[ii]->SetMinimum(0.000001);
  for(int ii=0; ii<2; ii++) var_75[ii]->SetMinimum(0.000001);
  for(int ii=0; ii<2; ii++) var_90[ii]->SetMinimum(0.000001);
  for(int ii=0; ii<2; ii++) var_all_0->SetMinimum(0.000001);
  for(int ii=0; ii<2; ii++) var_all_1->SetMinimum(0.000001);

  //
  vardata_30->Draw("pe");
  var_30[0]->Draw("samehist");
  var_30[1]->Draw("samehist");
  leg->Draw();
  vardata_30->Draw("pesame");
  gPad->RedrawAxis();
  sprintf(name,"%s%s%s","results_gammaJ/data-mc_",variableData.c_str(),"_30.root");
  c0->SaveAs(name);
  sprintf(name,"%s%s%s","results_gammaJ/data-mc_",variableData.c_str(),"_30.png");
  c0->SaveAs(name);
  //
  vardata_50->Draw("pe");
  var_50[0]->Draw("samehist");
  var_50[1]->Draw("samehist");
  leg->Draw();
  vardata_50->Draw("pesame");
  gPad->RedrawAxis();
  sprintf(name,"%s%s%s","results_gammaJ/data-mc_",variableData.c_str(),"_50.root");
  c0->SaveAs(name);
  sprintf(name,"%s%s%s","results_gammaJ/data-mc_",variableData.c_str(),"_50.png");
  c0->SaveAs(name);
  //
  vardata_75->Draw("pe");
  var_75[0]->Draw("samehist");
  var_75[1]->Draw("samehist");
  leg->Draw();
  vardata_75->Draw("pesame");
  gPad->RedrawAxis();
  sprintf(name,"%s%s%s","results_gammaJ/data-mc_",variableData.c_str(),"_75.root");
  c0->SaveAs(name);
  sprintf(name,"%s%s%s","results_gammaJ/data-mc_",variableData.c_str(),"_75.png");
  c0->SaveAs(name);
  //
  vardata_90->Draw("pe");
  var_90[0]->Draw("samehist");
  var_90[1]->Draw("samehist");
  leg->Draw();
  vardata_90->Draw("pesame");
  gPad->RedrawAxis();
  sprintf(name,"%s%s%s","results_gammaJ/data-mc_",variableData.c_str(),"_90.root");
  c0->SaveAs(name);
  sprintf(name,"%s%s%s","results_gammaJ/data-mc_",variableData.c_str(),"_90.png");
  c0->SaveAs(name);
  //
  vardata_all->Draw("pe");
  var_all_0->Draw("samehist");
  var_all_1->Draw("samehist");
  leg->Draw();
  vardata_all->Draw("pesame");
  gPad->RedrawAxis();
  sprintf(name,"%s%s%s","results_gammaJ/data-mc_",variableData.c_str(),"_all.root");
  c0->SaveAs(name);
  sprintf(name,"%s%s%s","results_gammaJ/data-mc_",variableData.c_str(),"_all.png");
  c0->SaveAs(name);

  // -------------------------------------------------------------------------
  sprintf(name,"results_gammaJ/yields.txt");
  ofstream outfile(name);  
  outfile << "####################################" << endl;
  outfile << "CUTS " << endl;
  outfile << "####################################" << endl;
  outfile << "ptphot1, HLT = 30 : " << pt1min_30 << " - " << pt1max_30 << endl;
  outfile << "ptphot1, HLT = 50 : " << pt1min_50 << " - " << pt1max_50 << endl; 
  outfile << "ptphot1, HLT = 75 : " << pt1min_75 << " - " << pt1max_75 << endl; 
  outfile << "ptphot1, HLT = 90 : " << pt1min_90 << " - " << pt1max_90 << endl; 
  outfile << "ebcat : " << eb << endl;
  outfile << "r9cat : " << r9 << endl;
  outfile << endl;
  outfile << "####################################" << endl;
  outfile << "N of generated events" << endl;
  outfile << "####################################" << endl;
  outfile << "# events QCD, 20-30 = "       << n_mc_2012[0]  << endl;
  outfile << "# events QCD, 30-80 = "       << n_mc_2012[1]  << endl;
  outfile << "# events QCD, 80-170 = "      << n_mc_2012[2]  << endl;
  outfile << "# events QCD, 170-250 = "     << n_mc_2012[3]  << endl;
  outfile << "# events QCD, 250-350 = "     << n_mc_2012[4]  << endl;
  outfile << "# events QCD, >350 = "        << n_mc_2012[5]  << endl;
  outfile << "# events g+jet, 0-15 = "      << n_mc_2012[6]  << endl;
  outfile << "# events g+jet, 15-30 = "     << n_mc_2012[7]  << endl;
  outfile << "# events g+jet, 30-50 = "     << n_mc_2012[8]  << endl;
  outfile << "# events g+jet, 50-80 = "     << n_mc_2012[9]  << endl;
  outfile << "# events g+jet, 80-120 = "    << n_mc_2012[10] << endl;
  outfile << "# events g+jet, 120-170 = "   << n_mc_2012[11] << endl;
  outfile << "# events g+jet, 170-300 = "   << n_mc_2012[12] << endl;
  outfile << "# events g+jet, 470-800 = "   << n_mc_2012[13] << endl;
  outfile << "# events g+jet, 800-1400 = "  << n_mc_2012[14] << endl;
  outfile << "# events g+jet, 1400-1800 = " << n_mc_2012[15] << endl;
  outfile << endl;
  outfile << "N of selected events, HLT = 30 (not scaled for lumi)"     << endl;  
  outfile << "########################################################" << endl;
  outfile << "# events QCD, 20-30 = "       << num_uns_mc_2012_30[0]  << endl;
  outfile << "# events QCD, 30-80 = "       << num_uns_mc_2012_30[1]  << endl;
  outfile << "# events QCD, 80-170 = "      << num_uns_mc_2012_30[2]  << endl;
  outfile << "# events QCD, 170-250 = "     << num_uns_mc_2012_30[3]  << endl;
  outfile << "# events QCD, 250-350 = "     << num_uns_mc_2012_30[4]  << endl;
  outfile << "# events QCD, >350 = "        << num_uns_mc_2012_30[5]  << endl;
  outfile << "# events g+jet, 0-15 = "      << num_uns_mc_2012_30[6]  << endl;
  outfile << "# events g+jet, 15-30 = "     << num_uns_mc_2012_30[7]  << endl;
  outfile << "# events g+jet, 30-50 = "     << num_uns_mc_2012_30[8]  << endl;
  outfile << "# events g+jet, 50-80 = "     << num_uns_mc_2012_30[9]  << endl;
  outfile << "# events g+jet, 80-120 = "    << num_uns_mc_2012_30[10] << endl;
  outfile << "# events g+jet, 120-170 = "   << num_uns_mc_2012_30[11] << endl;
  outfile << "# events g+jet, 170-300 = "   << num_uns_mc_2012_30[12] << endl;
  outfile << "# events g+jet, 470-800 = "   << num_uns_mc_2012_30[13] << endl;
  outfile << "# events g+jet, 800-1400 = "  << num_uns_mc_2012_30[14] << endl;
  outfile << "# events g+jet, 1400-1800 = " << num_uns_mc_2012_30[15] << endl;
  outfile << "ndata = " << num_data_30 << endl;
  outfile << endl;
  outfile << "N of selected events, HLT = 50 (not scaled for lumi)"     << endl;  
  outfile << "########################################################" << endl;
  outfile << "# events QCD, 20-30 = "       << num_uns_mc_2012_50[0]  << endl;
  outfile << "# events QCD, 30-80 = "       << num_uns_mc_2012_50[1]  << endl;
  outfile << "# events QCD, 80-170 = "      << num_uns_mc_2012_50[2]  << endl;
  outfile << "# events QCD, 170-250 = "     << num_uns_mc_2012_50[3]  << endl;
  outfile << "# events QCD, 250-350 = "     << num_uns_mc_2012_50[4]  << endl;
  outfile << "# events QCD, >350 = "        << num_uns_mc_2012_50[5]  << endl;
  outfile << "# events g+jet, 0-15 = "      << num_uns_mc_2012_50[6]  << endl;
  outfile << "# events g+jet, 15-30 = "     << num_uns_mc_2012_50[7]  << endl;
  outfile << "# events g+jet, 30-50 = "     << num_uns_mc_2012_50[8]  << endl;
  outfile << "# events g+jet, 50-80 = "     << num_uns_mc_2012_50[9]  << endl;
  outfile << "# events g+jet, 80-120 = "    << num_uns_mc_2012_50[10] << endl;
  outfile << "# events g+jet, 120-170 = "   << num_uns_mc_2012_50[11] << endl;
  outfile << "# events g+jet, 170-300 = "   << num_uns_mc_2012_50[12] << endl;
  outfile << "# events g+jet, 470-800 = "   << num_uns_mc_2012_50[13] << endl;
  outfile << "# events g+jet, 800-1400 = "  << num_uns_mc_2012_50[14] << endl;
  outfile << "# events g+jet, 1400-1800 = " << num_uns_mc_2012_50[15] << endl;
  outfile << "ndata = " << num_data_50 << endl;
  outfile << endl;
  outfile << "N of selected events, HLT = 75 (not scaled for lumi)"     << endl;  
  outfile << "########################################################" << endl;
  outfile << "# events QCD, 20-30 = "       << num_uns_mc_2012_75[0]  << endl;
  outfile << "# events QCD, 30-80 = "       << num_uns_mc_2012_75[1]  << endl;
  outfile << "# events QCD, 80-170 = "      << num_uns_mc_2012_75[2]  << endl;
  outfile << "# events QCD, 170-250 = "     << num_uns_mc_2012_75[3]  << endl;
  outfile << "# events QCD, 250-350 = "     << num_uns_mc_2012_75[4]  << endl;
  outfile << "# events QCD, >350 = "        << num_uns_mc_2012_75[5]  << endl;
  outfile << "# events g+jet, 0-15 = "      << num_uns_mc_2012_75[6]  << endl;
  outfile << "# events g+jet, 15-30 = "     << num_uns_mc_2012_75[7]  << endl;
  outfile << "# events g+jet, 30-50 = "     << num_uns_mc_2012_75[8]  << endl;
  outfile << "# events g+jet, 50-80 = "     << num_uns_mc_2012_75[9]  << endl;
  outfile << "# events g+jet, 80-120 = "    << num_uns_mc_2012_75[10] << endl;
  outfile << "# events g+jet, 120-170 = "   << num_uns_mc_2012_75[11] << endl;
  outfile << "# events g+jet, 170-300 = "   << num_uns_mc_2012_75[12] << endl;
  outfile << "# events g+jet, 470-800 = "   << num_uns_mc_2012_75[13] << endl;
  outfile << "# events g+jet, 800-1400 = "  << num_uns_mc_2012_75[14] << endl;
  outfile << "# events g+jet, 1400-1800 = " << num_uns_mc_2012_75[15] << endl;
  outfile << "ndata = " << num_data_75 << endl;
  outfile << endl;
  outfile << "N of selected events, HLT = 90 (not scaled for lumi)"     << endl;  
  outfile << "########################################################" << endl;
  outfile << "# events QCD, 20-30 = "       << num_uns_mc_2012_90[0]  << endl;
  outfile << "# events QCD, 30-80 = "       << num_uns_mc_2012_90[1]  << endl;
  outfile << "# events QCD, 80-170 = "      << num_uns_mc_2012_90[2]  << endl;
  outfile << "# events QCD, 170-250 = "     << num_uns_mc_2012_90[3]  << endl;
  outfile << "# events QCD, 250-350 = "     << num_uns_mc_2012_90[4]  << endl;
  outfile << "# events QCD, >350 = "        << num_uns_mc_2012_90[5]  << endl;
  outfile << "# events g+jet, 0-15 = "      << num_uns_mc_2012_90[6]  << endl;
  outfile << "# events g+jet, 15-30 = "     << num_uns_mc_2012_90[7]  << endl;
  outfile << "# events g+jet, 30-50 = "     << num_uns_mc_2012_90[8]  << endl;
  outfile << "# events g+jet, 50-80 = "     << num_uns_mc_2012_90[9]  << endl;
  outfile << "# events g+jet, 80-120 = "    << num_uns_mc_2012_90[10] << endl;
  outfile << "# events g+jet, 120-170 = "   << num_uns_mc_2012_90[11] << endl;
  outfile << "# events g+jet, 170-300 = "   << num_uns_mc_2012_90[12] << endl;
  outfile << "# events g+jet, 470-800 = "   << num_uns_mc_2012_90[13] << endl;
  outfile << "# events g+jet, 800-1400 = "  << num_uns_mc_2012_90[14] << endl;
  outfile << "# events g+jet, 1400-1800 = " << num_uns_mc_2012_90[15] << endl;
  outfile << "ndata = " << num_data_90 << endl;
  outfile << endl;

  double num_bkg_30(0), err_num_bkg_30(0);
  double num_bkg_50(0), err_num_bkg_50(0);
  double num_bkg_75(0), err_num_bkg_75(0);
  double num_bkg_90(0), err_num_bkg_90(0);
  double num_mc_total_30[16],num_uns_mc_total_30[16], n_mc_total_30[16], err_num_mc_total_30[16], err_num_uns_mc_total_30[16];
  double num_mc_total_50[16],num_uns_mc_total_50[16], n_mc_total_50[16], err_num_mc_total_50[16], err_num_uns_mc_total_50[16];
  double num_mc_total_75[16],num_uns_mc_total_75[16], n_mc_total_75[16], err_num_mc_total_75[16], err_num_uns_mc_total_75[16];
  double num_mc_total_90[16],num_uns_mc_total_90[16], n_mc_total_90[16], err_num_mc_total_90[16], err_num_uns_mc_total_90[16];
  for (int i=0; i<16; i++){
    if(i<6) num_bkg_30 += num_mc_2012_30[i];
    if(i<6) num_bkg_50 += num_mc_2012_50[i];
    if(i<6) num_bkg_75 += num_mc_2012_75[i];
    if(i<6) num_bkg_90 += num_mc_2012_90[i];
    num_mc_total_30[i] = num_mc_2012_30[i];
    num_mc_total_50[i] = num_mc_2012_50[i];
    num_mc_total_75[i] = num_mc_2012_75[i];
    num_mc_total_90[i] = num_mc_2012_90[i];
    num_uns_mc_total_30[i] = num_uns_mc_2012_30[i];
    num_uns_mc_total_50[i] = num_uns_mc_2012_50[i];
    num_uns_mc_total_75[i] = num_uns_mc_2012_75[i];
    num_uns_mc_total_90[i] = num_uns_mc_2012_90[i];

    err_num_uns_mc_total_30[i] = sqrt(num_uns_mc_total_30[i]);
    err_num_uns_mc_total_50[i] = sqrt(num_uns_mc_total_50[i]);
    err_num_uns_mc_total_75[i] = sqrt(num_uns_mc_total_75[i]);
    err_num_uns_mc_total_90[i] = sqrt(num_uns_mc_total_90[i]);
    if(num_uns_mc_total_30[i]) err_num_mc_total_30[i] = err_num_uns_mc_total_30[i] * num_mc_total_30[i]/num_uns_mc_total_30[i];
    else err_num_mc_total_30[i] = 0;

    if(num_uns_mc_total_50[i]) err_num_mc_total_50[i] = err_num_uns_mc_total_50[i] * num_mc_total_50[i]/num_uns_mc_total_50[i];
    else err_num_mc_total_50[i] = 0;

    if(num_uns_mc_total_75[i]) err_num_mc_total_75[i] = err_num_uns_mc_total_75[i] * num_mc_total_75[i]/num_uns_mc_total_75[i];
    else err_num_mc_total_75[i] = 0;

    if(num_uns_mc_total_90[i]) err_num_mc_total_90[i] = err_num_uns_mc_total_90[i] * num_mc_total_90[i]/num_uns_mc_total_90[i];
    else err_num_mc_total_90[i] = 0;

    n_mc_total_30[i] = n_mc_2012[i] * scale_mc_2012_30[i];
    n_mc_total_50[i] = n_mc_2012[i] * scale_mc_2012_50[i];
    n_mc_total_75[i] = n_mc_2012[i] * scale_mc_2012_75[i];
    n_mc_total_90[i] = n_mc_2012[i] * scale_mc_2012_90[i];
  }

  for (int i=0; i<6; i++){ 
    err_num_bkg_30 = sqrt(err_num_bkg_30*err_num_bkg_30 + err_num_mc_total_30[i]*err_num_mc_total_30[i]);
    err_num_bkg_50 = sqrt(err_num_bkg_50*err_num_bkg_50 + err_num_mc_total_50[i]*err_num_mc_total_50[i]);
    err_num_bkg_75= sqrt(err_num_bkg_75*err_num_bkg_75 + err_num_mc_total_75[i]*err_num_mc_total_75[i]);
    err_num_bkg_90 = sqrt(err_num_bkg_90*err_num_bkg_90 + err_num_mc_total_90[i]*err_num_mc_total_90[i]);
  }
  
  outfile << endl;
  outfile << "final numbers, HLT = 30" << endl;
  outfile << "nallbkg        = " << num_bkg_30 << " +/- " << err_num_bkg_30 << endl;
  outfile << "QCD, 20-30     = " << num_mc_total_30[0]  << " +/- " << err_num_mc_total_30[0]  << endl;
  outfile << "QCD, 30-80     = " << num_mc_total_30[1]  << " +/- " << err_num_mc_total_30[1]  << endl;
  outfile << "QCD, 80-170    = " << num_mc_total_30[2]  << " +/- " << err_num_mc_total_30[2]  << endl;
  outfile << "QCD, 170-250   = " << num_mc_total_30[3]  << " +/- " << err_num_mc_total_30[3]  << endl;
  outfile << "QCD, 250-350   = " << num_mc_total_30[4]  << " +/- " << err_num_mc_total_30[4]  << endl;
  outfile << "QCD, >350      = " << num_mc_total_30[5]  << " +/- " << err_num_mc_total_30[5]  << endl;
  outfile << "G+j, 0-15      = " << num_mc_total_30[6]  << " +/- " << err_num_mc_total_30[6]  << endl;
  outfile << "G+j, 15-30     = " << num_mc_total_30[7]  << " +/- " << err_num_mc_total_30[7]  << endl;
  outfile << "G+j, 30-50     = " << num_mc_total_30[8]  << " +/- " << err_num_mc_total_30[8]  << endl;
  outfile << "G+j, 50-80     = " << num_mc_total_30[9]  << " +/- " << err_num_mc_total_30[9]  << endl;
  outfile << "G+j, 80-120    = " << num_mc_total_30[10] << " +/- " << err_num_mc_total_30[10]  << endl;
  outfile << "G+j, 120-170   = " << num_mc_total_30[11] << " +/- " << err_num_mc_total_30[11]  << endl;
  outfile << "G+j, 170-300   = " << num_mc_total_30[12] << " +/- " << err_num_mc_total_30[12]  << endl;
  outfile << "G+j, 470-800   = " << num_mc_total_30[13] << " +/- " << err_num_mc_total_30[13]  << endl;
  outfile << "G+j, 800-1400  = " << num_mc_total_30[14] << " +/- " << err_num_mc_total_30[14]  << endl;
  outfile << "G+j, 1400-1800 = " << num_mc_total_30[15] << " +/- " << err_num_mc_total_30[15]  << endl;
  outfile << endl;          
  outfile << endl;
  outfile << "eff gamma+jets = "  << (num_mc_total_30[6] + num_mc_total_30[7] + num_mc_total_30[8] + num_mc_total_30[9] + num_mc_total_30[10] + num_mc_total_30[11] + num_mc_total_30[12] + num_mc_total_30[13] + num_mc_total_30[14] + num_mc_total_30[15])/(n_mc_total_30[6] + n_mc_total_30[7] + n_mc_total_30[8] + n_mc_total_30[9] + n_mc_total_30[10] + n_mc_total_30[11] + n_mc_total_30[12] + n_mc_total_30[13] + n_mc_total_30[14] + n_mc_total_30[15]) << endl;  
  
  outfile << endl;
  outfile << "final numbers, HLT = 50" << endl;
  outfile << "nallbkg        = " << num_bkg_50 << " +/- " << err_num_bkg_50 << endl;
  outfile << "QCD, 20-30     = " << num_mc_total_50[0]  << " +/- " << err_num_mc_total_50[0]  << endl;
  outfile << "QCD, 30-80     = " << num_mc_total_50[1]  << " +/- " << err_num_mc_total_50[1]  << endl;
  outfile << "QCD, 80-170    = " << num_mc_total_50[2]  << " +/- " << err_num_mc_total_50[2]  << endl;
  outfile << "QCD, 170-250   = " << num_mc_total_50[3]  << " +/- " << err_num_mc_total_50[3]  << endl;
  outfile << "QCD, 250-350   = " << num_mc_total_50[4]  << " +/- " << err_num_mc_total_50[4]  << endl;
  outfile << "QCD, >350      = " << num_mc_total_50[5]  << " +/- " << err_num_mc_total_50[5]  << endl;
  outfile << "G+j, 0-15      = " << num_mc_total_50[6]  << " +/- " << err_num_mc_total_50[6]  << endl;
  outfile << "G+j, 15-30     = " << num_mc_total_50[7]  << " +/- " << err_num_mc_total_50[7]  << endl;
  outfile << "G+j, 30-50     = " << num_mc_total_50[8]  << " +/- " << err_num_mc_total_50[8]  << endl;
  outfile << "G+j, 50-80     = " << num_mc_total_50[9]  << " +/- " << err_num_mc_total_50[9]  << endl;
  outfile << "G+j, 80-120    = " << num_mc_total_50[10] << " +/- " << err_num_mc_total_50[10]  << endl;
  outfile << "G+j, 120-170   = " << num_mc_total_50[11] << " +/- " << err_num_mc_total_50[11]  << endl;
  outfile << "G+j, 170-300   = " << num_mc_total_50[12] << " +/- " << err_num_mc_total_50[12]  << endl;
  outfile << "G+j, 470-800   = " << num_mc_total_50[13] << " +/- " << err_num_mc_total_50[13]  << endl;
  outfile << "G+j, 800-1400  = " << num_mc_total_50[14] << " +/- " << err_num_mc_total_50[14]  << endl;
  outfile << "G+j, 1400-1800 = " << num_mc_total_50[15] << " +/- " << err_num_mc_total_50[15]  << endl;
  outfile << endl;          
  outfile << endl;
  outfile << "eff gamma+jets = "  << (num_mc_total_50[6] + num_mc_total_50[7] + num_mc_total_50[8] + num_mc_total_50[9] + num_mc_total_50[10] + num_mc_total_50[11] + num_mc_total_50[12] + num_mc_total_50[13] + num_mc_total_50[14] + num_mc_total_50[15])/(n_mc_total_50[6] + n_mc_total_50[7] + n_mc_total_50[8] + n_mc_total_50[9] + n_mc_total_50[10] + n_mc_total_50[11] + n_mc_total_50[12] + n_mc_total_50[13] + n_mc_total_50[14] + n_mc_total_50[15]) << endl;  
  
  outfile << endl;
  outfile << "final numbers, HLT = 75" << endl;
  outfile << "nallbkg        = " << num_bkg_75 << " +/- " << err_num_bkg_75 << endl;
  outfile << "QCD, 20-30     = " << num_mc_total_75[0]  << " +/- " << err_num_mc_total_75[0]  << endl;
  outfile << "QCD, 30-80     = " << num_mc_total_75[1]  << " +/- " << err_num_mc_total_75[1]  << endl;
  outfile << "QCD, 80-170    = " << num_mc_total_75[2]  << " +/- " << err_num_mc_total_75[2]  << endl;
  outfile << "QCD, 170-250   = " << num_mc_total_75[3]  << " +/- " << err_num_mc_total_75[3]  << endl;
  outfile << "QCD, 250-350   = " << num_mc_total_75[4]  << " +/- " << err_num_mc_total_75[4]  << endl;
  outfile << "QCD, >350      = " << num_mc_total_75[5]  << " +/- " << err_num_mc_total_75[5]  << endl;
  outfile << "G+j, 0-15      = " << num_mc_total_75[6]  << " +/- " << err_num_mc_total_75[6]  << endl;
  outfile << "G+j, 15-30     = " << num_mc_total_75[7]  << " +/- " << err_num_mc_total_75[7]  << endl;
  outfile << "G+j, 30-50     = " << num_mc_total_75[8]  << " +/- " << err_num_mc_total_75[8]  << endl;
  outfile << "G+j, 50-80     = " << num_mc_total_75[9]  << " +/- " << err_num_mc_total_75[9]  << endl;
  outfile << "G+j, 80-120    = " << num_mc_total_75[10] << " +/- " << err_num_mc_total_75[10]  << endl;
  outfile << "G+j, 120-170   = " << num_mc_total_75[11] << " +/- " << err_num_mc_total_75[11]  << endl;
  outfile << "G+j, 170-300   = " << num_mc_total_75[12] << " +/- " << err_num_mc_total_75[12]  << endl;
  outfile << "G+j, 470-800   = " << num_mc_total_75[13] << " +/- " << err_num_mc_total_75[13]  << endl;
  outfile << "G+j, 800-1400  = " << num_mc_total_75[14] << " +/- " << err_num_mc_total_75[14]  << endl;
  outfile << "G+j, 1400-1800 = " << num_mc_total_75[15] << " +/- " << err_num_mc_total_75[15]  << endl;
  outfile << endl;          
  outfile << endl;
  outfile << "eff gamma+jets = "  << (num_mc_total_75[6] + num_mc_total_75[7] + num_mc_total_75[8] + num_mc_total_75[9] + num_mc_total_75[10] + num_mc_total_75[11] + num_mc_total_75[12] + num_mc_total_75[13] + num_mc_total_75[14] + num_mc_total_75[15])/(n_mc_total_75[6] + n_mc_total_75[7] + n_mc_total_75[8] + n_mc_total_75[9] + n_mc_total_75[10] + n_mc_total_75[11] + n_mc_total_75[12] + n_mc_total_75[13] + n_mc_total_75[14] + n_mc_total_75[15]) << endl;  
  
  outfile << endl;
  outfile << "final numbers, HLT = 90" << endl;
  outfile << "nallbkg        = " << num_bkg_90 << " +/- " << err_num_bkg_90 << endl;
  outfile << "QCD, 20-30     = " << num_mc_total_90[0]  << " +/- " << err_num_mc_total_90[0]  << endl;
  outfile << "QCD, 30-80     = " << num_mc_total_90[1]  << " +/- " << err_num_mc_total_90[1]  << endl;
  outfile << "QCD, 80-170    = " << num_mc_total_90[2]  << " +/- " << err_num_mc_total_90[2]  << endl;
  outfile << "QCD, 170-250   = " << num_mc_total_90[3]  << " +/- " << err_num_mc_total_90[3]  << endl;
  outfile << "QCD, 250-350   = " << num_mc_total_90[4]  << " +/- " << err_num_mc_total_90[4]  << endl;
  outfile << "QCD, >350      = " << num_mc_total_90[5]  << " +/- " << err_num_mc_total_90[5]  << endl;
  outfile << "G+j, 0-15      = " << num_mc_total_90[6]  << " +/- " << err_num_mc_total_90[6]  << endl;
  outfile << "G+j, 15-30     = " << num_mc_total_90[7]  << " +/- " << err_num_mc_total_90[7]  << endl;
  outfile << "G+j, 30-50     = " << num_mc_total_90[8]  << " +/- " << err_num_mc_total_90[8]  << endl;
  outfile << "G+j, 50-80     = " << num_mc_total_90[9]  << " +/- " << err_num_mc_total_90[9]  << endl;
  outfile << "G+j, 80-120    = " << num_mc_total_90[10] << " +/- " << err_num_mc_total_90[10]  << endl;
  outfile << "G+j, 120-170   = " << num_mc_total_90[11] << " +/- " << err_num_mc_total_90[11]  << endl;
  outfile << "G+j, 170-300   = " << num_mc_total_90[12] << " +/- " << err_num_mc_total_90[12]  << endl;
  outfile << "G+j, 470-800   = " << num_mc_total_90[13] << " +/- " << err_num_mc_total_90[13]  << endl;
  outfile << "G+j, 800-1400  = " << num_mc_total_90[14] << " +/- " << err_num_mc_total_90[14]  << endl;
  outfile << "G+j, 1400-1800 = " << num_mc_total_90[15] << " +/- " << err_num_mc_total_90[15]  << endl;
  outfile << endl;          
  outfile << endl;
  outfile << "eff gamma+jets = "  << (num_mc_total_90[6] + num_mc_total_90[7] + num_mc_total_90[8] + num_mc_total_90[9] + num_mc_total_90[10] + num_mc_total_90[11] + num_mc_total_90[12] + num_mc_total_90[13] + num_mc_total_90[14] + num_mc_total_90[15])/(n_mc_total_90[6] + n_mc_total_90[7] + n_mc_total_90[8] + n_mc_total_90[9] + n_mc_total_90[10] + n_mc_total_90[11] + n_mc_total_90[12] + n_mc_total_90[13] + n_mc_total_90[14] + n_mc_total_90[15]) << endl;  
  cout << endl;
  outfile << endl;
  outfile.close();
  
  hOutputFile->Write() ;
  hOutputFile->Close() ;
  hOutputFile->Delete();
  
  delete data;
  
  for(int i=0; i<16; i++){
    delete mc_2012_fill_30[i];
    delete mc_2012_fill_50[i];
    delete mc_2012_fill_75[i];
    delete mc_2012_fill_90[i];
   delete mc_2012[i];
  }
  
  vector<double> values;
  
  return values;
}