Example #1
0
void RAA_read_MinBias(int startfile = 0, int endfile = 1, char *algo = "Pu", char *jet_type = "PF", char *Type = "Data"){

  TH1::SetDefaultSumw2();
  
  TStopwatch timer;
  timer.Start();
  
  TDatime date;
  
  cout<<"Running for Algo = "<<algo<<" "<<jet_type<<endl;
  
  bool printDebug = false;

  // Now im going to change the file reading here for PbPb to look at the unmerged files through condor. 
  std::string infile1;
  if(Type=="MC")infile1 = "PbPb_HydjetMinBias_forest.txt";
  //if(Type=="Data")infile1 = "PbPb_MinBiasUPC_forest.txt";
  if(Type=="Data")infile1 = "jetRAA_MinBiasUPC_forest.txt";
  //if(Type=="Data")infile1 = "14010_MinBiasUPC_forest.txt";
  
  std::ifstream instr1(infile1.c_str(),std::ifstream::in);
  std::string filename1;
  
  cout<<"reading from "<<startfile<<" to "<<endfile<<endl;
  
  for(int ifile = 0;ifile<startfile;ifile++){
    instr1>>filename1;
  }
  
  const int N = 5;
  
  TChain *jetpbpb1[N][no_radius];

  string dir[N][no_radius];
  
  for(int k = 0;k<no_radius;k++){
    dir[0][k] = "hltanalysis";
    dir[1][k] = "skimanalysis";
    dir[2][k] = Form("ak%s%d%sJetAnalyzer",algo,list_radius[k],jet_type);
    //dir[3][k] = Form("akPu%d%sJetAnalyzer",list_radius[k],jet_type);
    dir[3][k] = "hiEvtAnalyzer";
    dir[4][k] = "hltobject"; //- not there in MinBias files 
    //dir[6][k] = "pfcandAnalyzer";
  }

  string trees[N] = {
    "HltTree",
    "HltTree",
    "t",
    //"t",
    "HiTree",
    "jetObjTree"
    //"pfTree"
  };
  
  //this loop is to assign the tree values before we go into the file loop. 
  for(int k = 0;k<no_radius;k++){
    for(int t = 0;t<N;t++){
      jetpbpb1[t][k] = new TChain(string(dir[t][k]+"/"+trees[t]).data());
    }//tree loop ends
  }// radius loop ends
  
  for(int ifile = startfile;ifile<endfile;ifile++){
    
    instr1>>filename1;
    if(printDebug)cout<<"File: "<<filename1<<endl;
    for(int k = 0;k<no_radius;k++){

      for(int t = 0;t<N;t++){
	
	//jetpbpb1[t][k] = new TChain(string(dir[t][k]+"/"+trees[t]).data()) ;
	jetpbpb1[t][k]->Add(filename1.c_str());
	if(printDebug)cout << "Tree loaded  " << string(dir[t][k]+"/"+trees[t]).data() << endl;
	if(printDebug)cout << "Entries : " << jetpbpb1[t][k]->GetEntries() << endl;
		
      }// tree loop ends
    }// radius loop ends
    
  }// file loop ends
  

  for(int k = 0;k<no_radius;k++){
    jetpbpb1[2][k]->AddFriend(jetpbpb1[0][k]);
    jetpbpb1[2][k]->AddFriend(jetpbpb1[1][k]);
    jetpbpb1[2][k]->AddFriend(jetpbpb1[3][k]);
    jetpbpb1[2][k]->AddFriend(jetpbpb1[4][k]);
  }// radius loop ends

  cout<<"total no of entries in the combined forest files = "<<jetpbpb1[2][0]->GetEntries()<<endl;

  //file 1: 
  // jet tree 1
  int nrefe_1;
  float pt_1[1000];
  //float old_pt3[1000];
  float raw_1[1000];
  float refpt_1[1000];
  float subid_1[1000];
  float eta_1[1000];
  float eta_1_CM[1000];
  float phi_1[1000];
  float chMax_1[1000];
  float trkMax_1[1000];
  float chSum_1[1000];
  float phSum_1[1000];
  float neSum_1[1000];
  float trkSum_1[1000];
  float phMax_1[1000];
  float neMax_1[1000];
  float eMax_1[1000];
  float muMax_1[1000];
  float eSum_1[1000];
  float muSum_1[1000];
  float jtpu_1[1000];
  // event tree
  int evt_1;
  int run_1;
  int lumi_1;
  int hiBin_1;
  float vx_1;
  float vy_1;
  float vz_1;
  int hiNpix_1;
  int hiNtracks_1;
  float hiHF_1;
  float hiHFminus_1;
  float hiHFplus_1;
  float hiHFplusEta4_1;
  float hiHFminusEta4_1;
  int pcollisionEventSelection_1;
  int pHBHENoiseFilter_1;
  int pprimaryvertexFilter_1;
  int pVertexFilterCutGplus_1;

  // trigger tree
  int L1_MB_1;
  int l1MB_1;
  int L1_MB_p_1;
  int l1MB_p_1;
  int L1_sj36_1;
  int L1_sj52_1;
  int jetMB_1;
  int jet55_1;
  int jet65_1;
  int jet80_1;
  int jetMB_p_1;
  int L1_sj36_p_1;
  int L1_sj52_p_1;
  int jet55_p_1;
  int jet65_p_1;
  int jet80_p_1;


  // trigger object tree - this contains the maximum value of the particular trigger object. 
  float trgObj_id_1;
  float trgObj_pt_1;
  float trgObj_eta_1;
  float trgObj_phi_1;
  float trgObj_mass_1;
  
  /*
  Int_t nPFpart;
  Int_t pfId[NOBJECT_MAX];
  Float_t pfPt[NOBJECT_MAX];
  Float_t pfVsPtInitial[NOBJECT_MAX];
  Float_t pfVsPt[NOBJECT_MAX];
  Float_t pfEta[NOBJECT_MAX];
  Float_t pfPhi[NOBJECT_MAX];
  Float_t pfArea[NOBJECT_MAX];
  Float_t v_n[5][15];
  Float_t psi_n[5][15];
  Float_t sumpT[15];
  */
  
  for(int k = 0;k<no_radius;k++){
    //set the branch addresses:  - one of the most boring parts of the code: 
    jetpbpb1[2][k]->SetBranchAddress("evt",&evt_1);
    jetpbpb1[2][k]->SetBranchAddress("run",&run_1);
    jetpbpb1[2][k]->SetBranchAddress("lumi",&lumi_1);
    jetpbpb1[2][k]->SetBranchAddress("hiBin",&hiBin_1);
    jetpbpb1[2][k]->SetBranchAddress("vz",&vz_1);
    jetpbpb1[2][k]->SetBranchAddress("vx",&vx_1);
    jetpbpb1[2][k]->SetBranchAddress("vy",&vy_1);
    jetpbpb1[2][k]->SetBranchAddress("hiNpix",&hiNpix_1);
    jetpbpb1[2][k]->SetBranchAddress("hiNtracks",&hiNtracks_1);
    jetpbpb1[2][k]->SetBranchAddress("hiHFminus",&hiHFminus_1);
    jetpbpb1[2][k]->SetBranchAddress("hiHF",&hiHF_1);
    jetpbpb1[2][k]->SetBranchAddress("hiHFplus",&hiHFplus_1);
    jetpbpb1[2][k]->SetBranchAddress("hiHFplusEta4",&hiHFplusEta4_1);
    jetpbpb1[2][k]->SetBranchAddress("hiHFminusEta4",&hiHFminusEta4_1);
    jetpbpb1[2][k]->SetBranchAddress("pcollisionEventSelection",&pcollisionEventSelection_1);
    jetpbpb1[2][k]->SetBranchAddress("pHBHENoiseFilter",&pHBHENoiseFilter_1);
    //jetpbpb1[2][k]->SetBranchAddress("pprimaryvertexFilter",&pprimaryvertexFilter_1);
    //jetpbpb1[2][k]->SetBranchAddress("pVertexFilterCutGplus",&pVertexFilterCutGplus_1);
  
    jetpbpb1[2][k]->SetBranchAddress("nref",&nrefe_1);
    jetpbpb1[2][k]->SetBranchAddress("jtpt",&pt_1);
    jetpbpb1[2][k]->SetBranchAddress("jteta",&eta_1);
    jetpbpb1[2][k]->SetBranchAddress("jtphi",&phi_1);
    jetpbpb1[2][k]->SetBranchAddress("rawpt",&raw_1);
    jetpbpb1[2][k]->SetBranchAddress("jtpu",&jtpu_1);
    if(Type=="MC")jetpbpb1[2][k]->SetBranchAddress("refpt",&refpt_1);
    if(Type=="MC")jetpbpb1[2][k]->SetBranchAddress("subid",&subid_1);
    jetpbpb1[2][k]->SetBranchAddress("chargedMax",&chMax_1);
    jetpbpb1[2][k]->SetBranchAddress("chargedSum",&chSum_1);
    jetpbpb1[2][k]->SetBranchAddress("trackMax",&trkMax_1);
    jetpbpb1[2][k]->SetBranchAddress("trackSum",&trkSum_1);
    jetpbpb1[2][k]->SetBranchAddress("photonMax",&phMax_1);
    jetpbpb1[2][k]->SetBranchAddress("photonSum",&phSum_1);
    jetpbpb1[2][k]->SetBranchAddress("neutralMax",&neMax_1);
    jetpbpb1[2][k]->SetBranchAddress("neutralSum",&neSum_1);
    jetpbpb1[2][k]->SetBranchAddress("eSum",&eSum_1);
    jetpbpb1[2][k]->SetBranchAddress("eMax",&eMax_1);
    jetpbpb1[2][k]->SetBranchAddress("muSum",&muSum_1);
    jetpbpb1[2][k]->SetBranchAddress("muMax",&muMax_1);
    jetpbpb1[2][k]->SetBranchAddress("HLT_HIMinBiasHfOrBSC_v1",&jetMB_1);
    jetpbpb1[2][k]->SetBranchAddress("HLT_HIMinBiasHfOrBSC_v1_Prescl",&jetMB_p_1);
    jetpbpb1[2][k]->SetBranchAddress("L1_ZeroBias",&L1_MB_1);
    jetpbpb1[2][k]->SetBranchAddress("L1_ZeroBias_Prescl",&L1_MB_p_1);
    jetpbpb1[2][k]->SetBranchAddress("HLT_HIJet55_v1",&jet55_1);
    jetpbpb1[2][k]->SetBranchAddress("HLT_HIJet55_v1_Prescl",&jet55_p_1);
    jetpbpb1[2][k]->SetBranchAddress("HLT_HIJet65_v1",&jet65_1);
    jetpbpb1[2][k]->SetBranchAddress("HLT_HIJet65_v1_Prescl",&jet65_p_1);
    jetpbpb1[2][k]->SetBranchAddress("HLT_HIJet80_v1",&jet80_1);
    jetpbpb1[2][k]->SetBranchAddress("HLT_HIJet80_v1_Prescl",&jet80_p_1);
    jetpbpb1[2][k]->SetBranchAddress("L1_SingleJet36_BptxAND",&L1_sj36_1);
    jetpbpb1[2][k]->SetBranchAddress("L1_SingleJet36_BptxAND_Prescl",&L1_sj36_p_1);
    jetpbpb1[2][k]->SetBranchAddress("L1_SingleJet52_BptxAND",&L1_sj52_1);
    jetpbpb1[2][k]->SetBranchAddress("L1_SingleJet52_BptxAND_Prescl",&L1_sj52_p_1);

    jetpbpb1[4][k]->SetBranchAddress("pt",&trgObj_pt_1);
    jetpbpb1[4][k]->SetBranchAddress("eta",&trgObj_eta_1);
    jetpbpb1[4][k]->SetBranchAddress("phi",&trgObj_phi_1);
    
    /*
    jetpbpb1[2][k]->SetBranchAddress("nPFpart", &nPFpart);
    jetpbpb1[2][k]->SetBranchAddress("pfId", pfId);
    jetpbpb1[2][k]->SetBranchAddress("pfPt", pfPt);
    jetpbpb1[2][k]->SetBranchAddress("pfVsPtInitial", pfVsPtInitial);
    jetpbpb1[2][k]->SetBranchAddress("pfVsPt", pfVsPt);
    jetpbpb1[2][k]->SetBranchAddress("pfEta", pfEta);
    jetpbpb1[2][k]->SetBranchAddress("pfPhi", pfPhi);
    jetpbpb1[2][k]->SetBranchAddress("pfArea", pfArea);
    jetpbpb1[2][k]->SetBranchAddress("vn",&v_n);
    jetpbpb1[2][k]->SetBranchAddress("psin",&psi_n);
    jetpbpb1[2][k]->SetBranchAddress("sumpt",&sumpT);
    */
  }//radius loop


  // we need to add the histograms to find the jet spectra from normal and failure mode- infact just add them to the ntuples per event the value of the HFSumpT*vn*cos/sin(n*psi_n) so we can plot the spectra at the final stage. this would make things easier.
  /*
  TNtuple *jets_ID;
  if(Type=="Data") jets_ID= new TNtuple("jets_ID","","rawpt:jtpt:jtpu:L1_MB:L1_MB_prescl:HLTZeroBias_MB:HLTZeroBias_MB_prescl:cent:chMax:chSum:phMax:phSum:neMax:neSum:muMax:muSum:eMax:eSum");
  if(Type=="MC")  jets_ID= new TNtuple("jets_ID","","rawpt:jtpt:jtpu:L1_MB:L1_MB_prescl:HLTZeroBias_MB:HLTZeroBias_MB_prescl:cent:chMax:chSum:phMax:phSum:neMax:neSum:muMax:muSum:eMax:eSum:refpt:subid");
  Float_t arrayValues_Data[18];
  Float_t arrayValues_MC[20];
  */
  
  TH1F *hEvents  = new TH1F("hEvents","",2,0,1);
  TH1F *hEvents_Jet80  = new TH1F("hEvents_Jet80","",2,0,1);
  TH1F *hJets = new TH1F("hJets","",2,0,1);

  TH1F *hJetMB_80_1 = new TH1F("hJetMB_80_1","",200,0,200);
  TH1F *hJetMB_65_1 = new TH1F("hJetMB_65_1_","",200,0,200);
  TH1F *hJetMB_55_1 = new TH1F("hJetMB_55_1","",200,0,200);
  TH1F *hJetMBSpectra[no_radius][nbins_cent];
  for(int k = 0;k<no_radius;++k){
    for(int i = 0;i<nbins_cent;++i)
      hJetMBSpectra[k][i] = new TH1F(Form("hJetMBSpectra_R%d_cent%d",list_radius[k],i),"Data from MB trigger alone to add to the Jet triggered data",1000,0,1000);
  }
  
  TH1F *hL1MB = new TH1F("hL1MB","",200,0,200);
  TH1F *hJet80 = new TH1F("hJet80","",200,0,200);
  TH1F *hJet80_Trig = new TH1F("hJet80_Trig","",200,0,200);
  TH1F *hJet65 = new TH1F("hJet65","",200,0,200);
  TH1F *hJet55 = new TH1F("hJet55","",200,0,200);
  TH1F *hL1SJ36 = new TH1F("hL1SJ36","",200,0,200);
  TH1F *hL1SJ52 = new TH1F("hL1SJ52","",200,0,200);
  TH1F *hL1MB_JetMB = new TH1F("hL1MB_JetMB","",200,0,200);
  TH1F *hJet80_JetMB = new TH1F("hJet80_JetMB","",200,0,200);
  TH1F *hJet65_JetMB = new TH1F("hJet65_JetMB","",200,0,200);
  TH1F *hJet55_JetMB = new TH1F("hJet55_JetMB","",200,0,200);
  TH1F *hJet65_Jet80 = new TH1F("hJet65_Jet80","",200,0,200);
  TH1F *hJet55_Jet80 = new TH1F("hJet55_Jet80","",200,0,200);
  TH1F *hL1SJ36_JetMB = new TH1F("hL1SJ36_JetMB","",200,0,200);
  TH1F *hL1SJ52_JetMB = new TH1F("hL1SJ52_JetMB","",200,0,200);

  TH1F * hJet80_Prescl = new TH1F("hJet80_Prescl","",200,0,10);
  TH1F * hJet65_Prescl = new TH1F("hJet65_Prescl","",200,0,10);
  TH1F * hJet55_Prescl = new TH1F("hJet55_Prescl","",200,0,10);
  
    
  // jetpbpb1[2][0]->Draw("jtpt[0]>>hJet80_JetMB","(pcollisionEventSelection&&HLT_HIMinBiasHfOrBSC_v1&&HLT_HIJet80_v1&&abs(jteta)<2&&abs(vz)<15&&pHBHENoiseFilter&&HLT_HIJet80_v1_Prescl==1)","goff");
  // jetpbpb1[2][0]->Draw("Max$(jtpt)>>hJet80_Trig","(pcollisionEventSelection&&HLT_HIJet80_v1&&abs(jteta)<2&&abs(vz)<15&&pHBHENoiseFilter&&jetObjTree.pt>80)","goff");
  // jetpbpb1[2][0]->Draw("Max$(jtpt)>>hJet65_JetMB","(pcollisionEventSelection&&HLT_HIMinBiasHfOrBSC_v1&&HLT_HIJet65_v1&&abs(jteta)<2&&abs(vz)<15&&pHBHENoiseFilter&&HLT_HIJet65_v1_Prescl==1)","goff");
  // jetpbpb1[2][0]->Draw("Max$(jtpt)>>hJet55_JetMB","(pcollisionEventSelection&&HLT_HIMinBiasHfOrBSC_v1&&HLT_HIJet55_v1&&abs(jteta)<2&&abs(vz)<15&&pHBHENoiseFilter&&HLT_HIJet55_v1_Prescl==1)","goff");
  // // jetpbpb1[2][0]->Draw("Max$(jtpt)>>hJet65_Jet80","(pcollisionEventSelection&&HLT_HIJet65_v1&&HLT_HIJet80_v1&&abs(jteta)<2&&abs(vz)<15&&pHBHENoiseFilter&&pt>80)","goff");
  // // jetpbpb1[2][0]->Draw("Max$(jtpt)>>hJet55_Jet80","(pcollisionEventSelection&&HLT_HIJet80_v1&&HLT_HIJet55_v1&&abs(jteta)<2&&abs(vz)<15&&pHBHENoiseFilter&&pt>80)","goff");
  // jetpbpb1[2][0]->Draw("Max$(jtpt)>>hJetMB_80_1","(pcollisionEventSelection&&HLT_HIMinBiasHfOrBSC_v1&&abs(jteta)<2&&abs(vz)<15&&pHBHENoiseFilter&&HLT_HIJet80_v1_Prescl==1)","goff");
  // jetpbpb1[2][0]->Draw("Max$(jtpt)>>hJetMB_65_1","(pcollisionEventSelection&&HLT_HIMinBiasHfOrBSC_v1&&abs(jteta)<2&&abs(vz)<15&&pHBHENoiseFilter&&HLT_HIJet65_v1_Prescl==1)","goff");
  // jetpbpb1[2][0]->Draw("Max$(jtpt)>>hJetMB_55_1","(pcollisionEventSelection&&HLT_HIMinBiasHfOrBSC_v1&&abs(jteta)<2&&abs(vz)<15&&pHBHENoiseFilter&&HLT_HIJet55_v1_Prescl==1)","goff");

  // for(int k = 0;k<no_radius;++k){

  // for(int i = 0;i<nbins_cent;i++){
  //   //cout<<Form("%f %f",5*boundaries_cent[i],5*boundaries_cent[i+1])<<endl;
  //   //cout<<Form("38.695*(pcollisionEventSelection && HLT_HIMinBiasHfOrBSC_v1 && abs(jteta)<2 && abs(vz)<15 && pHBHENoiseFilter && !HLT_HIJet80_v1 && !HLT_HIJet65_v1 && !HLT_HIJet55_v1 && hiBin>=%f && hiBin<%f)",5*boundaries_cent[i],5*boundaries_cent[i+1])<<endl;
  //   jetpbpb1[2][k]->Draw(Form("jtpt>>hJetMBSpectra_R%d_cent%d",list_radius[k],i),Form("38.695*(pcollisionEventSelection && HLT_HIMinBiasHfOrBSC_v1 && abs(jteta)<2 && abs(vz)<15 && pHBHENoiseFilter && !HLT_HIJet80_v1 && !HLT_HIJet65_v1 && !HLT_HIJet55_v1 && hiBin>=%f && hiBin<%f && chargedMax/jtpt>0.02 && eMax/jtpt<0.6)",5*boundaries_cent[i],5*boundaries_cent[i+1]),"goff");
  //   //hJetMBSpectra[k][i]->Print("base");
  // }
    
  // TTree* trigger_info;
  // Int_t evt_value;
  // Int_t run_value;
  // Int_t lumi_value;
  // Int_t nref;
  // Float_t jetpt[1000];
  // Float_t jeteta[1000];
  // Int_t Jet80;
  // Int_t Jet80_prescl;
  // Int_t Jet65;
  // Int_t Jet65_prescl;
  // Int_t Jet55;
  // Int_t Jet55_prescl;
  // Int_t HIMinBias;
  // Int_t HIMinBias_prescl;
  
  // trigger_info = new TTree("trigger_info","");
  // trigger_info->Branch("run_value",&run_value,"run_value/I");
  // trigger_info->Branch("evt_value",&evt_value,"evt_value/I");
  // trigger_info->Branch("lumi_value",&lumi_value,"lumi_value/I");
  // trigger_info->Branch("nref",&nref,"nref/I");
  // trigger_info->Branch("jetpt",&jetpt,"jetpt[nref]/F");
  // trigger_info->Branch("jeteta",&jeteta,"jeteta[nref]/F");
  // trigger_info->Branch("Jet80",&Jet80,"Jet80/I");
  // trigger_info->Branch("Jet80_prescl",&Jet80_prescl,"Jet80_prescl/I");
  // trigger_info->Branch("Jet65",&Jet65,"Jet65/I");
  // trigger_info->Branch("Jet65_prescl",&Jet65_prescl,"Jet65_prescl/I");
  // trigger_info->Branch("Jet55",&Jet55,"Jet55/I");
  // trigger_info->Branch("Jet55_prescl",&Jet55_prescl,"Jet55_prescl/I");
  // trigger_info->Branch("HIMinBias",&HIMinBias,"HIMinBias/I");
  // trigger_info->Branch("HIMinBias_prescl",&HIMinBias_prescl,"HIMinBias_prescl/I");  
  
  // prescl is calculated as the ratio of the 
  //minbias prescl = 38.695
  // jet80  prescl = 1 (same in minbias sample as well)
  // jet65  prescl = 1.11398 (1.11287)
  // jet55  prescl = 2.0475 (2.0292)

  
  TH1F* hDenominator[nbins_cent][no_radius]; 
  TH1F* hNumerator_80[nbins_cent][no_radius];
  TH1F* hNumerator_65[nbins_cent][no_radius];
  TH1F* hNumerator_55[nbins_cent][no_radius];

  TH1F * hNumerator_55_n65_n80[nbins_cent][no_radius];
  TH1F * hNumerator_65_n80[nbins_cent][no_radius];

  
  for(int k = 0;k<no_radius;++k){

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

      hDenominator[i][k] =new TH1F(Form("hDenominator_R%d_cent%d",list_radius[k], i),"",nbins_pt,boundaries_pt);
      hNumerator_80[i][k] =new TH1F(Form("hNumerator_80_R%d_cent%d",list_radius[k], i),"",nbins_pt,boundaries_pt);
      hNumerator_65[i][k] =new TH1F(Form("hNumerator_65_R%d_cent%d",list_radius[k], i),"",nbins_pt,boundaries_pt);
      hNumerator_55[i][k] =new TH1F(Form("hNumerator_55_R%d_cent%d",list_radius[k], i),"",nbins_pt,boundaries_pt);
      hNumerator_55_n65_n80[i][k] =new TH1F(Form("hNumerator_55_n65_n80_R%d_cent%d",list_radius[k], i),"",nbins_pt,boundaries_pt);
      hNumerator_65_n80[i][k] =new TH1F(Form("hNumerator_65_n80_R%d_cent%d",list_radius[k], i),"",nbins_pt,boundaries_pt);

    }
  }
  
  // but these prescl values are derived from the triggered data sample, need to check if they are the same in the minbias sample 
  // cout<<"total number of events with minbias trigger = "<<jetpbpb1[2][0]->GetEntries("HLT_HIMinBiasHfOrBSC_v1 && HLT_HIJet80_v1_Prescl==1")<<endl;
  // cout<<" numerator   "<<jetpbpb1[2][0]->GetEntries("HLT_HIMinBiasHfOrBSC_v1 && HLT_HIJet80_v1_Prescl==1 && HLT_HIJet80_v1 && jtpt[0]>110 && TMath::Abs(jteta[0])<2")<<endl;
  // cout<<" denominator "<<jetpbpb1[2][0]->GetEntries("HLT_HIMinBiasHfOrBSC_v1 && HLT_HIJet80_v1_Prescl==1 && jtpt[0]>110 && TMath::Abs(jteta[0])<2")<<endl;

  for(int k = 0;k<no_radius;k++){

    if(printDebug)cout<<"Running data reading for R = "<<list_radius[k]<<endl;
    // loop for the jetpbpb1[2] tree 
    Long64_t nentries_MB = jetpbpb1[2][k]->GetEntries();
    if(printDebug)cout<<"nentries_MB = "<<nentries_MB<<endl;
    
    for(int jentry = 0;jentry<nentries_MB;jentry++){

      jetpbpb1[0][k]->GetEntry(jentry);
      jetpbpb1[1][k]->GetEntry(jentry);
      jetpbpb1[2][k]->GetEntry(jentry);    
      jetpbpb1[3][k]->GetEntry(jentry);
      //jetpbpb1[4][k]->GetEntry(jentry);

      //if(printDebug && jentry%100000==0)cout<<"Jet 55or65 file"<<endl;
      if(printDebug && jentry%100000==0)cout<<jentry<<": event = "<<evt_1<<"; run = "<<run_1<<endl;
      
      int centBin = findBin(hiBin_1);//tells us the centrality of the event. 
      if(centBin == -1 || centBin >=nbins_cent) continue;
      
      if(pHBHENoiseFilter_1==0 || pcollisionEventSelection_1==0) continue; 

      if(fabs(vz_1)>15) continue;
      
      //if(jetMB_1==0 || jet80_p_1==0 || jet65_p_1==0 || jet55_p_1==0)  continue;
      //if(jetMB_1==0)  continue;

      if(nrefe_1 > 30) continue;


      hEvents->Fill(1);
      if(jet80_1)hEvents_Jet80->Fill(1);

#if 0
      //apply the supernova rejection cut:
      //int jetCounter = 0;//counts jets which are going to be used in the supernova cut rejection. 
      //for(int g = 0;g<nrefe_1;g++)
      //  if(eta_1[g]>=-2 && eta_1[g]<2) if(pt_1[g]>=50) jetCounter++;	  
      
      //if(jetCounter>10) continue;
      
      
      // Float_t largepT = pt_1[0];
      // //cout<<"large pT = "<<largepT<<endl;
      // Float_t deltaR = 0;
      // Float_t small_deltaR = 100.;
      // Int_t small_position = 0;
      // // find the jet thats matched with the trigger object in delta R. 
      // for(int j = 0;j<nrefe_1;++j){

      // 	deltaR = Calc_deltaR(eta_1[j],phi_1[j], trgObj_eta_1, trgObj_phi_1);
	
      // 	if(deltaR < small_deltaR){
	  
      // 	  small_deltaR = deltaR;
      // 	  small_position = j;
	  
      // 	}

      // }

      // Float_t deltaR_leading = Calc_deltaR(eta_1[0],phi_1[0], trgObj_eta_1, trgObj_phi_1);
      
      //if(trgObj_pt_1 != -99)cout<<" JetMB = "<<jetMB_1<<" Jet80 = "<<jet80_1<<" Jet65 = "<<jet65_1<<" Jet55 = "<<jet55_1<<endl;
      //if(trgObj_pt_1 != -99)cout<<" Trigger object pt =  "<<trgObj_pt_1<<", matched jet pt = "<<pt_1[small_position]<<", deltaR = "<<small_deltaR<<", leading jet pt = "<<pt_1[0]<<", delta R with leading jet = "<<deltaR_leading<<endl;
      
      // hDenominator[k]->Fill(pt_1[small_position]);
      
      // if(jet80_1==1) hNumerator_80[k]->Fill(pt_1[small_position], jet80_p_1); 
      // if(jet65_1==1) hNumerator_65[k]->Fill(pt_1[small_position], jet65_p_1); 
      // if(jet55_1==1) hNumerator_55[k]->Fill(pt_1[small_position], jet55_p_1);
      
      // now the jet which is matched with the trigger object is the jet at position 
      for(int j = 0;j<nrefe_1;++j){
      //for(int j = 0;j<1;++j){ // plotting the leading jet. 
	
	//if(chMax_1[j]/pt_1[j] < 0.02 || eMax_1[j]/pt_1[j]>0.6) continue; 
	
	hDenominator[k][centBin]->Fill(pt_1[j]);
	
	if(jet80_1==1) hNumerator_80[k][centBin]->Fill(pt_1[j], jet80_p_1); 
	if(jet65_1==1) hNumerator_65[k][centBin]->Fill(pt_1[j], jet65_p_1); 
	if(jet55_1==1) hNumerator_55[k][centBin]->Fill(pt_1[j], jet55_p_1);
	
	if(jet55_1==1 && jet65_1==0 && jet80_1==0) hNumerator_55_n65_n80[k][centBin]->Fill(pt_1[j]);
	if(jet65_1==1 && jet80_1==0) hNumerator_65_n80[k][centBin]->Fill(pt_1[j]);
	
	
	// if(jetMB_1==1 && jet80_p_1==1) {
	
	//   hDenominator[k]->Fill(pt_1[j]);
	  
	//   if(jet80_1==1) hNumerator_80[k]->Fill(pt_1[j]); 
	//   // if(jet65_1==1) hNumerator_65[k]->Fill(pt_1[0]); 
	//   // if(jet55_1==1) hNumerator_55[k]->Fill(pt_1[0]);
	  
	//   // if(jet55_1==1 && jet65_1==0 && jet80_1==0) hNumerator_55_n65_n80[k]->Fill(pt_1[0]);
	//   // if(jet65_1==1 && jet80_1==0) hNumerator_65_n80[k]->Fill(pt_1[0]);
	  
	// }
	
	
      }
#endif
	
      //trigger_info->Fill();


      
      //cout<<"after eta selection large pT = "<<largepT<<endl;
      
      //if(largepT!=test)cout<<"large pT is different in |eta|<2"<<endl;

      // hJet80_Prescl->Fill(jet80_p_1);
      // hJet65_Prescl->Fill(jet65_p_1);
      // hJet55_Prescl->Fill(jet55_p_1);

      // //if(l1MB_1 && jetMB_1) hJetMB->Fill(pt_1[0]);
      // if(jetMB_1==1)hJetMB_80_1->Fill(largepT);
      // if(jetMB_1==1 && jet65_p_1 == 1)hJetMB_65_1->Fill(largepT);
      // if(jetMB_1==1 && jet55_p_1 == 1)hJetMB_55_1->Fill(largepT);

      // if(jetMB_1==1 && jet80_1==1) hJet80_JetMB->Fill(largepT);
      // if(jetMB_1==1 && jet65_1==1 && jet65_p_1 ==1 ) hJet65_JetMB->Fill(largepT);
      // if(jetMB_1==1 && jet55_1==1 && jet55_p_1 ==1 ) hJet55_JetMB->Fill(largepT);
      
      //if(printDebug && jentry%100==0) cout<<"MB prescl = "<<jetMB_p_1<<endl;
      //if(printDebug && jentry%100==0) cout<<"Jet 55 prescl = "<<jet55_p_1<<endl;
      //if(printDebug && jentry%100==0) cout<<"Jet 65 prescl = "<<jet65_p_1<<endl;
      //if(printDebug && jentry%100==0) cout<<"Jet 80 prescl = "<<jet80_p_1<<endl;

    }//nentries_jet55or65 loop
    
  }//radius loop.
  
  // TH1F * hJet55_TrigTurnon = (TH1F*)hJet55_JetMB->Clone("hJet55_TrigTurnon");
  // hJet55_TrigTurnon->Divide(hJetMB);

  // TH1F * hJet65_TrigTurnon = (TH1F*)hJet65_JetMB->Clone("hJet65_TrigTurnon");
  // hJet65_TrigTurnon->Divide(hJetMB);

  // TH1F * hJet80_TrigTurnon = (TH1F*)hJet80_JetMB->Clone("hJet80_TrigTurnon");
  // hJet80_TrigTurnon->Divide(hJetMB);

  // TH1F * hL1SJ36_TrigTurnon = (TH1F*)hL1SJ36_JetMB->Clone("hL1SJ36_TrigTurnon");
  // hL1SJ36_TrigTurnon->Divide(hJetMB);

  // TH1F * hL1SJ52_TrigTurnon = (TH1F*)hL1SJ52_JetMB->Clone("hL1SJ52_TrigTurnon");
  // hL1SJ52_TrigTurnon->Divide(hJetMB); 
  
  if(Type=="Data"){
    TFile f(Form("/net/hisrv0001/home/rkunnawa/WORK/RAA/CMSSW_5_3_20/src/Output/PbPb_MinBiasUPC_supernova30_jetid_prescl_ak%s%s_%d_%d.root",algo,jet_type,date.GetDate(),endfile),"RECREATE");
    f.cd();

    hEvents->Write();
    hEvents_Jet80->Write();

    //jets_ID->Write();
    //hJets->Write();
    //hEvents->Write();
#if 0
    //trigger_info->Write();
    for(int i = 0; i<nbins_cent; ++i){
      for(int k = 0;k<no_radius; ++k){
	hDenominator[k][i]->Write();
	hNumerator_80[k][i]->Write();
	hNumerator_65[k][i]->Write();
	hNumerator_55[k][i]->Write();
	hNumerator_55_n65_n80[k][i]->Write();
	hNumerator_65_n80[k][i]->Write();
	//hDenominator[k][i]->Print();
	//hNumerator_80[k][i]->Print();
	//hNumerator_65[k][i]->Print();
	//hNumerator_55[k][i]->Print();
	//hNumerator_55_n65_n80[k][i]->Print();
	//hNumerator_65_n80[k][i]->Print();

      }
    }
#endif
    
    
#if 0
    hJetMB_55_1->Write();
    hJetMB_55_1->Print("base");
    hJetMB_65_1->Write();
    hJetMB_65_1->Print("base");
    hJetMB_80_1->Write();
    hJetMB_80_1->Print("base");

    // for(int k = 0;k<no_radius;++k){
    //   for(int i = 0;i<nbins_cent;++i){
    // 	hJetMBSpectra[k][i]->Write();
    // 	hJetMBSpectra[k][i]->Print("base");
    //   }
    // }
    
    //hJet80->Write();
    //hJet65->Write();
    //hJet55->Write();
    //hL1MB->Write();
    //hL1SJ36->Write();
    //hL1SJ52->Write();
    hJet80_JetMB->Write();
    hJet80_JetMB->Print("base");
    hJet65_JetMB->Write();
    hJet65_JetMB->Print("base");
    hJet55_JetMB->Write();
    hJet55_JetMB->Print("base");
    hJet80_Prescl->Write();
    hJet80_Prescl->Print("base");
    hJet65_Prescl->Write();
    hJet65_Prescl->Print("base");
    hJet55_Prescl->Write();
    hJet55_Prescl->Print("base");
    // hJet65_Jet80->Write();
    // hJet65_Jet80->Print("base");
    // hJet55_Jet80->Write();
    // hJet55_Jet80->Print("base");
    // hJet80_Trig->Write();
    // hJet80_Trig->Print("base");
    //hL1MB_JetMB->Write();
    //hL1SJ36_JetMB->Write();
    //hL1SJ52_JetMB->Write();
    // hJet55_TrigTurnon->Write();
    // hJet65_TrigTurnon->Write();
    // hJet80_TrigTurnon->Write();
    // hL1SJ36_TrigTurnon->Write();
    // hL1SJ52_TrigTurnon->Write();
#endif
  }

  if(Type=="MC"){
    TFile f(Form("/net/hisrv0001/home/rkunnawa/WORK/RAA/CMSSW_5_3_20/src/Output/PbPb_HydjetMinBias_jetntuple_withEvtCuts_ak%s3%s_%d_%d.root",algo,jet_type,date.GetDate(),endfile),"RECREATE");
    f.cd();

    //jets_ID->Write();
    //hJets->Write();
    //hEvents->Write();
  }
  
  timer.Stop();
  cout<<"Macro finished: "<<endl;
  cout<<"CPU time (min)  = "<<(float)timer.CpuTime()/60<<endl;
  cout<<"Real time (min) = "<<(float)timer.RealTime()/60<<endl;

}
int main(int argc, char** argv)
{ 

  //Chain
  TChain* chain = new TChain("MiBiCommonNTTwoPhotons/SimpleNtuple");
  // Summer 12 DY sample
  chain->Add("root://eoscms//eos/cms/store/cmst3/user/malberti/HIGGS/VERTEX/2012/MC/DYJetsToLL_M-50_TuneZ2Star_8TeV-madgraph-tarball_Summer12-PU_S7_START52_V9-v2_AODSIM/MiBiCommonNT_1_*.root");
  chain->Add("root://eoscms//eos/cms/store/cmst3/user/malberti/HIGGS/VERTEX/2012/MC/DYJetsToLL_M-50_TuneZ2Star_8TeV-madgraph-tarball_Summer12-PU_S7_START52_V9-v2_AODSIM/MiBiCommonNT_2_*.root");
  chain->Add("root://eoscms//eos/cms/store/cmst3/user/malberti/HIGGS/VERTEX/2012/MC/DYJetsToLL_M-50_TuneZ2Star_8TeV-madgraph-tarball_Summer12-PU_S7_START52_V9-v2_AODSIM/MiBiCommonNT_3_*.root");
  chain->Add("root://eoscms//eos/cms/store/cmst3/user/malberti/HIGGS/VERTEX/2012/MC/DYJetsToLL_M-50_TuneZ2Star_8TeV-madgraph-tarball_Summer12-PU_S7_START52_V9-v2_AODSIM/MiBiCommonNT_4_*.root");
  chain->Add("root://eoscms//eos/cms/store/cmst3/user/malberti/HIGGS/VERTEX/2012/MC/DYJetsToLL_M-50_TuneZ2Star_8TeV-madgraph-tarball_Summer12-PU_S7_START52_V9-v2_AODSIM/MiBiCommonNT_5_*.root");
  chain->Add("root://eoscms//eos/cms/store/cmst3/user/malberti/HIGGS/VERTEX/2012/MC/DYJetsToLL_M-50_TuneZ2Star_8TeV-madgraph-tarball_Summer12-PU_S7_START52_V9-v2_AODSIM/MiBiCommonNT_6_*.root");
  chain->Add("root://eoscms//eos/cms/store/cmst3/user/malberti/HIGGS/VERTEX/2012/MC/DYJetsToLL_M-50_TuneZ2Star_8TeV-madgraph-tarball_Summer12-PU_S7_START52_V9-v2_AODSIM/MiBiCommonNT_7_*.root");
  chain->Add("root://eoscms//eos/cms/store/cmst3/user/malberti/HIGGS/VERTEX/2012/MC/DYJetsToLL_M-50_TuneZ2Star_8TeV-madgraph-tarball_Summer12-PU_S7_START52_V9-v2_AODSIM/MiBiCommonNT_8_*.root");
  chain->Add("root://eoscms//eos/cms/store/cmst3/user/malberti/HIGGS/VERTEX/2012/MC/DYJetsToLL_M-50_TuneZ2Star_8TeV-madgraph-tarball_Summer12-PU_S7_START52_V9-v2_AODSIM/MiBiCommonNT_9_*.root");
  chain->Add("root://eoscms//eos/cms/store/cmst3/user/malberti/HIGGS/VERTEX/2012/MC/DYJetsToLL_M-50_TuneZ2Star_8TeV-madgraph-tarball_Summer12-PU_S7_START52_V9-v2_AODSIM/MiBiCommonNT_1*_*.root");



  treeReader reader((TTree*)(chain));

  // histos
  TH1F *hgen = new TH1F("hgen","hgen",60,0,60);
  hgen  -> GetXaxis()->SetTitle("N_{gen} + 1");

  TH1F *hnpumc = new TH1F("hnpumc","hnpumc",60,0,60);
  hnpumc  -> GetXaxis()->SetTitle("N_{gen}");

  TH1F *htruenpumc = new TH1F("htruenpumc","htruenpumc",60,0,60);
  htruenpumc  -> GetXaxis()->SetTitle("N_{gen}");

  TH2F *hnvtxreco_vs_npugen     = new TH2F("hnvtxreco_vs_npugen","hnvtxreco_vs_npugen",60,0,60,60,0,60);
  hnvtxreco_vs_npugen -> GetXaxis()->SetTitle("N_{gen} + 1");
  hnvtxreco_vs_npugen -> GetYaxis()->SetTitle("N_{reco}");

  TH2F *hnpugen_vs_nvtxreco     = new TH2F("hnpugen_vs_nvtxreco","hnpugen_vs_nvtxreco",60,0,60,60,0,60);
  hnpugen_vs_nvtxreco -> GetXaxis()->SetTitle("N_{reco}"); 
  hnpugen_vs_nvtxreco -> GetYaxis()->SetTitle("N_{gen} + 1");
 


  int entryMax = reader.GetEntries();
  std::cout<< "Total number of entries : " << entryMax << std::endl;
  
  // estimate the response curve NPU vs NVXT
  for (int u = 0; u < entryMax; u++ )
    {
      if(u%10000 == 0) std::cout<<"reading event "<< u <<std::endl;
      reader.GetEntry(u);
      
     
      std::vector<int>* mc_PUit_NumInteractions  = reader.GetInt("mc_PUit_NumInteractions");
      int npu = mc_PUit_NumInteractions->at(0);

      std::vector<float>* mc_PUit_TrueNumInteractions  = reader.GetFloat("mc_PUit_TrueNumInteractions");
      int truenpu = mc_PUit_TrueNumInteractions->at(0);

      std::vector<float>* PV_z       = reader.GetFloat("PV_z");
      int nvtx = PV_z->size(); // number of sim PU vtx
      
      hgen->Fill(npu+1);
      hnpumc->Fill(npu);
      htruenpumc->Fill(truenpu);

      hnvtxreco_vs_npugen -> Fill(npu+1,nvtx);
      hnpugen_vs_nvtxreco -> Fill(nvtx,npu+1);
  
    }
  
  TFile ff("weights/HistosForPUReweighting_DYJetsToLL_Summer12_S9-v2.root","recreate");

  hgen->Write();
  hnpumc->Write();
  htruenpumc->Write();
  hnvtxreco_vs_npugen -> Write();
  hnpugen_vs_nvtxreco -> Write();

  ff.Close();
  return 0;
  

}
Example #3
0
File: MyClass.C Project: libov/zeus
void MyClass::Loop()
{
//   In a ROOT session, you can do:
//      Root > .L MyClass.C
//      Root > MyClass 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;

    Float_t fJetEtCut = 4.2;
    TH1F * fDebugSVTX = new TH1F ("h1", "", 20, 0, 20);

    fChain->SetBranchStatus("*",0);  // disable all branches
    fChain->SetBranchStatus("Siq2da",1);  // activate branchname

    // create a histogram - for graphical visualization
    TH1F * histo_q2da = new TH1F ("h1", "Q^{2} distribution (double-angle method)", 100, 0, 1000);
    histo_q2da -> SetXTitle ("Q^{2}_{da}, GeV");

   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;

      // selection of the secondary vertices
       for (int vertex=0; vertex < Kt_njet_a; vertex++) {

            fDebugSVTX->Fill(0);

            // try to match one this jet (from block A) to one of the jets in block B
            // helping variables
            Bool_t      jetAinB=false;
            Int_t       correspjetB=-1;
            // loop over jets in block B
            for (int jetB=0; jetB<Kt_njet_b; jetB++) {
                // check whether Eta, Et and Phi are the same for both jets
                Float_t     deltaEta=Kt_etajet_a[vertex]-Kt_etajet_b[jetB];
                Float_t     deltaPhi=Kt_phijet_a[vertex]-Kt_phijet_b[jetB];
                Float_t     deltaEt=Kt_etjet_a[vertex]-Kt_etjet_b[jetB];
                if ( (deltaEta==0) && (deltaPhi==0) &&  (deltaEt==0) ) {
                    // found a match!
                    jetAinB=true;
                    correspjetB=jetB;
                }
            }

            // skip this block-A-jet if couldn't find a corresponding block-B-jet.
            if ( !jetAinB ) continue;
            fDebugSVTX->Fill(1);

            // JET ET CUT
            if ( Kt_etjet_b[correspjetB] < fJetEtCut) continue;
            fDebugSVTX->Fill(2);

            // JET ETA CUT
            if ( ( Kt_etajet_b[correspjetB] > 2.2 ) || ( Kt_etajet_b[correspjetB] < -1.6 ) ) continue;
            fDebugSVTX->Fill(3);

            // calculate significance of the vertex
            Float_t Significance = CalculateSignificance(vertex);

            // check whether it was successful
            if (Significance==(-999)) continue;
            fDebugSVTX->Fill(4);
            if (Significance==(-998)) continue;
            fDebugSVTX->Fill(5);

            // calculate also projected decay length
            //Float_t     ProjDecayLength = CalculateProjDecayLength(vertex);

            // calculate chi2 over NDOF (in the ntuples we have only chi2)
            Float_t     chi2ndf=Vtxsec_chi2[vertex]/Vtxsec_ndf[vertex];
            // chi2/NDOF cut
            if (chi2ndf>6.) continue;
            fDebugSVTX->Fill(6);

            // create a vertex object to be stored for later processing
    
            // ok, a good vertex was found, store it to array and raise the good-vtx-found flag
            //fSecondaryVertexFound=true;
        }

      // if (Cut(ientry) < 0) continue;
      histo_q2da -> Fill(Siq2da[0]);
   }

    // now draw the histogram
    histo_q2da -> Draw();
}
Example #4
0
void plotDYUnfoldingMatrix(const TString input, int systematicsMode = DYTools::NORMAL, int randomSeed = 1, double reweightFsr = 1.0, double massLimit = -1.0)
//systematicsMode 0 (NORMAL) - no systematic calc
//1 (RESOLUTION_STUDY) - systematic due to smearing, 2 (FSR_STUDY) - systematics due to FSR, reweighting
//check mass spectra with reweightFsr = 0.95; 1.00; 1.05  
//mass value until which do reweighting
{

  // check whether it is a calculation
  if (input.Contains("_DebugRun_")) {
    std::cout << "plotDYUnfoldingMatrix: _DebugRun_ detected. Terminating the script\n";
    return;
  }

  // normal calculation

  gBenchmark->Start("plotDYUnfoldingMatrix");

  if (systematicsMode==DYTools::NORMAL)
    std::cout<<"Running script in the NORMAL mode"<<std::endl;
  else if (systematicsMode==DYTools::RESOLUTION_STUDY)
    std::cout<<"Running script in the RESOLUTION_STUDY mode"<<std::endl;
  else if (systematicsMode==DYTools::FSR_STUDY)
    std::cout<<"Running script in the FSR_STUDY mode"<<std::endl;
  else if (systematicsMode==DYTools::ESCALE_RESIDUAL) 
    std::cout << "Running script in the ESCALE_RESIDUAL mode\n";
  else { 
    std::cout<<"requested mode not recognized"<<std::endl;
    assert(0);
  }

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================
  
  Bool_t doSave  = false;    // save plots?
  TString format = "png";   // output file format
  int saveMadePlots = 1;  // whether save produced canvases
  
  vector<TString> fnamev;   // file names   
  vector<TString> labelv;   // legend label
  vector<Int_t>   colorv;   // color in plots
  vector<Int_t>   linev;    // line style
  vector<Double_t> xsecv;
  vector<Double_t> lumiv;
  TString          dirTag;

  ifstream ifs;
  ifs.open(input.Data());
  if (!ifs.is_open()) std::cout << "failed to open a file <" << input.Data() << ">\n";
  assert(ifs.is_open());
  string line;
  Int_t state=0;
  const int inputFileMayContainEScaleDefinition = 1;
  int expectEscaleLine=1;
  ElectronEnergyScale escale((inputFileMayContainEScaleDefinition) ? 
	  ElectronEnergyScale::UNDEFINED : // read electron energy scale from the file
	  ElectronEnergyScale::Date20120101_default);
  while(getline(ifs,line)) {
    if(line[0]=='#') continue;
    if(state == 0){
      dirTag = TString(line);
      state++;
      continue;
    }else{
      if (inputFileMayContainEScaleDefinition && expectEscaleLine) {
	expectEscaleLine=0;
	// try to determine whether the input file was updated
	if (ElectronEnergyScale::DetermineCalibrationSet(line.c_str()) !=
	    ElectronEnergyScale::UNDEFINED) {
	  //std::cout << "got it ok: <" << line << ">" << std::endl;
	  escale.init(TString(line.c_str()));
	  if (!escale.isInitialized()) {
	    std::cout << "code error\n";
	    return;
	  }
	  // continue reading the file
	  getline(ifs,line);
	}
	else {
	  std::cout << "\n";
	  std::cout << "\n\tInput file does not contain electron energy scale. The expected file format:\n";
	  std::cout << "\tLine1: directory\n";
	  std::cout << "\tLine2: electron energy scale correction name (NEW from 2012 Jan 21)\n";
	  std::cout << "\tLine3: file_name.root xsect color linesty label\n";
	  std::cout << "using the default set\n\n";
	  escale.init("Date20120101_default");
	  if (!escale.isInitialized()) {
	    std::cout << "failed to correct the behavior\n";
	    return;
	  }
	}
	std::cout << "energy scale corrections: " << escale.calibrationSetName() << "\n";
      }
      string fname;
      Int_t color, linesty;
      stringstream ss(line);
      Double_t xsec;
      ss >> fname >> xsec >> color >> linesty;
      string label = line.substr(line.find('@')+1);
      fnamev.push_back(fname);
      labelv.push_back(label);
      colorv.push_back(color);
      linev.push_back(linesty);
      xsecv.push_back(xsec);
      lumiv.push_back(0);
    }
  }
  ifs.close();
  
  const Double_t kGAP_LOW  = 1.4442;
  const Double_t kGAP_HIGH = 1.566;


  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================


  TRandom random;
  // The random seeds are needed only if we are running this script in systematics mode
  int seed = randomSeed;
  random.SetSeed(seed);
  gRandom->SetSeed(seed);
  // In the case of systematic studies, generate an array of random offsets
  TVectorD shift(escale._nEtaBins); // this vector is outdated by the new features in the escale obj.class
  shift = 0;
  if(systematicsMode==DYTools::RESOLUTION_STUDY) {
    escale.randomizeSmearingWidth(seed);
    for(int i=0; i<escale._nEtaBins; i++)
      shift[i] = gRandom->Gaus(0,1);
  }

  // prepare tools for ESCALE_RESIDUAL
  TH1F *shapeWeights=NULL;
  if (systematicsMode==DYTools::ESCALE_RESIDUAL) {
    TString shapeFName=TString("../root_files/yields/") + dirTag + TString("/shape_weights.root");
    std::cout << "Obtaining shape_weights.root from <" << shapeFName << ">\n";
    TFile fshape(shapeFName);
    if (!fshape.IsOpen()) {
      std::cout << "failed to open a file <" << shapeFName << ">\n";
      throw 2;
    }
    shapeWeights = (TH1F*)fshape.Get("weights");
    shapeWeights->SetDirectory(0);
    dirTag += TString("_escale_residual");
    std::cout << "changing dirTag to <" << dirTag << ">\n";
  }

  //  
  // Set up histograms
  //
  vector<TH1F*> hZMassv;//, hZMass2v, hZPtv, hZPt2v, hZyv, hZPhiv;  
  
  char hname[100];
  for(UInt_t ifile = 0; ifile<fnamev.size(); ifile++) {
    sprintf(hname,"hZMass_%i",ifile); hZMassv.push_back(new TH1F(hname,"",500,0,1500)); hZMassv[ifile]->Sumw2();
  }

  TH1F *hMassDiff   = new TH1F("hMassDiff","", 100, -30, 30);
  TH1F *hMassDiffBB = new TH1F("hMassDiffBB","", 100, -30, 30);
  TH1F *hMassDiffEB = new TH1F("hMassDiffEB","", 100, -30, 30);
  TH1F *hMassDiffEE = new TH1F("hMassDiffEE","", 100, -30, 30);

  TH1F *hMassDiffV[DYTools::nMassBins];
  for(int i=0; i<DYTools::nMassBins; i++){
    sprintf(hname,"hMassDiffV_%d",i);
    hMassDiffV[i] = new TH1F(hname,"",100,-50,50);
  }

  // MC spectra for storage in ROOT file
  // The FSR of RECO means that this is the spectrum of generator-level
  // post-FSR mass for events that were actually reconstructed (i.e. includes
  // efficiency and acceptances losses)
  TVectorD yieldsMcFsrOfRec    (DYTools::nMassBins);
  TVectorD yieldsMcFsrOfRecErr (DYTools::nMassBins);
  TVectorD yieldsMcRec         (DYTools::nMassBins);
  TVectorD yieldsMcRecErr      (DYTools::nMassBins);
  yieldsMcFsrOfRec     = 0;
  yieldsMcFsrOfRecErr  = 0;
  yieldsMcRec          = 0;
  yieldsMcRecErr       = 0;
  // The yields at generator level with mass bins defined by post-FSR di-leptons
  TVectorD yieldsMcFsr    (DYTools::nMassBins);
  yieldsMcFsr          = 0;

  // Vectors for bin to bin corrections
  TVectorD DetCorrFactorNumerator  (DYTools::nMassBins);
  TVectorD DetCorrFactorDenominator(DYTools::nMassBins);
  TVectorD DetCorrFactor           (DYTools::nMassBins);
  TVectorD DetCorrFactorErrPos     (DYTools::nMassBins);
  TVectorD DetCorrFactorErrNeg     (DYTools::nMassBins);
  DetCorrFactorNumerator   = 0;
  DetCorrFactorDenominator = 0;
  DetCorrFactor            = 0;
  DetCorrFactorErrPos      = 0;
  DetCorrFactorErrNeg      = 0;
  
  // Matrices for unfolding
  TMatrixD DetMigration(DYTools::nMassBins, DYTools::nMassBins);
  TMatrixD DetResponse(DYTools::nMassBins, DYTools::nMassBins);
  TMatrixD DetResponseErrPos(DYTools::nMassBins, DYTools::nMassBins);
  TMatrixD DetResponseErrNeg(DYTools::nMassBins, DYTools::nMassBins);
  for(int i=0; i<DYTools::nMassBins; i++){
    for(int j=0; j<DYTools::nMassBins; j++){
      DetMigration(i,j) = 0;
      DetResponse(i,j) = 0;
      DetResponseErrPos(i,j) = 0;
      DetResponseErrNeg(i,j) = 0;
    }
  }

  //
  // Access samples and fill histograms
  //  
  TFile *infile=0;
  TTree *eventTree=0;  
    
  // Data structures to store info from TTrees
  mithep::TEventInfo    *info = new mithep::TEventInfo();
  mithep::TGenInfo *gen  = new mithep::TGenInfo();
  TClonesArray *dielectronArr = new TClonesArray("mithep::TDielectron");
  
  // loop over samples  
  for(UInt_t ifile=0; ifile<fnamev.size(); ifile++) {
  
    // Read input file
    cout << "Processing " << fnamev[ifile] << "..." << endl;
    infile = new TFile(fnamev[ifile]); 
    assert(infile);

    // Get the TTrees
    eventTree = (TTree*)infile->Get("Events"); assert(eventTree);

    // Find weight for events for this file
    // The first file in the list comes with weight 1,
    // all subsequent ones are normalized to xsection and luminosity
    double xsec=xsecv[ifile];
    AdjustXSectionForSkim(infile,xsec,eventTree->GetEntries(),1);
    lumiv[ifile] = eventTree->GetEntries()/xsec;
    double scale = lumiv[0]/lumiv[ifile];
    cout << "       -> sample weight is " << scale << endl;

    // Set branch address to structures that will store the info  
    eventTree->SetBranchAddress("Info",&info);                TBranch *infoBr       = eventTree->GetBranch("Info");
    eventTree->SetBranchAddress("Gen",&gen);                  TBranch *genBr = eventTree->GetBranch("Gen");
    eventTree->SetBranchAddress("Dielectron",&dielectronArr); TBranch *dielectronBr = eventTree->GetBranch("Dielectron");
  
    // loop over events    
    for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) {
      //if (ientry>100000) break;

      genBr->GetEntry(ientry);
      infoBr->GetEntry(ientry);

      double reweight;
      if (systematicsMode!=DYTools::FSR_STUDY) reweight=1.0;
      else if (((gen->mass)-(gen->vmass))>massLimit) reweight=1.0;
      else reweight=reweightFsr;

      if (ientry<20) std::cout<<"reweight="<<reweight<<std::endl;


      // Use post-FSR generator level mass in unfolding
      int ibinFsr = DYTools::findMassBin(gen->mass);
      if(ibinFsr != -1 && ibinFsr < yieldsMcFsr.GetNoElements()){
         yieldsMcFsr[ibinFsr] += reweight * scale * gen->weight;
      }


      /*
      // For EPS2011 for both data and MC (starting from Summer11 production)
      // we use an OR of the twi triggers below. Both are unpresecaled.
      ULong_t eventTriggerBit = kHLT_Ele17_CaloIdL_CaloIsoVL_Ele8_CaloIdL_CaloIsoVL 
	| kHLT_Ele17_CaloIdT_TrkIdVL_CaloIsoVL_TrkIsoVL_Ele8_CaloIdT_TrkIdVL_CaloIsoVL_TrkIsoVL;
      ULong_t leadingTriggerObjectBit = kHLT_Ele17_CaloIdL_CaloIsoVL_Ele8_CaloIdL_CaloIsoVL_Ele1Obj
	| kHLT_Ele17_CaloIdT_TrkIdVL_CaloIsoVL_TrkIsoVL_Ele8_CaloIdT_TrkIdVL_CaloIsoVL_TrkIsoVL_Ele1Obj;
      ULong_t trailingTriggerObjectBit = kHLT_Ele17_CaloIdL_CaloIsoVL_Ele8_CaloIdL_CaloIsoVL_Ele2Obj
	| kHLT_Ele17_CaloIdT_TrkIdVL_CaloIsoVL_TrkIsoVL_Ele8_CaloIdT_TrkIdVL_CaloIsoVL_TrkIsoVL_Ele2Obj;
      */

      const bool isData=kFALSE;
      TriggerConstantSet constantsSet = Full2011DatasetTriggers; // Enum from TriggerSelection.hh
      TriggerSelection requiredTriggers(constantsSet, isData, info->runNum);
      ULong_t eventTriggerBit = requiredTriggers.getEventTriggerBit(info->runNum);
      ULong_t leadingTriggerObjectBit = requiredTriggers.getLeadingTriggerObjectBit(info->runNum);
      ULong_t trailingTriggerObjectBit = requiredTriggers.getTrailingTriggerObjectBit(info->runNum);

      
      if(!(info->triggerBits & eventTriggerBit)) continue;  // no trigger accept? Skip to next event...                                   

      // loop through dielectrons
      dielectronArr->Clear();
      dielectronBr->GetEntry(ientry);    
      for(Int_t i=0; i<dielectronArr->GetEntriesFast(); i++) {

        const mithep::TDielectron *dielectron = (mithep::TDielectron*)((*dielectronArr)[i]);
	
	// Apply selection
	// Eta cuts
        if((fabs(dielectron->scEta_1)>kGAP_LOW) && (fabs(dielectron->scEta_1)<kGAP_HIGH)) continue;
        if((fabs(dielectron->scEta_2)>kGAP_LOW) && (fabs(dielectron->scEta_2)<kGAP_HIGH)) continue;
	if((fabs(dielectron->scEta_1) > 2.5)       || (fabs(dielectron->scEta_2) > 2.5))       continue;  // outside eta range? Skip to next event...
	
	// Asymmetric SC Et cuts
	if( ! ( ( dielectron->scEt_1 > DYTools::etMinLead  && dielectron->scEt_2 > DYTools::etMinTrail)
		|| ( dielectron->scEt_1 > DYTools::etMinTrail  && dielectron->scEt_2 > DYTools::etMinLead) )) continue;
    	
	// Both electrons must match trigger objects. At least one ordering
	// must match
	if( ! ( 
	       (dielectron->hltMatchBits_1 & leadingTriggerObjectBit && 
		dielectron->hltMatchBits_2 & trailingTriggerObjectBit )
	       ||
	       (dielectron->hltMatchBits_1 & trailingTriggerObjectBit && 
		dielectron->hltMatchBits_2 & leadingTriggerObjectBit ) ) ) continue;
	
	// The Smurf electron ID package is the same as used in HWW analysis
	// and contains cuts like VBTF WP80 for pt>20, VBTF WP70 for pt<10
	// with some customization, plus impact parameter cuts dz and dxy
	if(!passSmurf(dielectron)) continue;  

        // We have a Z candidate! HURRAY! 

	// Apply extra smearing to MC reconstructed dielectron mass
	// to better resemble the data
	/*
	  outdated lines. kept for reference
	double smear1 = escale.extraSmearingSigma(dielectron->scEta_1);
        double smear2 = escale::extraSmearingSigma(dielectron->scEta_2);
	// In systematics mode, overwrite the smear values with
	// shifted ones.
	if(systematicsMode==DYTools::RESOLUTION_STUDY){
	  smear1 = escale::extraSmearingSigmaShifted(dielectron->scEta_1,shift);
	  smear2 = escale::extraSmearingSigmaShifted(dielectron->scEta_2,shift);
	}
        double smearTotal = sqrt(smear1*smear1 + smear2*smear2);
        double massResmeared = dielectron->mass + random.Gaus(0.0,smearTotal);
	*/
	/* lines based on new features -- begin */
	double massSmear = (systematicsMode == DYTools::RESOLUTION_STUDY) ?
	  escale.generateMCSmearRandomized(dielectron->scEta_1,dielectron->scEta_2) :
	  escale.generateMCSmear(dielectron->scEta_1,dielectron->scEta_2);
        double massResmeared = dielectron->mass + massSmear;
	/* lines based on new features -- end */

	hZMassv[ifile]->Fill(massResmeared,scale * gen->weight);

	// Fill structures for response matrix and bin by bin corrections

	if(ibinFsr != -1 && ibinFsr < yieldsMcFsrOfRec.GetNoElements()){
	    yieldsMcFsrOfRec[ibinFsr] += reweight * scale * gen->weight;
	    DetCorrFactorDenominator(ibinFsr) += reweight * scale * gen->weight;
          }

	else if(ibinFsr >= yieldsMcFsrOfRec.GetNoElements())
	  cout << "ERROR: binning problem" << endl;

	int ibinRec = DYTools::findMassBin(massResmeared);
	double shape_weight = (shapeWeights && (ibinRec!=-1)) ? 
	  shapeWeights->GetBinContent(ibinRec+1) : 1.0;
	if(ibinRec != -1 && ibinRec < yieldsMcRec.GetNoElements()){
	    yieldsMcRec[ibinRec] += reweight * scale * gen->weight;
	    DetCorrFactorNumerator(ibinRec) += reweight * scale * gen->weight * shape_weight;
          }

	else if(ibinRec >= yieldsMcRec.GetNoElements())
	  cout << "ERROR: binning problem" << endl;
	
	if( ibinRec != -1 && ibinRec < yieldsMcRec.GetNoElements() 
	    && ibinFsr != -1 && ibinFsr < yieldsMcRec.GetNoElements() ){
          DetMigration(ibinFsr,ibinRec) += reweight * scale * gen->weight * shape_weight;
	}
	
        Bool_t isB1 = (fabs(dielectron->scEta_1)<kGAP_LOW);
        Bool_t isB2 = (fabs(dielectron->scEta_2)<kGAP_LOW);         
	hMassDiff->Fill(massResmeared - gen->mass);
	if( isB1 && isB2 )
	  hMassDiffBB->Fill(massResmeared - gen->mass);
	if( (isB1 && !isB2) || (!isB1 && isB2) )
	  hMassDiffEB->Fill(massResmeared - gen->mass);
	if( !isB1 && !isB2 )
	  hMassDiffEE->Fill(massResmeared - gen->mass);
	
	if(ibinFsr != -1){
	  hMassDiffV[ibinFsr]->Fill(massResmeared - gen->mass);
	}
// 	if(ibinRec == -1)
// 	  printf("Missed bin:  M_fsr=%f   M_reco=%f\n", gen->mass, massResmeared);
	
      } // end loop over dielectrons

    } // end loop over events 
    delete infile;
    infile=0, eventTree=0;
  } // end loop over files
  delete gen;


  //finish reweighting of mass spectra

  
  // Find bin by bin corrections and the errors
  double tCentral, tErrNeg, tErrPos;
  for(int i=0; i<DYTools::nMassBins; i++){
    if ( DetCorrFactorDenominator(i) != 0 ){
      // This method does not take into account correlation between numerator
      // and denominator in calculation of errors. This is a flaw to be corrected
      // in the future.
      SimpleDivide( DetCorrFactorNumerator(i), DetCorrFactorDenominator(i), tCentral, tErrNeg, tErrPos);
      DetCorrFactor(i) = tCentral;
      DetCorrFactorErrPos(i) = tErrPos;
      DetCorrFactorErrNeg(i) = tErrNeg;
    } else {
      DetCorrFactor(i) = 0;
      DetCorrFactorErrPos(i) = 0;
      DetCorrFactorErrNeg(i) = 0;
    }
  }
  
  // Find response matrix, which is simply the normalized migration matrix
  for(int ifsr = 0; ifsr < DetMigration.GetNrows(); ifsr++){
    double nEventsInFsrMassBin = 0;
    for(int ireco = 0; ireco < DetMigration.GetNcols(); ireco++)
      nEventsInFsrMassBin += DetMigration(ifsr,ireco);
    // Now normalize each element and find errors
    for(int ireco = 0; ireco < DetMigration.GetNcols(); ireco++){
      tCentral = 0;
      tErrPos  = 0;
      tErrNeg  = 0;
      // Note: the event counts supposedly are dominated with events with weight "1"
      // coming from the primary MC sample, so the error is assumed Poissonian in
      // the call for efficiency-calculating function below.
      if( nEventsInFsrMassBin != 0 ){
	EfficiencyDivide(DetMigration(ifsr,ireco), nEventsInFsrMassBin, tCentral, tErrNeg, tErrPos);
      // BayesEfficiency does not seem to be working in newer ROOT versions, 
      // so it is replaced by simler method
//         BayesEfficiency( DetMigration(ifsr,ireco), nEventsInFsrMassBin, tCentral, tErrNeg, tErrPos);
      }
      DetResponse      (ifsr,ireco) = tCentral;
      DetResponseErrPos(ifsr,ireco) = tErrPos;
      DetResponseErrNeg(ifsr,ireco) = tErrNeg;
    }
  }

  // Find inverted response matrix
  TMatrixD DetInvertedResponse = DetResponse;
  Double_t det;
  DetInvertedResponse.Invert(&det);
  TMatrixD DetInvertedResponseErr(DetInvertedResponse.GetNrows(), DetInvertedResponse.GetNcols());
  calculateInvertedMatrixErrors(DetResponse, DetResponseErrPos, DetResponseErrNeg, DetInvertedResponseErr);

  // Package bin limits into TVectorD for storing in a file
  TVectorD BinLimitsArray(DYTools::nMassBins+1);
  for(int i=0; i<DYTools::nMassBins+1; i++)
    BinLimitsArray(i) = DYTools::massBinLimits[i];

  // Store constants in the file
  TString outputDir(TString("../root_files/constants/")+dirTag);
  if((systematicsMode==DYTools::RESOLUTION_STUDY) || (systematicsMode==DYTools::FSR_STUDY))
    outputDir = TString("../root_files/systematics/")+dirTag;
  gSystem->mkdir(outputDir,kTRUE);
  TString unfoldingConstFileName(outputDir+TString("/unfolding_constants.root"));
  if(systematicsMode==DYTools::RESOLUTION_STUDY){
    unfoldingConstFileName = outputDir+TString("/unfolding_constants_seed_");
    unfoldingConstFileName += seed;
    unfoldingConstFileName += ".root";
  }
  if(systematicsMode==DYTools::FSR_STUDY){
    unfoldingConstFileName = outputDir+TString("/unfolding_constants_reweight_");
    unfoldingConstFileName += int(100*reweightFsr);
    unfoldingConstFileName += ".root";
  }

  TFile fConst(unfoldingConstFileName, "recreate" );
  DetResponse             .Write("DetResponse");
  DetInvertedResponse     .Write("DetInvertedResponse");
  DetInvertedResponseErr  .Write("DetInvertedResponseErr");
  BinLimitsArray          .Write("BinLimitsArray");
  DetCorrFactor           .Write("DetCorrFactor");
  DetCorrFactorErrPos     .Write("DetCorrFactorErrPos");
  DetCorrFactorErrNeg     .Write("DetCorrFactorErrNeg");
  fConst.Close();
  
  // Store reference MC arrays in a file
  TString refFileName(outputDir+TString("/yields_MC_unfolding_reference.root"));
  TFile fRef(refFileName, "recreate" );
  BinLimitsArray    .Write("BinLimitsArray");
  yieldsMcFsr       .Write("yieldsMcFsr");
  yieldsMcFsrOfRec  .Write("yieldsMcFsrOfRec");
  yieldsMcRec       .Write("yieldsMcRec");
  fRef.Close();


  //--------------------------------------------------------------------------------------------------------------
  // Make plots 
  //==============================================================================================================  

  std::vector<TCanvas*> canvasV; // holder for a quick saver
  canvasV.reserve(10);

  TCanvas *c = MakeCanvas("zMass1","zMass1",800,600);
  canvasV.push_back(c);

  // string buffers
  char ylabel[50];   // y-axis label

  // Z mass
  sprintf(ylabel,"a.u. / %.1f GeV/c^{2}",hZMassv[0]->GetBinWidth(1));
  CPlot plotZMass1("zmass1","","m(ee) [GeV/c^{2}]",ylabel);
  if (fnamev.size()) hZMassv[0]->GetXaxis()->SetLimits(10.,2000.);
  for(UInt_t i=0; i<fnamev.size(); i++) { 
    plotZMass1.AddHist1D(hZMassv[i],labelv[i],"hist",colorv[i],linev[i]); 
  }
  plotZMass1.SetLogy();
  plotZMass1.SetLogx(); 
  plotZMass1.TransLegend(0.02, 0.0);
  plotZMass1.Draw(c,doSave,format);

  // Create plots of how reco mass looks and how unfolded mass should look like
  TVectorD massBinCentral     (DYTools::nMassBins);
  TVectorD massBinHalfWidth   (DYTools::nMassBins);
  TVectorD yieldMcFsrOfRecErr (DYTools::nMassBins);
  TVectorD yieldMcRecErr      (DYTools::nMassBins);
  for(int i=0; i < DYTools::nMassBins; i++){
    massBinCentral  (i) = (DYTools::massBinLimits[i+1] + DYTools::massBinLimits[i])/2.0;
    massBinHalfWidth(i) = (DYTools::massBinLimits[i+1] - DYTools::massBinLimits[i])/2.0;
    yieldsMcFsrOfRecErr(i) = sqrt(yieldsMcFsrOfRec[i]);
    yieldsMcRecErr     (i) = sqrt(yieldsMcRec[i]);
  }
  TGraphErrors *grFsrOfRec = new TGraphErrors(massBinCentral, yieldsMcFsrOfRec, 
					      massBinHalfWidth, yieldsMcFsrOfRecErr);
  TGraphErrors *grRec      = new TGraphErrors(massBinCentral, yieldsMcRec, 
					      massBinHalfWidth, yieldsMcRecErr);
  TCanvas *d = MakeCanvas("zMass2","zMass2",800,600);
  canvasV.push_back(d);
  CPlot plotZMass2("zmass2","","m(ee) [GeV/c^{2}]","events");
  plotZMass2.SetLogx(1);
  plotZMass2.AddGraph(grFsrOfRec,"no detector effects","PE",kBlack);
  plotZMass2.AddGraph(grRec,"reconstructed","PE",kBlue);
  plotZMass2.Draw(d);

//   double xsize = 600;
//   double ysize = 600;
  int xsize = 600;
  int ysize = 400;

  // Create the plot of the response matrix
  TH2F *hResponse = new TH2F("hResponse","",DYTools::nMassBins, DYTools::massBinLimits,
			     DYTools::nMassBins, DYTools::massBinLimits);
  for(int i=1; i<=DYTools::nMassBins; i++)
    for(int j=1; j<=DYTools::nMassBins; j++)
      hResponse->SetBinContent(i,j,DetResponse(i-1,j-1));
  TCanvas *e = MakeCanvas("response","response",xsize,ysize);
  canvasV.push_back(e);
  CPlot plotResponse("response","",
		     "generator post-FSR m(ee) [GeV/c^{2}]",
		     "reconstructed  m(ee) [GeV/c^{2}]");
  plotResponse.AddHist2D(hResponse,"COLZ");
  e->cd();
  plotResponse.SetLogx();
  plotResponse.SetLogy();
  gPad->SetRightMargin(0.15);
  gStyle->SetPalette(1);
  hResponse->GetXaxis()->SetMoreLogLabels();
  hResponse->GetXaxis()->SetNoExponent();
  hResponse->GetYaxis()->SetNoExponent();
  plotResponse.Draw(e);

  // Create the plot of the inverted response matrix
  TH2F *hInvResponse = new TH2F("hInvResponse","",DYTools::nMassBins, DYTools::massBinLimits,
			     DYTools::nMassBins, DYTools::massBinLimits);
  for(int i=1; i<=DYTools::nMassBins; i++)
    for(int j=1; j<=DYTools::nMassBins; j++)
      hInvResponse->SetBinContent(i,j,DetInvertedResponse(i-1,j-1));
  TCanvas *f = MakeCanvas("invResponse","invResponse",xsize,ysize);
  canvasV.push_back(f);
  CPlot plotInvResponse("inverted response","",
			"reconstructed  m(ee) [GeV/c^{2}]",
			"generator post-FSR m(ee) [GeV/c^{2}]");
  plotInvResponse.AddHist2D(hInvResponse,"COLZ");
  f->cd();
  plotInvResponse.SetLogx();
  plotInvResponse.SetLogy();
  gPad->SetRightMargin(0.15);
  gStyle->SetPalette(1);
  hInvResponse->GetXaxis()->SetMoreLogLabels();
  hInvResponse->GetXaxis()->SetNoExponent();
  hInvResponse->GetYaxis()->SetNoExponent();
  plotInvResponse.Draw(f);

  // Create a plot of detector resolution without mass binning
  TCanvas *g = MakeCanvas("massDiff","massDiff",600,600);
  canvasV.push_back(g);
  CPlot plotMassDiff("massDiff","","reco mass - gen post-FSR mass [GeV/c^{2}]","a.u.");
  hMassDiffBB->Scale(1.0/hMassDiffBB->GetSumOfWeights());
  hMassDiffEB->Scale(1.0/hMassDiffEB->GetSumOfWeights());
  hMassDiffEE->Scale(1.0/hMassDiffEE->GetSumOfWeights());
  plotMassDiff.AddHist1D(hMassDiffBB,"EB-EB","hist",kBlack);
  plotMassDiff.AddHist1D(hMassDiffEB,"EE-EB","hist",kBlue);
  plotMassDiff.AddHist1D(hMassDiffEE,"EE-EE","hist",kRed);
  plotMassDiff.TransLegend(0.1, 0.0);
  plotMassDiff.Draw(g);



  // Create a plot of reco - gen post-FSR mass difference for several mass bins
  TCanvas *h = MakeCanvas("massDiffV","massDiffV",600,600);
  canvasV.push_back(h);
  CPlot plotMassDiffV("massDiffV","","reco mass - gen post-FSR mass [GeV/c^{2}]","a.u.");
  hMassDiffV[7]->Scale(1.0/hMassDiffV[7]->GetSumOfWeights());
  hMassDiffV[6]->Scale(1.0/hMassDiffV[6]->GetSumOfWeights());
  hMassDiffV[5]->Scale(1.0/hMassDiffV[5]->GetSumOfWeights());
  hMassDiffV[4]->Scale(1.0/hMassDiffV[4]->GetSumOfWeights());
  plotMassDiffV.AddHist1D(hMassDiffV[4],"50-60 GeV/c^{2}","hist",kBlack);
  plotMassDiffV.AddHist1D(hMassDiffV[5],"60-76 GeV/c^{2}","hist",kBlue);
  plotMassDiffV.AddHist1D(hMassDiffV[6],"76-86 GeV/c^{2}","hist",kRed);
  plotMassDiffV.AddHist1D(hMassDiffV[7],"86-96 GeV/c^{2}","hist",kMagenta);
  plotMassDiffV.SetXRange(-20,50);
  plotMassDiffV.Draw(h);

  // Create graph of bin-to-bin corrections
  TGraphAsymmErrors *grCorrFactor 
    = new TGraphAsymmErrors(massBinCentral, DetCorrFactor,
			    massBinHalfWidth, massBinHalfWidth,
			    DetCorrFactorErrNeg, DetCorrFactorErrPos);
  TCanvas *c11 = MakeCanvas("corrFactor","corrFactor",800,600);
  canvasV.push_back(c11);
  CPlot plotCorrFactor("corrFactor","","m(ee) [GeV/c^{2}]","correction factor");
  plotCorrFactor.AddGraph(grCorrFactor,"PE",kBlue);
  plotCorrFactor.SetLogx();
  plotCorrFactor.SetYRange(0,2.0);
  plotCorrFactor.Draw(c11);

  if (saveMadePlots) {
    TString plotPath=TString("../root_files/plots/") + dirTag; 
    TString name=plotPath + TString("/unfolding_plots.root");
    gSystem->mkdir(plotPath,true);
    TFile* fplots = TFile::Open(name,"RECREATE");
    for (unsigned int i=0; i<canvasV.size(); ++i) {
      canvasV[i]->Write();
    }
    fplots->Close();
  }

  //--------------------------------------------------------------------------------------------------------------
  // Summary print out
  //==============================================================================================================
  cout << endl;
  cout << "*" << endl;
  cout << "* SUMMARY" << endl;
  cout << "*--------------------------------------------------" << endl;
  cout << endl; 
  
  // Printout of all constants, uncomment if needed

  //printf("DetMigration:\n"); DetMigration.Print();
  //printf("DetResponse:\n"); DetResponse.Print();
  //printf("DetInvertedResponse:\n"); DetInvertedResponse.Print();

//   DetCorrFactor.Print();
//   DetResponse.Print();
  
//   printf("Detector corr factor numerator:\n");
//   DetCorrFactorNumerator.Print();
//   printf("yieldsMcRec:\n");
//   yieldsMcRec.Print();

//   printf("Detector corr factor denominator:\n");
//   DetCorrFactorDenominator.Print();
//   printf("yieldsMcFsrOfRec:\n");
//   yieldsMcFsrOfRec.Print();

  gBenchmark->Show("plotDYUnfoldingMatrix");
}
void readTree_background() {
  Char_t *filename = "Background.root";
  // Retrieve the TTree
  TFile* myFile = TFile::Open(filename);
  TTree* tree = (TTree*)(myFile->Get("tree"));
  Double_t Et1, eta1, phi1, Et2, eta2, phi2;
  tree->SetBranchAddress("Et1" ,&Et1 );
  tree->SetBranchAddress("eta1",&eta1);
  tree->SetBranchAddress("phi1",&phi1);
  tree->SetBranchAddress("Et2" ,&Et2 );
  tree->SetBranchAddress("eta2",&eta2);
  tree->SetBranchAddress("phi2",&phi2);
  // Book histograms
  TH1F* hmass = new TH1F("hmass","m_{#gamma#gamma}",60,100.,160.);
  hmass->GetXaxis()->SetTitle("Invariant mass [GeV]");
  hmass->GetYaxis()->SetTitle("Events");
  // Loop over the events
  Long64_t events = tree->GetEntries();  
  for (int i=0; i<events; i++) {
    tree->GetEntry(i);
    TLorentzVector g1,g2;
    g1.SetPtEtaPhiM(Et1,eta1,phi1,0.);
    g2.SetPtEtaPhiM(Et2,eta2,phi2,0.);
    TLorentzVector gg=g1+g2;
    hmass->Fill( gg.M() );
  }
  // Test of different background options
  hmass->DrawClone("e");
  TCanvas* myCanvas = new TCanvas("myCanvas","Background fits",800,800);
  myCanvas->Divide(2,2);
  // Linear background
  TF1* myBack1 = new TF1("myBack1","[0]+[1]*x",100.,160.);
  myBack1->SetParameter(0,events);
  myBack1->SetParameter(1,-100.);
  myCanvas->cd(1);
  hmass->Fit(myBack1);
  hmass->DrawClone("e");
  EvaluatePvalue(myBack1);
  // Quadratic background
  TF1* myBack2 = new TF1("myBack2","[0]+[1]*x+[2]*x**2",100.,160.);
  myBack2->SetParameter(0,events);
  myBack2->SetParameter(1,-100.);
  myBack2->SetParameter(1,0.);
  myCanvas->cd(2);
  hmass->Fit(myBack2);
  hmass->DrawClone("e");
  EvaluatePvalue(myBack2);
  // Exponential background
  TF1* myBack3 = new TF1("myBack3","[0]*exp(-x/[1])",100.,160.);
  myBack3->SetParameter(0,events);
  myBack3->SetParameter(1,100.);
  myCanvas->cd(3);
  hmass->Fit(myBack3);
  hmass->DrawClone("e");
  EvaluatePvalue(myBack3);
  // Cubic background
  TF1* myBack4 = new TF1("myBack4","[0]+[1]*x+[2]*x**2+[3]*x**3",100.,160.);
  myBack4->SetParameter(0,0.);
  myBack4->SetParameter(1,0.);
  myBack4->SetParameter(2,0.);
  myBack4->SetParameter(3,0.);
  myCanvas->cd(4);
  TFitResultPtr fit4 = hmass->Fit(myBack4,"S");
  hmass->DrawClone("e");
  EvaluatePvalue(myBack4);
}
int main( int argc, const char* argv[] ){

  // List of arguments:
  // 0: The executable itself
  // 1: The number of times JetMET is smeared (not smeared if equal to 1)
  // 2: The scale and type of JES shift (if fabs(x) < 0.5, shift by eta, else absolute

// fixme: Depracated
   float JES_JetMET = 1.0;

  string xmlFileName = string ("./MyMassAnalysis.xml");

  for (int i=1;i<argc;++i) {
    if (strncmp(argv[i],"-c",2)==0) xmlFileName = string(argv[i+1]);
    if (strncmp(argv[i],"-h",2)==0) {
      cout << " -c xm_config_file\n";
      exit(1);
    }
  }

  cout<<"#########################"<<endl;
  cout<<"Beginning of the program"<<endl;
  cout<<"#########################"<<endl;

  //////////////////////
  //Global variables
  //////////////////////

  // GEN
  TH1F * histoGenTopRapidity1 = new TH1F("GenTopRapidity1", "GenTopRapidity1", 100, -5, 5);
  TH1F * histoGenTopRapidity2 = new TH1F("GenTopRapidity2", "GenTopRapidity2", 100, -5, 5);
  TH1F * histoGenTopMass1 = new TH1F("GenTopMass1", "GenTopMass1", 200, 0, 200);
  TH1F * histoGenTopMass2 = new TH1F("GenTopMass2", "GenTopMass2", 200, 0, 200);
  TH2F * histoGenTopMass1VsTopMass2 = new TH2F("GenTopMass1VsTopMass2", "GenTopMass1VsTopMass2", 200, 0, 200, 200, 0, 200);
  TH1F * histoGenDelta_y = new TH1F("GenDelta_y", "GenDelta_y", 400, -2, 2);
  TH1F * histoGenTTRapidity = new TH1F("GenTTRapidity", "GenTTRapidity", 500, -2.5, 2.5);
  TH1F * histoGenTTPt = new TH1F("GenTTPt", "GenTTPt", 250, 0, 250);
  TH1F * histoGenTTMass = new TH1F("GenTTMass", "GenTTMass", 100, 0, 1000);

  TH2F * histoGenDelta_yVsTTRapidity = new TH2F("GenDelta_yVsTTRapidity", "GenDelta_yVsTTRapidity", 10, -2, 2, 5, -2.5, 2.5);
  TH2F * histoGenDelta_yVsTTPt = new TH2F("GenDelta_yVsTTPt", "GenDelta_yVsTTPt", 10, -2, 2, 5, 0, 250);
  TH2F * histoGenDelta_yVsTTMass = new TH2F("GenDelta_yVsTTMass", "GenDelta_yVsTTMass", 10, -2, 2, 5, 0, 1000);
  TH1F * histoGenN_plusTTRapidity = new TH1F("GenN_plusTTRapidity", "GenN_plusTTRapidity", 20, -2.5, 2.5);
  histoGenN_plusTTRapidity->Sumw2();
  TH1F * histoGenN_plusTTPt = new TH1F("GenN_plusTTPt", "GenN_plusTTPt", 20, 0, 250);
  histoGenN_plusTTPt->Sumw2();
  TH1F * histoGenN_plusTTMass = new TH1F("GenN_plusTTMass", "GenN_plusTTMass", 20, 0, 1000);
  histoGenN_plusTTMass->Sumw2();
  TH1F * histoGenN_minusTTRapidity = new TH1F("GenN_minusTTRapidity", "GenN_minusTTRapidity", 20, -2.5, 2.5);
  histoGenN_minusTTRapidity->Sumw2();
  TH1F * histoGenN_minusTTPt = new TH1F("GenN_minusTTPt", "GenN_minusTTPt", 20, 0, 250);
  histoGenN_minusTTPt->Sumw2();
  TH1F * histoGenN_minusTTMass = new TH1F("GenN_minusTTMass", "GenN_minusTTMass", 20, 0, 1000);
  histoGenN_minusTTMass->Sumw2();
  TH1F * histoGenN_plusMinusN_minusTTRapidity = new TH1F("GenN_plusMinusN_minusTTRapidity", "GenN_plusMinusN_minusTTRapidity", 20, -2.5, 2.5);
  histoGenN_plusMinusN_minusTTRapidity->Sumw2();
  TH1F * histoGenN_plusPlusN_minusTTRapidity = new TH1F("GenN_plusPlusN_minusTTRapidity", "GenN_plusPlusN_minusTTRapidity", 20, -2.5, 2.5);
  histoGenN_plusPlusN_minusTTRapidity->Sumw2();
  TH1F * histoGenN_plusMinusN_minusTTPt = new TH1F("GenN_plusMinusN_minusTTPt", "GenN_plusMinusN_minusTTPt", 20, 0, 250);
  histoGenN_plusMinusN_minusTTPt->Sumw2();
  TH1F * histoGenN_plusPlusN_minusTTPt = new TH1F("GenN_plusPlusN_minusTTPt", "GenN_plusPlusN_minusTTPt", 20, 0, 250);
  histoGenN_plusPlusN_minusTTPt->Sumw2();
  TH1F * histoGenN_plusMinusN_minusTTMass = new TH1F("GenN_plusMinusN_minusTTMass", "GenN_plusMinusN_minusTTMass", 20, 0, 1000);
  histoGenN_plusMinusN_minusTTMass->Sumw2();
  TH1F * histoGenN_plusPlusN_minusTTMass = new TH1F("GenN_plusPlusN_minusTTMass", "GenN_plusPlusN_minusTTMass", 20, 0, 1000);
  histoGenN_plusPlusN_minusTTMass->Sumw2();
  TH1F * histoGenA_cTTRapidity = new TH1F("GenA_cTTRapidity", "GenA_cTTRapidity", 20, -2.5, 2.5);
  histoGenA_cTTRapidity->Sumw2();
  TH1F * histoGenA_cTTPt = new TH1F("GenA_cTTPt", "GenA_cTTPt", 20, 0, 250);
  histoGenA_cTTPt->Sumw2();
  TH1F * histoGenA_cTTMass = new TH1F("GenA_cTTMass", "GenA_cTTMass", 20, 0, 1000);
  histoGenA_cTTMass->Sumw2();
  // Fine binning
  TH2F * histoFineBinning_GenDelta_yVsTTRapidity = new TH2F("FineBinning_GenDelta_yVsTTRapidity", "FineBinning_GenDelta_yVsTTRapidity", 200, -2, 2, 500, -2.5, 2.5);
  TH2F * histoFineBinning_GenDelta_yVsTTPt = new TH2F("FineBinning_GenDelta_yVsTTPt", "FineBinning_GenDelta_yVsTTPt", 200, -2, 2, 250, 0, 250);
  TH2F * histoFineBinning_GenDelta_yVsTTMass = new TH2F("FineBinning_GenDelta_yVsTTMass", "FineBinning_GenDelta_yVsTTMass", 200, -2, 2, 100, 0, 1000);
  TH1F * histoFineBinning_GenN_plusTTRapidity = new TH1F("FineBinning_GenN_plusTTRapidity", "FineBinning_GenN_plusTTRapidity", 500, -2.5, 2.5);
  histoFineBinning_GenN_plusTTRapidity->Sumw2();
  TH1F * histoFineBinning_GenN_plusTTPt = new TH1F("FineBinning_GenN_plusTTPt", "FineBinning_GenN_plusTTPt", 250, 0, 250);
  histoFineBinning_GenN_plusTTPt->Sumw2();
  TH1F * histoFineBinning_GenN_plusTTMass = new TH1F("FineBinning_GenN_plusTTMass", "FineBinning_GenN_plusTTMass", 100, 0, 1000);
  histoFineBinning_GenN_plusTTMass->Sumw2();
  TH1F * histoFineBinning_GenN_minusTTRapidity = new TH1F("FineBinning_GenN_minusTTRapidity", "FineBinning_GenN_minusTTRapidity", 500, -2.5, 2.5);
  histoFineBinning_GenN_minusTTRapidity->Sumw2();
  TH1F * histoFineBinning_GenN_minusTTPt = new TH1F("FineBinning_GenN_minusTTPt", "FineBinning_GenN_minusTTPt", 250, 0, 250);
  histoFineBinning_GenN_minusTTPt->Sumw2();
  TH1F * histoFineBinning_GenN_minusTTMass = new TH1F("FineBinning_GenN_minusTTMass", "FineBinning_GenN_minusTTMass", 100, 0, 1000);
  histoFineBinning_GenN_minusTTMass->Sumw2();
  TH1F * histoFineBinning_GenN_plusMinusN_minusTTRapidity = new TH1F("FineBinning_GenN_plusMinusN_minusTTRapidity", "FineBinning_GenN_plusMinusN_minusTTRapidity", 500, -2.5, 2.5);
  histoFineBinning_GenN_plusMinusN_minusTTRapidity->Sumw2();
  TH1F * histoFineBinning_GenN_plusPlusN_minusTTRapidity = new TH1F("FineBinning_GenN_plusPlusN_minusTTRapidity", "FineBinning_GenN_plusPlusN_minusTTRapidity", 500, -2.5, 2.5);
  histoFineBinning_GenN_plusPlusN_minusTTRapidity->Sumw2();
  TH1F * histoFineBinning_GenN_plusMinusN_minusTTPt = new TH1F("FineBinning_GenN_plusMinusN_minusTTPt", "FineBinning_GenN_plusMinusN_minusTTPt", 250, 0, 250);
  histoFineBinning_GenN_plusMinusN_minusTTPt->Sumw2();
  TH1F * histoFineBinning_GenN_plusPlusN_minusTTPt = new TH1F("FineBinning_GenN_plusPlusN_minusTTPt", "FineBinning_GenN_plusPlusN_minusTTPt", 250, 0, 250);
  histoFineBinning_GenN_plusPlusN_minusTTPt->Sumw2();
  TH1F * histoFineBinning_GenN_plusMinusN_minusTTMass = new TH1F("FineBinning_GenN_plusMinusN_minusTTMass", "FineBinning_GenN_plusMinusN_minusTTMass", 100, 0, 1000);
  histoFineBinning_GenN_plusMinusN_minusTTMass->Sumw2();
  TH1F * histoFineBinning_GenN_plusPlusN_minusTTMass = new TH1F("FineBinning_GenN_plusPlusN_minusTTMass", "FineBinning_GenN_plusPlusN_minusTTMass", 100, 0, 1000);
  histoFineBinning_GenN_plusPlusN_minusTTMass->Sumw2();
  TH1F * histoFineBinning_GenA_cTTRapidity = new TH1F("FineBinning_GenA_cTTRapidity", "FineBinning_GenA_cTTRapidity", 500, -2.5, 2.5);
  histoFineBinning_GenA_cTTRapidity->Sumw2();
  TH1F * histoFineBinning_GenA_cTTPt = new TH1F("FineBinning_GenA_cTTPt", "FineBinning_GenA_cTTPt", 250, 0, 250);
  histoFineBinning_GenA_cTTPt->Sumw2();
  TH1F * histoFineBinning_GenA_cTTMass = new TH1F("FineBinning_GenA_cTTMass", "FineBinning_GenA_cTTMass", 100, 0, 1000);
  histoFineBinning_GenA_cTTMass->Sumw2();


  // RECO
  TH1F * histoRecoTopRapidity1 = new TH1F("RecoTopRapidity1", "RecoTopRapidity1", 100, -5, 5);
  TH1F * histoRecoTopRapidity2 = new TH1F("RecoTopRapidity2", "RecoTopRapidity2", 100, -5, 5);
  TH1F * histoRecoLeptonRapidity1 = new TH1F("RecoLeptonRapidity1", "RecoLeptonRapidity1", 100, -5, 5);
  TH1F * histoRecoLeptonRapidity2 = new TH1F("RecoLeptonRapidity2", "RecoLeptonRapidity2", 100, -5, 5);
  TH1F * histoRecoTopMass1 = new TH1F("RecoTopMass1", "RecoTopMass1", 300, 0, 300);
  TH1F * histoRecoTopMass2 = new TH1F("RecoTopMass2", "RecoTopMass2", 300, 0, 300);
  TH2F * histoRecoTopMass1VsTopMass2 = new TH2F("RecoTopMass1VsTopMass2", "RecoTopMass1VsTopMass2", 300, 0, 300, 300, 0, 300);
  TH1F * histoRecoDelta_y = new TH1F("RecoDelta_y", "RecoDelta_y", 400, -2, 2);
  TH1F * histoRecoTTRapidity = new TH1F("RecoTTRapidity", "RecoTTRapidity", 500, -2.5, 2.5);
  TH1F * histoRecoTTPt = new TH1F("RecoTTPt", "RecoTTPt", 250, 0, 250);
  TH1F * histoRecoTTMass = new TH1F("RecoTTMass", "RecoTTMass", 100, 0, 1000);

  TH2F * histoRecoDelta_yVsTTRapidity = new TH2F("RecoDelta_yVsTTRapidity", "RecoDelta_yVsTTRapidity", 10, -2, 2, 5, -2.5, 2.5);
  TH2F * histoRecoDelta_yVsTTPt = new TH2F("RecoDelta_yVsTTPt", "RecoDelta_yVsTTPt", 10, -2, 2, 5, 0, 250);
  TH2F * histoRecoDelta_yVsTTMass = new TH2F("RecoDelta_yVsTTMass", "RecoDelta_yVsTTMass", 10, -2, 2, 5, 0, 1000);
  TH1F * histoRecoN_plusTTRapidity = new TH1F("RecoN_plusTTRapidity", "RecoN_plusTTRapidity", 20, -2.5, 2.5);
  histoRecoN_plusTTRapidity->Sumw2();
  TH1F * histoRecoN_plusTTPt = new TH1F("RecoN_plusTTPt", "RecoN_plusTTPt", 20, 0, 250);
  histoRecoN_plusTTPt->Sumw2();
  TH1F * histoRecoN_plusTTMass = new TH1F("RecoN_plusTTMass", "RecoN_plusTTMass", 20, 0, 1000);
  histoRecoN_plusTTMass->Sumw2();
  TH1F * histoRecoN_minusTTRapidity = new TH1F("RecoN_minusTTRapidity", "RecoN_minusTTRapidity", 20, -2.5, 2.5);
  histoRecoN_minusTTRapidity->Sumw2();
  TH1F * histoRecoN_minusTTPt = new TH1F("RecoN_minusTTPt", "RecoN_minusTTPt", 20, 0, 250);
  histoRecoN_minusTTPt->Sumw2();
  TH1F * histoRecoN_minusTTMass = new TH1F("RecoN_minusTTMass", "RecoN_minusTTMass", 20, 0, 1000);
  histoRecoN_minusTTMass->Sumw2();
  TH1F * histoRecoN_plusMinusN_minusTTRapidity = new TH1F("RecoN_plusMinusN_minusTTRapidity", "RecoN_plusMinusN_minusTTRapidity", 20, -2.5, 2.5);
  histoRecoN_plusMinusN_minusTTRapidity->Sumw2();
  TH1F * histoRecoN_plusPlusN_minusTTRapidity = new TH1F("RecoN_plusPlusN_minusTTRapidity", "RecoN_plusPlusN_minusTTRapidity", 20, -2.5, 2.5);
  histoRecoN_plusPlusN_minusTTRapidity->Sumw2();
  TH1F * histoRecoN_plusMinusN_minusTTPt = new TH1F("RecoN_plusMinusN_minusTTPt", "RecoN_plusMinusN_minusTTPt", 20, 0, 250);
  histoRecoN_plusMinusN_minusTTPt->Sumw2();
  TH1F * histoRecoN_plusPlusN_minusTTPt = new TH1F("RecoN_plusPlusN_minusTTPt", "RecoN_plusPlusN_minusTTPt", 20, 0, 250);
  histoRecoN_plusPlusN_minusTTPt->Sumw2();
  TH1F * histoRecoN_plusMinusN_minusTTMass = new TH1F("RecoN_plusMinusN_minusTTMass", "RecoN_plusMinusN_minusTTMass", 20, 0, 1000);
  histoRecoN_plusMinusN_minusTTMass->Sumw2();
  TH1F * histoRecoN_plusPlusN_minusTTMass = new TH1F("RecoN_plusPlusN_minusTTMass", "RecoN_plusPlusN_minusTTMass", 20, 0, 1000);
  histoRecoN_plusPlusN_minusTTMass->Sumw2();
  TH1F * histoRecoA_cTTRapidity = new TH1F("RecoA_cTTRapidity", "RecoA_cTTRapidity", 20, -2.5, 2.5);
  histoRecoA_cTTRapidity->Sumw2();
  TH1F * histoRecoA_cTTPt = new TH1F("RecoA_cTTPt", "RecoA_cTTPt", 20, 0, 250);
  histoRecoA_cTTPt->Sumw2();
  TH1F * histoRecoA_cTTMass = new TH1F("RecoA_cTTMass", "RecoA_cTTMass", 20, 0, 1000);
  histoRecoA_cTTMass->Sumw2();
  // Fine binning
  TH2F * histoFineBinning_RecoDelta_yVsTTRapidity = new TH2F("FineBinning_RecoDelta_yVsTTRapidity", "FineBinning_RecoDelta_yVsTTRapidity", 200, -2, 2, 500, -2.5, 2.5);
  TH2F * histoFineBinning_RecoDelta_yVsTTPt = new TH2F("FineBinning_RecoDelta_yVsTTPt", "FineBinning_RecoDelta_yVsTTPt", 200, -2, 2, 250, 0, 250);
  TH2F * histoFineBinning_RecoDelta_yVsTTMass = new TH2F("FineBinning_RecoDelta_yVsTTMass", "FineBinning_RecoDelta_yVsTTMass", 200, -2, 2, 100, 0, 1000);
  TH1F * histoFineBinning_RecoN_plusTTRapidity = new TH1F("FineBinning_RecoN_plusTTRapidity", "FineBinning_RecoN_plusTTRapidity", 500, -2.5, 2.5);
  histoFineBinning_RecoN_plusTTRapidity->Sumw2();
  TH1F * histoFineBinning_RecoN_plusTTPt = new TH1F("FineBinning_RecoN_plusTTPt", "FineBinning_RecoN_plusTTPt", 250, 0, 250);
  histoFineBinning_RecoN_plusTTPt->Sumw2();
  TH1F * histoFineBinning_RecoN_plusTTMass = new TH1F("FineBinning_RecoN_plusTTMass", "FineBinning_RecoN_plusTTMass", 100, 0, 1000);
  histoFineBinning_RecoN_plusTTMass->Sumw2();
  TH1F * histoFineBinning_RecoN_minusTTRapidity = new TH1F("FineBinning_RecoN_minusTTRapidity", "FineBinning_RecoN_minusTTRapidity", 500, -2.5, 2.5);
  histoFineBinning_RecoN_minusTTRapidity->Sumw2();
  TH1F * histoFineBinning_RecoN_minusTTPt = new TH1F("FineBinning_RecoN_minusTTPt", "FineBinning_RecoN_minusTTPt", 250, 0, 250);
  histoFineBinning_RecoN_minusTTPt->Sumw2();
  TH1F * histoFineBinning_RecoN_minusTTMass = new TH1F("FineBinning_RecoN_minusTTMass", "FineBinning_RecoN_minusTTMass", 100, 0, 1000);
  histoFineBinning_RecoN_minusTTMass->Sumw2();
  TH1F * histoFineBinning_RecoN_plusMinusN_minusTTRapidity = new TH1F("FineBinning_RecoN_plusMinusN_minusTTRapidity", "FineBinning_RecoN_plusMinusN_minusTTRapidity", 500, -2.5, 2.5);
  histoFineBinning_RecoN_plusMinusN_minusTTRapidity->Sumw2();  
  TH1F * histoFineBinning_RecoN_plusPlusN_minusTTRapidity = new TH1F("FineBinning_RecoN_plusPlusN_minusTTRapidity", "FineBinning_RecoN_plusPlusN_minusTTRapidity", 500, -2.5, 2.5);
  histoFineBinning_RecoN_plusPlusN_minusTTRapidity->Sumw2();
  TH1F * histoFineBinning_RecoN_plusMinusN_minusTTPt = new TH1F("FineBinning_RecoN_plusMinusN_minusTTPt", "FineBinning_RecoN_plusMinusN_minusTTPt", 250, 0, 250);
  histoFineBinning_RecoN_plusMinusN_minusTTPt->Sumw2();
  TH1F * histoFineBinning_RecoN_plusPlusN_minusTTPt = new TH1F("FineBinning_RecoN_plusPlusN_minusTTPt", "FineBinning_RecoN_plusPlusN_minusTTPt", 250, 0, 250);
  histoFineBinning_RecoN_plusPlusN_minusTTPt->Sumw2();
  TH1F * histoFineBinning_RecoN_plusMinusN_minusTTMass = new TH1F("FineBinning_RecoN_plusMinusN_minusTTMass", "FineBinning_RecoN_plusMinusN_minusTTMass", 100, 0, 1000);
  histoFineBinning_RecoN_plusMinusN_minusTTMass->Sumw2();
  TH1F * histoFineBinning_RecoN_plusPlusN_minusTTMass = new TH1F("FineBinning_RecoN_plusPlusN_minusTTMass", "FineBinning_RecoN_plusPlusN_minusTTMass", 100, 0, 1000);
  histoFineBinning_RecoN_plusPlusN_minusTTMass->Sumw2();
  TH1F * histoFineBinning_RecoA_cTTRapidity = new TH1F("FineBinning_RecoA_cTTRapidity", "FineBinning_RecoA_cTTRapidity", 500, -2.5, 2.5);
  histoFineBinning_RecoA_cTTRapidity->Sumw2();
  TH1F * histoFineBinning_RecoA_cTTPt = new TH1F("FineBinning_RecoA_cTTPt", "FineBinning_RecoA_cTTPt", 250, 0, 250);
  histoFineBinning_RecoA_cTTPt->Sumw2();
  TH1F * histoFineBinning_RecoA_cTTMass = new TH1F("FineBinning_RecoA_cTTMass", "FineBinning_RecoA_cTTMass", 100, 0, 1000);
  histoFineBinning_RecoA_cTTMass->Sumw2();




  // RECO vs GEN
  TH2F * histoRecoVsGenTopRapidity1 = new TH2F("RecoVsGenTopRapidity1", "RecoVsGenTopRapidity1", 100, -5, 5, 100, -5, 5);
  TH2F * histoRecoVsGenTopRapidity2 = new TH2F("RecoVsGenTopRapidity2", "RecoVsGenTopRapidity2", 100, -5, 5, 100, -5, 5);
  TH2F * histoRecoVsGenTopMass1 = new TH2F("RecoVsGenTopMass1", "RecoVsGenTopMass1", 300, 0, 300, 200, 0, 200);
  TH2F * histoRecoVsGenTopMass2 = new TH2F("RecoVsGenTopMass2", "RecoVsGenTopMass2", 300, 0, 300, 200, 0, 200);
  TH1F * histoRecoMinusGenDivGenTopRapidity1 = new TH1F("RecoMinusGenDivGenTopRapidity1", "RecoMinusGenDivGenTopRapidity1", 100, -3, 3);
  TH1F * histoRecoMinusGenDivGenTopRapidity2 = new TH1F("RecoMinusGenDivGenTopRapidity2", "RecoMinusGenDivGenTopRapidity2", 100, -3, 3);
  TH1F * histoRecoMinusGenDivGenLeptonRapidity1 = new TH1F("RecoMinusGenDivGenLeptonRapidity1", "RecoMinusGenDivGenLeptonRapidity1", 100, -3, 3);
  TH1F * histoRecoMinusGenDivGenLeptonRapidity2 = new TH1F("RecoMinusGenDivGenLeptonRapidity2", "RecoMinusGenDivGenLeptonRapidity2", 100, -3, 3);
  TH1F * histoRecoMinusGenDivGenTopMass1 = new TH1F("RecoMinusGenDivGenTopMass1", "RecoMinusGenDivGenTopMass1", 100, -3, 3);
  TH1F * histoRecoMinusGenDivGenTopMass2 = new TH1F("RecoMinusGenDivGenTopMass2", "RecoMinusGenDivGenTopMass2", 100, -3, 3);

  TH2F * histoFineBinning_RecoVsGenDelta_y = new TH2F("FineBinning_RecoVsGenDelta_y", "FineBinning_RecoVsGenDelta_y", 400, -2, 2, 400, -2, 2); // Migration Matrix
  TH2F * histoRecoVsGenDelta_y = new TH2F("RecoVsGenDelta_y", "RecoVsGenDelta_y", 8, -2, 2, 16, -2, 2); // Migration Matrix
  TH1F * histoRecoMinusGenDivGenDelta_y = new TH1F("RecoMinusGenDivGenDelta_y", "RecoMinusGenDivGenDelta_y", 100, -3, 3);

  TH2F * histoRecoVsGenTTRapidity = new TH2F("RecoVsGenTTRapidity", "RecoVsGenTTRapidity", 500, -2.5, 2.5, 500, -2.5, 2.5);
  TH1F * histoRecoMinusGenDivGenTTRapidity = new TH1F("RecoMinusGenDivGenTTRapidity", "RecoMinusGenDivGenTTRapidity", 100, -3, 3);
  TH2F * histoRecoVsGenTTPt = new TH2F("RecoVsGenTTPt", "RecoVsGenTTPt", 250, 0, 250, 250, 0, 250);
  TH1F * histoRecoMinusGenDivGenTTPt = new TH1F("RecoMinusGenDivGenTTPt", "RecoMinusGenDivGenTTPt", 100, -3, 3);
  TH2F * histoRecoVsGenTTMass = new TH2F("RecoVsGenTTMass", "RecoVsGenTTMass", 100, 0, 1000, 100, 0, 1000);
  TH1F * histoRecoMinusGenDivGenTTMass = new TH1F("RecoMinusGenDivGenTTMass", "RecoMinusGenDivGenTTMass", 100, -3, 3);

  TH1F * histoDelta_yEfficiencyN = new TH1F("Delta_yEfficiencyN", "Delta_yEfficiencyN", 10, -2, 2);
  TH1F * histoDelta_yEfficiencyD = new TH1F("Delta_yEfficiencyD", "Delta_yEfficiencyD", 10, -2, 2);
  TH1F * histoDelta_yEfficiency = new TH1F("Delta_yEfficiency", "Delta_yEfficiency", 10, -2, 2);

  TH2F * histoDelta_yVsTTRapidityEfficiency = new TH2F("Delta_yVsTTRapidityEfficiency", "Delta_yVsTTRapidityEfficiency", 10, -2, 2, 5, -2.5, 2.5);
  TH2F * histoDelta_yVsTTPtEfficiency = new TH2F("Delta_yVsTTPtEfficiency", "Delta_yVsTTPtEfficiency", 10, -2, 2, 5, 0, 250);
  TH2F * histoDelta_yVsTTMassEfficiency = new TH2F("Delta_yVsTTMassEfficiency", "Delta_yVsTTMassEfficiency", 10, -2, 2, 5, 0, 1000);
  // Fine binning
  TH1F * histoFineBinning_Delta_yEfficiencyN = new TH1F("FineBinning_Delta_yEfficiencyN", "FineBinning_Delta_yEfficiencyN", 200, -2, 2);
  TH1F * histoFineBinning_Delta_yEfficiencyD = new TH1F("FineBinning_Delta_yEfficiencyD", "FineBinning_Delta_yEfficiencyD", 200, -2, 2);
  TH1F * histoFineBinning_Delta_yEfficiency = new TH1F("FineBinning_Delta_yEfficiency", "FineBinning_Delta_yEfficiency", 200, -2, 2);

  TH2F * histoFineBinning_Delta_yVsTTRapidityEfficiency = new TH2F("FineBinning_Delta_yVsTTRapidityEfficiency", "FineBinning_Delta_yVsTTRapidityEfficiency", 200, -2, 2, 500, -2.5, 2.5);
  TH2F * histoFineBinning_Delta_yVsTTPtEfficiency = new TH2F("FineBinning_Delta_yVsTTPtEfficiency", "FineBinning_Delta_yVsTTPtEfficiency", 200, -2, 2, 250, 0, 250);
  TH2F * histoFineBinning_Delta_yVsTTMassEfficiency = new TH2F("FineBinning_Delta_yVsTTMassEfficiency", "FineBinning_Delta_yVsTTMassEfficiency", 200, -2, 2, 100, 0, 1000);




  vector < Dataset > datasets;
  DiLeptonSelection sel;
  float Luminosity = 0;
  // 0: MC - 1: Data - 2 Data & MC
  int DataType = 0;
  int verbosity = -1;
  
  // Analysis variables
  int step;
  //4-vectors
  vector < TLorentzVector > nu1;
  vector < TLorentzVector > nu2;
  //  TLorentzVector lvTop1_aux;
  //TLorentzVector lvTop2_aux;

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

  //////////////////////
  // Initialisation
  //////////////////////
  AnalysisEnvironmentLoader anaEL (xmlFileName);
  anaEL.LoadSamples (datasets); // now the list of datasets written in the xml file is known
  anaEL.LoadDiLeptonSelection (sel); // now the parameters for the selection are given to the selection
  anaEL.LoadGeneralInfo(DataType, Luminosity, verbosity );

  float weight_MC; 
  int nEvents;
  int firstEvent;
  int initialEvents;
  anaEL.LoadAnalysisInfo("Run", "firstEvent", firstEvent);
  anaEL.LoadAnalysisInfo("Run", "nEvents", nEvents);
  anaEL.LoadAnalysisInfo("Run", "initialEvents", initialEvents);
  string channelName;
  anaEL.LoadAnalysisInfo("MassAnalysis", "ChannelName", channelName);

  anaEL.LoadWeight (sel); // now the parameters for SFBweight are initialized (for b-tag!)

  //******************************************
  //Load Scale Factors for lepton efficiencies
  //******************************************
  sel.LoadElScaleFactors();
  sel.LoadMuScaleFactors();
  sel.InitJESUnc();

  bool nonskimmed = true;

  TopTree::NTEvent * event = 0;

  TFile * TupleFile = new TFile("TupleFileNonSkimmed_TTbarSignalPowheg.root","RECREATE");
  float mttbar_rec, mttbar_gen;
  float diffysquare_rec, diffysquare_gen;
  float diffabseta_rec, diffabseta_gen;
  float weight;
  float pt_ttbar, pt_ttbar_gen;
  float pz_ttbar, pz_ttbar_gen;
  float eta_ttbar_rec, eta_ttbar_gen;
  float y_ttbar_rec, y_ttbar_gen;
  float diffabsy_rec, diffabsy_gen;

  TTree *tree = new TTree("Tuple","Tuple");
  tree->Branch("mttbar_rec",&mttbar_rec,"mttbar_rec/F");
  tree->Branch("mttbar_gen",&mttbar_gen,"mttbar_gen/F");
  tree->Branch("diffysquare_rec",&diffysquare_rec,"diffysquare_rec/F");
  tree->Branch("diffysquare_gen",&diffysquare_gen,"diffysquare_gen/F");
  tree->Branch("diffabseta_rec",&diffabseta_rec,"diffabseta_rec/F");
  tree->Branch("diffabseta_gen",&diffabseta_gen,"diffabseta_gen/F");
  tree->Branch("weight",&weight,"weight/F");
  tree->Branch("pt_ttbar",&pt_ttbar,"pt_ttbar/F");
  tree->Branch("pt_ttbar_gen",&pt_ttbar_gen,"pt_ttbar_gen/F");
  tree->Branch("pz_ttbar",&pz_ttbar,"pz_ttbar/F");
  tree->Branch("pz_ttbar_gen",&pz_ttbar_gen,"pz_ttbar_gen/F");
  tree->Branch("eta_ttbar_rec",&eta_ttbar_rec,"eta_ttbar_rec/F");
  tree->Branch("eta_ttbar_gen",&eta_ttbar_gen,"eta_ttbar_gen/F");
  tree->Branch("y_ttbar_rec",&y_ttbar_rec,"y_ttbar_rec/F");
  tree->Branch("y_ttbar_gen",&y_ttbar_gen,"y_ttbar_gen/F");
  tree->Branch("diffabsy_rec",&diffabsy_rec,"diffabsy_rec/F");
  tree->Branch("diffabsy_gen",&diffabsy_gen,"diffabsy_gen/F");

  //////////////////////
  //LOOP OVER THE DATASETS
  //////////////////////
  if(verbosity>0) {
    cout<<"#########################"<<endl;
    cout<<" Loop over the datasets  "<<endl;
    cout<<"#########################"<<endl;
  }

  float num_mttbar_eff = 0.;
  float den_mttbar_eff = 0.;

  for (unsigned int d = 0; d < datasets.size (); d++) {

    weight_MC = datasets[d].NormFactor()*Luminosity;

    if(datasets[d].isData() == true) weight_MC = 1.; cout << "isDATA" << endl;

    AMWT amwt(anaEL, datasets[d].isData());

    TString sample_name(datasets[d].Name());


    bool isData = datasets[d].isData ();
    datasets[d].eventTree ()->SetBranchAddress ("NTEvent",&event);

    cout << "Sample : " << sample_name<< endl;
    cout << "Data   : " << isData<< endl;

    unsigned int nEventsSample = (int) (datasets[d].eventTree ()->GetEntries ());
    unsigned int endEventToRun;

    if (firstEvent>nEventsSample) firstEvent = nEventsSample;
    if ((nEvents==-1)||((nEvents+firstEvent)>nEventsSample)) endEventToRun = nEventsSample;
    else endEventToRun = nEvents+firstEvent;
    cout << "Events to run: number / first / last / all: " << endEventToRun-firstEvent 
         << " / " << firstEvent << " / " << endEventToRun
         << " / " << nEventsSample << endl;

// Standard parameters for doFullSelection:

    bool applyEEScale = false; float EEScaleParam = 1.; bool applyEEResol = false; float EEResolParam = 1.;
    bool applyMEScale = false; float MEScaleParam = 1.; bool applyMEResol = false; float MEResolParam = 1.;
    bool applyMETS = false; float METScale = 1.;
    bool applyJES = false; float JESParam = 1.;
    bool applyJER = false; float JERFactor = 0.; 

    //////////////////////
    //LOOP OVER THE EVENTS
    //////////////////////

    float N_plus_reco = 0;
    float N_minus_reco = 0;

    float N_plus_gen = 0;
    float N_minus_gen = 0;

    mttbar_rec = 0;
    mttbar_gen = 0;
    diffysquare_rec = 0;
    diffysquare_gen = 0;
    diffabseta_rec = 0;
    diffabseta_gen = 0;
    weight = weight_MC;
    pt_ttbar = 0;
    pt_ttbar_gen = 0;
    pz_ttbar = 0;
    pz_ttbar_gen = 0;
    eta_ttbar_rec = 0;
    eta_ttbar_gen = 0;
    y_ttbar_rec = 0;
    y_ttbar_gen = 0;
    diffabsy_rec = 0;
    diffabsy_gen = 0;

    for (unsigned int ievt = firstEvent; ievt < endEventToRun; ievt++) {
//           for (unsigned int ievt = 0; ievt < 10; ievt++) {

      datasets[d].eventTree ()->GetEntry (ievt);

      if(ievt%1000 == 0) cout << "number of processed events " << ievt << endl;
      if (verbosity >= 1) cout << "Event : "<< event->runNb<<" , " << event->lumiblock <<" , " << event->eventNb<<endl;

      if(!(event->TMEME == 2  || event->TMEME == 10101 || event->TMEME == 20200 || event->TMEME == 20 || event->TMEME == 11010 ||
event->TMEME == 22000|| event->TMEME == 11 || event->TMEME == 11001 || event->TMEME == 10110 || event->TMEME == 21100 )) continue;

      string candType;
      vector<NTElectron> candElec;
      vector<NTMuon> candMuon;


      //Load event for the selection
      sel.LoadEvent(event);

      int finalCut = sel.doFullSelection(&(datasets[d]), channelName, false, /*print*/ verbosity,
	false, false, -1., -1., applyJES,  JESParam,
	 applyEEScale,  EEScaleParam,  applyEEResol,  EEResolParam,
	 applyMEScale,  MEScaleParam,  
	 applyJER,  JERFactor,  applyMETS,  METScale);




        TLorentzVector lvTop1_gen;
        TLorentzVector lvTop2_gen;
        TLorentzVector lvTop1plusTop2_gen;
        float yt_gen = 0.;
        float ytbar_gen = 0.;
        float Delta_y_gen = 0.;

        if(datasets[d].Name() == "TTJets_Sig"){


        lvTop1_gen = (event->topAndDecays)[0].p4_t_gen;
        lvTop2_gen = (event->topAndDecays)[1].p4_t_gen;
        lvTop1plusTop2_gen = lvTop1_gen + lvTop2_gen;

        /////////////////////////
        //// GENERATOR LEVEL ////
        /////////////////////////

        histoGenTopRapidity1->Fill(lvTop1_gen.Rapidity());
        histoGenTopRapidity2->Fill(lvTop2_gen.Rapidity());
        histoGenTopMass1->Fill(lvTop1_gen.M());
        histoGenTopMass2->Fill(lvTop2_gen.M());
        histoGenTopMass1VsTopMass2->Fill(lvTop1_gen.M(),lvTop2_gen.M());

        yt_gen = lvTop1_gen.Rapidity();
        if(yt_gen<0.) yt_gen = (-1)*yt_gen;
        ytbar_gen = lvTop2_gen.Rapidity();
        if(ytbar_gen<0.) ytbar_gen = (-1)*ytbar_gen;
        Delta_y_gen = yt_gen - ytbar_gen;
	//        cout << "Delta_y_gen:" << Delta_y_gen << endl;
        histoGenDelta_y->Fill(Delta_y_gen);
        histoDelta_yEfficiencyD->Fill(Delta_y_gen);
        histoFineBinning_Delta_yEfficiencyD->Fill(Delta_y_gen);

        if(Delta_y_gen>0.){
          N_plus_gen++;
          histoGenN_plusTTRapidity->Fill(lvTop1plusTop2_gen.Rapidity());
          histoGenN_plusTTPt->Fill(lvTop1plusTop2_gen.Perp());
          histoGenN_plusTTMass->Fill(lvTop1plusTop2_gen.M());
          histoFineBinning_GenN_plusTTRapidity->Fill(lvTop1plusTop2_gen.Rapidity());
          histoFineBinning_GenN_plusTTPt->Fill(lvTop1plusTop2_gen.Perp());
          histoFineBinning_GenN_plusTTMass->Fill(lvTop1plusTop2_gen.M());
	}

        if(Delta_y_gen<0.){
          N_minus_gen++;
          histoGenN_minusTTRapidity->Fill(lvTop1plusTop2_gen.Rapidity());
          histoGenN_minusTTPt->Fill(lvTop1plusTop2_gen.Perp());
          histoGenN_minusTTMass->Fill(lvTop1plusTop2_gen.M());
          histoFineBinning_GenN_minusTTRapidity->Fill(lvTop1plusTop2_gen.Rapidity());
          histoFineBinning_GenN_minusTTPt->Fill(lvTop1plusTop2_gen.Perp());
          histoFineBinning_GenN_minusTTMass->Fill(lvTop1plusTop2_gen.M());

	}

        histoGenTTRapidity->Fill(lvTop1plusTop2_gen.Rapidity());
        histoGenTTPt->Fill(lvTop1plusTop2_gen.Perp());
        histoGenTTMass->Fill(lvTop1plusTop2_gen.M());
        histoGenDelta_yVsTTRapidity->Fill(Delta_y_gen, lvTop1plusTop2_gen.Rapidity());
        histoGenDelta_yVsTTPt->Fill(Delta_y_gen, lvTop1plusTop2_gen.Perp());
        histoGenDelta_yVsTTMass->Fill(Delta_y_gen, lvTop1plusTop2_gen.M());

        histoFineBinning_GenDelta_yVsTTRapidity->Fill(Delta_y_gen, lvTop1plusTop2_gen.Rapidity());
        histoFineBinning_GenDelta_yVsTTPt->Fill(Delta_y_gen, lvTop1plusTop2_gen.Perp());
        histoFineBinning_GenDelta_yVsTTMass->Fill(Delta_y_gen, lvTop1plusTop2_gen.M());


        if(nonskimmed == true){
         mttbar_gen = lvTop1plusTop2_gen.M();
         diffysquare_gen = yt_gen*yt_gen - ytbar_gen*ytbar_gen;
         diffabseta_gen = fabs(lvTop1_gen.Eta()) - fabs(lvTop2_gen.Eta());
         pt_ttbar_gen = lvTop1plusTop2_gen.Perp();
         pz_ttbar_gen = lvTop1plusTop2_gen.Pz();
         eta_ttbar_gen = lvTop1plusTop2_gen.Eta();
         y_ttbar_gen = lvTop1plusTop2_gen.Rapidity();
         diffabsy_gen = fabs(lvTop1_gen.Rapidity()) - fabs(lvTop2_gen.Rapidity());
	}

	}

      if (finalCut >6) {

        if(nonskimmed == false){
         if(datasets[d].Name() == "TTJets_Sig"){
         mttbar_gen = lvTop1plusTop2_gen.M();
         diffysquare_gen = yt_gen*yt_gen - ytbar_gen*ytbar_gen;
         diffabseta_gen = fabs(lvTop1_gen.Eta()) - fabs(lvTop2_gen.Eta());
         pt_ttbar_gen = lvTop1plusTop2_gen.Perp();
         pz_ttbar_gen = lvTop1plusTop2_gen.Pz();
         eta_ttbar_gen = lvTop1plusTop2_gen.Eta();
         y_ttbar_gen = lvTop1plusTop2_gen.Rapidity();
         diffabsy_gen = fabs(lvTop1_gen.Rapidity()) - fabs(lvTop2_gen.Rapidity());
	 }
	}

        sel.GetLeptonPair(candMuon, candElec, candType);

        for(unsigned int i=0; i<candMuon.size(); i++){
          if(candMuon[i].Charge == +1) histoRecoLeptonRapidity1->Fill(candMuon[i].p4.Rapidity());
          if(candMuon[i].Charge == -1) histoRecoLeptonRapidity2->Fill(candMuon[i].p4.Rapidity());
	}

        for(unsigned int j=0; j<candElec.size(); j++){
          if(candElec[j].Charge == +1) histoRecoLeptonRapidity1->Fill(candElec[j].p4.Rapidity());
          if(candElec[j].Charge == -1) histoRecoLeptonRapidity2->Fill(candElec[j].p4.Rapidity());
	}



        TLorentzVector lvTop1_reco;
        TLorentzVector lvTop2_reco;
        TLorentzVector lvTop1plusTop2_reco;


        TopMassVariables * tmv = amwt.findMass(sel, lvTop1_reco, lvTop2_reco);
        lvTop1plusTop2_reco = lvTop1_reco + lvTop2_reco;



        ////////////////////
        /// RECO LEVEL /////
        ////////////////////

        histoRecoTopRapidity1->Fill(lvTop1_reco.Rapidity());
        histoRecoTopRapidity2->Fill(lvTop2_reco.Rapidity());
        histoRecoTopMass1->Fill(lvTop1_reco.M());
        histoRecoTopMass2->Fill(lvTop2_reco.M());
        histoRecoTopMass1VsTopMass2->Fill(lvTop1_reco.M(),lvTop2_reco.M());

        float yt_reco = lvTop1_reco.Rapidity();
        if(yt_reco<0.) yt_reco = (-1)*yt_reco;
        float ytbar_reco = lvTop2_reco.Rapidity();
        if(ytbar_reco<0.) ytbar_reco = (-1)*ytbar_reco;
        float Delta_y_reco = yt_reco - ytbar_reco;
	//        cout << "Delta_y_reco:" << Delta_y_reco << endl;
        histoRecoDelta_y->Fill(Delta_y_reco);
        histoDelta_yEfficiencyN->Fill(Delta_y_reco);
        histoFineBinning_Delta_yEfficiencyN->Fill(Delta_y_reco);

        if(Delta_y_reco>0.){
          N_plus_reco++;
          histoRecoN_plusTTRapidity->Fill(lvTop1plusTop2_reco.Rapidity());
          histoRecoN_plusTTPt->Fill(lvTop1plusTop2_reco.Perp());
          histoRecoN_plusTTMass->Fill(lvTop1plusTop2_reco.M());
          histoFineBinning_RecoN_plusTTRapidity->Fill(lvTop1plusTop2_reco.Rapidity());
          histoFineBinning_RecoN_plusTTPt->Fill(lvTop1plusTop2_reco.Perp());
          histoFineBinning_RecoN_plusTTMass->Fill(lvTop1plusTop2_reco.M());
	}

        if(Delta_y_reco<0.){
          N_minus_reco++;
          histoRecoN_minusTTRapidity->Fill(lvTop1plusTop2_reco.Rapidity());
          histoRecoN_minusTTPt->Fill(lvTop1plusTop2_reco.Perp());
          histoRecoN_minusTTMass->Fill(lvTop1plusTop2_reco.M());
          histoFineBinning_RecoN_minusTTRapidity->Fill(lvTop1plusTop2_reco.Rapidity());
          histoFineBinning_RecoN_minusTTPt->Fill(lvTop1plusTop2_reco.Perp());
          histoFineBinning_RecoN_minusTTMass->Fill(lvTop1plusTop2_reco.M());
	}

        histoRecoTTRapidity->Fill(lvTop1plusTop2_reco.Rapidity());
        histoRecoTTPt->Fill(lvTop1plusTop2_reco.Perp());
        histoRecoTTMass->Fill(lvTop1plusTop2_reco.M());
        histoRecoDelta_yVsTTRapidity->Fill(Delta_y_reco, lvTop1plusTop2_reco.Rapidity());
        histoRecoDelta_yVsTTPt->Fill(Delta_y_reco, lvTop1plusTop2_reco.Perp());
        histoRecoDelta_yVsTTMass->Fill(Delta_y_reco, lvTop1plusTop2_reco.M());

        histoFineBinning_RecoDelta_yVsTTRapidity->Fill(Delta_y_reco, lvTop1plusTop2_reco.Rapidity());
        histoFineBinning_RecoDelta_yVsTTPt->Fill(Delta_y_reco, lvTop1plusTop2_reco.Perp());
        histoFineBinning_RecoDelta_yVsTTMass->Fill(Delta_y_reco, lvTop1plusTop2_reco.M());

        if(nonskimmed == false){

         mttbar_rec = lvTop1plusTop2_reco.M();
         diffysquare_rec = yt_reco*yt_reco - ytbar_reco*ytbar_reco;
         diffabseta_rec = fabs(lvTop1_reco.Eta()) - fabs(lvTop2_reco.Eta());
         pt_ttbar = lvTop1plusTop2_reco.Perp();
         pz_ttbar = lvTop1plusTop2_reco.Pz();
         eta_ttbar_rec = lvTop1plusTop2_reco.Eta();
         y_ttbar_rec = lvTop1plusTop2_reco.Rapidity();
         diffabsy_rec = fabs(lvTop1_reco.Rapidity()) - fabs(lvTop2_reco.Rapidity());

	}

        ////////////////////////
        // RECO VS GEN LEVEL ///
        ////////////////////////
        if(datasets[d].Name() == "TTJets_Sig"){
 
        histoRecoVsGenTopRapidity1->Fill(lvTop1_reco.Rapidity(), lvTop1_gen.Rapidity());
        histoRecoVsGenTopRapidity2->Fill(lvTop2_reco.Rapidity(), lvTop2_gen.Rapidity());
        histoRecoVsGenTopMass1->Fill(lvTop1_reco.M(), lvTop1_gen.M());
        histoRecoVsGenTopMass2->Fill(lvTop2_reco.M(), lvTop2_gen.M());
	histoRecoMinusGenDivGenTopRapidity1->Fill((lvTop1_reco.Rapidity() - lvTop1_gen.Rapidity())/lvTop1_gen.Rapidity());
        histoRecoMinusGenDivGenTopRapidity2->Fill((lvTop2_reco.Rapidity() - lvTop2_gen.Rapidity())/lvTop2_gen.Rapidity());

        for(unsigned int i=0; i<candMuon.size(); i++){
          if(candMuon[i].Charge == +1) histoRecoMinusGenDivGenLeptonRapidity1->Fill((candMuon[i].p4.Rapidity() - lvTop1_gen.Rapidity())/lvTop1_gen.Rapidity());
          if(candMuon[i].Charge == -1) histoRecoMinusGenDivGenLeptonRapidity2->Fill((candMuon[i].p4.Rapidity() - lvTop2_gen.Rapidity())/lvTop2_gen.Rapidity());
	}

        for(unsigned int j=0; j<candElec.size(); j++){
          if(candElec[j].Charge == +1) histoRecoMinusGenDivGenLeptonRapidity1->Fill((candElec[j].p4.Rapidity() - lvTop1_gen.Rapidity())/lvTop1_gen.Rapidity());
          if(candElec[j].Charge == -1) histoRecoMinusGenDivGenLeptonRapidity2->Fill((candElec[j].p4.Rapidity() - lvTop2_gen.Rapidity())/lvTop2_gen.Rapidity());
	}

	histoRecoMinusGenDivGenTopMass1->Fill((lvTop1_reco.M() - lvTop1_gen.M())/lvTop1_gen.M());
        histoRecoMinusGenDivGenTopMass2->Fill((lvTop2_reco.M() - lvTop2_gen.M())/lvTop2_gen.M());

        histoRecoVsGenDelta_y->Fill(Delta_y_reco, Delta_y_gen);
        histoFineBinning_RecoVsGenDelta_y->Fill(Delta_y_reco, Delta_y_gen);
        histoRecoMinusGenDivGenDelta_y->Fill((Delta_y_reco - Delta_y_gen)/Delta_y_gen);

        histoRecoVsGenTTRapidity->Fill(lvTop1plusTop2_reco.Rapidity(),lvTop1plusTop2_gen.Rapidity());
        histoRecoMinusGenDivGenTTRapidity->Fill((lvTop1plusTop2_reco.Rapidity() - lvTop1plusTop2_gen.Rapidity())/lvTop1plusTop2_gen.Rapidity());
        histoRecoVsGenTTPt->Fill(lvTop1plusTop2_reco.Perp(),lvTop1plusTop2_gen.Perp());
        histoRecoMinusGenDivGenTTPt->Fill((lvTop1plusTop2_reco.Perp() - lvTop1plusTop2_gen.Perp())/lvTop1plusTop2_gen.Perp());
        histoRecoVsGenTTMass->Fill(lvTop1plusTop2_reco.M(),lvTop1plusTop2_gen.M());
        histoRecoMinusGenDivGenTTMass->Fill((lvTop1plusTop2_reco.M() - lvTop1plusTop2_gen.M())/lvTop1plusTop2_gen.M());

	}

	//	tmv->printAll();
	delete tmv;
       if(nonskimmed == false && mttbar_rec > 60.){ tree->Fill(); num_mttbar_eff += weight_MC;}
       if(nonskimmed == false) den_mttbar_eff += weight_MC;
      }

      if(nonskimmed == true) tree->Fill();

    }  // end of loop over evts

    float A_C_reco = (N_plus_reco - N_minus_reco)/(N_plus_reco + N_minus_reco);
    float A_C_gen = (N_plus_gen - N_minus_gen)/(N_plus_gen + N_minus_gen);

    cout << "A_C_gen:" << A_C_gen << endl;
    cout << "A_C_reco:" << A_C_reco << endl;

    histoGenN_plusMinusN_minusTTRapidity->Add(histoGenN_plusTTRapidity);
    histoGenN_plusMinusN_minusTTRapidity->Add(histoGenN_minusTTRapidity,-1);
    histoGenN_plusPlusN_minusTTRapidity->Add(histoGenN_plusTTRapidity);
    histoGenN_plusPlusN_minusTTRapidity->Add(histoGenN_minusTTRapidity);

    histoGenA_cTTRapidity->Divide(histoGenN_plusMinusN_minusTTRapidity, histoGenN_plusPlusN_minusTTRapidity);

    histoGenN_plusMinusN_minusTTPt->Add(histoGenN_plusTTPt);
    histoGenN_plusMinusN_minusTTPt->Add(histoGenN_minusTTPt,-1);
    histoGenN_plusPlusN_minusTTPt->Add(histoGenN_plusTTPt);
    histoGenN_plusPlusN_minusTTPt->Add(histoGenN_minusTTPt);

    histoGenA_cTTPt->Divide(histoGenN_plusMinusN_minusTTPt, histoGenN_plusPlusN_minusTTPt);

    histoGenN_plusMinusN_minusTTMass->Add(histoGenN_plusTTMass);
    histoGenN_plusMinusN_minusTTMass->Add(histoGenN_minusTTMass,-1);
    histoGenN_plusPlusN_minusTTMass->Add(histoGenN_plusTTMass);
    histoGenN_plusPlusN_minusTTMass->Add(histoGenN_minusTTMass);

    histoGenA_cTTMass->Divide(histoGenN_plusMinusN_minusTTMass, histoGenN_plusPlusN_minusTTMass);

    histoRecoN_plusMinusN_minusTTRapidity->Add(histoRecoN_plusTTRapidity);
    histoRecoN_plusMinusN_minusTTRapidity->Add(histoRecoN_minusTTRapidity,-1);
    histoRecoN_plusPlusN_minusTTRapidity->Add(histoRecoN_plusTTRapidity);
    histoRecoN_plusPlusN_minusTTRapidity->Add(histoRecoN_minusTTRapidity);

    histoRecoA_cTTRapidity->Divide(histoRecoN_plusMinusN_minusTTRapidity, histoRecoN_plusPlusN_minusTTRapidity);

    histoRecoN_plusMinusN_minusTTPt->Add(histoRecoN_plusTTPt);
    histoRecoN_plusMinusN_minusTTPt->Add(histoRecoN_minusTTPt,-1);
    histoRecoN_plusPlusN_minusTTPt->Add(histoRecoN_plusTTPt);
    histoRecoN_plusPlusN_minusTTPt->Add(histoRecoN_minusTTPt);

    histoRecoA_cTTPt->Divide(histoRecoN_plusMinusN_minusTTPt, histoRecoN_plusPlusN_minusTTPt);

    histoRecoN_plusMinusN_minusTTMass->Add(histoRecoN_plusTTMass);
    histoRecoN_plusMinusN_minusTTMass->Add(histoRecoN_minusTTMass,-1);
    histoRecoN_plusPlusN_minusTTMass->Add(histoRecoN_plusTTMass);
    histoRecoN_plusPlusN_minusTTMass->Add(histoRecoN_minusTTMass);

    histoRecoA_cTTMass->Divide(histoRecoN_plusMinusN_minusTTMass, histoRecoN_plusPlusN_minusTTMass);





    histoFineBinning_GenN_plusMinusN_minusTTRapidity->Add(histoFineBinning_GenN_plusTTRapidity);
    histoFineBinning_GenN_plusMinusN_minusTTRapidity->Add(histoFineBinning_GenN_minusTTRapidity,-1);
    histoFineBinning_GenN_plusPlusN_minusTTRapidity->Add(histoFineBinning_GenN_plusTTRapidity);
    histoFineBinning_GenN_plusPlusN_minusTTRapidity->Add(histoFineBinning_GenN_minusTTRapidity);

    histoFineBinning_GenA_cTTRapidity->Divide(histoFineBinning_GenN_plusMinusN_minusTTRapidity, histoFineBinning_GenN_plusPlusN_minusTTRapidity);

    histoFineBinning_GenN_plusMinusN_minusTTPt->Add(histoFineBinning_GenN_plusTTPt);
    histoFineBinning_GenN_plusMinusN_minusTTPt->Add(histoFineBinning_GenN_minusTTPt,-1);
    histoFineBinning_GenN_plusPlusN_minusTTPt->Add(histoFineBinning_GenN_plusTTPt);
    histoFineBinning_GenN_plusPlusN_minusTTPt->Add(histoFineBinning_GenN_minusTTPt);

    histoFineBinning_GenA_cTTPt->Divide(histoFineBinning_GenN_plusMinusN_minusTTPt, histoFineBinning_GenN_plusPlusN_minusTTPt);

    histoFineBinning_GenN_plusMinusN_minusTTMass->Add(histoFineBinning_GenN_plusTTMass);
    histoFineBinning_GenN_plusMinusN_minusTTMass->Add(histoFineBinning_GenN_minusTTMass,-1);
    histoFineBinning_GenN_plusPlusN_minusTTMass->Add(histoFineBinning_GenN_plusTTMass);
    histoFineBinning_GenN_plusPlusN_minusTTMass->Add(histoFineBinning_GenN_minusTTMass);

    histoFineBinning_GenA_cTTMass->Divide(histoFineBinning_GenN_plusMinusN_minusTTMass, histoFineBinning_GenN_plusPlusN_minusTTMass);

    histoFineBinning_RecoN_plusMinusN_minusTTRapidity->Add(histoFineBinning_RecoN_plusTTRapidity);
    histoFineBinning_RecoN_plusMinusN_minusTTRapidity->Add(histoFineBinning_RecoN_minusTTRapidity,-1);
    histoFineBinning_RecoN_plusPlusN_minusTTRapidity->Add(histoFineBinning_RecoN_plusTTRapidity);
    histoFineBinning_RecoN_plusPlusN_minusTTRapidity->Add(histoFineBinning_RecoN_minusTTRapidity);

    histoFineBinning_RecoA_cTTRapidity->Divide(histoFineBinning_RecoN_plusMinusN_minusTTRapidity, histoFineBinning_RecoN_plusPlusN_minusTTRapidity);

    histoFineBinning_RecoN_plusMinusN_minusTTPt->Add(histoFineBinning_RecoN_plusTTPt);
    histoFineBinning_RecoN_plusMinusN_minusTTPt->Add(histoFineBinning_RecoN_minusTTPt,-1);
    histoFineBinning_RecoN_plusPlusN_minusTTPt->Add(histoFineBinning_RecoN_plusTTPt);
    histoFineBinning_RecoN_plusPlusN_minusTTPt->Add(histoFineBinning_RecoN_minusTTPt);

    histoFineBinning_RecoA_cTTPt->Divide(histoFineBinning_RecoN_plusMinusN_minusTTPt, histoFineBinning_RecoN_plusPlusN_minusTTPt);

    histoFineBinning_RecoN_plusMinusN_minusTTMass->Add(histoFineBinning_RecoN_plusTTMass);
    histoFineBinning_RecoN_plusMinusN_minusTTMass->Add(histoFineBinning_RecoN_minusTTMass,-1);
    histoFineBinning_RecoN_plusPlusN_minusTTMass->Add(histoFineBinning_RecoN_plusTTMass);
    histoFineBinning_RecoN_plusPlusN_minusTTMass->Add(histoFineBinning_RecoN_minusTTMass);

    histoFineBinning_RecoA_cTTMass->Divide(histoFineBinning_RecoN_plusMinusN_minusTTMass, histoFineBinning_RecoN_plusPlusN_minusTTMass);



    histoDelta_yEfficiency->Divide(histoDelta_yEfficiencyN, histoDelta_yEfficiencyD);
    histoFineBinning_Delta_yEfficiency->Divide(histoFineBinning_Delta_yEfficiencyN, histoFineBinning_Delta_yEfficiencyD);


    for (unsigned int bin_index1 = 1; bin_index1 < 11; bin_index1++) {
     for (unsigned int bin_index2 = 1; bin_index2 < 6; bin_index2++) {
       float value = histoRecoDelta_yVsTTRapidity->GetBinContent(bin_index1,bin_index2)/histoGenDelta_yVsTTRapidity->GetBinContent(bin_index1,bin_index2);
       histoDelta_yVsTTRapidityEfficiency->SetBinContent(bin_index1, bin_index2, value);
       float value_fb = histoFineBinning_RecoDelta_yVsTTRapidity->GetBinContent(bin_index1,bin_index2)/histoFineBinning_GenDelta_yVsTTRapidity->GetBinContent(bin_index1,bin_index2);
       histoFineBinning_Delta_yVsTTRapidityEfficiency->SetBinContent(bin_index1, bin_index2, value_fb);

     }
    }

    for (unsigned int bin_index1 = 1; bin_index1 < 11; bin_index1++) {
     for (unsigned int bin_index2 = 1; bin_index2 < 6; bin_index2++) {
       float value = histoRecoDelta_yVsTTPt->GetBinContent(bin_index1,bin_index2)/histoGenDelta_yVsTTPt->GetBinContent(bin_index1,bin_index2);
       histoDelta_yVsTTPtEfficiency->SetBinContent(bin_index1, bin_index2, value);
       float value_fb = histoFineBinning_RecoDelta_yVsTTPt->GetBinContent(bin_index1,bin_index2)/histoFineBinning_GenDelta_yVsTTPt->GetBinContent(bin_index1,bin_index2);
       histoFineBinning_Delta_yVsTTPtEfficiency->SetBinContent(bin_index1, bin_index2, value_fb);

     }
    }


    for (unsigned int bin_index1 = 1; bin_index1 < 11; bin_index1++) {
     for (unsigned int bin_index2 = 1; bin_index2 < 6; bin_index2++) {
       float value = histoRecoDelta_yVsTTMass->GetBinContent(bin_index1,bin_index2)/histoGenDelta_yVsTTMass->GetBinContent(bin_index1,bin_index2);
       histoDelta_yVsTTMassEfficiency->SetBinContent(bin_index1, bin_index2, value);
       float value_fb = histoFineBinning_RecoDelta_yVsTTPt->GetBinContent(bin_index1,bin_index2)/histoFineBinning_GenDelta_yVsTTPt->GetBinContent(bin_index1,bin_index2);
       histoFineBinning_Delta_yVsTTPtEfficiency->SetBinContent(bin_index1, bin_index2, value_fb);

     }
    }






  }				// end of loop over the datasets


//  if(verbosity>0) {
    cout<<"#########################"<<endl;
    cout<<"    End of the program   "<<endl;
    cout<<"#########################"<<endl;
//  }

    tree->Print();

    TupleFile->Write();
    TupleFile->Close();


    TFile * fileCA = new TFile("ChargeAsymmetryResults_NonSkimmed_TTbarSignalPowheg.root","RECREATE");
    //  fileCA->cd();

    // GEN
    histoGenTopRapidity1->Write();
    histoGenTopRapidity2->Write();
    histoGenTopMass1->Write();
    histoGenTopMass2->Write();
    histoGenTopMass1VsTopMass2->Write();
    histoGenDelta_y->Write();
    histoGenTTRapidity->Write();
    histoGenTTPt->Write();
    histoGenTTMass->Write();
    histoGenDelta_yVsTTRapidity->Write();
    histoGenDelta_yVsTTPt->Write();
    histoGenDelta_yVsTTMass->Write();
    histoGenN_plusTTRapidity->Write();
    histoGenN_plusTTPt->Write();
    histoGenN_plusTTMass->Write();
    histoGenN_minusTTRapidity->Write();
    histoGenN_minusTTPt->Write();
    histoGenN_minusTTMass->Write();
    histoGenN_plusMinusN_minusTTRapidity->Write();
    histoGenN_plusPlusN_minusTTRapidity->Write();
    histoGenN_plusMinusN_minusTTPt->Write();
    histoGenN_plusPlusN_minusTTPt->Write();
    histoGenN_plusMinusN_minusTTMass->Write();
    histoGenN_plusPlusN_minusTTMass->Write();
    histoGenA_cTTRapidity->Write();
    histoGenA_cTTPt->Write();
    histoGenA_cTTMass->Write();
    histoFineBinning_GenDelta_yVsTTRapidity->Write();
    histoFineBinning_GenDelta_yVsTTPt->Write();
    histoFineBinning_GenDelta_yVsTTMass->Write();
    histoFineBinning_GenN_plusTTRapidity->Write();
    histoFineBinning_GenN_plusTTPt->Write();
    histoFineBinning_GenN_plusTTMass->Write();
    histoFineBinning_GenN_minusTTRapidity->Write();
    histoFineBinning_GenN_minusTTPt->Write();
    histoFineBinning_GenN_minusTTMass->Write();
    histoFineBinning_GenN_plusMinusN_minusTTRapidity->Write();
    histoFineBinning_GenN_plusPlusN_minusTTRapidity->Write();
    histoFineBinning_GenN_plusMinusN_minusTTPt->Write();
    histoFineBinning_GenN_plusPlusN_minusTTPt->Write();
    histoFineBinning_GenN_plusMinusN_minusTTMass->Write();
    histoFineBinning_GenN_plusPlusN_minusTTMass->Write();
    histoFineBinning_GenA_cTTRapidity->Write();
    histoFineBinning_GenA_cTTPt->Write();
    histoFineBinning_GenA_cTTMass->Write(); 



    // RECO
    histoRecoTopRapidity1->Write();
    histoRecoTopRapidity2->Write();
    histoRecoLeptonRapidity1->Write();
    histoRecoLeptonRapidity2->Write();
    histoRecoTopMass1->Write();
    histoRecoTopMass2->Write();
    histoRecoTopMass1VsTopMass2->Write();
    histoRecoDelta_y->Write();
    histoRecoTTRapidity->Write();
    histoRecoTTPt->Write();
    histoRecoTTMass->Write();
    histoRecoDelta_yVsTTRapidity->Write();
    histoRecoDelta_yVsTTPt->Write();
    histoRecoDelta_yVsTTMass->Write();
    histoRecoN_plusTTRapidity->Write();
    histoRecoN_plusTTPt->Write();
    histoRecoN_plusTTMass->Write();
    histoRecoN_minusTTRapidity->Write();
    histoRecoN_minusTTPt->Write();
    histoRecoN_minusTTMass->Write();
    histoRecoN_plusMinusN_minusTTRapidity->Write();
    histoRecoN_plusPlusN_minusTTRapidity->Write();
    histoRecoN_plusMinusN_minusTTPt->Write();
    histoRecoN_plusPlusN_minusTTPt->Write();
    histoRecoN_plusMinusN_minusTTMass->Write();
    histoRecoN_plusPlusN_minusTTMass->Write();
    histoRecoA_cTTRapidity->Write();
    histoRecoA_cTTPt->Write();
    histoRecoA_cTTMass->Write();
    histoFineBinning_RecoDelta_yVsTTRapidity->Write();
    histoFineBinning_RecoDelta_yVsTTPt->Write();
    histoFineBinning_RecoDelta_yVsTTMass->Write();
    histoFineBinning_RecoN_plusTTRapidity->Write();
    histoFineBinning_RecoN_plusTTPt->Write();
    histoFineBinning_RecoN_plusTTMass->Write();
    histoFineBinning_RecoN_minusTTRapidity->Write();
    histoFineBinning_RecoN_minusTTPt->Write();
    histoFineBinning_RecoN_minusTTMass->Write();
    histoFineBinning_RecoN_plusMinusN_minusTTRapidity->Write();
    histoFineBinning_RecoN_plusPlusN_minusTTRapidity->Write();
    histoFineBinning_RecoN_plusMinusN_minusTTPt->Write();
    histoFineBinning_RecoN_plusPlusN_minusTTPt->Write();
    histoFineBinning_RecoN_plusMinusN_minusTTMass->Write();
    histoFineBinning_RecoN_plusPlusN_minusTTMass->Write();
    histoFineBinning_RecoA_cTTRapidity->Write();
    histoFineBinning_RecoA_cTTPt->Write();
    histoFineBinning_RecoA_cTTMass->Write(); 

    // RECO vs GEN
    histoRecoVsGenTopRapidity1->Write();
    histoRecoVsGenTopRapidity2->Write();
    histoRecoMinusGenDivGenLeptonRapidity1->Write();
    histoRecoMinusGenDivGenLeptonRapidity2->Write();
    histoRecoMinusGenDivGenTopRapidity1->Write();
    histoRecoMinusGenDivGenTopRapidity2->Write();
    histoRecoVsGenTopMass1->Write();
    histoRecoVsGenTopMass2->Write();
    histoRecoMinusGenDivGenTopMass1->Write();
    histoRecoMinusGenDivGenTopMass2->Write();
    histoRecoVsGenDelta_y->Write();
    histoFineBinning_RecoVsGenDelta_y->Write();
    histoRecoMinusGenDivGenDelta_y->Write();
    histoRecoVsGenTTRapidity->Write();
    histoRecoMinusGenDivGenTTRapidity->Write();
    histoRecoVsGenTTPt->Write();
    histoRecoMinusGenDivGenTTPt->Write();
    histoRecoVsGenTTMass->Write();
    histoRecoMinusGenDivGenTTMass->Write();
    histoDelta_yEfficiencyN->Write();
    histoDelta_yEfficiencyD->Write();
    histoDelta_yEfficiency->Write();
    histoDelta_yVsTTRapidityEfficiency->Write();
    histoDelta_yVsTTPtEfficiency->Write();
    histoDelta_yVsTTMassEfficiency->Write();
    histoFineBinning_Delta_yEfficiencyN->Write();
    histoFineBinning_Delta_yEfficiencyD->Write();
    histoFineBinning_Delta_yEfficiency->Write();
    histoFineBinning_Delta_yVsTTRapidityEfficiency->Write();
    histoFineBinning_Delta_yVsTTPtEfficiency->Write();
    histoFineBinning_Delta_yVsTTMassEfficiency->Write();


    //    fileCA->Write();
    fileCA->Close();
    delete fileCA;

    cout << "num_mttbar_eff = " <<  num_mttbar_eff << endl;
    cout << "den_mttbar_eff = " <<  den_mttbar_eff << endl;
    cout << "mttbar_eff = " <<  num_mttbar_eff / den_mttbar_eff << endl;

  return (0);
}
Example #7
0
void DataJetIDskimTree() {
    TH2F* jetptjetid[nJetID];
    TH1F* jetpt;
    TH2F* Spikeetaphi;
    TH2F* Spikeetapt;
    jetpt = new TH1F(Form("jetpt"),Form("jetpt"),1000,0.,1000.);
    jetpt -> Sumw2();
    Spikeetaphi = new TH2F(Form("Spikeetaphi"),Form("Spikeetaphi"),200,-5.,5.,200, -TMath::Pi(), TMath::Pi());
    Spikeetaphi -> Sumw2();
    Spikeetapt = new TH2F(Form("Spikeetapt"),Form("Spikeetapt"),200,-5.,5.,1000,0.,1000.);
    Spikeetapt -> Sumw2();
    for(int ijetid=0; ijetid<nJetID; ijetid++) {
        if(JetIDName[ijetid].Contains("pt") || JetIDName[ijetid].Contains("Maxr")) {
            jetptjetid[ijetid] = new TH2F(Form("jetpt%s",JetIDName[ijetid].Data()), Form("jetpt%s",JetIDName[ijetid].Data()), 1000, 0., 1000., 200, 0., 2.);      //Added
        }
        else if(JetIDName[ijetid].Contains("N") || JetIDName[ijetid].Contains("PP")) {
            jetptjetid[ijetid] = new TH2F(Form("jetpt%s",JetIDName[ijetid].Data()), Form("jetpt%s",JetIDName[ijetid].Data()), 1000, 0., 1000., 100, 0., 100.);    //Added
        }
        else {
            jetptjetid[ijetid] = new TH2F(Form("jetpt%s",JetIDName[ijetid].Data()), Form("jetpt%s",JetIDName[ijetid].Data()), 1000, 0., 1000., 3000, 0., 300.);   //Added
        }
        jetptjetid[ijetid]->Sumw2();      //Added
    }

    TH2F * jetptjetidEtaBin[netabin][nJetID];
    TH1F * jetptEtaBin[netabin];

    for(int ieta=0; ieta < netabin; ieta++) {
        jetptEtaBin[ieta] = new TH1F(Form("jetptEtaBin%.f_%.f",deta[ieta]*10,deta[ieta+1]*10),Form("jetptEtaBin%.f_%.f",deta[ieta]*10,deta[ieta+1]*10),1000,0.,1000.);
        jetptEtaBin[ieta]->Sumw2();
        for(int ijetid=0; ijetid<nJetID; ijetid++) {
            if(JetIDName[ijetid].Contains("pt") || JetIDName[ijetid].Contains("Maxr")) {
                jetptjetidEtaBin[ieta][ijetid] = new TH2F(Form("jetpt%sEtaBin%.f_%.f",JetIDName[ijetid].Data(),deta[ieta]*10,deta[ieta+1]*10), Form("jetpt%sEtaBin%.f_%.f",JetIDName[ijetid].Data(),deta[ieta]*10,deta[ieta+1]*10), 1000, 0., 1000., 200, 0., 2.);    //Added
                jetptjetidEtaBin[ieta][ijetid]->Sumw2();      //Added
            }
            if(JetIDName[ijetid].Contains("PP") || JetIDName[ijetid].Contains("N")) {
                jetptjetidEtaBin[ieta][ijetid] = new TH2F(Form("jetpt%sEtaBin%.f_%.f",JetIDName[ijetid].Data(),deta[ieta]*10,deta[ieta+1]*10), Form("jetpt%sEtaBin%.f_%.f",JetIDName[ijetid].Data(),deta[ieta]*10,deta[ieta+1]*10), 1000, 0., 1000., 100, 0., 100.);    //Added
                jetptjetidEtaBin[ieta][ijetid]->Sumw2();      //Added
            }
        }
    }

    std::cout<<"start working\n";

    cout<<"Analyzing DATA!"<<endl;

    TFile *f = new TFile(Form("/cms/store/user/qixu/jetRpA/skimTree/DATA%s%sskimfile.root",coll.Data(),algo.Data()));

    TFile *fcrel3 = NULL ;
    TH1D *C_rel= NULL ;

    fcrel3 = TFile::Open(Form("/cms/store/user/qixu/jetRpA/RpA/NewMC/Corrections/CasymYaxian_%s_double_hcalbins_algo_%s_pt100_140_jet50_alphahigh_20_phicut250.root",coll.Data(),algo.Data()), "readonly");
    if(fcrel3)  C_rel=(TH1D*)fcrel3->Get("C_asym");

    TF1 * fUE = new TF1("fUE","1-[0]/pow(x,[1])",20,600);
    if(algo=="ak3PF")  fUE->SetParameters(0.8648,0.8167);
    else if (algo=="akPu3PF") fUE->SetParameters(0.3015,0.8913);
    else fUE->SetParameters(0.,0.);

    TTree *nt = (TTree*)f->Get("nt");

    Float_t jtpt[1000],jteta[1000],jtphi[1000],rawpt[1000];
    Int_t t_chargedN[100], t_neutralN[100], t_photonN[100];
    Float_t t_chargedSum[100], t_photonSum[100], t_neutralSum[100], t_chargedMax[100], t_neutralMax[100], t_photonMax[100], t_eSum[100], t_muSum[100];
    Int_t run,nref,hiBin;
    Int_t HLT_PAJet20_noJetID_v1;
    Int_t HLT_PAJet40_noJetID_v1;
    Int_t HLT_PAJet60_noJetID_v1;
    Int_t HLT_PAJet80_noJetID_v1;
    Int_t HLT_PAJet100_noJetID_v1;

    Int_t pPAcollisionEventSelectionPA;
    Int_t pprimaryVertexFilter;
    Int_t pHBHENoiseFilter;

    Float_t weight;
    Float_t vz,pt;

    nt->SetBranchAddress("run",&run);
    nt->SetBranchAddress("vz",&vz);
    nt->SetBranchAddress("pt",&pt);
    nt->SetBranchAddress("hiBin",&hiBin);
    nt->SetBranchAddress("nref",&nref);
    nt->SetBranchAddress("rawpt",rawpt);
    nt->SetBranchAddress("HLT_PAJet20_noJetID_v1",&HLT_PAJet20_noJetID_v1);
    nt->SetBranchAddress("HLT_PAJet40_noJetID_v1",&HLT_PAJet40_noJetID_v1);
    nt->SetBranchAddress("HLT_PAJet60_noJetID_v1",&HLT_PAJet60_noJetID_v1);
    nt->SetBranchAddress("HLT_PAJet80_noJetID_v1",&HLT_PAJet80_noJetID_v1);
    nt->SetBranchAddress("HLT_PAJet100_noJetID_v1",&HLT_PAJet100_noJetID_v1);
    nt->SetBranchAddress("pPAcollisionEventSelectionPA",&pPAcollisionEventSelectionPA);
    if(coll=="PPb")
        nt->SetBranchAddress("pprimaryVertexFilter",&pprimaryVertexFilter);
    if(coll=="PbP")
        nt->SetBranchAddress("pprimaryvertexFilter",&pprimaryVertexFilter);
    nt->SetBranchAddress("pHBHENoiseFilter",&pHBHENoiseFilter);
    nt->SetBranchAddress("jtpt",jtpt);
    nt->SetBranchAddress("jteta",jteta);
    nt->SetBranchAddress("jtphi",jtphi);
    nt->SetBranchAddress("chargedN",t_chargedN);
    nt->SetBranchAddress("photonN",t_photonN);
    nt->SetBranchAddress("neutralN",t_neutralN);
    nt->SetBranchAddress("chargedMax",t_chargedMax);
    nt->SetBranchAddress("photonMax",t_photonMax);
    nt->SetBranchAddress("neutralMax",t_neutralMax);
    nt->SetBranchAddress("chargedSum",t_chargedSum);
    nt->SetBranchAddress("photonSum",t_photonSum);
    nt->SetBranchAddress("neutralSum",t_neutralSum);
    nt->SetBranchAddress("muSum",t_muSum);
    nt->SetBranchAddress("eSum",t_eSum);
    nt->SetBranchAddress("weight",&weight);

    Int_t nentries = nt->GetEntries();

    for(int i=0; i<nentries; i++) {
        nt->GetEntry(i);
        if(coll == "PPb" && run>211256) continue;//only for pPb runs at moment
        if(coll == "PbP" && run<=211256) continue;//only for pPb runs at moment
        if((TMath::Abs(vz)>15) || (!pPAcollisionEventSelectionPA) || (!pprimaryVertexFilter)|| (!pHBHENoiseFilter)) continue;
        if(!HLT_PAJet20_noJetID_v1 && !HLT_PAJet40_noJetID_v1 && !HLT_PAJet60_noJetID_v1 && !HLT_PAJet80_noJetID_v1 && !HLT_PAJet100_noJetID_v1 ) continue;

        if(i%10000==1)    cout<<"analyzing "<< i <<" th event"<<endl;
        for(int j4i = 0; j4i < nref; j4i++) {
            double jet_pt = jtpt[j4i];
            double jet_eta = jteta[j4i];
            double jet_phi = jtphi[j4i];
            double raw_pt = rawpt[j4i];
            double jetweight = 1.;
//       jetweight*=(fUE->Eval(jet_pt))*C_rel->GetBinContent(C_rel->FindBin(jet_eta));
            jetweight*=C_rel->GetBinContent(C_rel->FindBin(jet_eta));

            double chargedMax = t_chargedMax[j4i];
            double chargedSum = t_chargedSum[j4i];
            double neutralMax = t_neutralMax[j4i];
            double neutralSum = t_neutralSum[j4i];
            double photonMax = t_photonMax[j4i];
            double photonSum = t_photonSum[j4i];
            int chargedN = t_chargedN[j4i];
            int neutralN = t_neutralN[j4i];
            int photonN = t_photonN[j4i];
            double muSum = t_muSum[j4i];
            double eSum = t_eSum[j4i];
            //      if((chargedN == 0 || chargedSum == 0) && TMath::Abs(jet_eta)< 2.4) continue;  // jet id selection
            double PPTighter0 = (double)(neutralSum/jet_pt < 0.8 && eSum/jet_pt < 1.0 && photonSum/jet_pt < 1.0 && (chargedSum+neutralSum+muSum+eSum)/jet_pt < 1.0 && ((chargedSum/jet_pt>0 && chargedN>0 && TMath::Abs(jet_eta)<2.4) || TMath::Abs(jet_eta) >=2.4));
            double PPTighter1 = (double)(neutralSum/jet_pt < 0.8 && eSum/jet_pt < 1.0 && photonSum/jet_pt < 1.0 && (chargedSum+neutralSum+muSum+eSum)/jet_pt < 1.0 && chargedSum/jet_pt < 0.95 && ((chargedSum/jet_pt>0 && chargedN>0 && TMath::Abs(jet_eta)<2.4) || TMath::Abs(jet_eta) >=2.4) );
            double PPTighter2 = (double)(neutralSum/jet_pt < 0.9 && eSum/jet_pt < 1.0 && photonSum/jet_pt < 1.0 && (chargedSum+neutralSum+muSum+eSum)/jet_pt < 1.0 && ((chargedSum/jet_pt>0 && chargedN>0 && TMath::Abs(jet_eta)<2.4) || TMath::Abs(jet_eta) >=2.4) );
            double PPTighter3 = (double)(neutralSum/jet_pt < 0.9 && eSum/jet_pt < 1.0 && photonSum/jet_pt < 1.0 && (chargedSum+neutralSum+muSum+eSum)/jet_pt < 1.0 && chargedSum/jet_pt < 0.95 && ((chargedSum/jet_pt>0 && chargedN>0 && TMath::Abs(jet_eta)<2.4) || TMath::Abs(jet_eta) >=2.4) );
            double PPTighter4 = (double)(neutralSum/jet_pt < 0.9 && eSum/jet_pt < 1.0 && photonSum/jet_pt < 1.0 && (chargedSum+neutralSum+muSum+eSum)/jet_pt < 0.95 && chargedSum/jet_pt < 0.95 && ((chargedSum/jet_pt>0 && chargedN>0 && TMath::Abs(jet_eta)<2.4) || TMath::Abs(jet_eta) >=2.4) );
            double PPTighter5 = (double)(neutralSum/jet_pt < 0.8 && eSum/jet_pt < 1.0 && photonSum/jet_pt < 1.0 && (chargedSum+neutralSum+muSum+eSum)/jet_pt < 0.95 && chargedSum/jet_pt < 0.95 && ((chargedSum/jet_pt>0 && chargedN>0 && TMath::Abs(jet_eta)<2.4) || TMath::Abs(jet_eta) >=2.4) );
            double PPTighter = PPTighter0*TMath::Power(2,5)+PPTighter1*TMath::Power(2,4)+PPTighter2*TMath::Power(2,3)+PPTighter3*TMath::Power(2,2)+PPTighter4*TMath::Power(2,1)+PPTighter5*TMath::Power(2,0)+0.5;
            double jetidv[nJetID]= {chargedMax,chargedSum,neutralMax,neutralSum,photonMax,photonSum,chargedMax/jet_pt,chargedSum/jet_pt,neutralMax/jet_pt,neutralSum/jet_pt,photonMax/jet_pt,photonSum/jet_pt,eSum/jet_pt,(chargedSum+neutralSum+photonSum+muSum+eSum)/jet_pt,(chargedSum+neutralSum+photonSum+muSum+eSum)/raw_pt,neutralMax/TMath::Max(chargedSum,neutralSum),(double)chargedN,(double)neutralN,(double)photonN,(double)(neutralSum/jet_pt<1.0 && eSum/jet_pt<1.0 && photonSum/jet_pt<1.0 && ((chargedSum>0 && TMath::Abs(jet_eta)<2.4) || TMath::Abs(jet_eta) >=2.4) ), (double)(neutralSum/jet_pt<0.9 && eSum/jet_pt<1.0 && photonSum/jet_pt<0.9 && ((chargedSum>0 && chargedN>0 && TMath::Abs(jet_eta)<2.4) || TMath::Abs(jet_eta) >=2.4) ),PPTighter,(chargedSum+neutralSum+muSum+eSum)/jet_pt};
            if(raw_pt<22 || fabs(jet_eta)>5) continue;
            if(jet_pt>4*pt) continue;
            //if(neutralSum/jet_pt > 0.8 && chargedSum/jet_pt < 0.1) {
            if(neutralSum/jet_pt > 0.8) {
                Spikeetaphi->Fill(jet_eta,jet_phi, weight);
                Spikeetapt->Fill(jet_eta,jet_pt, weight);
            }

            jet_pt = jet_pt*jetweight;

            int dEtaBin = -1;
            if(coll=="PPb")	jet_eta=jet_eta+0.465;
            if(coll=="PbP")	jet_eta=jet_eta-0.465;


            if(TMath::Abs(jet_eta)<=1.) {
                jetpt->Fill(jet_pt,weight);
                for(int ijetid=0; ijetid<nJetID; ijetid++) {
                    jetptjetid[ijetid]->Fill(jet_pt, jetidv[ijetid],weight);     //Added
                }
            }
            for(int ieta =0; ieta<netabin; ieta++) {
                if(jet_eta>deta[ieta]&&jet_eta<=deta[ieta+1]) dEtaBin=ieta;
            }//assign the eta bin for jets
            if(dEtaBin!=-1) {
                jetptEtaBin[dEtaBin]->Fill(jet_pt,weight);
                for(int ijetid=0; ijetid<nJetID; ijetid++) {
                    if(JetIDName[ijetid].Contains("pt") || JetIDName[ijetid].Contains("Maxr") || JetIDName[ijetid].Contains("PP") || JetIDName[ijetid].Contains("N")) {
                        jetptjetidEtaBin[dEtaBin][ijetid]->Fill(jet_pt,jetidv[ijetid],weight);
                    }
                }
            }
        } //loop over jet

    }	//loop over tree

    TString dataType;
    TString out_name;
    dataType = "DATA";
    out_name=Form("%s%s%sskimJetID.root",dataType.Data(),coll.Data(),algo.Data());

    TFile *out_file = new TFile(Form("/tmp/xuq7/%s",out_name.Data()),"RECREATE");

    jetpt->Write();
    Spikeetaphi->Write();
    Spikeetapt->Write();
    for(int ijetid=0; ijetid<nJetID; ijetid++) {
        jetptjetid[ijetid]->Write();
    }
    for(int ieta=0; ieta<netabin; ieta++) {
        for(int ijetid=0; ijetid<nJetID; ijetid++) {
            if(JetIDName[ijetid].Contains("pt") || JetIDName[ijetid].Contains("Maxr") || JetIDName[ijetid].Contains("PP") || JetIDName[ijetid].Contains("N")) {
                jetptjetidEtaBin[ieta][ijetid]->Write();
            }
        }
        jetptEtaBin[ieta]->Write();
    }
    out_file->Close();
    cout<<"Output file: "<<Form("%s",out_name.Data())<<endl;

    cout<<"working done\n";

}
Example #8
0
void AccTimesEff::Loop()
{
   TStopwatch timer;
   timer.Start();
   // parameters /////////////////////////////////////////////////////////////
   vector<TString> files;
   files.push_back("file:////user/treis/mcsamples/ZprimeToEMu_M-500_noAccCuts_TuneZ2star_8TeV_madgraph_treis-Summer12_DR53X_PU_S10_START53_V7C1-v1_9999ev.root");
   files.push_back("file:////user/treis/mcsamples/ZprimeToEMu_M-750_noAccCuts_TuneZ2star_8TeV_madgraph_treis-Summer12_DR53X_PU_S10_START53_V7C1-v1_10000ev.root");
   files.push_back("file:////user/treis/mcsamples/ZprimeToEMu_M-1000_noAccCuts_TuneZ2star_8TeV_madgraph_treis-Summer12_DR53X_PU_S10_START53_V7C1-v1_9998ev.root");
   files.push_back("file:////user/treis/mcsamples/ZprimeToEMu_M-1250_noAccCuts_TuneZ2star_8TeV_madgraph_treis-Summer12_DR53X_PU_S10_START53_V7C1-v1_9998ev.root");
   files.push_back("file:////user/treis/mcsamples/ZprimeToEMu_M-1500_noAccCuts_TuneZ2star_8TeV_madgraph_treis-Summer12_DR53X_PU_S10_START53_V7C1-v1_9997ev.root");
   files.push_back("file:////user/treis/mcsamples/ZprimeToEMu_M-1750_noAccCuts_TuneZ2star_8TeV_madgraph_treis-Summer12_DR53X_PU_S10_START53_V7C1-v1_9997ev.root");
   files.push_back("file:////user/treis/mcsamples/ZprimeToEMu_M-2000_noAccCuts_TuneZ2star_8TeV_madgraph_treis-Summer12_DR53X_PU_S10_START53_V7C1-v1_9999ev.root");
   files.push_back("file:////user/treis/mcsamples/ZprimeToEMu_M-2500_noAccCuts_TuneZ2star_8TeV_madgraph_treis-Summer12_DR53X_PU_S10_START53_V7C1-v1_9999ev.root");
   files.push_back("file:////user/treis/mcsamples/ZprimeToEMu_M-3000_noAccCuts_TuneZ2star_8TeV_madgraph_treis-Summer12_DR53X_PU_S10_START53_V7C1-v1_10000ev.root");
   files.push_back("file:////user/treis/mcsamples/ZprimeToEMu_M-3500_noAccCuts_TuneZ2star_8TeV_madgraph_treis-Summer12_DR53X_PU_S10_START53_V7C1-v1_9898ev.root");
   files.push_back("file:////user/treis/mcsamples/ZprimeToEMu_M-4000_noAccCuts_TuneZ2star_8TeV_madgraph_treis-Summer12_DR53X_PU_S10_START53_V7C1-v1_9998ev.root");
   files.push_back("file:////user/treis/mcsamples/ZprimeToEMu_M-5000_noAccCuts_TuneZ2star_8TeV_madgraph_treis-Summer12_DR53X_PU_S10_START53_V7C1-v1_9966ev.root");
   string outfileName = "accTimesEffHistos";

   // output file formats
   const bool saveSpec = 0;
   const bool saveAsPdf = 0;
   const bool saveAsPng = 1;
   const bool saveAsRoot = 0;
   TString plotDir = "./plots/";

   int font = 42; //62
   // selection cuts /////////////////////////////////////////////////////////
   float elePtCut = 35.;
   float muPtCut = 35.;
   float minInvMass = 0.;

   TH1::SetDefaultSumw2(kTRUE);

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

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

   TH1F *hGenEvts = new TH1F("hGenEvts", "hGenEvts", 145, 0., 5010.);
   hGenEvts->GetXaxis()->SetTitle("M_{Z'}^{truth}");
   hGenEvts->GetXaxis()->SetTitleFont(font);
   hGenEvts->GetXaxis()->SetLabelFont(font);
   hGenEvts->GetYaxis()->SetTitle("Events");
   hGenEvts->GetYaxis()->SetTitleFont(font);
   hGenEvts->GetYaxis()->SetLabelFont(font);
   hGenEvts->GetYaxis()->SetTitleOffset(1.2);
   hGenEvts->SetLineColor(kBlack);
   hGenEvts->SetLineWidth(2);
   hGenEvts->SetMarkerStyle(20);
   hGenEvts->SetMarkerColor(kBlack);
   TH1F *hGenEvtsEleInAcc = (TH1F*)hGenEvts->Clone("hGenEvtsEleInAcc");
   TH1F *hGenEvtsEleInAccEB = (TH1F*)hGenEvts->Clone("hGenEvtsEleInAccEB");
   TH1F *hGenEvtsEleInAccEE = (TH1F*)hGenEvts->Clone("hGenEvtsEleInAccEE");
   TH1F *hGenEvtsMuInAcc = (TH1F*)hGenEvts->Clone("hGenEvtsMuInAcc");
   TH1F *hGenEvtsInAcc = (TH1F*)hGenEvts->Clone("hGenEvtsInAcc");
   TH1F *hTrgEvts = (TH1F*)hGenEvts->Clone("hTrgEvts");
   hTrgEvts->SetTitle("hTrgEvts");
   TH1F *hRecoEvts = (TH1F*)hGenEvts->Clone("hRecoEvts");
   hRecoEvts->SetTitle("hRecoEvts");
   TH1F *hRecoEvtsEB = (TH1F*)hRecoEvts->Clone("hRecoEvtsEB");
   TH1F *hRecoEvtsEE = (TH1F*)hRecoEvts->Clone("hRecoEvtsEE");
   TH1F *hRecoEleEvts = (TH1F*)hRecoEvts->Clone("hRecoEleEvts");
   TH1F *hRecoEleEvtsEB = (TH1F*)hRecoEvts->Clone("hRecoEleEvtsEB");
   TH1F *hRecoEleEvtsEE = (TH1F*)hRecoEvts->Clone("hRecoEleEvtsEE");
   TH1F *hRecoMuEvts = (TH1F*)hRecoEvts->Clone("hRecoMuEvts");
   TH1F *hRecoNoTrgEvts = (TH1F*)hGenEvts->Clone("hRecoNoTrgEvts");
   hRecoNoTrgEvts->SetTitle("hRecoNoTrgEvts");
   TH1F *hRecoNoTrgEvtsEB = (TH1F*)hRecoNoTrgEvts->Clone("hRecoNoTrgEvtsEB");
   TH1F *hRecoNoTrgEvtsEE = (TH1F*)hRecoNoTrgEvts->Clone("hRecoNoTrgEvtsEE");
   TH1F *hRecoNoTrgEleEvts = (TH1F*)hRecoNoTrgEvts->Clone("hRecoNoTrgEleEvts");
   TH1F *hRecoNoTrgEleEvtsEB = (TH1F*)hRecoNoTrgEvts->Clone("hRecoNoTrgEleEvtsEB");
   TH1F *hRecoNoTrgEleEvtsEE = (TH1F*)hRecoNoTrgEvts->Clone("hRecoNoTrgEleEvtsEE");
   TH1F *hRecoNoTrgMuEvts = (TH1F*)hRecoNoTrgEvts->Clone("hRecoNoTrgMuEvts");
   TH1F* hAcc;
   TH1F* hAccEle;
   TH1F* hAccEleEB;
   TH1F* hAccEleEE;
   TH1F* hAccMu;
   TH1F* hAccTimesTrgEff;
   TH1F* hTrgEff;
   TH1F* hAccTimesEff;
   TH1F* hAccTimesEffEB;
   TH1F* hAccTimesEffEE;
   TH1F* hAccTimesEffEle;
   TH1F* hAccTimesEffEleEB;
   TH1F* hAccTimesEffEleEE;
   TH1F* hAccTimesEffMu;
   TH1F* hAccTimesEffNoTrg;
   //TH1F* hAccTimesEffNoTrgEB;
   //TH1F* hAccTimesEffNoTrgEE;
   TH1F* hAccTimesEffNoTrgEle;
   TH1F* hAccTimesEffNoTrgEleEB;
   TH1F* hAccTimesEffNoTrgEleEE;
   TH1F* hAccTimesEffNoTrgMu;
   TH1F* hEffAftTrg;
   TH1F* hEffAftTrgEle;
   TH1F* hEffAftTrgEleEB;
   TH1F* hEffAftTrgEleEE;
   TH1F* hEffAftTrgMu;
   TH1F* hTrgRecoVsReco;
   //TH1F* hTrgRecoVsRecoEB;
   //TH1F* hTrgRecoVsRecoEE;
   TH1F* hTrgRecoVsRecoEle;
   TH1F* hTrgRecoVsRecoEleEB;
   TH1F* hTrgRecoVsRecoEleEE;
   TH1F* hTrgRecoVsRecoMu;

   // output file
   stringstream ssOutfile;
   ssOutfile << outfileName << ".root";
   TFile *output = new TFile(ssOutfile.str().c_str(), "recreate");

   ///////////////////////////////////////////////////////////////////////////
   //LOOP OVER FILES 
   ///////////////////////////////////////////////////////////////////////////
   for (unsigned int p = 0; p < files.size(); ++p) {
      TFile* input = new TFile(files[p]);
      TTree *thetree = (TTree*)input->Get("gsfcheckerjob/tree");
      Init(thetree);
      Long64_t nentries = fChain->GetEntriesFast();
      cout << nentries << " events" << endl;

      unsigned int evCounter = 0;
      /////////////////////////////////////////////////////////////////////////////////////////////
      //LOOP OVER EVENTS
      /////////////////////////////////////////////////////////////////////////////////////////////
      //nentries = 10000;
      for (Long64_t jentry = 0; jentry < nentries; ++jentry) {
         Long64_t ientry = LoadTree(jentry);
         if (ientry < 0) break;
         fChain->GetEntry(jentry);
         // if (Cut(ientry) < 0) continue;
         //if (jentry % 50000 == 0) cout << "Processing event " << jentry << endl;
         thetree->GetEntry(jentry);

         // fill the gen histograms
         hGenEvts->Fill(genelemom_mass[0]);

         // fill the acc histograms
         if (hardGenEle_pt[0] > elePtCut) {
            if (fabs(hardGenEle_eta[0]) < 1.442) {
               hGenEvtsEleInAcc->Fill(genelemom_mass[0]);
               hGenEvtsEleInAccEB->Fill(genelemom_mass[0]);
            }
            else if (fabs(hardGenEle_eta[0]) > 1.56 && fabs(hardGenEle_eta[0]) < 2.5) {
               hGenEvtsEleInAcc->Fill(genelemom_mass[0]);
               hGenEvtsEleInAccEE->Fill(genelemom_mass[0]);
            }
         }
         if (hardGenMu_pt[0] > muPtCut && fabs(hardGenMu_eta[0]) < 2.4) {
            hGenEvtsMuInAcc->Fill(genelemom_mass[0]);
            if (fabs(hardGenEle_eta[0]) < 1.442 || (fabs(hardGenEle_eta[0]) > 1.56 && fabs(hardGenEle_eta[0]) < 2.5)) {
               if (hardGenEle_pt[0] > elePtCut) hGenEvtsInAcc->Fill(genelemom_mass[0]);
            }
         }

         // trigger?
         if (HLT_Mu22_Photon22_CaloIdL) hTrgEvts->Fill(genelemom_mass[0]);

         // at least one gsf electron and one muon above the threshold
         if (gsf_size < 1 || muon_size < 1) continue;

         vector<int> GSF_passHEEP;
         vector<int> MU_passGOOD;
         /////////////////////////////////////////////////////////////////////////////////////////////
         //loop over electrons
         for (int j = 0; j < gsf_size; ++j) {
            //cleaning: fake electrons from muons
            bool fakeEle = false;
            for (int k = 0; k < muon_size; ++k) {
               float DeltaR = deltaR(gsf_eta[j], gsf_phi[j], muon_eta[k], muon_phi[k]);
               if (DeltaR < 0.1) {
                  fakeEle = true;
                  break;
               }
            }
            if (fakeEle) continue;

            if (PassHEEP(j)) GSF_passHEEP.push_back(j);
         }

         //loop over muons
         for (int j = 0; j < muon_size; ++j) {
            if (PassHighPtMu(j)) MU_passGOOD.push_back(j);
         }

         if (GSF_passHEEP.size() == 1) {
            if (HLT_Mu22_Photon22_CaloIdL) {
               hRecoEleEvts->Fill(genelemom_mass[0]);
               if (fabs(gsfsc_eta[GSF_passHEEP[0]]) < 1.5) hRecoEleEvtsEB->Fill(genelemom_mass[0]);
               if (fabs(gsfsc_eta[GSF_passHEEP[0]]) > 1.5) hRecoEleEvtsEE->Fill(genelemom_mass[0]);
            }
            hRecoNoTrgEleEvts->Fill(genelemom_mass[0]);
            if (fabs(gsfsc_eta[GSF_passHEEP[0]]) < 1.5) hRecoNoTrgEleEvtsEB->Fill(genelemom_mass[0]);
            if (fabs(gsfsc_eta[GSF_passHEEP[0]]) > 1.5) hRecoNoTrgEleEvtsEE->Fill(genelemom_mass[0]);
         } 
         if (MU_passGOOD.size() == 1) {
            if (HLT_Mu22_Photon22_CaloIdL) hRecoMuEvts->Fill(genelemom_mass[0]);
            hRecoNoTrgMuEvts->Fill(genelemom_mass[0]);
         }

         // veto when there are more than one good candidates
         if (GSF_passHEEP.size() != 1 || MU_passGOOD.size() != 1) continue;

         //HEEP ele + GOOD muon
         TLorentzVector ele1;
         TLorentzVector mu1;

         ele1.SetPtEtaPhiM(gsf_gsfet[GSF_passHEEP[0]], gsf_eta[GSF_passHEEP[0]], gsf_phi[GSF_passHEEP[0]], 0.000511);
         mu1.SetPtEtaPhiM(muon_pt[MU_passGOOD[0]], muon_eta[MU_passGOOD[0]], muon_phi[MU_passGOOD[0]], 0.10566);

         double invMass = (ele1 + mu1).M();

         //MASS CUT
         if (invMass < minInvMass) continue;

         if (HLT_Mu22_Photon22_CaloIdL) {
            hRecoEvts->Fill(genelemom_mass[0]);
            if (fabs(gsfsc_eta[GSF_passHEEP[0]]) < 1.5) hRecoEvtsEB->Fill(genelemom_mass[0]);
            if (fabs(gsfsc_eta[GSF_passHEEP[0]]) > 1.5) hRecoEvtsEE->Fill(genelemom_mass[0]);
         }
         hRecoNoTrgEvts->Fill(genelemom_mass[0]);
         if (fabs(gsfsc_eta[GSF_passHEEP[0]]) < 1.5) hRecoNoTrgEvtsEB->Fill(genelemom_mass[0]);
         if (fabs(gsfsc_eta[GSF_passHEEP[0]]) > 1.5) hRecoNoTrgEvtsEE->Fill(genelemom_mass[0]);
         ++evCounter;
        ///////////////////////////////////////////////////////////////////////
      } //END LOOP OVER EVENTS
        //////////////////////////////////////////////////////////////////////

     //////////////////////////////////////////////////////////////////////////
   } //END LOOP OVER FILES
     //////////////////////////////////////////////////////////////////////////
   hAcc = (TH1F*)hGenEvtsInAcc->Clone("hAcc");
   hAccEle = (TH1F*)hGenEvtsEleInAcc->Clone("hAccEle");
   hAccEleEB = (TH1F*)hGenEvtsEleInAccEB->Clone("hAccEleEB");
   hAccEleEE = (TH1F*)hGenEvtsEleInAccEE->Clone("hAccEleEE");
   hAccMu = (TH1F*)hGenEvtsMuInAcc->Clone("hAccMu");
   hAccTimesTrgEff = (TH1F*)hTrgEvts->Clone("hAccTimesTrgEff");
   hTrgEff = (TH1F*)hTrgEvts->Clone("hTrgEff");
   hAccTimesEff = (TH1F*)hRecoEvts->Clone("hAccTimesEff");
   hAccTimesEffEB = (TH1F*)hRecoEvtsEB->Clone("hAccTimesEffEB");
   hAccTimesEffEE = (TH1F*)hRecoEvtsEE->Clone("hAccTimesEffEE");
   hAccTimesEffEle = (TH1F*)hRecoEleEvts->Clone("hAccTimesEffEle");
   hAccTimesEffEleEB = (TH1F*)hRecoEleEvtsEB->Clone("hAccTimesEffEleEB");
   hAccTimesEffEleEE = (TH1F*)hRecoEleEvtsEE->Clone("hAccTimesEffEleEE");
   hAccTimesEffMu = (TH1F*)hRecoMuEvts->Clone("hAccTimesEffMu");
   hAccTimesEffNoTrg = (TH1F*)hRecoNoTrgEvts->Clone("hAccTimesEffNoTrg");
   //hAccTimesEffNoTrgEB = (TH1F*)hRecoNoTrgEvtsEB->Clone("hAccTimesEffNoTrgEB");
   //hAccTimesEffNoTrgEE = (TH1F*)hRecoNoTrgEvtsEE->Clone("hAccTimesEffNoTrgEE");
   hAccTimesEffNoTrgEle = (TH1F*)hRecoNoTrgEleEvts->Clone("hAccTimesEffNoTrgEle");
   hAccTimesEffNoTrgEleEB = (TH1F*)hRecoNoTrgEleEvtsEB->Clone("hAccTimesEffNoTrgEleEB");
   hAccTimesEffNoTrgEleEE = (TH1F*)hRecoNoTrgEleEvtsEE->Clone("hAccTimesEffNoTrgEleEE");
   hAccTimesEffNoTrgMu = (TH1F*)hRecoNoTrgMuEvts->Clone("hAccTimesEffNoTrgMu");
   hEffAftTrg = (TH1F*)hRecoEvts->Clone("hAccTimesEff");
   hEffAftTrgEle = (TH1F*)hRecoEleEvts->Clone("hAccTimesEffEle");
   hEffAftTrgEleEB = (TH1F*)hRecoEleEvtsEB->Clone("hAccTimesEffEleEB");
   hEffAftTrgEleEE = (TH1F*)hRecoEleEvtsEE->Clone("hAccTimesEffEleEE");
   hEffAftTrgMu = (TH1F*)hRecoMuEvts->Clone("hAccTimesEffMu");
   hTrgRecoVsReco = (TH1F*)hRecoEvts->Clone("hTrgRecoVsReco");
   //hTrgRecoVsRecoEB = (TH1F*)hRecoEvtsEB->Clone("hTrgRecoVsRecoEB");
   //hTrgRecoVsRecoEE = (TH1F*)hRecoEvtsEE->Clone("hTrgRecoVsRecoEE");
   hTrgRecoVsRecoEle = (TH1F*)hRecoEleEvts->Clone("hTrgRecoVsRecoEle");
   hTrgRecoVsRecoEleEB = (TH1F*)hRecoEleEvtsEB->Clone("hTrgRecoVsRecoEleEB");
   hTrgRecoVsRecoEleEE = (TH1F*)hRecoEleEvtsEE->Clone("hTrgRecoVsRecoEleEE");
   hTrgRecoVsRecoMu = (TH1F*)hRecoMuEvts->Clone("hTrgRecoVsRecoMu");
   hAcc->Divide(hGenEvts);
   hAccEle->Divide(hGenEvts);
   hAccEleEB->Divide(hGenEvts);
   hAccEleEE->Divide(hGenEvts);
   hAccMu->Divide(hGenEvts);
   hAccTimesTrgEff->Divide(hGenEvts);
   hTrgEff->Divide(hGenEvtsInAcc);
   hAccTimesEff->Divide(hGenEvts);
   hAccTimesEffEB->Divide(hGenEvts);
   hAccTimesEffEE->Divide(hGenEvts);
   hAccTimesEffEle->Divide(hGenEvts);
   hAccTimesEffEleEB->Divide(hGenEvts);
   hAccTimesEffEleEE->Divide(hGenEvts);
   hAccTimesEffMu->Divide(hGenEvts);
   hAccTimesEffNoTrg->Divide(hGenEvts);
   //hAccTimesEffNoTrgEB->Divide(hGenEvts);
   //hAccTimesEffNoTrgEE->Divide(hGenEvts);
   hAccTimesEffNoTrgEle->Divide(hGenEvts);
   hAccTimesEffNoTrgEleEB->Divide(hGenEvts);
   hAccTimesEffNoTrgEleEE->Divide(hGenEvts);
   hAccTimesEffNoTrgMu->Divide(hGenEvts);
   hEffAftTrg->Divide(hTrgEvts);
   hEffAftTrgEle->Divide(hTrgEvts);
   hEffAftTrgEleEB->Divide(hTrgEvts);
   hEffAftTrgEleEE->Divide(hTrgEvts);
   hEffAftTrgMu->Divide(hTrgEvts);
   hTrgRecoVsReco->Divide(hRecoNoTrgEvts);
   //hTrgRecoVsRecoEB->Divide(hRecoNoTrgEvtsEB);
   //hTrgRecoVsRecoEE->Divide(hRecoNoTrgEvtsEE);
   hTrgRecoVsRecoEle->Divide(hRecoNoTrgEleEvts);
   hTrgRecoVsRecoEleEB->Divide(hRecoNoTrgEleEvtsEB);
   hTrgRecoVsRecoEleEE->Divide(hRecoNoTrgEleEvtsEE);
   hTrgRecoVsRecoMu->Divide(hRecoNoTrgMuEvts);

   // plot
   TCanvas *accTimesEffPlot = new TCanvas("accTimesEffPlot", "acc x eff", 100, 100, 600, 600);
   TPad *accTimesEffPad = new TPad("accTimesEffPad", "acc x eff pad", 0., 0., 1., 1.);
   accTimesEffPad->SetBottomMargin(0.12);
   accTimesEffPad->SetBorderMode(0);
   accTimesEffPad->SetBorderSize(2);
   accTimesEffPad->SetFrameBorderMode(0);
   accTimesEffPad->SetFillColor(0);
   accTimesEffPad->SetFrameFillColor(0);
   accTimesEffPad->SetLeftMargin(0.11);
   accTimesEffPad->SetRightMargin(0.09);
   accTimesEffPad->SetTopMargin(0.08);
   accTimesEffPad->SetTickx(1);
   accTimesEffPad->SetTicky(1);
   accTimesEffPad->Draw();
   accTimesEffPad->cd();

   gStyle->SetTitleFont(font);
   gStyle->SetLabelFont(font);
   gStyle->SetLegendFont(font);
   gStyle->SetOptStat(0);
   gStyle->SetOptTitle(0);
   gStyle->SetOptFit(1111);
   gStyle->SetTitleXOffset(1.);
   gStyle->SetTitleYOffset(1.3);
   gPad->SetTicks(1, 1);
   gPad->SetGrid(1, 1);

   TH1F* hAccTimesEff2 = (TH1F*)hAccTimesEff->Clone("hAccTimesEff2");

   TF1 *fitFunc = new TF1("fitFunc", "[0] + [1]/ (x + [2]) + [3]*x", 10., 5010.);
   //TF1 *fitFuncEB = new TF1("fitFuncEB", "[0] + [1]/ (x + [2])", 10., 5010.);
   TF1 *fitFuncEB = new TF1("fitFuncEB", "[0] + [1]/ (x + [2]) + [3]*x", 10., 5010.);
   TF1 *fitFuncEE = new TF1("fitFuncEE", "[0] + [1]/ (x*x + [2])", 10., 5010.);
   fitFunc->SetLineColor(kBlue);
   fitFuncEB->SetLineColor(kBlue);
   fitFuncEE->SetLineColor(kBlue);
   hAccTimesEff->Fit("fitFunc", "", "", 480., 5010.);
   hAccTimesEffEB->Fit("fitFuncEB", "", "", 480., 5010.);
   hAccTimesEffEE->Fit("fitFuncEE", "", "", 480., 5010.);
   cout << "Chi^2 / NDF: " << fitFunc->GetChisquare() << " / " << fitFunc->GetNDF() << ", prob: " << fitFunc->GetProb() << endl;
   cout << "Chi^2 / NDF EB: " << fitFuncEB->GetChisquare() << " / " << fitFuncEB->GetNDF() << ", prob: " << fitFuncEB->GetProb() << endl;
   cout << "Chi^2 / NDF EE: " << fitFuncEE->GetChisquare() << " / " << fitFuncEE->GetNDF() << ", prob: " << fitFuncEE->GetProb() << endl;

   hAccTimesEff->GetYaxis()->SetTitle("acc x eff");
   hAccTimesEff->GetYaxis()->SetRangeUser(0., 1.);
   hAccTimesEff->Draw();
   TLatex *tex = new TLatex(0.22, 0.21, "P(M|p0,p1,p2,p3) = p0 + #frac{p1}{M+p2} + p3*M");
   tex->SetNDC();
   tex->SetTextFont(font);
   tex->SetLineWidth(2);
   tex->SetTextSize(0.03);
   tex->Draw();
   tex->DrawLatex(0.109, 0.935, "CMS Simulation, 8 TeV");
   tex->DrawLatex(0.17, 0.85, "trg + electron + muon");

   TCanvas *accTimesEffPlotEB = new TCanvas("accTimesEffPlotEB", "acc x eff, barrel electron + muon", 100, 100, 600, 600);
   TPad *accTimesEffPadEB = (TPad*)accTimesEffPad->Clone("accTimesEffPadEB");
   accTimesEffPadEB->Draw(); 
   accTimesEffPadEB->cd();
   hAccTimesEffEB->GetYaxis()->SetTitle("acc x eff");
   hAccTimesEffEB->GetYaxis()->SetRangeUser(0., 1.);
   hAccTimesEffEB->Draw();
   tex->DrawLatex(0.109, 0.935, "CMS Simulation, 8 TeV");
   //tex->DrawLatex(0.46, 0.21, "P(M|p0,p1,p2) = p0 + #frac{p1}{M+p2}");
   tex->DrawLatex(0.22, 0.21, "P(M|p0,p1,p2,p3) = p0 + #frac{p1}{M+p2} + p3*M");
   tex->DrawLatex(0.17, 0.85, "trg + barrel electron + muon");

   TCanvas *accTimesEffPlotEE = new TCanvas("accTimesEffPlotEE", "acc x eff, endcap electron + muon", 100, 100, 600, 600);
   TPad *accTimesEffPadEE = (TPad*)accTimesEffPad->Clone("accTimesEffPadEE");
   accTimesEffPadEE->Draw(); 
   accTimesEffPadEE->cd();
   hAccTimesEffEE->GetYaxis()->SetTitle("acc x eff");
   hAccTimesEffEE->GetYaxis()->SetRangeUser(0., 1.);
   hAccTimesEffEE->Draw();
   tex->DrawLatex(0.109, 0.935, "CMS Simulation, 8 TeV");
   tex->DrawLatex(0.45, 0.38, "P(M|p0,p1,p2) = p0 + #frac{p1}{M^{2}+p2}");
   tex->DrawLatex(0.17, 0.85, "trg + endcap electron + muon");

   TCanvas *accTimesEffObjPlot = new TCanvas("accTimesEffObjPlot", "acc x eff, objects", 100, 100, 600, 600);
   TPad *accTimesEffObjPad = (TPad*)accTimesEffPad->Clone("accTimesEffObjPad");
   accTimesEffObjPad->Draw(); 
   accTimesEffObjPad->cd();
   hAccTimesEffEle->GetYaxis()->SetTitle("acc x eff");
   hAccTimesEffEle->GetYaxis()->SetRangeUser(0., 1.);
   hAccTimesEffEle->SetMarkerStyle(kFullSquare);
   hAccTimesEffEle->SetMarkerColor(kViolet);
   hAccTimesEffEle->SetLineColor(kViolet);
   hAccTimesEffEle->Draw();
   hAccTimesEffEleEB->SetMarkerStyle(kFullTriangleUp);
   hAccTimesEffEleEB->SetMarkerColor(kRed);
   hAccTimesEffEleEB->SetLineColor(kRed);
   hAccTimesEffEleEB->Draw("same");
   hAccTimesEffEleEE->SetMarkerStyle(kFullTriangleDown);
   hAccTimesEffEleEE->SetMarkerColor(kBlue);
   hAccTimesEffEleEE->SetLineColor(kBlue);
   hAccTimesEffEleEE->Draw("same");
   hAccTimesEffMu->SetMarkerStyle(34);
   hAccTimesEffMu->SetMarkerColor(kGreen+1);
   hAccTimesEffMu->SetLineColor(kGreen+1);
   hAccTimesEffMu->Draw("same");
   hAccTimesEff2->Draw("same");
   TLegend* legend = new TLegend(0.592, 0.279, 0.881, 0.467);
   legend->SetTextFont(font);
   legend->SetTextSize(0.03);
   legend->SetBorderSize(0);
   legend->SetLineColor(1);
   legend->SetLineStyle(1);
   legend->SetLineWidth(1);
   legend->SetFillColor(19);
   legend->SetFillStyle(0);
   legend->AddEntry(hAccTimesEff, "total acc x eff");
   legend->AddEntry(hAccTimesEffMu, "muons");
   legend->AddEntry(hAccTimesEffEle, "all electrons");
   legend->AddEntry(hAccTimesEffEleEB, "barrel electrons");
   legend->AddEntry(hAccTimesEffEleEE, "endcap electrons");
   legend->Draw("same");
   tex->DrawLatex(0.109, 0.935, "CMS Simulation, 8 TeV");
   tex->DrawLatex(0.17, 0.85, "trg: HLT_Mu22_Photon22_CaloIdL");

   // acc x eff with no trg applied
   TCanvas *accTimesEffNoTrgObjPlot = new TCanvas("accTimesEffNoTrgObjPlot", "acc x eff, no trigger, objects", 100, 100, 600, 600);
   TPad *accTimesEffNoTrgObjPad = (TPad*)accTimesEffPad->Clone("accTimesEffNoTrgObjPad");
   accTimesEffNoTrgObjPad->Draw(); 
   accTimesEffNoTrgObjPad->cd();
   hAccTimesEffNoTrgEle->GetYaxis()->SetTitle("acc x eff");
   hAccTimesEffNoTrgEle->GetYaxis()->SetRangeUser(0., 1.);
   hAccTimesEffNoTrgEle->SetMarkerStyle(kFullSquare);
   hAccTimesEffNoTrgEle->SetMarkerColor(kViolet);
   hAccTimesEffNoTrgEle->SetLineColor(kViolet);
   hAccTimesEffNoTrgEle->Draw();
   hAccTimesEffNoTrgEleEB->SetMarkerStyle(kFullTriangleUp);
   hAccTimesEffNoTrgEleEB->SetMarkerColor(kRed);
   hAccTimesEffNoTrgEleEB->SetLineColor(kRed);
   hAccTimesEffNoTrgEleEB->Draw("same");
   hAccTimesEffNoTrgEleEE->SetMarkerStyle(kFullTriangleDown);
   hAccTimesEffNoTrgEleEE->SetMarkerColor(kBlue);
   hAccTimesEffNoTrgEleEE->SetLineColor(kBlue);
   hAccTimesEffNoTrgEleEE->Draw("same");
   hAccTimesEffNoTrgMu->SetMarkerStyle(34);
   hAccTimesEffNoTrgMu->SetMarkerColor(kGreen+1);
   hAccTimesEffNoTrgMu->SetLineColor(kGreen+1);
   hAccTimesEffNoTrgMu->Draw("same");
   hAccTimesEffNoTrg->Draw("same");
   TLegend* accXeffNoTrg = (TLegend*)legend->Clone("effAftTrgLegend");
   accXeffNoTrg->Clear();
   accXeffNoTrg->AddEntry(hAccTimesEffNoTrg, "total acc x eff");
   accXeffNoTrg->AddEntry(hAccTimesEffNoTrgMu, "muons");
   accXeffNoTrg->AddEntry(hAccTimesEffNoTrgEle, "all electrons");
   accXeffNoTrg->AddEntry(hAccTimesEffNoTrgEleEB, "barrel electrons");
   accXeffNoTrg->AddEntry(hAccTimesEffNoTrgEleEE, "endcap electrons");
   accXeffNoTrg->Draw("same");
   tex->DrawLatex(0.109, 0.935, "CMS Simulation, 8 TeV");
   tex->DrawLatex(0.17, 0.85, "trg: none");

   // efficiency on triggered events
   TCanvas *effAftTrgPlot = new TCanvas("effAftTrgPlot", "efficiency after trigger", 100, 100, 600, 600);
   TPad *effAftTrgPad = (TPad*)accTimesEffPad->Clone("effAftTrgPad");
   effAftTrgPad->Draw(); 
   effAftTrgPad->cd();
   hEffAftTrgEle->GetYaxis()->SetTitle("eff");
   hEffAftTrgEle->GetYaxis()->SetRangeUser(0., 1.);
   hEffAftTrgEle->SetMarkerStyle(kFullSquare);
   hEffAftTrgEle->SetMarkerColor(kViolet);
   hEffAftTrgEle->SetLineColor(kViolet);
   hEffAftTrgEle->Draw();
   hEffAftTrgEleEB->SetMarkerStyle(kFullTriangleUp);
   hEffAftTrgEleEB->SetMarkerColor(kRed);
   hEffAftTrgEleEB->SetLineColor(kRed);
   hEffAftTrgEleEB->Draw("same");
   hEffAftTrgEleEE->SetMarkerStyle(kFullTriangleDown);
   hEffAftTrgEleEE->SetMarkerColor(kBlue);
   hEffAftTrgEleEE->SetLineColor(kBlue);
   hEffAftTrgEleEE->Draw("same");
   hEffAftTrgMu->SetMarkerStyle(34);
   hEffAftTrgMu->SetMarkerColor(kGreen+1);
   hEffAftTrgMu->SetLineColor(kGreen+1);
   hEffAftTrgMu->Draw("same");
   hEffAftTrg->Draw("same");
   TLegend* effAftTrgLegend = (TLegend*)legend->Clone("effAftTrgLegend");
   effAftTrgLegend->Clear();
   effAftTrgLegend->AddEntry(hEffAftTrg, "total eff after trigger");
   effAftTrgLegend->AddEntry(hEffAftTrgMu, "muons");
   effAftTrgLegend->AddEntry(hEffAftTrgEle, "all electrons");
   effAftTrgLegend->AddEntry(hEffAftTrgEleEB, "barrel electrons");
   effAftTrgLegend->AddEntry(hEffAftTrgEleEE, "endcap electrons");
   effAftTrgLegend->Draw("same");
   tex->DrawLatex(0.109, 0.935, "CMS Simulation, 8 TeV");
   tex->DrawLatex(0.14, 0.15, "trg: HLT_Mu22_Photon22_CaloIdL");

   // acceptance
   TCanvas *accPlot = new TCanvas("accPlot", "acc", 100, 100, 600, 600);
   TPad *accPad = (TPad*)accTimesEffPad->Clone("accPad");
   accPad->Draw(); 
   accPad->cd();
   hAcc->GetYaxis()->SetTitle("acc");
   hAcc->GetYaxis()->SetRangeUser(0., 1.);
   hAccEle->SetMarkerStyle(kFullSquare);
   hAccEle->SetMarkerColor(kViolet);
   hAccEle->SetLineColor(kViolet);
   hAccEle->Draw();
   hAccEleEB->SetMarkerStyle(kFullTriangleUp);
   hAccEleEB->SetMarkerColor(kRed);
   hAccEleEB->SetLineColor(kRed);
   hAccEleEB->Draw("same");
   hAccEleEE->SetMarkerStyle(kFullTriangleDown);
   hAccEleEE->SetMarkerColor(kBlue);
   hAccEleEE->SetLineColor(kBlue);
   hAccEleEE->Draw("same");
   hAccMu->SetMarkerStyle(34);
   hAccMu->SetMarkerColor(kGreen+1);
   hAccMu->SetLineColor(kGreen+1);
   hAccMu->Draw("same");
   hAcc->Draw("same");
   TLegend* accLegend = (TLegend*)legend->Clone("accLegend");
   accLegend->Clear();
   accLegend->AddEntry(hAcc, "total acceptance");
   accLegend->AddEntry(hAccMu, "muons");
   accLegend->AddEntry(hAccEle, "all electrons");
   accLegend->AddEntry(hAccEleEB, "barrel electrons");
   accLegend->AddEntry(hAccEleEE, "endcap electrons");
   accLegend->Draw("same");
   tex->DrawLatex(0.109, 0.935, "CMS Simulation, 8 TeV");

   // reco with trg vs. reco
   TCanvas *trgRecoVsRecoPlot = new TCanvas("trgRecoVsRecoPlot", "reco with trg vs. reco", 100, 100, 600, 600);
   TPad *trgRecoVsRecoPad = (TPad*)accTimesEffPad->Clone("trgRecoVsRecoPad");
   trgRecoVsRecoPad->Draw(); 
   trgRecoVsRecoPad->cd();
   hTrgRecoVsRecoEle->GetYaxis()->SetTitle("eff");
   hTrgRecoVsRecoEle->GetYaxis()->SetRangeUser(0., 1.);
   hTrgRecoVsRecoEle->SetMarkerStyle(kFullSquare);
   hTrgRecoVsRecoEle->SetMarkerColor(kViolet);
   hTrgRecoVsRecoEle->SetLineColor(kViolet);
   hTrgRecoVsRecoEle->Draw();
   //hTrgRecoVsRecoEleEB->SetMarkerStyle(kFullTriangleUp);
   //hTrgRecoVsRecoEleEB->SetMarkerColor(kRed);
   //hTrgRecoVsRecoEleEB->SetLineColor(kRed);
   //hTrgRecoVsRecoEleEB->Draw("same");
   //hTrgRecoVsRecoEleEE->SetMarkerStyle(kFullTriangleDown);
   //hTrgRecoVsRecoEleEE->SetMarkerColor(kBlue);
   //hTrgRecoVsRecoEleEE->SetLineColor(kBlue);
   //hTrgRecoVsRecoEleEE->Draw("same");
   hTrgRecoVsRecoMu->SetMarkerStyle(34);
   hTrgRecoVsRecoMu->SetMarkerColor(kGreen+1);
   hTrgRecoVsRecoMu->SetLineColor(kGreen+1);
   hTrgRecoVsRecoMu->Draw("same");
   hTrgRecoVsReco->Draw("same");
   TLegend* trgRecoVsRecoLegend = (TLegend*)legend->Clone("trgRecoVsRecoLegend");
   trgRecoVsRecoLegend->Clear();
   trgRecoVsRecoLegend->AddEntry(hTrgRecoVsReco, "total");
   trgRecoVsRecoLegend->AddEntry(hTrgRecoVsRecoMu, "muons");
   trgRecoVsRecoLegend->AddEntry(hTrgRecoVsRecoEle, "electrons");
   //trgRecoVsRecoLegend->AddEntry(hTrgRecoVsRecoEleEB, "barrel electrons");
   //trgRecoVsRecoLegend->AddEntry(hTrgRecoVsRecoEleEE, "endcap electrons");
   trgRecoVsRecoLegend->Draw("same");
   tex->DrawLatex(0.109, 0.935, "CMS Simulation, 8 TeV");

   TCanvas *accTimesTrgEffPlot = new TCanvas("accTimesTrgEffPlot", "acc x trigger eff", 100, 100, 600, 600);
   TPad *accTimesTrgEffPad = (TPad*)accTimesEffPad->Clone("accTimesTrgEffPad");
   accTimesTrgEffPad->Draw(); 
   accTimesTrgEffPad->cd();
   hAccTimesTrgEff->GetYaxis()->SetTitle("acc x trg eff");
   hAccTimesTrgEff->GetYaxis()->SetRangeUser(0., 1.);
   hAccTimesTrgEff->SetMarkerStyle(20);
   hAccTimesTrgEff->SetMarkerColor(kCyan);
   hAccTimesTrgEff->SetLineColor(kCyan);
   hAccTimesTrgEff->Draw();
   hTrgEff->SetMarkerStyle(21);
   hTrgEff->SetMarkerColor(kMagenta);
   hTrgEff->SetLineColor(kMagenta);
   hTrgEff->Draw("same");
   TLegend* trgLegend = (TLegend*)legend->Clone("trgLegend");
   trgLegend->Clear();
   trgLegend->AddEntry(hTrgEff, "trigger eff in acc");
   trgLegend->AddEntry(hAccTimesTrgEff, "acc x trigger eff");
   trgLegend->Draw("same");
   tex->DrawLatex(0.109, 0.935, "CMS Simulation, 8 TeV");

   // safe in various file formats
   if (saveSpec) {
     if (saveAsPdf) {
        accTimesTrgEffPlot->Print(plotDir + accTimesTrgEffPlot->GetName() + ".pdf", "pdf");
        accTimesEffPlot->Print(plotDir + accTimesEffPlot->GetName() + ".pdf", "pdf");
        accTimesEffPlotEB->Print(plotDir + accTimesEffPlotEB->GetName() + ".pdf", "pdf");
        accTimesEffPlotEE->Print(plotDir + accTimesEffPlotEE->GetName() + ".pdf", "pdf");
        accTimesEffObjPlot->Print(plotDir + accTimesEffObjPlot->GetName() + ".pdf", "pdf");
        accTimesEffNoTrgObjPlot->Print(plotDir + accTimesEffNoTrgObjPlot->GetName() + ".pdf", "pdf");
        effAftTrgPlot->Print(plotDir + effAftTrgPlot->GetName() + ".pdf", "pdf");
        trgRecoVsRecoPlot->Print(plotDir + trgRecoVsRecoPlot->GetName() + ".pdf", "pdf");
        accPlot->Print(plotDir + accPlot->GetName() + ".pdf", "pdf");
     }
     if (saveAsPng) {
        accTimesTrgEffPlot->Print(plotDir + accTimesTrgEffPlot->GetName() + ".png", "png");
        accTimesEffPlot->Print(plotDir + accTimesEffPlot->GetName() + ".png", "png");
        accTimesEffPlotEB->Print(plotDir + accTimesEffPlotEB->GetName() + ".png", "png");
        accTimesEffPlotEE->Print(plotDir + accTimesEffPlotEE->GetName() + ".png", "png");
        accTimesEffObjPlot->Print(plotDir + accTimesEffObjPlot->GetName() + ".png", "png");
        accTimesEffNoTrgObjPlot->Print(plotDir + accTimesEffNoTrgObjPlot->GetName() + ".png", "png");
        effAftTrgPlot->Print(plotDir + effAftTrgPlot->GetName() + ".png", "png");
        trgRecoVsRecoPlot->Print(plotDir + trgRecoVsRecoPlot->GetName() + ".png", "png");
        accPlot->Print(plotDir + accPlot->GetName() + ".png", "png");
     }
     if (saveAsRoot) {
        accTimesTrgEffPlot->Print(plotDir + accTimesTrgEffPlot->GetName() + ".root", "root");
        accTimesEffPlot->Print(plotDir + accTimesEffPlot->GetName() + ".root", "root");
        accTimesEffPlotEB->Print(plotDir + accTimesEffPlotEB->GetName() + ".root", "root");
        accTimesEffPlotEE->Print(plotDir + accTimesEffPlotEE->GetName() + ".root", "root");
        accTimesEffObjPlot->Print(plotDir + accTimesEffObjPlot->GetName() + ".root", "root");
        accTimesEffNoTrgObjPlot->Print(plotDir + accTimesEffNoTrgObjPlot->GetName() + ".root", "root");
        effAftTrgPlot->Print(plotDir + effAftTrgPlot->GetName() + ".root", "root");
        trgRecoVsRecoPlot->Print(plotDir + trgRecoVsRecoPlot->GetName() + ".root", "root");
        accPlot->Print(plotDir + accPlot->GetName() + ".root", "root");
     }
   }

   // write histos to file
   output->cd();
   hGenEvts->Write();
   hGenEvtsEleInAcc->Write();
   hGenEvtsEleInAccEB->Write();
   hGenEvtsEleInAccEE->Write();
   hGenEvtsMuInAcc->Write();
   hGenEvtsInAcc->Write();
   hTrgEvts->Write();
   hRecoEvts->Write();
   hRecoEvtsEB->Write();
   hRecoEvtsEE->Write();
   hRecoEleEvts->Write();
   hRecoEleEvtsEB->Write();
   hRecoEleEvtsEE->Write();
   hRecoMuEvts->Write();
   hAccEle->Write();
   hAccEleEB->Write();
   hAccEleEE->Write();
   hAccMu->Write();
   hAccTimesTrgEff->Write();
   hTrgEff->Write();
   hAccTimesEff->Write();
   hAccTimesEffEB->Write();
   hAccTimesEffEE->Write();
   hAccTimesEffEle->Write();
   hAccTimesEffEleEB->Write();
   hAccTimesEffEleEE->Write();
   hAccTimesEffMu->Write();
   hEffAftTrg->Write();
   hEffAftTrgEle->Write();
   hEffAftTrgEleEB->Write();
   hEffAftTrgEleEE->Write();
   hEffAftTrgMu->Write();
   fitFunc->Write();
   fitFuncEB->Write();
   fitFuncEE->Write();

   output->Close();
   timer.Stop();
   timer.Print();
}
Example #9
0
void msugra( char* filename , bool print = false ){
  
  TFile *corfile = new TFile();
  TH2F* hscan    = new TH2F();
  
  if( doCorrection ){
    
    corfile = TFile::Open("mSUGRA_m0-20to2000_m12-20to760_tanb-10andA0-0.root");
    hscan = (TH2F*) corfile->Get("hscan");

    if( hscan == 0 ){
      cout << "Can't find TH2 hscan!!!" << endl;
      exit(0);
    }
  }

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

  //-----------------------------------
  // Here we load the yield histograms
  //-----------------------------------
  TFile *f = TFile::Open( filename );
  
  //TH2F* hyield     = (TH2F*) f->Get("msugra",prefix));
  TH2F* hyield_k   = (TH2F*) f->Get("msugra");
  TH2F* hyield_kup = (TH2F*) f->Get("msugra_kup");
  TH2F* hyield_kdn = (TH2F*) f->Get("msugra_kdn");
  TH2F* hyield_jup = (TH2F*) f->Get("msugra_jup");
  TH2F* hyield_jdn = (TH2F*) f->Get("msugra_jdn");

  hyield_k->  Scale(mylumi);
  hyield_kup->Scale(mylumi);
  hyield_kdn->Scale(mylumi);
  hyield_jup->Scale(mylumi);
  hyield_jdn->Scale(mylumi);

  TH2F* hyield_A; 
  TH2F* hyield_B; 
  TH2F* hyield_C; 
  TH2F* hyield_D; 

  TH2F* hUL_NLO       = (TH2F*) hyield_k->Clone("hUL_NLO");
  TH2F* hUL_NLO_exp   = (TH2F*) hyield_k->Clone("hUL_NLO_exp");
  TH2F* hUL_NLO_expp1 = (TH2F*) hyield_k->Clone("hUL_NLO_expp1");
  TH2F* hUL_NLO_expm1 = (TH2F*) hyield_k->Clone("hUL_NLO_expm1");
  TH2F* hUL_LO        = (TH2F*) hyield_k->Clone("hUL_LO");

  TH1F* htotuncertainty = new TH1F("htotuncertainty","",200,0,2);

  hUL_NLO->Reset();
  hUL_LO->Reset();
  hUL_NLO_exp->Reset();

  const unsigned int nm0bins  = hyield_k->GetXaxis()->GetNbins();
  const unsigned int nm12bins = hyield_k->GetYaxis()->GetNbins();

  //---------------------------------------------------------
  //calculate acceptance error and UL at each scan point
  //---------------------------------------------------------

  float    accerr_NLO[nm0bins][nm12bins];
  Double_t ul_NLO[nm0bins][nm12bins];
  Double_t ul_NLO_SC[nm0bins][nm12bins];
  Double_t ul_NLO_nobkg[nm0bins][nm12bins];
  Double_t ul_NLO_exp[nm0bins][nm12bins];
  Double_t ul_NLO_expp1[nm0bins][nm12bins];
  Double_t ul_NLO_expm1[nm0bins][nm12bins];

  float accerr_LO[nm0bins][nm12bins];
  Double_t ul_LO[nm0bins][nm12bins];

  for( unsigned int m0bin = 1 ; m0bin <= nm0bins ; ++m0bin ){
    for( unsigned int m12bin = 1 ; m12bin <= nm12bins ; ++m12bin ){
      accerr_NLO[m0bin-1][m12bin-1]	= 0.;
      accerr_LO[m0bin-1][m12bin-1]	= 0.;
      ul_NLO[m0bin-1][m12bin-1]		= 9999.;
      ul_NLO_SC[m0bin-1][m12bin-1]	= 9999.;
      ul_NLO_nobkg[m0bin-1][m12bin-1]	= 9999.;
      ul_NLO_exp[m0bin-1][m12bin-1]	= 9999.;
      ul_NLO_expp1[m0bin-1][m12bin-1]   = 9999.;
      ul_NLO_expm1[m0bin-1][m12bin-1]   = 9999.;
      ul_LO[m0bin-1][m12bin-1]		= 9999.;
    }
  }

  //-----------------------------------------------
  // loop over scan points
  //-----------------------------------------------
      
  for( unsigned int m0bin = 1  ; m0bin  <= nm0bins  ; ++m0bin ){
    for( unsigned int m12bin = 1 ; m12bin <= nm12bins ; ++m12bin ){
     
      //---------------------------
      //get yields from TH2's
      //---------------------------
     
      //float yield     = hyield->GetBinContent( m0bin , m12bin );
      float yield_k   = hyield_k->GetBinContent( m0bin , m12bin );
      float yield_kup = hyield_kup->GetBinContent( m0bin , m12bin );
      float yield_kdn = hyield_kdn->GetBinContent( m0bin , m12bin );
      float yield_jup = hyield_jup->GetBinContent( m0bin , m12bin );
      float yield_jdn = hyield_jdn->GetBinContent( m0bin , m12bin );

      int   ngen  = 1;
      float scale = 1.0;

      int m0  = hyield_k->GetXaxis()->GetBinCenter(m0bin);
      int m12 = hyield_k->GetXaxis()->GetBinCenter(m12bin);

      if( doCorrection ){
	ngen = hscan->GetBinContent(m0bin,m12bin);

	if( ngen != 10000 ){
	  cout << "Skipping point with " << ngen << " entries" << endl;
	  continue;
	}
      }
     
      cout << endl << endl << "------------------------------------------------------------------------" << endl;
      cout << endl << "m0 " << m0bin-1 << " m12 " << m12bin-1 << endl;
      cout << hyield_k->GetXaxis()->GetBinCenter(m0bin) << " " << hyield_k->GetYaxis()->GetBinCenter(m12bin) << endl;

      //------------------------
      // skip bins with 0 yield
      //------------------------
     
      if( fabs( yield_k ) < 1.e-10 ){
	cout << "zero yield, skipping!" << endl;
	continue; 
      }

      //--------------------------
      //uncertainty from k-factor
      //--------------------------

      float kerr_up   = fabs( ( yield_kup - yield_k ) / yield_k );
      float kerr_dn   = fabs( ( yield_kdn - yield_k ) / yield_k );
      float kerr      = TMath::Max( kerr_up , kerr_dn );

      //--------------------------     
      //uncertainty from JES
      //--------------------------

      float jerr_up   = fabs( ( yield_jup - yield_k ) / yield_k );
      float jerr_dn   = fabs( ( yield_jdn - yield_k ) / yield_k );
      float jerr      = TMath::Max( jerr_up , jerr_dn );
     
      //-----------------------------------------------------------
      //add up NLO uncertainties (including k-factor uncertainty)
      //-----------------------------------------------------------

      float err2_NLO = 0.;
      err2_NLO += kerr * kerr;                                              //k-factor
      err2_NLO += jerr * jerr;                                              //JES
      err2_NLO += lumierr * lumierr;                                        //lumi
      err2_NLO += leperr * leperr;                                          //lep efficiency
      err2_NLO += pdferr * pdferr;                                          //PDF uncertainty
      accerr_NLO[m0bin-1][m12bin-1] = err2_NLO > 0 ? sqrt( err2_NLO ) : 0.; //total

      if( yield_k > 5 && yield_k < 8 )
	htotuncertainty->Fill( accerr_NLO[m0bin-1][m12bin-1] );

      ul_NLO[m0bin-1][m12bin-1]       = getUpperLimit          ( accerr_NLO[m0bin-1][m12bin-1] );
      ul_NLO_exp[m0bin-1][m12bin-1]   = getExpectedUpperLimit  ( accerr_NLO[m0bin-1][m12bin-1] );
      ul_NLO_expp1[m0bin-1][m12bin-1] = getExpectedP1UpperLimit( accerr_NLO[m0bin-1][m12bin-1] );
      ul_NLO_expm1[m0bin-1][m12bin-1] = getExpectedM1UpperLimit( accerr_NLO[m0bin-1][m12bin-1] );

      //--------------------------
      //printout errors and UL
      //--------------------------
     
      //cout << "yield            " << yield   << endl;
      cout << "yield * K        " << yield_k << endl;
      cout << "yield * Kup      " << yield_kup << endl;
      cout << "yield * Kdn      " << yield_kdn << endl;
      cout << "yield * JESup    " << yield_jup << endl;
      cout << "yield * JESdn    " << yield_jdn << endl;
      cout << "K error          " << kerr << endl;
      cout << "JES error        " << jerr << endl;
      cout << "total error NLO  " << accerr_NLO[m0bin-1][m12bin-1] << endl;
      cout << "NLO UL           " << ul_NLO[m0bin-1][m12bin-1] << endl;
      cout << "NLO UL sig cont  " << ul_NLO_SC[m0bin-1][m12bin-1] << endl;
      cout << "NLO UL no bkg    " << ul_NLO_nobkg[m0bin-1][m12bin-1] << endl;
      cout << "NLO UL exp       " << ul_NLO_exp[m0bin-1][m12bin-1] << endl;
     
      hUL_NLO->SetBinContent( m0bin , m12bin , ul_NLO[m0bin-1][m12bin-1] );
      hUL_NLO_exp->SetBinContent( m0bin , m12bin , ul_NLO_exp[m0bin-1][m12bin-1] );
      hUL_NLO_expp1->SetBinContent( m0bin , m12bin , ul_NLO_expp1[m0bin-1][m12bin-1] );
      hUL_NLO_expm1->SetBinContent( m0bin , m12bin , ul_NLO_expm1[m0bin-1][m12bin-1] );
    }
  }

  cout << __LINE__ << endl;
  //--------------------------------------------------------------------------------------------------------
  // at this point we have calculated the yields and upper limits at each point
  // next step is to build TH2 histos (ie. hexcl_NLO_obs) which are 1 if point is excluded, otherwise 0
  //--------------------------------------------------------------------------------------------------------
 
  float xmin = hyield_k->GetXaxis()->GetXmin();
  float xmax = hyield_k->GetXaxis()->GetXmax();
  float ymin = hyield_k->GetYaxis()->GetXmin();
  float ymax = hyield_k->GetYaxis()->GetXmax();
  int nx     = hyield_k->GetXaxis()->GetNbins();
  int ny     = hyield_k->GetYaxis()->GetNbins();

  TH2I* hexcl_NLO_obs       = new TH2I("hexcl_NLO_obs",       "Observed NLO Exclusion",nx,xmin,xmax,ny,ymin,ymax);
  TH2I* hexcl_NLO_obs_SC    = new TH2I("hexcl_NLO_obs_SC",    "Observed NLO Exclusion (Sig Cont)",nx,xmin,xmax,ny,ymin,ymax);
  TH2I* hexcl_NLO_obs_nobkg = new TH2I("hexcl_NLO_obs_nobkg", "Observed NLO Exclusion (No Bkg)",nx,xmin,xmax,ny,ymin,ymax);
  TH2I* hexcl_LO_obs        = new TH2I("hexcl_LO_obs",        "Observed LO Exclusion", nx,xmin,xmax,ny,ymin,ymax);
  TH2I* hexcl_NLO_exp       = new TH2I("hexcl_NLO_exp",       "Expected NLO Exclusion",nx,xmin,xmax,ny,ymin,ymax);
  TH2I* hexcl_NLO_expp1     = new TH2I("hexcl_NLO_expp1",     "Expected(+1) NLO Exclusion",nx,xmin,xmax,ny,ymin,ymax);
  TH2I* hexcl_NLO_expm1     = new TH2I("hexcl_NLO_expm1",     "Expected(-1) NLO Exclusion",nx,xmin,xmax,ny,ymin,ymax);

  for( unsigned int m0bin  = 1 ; m0bin  <= nm0bins  ; ++m0bin  ){
    for( unsigned int m12bin = 1 ; m12bin <= nm12bins ; ++m12bin ){

      hexcl_NLO_obs->SetBinContent( m0bin , m12bin , 0 );
      hexcl_NLO_obs_SC->SetBinContent( m0bin , m12bin , 0 );
      hexcl_NLO_obs_nobkg->SetBinContent( m0bin , m12bin , 0 );
      hexcl_LO_obs->SetBinContent( m0bin , m12bin , 0 );
      hexcl_NLO_exp->SetBinContent( m0bin , m12bin , 0 );
      hexcl_NLO_expp1->SetBinContent( m0bin , m12bin , 0 );
      hexcl_NLO_expm1->SetBinContent( m0bin , m12bin , 0 );

      if( doCorrection ){

	int ngen = hscan->GetBinContent(m0bin,m12bin);

	if( ngen != 10000 ){
	  hexcl_NLO_obs->SetBinContent( m0bin , m12bin , 2 );
	  hexcl_NLO_exp->SetBinContent( m0bin , m12bin , 2 );
	  hexcl_NLO_expp1->SetBinContent( m0bin , m12bin , 2 );
	  hexcl_NLO_expm1->SetBinContent( m0bin , m12bin , 2 );
	  continue;
	}
      }

      //---------------------------
      //NLO observed
      //---------------------------

      int excluded_NLO_obs = 0;
      if( hyield_k->GetBinContent( m0bin , m12bin ) > ul_NLO[m0bin-1][m12bin-1] ) excluded_NLO_obs = 1;
      hexcl_NLO_obs->SetBinContent( m0bin , m12bin , excluded_NLO_obs );

      //---------------------------
      //NLO observed (sig cont)
      //---------------------------

      int excluded_NLO_obs_SC = 0;
      if( doABCD ){
	if( hyield_k->GetBinContent( m0bin , m12bin ) > ul_NLO_SC[m0bin-1][m12bin-1] ) excluded_NLO_obs_SC = 1;
	hexcl_NLO_obs_SC->SetBinContent( m0bin , m12bin , excluded_NLO_obs_SC );
      }

      //---------------------------
      //NLO observed (nobkg)
      //---------------------------

      int excluded_NLO_obs_nobkg = 0;
      if( hyield_k->GetBinContent( m0bin , m12bin ) > ul_NLO_nobkg[m0bin-1][m12bin-1] ) excluded_NLO_obs_nobkg = 1;
      hexcl_NLO_obs_nobkg->SetBinContent( m0bin , m12bin , excluded_NLO_obs_nobkg );

      //---------------------------
      //NLO expected
      //---------------------------

      int excluded_NLO_exp = 0;
      if( hyield_k->GetBinContent( m0bin , m12bin ) > ul_NLO_exp[m0bin-1][m12bin-1] ) excluded_NLO_exp = 1;
      hexcl_NLO_exp->SetBinContent( m0bin , m12bin , excluded_NLO_exp );

      //---------------------------
      //NLO expected(+1)
      //---------------------------

      int excluded_NLO_expp1 = 0;
      if( hyield_k->GetBinContent( m0bin , m12bin ) > ul_NLO_expp1[m0bin-1][m12bin-1] ) excluded_NLO_expp1 = 1;
      hexcl_NLO_expp1->SetBinContent( m0bin , m12bin , excluded_NLO_expp1 );

      //---------------------------
      //NLO expected(-1)
      //---------------------------

      int excluded_NLO_expm1 = 0;
      if( hyield_k->GetBinContent( m0bin , m12bin ) > ul_NLO_expm1[m0bin-1][m12bin-1] ) excluded_NLO_expm1 = 1;
      hexcl_NLO_expm1->SetBinContent( m0bin , m12bin , excluded_NLO_expm1 );

      //---------------------------
      //print out stuff
      //---------------------------

      if( hyield_k->GetBinContent( m0bin , m12bin ) > 0. ){
     
	cout << endl << "m0 " << m0bin-1 << " m12 " << m12bin-1 << endl;
	cout << "NLO Yield     " << hyield_k->GetBinContent( m0bin , m12bin ) << endl;
       
	cout << "NLO UL        " << ul_NLO[m0bin-1][m12bin-1] << endl;
	cout << "Excluded?     " << excluded_NLO_obs << endl;
       
	cout << "NLO UL SC     " << ul_NLO_SC[m0bin-1][m12bin-1] << endl;
	cout << "Excluded?     " << excluded_NLO_obs_SC << endl;

	cout << "NLO UL no bkg " << ul_NLO_nobkg[m0bin-1][m12bin-1] << endl;
	cout << "Excluded?     " << excluded_NLO_obs_nobkg << endl;

	cout << "NLO UL exp    " << ul_NLO_exp[m0bin-1][m12bin-1] << endl;
	cout << "Excluded?     " << excluded_NLO_exp << endl;
       
	// cout << "LO UL         " << ul_LO[m0bin-1][m12bin-1] << endl;
	// cout << "Excluded?     " << excluded_LO_obs << endl;
       
      }
    }
  }


  //----------------------------------------------------------------------------------------
  // these objects specify the exclusion contours, they are built from the hexcl_* histos
  //----------------------------------------------------------------------------------------

  TH1F*         limit_NLO_obs			= getCurve(        hexcl_NLO_obs	, "limit_NLO_obs");
  TGraphErrors* limitgraph_NLO_obs		= getCurve_TGraph( hexcl_NLO_obs	, "limitgraph_NLO_obs");

  TH1F*         limit_NLO_obs_SC		= getCurve(        hexcl_NLO_obs_SC	, "limit_NLO_obs_SC");
  TGraphErrors* limitgraph_NLO_obs_SC		= getCurve_TGraph( hexcl_NLO_obs_SC	, "limitgraph_NLO_obs_SC");

  TH1F*         limit_NLO_obs_nobkg		= getCurve(        hexcl_NLO_obs_nobkg	, "limit_NLO_obs_nobkg");
  TGraphErrors* limitgraph_NLO_obs_nobkg	= getCurve_TGraph( hexcl_NLO_obs_nobkg	, "limitgraph_NLO_obs_nobkg");

  TH1F*         limit_NLO_exp			= getCurve(        hexcl_NLO_exp	, "limit_NLO_exp");
  TGraphErrors* limitgraph_NLO_exp		= getCurve_TGraph( hexcl_NLO_exp	, "limitgraph_NLO_exp");

  TH1F*         limit_NLO_expp1			= getCurve(        hexcl_NLO_expp1	, "limit_NLO_expp1");
  TGraphErrors* limitgraph_NLO_expp1		= getCurve_TGraph( hexcl_NLO_expp1	, "limitgraph_NLO_expp1");

  TH1F*         limit_NLO_expm1			= getCurve(        hexcl_NLO_expm1	, "limit_NLO_expm1");
  TGraphErrors* limitgraph_NLO_expm1		= getCurve_TGraph( hexcl_NLO_expm1	, "limitgraph_NLO_expm1");

  TH1F*         limit_LO_obs			= getCurve(        hexcl_LO_obs		, "limit_LO_obs");
  TGraphErrors* limitgraph_LO_obs		= getCurve_TGraph( hexcl_LO_obs		, "limitgraph_LO_obs");

  //----------------------------------
  // now draw a bunch of plots
  //----------------------------------

  TLatex *t = new TLatex();
  t->SetNDC();

  bool overlayTGraph = false;

  TCanvas *c1 = new TCanvas("c1","c1",1000,800);
  c1->cd();
  gPad->SetRightMargin(0.2);
  gPad->SetTopMargin(0.1);
  hexcl_NLO_obs->GetXaxis()->SetTitle("m_{0} (GeV)");
  hexcl_NLO_obs->GetYaxis()->SetTitle("m_{1/2} (GeV)");
  hexcl_NLO_obs->GetXaxis()->SetNdivisions(5);
  hexcl_NLO_obs->Draw("colz");
  t->DrawLatex(0.2,0.92,"observed NLO");
  if( overlayTGraph ){
    TGraphErrors* gr_NLO_obs = getCurve_TGraph( hexcl_NLO_obs , "gr_NLO_obs" );
    gr_NLO_obs->Draw("same");
  }

  TCanvas *c2 = new TCanvas("c2","c2",1000,800);
  c2->cd();
  gPad->SetRightMargin(0.2);
  gPad->SetTopMargin(0.1);
  hexcl_NLO_exp->GetXaxis()->SetTitle("m_{0} (GeV)");
  hexcl_NLO_exp->GetYaxis()->SetTitle("m_{1/2} (GeV)");
  hexcl_NLO_exp->GetXaxis()->SetNdivisions(5);
  hexcl_NLO_exp->Draw("colz");
  t->DrawLatex(0.2,0.92,"expected NLO");
 
  TCanvas *c3 = new TCanvas("c3","c3",1000,800);
  c3->cd();
  gPad->SetRightMargin(0.2);
  gPad->SetTopMargin(0.1);
  hexcl_NLO_expp1->GetXaxis()->SetTitle("m_{0} (GeV)");
  hexcl_NLO_expp1->GetYaxis()->SetTitle("m_{1/2} (GeV)");
  hexcl_NLO_expp1->GetXaxis()->SetNdivisions(5);
  hexcl_NLO_expp1->Draw("colz");
  t->DrawLatex(0.2,0.92,"expected(+1) NLO");

  TCanvas *c4 = new TCanvas("c4","c4",1000,800);
  c4->cd(1);
  gPad->SetRightMargin(0.2);
  gPad->SetTopMargin(0.1);
  hexcl_NLO_expm1->GetXaxis()->SetTitle("m_{0} (GeV)");
  hexcl_NLO_expm1->GetYaxis()->SetTitle("m_{1/2} (GeV)");
  hexcl_NLO_expm1->GetXaxis()->SetNdivisions(5);
  hexcl_NLO_expm1->Draw("colz");
  t->DrawLatex(0.2,0.92,"expected(-1) NLO");
 
  if( print ){
    c1->Print("../../plots/exclusion_obs.png");
    c2->Print("../../plots/exclusion_exp.png");
    c3->Print("../../plots/exclusion_expp1.png");
    c4->Print("../../plots/exclusion_expm1.png");

    c1->Print("../../plots/exclusion_obs.eps");
    c2->Print("../../plots/exclusion_exp.eps");
    c3->Print("../../plots/exclusion_expp1.eps");
    c4->Print("../../plots/exclusion_expm1.eps");

    gROOT->ProcessLine(".! ps2pdf ../../plots/exclusion_obs.eps   ../../plots/exclusion_obs.pdf");
    gROOT->ProcessLine(".! ps2pdf ../../plots/exclusion_exp.eps   ../../plots/exclusion_exp.pdf");
    gROOT->ProcessLine(".! ps2pdf ../../plots/exclusion_expp1.eps ../../plots/exclusion_expp1.pdf");
    gROOT->ProcessLine(".! ps2pdf ../../plots/exclusion_expm1.eps ../../plots/exclusion_expm1.pdf");
  }


  /*
  //exclusion TH1
  TCanvas *c2 = new TCanvas("c2","",800,600);
  c2->cd();

  limit_NLO_obs->SetMinimum(90.);
  limit_NLO_obs->SetTitle("Exclusion Curve in mSUGRA Space");
  limit_NLO_obs->GetXaxis()->SetTitle("m_{0} (GeV)");
  limit_NLO_obs->GetYaxis()->SetTitle("m_{1/2} (GeV)");
  //limit_NLO_obs->SetLineWidth(2);
  //limit_NLO_obs->SetLineColor(2);
  limit_NLO_obs->GetXaxis()->SetRangeUser(0,500);
  limit_NLO_obs->GetYaxis()->SetRangeUser(100,400);
  //limit_NLO_obs->Draw("c");
  limit_NLO_obs->Draw();
  limit_LO_obs->SetLineColor(2);
  limit_NLO_exp->SetLineColor(4);
  limit_LO_obs->Draw("same");
  limit_NLO_exp->Draw("same");

  TLegend *leg = new TLegend(0.6,0.6,0.8,0.8);
  leg->AddEntry(limit_NLO_obs, "NLO obs","l");
  leg->AddEntry(limit_LO_obs,  "LO obs","l");
  leg->AddEntry(limit_NLO_exp, "NLO exp","l");
  leg->SetBorderSize(1);
  leg->SetFillColor(0);
  leg->Draw();

  c2->Print("exclusion/limit_hist.png");

  TCanvas *c3 = new TCanvas("c3","",800,600);
  c3->cd();

  limitgraph_LO_obs->SetMarkerColor(2);
  limitgraph_NLO_exp->SetMarkerColor(4);
  limitgraph_NLO_obs->Draw("AP");
  limitgraph_LO_obs->Draw("sameP");
  limitgraph_NLO_exp->Draw("sameP");
  leg->Draw();

  c3->Print("exclusion/limit_graph.png");
  */

  outfile->cd();

  hexcl_NLO_obs->Write();
  limit_NLO_obs->Write();
  limitgraph_NLO_obs->Write();

  hexcl_NLO_obs_SC->Write();
  limit_NLO_obs_SC->Write();
  limitgraph_NLO_obs_SC->Write();

  hexcl_NLO_obs_nobkg->Write();
  limit_NLO_obs_nobkg->Write();
  limitgraph_NLO_obs_nobkg->Write();

  hexcl_LO_obs->Write();
  limit_LO_obs->Write();
  limitgraph_LO_obs->Write();

  hexcl_NLO_exp->Write();
  hexcl_NLO_expp1->Write();
  hexcl_NLO_expm1->Write();
  limit_NLO_exp->Write();
  limitgraph_NLO_exp->Write();

  hUL_NLO->Write();
  hUL_NLO_exp->Write();
  hUL_NLO_expp1->Write();
  hUL_NLO_expm1->Write();
  hUL_LO->Write();
  hyield_k->Write();

  htotuncertainty->Write();
  outfile->Close();
 
}
void DrawCalibrationPlotsEB( Char_t* infile1 = "/data1/rgerosa/L3_Weight/PromptSkim_Single_Double_Electron_recoFlag/EB/WZAnalysis_PromptSkim_W-DoubleElectron_FT_R_42_V21B_Z_noEP.root",
			    Char_t* infile2 = "/data1/rgerosa/L3_Weight/PromptSkim_Single_Double_Electron_recoFlag/EB/Even_WZAnalysis_PromptSkim_W-DoubleElectron_FT_R_42_V21B_Z_noEP.root",
			    Char_t* infile3 = "/data1/rgerosa/L3_Weight/PromptSkim_Single_Double_Electron_recoFlag/EB/Odd_WZAnalysis_PromptSkim_W-DoubleElectron_FT_R_42_V21B_Z_noEP.root",
			    int evalStat = 0,
			    Char_t* fileType = "png", 
			    Char_t* dirName = ".")
{

  bool  printPlots = false;

  // by TT
  int nbins = 500;

  // by xtal
  //int nbins = 500;

  // Set style options
  gROOT->Reset();
  gROOT->SetStyle("Plain");

  gStyle->SetPadTickX(1);
  gStyle->SetPadTickY(1);
  gStyle->SetOptTitle(0); 
  gStyle->SetOptStat(1110); 
  gStyle->SetOptFit(0); 
  gStyle->SetFitFormat("6.3g"); 
  gStyle->SetPalette(1); 
 
  gStyle->SetTextFont(42);
  gStyle->SetTextSize(0.05);
  gStyle->SetTitleFont(42,"xyz");
  gStyle->SetTitleSize(0.05);
  gStyle->SetLabelFont(42,"xyz");
  gStyle->SetLabelSize(0.05);
  gStyle->SetTitleXOffset(0.8);
  gStyle->SetTitleYOffset(1.1);
  gROOT->ForceStyle();

  if ( !infile1 ) {
    cout << " No input file specified !" << endl;
    return;
  }


  if ( evalStat && (!infile2 || !infile3 )){
    cout << " No input files to evaluate statistical precision specified !" << endl;
    return;
  }

  cout << "Making calibration plots for: " << infile1 << endl;
  
  TFile *f = new TFile(infile1);
  TH2F *h_scale_EB = (TH2F*)f->Get("h_scale_EB");
  TH2F *hcmap = (TH2F*) h_scale_EB->Clone("hcmap");
  hcmap -> Reset("ICEMS");

  // Mean over phi 

  for (int iEta = 1 ; iEta < h_scale_EB->GetNbinsY()+1 ; iEta ++)
  {
   float SumIC = 0;
   int numIC = 0;
   
   for(int iPhi = 1 ; iPhi < h_scale_EB->GetNbinsX()+1 ; iPhi++)
   {
    if( h_scale_EB->GetBinContent(iPhi,iEta) !=0)
    {
      SumIC = SumIC + h_scale_EB->GetBinContent(iPhi,iEta);
      numIC ++ ;
    }
   }
   
   for (int iPhi = 1; iPhi< h_scale_EB->GetNbinsX()+1  ; iPhi++)
   {
    if(numIC!=0 && SumIC!=0)
    hcmap->SetBinContent(iPhi,iEta,h_scale_EB->GetBinContent(iPhi,iEta)/(SumIC/numIC));
   }
  }
  

  
  //-----------------------------------------------------------------
  //--- Build the precision vs ieta plot starting from the TH2F of IC
  //-----------------------------------------------------------------
  TH1F *hoccall = new TH1F("hoccall", "hoccall", 1000,0.,1000.);
  for (int jbin = 1; jbin < h_occupancy-> GetNbinsY()+1; jbin++){
    for (int ibin = 1; ibin < h_occupancy-> GetNbinsX()+1; ibin++){
      float ic = h_occupancy->GetBinContent(ibin,jbin);
      	hoccall->Fill(ic);
    }
  }

  TH1F *hspreadall = new TH1F("hspreadall", "hspreadall", 800,0.,2.);
  for (int jbin = 1; jbin < hcmap-> GetNbinsY()+1; jbin++){
    for (int ibin = 1; ibin < hcmap-> GetNbinsX()+1; ibin++){
      float ic = hcmap->GetBinContent(ibin,jbin);
      if (ic>0 && ic<2 && ic !=1)    {
	hspreadall->Fill(ic);
      }
    }
  }

  
  TH1F *hspread[172];
  char hname[100];
  char htitle[100];
  
  for (int jbin = 1; jbin < hcmap-> GetNbinsY()+1; jbin++){
    //float etaring = hcmap-> GetYaxis()->GetBinLowEdge(jbin);
    float etaring = hcmap-> GetYaxis()->GetBinCenter(jbin);
    sprintf(hname,"hspread_ring_ieta%02d",etaring);
    hspread[jbin-1]= new TH1F(hname, hname, nbins/2,0.5,1.5);
    for (int ibin = 1; ibin < hcmap-> GetNbinsX()+1; ibin++){
      float ic = hcmap->GetBinContent(ibin,jbin);
      if (ic>0 && ic<2 && ic!=1)    {
	hspread[jbin-1]->Fill(ic);
      }
    }
  }
  
  TGraphErrors *sigma_vs_ieta = new TGraphErrors();
  sigma_vs_ieta->SetMarkerStyle(20);
  sigma_vs_ieta->SetMarkerSize(1);
  sigma_vs_ieta->SetMarkerColor(kBlue+2);
  
  TGraphErrors *scale_vs_ieta = new TGraphErrors();
  scale_vs_ieta->SetMarkerStyle(20);
  scale_vs_ieta->SetMarkerSize(1);
  scale_vs_ieta->SetMarkerColor(kBlue+2);
  
  TF1 *fgaus = new TF1("fgaus","gaus",-10,10);
  int np = 0;
  for (int i = 1; i < hcmap-> GetNbinsY()+1; i++){
    float etaring = hcmap-> GetYaxis()->GetBinCenter(i);
    //float etaring = hcmap-> GetYaxis()->GetBinLowEdge(i);
    if (int(etaring)==0) continue;
    if (hspread[i-1]-> GetEntries() == 0) continue;
    if (fabs(etaring) > 60) hspread[i-1]->Rebin(2);
    float e     = 0.5*hcmap-> GetYaxis()->GetBinWidth(i);
    fgaus->SetParameter(1,1);
    fgaus->SetParameter(2,hspread[i-1]->GetRMS());
    fgaus->SetRange(1-5*hspread[i-1]->GetRMS(),1+5*hspread[i-1]->GetRMS());
    hspread[i-1]->Fit("fgaus","QR");
    sigma_vs_ieta-> SetPoint(np,etaring,fgaus->GetParameter(2)/fgaus->GetParameter(1));
    //cout << etaring << "  " << fgaus->GetParameter(2)/fgaus->GetParameter(1) << endl;
    sigma_vs_ieta-> SetPointError(np, e ,fgaus->GetParError(2)/fgaus->GetParameter(1));
    scale_vs_ieta-> SetPoint(np,etaring,fgaus->GetParameter(1));
    scale_vs_ieta-> SetPointError(np,e,fgaus->GetParError(1));
    np++;
    
  }
  
  
  if (evalStat){
  TFile *f2 = new TFile(infile2);
  TH2F *h_scale_EB_2 = (TH2F*)f2->Get("h_scale_EB");
  TH2F *hcmap2 = (TH2F*) h_scale_EB->Clone("hcmap2");
  hcmap2 -> Reset("ICEMS");

  // Mean over phi 

  for (int iEta = 1 ; iEta < h_scale_EB_2->GetNbinsY()+1 ; iEta ++)
  {
   float SumIC = 0;
   int numIC = 0;
   
   for(int iPhi = 1 ; iPhi < h_scale_EB_2->GetNbinsX()+1 ; iPhi++)
   {
    if( h_scale_EB_2->GetBinContent(iPhi,iEta) !=0)
    {
      SumIC = SumIC + h_scale_EB_2->GetBinContent(iPhi,iEta);
      numIC ++ ;
    }
   }
   
   for (int iPhi = 1; iPhi< h_scale_EB_2->GetNbinsX()+1  ; iPhi++)
   {
    if(numIC!=0 && SumIC!=0)
    hcmap2->SetBinContent(iPhi,iEta,h_scale_EB_2->GetBinContent(iPhi,iEta)/(SumIC/numIC));
   }
  }
 

  TFile *f3 = new TFile(infile3);
  TH2F *h_scale_EB_3 = (TH2F*)f3->Get("h_scale_EB");
  TH2F *hcmap3 = (TH2F*) h_scale_EB->Clone("hcmap3");
  hcmap3 -> Reset("ICEMS");

  // Mean over phi 

  for (int iEta = 1 ; iEta < h_scale_EB_3->GetNbinsY()+1 ; iEta ++)
  {
   float SumIC = 0;
   int numIC = 0;
   
   for(int iPhi = 1 ; iPhi < h_scale_EB_3->GetNbinsX()+1 ; iPhi++)
   {
    if( h_scale_EB_3->GetBinContent(iPhi,iEta) !=0)
    {
      SumIC = SumIC + h_scale_EB_3->GetBinContent(iPhi,iEta);
      numIC ++ ;
    }
   }
   
   for (int iPhi = 1; iPhi< h_scale_EB_3->GetNbinsX()+1  ; iPhi++)
  {
    if(numIC!=0 && SumIC!=0)
    hcmap3->SetBinContent(iPhi,iEta,h_scale_EB_3->GetBinContent(iPhi,iEta)/(SumIC/numIC));
  }
  }

    TH1F *hstatprecision[171];
    
    for (int jbin = 1; jbin < hcmap2-> GetNbinsY()+1; jbin++){
      //int etaring = -85+(jbin-1);
      float etaring = hcmap2-> GetYaxis()->GetBinCenter(jbin);
      sprintf(hname,"hstatprecision_ring_ieta%02d",etaring);
      hstatprecision[jbin-1] = new TH1F(hname, hname, nbins,-0.5,0.5);
      for (int ibin = 1; ibin < hcmap2-> GetNbinsX()+1; ibin++){
	float ic1 = hcmap2->GetBinContent(ibin,jbin);
	float ic2 = hcmap3->GetBinContent(ibin,jbin);
	if (ic1>0 && ic1<2 && ic1!=1 && ic2>0 && ic2 <2 && ic2!=1){
	  hstatprecision[jbin-1]->Fill((ic1-ic2)/(ic1+ic2)); // sigma (diff/sum) gives the stat. precision on teh entire sample
	}
      }


    }

    TGraphErrors *statprecision_vs_ieta = new TGraphErrors();
    statprecision_vs_ieta->SetMarkerStyle(20);
    statprecision_vs_ieta->SetMarkerSize(1);
    statprecision_vs_ieta->SetMarkerColor(kRed+2);
   
    int n = 0;
    for (int i = 1; i < hcmap2-> GetNbinsY()+1; i++){
      etaring = hcmap2-> GetYaxis()->GetBinCenter(i);
      //etaring = hcmap2-> GetYaxis()->GetBinLowEdge(i);
      if (etaring==0) continue;
      if ( hstatprecision[i-1]->GetEntries() == 0) continue;
      if (fabs(etaring) > 60)hstatprecision[i-1]->Rebin(2);
      float e     = 0.5*hcmap2-> GetYaxis()->GetBinWidth(i);
      fgaus->SetParameter(1,1);
      fgaus->SetParameter(2,hstatprecision[i-1]->GetRMS());
      fgaus->SetRange(-5*hstatprecision[i-1]->GetRMS(),5*hstatprecision[i-1]->GetRMS());
      hstatprecision[i-1]->Fit("fgaus","QR");
      statprecision_vs_ieta-> SetPoint(n,etaring,fgaus->GetParameter(2));
      statprecision_vs_ieta-> SetPointError(n,e,fgaus->GetParError(2));
      n++;
    }
 
    TGraphErrors *residual_vs_ieta = new TGraphErrors();
    residual_vs_ieta->SetMarkerStyle(20);
    residual_vs_ieta->SetMarkerSize(1);
    residual_vs_ieta->SetMarkerColor(kGreen+2);
    
    

    for (int i= 0; i < statprecision_vs_ieta-> GetN(); i++){
      double spread, espread;
      double stat, estat;
      double residual, eresidual;
      double xdummy,ex;
      sigma_vs_ieta-> GetPoint(i, xdummy, spread );
      espread = sigma_vs_ieta-> GetErrorY(i);
      statprecision_vs_ieta-> GetPoint(i, xdummy, stat );
      estat = statprecision_vs_ieta-> GetErrorY(i);
      ex = statprecision_vs_ieta-> GetErrorX(i);
      if (spread > stat ){
	residual  = sqrt( spread*spread - stat*stat );
	eresidual = sqrt( pow(spread*espread,2) + pow(stat*estat,2))/residual;
      }
      else {
	residual = 0;
	eresidual = 0;
      }
      cout << residual << " " << eresidual << endl;
      residual_vs_ieta->SetPoint(i,xdummy, residual);
      residual_vs_ieta->SetPointError(i,ex,eresidual);


    }
    
  }
  


  //------------------------------------------------------------------------


    
  
  //-----------------------------------------------------------------
  //--- Draw plots
  //-----------------------------------------------------------------
  TCanvas *c[10];

  // --- plot 0 : map of coefficients 
  c[0] = new TCanvas("cmap","cmap");
  c[0] -> cd();
  c[0]->SetLeftMargin(0.1); 
  c[0]->SetRightMargin(0.13); 
  c[0]->SetGridx();
  hcmap->GetXaxis()->SetNdivisions(1020);
  hcmap->GetXaxis() -> SetLabelSize(0.03);
  hcmap->Draw("COLZ");
  hcmap->GetXaxis() ->SetTitle("i#phi");
  hcmap->GetYaxis() ->SetTitle("i#eta");
  hcmap->GetZaxis() ->SetRangeUser(0.9,1.1);
  
  c[7] = new TCanvas("cmap2","cmap2");
  c[7] -> cd();
  c[7]->SetLeftMargin(0.1); 
  c[7]->SetRightMargin(0.13); 
  c[7]->SetGridx();
  h_scale_EB->GetXaxis()->SetNdivisions(1020);
  h_scale_EB->GetXaxis() -> SetLabelSize(0.03);
  h_scale_EB->Draw("COLZ");
  h_scale_EB->GetXaxis() ->SetTitle("i#phi");
  h_scale_EB->GetYaxis() ->SetTitle("i#eta");
  h_scale_EB->GetZaxis() ->SetRangeUser(0.9,1.1);


 
  
  // --- plot 1 : ring precision vs ieta
  c[1] = new TCanvas("csigma","csigma");
  c[1]->SetGridx();
  c[1]->SetGridy();
  sigma_vs_ieta->GetHistogram()->GetYaxis()-> SetRangeUser(0.00,0.10);
  sigma_vs_ieta->GetHistogram()->GetXaxis()-> SetRangeUser(-85,85);
  sigma_vs_ieta->GetHistogram()->GetYaxis()-> SetTitle("#sigma_{c}");
  sigma_vs_ieta->GetHistogram()->GetXaxis()-> SetTitle("i#eta");
  sigma_vs_ieta->Draw("ap");
  if (evalStat){
    statprecision_vs_ieta->Draw("psame");
    sigma_vs_ieta->Draw("psame");
    TLegend * leg = new TLegend(0.6,0.7,0.89, 0.89);
    leg->SetFillColor(0);
    leg->AddEntry(statprecision_vs_ieta,"statistical precision", "LP");
    leg->AddEntry(sigma_vs_ieta,"spread", "LP");
    leg->Draw("same");
  }

  // --- plot 2 : scale vs ieta
  c[2] = new TCanvas("c_scale_vs_ieta","c_scale_vs_ieta");
  c[2]->SetGridx();
  c[2]->SetGridy();
  scale_vs_ieta->GetHistogram()->GetYaxis()-> SetRangeUser(0.95,1.05);
  scale_vs_ieta->GetHistogram()->GetXaxis()-> SetRangeUser(-85,85);
  scale_vs_ieta->GetHistogram()->GetYaxis()-> SetTitle("scale");
  scale_vs_ieta->GetHistogram()->GetXaxis()-> SetTitle("i#eta");
  scale_vs_ieta->Draw("ap");
  
  // --- plot 3 : spread all coefficients
  c[3] = new TCanvas("cspread","cspread",500,500);
  hspreadall->SetFillStyle(3004);
  hspreadall->SetFillColor(kGreen+2);
  hspreadall->GetXaxis()-> SetRangeUser(0.8,1.2);
  hspreadall->GetXaxis()-> SetTitle("c");
  hspreadall->Draw("hs");
  gPad->Update();

  TPaveStats *s_spread = (TPaveStats*)(hspreadall->GetListOfFunctions()->FindObject("stats"));
  s_spread -> SetX1NDC(0.55); //new x start position
  s_spread -> SetX2NDC(0.85); //new x end position
  s_spread -> SetY1NDC(0.750); //new x start position
  s_spread -> SetY2NDC(0.85); //new x end position
  s_spread -> SetOptStat(1110);
  s_spread -> SetTextColor(kGreen+2);
  s_spread -> SetTextSize(0.03);
  s_spread -> Draw("sames");

  //--- plot 4 : occupancy map
  c[4] = new TCanvas("cOcc","cOcc");
  c[4]->SetLeftMargin(0.1); 
  c[4]->SetRightMargin(0.13); 
  c[4]-> cd();
  c[4]->SetGridx();
  h_occupancy->GetXaxis()->SetNdivisions(1020);
  h_occupancy->GetXaxis() -> SetLabelSize(0.03);
  h_occupancy->Draw("COLZ");
  h_occupancy->GetXaxis() ->SetTitle("i#phi");
  h_occupancy->GetYaxis() ->SetTitle("i#eta");

  
  // --- plot 5 : statistical precision vs ieta
  if (evalStat){
  c[5] = new TCanvas("cstat","cstat");
  c[5]->SetGridx();
  c[5]->SetGridy();
  statprecision_vs_ieta->GetHistogram()->GetYaxis()-> SetRangeUser(0.0001,0.10);
  statprecision_vs_ieta->GetHistogram()->GetXaxis()-> SetRangeUser(-85,85);
  statprecision_vs_ieta->GetHistogram()->GetYaxis()-> SetTitle("#sigma((c_{P}-c_{D})/(c_{P}+c_{D}))");
  statprecision_vs_ieta->GetHistogram()->GetXaxis()-> SetTitle("i#eta");
  statprecision_vs_ieta->Draw("ap");

//   TF1 *fp = new TF1("fp","pol0");
//   fp->SetRange(-40,40);
//   statprecision_vs_ieta->Fit("fp","QRN");
//   float stat = fp->GetParameter(0);
//   float estat = fp->GetParError(0);
//   cout << "Statistical precision in |ieta| < 40 --> " <<  stat << " +/- " << estat << endl;
//   sigma_vs_ieta->Fit("fp","QRN");
//   float spread = fp->GetParameter(0);
//   float espread = fp->GetParError(0);
//   cout << "Spread in |ieta| < 40 --> " <<  spread << " +/- " << espread << endl;
//   float residual = sqrt( spread*spread - stat*stat );
//   float eresidual = sqrt( pow(spread*espread,2) + pow(stat*estat,2))/residual;
//   cout << "Residual miscalibration : " << residual << " +/- " << eresidual << endl;
  
  c[6] = new TCanvas("cresidual","cresidual");
  c[6]->SetGridx();
  c[6]->SetGridy();
  residual_vs_ieta->GetHistogram()->GetYaxis()-> SetRangeUser(0.0001,0.05);
  residual_vs_ieta->GetHistogram()->GetXaxis()-> SetRangeUser(-85,85);
  residual_vs_ieta->GetHistogram()->GetYaxis()-> SetTitle("residual spread");
  residual_vs_ieta->GetHistogram()->GetXaxis()-> SetTitle("i#eta");
  residual_vs_ieta->Draw("ap");
  
   
  }
 
  //-----------------------------------------------------------------
  //--- Print plots
  //-----------------------------------------------------------------
  
  if (printPlots){

    //gStyle->SetOptStat(1110);
    c[0]->Print("IC_map.png",fileType);
    c[1]->Print("IC_precision_vs_ieta.png",fileType);
    c[2]->Print("IC_scale_vs_ieta.png",fileType);
    c[3]->Print("IC_spread.png",fileType);
    c[4]->Print("occupancy_map.png",fileType);
  }
}
Example #11
0
int IndResponse5TeV(double kPt=30,const char *ksp="ppb",int ifile=0)
{

  timer.Start();

  //! Load Lib
  gSystem->Load("../HiForest_V3/hiForest_h.so");
  
  //! Load the hiforest input root file
  HiForest *c = 0;
  //! Latest
//  if(strcmp(ksp,"ppb")==0)c = new HiForest(Form("/mnt/hadoop/cms/store/user/dgulhan/pPb/HP04/prod13/Hijing_Pythia_pt%.f/HiForest_v72_v01_merged01/pt%.f_prod13_v72_merged_forest_%d.root",kPt,kPt,ifile),"PythiaHijing",cPPb); 
  if(strcmp(ksp,"ppb")==0)c = new HiForest(Form("/mnt/hadoop/cms/store/user/dgulhan/pPb/HP04/prod16/Hijing_Pythia_pt%.f/HiForest_v77_merged01/pt%.f_HP04_prod16_v77_merged_forest_%d.root",kPt,kPt,ifile),"PythiaHijing",cPPb); 
  else {
    c = new HiForest(Form("/mnt/hadoop/cms/store/user/kjung/pPbForest/Signal_Pythia_pt%.f/merged/pt%.f_HP04_prod16_v77_merged_forest_Sum.root",kPt,kPt),"Pythia",cPPb);
//    if(kPt==280)c = new HiForest(Form("/mnt/hadoop/cms/store/user/dgulhan/pPb/HP03/prod10/Signal_Pythia_pt%0.0f/HiForest_v63_v02_merged03/pt%0.0f_HP03_prod09_merged_forest_%d.root",kPt,kPt,ifile),"Pythia",cPPb);
//    else c = new HiForest(Form("/mnt/hadoop/cms/store/user/dgulhan/pPb/HP03/prod10/Signal_Pythia_pt%0.0f/HiForest_v63_merged03/pt%0.0f_HP03_prod09_merged_forest_%d.root",kPt,kPt,ifile),"Pythia",cPPb);
  }
  double xsection=0;
  double xup=0;
  double xsub=0;
  double maxpthat=9999;

  if(kPt==15){
    maxpthat=30;
    xup =5.335e-01;
    xsub=3.378e-02;
  }
  else if(kPt==30){
    maxpthat=50;
    xup =3.378e-02;
    xsub=3.778e-03;
  }
  else if(kPt==50){
    maxpthat=80;
    xup =3.778e-03;
    xsub=4.412e-04;
  }
  else if(kPt==80){
    maxpthat=120;
    xup =4.412e-04;
    xsub=6.147e-05;
  }
  else if(kPt==120){
    maxpthat=170;
    xup=6.147e-05;
    xsub=1.018e-05;
  }else if(kPt==170){
    maxpthat=220;
    xup=1.018e-05;
    xsub=2.477e-06;
  }else if(kPt==220){
    maxpthat=280;
    xup =2.477e-06;
    xsub=6.160e-07;
  }else if(kPt==280){
//    maxpthat=9999;
//    xup =6.160e-07;
//    xsub=0;
//  }
    maxpthat=370;
    xup =6.160e-07;
    xsub=1.088e-07;
    }else if(kPt==370){
    maxpthat=9999;
    xup=1.088e-07; 
    xsub=0;
    }

  xsection = xup-xsub;

  std::cout<<std::endl;
  std::cout<<std::endl;

  
  /*
  const int knj = 25;
  const char *cjets[knj] = {"icPu5",
			    "ak1PF","ak2PF","ak3PF","ak4PF","ak5PF","ak6PF",
			    "akPu1PF","akPu2PF","akPu3PF","akPu4PF","akPu5PF","akPu6PF",			    
			    "ak1Calo","ak2Calo","ak3Calo","ak4Calo","ak5Calo","ak6Calo",
			    "akPu1Calo","akPu2Calo","akPu3Calo","akPu4Calo","akPu5Calo","akPu6Calo"};

  const char *calgo[knj] = {"icPu5",
			    "ak1PF","ak2PF","ak3PF","ak4PF","ak5PF","ak6PF",
			    "akPu1PF","akPu2PF","akPu3PF","akPu4PF","akPu5PF","akPu6PF",			    
			    "ak1Calo","ak2Calo","ak3Calo","ak4Calo","ak5Calo","ak6Calo",
			    "akPu1Calo","akPu2Calo","akPu3Calo","akPu4Calo","akPu5Calo","akPu6Calo"};
  */
  const int knj = 16;
  const char *cjets[knj] = {"ak2PF","ak3PF","ak4PF","ak5PF",
			    "akPu2PF","akPu3PF","akPu4PF","akPu5PF",
			    "ak2Calo","ak3Calo","ak4Calo","ak5Calo",
			    "akPu2Calo","akPu3Calo","akPu4Calo","akPu5Calo"};
  const char *calgo[knj] = {"ak2PF","ak3PF","ak4PF","ak5PF",
			    "akPu2PF","akPu3PF","akPu4PF","akPu5PF",
			    "ak2Calo","ak3Calo","ak4Calo","ak5Calo",
			    "akPu2Calo","akPu3Calo","akPu4Calo","akPu5Calo"};

  c->hasIcPu5JetTree=0;
  c->hasAk1PFJetTree=0;
  c->hasAk6PFJetTree=0;
  c->hasAkPu1PFJetTree=0;
  c->hasAkPu6PFJetTree=0;
  c->hasAk1CaloJetTree=0;
  c->hasAk6CaloJetTree=0;
  c->hasAkPu1CaloJetTree=0;
  c->hasAkPu6CaloJetTree=0;


  /*
  c->hasMetTree=0;
  c->hasPFTree=0;
  c->hasIcPu5JetTree=0;
  c->hasAkPu2JetTree=0;
  c->hasAkPu3JetTree=0;
  c->hasAkPu4JetTree=0;
  c->hasAkPu2CaloJetTree=0;
  c->hasAkPu3CaloJetTree=0;
  c->hasAkPu4CaloJetTree=0;
  c->hasHltTree=0;
  c->hasTrackTree=0;
  c->hasPixTrackTree=0;
  c->hasSkimTree=0;
  c->hasTowerTree=0;
  c->hasHbheTree=0;
  c->hasEbTree=0;
  c->hasGenpTree=0;
  c->hasGenParticleTree=0;
  c->hasPhotonTree=0;
  */


  //! To get the jet object from hiforest
  Jets *iJet=0;

  std::cout<<"Loaded all tree variables and # of jet algorithms : "<<knj<<std::endl;
  std::cout<<"\t"<<std::endl;


  //! Open a output file for histos
  TFile *fout = new TFile(Form("Output/Response_%s_pT%0.0fGeV_%d.root",ksp,kPt,ifile),"RECREATE");


  std::cout<<"\t"<<std::endl;
  std::cout<<"\t"<<std::endl;
  std::cout<<"**************************************************** "<<std::endl;
  std::cout<<Form("Running for %s ",ksp)<<std::endl;
  std::cout<<Form("pT  cut for %0.3f ",kptrecocut)<<std::endl;
  std::cout<<Form("eta cut for %0.3f ",ketacut)<<std::endl;
  std::cout<<"My hiForest TTree : " <<c->GetName()<<std::endl;
  std::cout<<"Output file  "<<fout->GetName()<<std::endl;
  std::cout<<"**************************************************** "<<std::endl;
  std::cout<<"\t"<<std::endl;
  std::cout<<"\t"<<std::endl;


  //! 
  //! Define histograms here
  TH1::SetDefaultSumw2();
  TH2::SetDefaultSumw2();
  TProfile::SetDefaultSumw2();

  ////////////////////////////////////////////////////////////////////////////////////////////////////////
  TH1F *hEvt    = new TH1F("hEvt","# of events ",4,0,4);
  TH1F *hVz     = new TH1F("hVz","# of events ",80,-20,20);
  TH1F *hBin    = new TH1F("hBin","Centrality bin",100,-0.5,100-0.5);
  TH1F *hTotEve = new TH1F("hTotEve","# of events in the skimmed files",4,0,4);

  
  TH1F *hHF       = new TH1F("hHF","HF distribution",500,0,500);
  TH1F *hNTracks  = new TH1F("hNTracks","hiNTracks",500,0,500);
  TH2F *hNTracksHF = new TH2F("hNTracksHF","Ntrack vs HF ",500,0,500,500,0,500);
  TH2F *hBinHF      = new TH2F("hBinHF","HF vs hiBin",100,-0.5,100-0.5,500,0,500);
  TH2F *hBinNTracks = new TH2F("hBinNTracks","HF vs NTracks",100,-0.5,100-0.5,500,0,500);
    TH2F *hNTracksHFplusEta4 = new TH2F("hNTracksHFplusEta4","NTracks vs HFplusEta4",500,0,500, 500, 0., 500);
  
  TH1F *hgenpt_genm [knj][nmult], *hrecopt_genm[knj][nmult], *hrawpt_genm[knj][nmult];
  TH1F *hjeteta  [knj][nmult], *hjetphi[knj][nmult];
  TH2F *hjetpteta[knj][nmult], *hjetptphi[knj][nmult], *hjetetaphi[knj][nmult];

  //! Ratios of the pt distributions
  TProfile *hrecogen[knj][nmult], *hrecoraw[knj][nmult], *hrawgen[knj][nmult];

  //! Resposnse
  TH2F *hrescrpt_genm[knj][nmult], *hresrrpt_genm[knj][nmult], *hresrcrpt_genm[knj][nmult];
  TH2F *hrescreta_genm[knj][nmult], *hresrreta_genm[knj][nmult], *hresrcreta_genm[knj][nmult];

  TH2F *hratiorawrefpt_eta[knj][nmult][2], *hratiocorrrefpt_eta[knj][nmult][2];

  TH2F *hratiocorrrefpt_genm[knj][nmult];
  TH2F *hratiocorrrefpt_lead[knj][nmult], *hratiocorrrefpt_slead[knj][nmult];

    TH2F *hratiocorrrefpt_genhfb[knj][nhfbin];
    TH2F *hratiocorrrefpt_etaptbin[knj][bins];

  //! For comparison with data
  TH2F *hJetEnergyScale[knj][nmult];

  TH2F *hpteta[knj][nmult][maxe] ;
  TH2F *hptphi[knj][nmult][maxph] ;

  TH2F *hgenjrecoj[knj][nmult];
  TH1F *hNjets_genm[knj][nmult];
  TH1F *hNevt [knj][nmult];

  //! Background for jets 
  //! (photonSum+neutralSum+chargedSum-rawpt)
  TH2F *hjetptpu_genm[knj][nmult];             //! centrality                                                                       
  TH2F *hjetptpu_etab_genm[knj][nmult][ketar]; //! eta dependence             
  TH1F *hjetbkgd_genm[knj][nmult];
  TH2F *hjetptbkgd_genm[knj][nmult];
  TH2F *hjetptbkgd_etab_genm[knj][nmult][ketar];
  TH2F *hPFFraction_genm[knj][nmult][3];

  //! Efficency histos
  TH1F *hPtAll [knj][nmult], *hPtSel[knj][nmult];
  TH1F *hEtaAll[knj][nmult], *hEtaSel[knj][nmult];
  TH1F *hPhiAll[knj][nmult], *hPhiSel[knj][nmult];

  //! Response vs deltar
  TH1F *hRspVsDeltaR[knj][nmult][25];

  //! DeltaR efficiency                                                                                                                                                              
  TH1F *hDeltaR[knj][nmult];
  TH1F *hDeltaRAll[knj][nmult];
  TH1F *hDeltaRSel[knj][nmult];

    for(int nj=0;nj<knj;nj++){
        
        for(int icen=0;icen<nmult;icen++){
            hNevt [nj][icen] = new TH1F(Form("hNevt%d_%d",nj,icen),Form("# of events cent %d %s",icen,cjets[nj]),40,-40,40);
            
            hNjets_genm [nj][icen] = new TH1F(Form("hNjets_genm%d_%d",nj,icen),Form("# of jets cent %d jets %s",icen,cjets[nj]),200,30,630);
            hgenpt_genm [nj][icen] = new TH1F(Form("hgenpt_genm%d_%d",nj,icen),Form("Gen matched gen p_{T} distribution jet centb %d %s",icen,cjets[nj]),500,0,1000);
            hrecopt_genm[nj][icen] = new TH1F(Form("hrecopt_genm%d_%d",nj,icen),Form("Gen matched reco p_{T} distribution jet centb %d %s",icen,cjets[nj]),500,0,1000);
            hrawpt_genm [nj][icen] = new TH1F(Form("hrawpt_genm%d_%d",nj,icen),Form("Gen matched raw p_{T} distribution jet centb %d %s",icen,cjets[nj]),500,0,1000);
            
            //! Ratios
            hrecogen[nj][icen] = new TProfile(Form("hrecogen%d_%d",nj,icen),Form("reco/gen p_{T} distribution jet centb %d %s",icen,cjets[nj]),500,0,1000);
            hrecoraw[nj][icen] = new TProfile(Form("hrecoraw%d_%d",nj,icen),Form("reco/raw p_{T} distribution jet centb %d %s",icen,cjets[nj]),500,0,1000);
            hrawgen[nj][icen]  = new TProfile(Form("hrawgen%d_%d",nj,icen),Form("raw/gen p_{T} distribution jet centb %d %s",icen,cjets[nj]),500,0,1000);
            
            //! Gen matched
            hrescrpt_genm[nj][icen]= new TH2F(Form("hrescrpt_genm%d_%d",nj,icen),Form("Gen jet:(Reco/Gen) jet p_{T} distribution jet centb %d %s",icen,cjets[nj]),500,0,1000,150,rbinl,rbinh);
            hresrrpt_genm[nj][icen]= new TH2F(Form("hresrrpt_genm%d_%d",nj,icen),Form("Gen jet:(Raw/Gen) jet p_{T}  distribution jet centb %d %s",icen,cjets[nj]),500,0,1000,150,rbinl,rbinh);
            hresrcrpt_genm[nj][icen]= new TH2F(Form("hresrcrpt_genm%d_%d",nj,icen),Form("Reco jet:(Reco/Raw) jet p_{T} distribution jet centb %d %s",icen,cjets[nj]),500,0,1000,150,rbinl,rbinh);
            
            hrescreta_genm[nj][icen]= new TH2F(Form("hrescreta_genm%d_%d",nj,icen),Form("Gen jet:(Reco/Gen) jet p_{T} distribution jet centb %d %s",icen,cjets[nj]),100,-5.0,5.0,150,rbinl,rbinh);
            hresrreta_genm[nj][icen]= new TH2F(Form("hresrreta_genm%d_%d",nj,icen),Form("Gen jet:(Raw/Gen) jet p_{T}  distribution jet centb %d %s",icen,cjets[nj]),100,-5.0,5.0,150,rbinl,rbinh);
            hresrcreta_genm[nj][icen]= new TH2F(Form("hresrcreta_genm%d_%d",nj,icen),Form("Reco jet:(Reco/Raw) jet p_{T} distribution jet centb %d %s",icen,cjets[nj]),100,-5.0,5.0,150,rbinl,rbinh);
            
            hjeteta[nj][icen] = new TH1F(Form("hjeteta%d_%d",nj,icen),Form("jet eta distribution jet centb %d %s",icen,calgo[nj]),100,-5.0,5.0);
            hjetphi[nj][icen] = new TH1F(Form("hjetphi%d_%d",nj,icen),Form("jet phi distribution jet centb %d %s",icen,calgo[nj]),72,-pi,pi);
            
            hjetetaphi[nj][icen] = new TH2F(Form("hjetetaphi%d_%d",nj,icen),Form("jet eta-phi distribution jet centb %d %s",icen,calgo[nj]),100,-5.0,5.0,72,-pi,pi);
            hjetpteta[nj][icen] = new TH2F(Form("hjetpteta%d_%d",nj,icen),Form("jet pt-eta distribution jet centb %d %s",icen,calgo[nj]),500,0,1000,100,-5.0,5.0);
            hjetptphi[nj][icen] = new TH2F(Form("hjetptphi%d_%d",nj,icen),Form("jet pt-phi distribution jet centb %d %s",icen,calgo[nj]),500,0,1000,72,-pi,pi);
            
            
            hratiocorrrefpt_lead[nj][icen]= new TH2F(Form("hratiocorrrefpt_lead%d_%d",nj,icen),Form("Leading jet Reco jet / Gen jet p_{T} (corr.) distribution jet centb %d %s",icen,cjets[nj]),
                                                     500,0,1000,rbins,rbinl,rbinh);
            hratiocorrrefpt_slead[nj][icen]= new TH2F(Form("hratiocorrrefpt_slead%d_%d",nj,icen),Form("sub-Leading jet Reco jet / Gen jet p_{T} (corr.) distribution jet centb %d %s",icen,cjets[nj]),
                                                      500,0,1000,rbins,rbinl,rbinh);
            hratiocorrrefpt_genm[nj][icen]= new TH2F(Form("hratiocorrrefpt_genm%d_%d",nj,icen),Form("Gen matched jet Reco jet / Gen jet p_{T} (corr.) distribution jet centb %d %s",icen,cjets[nj]),
                                                     500,0,1000,rbins,rbinl,rbinh);
            hJetEnergyScale[nj][icen] = new TH2F(Form("hJetEnergyScale%d_%d",nj,icen),Form("hJetEnergyScale%d_%d",nj,icen),500,0,1000,50,-1.00,1.00);
            
            for(int ie=0;ie<2;ie++){
                hratiorawrefpt_eta[nj][icen][ie]= new TH2F(Form("hratiorawrefpt_eta%d_%d_%d",nj,icen,ie),
                                                           Form("Raw jet / Gen jet p_{T} (raw) distribution jet centb %d %s etabin%d",icen,cjets[nj],ie),
                                                           500,0,1000,rbins,rbinl,rbinh);
                hratiocorrrefpt_eta[nj][icen][ie]= new TH2F(Form("hratiocorrrefpt_eta%d_%d_%d",nj,icen,ie),
                                                            Form("Reco jet / Gen jet p_{T} (raw) distribution jet centb %d %s etabin%d",icen,cjets[nj],ie),
                                                            500,0,1000,rbins,rbinl,rbinh);
            }
            
            //hjetptpu_genm[nj][icen] = new TH2F(Form("hjetptpu_genm%d_%d",nj,icen),Form("jet(pt:pu) distribution jet centb %d %s",icen,cjets[nj]),dbins,ptbins_data,100,0,300);
            //for(int ie=0;ie<ketar;ie++){
            // hjetptpu_etab_genm[nj][icen][ie] = new TH2F(Form("hjetptpu_etab_genm%d_%d_%d",nj,icen,ie),Form("jet(pt:pu) distribution jet %s etabin %d cen %d",cjets[nj],icen,ie),
            ///					    dbins,ptbins_data,100,0,300);
            //}
            
            hjetptpu_genm[nj][icen] = new TH2F(Form("hjetptpu_genm%d_%d",nj,icen),Form("jet(pt:pu) distribution jet centb %d %s",icen,cjets[nj]),500,0,1000,100,0,300);
            for(int ie=0;ie<ketar;ie++){
                hjetptpu_etab_genm[nj][icen][ie] = new TH2F(Form("hjetptpu_etab_genm%d_%d_%d",nj,icen,ie),Form("jet(pt:pu) distribution jet %s etabin %d cen %d",cjets[nj],icen,ie),
                                                            500,0,1000,100,0,300);
                hjetptbkgd_etab_genm[nj][icen][ie] = new TH2F(Form("hjetptbkgd_etab_genm%d_%d_%d",nj,icen,ie),Form("jet(pt:bkgd) distribution jet etabin %d centb %d %s",ie,icen,calgo[nj]),500,0,1000,100,0,300);
            }
            hjetbkgd_genm  [nj][icen] = new TH1F(Form("hjetbkgd_genm%d_%d",nj,icen),Form("jet(pu) p_{T} distribution jet centb %d %s",icen,calgo[nj]),100,0,300);
            //hjetptbkgd_genm[nj][icen] = new TH2F(Form("hjetptbkgd_genm%d_%d",nj,icen),Form("jet(pt:bkgd) distribution jet centb %d %s",icen,calgo[nj]),dbins,ptbins_data,100,0,300);
            hjetptbkgd_genm[nj][icen] = new TH2F(Form("hjetptbkgd_genm%d_%d",nj,icen),Form("jet(pt:bkgd) distribution jet centb %d %s",icen,calgo[nj]),500,0,1000,100,0,300);
            //! PF fractions
            for(int ipf=0;ipf<3;ipf++){
                hPFFraction_genm[nj][icen][ipf] = new TH2F(Form("hPFFraction_genm%d_%d_%d",nj,icen,ipf),Form("PF fraction distribution jet centb %d %s %d",icen,calgo[nj],ipf),500,0,1000,15,0,1.5);
            }
            
            
            for(int m=0;m<maxe;m++){
                hpteta[nj][icen][m] = new TH2F(Form("hpteta%d_%d_%d",nj,icen,m),Form("resolution  pt(eta) distribution cent %d jet %s etabin%d",icen,cjets[nj],m),
                                               500,0,1000,rbins,rbinl,rbinh);
            }
            
            for(int m=0;m<maxph;m++){
                hptphi[nj][icen][m] = new TH2F(Form("hptphi%d_%d_%d",nj,icen,m),Form("resolution pt(phi) distribution cent %d jet %s phibin%d",icen,cjets[nj],m),
                                               500,0,1000,rbins,rbinl,rbinh);
            }
            
            hgenjrecoj[nj][icen] =new TH2F(Form("hgenjrecoj%d_%d",nj,icen),Form("gen jet2 : reco jet2 %s cent %d",cjets[nj],icen),500,0.,1000.,500,0.,1000.);
            
            //! efficency histograms
            hPtAll [nj][icen] = new TH1F(Form("hPtAll%d_%d",nj,icen),Form("Denominator pT for algorithm %s cent %d",cjets[nj],icen),40,10,110);
            hEtaAll[nj][icen] = new TH1F(Form("hEtaAll%d_%d",nj,icen),Form("Denominator eta  for algorithm %s cent %d",cjets[nj],icen),100,-5.0,5.0);
            hPhiAll[nj][icen] = new TH1F(Form("hPhiAll%d_%d",nj,icen),Form("Denominator  phi  for algorithm %s cent %d",cjets[nj],icen),20,-pi,pi);
            
            hPtSel [nj][icen] = new TH1F(Form("hPtSel%d_%d",nj,icen),Form("Numerator pT for algorithm %s cent %d",cjets[nj],icen),40,10,110);
            hEtaSel[nj][icen] = new TH1F(Form("hEtaSel%d_%d",nj,icen),Form("Numerator eta  for algorithm %s cent %d",cjets[nj],icen),100,-5.0,5.0);
            hPhiSel[nj][icen] = new TH1F(Form("hPhiSel%d_%d",nj,icen),Form("Numerator  phi  for algorithm %s cent %d",cjets[nj],icen),20,-pi,pi);
            
            hDeltaR[nj][icen]    = new TH1F(Form("hDeltaR%d_%d",nj,icen),Form("#DeltaR for algorithm %s cent %d",cjets[nj],icen),100,0,1);
            hDeltaRAll[nj][icen] = new TH1F(Form("hDeltaRAll%d_%d",nj,icen),Form("#DeltaR (all) for algorithm %s cent %d",cjets[nj],icen),100,0,1);
            hDeltaRSel[nj][icen] = new TH1F(Form("hDeltaRSel%d_%d",nj,icen),Form("#DeltaR (sel) for algorithm %s cent %d",cjets[nj],icen),100,0,1);
            
            for(int ir=0;ir<25;ir++){
                //! Response vs DeltaR
                hRspVsDeltaR[nj][icen][ir] = new TH1F(Form("hRspVsDeltaR%d_%d_%d",nj,icen,ir),Form(" <recopt/refpt> vs. #DeltaR (%d) algorithm %s cent %d",ir,cjets[nj],icen),rbins,rbinl,rbinh);
            }
        }//! icen
        //for eta clsoure in different jet pt bins
        for(int ipt=0;ipt<bins;ipt++){
            hratiocorrrefpt_etaptbin[nj][ipt]= new TH2F(Form("hratiocorrrefpt_etaptbin%d_%d",nj,ipt),Form("Gen matched jet Reco jet / Gen jet p_{T} (corr.) distribution jet vs eta in pt bin %d %s",ipt,cjets[nj]),
                                                  100,-5.0,5.0,rbins,rbinl,rbinh);
            
        }
        //for different HFplusEta4 bins
        for(int ihf=0;ihf<nhfbin;ihf++){
            hratiocorrrefpt_genhfb[nj][ihf]= new TH2F(Form("hratiocorrrefpt_genhfbin%d_%d",nj,ihf),Form("Gen matched jet Reco jet / Gen jet p_{T} (corr.) distribution jet hiHF bin %d %s",ihf,cjets[nj]),
                                                      500,0,1000,rbins,rbinl,rbinh);
        }
        
    }//! nj
  std::cout<<"Initialized the histograms " <<std::endl;
  ///////////////////////////////////////////////////////////////////////////////////////// 


  //! Centrality reweighting function

  //! vertex z reweighting




  Long64_t nentries = c->GetEntries();
  std::cout<<Form("# of entries in TTree for %s : ",ksp)<<nentries<<std::endl;
  std::cout<<std::endl;
  hEvt->Fill(2,nentries);

  //! weight  for the merging of the samples for different pT hat bins
  Float_t wxs = xsection/(nentries/100000.);
  
  Int_t iEvent=0; 
  for (Long64_t ievt=0; ievt<nentries;ievt++) {//! event loop
    //for (Long64_t ievt=0; ievt<5000;ievt++) {//! event loop
    //! load the hiForest event
    c->GetEntry(ievt);

    int hiBin       = c->evt.hiBin;
    float vz        = c->evt.vz;
    float hiHF      = c->evt.hiHF;
    int ntracks     = c->evt.hiNtracks;
    float HFplusEta = c->evt.hiHFplusEta4;
    float HFminusEta = c->evt.hiHFminusEta4 ; 
    float HFplusEta4 = HFplusEta+HFminusEta;
    //! testing
    //if(hiBin>4 && strcmp(ksp,"pbpb")==0)continue;

    //! apply vertex cut
    if(fabs(vz)>kVzcut)continue;


    //! Centrality bin
    if(hiBin<0 || hiBin>100)continue;
    int multb=GetMultBin(ntracks);
    int hiHFb=GetHFplusEta4Bin(HFplusEta4);  
      
    double wcen=1;
    double wvz=1;
    //wxs=1;
    if(strcmp(ksp,"pp")==0)multb=0;
  
    if(ievt%10000==0)std::cout<<" ********** Event # " <<ievt<<std::endl;
    //std::cout<<" ********** Event # " <<ievt<<"\t vz : "<<vz<<"\t hiBin : "<<hiBin<<"\t wxs : "<<wxs<<std::endl;


    //! Centrality from 0-100% 
    if(multb==-1 || multb==nmult)continue;
    if(hiHFb==-1 || hiHFb==nhfbin)continue;

    int istat=0;
    for(int nj=0;nj<knj;nj++){ //! loop over different jet algorithms
      

      if(nj==0)iJet = &(c->ak2PF);
      else if(nj==1)iJet = &(c->ak3PF);
      else if(nj==2)iJet = &(c->ak4PF);
      else if(nj==3)iJet = &(c->ak5PF);

      else if(nj==4)iJet = &(c->akPu2PF);
      else if(nj==5)iJet = &(c->akPu3PF);
      else if(nj==6)iJet = &(c->akPu4PF);
      else if(nj==7)iJet = &(c->akPu5PF);

      else if(nj==8)iJet = &(c->ak2Calo);
      else if(nj==9)iJet = &(c->ak3Calo);
      else if(nj==10)iJet = &(c->ak4Calo);
      else if(nj==11)iJet = &(c->ak5Calo);

      else if(nj==12)iJet = &(c->akPu2Calo);
      else if(nj==13)iJet = &(c->akPu3Calo);
      else if(nj==14)iJet = &(c->akPu4Calo);
      else if(nj==15)iJet = &(c->akPu5Calo);


      //! xsec-weight
      double pthat = iJet->pthat;
      if(pthat > maxpthat)continue;
      istat=1;
      
      //std::cout<<"\t Jet Algorithm : "<<cjets[nj]<<"\t # of Jets  : "<<iJet->nref<<"\t pthat : "<<pthat<<std::endl;
      if(nj==0)hTotEve->Fill(1); //! akPu3PF      


      int *ljet = new int[3];
      FindLeadSubLeadJets(iJet,ljet);
      if(ljet[0]>=0){
	hratiocorrrefpt_lead[nj][multb]->Fill(iJet->refpt[ljet[0]],iJet->jtpt[ljet[0]]/iJet->refpt[ljet[0]],wxs*wcen*wvz);
	hratiocorrrefpt_lead[nj][nmult-1]->Fill(iJet->refpt[ljet[0]],iJet->jtpt[ljet[0]]/iJet->refpt[ljet[0]],wxs*wcen*wvz);
      }
      if(ljet[1]>=0){
	hratiocorrrefpt_slead[nj][multb]->Fill(iJet->refpt[ljet[1]],iJet->jtpt[ljet[1]]/iJet->refpt[ljet[1]],wxs*wcen*wvz);
	hratiocorrrefpt_slead[nj][nmult-1]->Fill(iJet->refpt[ljet[1]],iJet->jtpt[ljet[1]]/iJet->refpt[ljet[1]],wxs*wcen*wvz);
      }

      //! Jet energy scale comparison with data
      if(ljet[0]>=0 && ljet[1]>=0 && iJet->jtpt[ljet[0]]>50. && iJet->jtpt[ljet[1]]>50.){//! atleas a dijet
        int mstat=1;
        double ptdij = (iJet->jtpt[ljet[0]] + iJet->jtpt[ljet[1]])/2.;
        if(ljet[2]>=0){
          //if(iJet->jtpt[ljet[2]]/ptdij > 0.2)mstat=0;
	  mstat=0;
        }
        if(mstat){
          double B=-9999;
          double rn1 = gRandom->Rndm();
          double rn2 = gRandom->Rndm();
          if(rn1 > rn2){
            B = (iJet->jtpt[ljet[0]] - iJet->jtpt[ljet[1]])/(iJet->jtpt[ljet[0]] + iJet->jtpt[ljet[1]]);
          }else{
            B = (iJet->jtpt[ljet[1]] - iJet->jtpt[ljet[0]])/(iJet->jtpt[ljet[1]] + iJet->jtpt[ljet[0]]);
          }
          hJetEnergyScale[nj][multb]->Fill(ptdij,B);
          hJetEnergyScale[nj][nmult-1]->Fill(ptdij,B);
	}
      }

      //! Gen matched jets
      for(int igen=0; igen<iJet->nref; igen++){
	if( iJet->subid[igen] != 0) continue;
	int gj = igen;
	
	float rawpt   = iJet->rawpt[gj];
	float refpt   = iJet->refpt[gj];
	float refeta  = iJet->refeta[gj];
	float refphi  = iJet->refphi[gj];
	float recopt  = iJet->jtpt[gj];
	float recoeta = iJet->jteta[gj];
	float delr    = iJet->refdrjt[gj];
          
       if(rawpt <15.) continue ;
     //  if(recopt<30.) continue ;
	if(fabs(refeta)<ketacut && refpt>10){
          //! Denominator for matching efficiency
	  hPtAll [nj][multb]->Fill(refpt,wxs*wcen*wvz);
          hEtaAll[nj][multb]->Fill(refeta,wxs*wcen*wvz);
          hPhiAll[nj][multb]->Fill(refphi,wxs*wcen*wvz);
	  
	  hPtAll [nj][nmult-1]->Fill(refpt,wxs*wcen*wvz);
          hEtaAll[nj][nmult-1]->Fill(refeta,wxs*wcen*wvz);
          hPhiAll[nj][nmult-1]->Fill(refphi,wxs*wcen*wvz);
	  
	  //! DeltaR efficiency
	  hDeltaR[nj][multb]->Fill(delr,wxs*wcen*wvz);
	  hDeltaR[nj][nmult-1]->Fill(delr,wxs*wcen*wvz);
	  for (int idrmax=0;idrmax<100;idrmax++) {
	    float drmax = idrmax*0.01+0.005;
	    hDeltaRAll[nj][multb]->Fill(drmax,wxs*wcen*wvz);
	    hDeltaRAll[nj][nmult-1]->Fill(drmax,wxs*wcen*wvz);
	    if (delr<drmax){
	      hDeltaRSel[nj][multb]->Fill(drmax,wxs*wcen*wvz);
	      hDeltaRSel[nj][nmult-1]->Fill(drmax,wxs*wcen*wvz);
	    }
	  }
        }

	
	if(recopt<kptrecocut || refpt<kptgencut || refpt==0 || fabs(recoeta)>ketacut || fabs(delr)>kdRcut)continue;

        if(fabs(refeta)<ketacut && refpt>10){
          //! Numerator for matching efficiency
          hPtSel [nj][multb]->Fill(refpt,wxs*wcen*wvz);
          hEtaSel[nj][multb]->Fill(refeta,wxs*wcen*wvz);
          hPhiSel[nj][multb]->Fill(refphi,wxs*wcen*wvz);

          hPtSel [nj][nmult-1]->Fill(refpt,wxs*wcen*wvz);
          hEtaSel[nj][nmult-1]->Fill(refeta,wxs*wcen*wvz);
          hPhiSel[nj][nmult-1]->Fill(refphi,wxs*wcen*wvz);
        }
	

	//! Response
	for (int idr=0;idr<25;idr++) {
	  double drcut = 0.0+idr*(0.25-0.00)/(25-1);
	  if (delr>drcut) continue;
	  hRspVsDeltaR[nj][multb][idr]->Fill(recopt/refpt,wxs*wcen*wvz);
	  hRspVsDeltaR[nj][nmult-1][idr]->Fill(recopt/refpt,wxs*wcen*wvz);
	}
	

    hratiocorrrefpt_genm[nj][multb]->Fill(refpt,recopt/refpt,wxs*wcen*wvz);
	hratiocorrrefpt_genhfb[nj][hiHFb]->Fill(refpt,recopt/refpt,wxs*wcen*wvz);
	hrecogen[nj][multb]->Fill(refpt,recopt/refpt,wxs*wcen*wvz);
	hrecoraw[nj][multb]->Fill(recopt,recopt/rawpt,wxs*wcen*wvz);
        hrawgen [nj][multb]->Fill(refpt,rawpt/refpt,wxs*wcen*wvz);
	hgenjrecoj [nj][multb]->Fill(refpt,recopt,wxs*wcen*wvz);


	hratiocorrrefpt_genm[nj][nmult-1]->Fill(refpt,recopt/refpt,wxs*wcen*wvz);
        hratiocorrrefpt_genhfb[nj][nhfbin-1]->Fill(refpt,recopt/refpt,wxs*wcen*wvz);
        hratiocorrrefpt_genhfb[nj][nhfbin-2]->Fill(refpt,recopt/refpt,wxs*wcen*wvz);
	hrecogen[nj][nmult-1]->Fill(refpt,recopt/refpt,wxs*wcen*wvz);
	hrecoraw[nj][nmult-1]->Fill(recopt,recopt/rawpt,wxs*wcen*wvz);
        hrawgen [nj][nmult-1]->Fill(refpt,rawpt/refpt,wxs*wcen*wvz);
	hgenjrecoj [nj][nmult-1]->Fill(refpt,recopt,wxs*wcen*wvz);

	int ieta=-1;
	if(fabs(recoeta)<1.3)ieta=0; //! barrel region
	else ieta=1; //! HCAL region

   int ptb=GetPtBin(refpt);
   hratiocorrrefpt_etaptbin[nj][ptb]->Fill(refeta,recopt/refpt,wxs*wcen*wvz);
          
          
	//! Response in eta
	hratiocorrrefpt_eta[nj][multb][ieta]->Fill(refpt,recopt/refpt,wxs*wcen*wvz);
	hratiorawrefpt_eta [nj][multb][ieta]->Fill(refpt,rawpt/refpt,wxs*wcen*wvz);
	hratiocorrrefpt_eta[nj][nmult-1][ieta]->Fill(refpt,recopt/refpt,wxs*wcen*wvz);
	hratiorawrefpt_eta [nj][nmult-1][ieta]->Fill(refpt,rawpt/refpt,wxs*wcen*wvz);

	hjeteta   [nj][multb]->Fill(iJet->jteta[gj]);
	hjetphi   [nj][multb]->Fill(iJet->jtphi[gj]);
	hjetpteta [nj][multb]->Fill(iJet->jtpt[gj],iJet->jteta[gj]);
	hjetptphi [nj][multb]->Fill(iJet->jtpt[gj],iJet->jtphi[gj]);
	hjetetaphi[nj][multb]->Fill(iJet->jteta[gj],iJet->jtphi[gj]);

	hjeteta   [nj][nmult-1]->Fill(iJet->jteta[gj]);
	hjetphi   [nj][nmult-1]->Fill(iJet->jtphi[gj]);
	hjetpteta [nj][nmult-1]->Fill(iJet->jtpt[gj],iJet->jteta[gj]);
	hjetptphi [nj][nmult-1]->Fill(iJet->jtpt[gj],iJet->jtphi[gj]);
	hjetetaphi[nj][nmult-1]->Fill(iJet->jteta[gj],iJet->jtphi[gj]);



	//! Fill the background pT info for the signal matched jets only
	//! pileup study
	hjetptpu_genm[nj][multb]->Fill(recopt,iJet->jtpu[gj],wxs*wcen*wvz);
	hjetptpu_etab_genm[nj][multb][ieta]->Fill(recopt,iJet->jtpu[gj],wxs*wcen*wvz);

	hjetptpu_genm[nj][nmult-1]->Fill(recopt,iJet->jtpu[gj],wxs*wcen*wvz);
	hjetptpu_etab_genm[nj][nmult-1][ieta]->Fill(recopt,iJet->jtpu[gj],wxs*wcen*wvz);
	
	//! Jet bkgd estimation
	//! (photonSum+neutralSum+chargedSum-rawpt)
	double jbkgd  = (iJet->photonSum[gj]+iJet->neutralSum[gj]+iJet->chargedSum[gj]) - rawpt;
	hjetbkgd_genm  [nj][multb]->Fill(jbkgd,wxs*wcen*wvz);
	hjetptbkgd_genm[nj][multb]->Fill(recopt,jbkgd,wxs*wcen*wvz);
	hjetptbkgd_etab_genm[nj][multb][ieta]->Fill(recopt,jbkgd,wxs*wcen*wvz);

	hjetbkgd_genm  [nj][nmult-1]->Fill(jbkgd,wxs*wcen*wvz);
	hjetptbkgd_genm[nj][nmult-1]->Fill(recopt,jbkgd,wxs*wcen*wvz);
	hjetptbkgd_etab_genm[nj][nmult-1][ieta]->Fill(recopt,jbkgd,wxs*wcen*wvz);

	hPFFraction_genm[nj][multb][0]->Fill(recopt,iJet->photonSum[gj]/rawpt);
	hPFFraction_genm[nj][multb][1]->Fill(recopt,iJet->neutralSum[gj]/rawpt);
	hPFFraction_genm[nj][multb][2]->Fill(recopt,iJet->chargedSum[gj]/rawpt);

	hPFFraction_genm[nj][nmult-1][0]->Fill(recopt,iJet->photonSum[gj]/rawpt);
	hPFFraction_genm[nj][nmult-1][1]->Fill(recopt,iJet->neutralSum[gj]/rawpt);
	hPFFraction_genm[nj][nmult-1][2]->Fill(recopt,iJet->chargedSum[gj]/rawpt);
	
	hNjets_genm [nj][multb]->Fill(refpt);
	hgenpt_genm [nj][multb]->Fill(refpt,wxs*wcen*wvz);
	hrecopt_genm[nj][multb]->Fill(recopt,wxs*wcen*wvz);	  
	hrawpt_genm [nj][multb]->Fill(rawpt,wxs*wcen*wvz);

	hNjets_genm [nj][nmult-1]->Fill(refpt);
	hgenpt_genm [nj][nmult-1]->Fill(refpt,wxs*wcen*wvz);
	hrecopt_genm[nj][nmult-1]->Fill(recopt,wxs*wcen*wvz);	  
	hrawpt_genm [nj][nmult-1]->Fill(rawpt,wxs*wcen*wvz);
	
	//! Very fine bin in ref pt
	hrescrpt_genm[nj][multb]->Fill(refpt,recopt/refpt,wxs*wcen*wvz);
	hresrrpt_genm[nj][multb]->Fill(refpt,rawpt/refpt,wxs*wcen*wvz);
	hresrcrpt_genm[nj][multb]->Fill(recopt,recopt/rawpt,wxs*wcen*wvz);

	hrescrpt_genm [nj][nmult-1]->Fill(refpt,recopt/refpt,wxs*wcen*wvz);
	hresrrpt_genm [nj][nmult-1]->Fill(refpt,rawpt/refpt,wxs*wcen*wvz);
	hresrcrpt_genm[nj][nmult-1]->Fill(recopt,recopt/rawpt,wxs*wcen*wvz);

	//! Very fine bin in ref eta
	hrescreta_genm[nj][multb]->Fill(refeta,recopt/refpt,wxs*wcen*wvz);
	hresrreta_genm[nj][multb]->Fill(refeta,rawpt/refpt,wxs*wcen*wvz);
	hresrcreta_genm[nj][multb]->Fill(recoeta,recopt/rawpt,wxs*wcen*wvz);

	hrescreta_genm[nj][nmult-1]->Fill(refeta,recopt/refpt,wxs*wcen*wvz);
	hresrreta_genm[nj][nmult-1]->Fill(refeta,rawpt/refpt,wxs*wcen*wvz);
	hresrcreta_genm[nj][nmult-1]->Fill(recoeta,recopt/rawpt,wxs*wcen*wvz);


        //! Response in different eta and phi bins
        int etabin = GetEtaBin(fabs(refeta));
	int phibin = GetPhiBin(refphi);

        //! Response in eta and phi bins
        if(etabin >= 0 && etabin<maxe){
	  hpteta[nj][multb][etabin]->Fill(refpt,recopt/refpt,wxs*wcen*wvz);
	  hpteta[nj][nmult-1][etabin]->Fill(refpt,recopt/refpt,wxs*wcen*wvz);
	}
        if(phibin >= 0 && phibin<maxph){
	  hptphi[nj][multb][phibin]->Fill(refpt,recopt/refpt,wxs*wcen*wvz);
	  hptphi[nj][nmult-1][phibin]->Fill(refpt,recopt/refpt,wxs*wcen*wvz);
	}
      }//! igen loop
      hNevt[nj][multb]->Fill(vz,wxs*wcen*wvz);
      hNevt[nj][nmult-1]->Fill(vz,wxs*wcen*wvz);

      delete [] ljet;
    }//! nj jet loop

    if(istat){
      hBin->Fill(hiBin,wxs*wcen*wvz);
      hVz->Fill(vz,wxs*wcen*wvz);
      hHF->Fill(hiHF,wxs*wcen*wvz);

      hNTracks->Fill(ntracks,wxs*wcen*wvz);
      hNTracksHF->Fill(ntracks,hiHF,wxs*wcen*wvz);
      hBinHF->Fill(hiBin,hiHF,wxs*wcen*wvz);
      hBinNTracks->Fill(hiBin,ntracks,wxs*wcen*wvz);
      hNTracksHFplusEta4->Fill(ntracks,HFplusEta4,wxs*wcen*wvz);
      iEvent++;
    }
    //std::cout<<"Completed event #  "<<ievt<<std::endl; 
  }//! event loop ends
  
  std::cout<<std::endl;
  std::cout<<std::endl;
  std::cout<<std::endl;

  std::cout<<"Events which passed the pT hat cut : "<<hTotEve->Integral()<<" out of  : "<<hEvt->Integral()
	   <<" efficiency of all the cuts : " <<hTotEve->Integral()/hEvt->Integral()<<std::endl;
  std::cout<<std::endl;


  for(int nj=0;nj<knj;nj++){
    std::cout<<"# of Events for : "<<cjets[nj]<<"\t"<<hNevt[nj][nmult-1]->Integral()<<"\t # of Jets : "<<hNjets_genm[nj][nmult-1]->Integral()<<std::endl;
  }

  //! Write to output file
  fout->cd();
  fout->Write();
  fout->Close();


  //! Check
  timer.Stop();
  double rtime  = timer.RealTime();
  double ctime  = timer.CpuTime();

  std::cout<<std::endl;
  std::cout<<Form("RealTime=%f seconds, CpuTime=%f seconds",rtime,ctime)<<std::endl;
  std::cout<<std::endl;
  std::cout<<"Good bye : " <<"\t"<<std::endl;
  return 1;
}
Example #12
0
void DoubleHiggsAnalysis::Analyze(){

  Long64_t numberOfEntries = treeReader_->GetEntries();

  // Get pointers to branches used in this analysis
  TClonesArray *branchJet = treeReader_->UseBranch("Jet");
  TClonesArray *branchPhoton = treeReader_->UseBranch("Photon");
  TClonesArray *branchElectron = treeReader_->UseBranch("Electron");
  TClonesArray *branchMuon = treeReader_->UseBranch("Muon");

  TH1F *histPhoMass = new TH1F("mass", "M_{inv}(#gamma#gamma)", 100, 100.0, 180.0);

  //setXsec
  getProcessXsec();
  setGenEvents(numberOfEntries);
  setEventWeight();
  eventWeight_t=eventWeight_;

  cout<<"starting loop on "<<numberOfEntries<<" entries"<<endl;
  // Loop over all events
  for(Int_t entry = 0; entry < numberOfEntries; ++entry)
    {
      if(entry%300 == 0)cout<<"### Processing entry: "<<entry<<endl; 
    // Load selected branches with data from specified event
      treeReader_->ReadEntry(entry);
      bool passedJetSelection=false;
      bool passedPhotonSelection=false;
      bool passedLeptonSelection=false;      

      bool looseBtagWP=false;

      Photon *pho1, *pho2;
      // Filling photon variables
      pho1 = (Photon *) branchPhoton->At(0);
      pho2 = (Photon *) branchPhoton->At(1);
      
      passedPhotonSelection=PhotonSelection(branchPhoton);
      if (passedPhotonSelection){
	counters_photonSel_++;
	passedJetSelection=JetSelection(branchJet, looseBtagWP,pho1,pho2);
	passedLeptonSelection=LeptonSelection(branchElectron,branchMuon,pho1,pho2);
      }
      
      //filling histograms and tree
      if(passedJetSelection && passedPhotonSelection){
	counters_jetSel_++;

	ptPhot1_t=pho1->PT;
	ptPhot2_t=pho2->PT;
	etaPhot1_t=pho1->Eta;
	etaPhot2_t=pho2->Eta;
	if(etaPhot2_t == 0)cout<<"--------"<<endl;
	phiPhot1_t=pho1->Phi;
	phiPhot2_t=pho2->Phi;
	histPhoMass->Fill(((pho1->P4()) + (pho2->P4())).M());

	//Filling jet variables
	jet1 = (Jet*) branchJet->At(bjet_indexes.first);
	jet2 = (Jet*) branchJet->At(bjet_indexes.second);

	ptJet_t[0]=jet1->PT;
	ptJet_t[1]=jet2->PT;
	etaJet_t[0]=jet1->Eta;
	etaJet_t[1]=jet2->Eta;
	phiJet_t[0]=jet1->Phi;
	phiJet_t[1]=jet2->Phi;

	deltaRGammaGamma_t=(pho1->P4().DeltaR(pho2->P4()));
	deltaRBB_t=(jet1->P4().DeltaR(jet2->P4()));
	minDeltaRGammaB_t=(pho1->P4().DeltaR(jet1->P4()));
	if(pho1->P4().DeltaR(jet2->P4()) < minDeltaRGammaB_t )minDeltaRGammaB_t=pho1->P4().DeltaR(jet2->P4());
	if(pho2->P4().DeltaR(jet1->P4()) < minDeltaRGammaB_t )minDeltaRGammaB_t=pho2->P4().DeltaR(jet1->P4());
	if(pho2->P4().DeltaR(jet2->P4()) < minDeltaRGammaB_t )minDeltaRGammaB_t=pho2->P4().DeltaR(jet2->P4());
	ptGG_t=(pho1->P4()+pho2->P4()).Pt();
	ptBB_t=(jet1->P4()+jet2->P4()).Pt();
	ptBBGG_t=ptBB_t+ptGG_t;
	mgg_t=((pho1->P4()) + (pho2->P4())).M();
	mbb_t=(jet1->P4()+jet2->P4()).M();
	mggbb_t=((pho1->P4()+pho2->P4())+(jet1->P4()+jet2->P4())).M();

	bool passedAdditionalCuts=false;
	float deltaRGGcut=2.;
	float deltaRGBcut=1.5;
	float deltaRBBcut=2.;
	int njetsCut=4;
	passedAdditionalCuts=additionalCuts(deltaRGGcut,deltaRGBcut,deltaRBBcut,njetsCut);
	if(passedAdditionalCuts){
	  counters_additionalCuts_++;
	  tree_passedEvents->Fill();
	  if((mgg_t>120. && mgg_t<130.) && (mbb_t >105. && mbb_t<145.))counters_massWindow_++;
	}
      }
    }
  
  histPhoMass->Write();
  tree_passedEvents->Write();
  outFile_->Write();
  outFile_->Close();

}
Example #13
0
void hbbNN(Int_t ntrain=15) {
// Example of a Multi Layer Perceptron
// For a Tevatron search for SUSY Higgs in bh->bbb, a neural network 
// was used to separate the signal from the background passing 
// some selection cuts. Here is a simplified version of this network, 
// taking into account only bbb events.
//Author: P. Jonsson

//Part 1, preparing the inputs

//Booking some histograms for signal and background, 
//Add histograms yourself for the dijet mass (MH[0]) of the leading pT 
//(=transverse momenta) jets for background and signal  

   TH1F *detas = new TH1F("detas", "detas", 50, .0, 4.);
   TH1F *detab = new TH1F("detab", "detab", 50, .0, 4.);   
   TH1F *dphis = new TH1F("dphis", "dphis", 50, .0, 3.15);
   TH1F *dphib = new TH1F("dphib", "dphib", 50, .0, 3.15);  
   TH1F *angles = new TH1F("angles", "angles", 50, .0, 2.);
   TH1F *angleb = new TH1F("angleb", "angleb", 50, .0, 2.);  
   TH1F *pbalances = new TH1F("pbalances", "pbalances", 50, .0, 1.);
   TH1F *pbalanceb = new TH1F("pbalanceb", "pbalanceb", 50, .0, 1.); 
   TH1F *etahs = new TH1F("etahs", "etahs", 50, -2.5, 2.5);
   TH1F *etahb = new TH1F("etahb", "etahb", 50, -2.5, 2.5);  
   TH1F *sphericitys = new TH1F("sphericitys", "sphericitys", 50, .0, 1.);
   TH1F *sphericityb = new TH1F("sphericityb", "sphericityb", 50, .0, 1.); 

   if (!gROOT->GetClass("TMultiLayerPerceptron")) {
      gSystem->Load("libMLP");
   }

   // Prepare inputs
   // The 2 trees are merged into one, and a "type" branch, 
   // equal to 1 for the signal and 0 for the background is added.

   TChain * signal = new TChain("higgsSearch","");

   //Use a Higgs signal at a mass of  110 GeV   
    signal->Add("LHinput-cut_2b25_1j15-Tight-MC_higgs110GeV.root/higgsSearch");

    //Use a background of multijet bbb events
   TChain *background = new TChain("higgsSearch","");
   background->Add("LHinput-cut_2b25_1j15-Tight-MC_bbb.root/higgsSearch");

   //book combined tree of selected events top use for training
   TFile *f = new TFile("training.root","recreate");
   TTree *simu = new TTree("MonteCarlo", "Filtered Monte Carlo Events");

   Double_t nnoutxlm[4], MH[6], dEta[6], dPhi[6], Angle[6], EtaH[6], pBalance[6], Sphericity;
   Double_t dphi, deta, angle, etah, pbalance, sphericity; 
   Int_t Njets, typeH[6], typeO, nsignal, nbkg;

   //counters for signal and background events
   nsignal=0;
   nbkg=0;

   // 
   //Set branch addresses to use from signal and background trees
   //Description of variables inline below. 
   //Draw histograms of these  variables for signal and background on top 
   //of eachother in different colors. 
   //Save these plots (you can look up how to save plots to files at root.cern.ch)
 
   //Invariant di-jet mass
   signal->SetBranchAddress("MH",  &MH);

   //Delta eta, difference in pseudorapidity (spatial coodinate used to 
   //describe angle with the beam axis = -ln(tan(theta/2))
   signal->SetBranchAddress("dEta",    &dEta);

   //Delta phi, azimuthal angle (going from 0 to 2pi around the beampipe)
   signal->SetBranchAddress("dPhi",  &dPhi);

   //Angle between the leading jet and the combined jet-pair
   signal->SetBranchAddress("Eta1mEtaH", &Angle);

   //Pseudorapidity of the combined jet-pair
   signal->SetBranchAddress("EtaH",  &EtaH);

   //Which jet-pair comes from the true Higgs decay
   signal->SetBranchAddress("type", &typeH);

   //Momentum balance of the jet-pair: p1-p2/p1+p2 
   signal->SetBranchAddress("pBalance",  &pBalance);

   //Number of jets in the event 
   signal->SetBranchAddress("Njets", &Njets);

   //Event sphericity (measure of how spherical, round, the event is)
   signal->SetBranchAddress("FW_H2", &Sphericity);

   //same for background
   background->SetBranchAddress("MH",  &MH);
   background->SetBranchAddress("dEta",    &dEta);
   background->SetBranchAddress("dPhi",  &dPhi);
   background->SetBranchAddress("Eta1mEtaH", &Angle);
   background->SetBranchAddress("EtaH",  &EtaH);
   background->SetBranchAddress("pBalance",  &pBalance);
   background->SetBranchAddress("Njets", &Njets);
   background->SetBranchAddress("FW_H2", &Sphericity);

   //Make input branches of variables to use for the training
   simu->Branch("dEta", &deta, "dEta/D");
   simu->Branch("dPhi",  &dphi,  "dPhi/D");
   simu->Branch("Angle",    &angle,    "Angle/D");
   simu->Branch("pBalance",  &pbalance,  "pBalance/D");
   simu->Branch("EtaH", &etah, "EtaH/D");
   simu->Branch("Sphericity",  &sphericity,  "Sphericity/D");
   simu->Branch("type",   &typeO,   "type/I");
  
   //loop over signal and select events to use for training 
   Int_t i;
   for (i = 0; i < signal->GetEntries(); i++) {
     signal->GetEntry(i);
     //only consider events with 3 jets
      if (Njets==3){
          typeO=0; 
          //select only events where the two leading pT jets come from the 
	  //Higgs decay (typeH[0]==1), and these two jets are separated by 
	  //sqrt(dEta[0]*dEta[0]+dPhi[0]*dPhi[0]) > 1, and the invariant 
          //di-jet mass is greater than 50 GeV
          if (typeH[0]==1 && sqrt(dEta[0]*dEta[0]+dPhi[0]*dPhi[0]) > 1. && MH[0]>50.){          
	    deta = dEta[0];
	    dphi =2*acos(0)- dPhi[0]; 
            angle = Angle[0];
            pbalance = pBalance[0];
            etah = EtaH[0];
            sphericity = Sphericity;
            typeO=1; 
	   }
	  //fill selected signal events (type0==1)
          if (typeO==1){
	    //fill the histograms like this:
	      detas->Fill(deta); 	      
	      dphis->Fill(dphi);
	      angles->Fill(angle);
	      pbalances->Fill(pbalance);
	      etahs->Fill(etah);
	      sphericitys->Fill(sphericity);


	      //fill the training tree   
              simu->Fill();
              nsignal++; 
	  }
      }
   }

   cout << nsignal <<endl; 
   //now loop over background events
   for (i = 0; i < background->GetEntries(); i++) {
      background->GetEntry(i);
      if (Njets==3){
          typeO=1;
	  //similar for background events
          if (sqrt(dEta[0]*dEta[0]+dPhi[0]*dPhi[0]) > 1. && MH[0]>50.){
	    deta = dEta[0];
	    dphi =2*acos(0)- dPhi[0]; 
            angle = Angle[0];
            pbalance = pBalance[0];
            etah = EtaH[0];
            sphericity = Sphericity;
            typeO=0; 
          }
	  //fill the selected background events until you have the same 
          //number as signal
          if (typeO==0 && nbkg<nsignal){
	    //fill the background histograms here:
    	      detab->Fill(deta); 	      
    	      dphib->Fill(dphi);
    	      angleb->Fill(angle);
    	      pbalanceb->Fill(pbalance);
    	      etahb->Fill(etah);
    	      sphericityb->Fill(sphericity);
            
	    
	    
	    nbkg++;
            simu->Fill();
	  } 
      }

   }
   cout << nbkg << endl;   


   	/*Plot the simulated and background variable distributions */
	TCanvas *c1 = new TCanvas("c2", "Signal and Background Distributions");
	c1->Divide(2,3);
	c1->cd(1);  dphis->Draw();       dphib->	SetLineColor(kRed);   dphib->Draw("same");	
	c1->cd(2);  detas->Draw();       detab->	SetLineColor(kRed);   detab->Draw("same");	
	c1->cd(3);  angles->Draw();      angleb->	SetLineColor(kRed);   angleb->Draw("same");	
	c1->cd(4);  pbalances ->Draw();  pbalanceb->	SetLineColor(kRed);   pbalanceb ->Draw("same");	
	c1->cd(5);  etahs->Draw();       etahb->	SetLineColor(kRed);   etahb->Draw("same");	
	c1->cd(6);  sphericitys->Draw(); sphericityb->	SetLineColor(kRed);   sphericityb->Draw("same");	
	c1->SaveAs("sig_background_distr.pdf");	
	


	for(Int_t i = 1; i++; i < 5)
	{ 
		stringstream ss;
		ss << i*5;
		TString structure = "@dEta, @dPhi, @EtaH, @pBalance, @Sphericity, @Angle:" + ss.str() + ":1:type";;
		trainNetwork(simu, structure, 100);

	}
}
Example #14
0
void pmt_testing(char* input_file) {

  Double_t width = 1000;
  Double_t height = 1000;
  TCanvas * canvas = new TCanvas("canvas", "PMT Testing", 0, 0, width, height);
  canvas->SetWindowSize(width + (width - canvas->GetWw()), 
                        height + (height - canvas->GetWh()));

  //Parameters
  Int_t nbins = 40;
  Double_t min = 550000; //hist min/max values
  Double_t max = 600000; //Must be better way to get these!

  //Initialized variables
  Int_t num_data_points = 0;
  Int_t pulse;
  Int_t channel;
  Int_t total_channels;
  const Int_t pedestal = 2020; //how to determine this?

  TFile *file = new TFile("adc_data.root", "recreate"); 

  //Style settings
  gROOT->SetStyle("Plain");
  gStyle->SetPalette(53);
  gStyle->SetOptStat(111111);
  gStyle->SetOptFit(1111);
  gStyle->SetStatBorderSize(0);
  gStyle->SetOptTitle(1); 

  
  //Prepare Data
  //Create nTuple
  TTree *t1 = new TTree("t1", "ADC Data");
  t1->Branch("pulse", &pulse, "pulse/I");
  t1->Branch("channel", &channel, "channel/I");

 
  ifstream in;
  in.open(input_file);
  //Fill TTree
  while ( in >> channel) {
    if (num_data_points % 2520 == 0)
      pulse++;  
    t1->Fill();
    num_data_points++;
  }
  in.close();

  TH1F * spectrum = new TH1F("spectrum", "ADC Spectrum; Accumulated Channels; Counts", nbins, min, max); 
  //spectrum->SetBit(TH1::kCanRebin);
  spectrum->Sumw2(); 
  for(Int_t i = 0; i < t1->GetEntries(); i++) {
    t1->GetEntry(i);
    if (i % 2520 == 0) {
      cout << "total_channels = " << total_channels << endl;
      spectrum->Fill(total_channels);
      total_channels = 0;
    }
    total_channels += TMath::Abs(channel - pedestal);
  }

  spectrum->SetLineWidth(2);
  spectrum->SetMarkerColor(kBlack);
  spectrum->SetLineColor(kBlack);

  // Fit Gaussian to curve and Draw
  spectrum->Fit("gaus");
  spectrum->GetFunction("gaus")->SetLineColor(kRed);
  spectrum->Draw("Same");
  t1->Write();
  spectrum->Write();
}
Example #15
0
int
Proto2ShowerCalib::process_event(PHCompositeNode *topNode)
{

  if (verbosity > 2)
    cout << "Proto2ShowerCalib::process_event() entered" << endl;

  // init eval objects
  _eval_run.reset();
  _eval_3x3_raw.reset();
  _eval_5x5_raw.reset();
  _eval_3x3_prod.reset();
  _eval_5x5_prod.reset();
  _eval_3x3_temp.reset();
  _eval_5x5_temp.reset();
  _eval_3x3_recalib.reset();
  _eval_5x5_recalib.reset();

  Fun4AllHistoManager *hm = get_HistoManager();
  assert(hm);

  if (not _is_sim)
    {
      PdbParameterMap *info = findNode::getClass<PdbParameterMap>(topNode,
          "RUN_INFO");

      assert(info);

      PHG4Parameters run_info_copy("RunInfo");
      run_info_copy.FillFrom(info);

      _eval_run.beam_mom = run_info_copy.get_double_param("beam_MTNRG_GeV");

      TH1F * hBeam_Mom = dynamic_cast<TH1F *>(hm->getHisto("hBeam_Mom"));
      assert(hBeam_Mom);

      hBeam_Mom->Fill(_eval_run.beam_mom);
    }

  EventHeader* eventheader = findNode::getClass<EventHeader>(topNode,
      "EventHeader");
  if (not _is_sim)
    {
      assert(eventheader);

      _eval_run.run = eventheader->get_RunNumber();
      if (verbosity > 4)
        cout << __PRETTY_FUNCTION__ << _eval_run.run << endl;

      _eval_run.event = eventheader->get_EvtSequence();
    }

  if (_is_sim)
    {

      PHG4TruthInfoContainer* truthInfoList = findNode::getClass<
          PHG4TruthInfoContainer>(topNode, "G4TruthInfo");

      assert(truthInfoList);

      _eval_run.run = -1;

      const PHG4Particle * p = truthInfoList->GetPrimaryParticleRange().first->second;
      assert(p);

      const PHG4VtxPoint * v = truthInfoList->GetVtx(p->get_vtx_id());
      assert(v);

      _eval_run.beam_mom = sqrt(
          p->get_px() * p->get_px() + p->get_py() * p->get_py()
              + p->get_pz() * p->get_pz());
      _eval_run.truth_y = v->get_y();
      _eval_run.truth_z = v->get_z();

    }

  // normalization
  TH1F * hNormalization = dynamic_cast<TH1F *>(hm->getHisto("hNormalization"));
  assert(hNormalization);

  hNormalization->Fill("ALL", 1);

  RawTowerContainer* TOWER_RAW_CEMC = findNode::getClass<RawTowerContainer>(
      topNode, _is_sim ? "TOWER_RAW_LG_CEMC" : "TOWER_RAW_CEMC");
  assert(TOWER_RAW_CEMC);
  RawTowerContainer* TOWER_CALIB_CEMC = findNode::getClass<RawTowerContainer>(
      topNode, _is_sim ? "TOWER_CALIB_LG_CEMC" : "TOWER_CALIB_CEMC");
  assert(TOWER_CALIB_CEMC);

  // other nodes
  RawTowerContainer* TOWER_CALIB_TRIGGER_VETO = findNode::getClass<
      RawTowerContainer>(topNode, "TOWER_CALIB_TRIGGER_VETO");
  if (not _is_sim)
    {
      assert(TOWER_CALIB_TRIGGER_VETO);
    }

  RawTowerContainer* TOWER_CALIB_HODO_HORIZONTAL = findNode::getClass<
      RawTowerContainer>(topNode, "TOWER_CALIB_HODO_HORIZONTAL");
  if (not _is_sim)
    {
      assert(TOWER_CALIB_HODO_HORIZONTAL);
    }
  RawTowerContainer* TOWER_CALIB_HODO_VERTICAL = findNode::getClass<
      RawTowerContainer>(topNode, "TOWER_CALIB_HODO_VERTICAL");
  if (not _is_sim)
    {
      assert(TOWER_CALIB_HODO_VERTICAL);
    }

  RawTowerContainer* TOWER_TEMPERATURE_EMCAL = findNode::getClass<
      RawTowerContainer>(topNode, "TOWER_TEMPERATURE_EMCAL");
  if (not _is_sim)
    {
      assert(TOWER_TEMPERATURE_EMCAL);
    }

  RawTowerContainer* TOWER_CALIB_C1 = findNode::getClass<RawTowerContainer>(
      topNode, "TOWER_CALIB_C1");
  if (not _is_sim)
    {
      assert(TOWER_CALIB_C1);
    }
  RawTowerContainer* TOWER_CALIB_C2 = findNode::getClass<RawTowerContainer>(
      topNode, "TOWER_CALIB_C2");
  if (not _is_sim)
    {
      assert(TOWER_CALIB_C2);
    }

  // Cherenkov
  bool cherekov_e = false;
  if (not _is_sim)
    {
      RawTower * t_c2_in = NULL;
      RawTower * t_c2_out = NULL;

      assert(eventheader);
      if (eventheader->get_RunNumber() >= 2105)
        {
          t_c2_in = TOWER_CALIB_C2->getTower(10);
          t_c2_out = TOWER_CALIB_C2->getTower(11);
        }
      else
        {
          t_c2_in = TOWER_CALIB_C2->getTower(0);
          t_c2_out = TOWER_CALIB_C2->getTower(1);
        }
      assert(t_c2_in);
      assert(t_c2_out);

      const double c2_in = t_c2_in->get_energy();
      const double c2_out = t_c2_out->get_energy();
      const double c1 = TOWER_CALIB_C1->getTower(0)->get_energy();

      _eval_run.C2_sum = c2_in + c2_out;
      cherekov_e = (_eval_run.C2_sum) > 100;
      hNormalization->Fill("C2-e", cherekov_e);

      TH2F * hCheck_Cherenkov = dynamic_cast<TH2F *>(hm->getHisto(
          "hCheck_Cherenkov"));
      assert(hCheck_Cherenkov);
      hCheck_Cherenkov->Fill(c1, "C1", 1);
      hCheck_Cherenkov->Fill(c2_in, "C2 in", 1);
      hCheck_Cherenkov->Fill(c2_out, "C2 out", 1);
      hCheck_Cherenkov->Fill(c2_in + c2_out, "C2 sum", 1);
    }

  // veto
  TH1F * hCheck_Veto = dynamic_cast<TH1F *>(hm->getHisto("hCheck_Veto"));
  assert(hCheck_Veto);
  bool trigger_veto_pass = true;
  if (not _is_sim)
    {
      auto range = TOWER_CALIB_TRIGGER_VETO->getTowers();
      for (auto it = range.first; it != range.second; ++it)
        {
          RawTower* tower = it->second;
          assert(tower);

          hCheck_Veto->Fill(tower->get_energy());

          if (abs(tower->get_energy()) > 15)
            trigger_veto_pass = false;
        }
    }
  hNormalization->Fill("trigger_veto_pass", trigger_veto_pass);
  _eval_run.trigger_veto_pass = trigger_veto_pass;

  // hodoscope
  TH1F * hCheck_Hodo_H = dynamic_cast<TH1F *>(hm->getHisto("hCheck_Hodo_H"));
  assert(hCheck_Hodo_H);
  int hodo_h_count = 0;
  if (not _is_sim)
    {
      auto range = TOWER_CALIB_HODO_HORIZONTAL->getTowers();
      for (auto it = range.first; it != range.second; ++it)
        {
          RawTower* tower = it->second;
          assert(tower);

          hCheck_Hodo_H->Fill(tower->get_energy());

          if (abs(tower->get_energy()) > 30)
            {
              hodo_h_count++;
              _eval_run.hodo_h = tower->get_id();
            }
        }
    }
  const bool valid_hodo_h = hodo_h_count == 1;
  hNormalization->Fill("valid_hodo_h", valid_hodo_h);
  _eval_run.valid_hodo_h = valid_hodo_h;

  TH1F * hCheck_Hodo_V = dynamic_cast<TH1F *>(hm->getHisto("hCheck_Hodo_V"));
  assert(hCheck_Hodo_V);
  int hodo_v_count = 0;
  if (not _is_sim)
    {
      auto range = TOWER_CALIB_HODO_VERTICAL->getTowers();
      for (auto it = range.first; it != range.second; ++it)
        {
          RawTower* tower = it->second;
          assert(tower);

          hCheck_Hodo_V->Fill(tower->get_energy());

          if (abs(tower->get_energy()) > 30)
            {
              hodo_v_count++;
              _eval_run.hodo_v = tower->get_id();
            }
        }
    }
  const bool valid_hodo_v = hodo_v_count == 1;
  _eval_run.valid_hodo_v = valid_hodo_v;
  hNormalization->Fill("valid_hodo_v", valid_hodo_v);

  const bool good_e = (valid_hodo_v and valid_hodo_h and cherekov_e
      and trigger_veto_pass) and (not _is_sim);
  hNormalization->Fill("good_e", good_e);

  // simple clustering
  pair<int, int> max_3x3 = find_max(TOWER_CALIB_CEMC, 3);
  pair<int, int> max_5x5 = find_max(TOWER_CALIB_CEMC, 5);

  _eval_3x3_raw.max_col = max_3x3.first;
  _eval_3x3_raw.max_row = max_3x3.second;
  _eval_3x3_prod.max_col = max_3x3.first;
  _eval_3x3_prod.max_row = max_3x3.second;
  _eval_3x3_temp.max_col = max_3x3.first;
  _eval_3x3_temp.max_row = max_3x3.second;
  _eval_3x3_recalib.max_col = max_3x3.first;
  _eval_3x3_recalib.max_row = max_3x3.second;

  _eval_5x5_raw.max_col = max_5x5.first;
  _eval_5x5_raw.max_row = max_5x5.second;
  _eval_5x5_prod.max_col = max_5x5.first;
  _eval_5x5_prod.max_row = max_5x5.second;
  _eval_5x5_temp.max_col = max_5x5.first;
  _eval_5x5_temp.max_row = max_5x5.second;
  _eval_5x5_recalib.max_col = max_5x5.first;
  _eval_5x5_recalib.max_row = max_5x5.second;

  // tower
  bool good_temp = true;
  double sum_energy_calib = 0;
  double sum_energy_T = 0;
  TH1F * hTemperature = dynamic_cast<TH1F *>(hm->getHisto("hTemperature"));
  assert(hTemperature);

  stringstream sdata;

  if (good_e)
    sdata << abs(_eval_run.beam_mom) << "\t";

  // tower temperature and recalibration
    {
      auto range = TOWER_CALIB_CEMC->getTowers();
      for (auto it = range.first; it != range.second; ++it)
        {

          RawTowerDefs::keytype key = it->first;
          RawTower* tower = it->second;
          assert(tower);

          const int col = tower->get_bineta();
          const int row = tower->get_binphi();

          if (col < 0 or col >= 8)
            continue;
          if (row < 0 or row >= 8)
            continue;

          const double energy_calib = tower->get_energy();
          sum_energy_calib += energy_calib;

          RawTower* tower_raw = TOWER_RAW_CEMC->getTower(key);
          assert(tower_raw);

          double energy_T = 0;
          if (not _is_sim)
            {
              RawTower_Temperature * temp_t =
                  dynamic_cast<RawTower_Temperature *>(TOWER_TEMPERATURE_EMCAL->getTower(
                      tower->get_row(), tower->get_column())); // note swap of col/row in temperature storage
              assert(temp_t);

              const double T = temp_t->get_temperature_from_time(
                  eventheader->get_TimeStamp());
              hTemperature->Fill(T);

              if (T < 25 or T > 35)
                good_temp = false;

              energy_T = TemperatureCorrection::Apply(energy_calib, T);
            }

          // recalibration
          assert(
              _recalib_const.find(make_pair(col, row)) != _recalib_const.end());
          const double energy_recalib = energy_T
              * _recalib_const[make_pair(col, row)];

          // energy sums
          sum_energy_T += energy_T;

          // calibration file
//          sdata << tower->get_energy() << "\t";
          // calibration file - only output 5x5 towers
          if (col >= max_5x5.first - 2 and col <= max_5x5.first + 2
              and row >= max_5x5.second - 2 and row <= max_5x5.second + 2)
            {
              sdata << tower->get_energy() << "\t";
            }
          else
            {
              sdata << 0 << "\t";
            }

          // cluster 3x3
          if (col >= max_3x3.first - 1 and col <= max_3x3.first + 1)
            if (row >= max_3x3.second - 1 and row <= max_3x3.second + 1)
              {
                // in cluster

                _eval_3x3_raw.average_col += abs(tower_raw->get_energy()) * col;
                _eval_3x3_raw.average_row += abs(tower_raw->get_energy()) * row;
                _eval_3x3_raw.sum_E += abs(tower_raw->get_energy());

                _eval_3x3_prod.average_col += energy_calib * col;
                _eval_3x3_prod.average_row += energy_calib * row;
                _eval_3x3_prod.sum_E += energy_calib;

                _eval_3x3_temp.average_col += energy_T * col;
                _eval_3x3_temp.average_row += energy_T * row;
                _eval_3x3_temp.sum_E += energy_T;

                _eval_3x3_recalib.average_col += energy_recalib * col;
                _eval_3x3_recalib.average_row += energy_recalib * row;
                _eval_3x3_recalib.sum_E += energy_recalib;
              }

          // cluster 5x5
          if (col >= max_5x5.first - 2 and col <= max_5x5.first + 2)
            if (row >= max_5x5.second - 2 and row <= max_5x5.second + 2)
              {
                // in cluster

                _eval_5x5_raw.average_col += abs(tower_raw->get_energy()) * col;
                _eval_5x5_raw.average_row += abs(tower_raw->get_energy()) * row;
                _eval_5x5_raw.sum_E += abs(tower_raw->get_energy());

                _eval_5x5_prod.average_col += energy_calib * col;
                _eval_5x5_prod.average_row += energy_calib * row;
                _eval_5x5_prod.sum_E += energy_calib;

                _eval_5x5_temp.average_col += energy_T * col;
                _eval_5x5_temp.average_row += energy_T * row;
                _eval_5x5_temp.sum_E += energy_T;

                _eval_5x5_recalib.average_col += energy_recalib * col;
                _eval_5x5_recalib.average_row += energy_recalib * row;
                _eval_5x5_recalib.sum_E += energy_recalib;
              }
        }
    }

  _eval_3x3_raw.reweight_clus_pol();
  _eval_5x5_raw.reweight_clus_pol();
  _eval_3x3_prod.reweight_clus_pol();
  _eval_5x5_prod.reweight_clus_pol();
  _eval_3x3_temp.reweight_clus_pol();
  _eval_5x5_temp.reweight_clus_pol();
  _eval_3x3_recalib.reweight_clus_pol();
  _eval_5x5_recalib.reweight_clus_pol();

  const double EoP = sum_energy_T / abs(_eval_run.beam_mom);
  hNormalization->Fill("good_temp", good_temp);

  bool good_data = good_e and good_temp;
  hNormalization->Fill("good_data", good_data);

  _eval_run.good_temp = good_temp;
  _eval_run.good_e = good_e;
  _eval_run.good_data = good_data;
  _eval_run.sum_energy_T = sum_energy_T;
  _eval_run.EoP = EoP;

  // E/p
  if (good_data)
    {
      if (verbosity >= 3)
        cout << __PRETTY_FUNCTION__ << " sum_energy_calib = "
            << sum_energy_calib << " sum_energy_T = " << sum_energy_T
            << " _eval_run.beam_mom = " << _eval_run.beam_mom << endl;

      TH2F * hEoP = dynamic_cast<TH2F *>(hm->getHisto("hEoP"));
      assert(hEoP);

      hEoP->Fill(EoP, abs(_eval_run.beam_mom));
    }

  // calibration file
  if (good_data and abs(_eval_run.beam_mom) >= 4
      and abs(_eval_run.beam_mom) <= 8)
    {
      assert(fdata.is_open());

      fdata << sdata.str();

      fdata << endl;
    }

  TTree * T = dynamic_cast<TTree *>(hm->getHisto("T"));
  assert(T);
  T->Fill();

  return Fun4AllReturnCodes::EVENT_OK;
}
Example #16
0
int main (int argc, char** argv)
{

  if (argc < 3) {
    printHelp() ;
    exit (1) ;
  }

  std::string inputfiles, inputdir ;
  std::string outputRootName = "histoTPG.root" ;
  int verbose = 0 ;
  int occupancyCut = 0 ;
  std::string l1algo ; 

  bool ok(false) ;
  for (int i=0 ; i<argc ; i++) {
    if (argv[i] == std::string("-h") ) {
      printHelp() ;
      exit(1);
    }
    if (argv[i] == std::string("-i") && argc>i+1) {
      ok = true ;
      inputfiles = argv[i+1] ;
    }
    if (argv[i] == std::string("-d") && argc>i+1) inputdir = argv[i+1] ;
    if (argv[i] == std::string("-o") && argc>i+1) outputRootName = argv[i+1] ;
    if (argv[i] == std::string("-v") && argc>i+1) verbose = atoi(argv[i+1]) ;
    if (argv[i] == std::string("-l1") && argc>i+1) l1algo =  std::string(argv[i+1]) ;
    if (argv[i] == std::string("--cutTPOccup") && argc>i+1) occupancyCut = atoi(argv[i+1]) ;
  }
  if (!ok) {
    std::cout<<"No input files have been given: nothing to do!"<<std::endl ;
    printHelp() ;
    exit(1);
  }
  
  std::vector<int> algobits ;
  std::vector<std::string> algos = split(l1algo,",") ;
  for (unsigned int i=0 ; i<algos.size() ; i++) algobits.push_back(atoi(algos[i].c_str())) ;


  unsigned int ref = 2 ;



  ///////////////////////
  // book the histograms
  ///////////////////////

  TH2F * occupancyTP = new TH2F("occupancyTP", "Occupancy TP data", 72, 1, 73, 38, -19, 19) ;
  occupancyTP->GetYaxis()->SetTitle("eta index") ;
  occupancyTP->GetXaxis()->SetTitle("phi index") ;
  TH2F * occupancyTPEmul = new TH2F("occupancyTPEmul", "Occupancy TP emulator", 72, 1, 73, 38, -19, 19) ;
  occupancyTPEmul->GetYaxis()->SetTitle("eta index") ;
  occupancyTPEmul->GetXaxis()->SetTitle("phi index") ;

  TH1F * TP = new TH1F("TP", "TP", 256, 0., 256.) ;
  TP->GetXaxis()->SetTitle("TP (ADC)") ;
  TH1F * TPEmul = new TH1F("TPEmul", "TP Emulator", 256, 0., 256.) ;
  TPEmul->GetXaxis()->SetTitle("TP (ADC)") ;
  TH1F * TPEmulMax = new TH1F("TPEmulMax", "TP Emulator max", 256, 0., 256.) ;
  TPEmulMax->GetXaxis()->SetTitle("TP (ADC)") ;
  TH3F * TPspectrumMap3D = new TH3F("TPspectrumMap3D", "TP data spectrum map", 72, 1, 73, 38, -19, 19, 256, 0., 256.) ;
  TPspectrumMap3D->GetYaxis()->SetTitle("eta index") ;
  TPspectrumMap3D->GetXaxis()->SetTitle("phi index") ;

  TH1F * TPMatchEmul = new TH1F("TPMatchEmul", "TP data matching Emulator", 7, -1., 6.) ;
  TH1F * TPEmulMaxIndex = new TH1F("TPEmulMaxIndex", "Index of the max TP from Emulator", 7, -1., 6.) ;
  TH3I * TPMatchEmul3D = new TH3I("TPMatchEmul3D", "TP data matching Emulator", 72, 1, 73, 38, -19, 19, 7, -1, 6) ;
  TPMatchEmul3D->GetYaxis()->SetTitle("eta index") ;
  TPMatchEmul3D->GetXaxis()->SetTitle("phi index") ;

  TH2I * ttfMismatch = new TH2I("ttfMismatch", "TTF mismatch map",  72, 1, 73, 38, -19, 19) ;
  ttfMismatch->GetYaxis()->SetTitle("eta index") ;
  ttfMismatch->GetXaxis()->SetTitle("phi index") ;

  ///////////////////////
  // Chain the trees:
  ///////////////////////

  TChain * chain = new TChain ("EcalTPGAnalysis") ;
  std::vector<std::string> files ;
  if (inputfiles.find(std::string(",")) != std::string::npos) files = split(inputfiles,",") ;
  if (inputfiles.find(std::string(":")) != std::string::npos) {
    std::vector<std::string> filesbase = split(inputfiles,":") ;
    if (filesbase.size() == 4) {
      int first = atoi(filesbase[1].c_str()) ;
      int last = atoi(filesbase[2].c_str()) ;
      for (int i=first ; i<=last ; i++) {
	std::stringstream name ;
	name<<filesbase[0]<<i<<filesbase[3] ;
	files.push_back(name.str()) ;
      }
    }
  }
  for (unsigned int i=0 ; i<files.size() ; i++) {
    files[i] = inputdir+"/"+files[i] ;
    std::cout<<"Input file: "<<files[i]<<std::endl ;
    chain->Add (files[i].c_str()) ;
  }

  EcalTPGVariables treeVars ;
  setBranchAddresses (chain, treeVars) ;

  int nEntries = chain->GetEntries () ;
  std::cout << "Number of entries: " << nEntries <<std::endl ;    



  ///////////////////////
  // Main loop over entries
  ///////////////////////

  for (int entry = 0 ; entry < nEntries ; ++entry) {
    chain->GetEntry (entry) ;
    if (entry%1000==0) std::cout <<"------> "<< entry+1 <<" entries processed" << " <------\n" ; 
    if (verbose>0) std::cout<<"Run="<<treeVars.runNb<<" Evt="<<treeVars.runNb<<std::endl ;

    // trigger selection if any
    bool keep(false) ;
    if (!algobits.size()) keep = true ; // keep all events when no trigger selection
    for (unsigned int algo = 0 ; algo<algobits.size() ; algo++)
      for (unsigned int ntrig = 0 ; ntrig < treeVars.nbOfActiveTriggers ; ntrig++)
	if (algobits[algo] == treeVars.activeTriggers[ntrig]) keep = true ;
    if (!keep) continue ;
    
             
    // loop on towers
    for (unsigned int tower = 0 ; tower < treeVars.nbOfTowers ; tower++) {

      int tp = getEt(treeVars.rawTPData[tower]) ;
      int emul[5] = {getEt(treeVars.rawTPEmul1[tower]),  
		     getEt(treeVars.rawTPEmul2[tower]),
		     getEt(treeVars.rawTPEmul3[tower]),
		     getEt(treeVars.rawTPEmul4[tower]),
		     getEt(treeVars.rawTPEmul5[tower])} ;
      int maxOfTPEmul = 0 ;
      int indexOfTPEmulMax = -1 ;
      for (int i=0 ; i<5 ; i++) if (emul[i]>maxOfTPEmul) {
	maxOfTPEmul = emul[i] ; 
	indexOfTPEmulMax = i ;
      }
      int ieta = treeVars.ieta[tower] ;
      int iphi = treeVars.iphi[tower] ;
      int nbXtals = treeVars.nbOfXtals[tower] ;
      int ttf = getTtf(treeVars.rawTPData[tower]) ;


      if (verbose>9 && (tp>0 || maxOfTPEmul>0)) {
	std::cout<<"(phi,eta, Nbxtals)="<<std::dec<<iphi<<" "<<ieta<<" "<<nbXtals<<std::endl ;
	std::cout<<"Data Et, TTF: "<<tp<<" "<<ttf<<std::endl ;
	std::cout<<"Emulator: " ;
	for (int i=0 ; i<5 ; i++) std::cout<<emul[i]<<" " ;
	std::cout<<std::endl ;
      }


      // Fill TP spctrum
      TP->Fill(tp) ;
      TPEmul->Fill(emul[ref]) ;
      TPEmulMax->Fill(maxOfTPEmul) ;
      TPspectrumMap3D->Fill(iphi, ieta, tp) ;


      // Fill TP occupancy
      if (tp>occupancyCut) occupancyTP->Fill(iphi, ieta) ;
      if (emul[ref]>occupancyCut) occupancyTPEmul->Fill(iphi, ieta) ;


      // Fill TP-Emulator matching
      // comparison is meaningful when:
      if (tp>0 && nbXtals == 25) {
	bool match(false) ;
	for (int i=0 ; i<5 ; i++) {
	  if (tp == emul[i]) {
	    TPMatchEmul->Fill(i+1) ;
	    TPMatchEmul3D->Fill(iphi, ieta, i+1) ;
	    match = true ;
	  }
	}
	if (!match) {
	  TPMatchEmul->Fill(-1) ;
	  TPMatchEmul3D->Fill(iphi, ieta, -1) ;
	  if (verbose>5) {
	    std::cout<<"MISMATCH"<<std::endl ;
	    std::cout<<"(phi,eta, Nbxtals)="<<std::dec<<iphi<<" "<<ieta<<" "<<nbXtals<<std::endl ;
	    std::cout<<"Data Et, TTF: "<<tp<<" "<<ttf<<std::endl ;
	    std::cout<<"Emulator: " ;
	    for (int i=0 ; i<5 ; i++) std::cout<<emul[i]<<" " ;
	    std::cout<<std::endl ;
	  }
	}
      }
      if (maxOfTPEmul>0) TPEmulMaxIndex->Fill(indexOfTPEmulMax+1) ;


      // Fill TTF mismatch
      if ((ttf==1 || ttf==3) && nbXtals != 25) ttfMismatch->Fill(iphi, ieta) ;


    } // end loop towers


  } // endloop entries

  

  ///////////////////////
  // Format & write histos
  ///////////////////////


  // 1. TP Spectrum  
  TProfile2D * TPspectrumMap = TPspectrumMap3D->Project3DProfile("yx") ;
  TPspectrumMap->SetName("TPspectrumMap") ;

  // 2. TP Timing
  TH2F * TPMatchEmul2D = new TH2F("TPMatchEmul2D", "TP data matching Emulator", 72, 1, 73, 38, -19, 19) ;
  TH2F * TPMatchFraction2D = new TH2F("TPMatchFraction2D", "TP data: fraction of non-single timing", 72, 1, 73, 38, -19, 19) ;
  TPMatchEmul2D->GetYaxis()->SetTitle("eta index") ; 
  TPMatchEmul2D->GetXaxis()->SetTitle("phi index") ;
  TPMatchEmul2D->GetZaxis()->SetRangeUser(-1,6) ;
  TPMatchFraction2D->GetYaxis()->SetTitle("eta index") ; 
  TPMatchFraction2D->GetXaxis()->SetTitle("phi index") ;
  for (int binx=1 ; binx<=72 ; binx++)    
    for (int biny=1 ; biny<=38 ; biny++) {
      int maxBinz = 5 ;
      double maxCell = TPMatchEmul3D->GetBinContent(binx, biny, maxBinz) ;
      double totalCell(0) ;
      for (int binz=1; binz<=7 ; binz++) {
	double content = TPMatchEmul3D->GetBinContent(binx, biny, binz) ;
	if (content>maxCell) {
	  maxCell = content ;
	  maxBinz = binz ;
	}
	totalCell += content ;
      }
      if (maxCell <=0) maxBinz = 2 ; // empty cell
      TPMatchEmul2D->SetBinContent(binx, biny, float(maxBinz)-2.) ; //z must be in [-1,5] 
      double fraction = 0 ;
      if (totalCell>0) fraction = 1.- maxCell/totalCell ;
      TPMatchFraction2D->SetBinContent(binx, biny, fraction) ;
      if (totalCell > maxCell && verbose>9) {
	std::cout<<"--->"<<std::endl ;	
	for (int binz=1; binz<=7 ; binz++) {	  
	  std::cout<< "(phi,eta, z): (" 
		   << TPMatchEmul3D->GetXaxis()->GetBinLowEdge(binx) 
		   << ", " << TPMatchEmul3D->GetYaxis()->GetBinLowEdge(biny) 
		   << ", " << TPMatchEmul3D->GetZaxis()->GetBinLowEdge(binz)		   
		   << ") Content="<<TPMatchEmul3D->GetBinContent(binx, biny, binz)		   
		   << ", erro="<<TPMatchEmul3D->GetBinContent(binx, biny, binz)	   
		   << std::endl ;	
	}
      }
    }



  TFile saving (outputRootName.c_str (),"recreate") ;
  saving.cd () ;
  
  occupancyTP->Write() ;
  occupancyTPEmul->Write() ;
  
  TP->Write() ;
  TPEmul->Write() ;
  TPEmulMax->Write() ;
  TPspectrumMap->Write() ;

  TPMatchEmul->Write() ; 
  TPMatchEmul3D->Write() ; 
  TPEmulMaxIndex->Write() ;
  TPMatchEmul2D->Write() ; 
  TPMatchFraction2D->Write() ; 

  ttfMismatch->Write() ; 

     
  saving.Close () ;
  delete chain ;

  return 0 ;
}
Example #17
0
void defineBinning(Int_t   jetChannel = 0 , TString theSample = "WW", Bool_t jetGenVeto = 0 ) {

  gSystem->Load("libRooUnfold");

  TH1::SetDefaultSumw2();

  //TString path = Form("rootfiles/%djet/%s/", jetChannel, flavorChannel.Data());
 
  //gSystem->mkdir(path, kTRUE);
 
 
  //----------------------------------------------------------------------------
  // Input files
  //----------------------------------------------------------------------------

  TString filesPath;

  //filesPath = "/gpfs/csic_projects/tier3data/LatinosSkims/ReducedTrees/DiferentialXSection/";
  filesPath = "/gpfs/csic_projects/cms/calderon/WWGEN/";
  

  TChain* tree = new TChain("latino", "latino");

  //tree->Add(filesPath + "latino_000_WWJets2LMad_OF.root");
  //tree->Add(filesPath + "latinostep3_latinosYieldSkim_MC_WWmg.root");
  //tree->Add(filesPath + "latino_006_WWJets_pow_OF.root");
  //tree->Add(filesPath + "latino_006_WWJets_pow_OF_genJets.root");
  //tree->Add(filesPath + "latino_006_WWJets_pow_OF_genJets_Smear.root");
  //tree->Add(filesPath + "latino_006_WWJets_pow_OF_genJets_nll_ewk_Smear.root");

  //tree->Add(filesPath + "latino_002_WWJets_mcnlo_OF.root");
  //tree->Add(filesPath + "latino_002_WWJets_mcnlo_OF_genJets.root");
  //tree->Add(filesPath + "latino_002_WWJets_mcnlo_OF_genJets_Smear.root");
  //tree->Add(filesPath + "latino_002_WWJets_mcnlo_OF_genJets_nll_ewk_Smear.root");


  //tree->Add(filesPath + "latino_000_WWJets_mad_OF.root");
  //tree->Add(filesPath + "latino_000_WWJets_mad_OF_genJets.root");
  //tree->Add(filesPath + "latino_000_WWJets_mad_OF_genJets_Smear.root");
  //tree->Add(filesPath + "latino_000_WWJets_mad_OF_genJets_nll_ewk_Smear.root");

  //tree->Add(filesPath + "latino_001_GGWWJets_OF.root");
  //tree->Add(filesPath + "latino_001_GGWWJets_OF_genJets_Smear.root");
  //tree->Add(filesPath + "latino_001_GGWWJets_OF_jetSmear_METxy.root");

 


  //-*** Final for data 
  //tree->Add("/gpfs/csic_projects/cms/calderon/WWGEN/finalFilesForData/latino006_nll_ewk.root"); // POW 
  tree->Add("/gpfs/csic_projects/cms/calderon/WWGEN/finalFilesForData/latino_001_GGWWJets_jetSmear_METxy.root"); // GG
  //tree->Add("/gpfs/csic_projects/cms/calderon/WWGEN/finalFilesForData/latino000_nll_ewk.root"); // MAD
  //tree->Add("/gpfs/csic_projects/cms/calderon/WWGEN/finalFilesForData/latino002_nll_ewk.root"); // MCNLO


  //----------------------------------------------------------------------------
  // Define functions
  //----------------------------------------------------------------------------
  Float_t smear (Float_t xt); 

   //----------------------------------------------------------------------------
  // Output files
  //----------------------------------------------------------------------------
  
  //TString path = Form("_GEN_0jet_pow_full.root",  jetChannel); 0,0.25,0.5,0.75,1,1.25,1.5,1.75,2,
  //TString path = Form("_GEN_0jet_mcnlo_full_NNLL_JetGenVeto_Eff_NNLOXsec_NewLumi_NoPU_newMiss.root"); 
  TString path = Form("_GEN_0jet_gg_full_JetGenVeto_Eff_NewLumi_NoPU_newMiss.root");
  //TString path = Form("_gg_tmp.root");

  TFile* output = new TFile( theSample+path, "recreate");


  // Defining binning
  //----------------------------------------------------------------------------

  //Double_t pt1bins[6] = {25,50,100,150,200,400};
  
  Double_t RECOpt1bins[11] = {10,20,40,60,80,100,125,150,175,200,210};
  Double_t GENpt1bins[7] = {10,20,50,100,150,200,210};

  const Int_t pt1Nbin = 9;
  const Int_t ptllNbin = 8; 
  const Int_t mllNbin = 9;
  const Int_t dphiNbin = 13;
  const Int_t jetEtNbin = 10;

  Double_t pt1bins[pt1Nbin] = {20,40,60,80,100,125,150,175,200}; 
  Double_t ptllbins[ptllNbin] = {30,40,50,60,70,85,120,150};
  Double_t mllbins[mllNbin] = {20,40,60,80,100,125,150,175,200};
  Double_t dphibins[dphiNbin] = {0,0.25,0.5,0.75,1,1.25,1.5,1.75,2,2.25,2.5,2.75,3};//{0,0.5,1,1.5,2,2.5,3};
  Double_t jetEtbins[jetEtNbin] = {30,40,50,60,70,80,90,100,110,120}; 


  // Pt, Dilepton, DeltaPhi, Mll

  // GEN level ( phase space)  differential histograms 
  //----------------------------------------------------------------------------

  TH1F* hPtLepton1_GEN  = new TH1F("hPtLepton1_GEN",       "", pt1Nbin-1, pt1bins);
  TH1F* hPtLepton1_RECO  = new TH1F("hPtLepton1_RECO",       "", pt1Nbin-1, pt1bins);
  TH2F* hPtLepton1_RECO_GEN =  new TH2F("hPtLepton1_RECO_GEN", "", pt1Nbin-1, pt1bins, pt1Nbin-1, pt1bins);

  TH1F* hDilepton_GEN  = new TH1F("hDilepton_GEN",       "", ptllNbin-1, ptllbins);
  TH1F* hDilepton_RECO  = new TH1F("hDilepton_RECO",       "", ptllNbin-1, ptllbins);
  TH2F* hDilepton_RECO_GEN =  new TH2F("hDilepton_RECO_GEN", "", ptllNbin-1, ptllbins, ptllNbin-1, ptllbins);

  TH1F* hmll_GEN  = new TH1F("hmll_GEN",       "", mllNbin-1, mllbins);
  TH1F* hmll_RECO  = new TH1F("hmll_RECO",       "",mllNbin-1,  mllbins);
  TH2F* hmll_RECO_GEN =  new TH2F("hmll_RECO_GEN", "", mllNbin-1, mllbins, mllNbin-1, mllbins);

  TH1F* hdphi_GEN  = new TH1F("hdphi_GEN",       "", dphiNbin-1, dphibins);
  TH1F* hdphi_RECO  = new TH1F("hdphi_RECO",       "", dphiNbin-1,  dphibins);
  TH2F* hdphi_RECO_GEN =  new TH2F("hdphi_RECO_GEN", "", dphiNbin-1, dphibins, dphiNbin-1, dphibins);

  TH1F* hjetEt_GEN  = new TH1F("hjetEt_GEN",       "", jetEtNbin-1, jetEtbins);
  TH1F* hjetEt_RECO  = new TH1F("hjetEt_RECO",       "", jetEtNbin-1,  jetEtbins);
  TH2F* hjetEt_RECO_GEN =  new TH2F("hjetEt_RECO_GEN", "", jetEtNbin-1, jetEtbins, jetEtNbin-1, jetEtbins);

  TH1F* hInclusive_GEN  = new TH1F("hInclusive_GEN",       "", 3,0,3);
 

  RooUnfoldResponse responsePtLepton1GEN(hPtLepton1_RECO, hPtLepton1_GEN);
  RooUnfoldResponse responseMllGEN(hmll_RECO, hmll_GEN );
  RooUnfoldResponse responseJetEtGEN(hjetEt_RECO, hjetEt_GEN );


  // WW level differential histograms 
  //----------------------------------------------------------------------------

  TH1F* hPtLepton1WWLevel_RECO  = new TH1F("hPtLepton1WWLevel_RECO",       "", pt1Nbin-1, pt1bins);
  TH1F* hPtLepton1WWLevel_GEN  = new TH1F("hPtLepton1WWLevel_GEN",       "", pt1Nbin-1, pt1bins);
  TH2F* hPtLepton1WWLevel_RECO_GEN =  new TH2F("hPtLepton1WWLevel_RECO_GEN", "", pt1Nbin-1, pt1bins, pt1Nbin-1, pt1bins);

 
  TH1F* hDileptonWWLevel_RECO  = new TH1F("hDileptonWWLevel_RECO",       "", ptllNbin-1, ptllbins);
  TH1F* hDileptonWWLevel_GEN  = new TH1F("hDileptonWWLevel_GEN",       "", ptllNbin-1, ptllbins);
  TH2F* hDileptonWWLevel_RECO_GEN =  new TH2F("hDileptonWWLevel_RECO_GEN", "", ptllNbin-1, ptllbins, ptllNbin-1, ptllbins);

  TH1F* hmllWWLevel_RECO  = new TH1F("hmllWWLevel_RECO",       "", mllNbin-1, mllbins);
  TH1F* hmllWWLevel_GEN  = new TH1F("hmllWWLevel_GEN",       "", mllNbin-1, mllbins);
  TH2F* hmllWWLevel_RECO_GEN =  new TH2F("hmllWWLevel_RECO_GEN", "", mllNbin-1, mllbins,mllNbin-1, mllbins);

  TH1F* hdphiWWLevel_RECO  = new TH1F("hdphiWWLevel_RECO",       "", dphiNbin-1, dphibins);
  TH1F* hdphiWWLevel_GEN  = new TH1F("hdphiWWLevel_GEN",       "", dphiNbin-1, dphibins);
  TH2F* hdphiWWLevel_RECO_GEN =  new TH2F("hdphiWWLevel_RECO_GEN", "", dphiNbin-1, dphibins,dphiNbin-1, dphibins);

  TH1F* hjetEtWWLevel_GEN  = new TH1F("hjetEtWWLevel_GEN",       "", jetEtNbin-1, jetEtbins);
  TH1F* hjetEtWWLevel_RECO  = new TH1F("hjetEtWWLevel_RECO",       "", jetEtNbin-1,  jetEtbins);
  TH2F* hjetEtWWLevel_RECO_GEN =  new TH2F("hjetEtWWLevel_RECO_GEN", "", jetEtNbin-1, jetEtbins, jetEtNbin-1, jetEtbins);
  
  TH1D* hPtLepton1WWLevel_nonselected = new TH1D("hPtLepton1WWLevel_nonselected", "hPtLepton1WWLevel_nonselected",pt1Nbin-1, pt1bins);

  TH1F* hdeltaR = new TH1F("hdeltaR", "hdeltaR", 50,0,0.1);

  TH1F* hgenJetEt = new TH1F("hgenJetEt", "hgenJetEt", 100,0,100);
  TH1F* hrecoJetEt = new TH1F("hrecoJetEt", "hrecoJetEt", 100,0,100);
  TH2F* hJetEt_Gen_Reco = new TH2F("hJetEt_Gen_Reco", "hJetEt_Gen_Reco", 100,0,100,100,0,100);

  TH1F* hInclusiveWWLevel_GEN  = new TH1F("hInclusiveWWLevel_GEN",       "",3,0,3);
  TH1F* hInclusiveWWLevel_RECO  = new TH1F("hInclusiveWWLevel_RECO",       "",3,0,3);


  // WW level  define response matrix
  
  RooUnfoldResponse responsePtLepton1(hPtLepton1WWLevel_RECO, hPtLepton1WWLevel_GEN);

  RooUnfoldResponse responseDilepton(hDileptonWWLevel_RECO, hDileptonWWLevel_GEN);

  RooUnfoldResponse responseMll(hmllWWLevel_RECO, hmllWWLevel_GEN );

  RooUnfoldResponse responseDphi(hdphiWWLevel_RECO , hdphiWWLevel_GEN);

  RooUnfoldResponse responseJetEt(hjetEtWWLevel_RECO , hjetEtWWLevel_GEN);

  RooUnfoldResponse responseInclusive(hInclusiveWWLevel_RECO, hInclusiveWWLevel_GEN );

  // Declaration of leaf types
  //----------------------------------------------------------------------------

  Float_t baseW;        tree->SetBranchAddress("baseW"       , &baseW);
  Float_t channel;      tree->SetBranchAddress("channel"     , &channel);
  Float_t chmet;        tree->SetBranchAddress("chmet"       , &chmet);
  Float_t dataset;      tree->SetBranchAddress("dataset"     , &dataset);
  Float_t dphill;       tree->SetBranchAddress("dphill"      , &dphill);
  Float_t dphilljet;    tree->SetBranchAddress("dphilljet"   , &dphilljet);
  Float_t dphilljetjet; tree->SetBranchAddress("dphilljetjet", &dphilljetjet);
  Float_t drll;         tree->SetBranchAddress("drll"        , &drll);
  Float_t effW;         tree->SetBranchAddress("effW"        , &effW);
  Float_t jetphi1;      tree->SetBranchAddress("jetphi1"     , &jetphi1);
  Float_t jetphi2;      tree->SetBranchAddress("jetphi2"     , &jetphi2);
  Float_t jetphi3;      tree->SetBranchAddress("jetphi3"     , &jetphi3);
  Float_t jeteta1;      tree->SetBranchAddress("jeteta1"     , &jeteta1);
  Float_t jeteta2;      tree->SetBranchAddress("jeteta2"     , &jeteta2);
  Float_t jeteta3;      tree->SetBranchAddress("jeteta3"     , &jeteta3);
  Float_t jetpt1;       tree->SetBranchAddress("jetpt1"      , &jetpt1);
  Float_t jetpt2;       tree->SetBranchAddress("jetpt2"      , &jetpt2);
  Float_t jetpt3;       tree->SetBranchAddress("jetpt3"      , &jetpt3);
  Float_t jettche1;     tree->SetBranchAddress("jettche1"    , &jettche1);
  Float_t jettche2;     tree->SetBranchAddress("jettche2"    , &jettche2);
  Float_t mctruth;      tree->SetBranchAddress("mctruth"     , &mctruth);
  Float_t mll;          tree->SetBranchAddress("mll"         , &mll);
  Float_t mpmet;        tree->SetBranchAddress("mpmet"       , &mpmet); 
  Float_t mth;          tree->SetBranchAddress("mth"         , &mth);
  Float_t nbjet;        tree->SetBranchAddress("nbjet"       , &nbjet);
  Float_t nbjettche;    tree->SetBranchAddress("nbjettche"   , &nbjettche);
  Float_t nextra;       tree->SetBranchAddress("nextra"      , &nextra);
  Float_t njet;         tree->SetBranchAddress("njet"        , &njet);
  Float_t nvtx;         tree->SetBranchAddress("nvtx"        , &nvtx);
  Float_t pchmet;       tree->SetBranchAddress("pchmet"      , &pchmet);
  Float_t pfmet;        tree->SetBranchAddress("pfmet"       , &pfmet);
  Float_t ppfmet;       tree->SetBranchAddress("ppfmet"      , &ppfmet);
  Float_t isomva1;      tree->SetBranchAddress("isomva1"     , &isomva1);
  Float_t isomva2;      tree->SetBranchAddress("isomva2"     , &isomva2);
  Float_t pt1;          tree->SetBranchAddress("pt1"         , &pt1);
  Float_t pt2;          tree->SetBranchAddress("pt2"         , &pt2);
  Float_t pt3;          tree->SetBranchAddress("pt3"         , &pt3);
  Float_t phi1;         tree->SetBranchAddress("phi1"         , &phi1);
  Float_t dymva1;       tree->SetBranchAddress("dymva1"         , &dymva1);
  Float_t phi2;         tree->SetBranchAddress("phi2"         , &phi2);
  Float_t eta1;         tree->SetBranchAddress("eta1"         , &eta1);
  Float_t eta2;         tree->SetBranchAddress("eta2"         , &eta2);
  Float_t ch1;          tree->SetBranchAddress("ch1"         , &ch1);
  Float_t ch2;          tree->SetBranchAddress("ch2"         , &ch2);
  Float_t ptll;         tree->SetBranchAddress("ptll"        , &ptll);
  Float_t softtche;     tree->SetBranchAddress("softtche"    , &softtche);
  Float_t trigger;      tree->SetBranchAddress("trigger"     , &trigger);
  Float_t triggW;       tree->SetBranchAddress("triggW"      , &triggW);
  Int_t   bveto;        tree->SetBranchAddress("bveto"       , &bveto);
  Int_t   bveto_ip;     tree->SetBranchAddress("bveto_ip"    , &bveto_ip);
  Int_t   bveto_mu;     tree->SetBranchAddress("bveto_mu"    , &bveto_mu);
  Int_t   bveto_nj30;   tree->SetBranchAddress("bveto_nj30"  , &bveto_nj30);
  Int_t   dphiveto;     tree->SetBranchAddress("dphiveto"    , &dphiveto);
  Int_t   sameflav;     tree->SetBranchAddress("sameflav"    , &sameflav);
  Int_t   zveto;        tree->SetBranchAddress("zveto"       , &zveto);
  UInt_t  event;        tree->SetBranchAddress("event"       , &event);
  UInt_t  lumi;         tree->SetBranchAddress("lumi"        , &lumi);
  UInt_t  run;          tree->SetBranchAddress("run"         , &run);
  Float_t puW;          tree->SetBranchAddress("puW"         , &puW);
  

  // Apply NNLL resummation 
  Float_t nllW = 1; //tree->SetBranchAddress("nllW", &nllW);

// GEN info... 


//Define Status1 leptons 

  Float_t lepGenpt1, lepGenpt2, lepGenpt3;
  tree->SetBranchAddress("genVV_S1lepton1_pt", &lepGenpt1);
  tree->SetBranchAddress("genVV_S1lepton2_pt", &lepGenpt2);
  tree->SetBranchAddress("genVV_S1lepton3_pt", &lepGenpt3);

  Float_t lepGeneta1, lepGeneta2, lepGeneta3;
  tree->SetBranchAddress("genVV_S1lepton1_eta", &lepGeneta1);
  tree->SetBranchAddress("genVV_S1lepton2_eta", &lepGeneta2);
  tree->SetBranchAddress("genVV_S1lepton3_eta", &lepGeneta3);

  Float_t lepGenphi1, lepGenphi2, lepGenphi3;
  tree->SetBranchAddress("genVV_S1lepton1_phi", &lepGenphi1);
  tree->SetBranchAddress("genVV_S1lepton2_phi", &lepGenphi2);
  tree->SetBranchAddress("genVV_S1lepton3_phi", &lepGenphi3);

  Float_t lepGenM1, lepGenM2, lepGenM3;
  tree->SetBranchAddress("genVV_S1lepton1_oVpid", &lepGenM1); 
  tree->SetBranchAddress("genVV_S1lepton2_oVpid", &lepGenM2); 
  tree->SetBranchAddress("genVV_S1lepton3_oVpid", &lepGenM3); 

  Float_t lepGenimTau1, lepGenimTau2, lepGenimTau3;
  tree->SetBranchAddress("genVV_S1lepton1_imTau", &lepGenimTau1); 
  tree->SetBranchAddress("genVV_S1lepton2_imTau", &lepGenimTau2); 
  tree->SetBranchAddress("genVV_S1lepton3_imTau", &lepGenimTau3); 

  Float_t lepGenpid1, lepGenpid2, lepGenpid3;
  tree->SetBranchAddress("genVV_S1lepton1_pid", &lepGenpid1);
  tree->SetBranchAddress("genVV_S1lepton2_pid", &lepGenpid2);
  tree->SetBranchAddress("genVV_S1lepton3_pid", &lepGenpid3);

  Float_t lepGenS3pid1, lepGenS3pid2, lepGenS3pid3;
  tree->SetBranchAddress("genVV_lepton1_pid", &lepGenS3pid1);
  tree->SetBranchAddress("genVV_lepton2_pid", &lepGenS3pid2);
  tree->SetBranchAddress("genVV_lepton3_pid", &lepGenS3pid3);

  Float_t lepGenS3M1, lepGenS3M2, lepGenS3M3;
  tree->SetBranchAddress("genVV_lepton1_oVpid", &lepGenS3M1); 
  tree->SetBranchAddress("genVV_lepton2_oVpid", &lepGenS3M2); 
  tree->SetBranchAddress("genVV_lepton3_oVpid", &lepGenS3M3); 

  Float_t jetGen1_pt, jetGen2_pt, jetGen3_pt, jetGen4_pt, jetGen5_pt;
  tree->SetBranchAddress("genVV_jet1_pt", &jetGen1_pt);
  tree->SetBranchAddress("genVV_jet2_pt", &jetGen2_pt);
  tree->SetBranchAddress("genVV_jet3_pt", &jetGen3_pt);
  tree->SetBranchAddress("genVV_jet4_pt", &jetGen4_pt);  
  tree->SetBranchAddress("genVV_jet5_pt", &jetGen5_pt);

  Float_t jetGen1_eta, jetGen2_eta, jetGen3_eta, jetGen4_eta, jetGen5_eta;
  tree->SetBranchAddress("genVV_jet1_eta", &jetGen1_eta);
  tree->SetBranchAddress("genVV_jet2_eta", &jetGen2_eta);
  tree->SetBranchAddress("genVV_jet3_eta", &jetGen3_eta);
  tree->SetBranchAddress("genVV_jet4_eta", &jetGen4_eta);  
  tree->SetBranchAddress("genVV_jet5_eta", &jetGen5_eta);

  Float_t jetGen1_phi, jetGen2_phi, jetGen3_phi, jetGen4_phi, jetGen5_phi;
  tree->SetBranchAddress("genVV_jet1_phi", &jetGen1_phi);
  tree->SetBranchAddress("genVV_jet2_phi", &jetGen2_phi);
  tree->SetBranchAddress("genVV_jet3_phi", &jetGen3_phi);
  tree->SetBranchAddress("genVV_jet4_phi", &jetGen4_phi);  
  tree->SetBranchAddress("genVV_jet5_phi", &jetGen5_phi);

// 

 

 // Set the channel
  //----------------------------------------------------------------------------
  Float_t SelectedChannel = -999;

  /*  if      (flavorChannel == "MuMu") SelectedChannel =  0;
  else if (flavorChannel == "EE"  ) SelectedChannel =  1;
  else if (flavorChannel == "EMu" ) SelectedChannel =  2;
  else if (flavorChannel == "MuE" ) SelectedChannel =  3;
  else if (flavorChannel == "All" ) SelectedChannel = -1;
  */

  int kk = 0;

 //----------------------------------------------------------------------------
  // Loop
  //----------------------------------------------------------------------------
  

  // Float_t Nentries = 179545; 
  //Float_t Nentries = 187525;
  Float_t Nentries = 10745; // with powheg 
  //Float_t Nentries = 9792; // with madgraph 

  for (int ievent=0; ievent<tree->GetEntriesFast(); ievent++) {
  //for (int ievent=0; ievent<Nentries; ievent++) {
  //for (int ievent=Nentries; ievent<tree->GetEntriesFast(); ievent++) {
   
    tree->GetEntry(ievent);

    //Double_t mybaseW =  5984.0/1933235;//5812.3/1933235; // madgraph (1933232)
    //Double_t mybaseW = 5984.0/999864;//  5812.3/999864; // powheg (999860)
    Double_t mybaseW = 182.852 /109986; // GGWW 
    //Double_t mybaseW = 5984.0/539594; //5812.3/539594; // mcnlo



    Float_t luminosity = 19.365;

    Double_t efficiencyW =  effW * triggW * puW;
    // Double_t totalW = effW * triggW * baseW * efficiencyW * luminosity;

    Double_t totalW = puW * mybaseW * luminosity;//efficiencyW;

    Double_t totalWGen = nllW *  mybaseW * luminosity ; //Removing PU from gen level
    
    Double_t totalWReco =  effW * triggW * puW * nllW *  mybaseW * luminosity;// * effW * triggW ;//puW *  mybaseW * luminosity;//puW * effW * triggW * mybaseW * luminosity;

  
    // The GEN selection begins here
    //--------------------------------------------------------------------------
    
    /// ---> 1) Need status 1 leptons to define the same fiducial region
    /// ---> 2) Count how many GEN leptons we have in each bin, applying the fidual region cuts
    /// ---> 3) Apply also, OF, jetbin and opposite-charged cuts.
    
    
    bool genEvent = false; 

    /*
    if ( fabs(lepGenpid1) > 20 ) continue;
    if ( fabs(lepGenpid2) > 20 ) continue;
    
    //Select the pair of leptons coming from the two Ws   

    if (fabs(lepGenM1)!= 24) continue; 
    if (fabs(lepGenM2)!= 24) continue; 
    
    if (lepGenpt1 <= 20) continue;  
    if (lepGenpt2 <= 20) continue;
    
    if ( fabs(lepGenpid1) == fabs(lepGenpid2) ) continue;
    
    if ( (fabs(lepGenpid1) == 13 && fabs(lepGeneta1) >= 2.4) || 
	 (fabs(lepGenpid1) == 11 && fabs(lepGeneta1) >= 2.5)) continue;

    if ( (fabs(lepGenpid2) == 13 && fabs(lepGeneta2) >= 2.4) || 
	 (fabs(lepGenpid2) == 11 && fabs(lepGeneta2) >= 2.5)) continue;
    


    // If jet veto at GEN level
    //--------------------------------------------------------------------------

    Int_t nGenJets = 0, nGenJet1 = 0, nGenJet2 = 0, nGenJet3 = 0, nGenJet4 = 0, nGenJet5 = 0; 
  
    if ( jetGen1_pt>=30 ) nGenJet1++;
    if ( jetGen2_pt>=30 ) nGenJet2++;
    if ( jetGen3_pt>=30 ) nGenJet3++;
    if ( jetGen4_pt>=30 ) nGenJet4++;
    if ( jetGen5_pt>=30 ) nGenJet5++;
   
    nGenJets = nGenJet1 + nGenJet2 + nGenJet3 + nGenJet4 + nGenJet5; 
    
    if ( jetGenVeto && nGenJets > 0 )  continue;

    if ( jetChannel && nGenJets != 1 ) continue;
    */


    if ( fabs(lepGenpid1) <= 20  && 
	 fabs(lepGenpid1) <= 20  && 
    	 fabs(lepGenM1)== 24 &&  
	 fabs(lepGenM2)== 24 && 
	 lepGenpt1 > 20 &&  
	 lepGenpt2 > 20 &&
	 fabs(lepGenpid1) != fabs(lepGenpid2) &&  
	 ((fabs(lepGenpid1) == 13 && fabs(lepGeneta1) < 2.4) || 
	  (fabs(lepGenpid1) == 11 && fabs(lepGeneta1) < 2.5)) &&  
	 ((fabs(lepGenpid2) == 13 && fabs(lepGeneta2) < 2.4) || 
	  (fabs(lepGenpid2) == 11 && fabs(lepGeneta2) < 2.5)) )  { 


	   // If jet veto at GEN level
	   //--------------------------------------------------------------------------

	   Int_t nGenJets = 0, nGenJet1 = 0, nGenJet2 = 0, nGenJet3 = 0, nGenJet4 = 0, nGenJet5 = 0; 
  
	   if ( jetGen1_pt>=30 ) nGenJet1++;
	   if ( jetGen2_pt>=30 ) nGenJet2++;
	   if ( jetGen3_pt>=30 ) nGenJet3++;
	   if ( jetGen4_pt>=30 ) nGenJet4++;
	   if ( jetGen5_pt>=30 ) nGenJet5++;
	   
	   nGenJets = nGenJet1 + nGenJet2 + nGenJet3 + nGenJet4 + nGenJet5; 
    
	   if (jetGenVeto && nGenJets < 1 )  genEvent = true;

	 } 



    Float_t dileptonGenPt;
    Float_t mllGen;
    Float_t dphiGen;

    TLorentzVector leptonGen1p4;
    TLorentzVector leptonGen2p4;
    leptonGen1p4.SetPtEtaPhiM(lepGenpt1, lepGeneta1, lepGenphi1, 0.0);
    leptonGen2p4.SetPtEtaPhiM(lepGenpt2, lepGeneta2, lepGenphi2, 0.0);   

  
    Float_t Genpt1S = smear(lepGenpt1);    
    
    dileptonGenPt = (leptonGen1p4+leptonGen2p4).Pt();
    mllGen = (leptonGen1p4+leptonGen2p4).M();
    dphiGen = fabs(leptonGen1p4.DeltaPhi(leptonGen2p4));


    
    if  (genEvent ) {

      hPtLepton1_GEN->Fill(lepGenpt1, totalWGen);//*baseW*luminosity*0.00300652); // leading pt ---> which pt should I store here? 
    
      hDilepton_GEN->Fill(dileptonGenPt,totalWGen); // ptll 
    
      hmll_GEN->Fill(mllGen,totalWGen); // mll
      
      hdphi_GEN->Fill(dphiGen,totalWGen); // deltaPhi

      hjetEt_GEN->Fill(jetGen1_pt, totalWGen); 

      hInclusive_GEN->Fill(1, totalWGen);
    }
    
    // The RECO selection begins here. The RECO leptons are supposed to pass the ID+ISO selection already? 
    //----------------------------------------------------------------------------------------------------
  
    TLorentzVector lepton1p4;
    TLorentzVector lepton2p4;
    lepton1p4.SetPtEtaPhiM(pt1, eta1, phi1, 0.0);
    lepton2p4.SetPtEtaPhiM(pt2, eta2, phi2, 0.0);
   

    Float_t dileptonPt = (lepton1p4+lepton2p4).Pt();
    Float_t mll = (lepton1p4+lepton2p4).M();
    Float_t deltaphill = fabs(lepton1p4.DeltaPhi(lepton2p4));

 
    hPtLepton1_RECO_GEN->Fill(pt1, lepGenpt1, totalW);
    hPtLepton1_RECO->Fill(pt1, totalWReco);

    hDilepton_RECO->Fill(dileptonPt, totalW);
    hDilepton_RECO_GEN->Fill(dileptonPt, dileptonGenPt, totalW);

    hmll_RECO->Fill(mll, totalW);
    hmll_RECO_GEN->Fill(mll, mllGen , totalW);

    hdphi_RECO->Fill(dphill, totalW);
    hdphi_RECO_GEN->Fill(dphill,dphiGen , totalW);
 
    hjetEt_RECO->Fill(jetpt1, totalW);
    hjetEt_RECO_GEN->Fill(jetpt1, jetGen1_pt, totalW);


    // ---->>> Fill Response matrix to do only unfolding on resolution
    //         without any selection efficiency propagated, but fiducial region as reco one.

    responsePtLepton1GEN.Fill(pt1, lepGenpt1, totalWReco);
    responseMllGEN.Fill(mll, mllGen, totalWReco);

 

    /// ---> 3) Going to apply the selection analysis cuts on RECO objects

    Int_t dphiv = (njet <= 1 || (njet > 1 && dphilljetjet < 165.*TMath::DegToRad()));
    
    Float_t metvar = (njet <= 1) ? mpmet : pfmet;
    
    Float_t jetbin = njet;
    
    Float_t dyMVA = ( !sameflav || ( (njet!=0 || dymva1>0.88) && (njet!=1 || dymva1>0.84) && ( njet==0 || njet==1 || (pfmet > 45.0)) ) );


    Bool_t isMatched = true; 
    Bool_t isMatchedGEN = true; 
    Bool_t isMatchedRECO = true; 
    Float_t deltaR = 9999.9;
   
    hgenJetEt->Fill(jetGen1_pt );
    
    

    if(  pt1 > 20 && pt2 > 20  && !sameflav && ch1*ch2 < 0 &&
	 trigger == 1                        &&
	 nextra == 0                         && 
	 pfmet > 20                          &&
	 mll > 12                            &&
	 (zveto==1 || !sameflav)             &&
	 (mpmet > 20  && dyMVA)              &&
	 (dphiv || !sameflav)                &&
	 bveto_mu                            &&
	 ptll>30 && (!sameflav || ptll>45 )  &&
	 jetbin == jetChannel                && 
	 (bveto_ip==1 &&  nbjettche==0)   
	 ){
     
	//hgenJetEt->Fill(jetGen1_pt );
	hrecoJetEt->Fill(jetpt1);
	hJetEt_Gen_Reco->Fill(jetGen1_pt, jetpt1);

	//	cout << jetGen1_pt << "  "  <<jetpt1  << endl;

	// if (true) {	     




      // DEFINE MATCHING RECO - GEN
      //--------------------------------------------------------------------------
    
	//if ( lepton1p4.DeltaR(leptonGen1p4) >= 0.15 )isMatchedGEN = false;//&& lepton1p4.DeltaR(leptonGen2p4) >= 0.15 )  isMatchedGEN = false;

	if ( lepton1p4.DeltaR(leptonGen1p4) >= 0.15 && lepton1p4.DeltaR(leptonGen2p4) >= 0.15 )  isMatchedGEN = false;
	
	if ( leptonGen1p4.DeltaR(lepton1p4) >= 0.15 && leptonGen1p4.DeltaR(lepton2p4) >= 0.15 )  isMatchedRECO = false; 
   


	Float_t pt1S = smear(pt1);

	//Float_t pt1S = linearW(pt1, 0.006);
	
	
	//cout << totalWReco  << endl;

	
	hPtLepton1WWLevel_RECO->Fill(pt1,    totalWReco); 
	hPtLepton1WWLevel_GEN->Fill(lepGenpt1,totalW);
	hPtLepton1WWLevel_RECO_GEN->Fill(pt1,lepGenpt1, totalW);
	
	hDileptonWWLevel_RECO->Fill(dileptonPt,        totalWReco); 
	hDileptonWWLevel_GEN->Fill(dileptonGenPt,totalW);
	hDileptonWWLevel_RECO_GEN->Fill(dileptonPt,dileptonGenPt , totalW);
	
	hmllWWLevel_RECO->Fill(mll,        totalWReco); 
	hmllWWLevel_GEN->Fill(mllGen,totalW);
	hmllWWLevel_RECO_GEN->Fill(mll , mllGen, totalW);
	
	hdphiWWLevel_RECO->Fill(dphill,        totalWReco); 
	hdphiWWLevel_GEN->Fill(dphiGen,totalW);
	hdphiWWLevel_RECO_GEN->Fill(dphill,dphiGen, totalW);
	
	hjetEtWWLevel_RECO->Fill(jetpt1, totalWReco);
	hjetEtWWLevel_GEN->Fill( jetGen1_pt, totalWReco);
	hjetEtWWLevel_RECO_GEN->Fill(jetpt1, jetGen1_pt, totalW);

	hInclusiveWWLevel_GEN->Fill(1, totalWGen);
	hInclusiveWWLevel_RECO->Fill(1,   totalWReco);

	
	//---- Fill response matrix ( we have always with our selection 2 gen leptons and 2 reco leptons)
	if  (genEvent) {

	  responsePtLepton1.Fill(pt1, lepGenpt1, totalWReco);
	  responseDilepton.Fill(dileptonPt, dileptonGenPt, totalWReco);
	  responseMll.Fill(mll, mllGen, totalWReco);
	  responseDphi.Fill(dphill, dphiGen, totalWReco);
	  responseInclusive.Fill(1, 1, totalWReco);


	  responsePtLepton1.Miss(lepGenpt1, (1-efficiencyW)*totalWGen );
	  responseDilepton.Miss(dileptonGenPt, (1-efficiencyW)*totalWGen);
	  responseMll.Miss(mllGen, (1-efficiencyW)*totalWGen);
	  responseDphi.Miss(dphiGen, (1-efficiencyW)*totalWGen);
	  responseInclusive.Miss(1, (1-efficiencyW)*totalWGen);
	  


	} else {
	  
	  responsePtLepton1.Fake(pt1, totalWReco);
	  responseDilepton.Fake(dileptonPt, totalWReco);
	  responseMll.Fake(mll,  totalWReco);
	  responseDphi.Fake(dphill, totalWReco);
	  responseInclusive.Fake(1, totalWReco);
	}
   
    } else {	

      if  (genEvent) {
	hPtLepton1WWLevel_nonselected->Fill(lepGenpt1, totalW);
	
	//---- Fill response matrix with efficiency 
	
	responsePtLepton1.Miss(lepGenpt1, totalWGen);
	responseDilepton.Miss(dileptonGenPt, totalWGen);
	responseMll.Miss(mllGen, totalWGen);
	responseDphi.Miss(dphiGen, totalWGen);

	responseInclusive.Miss(1, totalWGen);
   
      }

    }
	   





    /*
	//---- Fill response matrix 	
	
	if (isMatchedGEN ) {
	  
	  responsePtLepton1.Fill(pt1, lepGenpt1, totalWReco);
	  responseDilepton.Fill(dileptonPt, dileptonGenPt, totalWReco);
	  responseMll.Fill(mll, mllGen, totalWReco);
	  responseDphi.Fill(dphill, dphiGen, totalWReco);
	  
	  //      }	else if (!isMatchedGEN ) { 


	} else { 
	   
	  responsePtLepton1.Fake(pt1, totalWReco);
	  responseDilepton.Fake(dileptonPt, totalWReco);
	  responseMll.Fake(mll,  totalWReco);
	  responseDphi.Fake(dphill, totalWReco);
	  
	  if (!isMatchedRECO) responsePtLepton1.Miss(lepGenpt1, totalWGen);
	  
	  //cout << "Not found matched GEN !!! " << endl;
	    
	  //	responsePtLepton1.Miss(lepGenpt1, totalWGen);
	        
	} 

	 } else {	
 
	hPtLepton1WWLevel_nonselected->Fill(lepGenpt1, totalW);
	
	//---- Fill response matrix with efficiency 
	
	responsePtLepton1.Miss(lepGenpt1, totalWGen);
	responseDilepton.Miss(dileptonGenPt, totalWGen);
	responseMll.Miss(mllGen, totalWGen);
	responseDphi.Miss(dphiGen, totalWGen);
	 }
	 
*/

    
    }
 
  // Save the histograms
  //----------------------------------------------------------------------------
  output->cd();
  responsePtLepton1GEN.Write();
  responseMllGEN.Write();
  responseJetEtGEN.Write();
  responsePtLepton1.Write();
  responseDilepton.Write();
  responseMll.Write();
  responseDphi.Write();
  responseInclusive.Write();
  output->Write("", TObject::kOverwrite);
  output->Close();



  // Define binning 

  


  
}
int main(int argc,  char * argv[]){

  if(argc < 4){cout<<" Usage: executable first_file_name second_file_name out_file(without suffix)"<<endl; 
  return -4;}
  cout<<"Please make sure that the peak time is expected in SAMPLE units"<<endl;
  cout<<"This program will run using the relative timing"<<endl;

  int fromSL1 = 0;
  int fromSL2 = 0;
  int noCompare =0;
  if (argc > 4) { 
     fromSL1 = atoi(argv[4]); 
  }
  if (argc > 5) { 
     fromSL2 = atoi(argv[5]); 
  }  
  if (argc > 6) {
     noCompare = atoi(argv[6]);
  }


  char Buffer[5000];
  //int SMn =0;
  //int HowManyTT =0;

  // reading the peak file
  double Shift1[71], Shift2[71], SMave1[71], SMave2[71];
  for(int i=0;i<71;i++){Shift1[i]=-1000.; Shift2[i]=-1000.; SMave1[i] = -1000.; SMave2[i] = -1000.;}
  int TTnum,SLSMn,SLshift;
  //float rms,shift,rel_shift, rel_rms;
  int HowManyShifts = 0;
  
  ifstream TxtFile1(argv[2]);
  if( !(TxtFile1.is_open()) ){cout<<"Error: file"<<argv[2]<<" not found!!"<<endl;return -2;}
  while( !(TxtFile1.eof()) ){
  
    TxtFile1.getline(Buffer,5000);
    if (!strstr(Buffer,"#") && !(strspn(Buffer," ") == strlen(Buffer)))
       {
             if (fromSL1) sscanf(Buffer,"%d %d %d",&SLSMn,&TTnum,&SLshift);
             else sscanf(Buffer," %d %d",&TTnum,&SLshift);
              if(TTnum < 1 || TTnum >68){cout<<"Wrong TT in txt file: "<<TTnum<<endl;continue;}
	         HowManyShifts++;
              Shift1[TTnum]=-SLshift;//
    }
  }//end of file
  TxtFile1.close();
  cout<<"Found "<<HowManyShifts<<" tt timing while reading the file "<<argv[2]<<" (should be up to 68)"<<endl;
  
  HowManyShifts = 0;
  
  ifstream TxtFile2(argv[1]);
  if( !(TxtFile2.is_open()) ){cout<<"Error: file"<<argv[1]<<" not found!!"<<endl;return -2;}
  while( !(TxtFile2.eof()) ){
  
    TxtFile2.getline(Buffer,5000);
    if (!strstr(Buffer,"#") && !(strspn(Buffer," ") == strlen(Buffer)))
       {
             if (fromSL2) sscanf(Buffer,"%d %d %d",&SLSMn,&TTnum,&SLshift);
             else sscanf(Buffer," %d %d",&TTnum,&SLshift);
              if(TTnum < 1 || TTnum >68){cout<<"Wrong TT in txt file: "<<TTnum<<endl;continue;}
	         HowManyShifts++;
              Shift2[TTnum]=-SLshift;//
	      if (noCompare) Shift2[TTnum]=0;
      }
  }//end of file
  TxtFile2.close();
  cout<<"Found "<<HowManyShifts<<" tt timing while reading the file "<<argv[1]<<" (should be up to 68)"<<endl;
  /*
  if (fromSL){
     HowManyShifts = 0;
     ifstream AveFile1(argv[5]);
     if( !(AveFile1.is_open()) ){cout<<"Error: file"<<argv[5]<<" not found!!"<<endl;return -2;}
     while( !(AveFile1.eof()) ){
  
       AveFile1.getline(Buffer,5000);
       if (!strstr(Buffer,"#") && !(strspn(Buffer," ") == strlen(Buffer)))
          {
	      sscanf(Buffer," %d %f",&SMnum,&rel_shift);
	      //cout<<"TT: "<<TTnum<<endl;
	      if(SMnum < 1 || SMnum >54){cout<<"Wrong SM in txt file: "<<SMnum<<endl;continue;}
	      if(rel_shift <= 4.5){cout<<" Average < 4.5 in SM: "<<SMnum<<" skipped"<<endl;continue;}
	      if(rel_shift > 8. ){ cout<<" Average > 8 in SM: "<<SMnum<<" skipped"<<endl;continue;}
	      //std::cout <<"SM1 "<< SMnum <<  " value " << rel_shift << std::endl;
	      HowManyShifts++;
	      float move = (0. - rel_shift)*25.;
	      SMave1[SMnum] = move;
	      //if( fabs(move)> 10.){cout<<"!! Large shift ( "<<move<<" ns) required for SM: "<<SMnum<<endl; }   
       }
     }//end of file
     AveFile1.close();
     cout<<"Found "<<HowManyShifts<<" SM's while reading the file "<<argv[5]<<" (should be up to 54)"<<endl;
  
     HowManyShifts = 0;
     ifstream AveFile2(argv[6]);
     if( !(AveFile2.is_open()) ){cout<<"Error: file"<<argv[6]<<" not found!!"<<endl;return -2;}
     while( !(AveFile2.eof()) ){
  
       AveFile2.getline(Buffer,5000);
       if (!strstr(Buffer,"#") && !(strspn(Buffer," ") == strlen(Buffer)))
          {
	   sscanf(Buffer,"%d %f",&SMnum,&rel_shift);
	   //cout<<"TT: "<<TTnum<<endl;
	   if(SMnum < 1 || SMnum >54){cout<<"Wrong SM in txt file: "<<SMnum<<endl;continue;}
	   if(rel_shift <= 4.5){cout<<" Average < 4.5 in SM: "<<SMnum<<" skipped"<<endl;continue;}
	   if(rel_shift > 8. ){ cout<<" Average > 8 in SM: "<<SMnum<<" skipped"<<endl;continue;}
	   //std::cout <<"SM1 "<< SMnum <<  " value " << rel_shift << std::endl;
	   HowManyShifts++;
	   float move = (0. - rel_shift)*25.;
	   SMave2[SMnum] = move;
	   //if( fabs(move)> 10.){cout<<"!! Large shift ( "<<move<<" ns) required for TT: "<<SMnum<<endl; }   
       }
     }//end of file
     AveFile2.close();
     cout<<"Found "<<HowManyShifts<<" SM's while reading the file "<<argv[6]<<" (should be up to 54)"<<endl;
   }

  //Perform the average over the SM's
  double average1 = 0.0;
  double number1 = 0.0;
  double average2 = 0.0;
  double number2 = 0.0;
  
  for ( int i = 1; i<55; i++){
     if (SMave1[i] > -1000.0 ) {number1++; average1 += SMave1[i];} 
     if (SMave2[i] > -1000.0 ) {number2++; average2 += SMave2[i];}
  }
  
  if (number1 > 0.0) average1 /= number1;
  if (number2 > 0.0) average2 /= number2;
  std::cout << " Average of 1 " << average1 << std::endl;
  std::cout << " Average of 2 " << average2 << std::endl;
*/
  TH1F *diffHist = new TH1F("DifferenceHist","DifferenceHist",500,-25.,25.);
  
  // calculate the differences between the two files
  for(int i=1;i<69;i++){
    if(Shift1[i]>-1000. && Shift2[i] > -1000.){
            double diff = Shift2[i]-Shift1[i];
            diffHist->Fill(diff);
            if ( diff < -2 || diff > 2 ) std::cout << "NONONO TT " << i << " is more than 5 ns off: " << diff << std::endl;
            }
  }
  
  string rootFileName = argv[3]; 
  rootFileName += ".root";
  
  TFile *myfile = new TFile(rootFileName.c_str(),"RECREATE");
  myfile->cd();
  diffHist->Write();
  myfile->Write();
  myfile->Close();
  
  
  
  
  return 0;
}
Example #19
0
void histo_plot(void)
{

  // Store constants for connecting to database (fill in blanks as
  // appropriate)
  const Char_t *dbusername = "dbmanager";  // username for DB access
  const Char_t *dbpasswd = "parity";    // password for DB access
  const Char_t *dbname = "pandb";      // name of DB
  const Char_t *dbhostname = "alquds.jlab.org";  // hostname of DB server computer

  // Connect to MySQL server
  Char_t *dburl = new Char_t[50];
  sprintf(dburl,"mysql://%s/%s", dbhostname, dbname);
  TSQLServer *db = TSQLServer::Connect(dburl, dbusername, dbpasswd);
  delete []dburl;
  dburl=NULL;

  // Get name of dbtablename 
  Char_t * dbtablename= new Char_t[50];
  const Char_t *inputtable = "Please enter desired table:  ";
  cout << inputtable;
  cin.getline(dbtablename, 49);
  cout << dbtablename << endl;

  // Get name of column to plot
  Char_t *column = new Char_t[50];
  const Char_t *inputcolumn = "Please enter desired column:  ";
  cout << inputcolumn;
  cin.getline(column, 49);
  cout << column << endl;

  // Construct query
  Char_t *sql = new Char_t[4200];
  sprintf(sql, "SELECT %s FROM %s", column, dbtablename);
  cout << sql << endl;

  // start timer
  TStopwatch timer;
  timer.Start();

  // Submit query to server
  TSQLRow *row;
  TSQLResult *res;
  res = db->Query(sql);

  // Process results
  Int_t nrows = res->GetRowCount();
  cout << "Got " << nrows << " rows in result." << endl;

  Int_t nfields = res->GetFieldCount();
  cout << "Got " << nfields << " fields in result." << endl;
  if (nfields != 1) {
    cerr << "Select only one column to average over!" << endl;
    exit;
  }

  // Get histogram ranges
  Char_t *lowrangechar = new Char_t[10];
  const Char_t *lowrangemessage = "Please enter lower limit of "
    "the histogram range:  ";
  cout << lowrangemessage;
  cin.getline(lowrangechar, 9);
  Float_t lowrangefloat = atof(lowrangechar);
  
  Char_t *highrangechar = new Char_t[10];
  const Char_t *highrangemessage = "Please enter upper limit of "
    "the histogram range:  ";
  cout << highrangemessage;
  cin.getline(highrangechar, 9);
  Float_t highrangefloat = atof(highrangechar);
  
  // Create histogram
  TH1F *histo = new TH1F("histo", column, 50, lowrangefloat,
			 highrangefloat);

  // Fill histogram
  for (Int_t i = 0; i<nrows; i++) {
    row = res->Next();
    Float_t field = atof(row->GetField(0));
    delete row;
    histo->Fill(field);
  }

  histo->Draw();

  // stop timer and print results
  timer.Stop();
  Double_t rtime = timer.RealTime();
  Double_t ctime = timer.CpuTime();

  printf("\nRealTime=%f seconds, CpuTime=%f seconds\n", rtime, ctime);

  // Clean up
  delete []sql;
  delete []dbtablename;
  delete []column;
  delete []lowrangechar;
  delete []highrangechar;

  delete res;
  delete db;

}
void plotPedestalAnalysis(string inputFileName, string outputDIR, bool testDoubleGaussianChannels){

  system(("mkdir -p "+outputDIR).c_str());

  setTDRStyle();
  gROOT->SetBatch(kTRUE);

  TFile* inputFile = TFile::Open(inputFileName.c_str(),"READ");
  inputFile->cd();
  TTree* tree = (TTree*) inputFile->Get("pedestalFullNoise");

  uint32_t detid,fedKey;
  uint16_t fecCrate,fecSlot, fecRing, ccuAdd, ccuChan, lldChannel, fedId, fedCh, apvId, stripId;
  float    fitChi2Probab, kSProbab, jBProbab, aDProbab, fitChi2;
  float    noiseSkewness, noiseKurtosis;
  float    fitGausMean, fitGausSigma, fitGausNormalization;
  float    fitGausMeanError, fitGausSigmaError, fitGausNormalizationError;
  vector<float>* noiseDistribution = 0;
  vector<float>* noiseDistributionError = 0;
  float    nBin, xMin, xMax;

  tree->SetBranchStatus("*",kFALSE);
  tree->SetBranchStatus("detid",kTRUE);
  tree->SetBranchStatus("fedKey",kTRUE);
  tree->SetBranchStatus("fecCrate",kTRUE);
  tree->SetBranchStatus("fecSlot",kTRUE);
  tree->SetBranchStatus("fecRing",kTRUE);
  tree->SetBranchStatus("ccuAdd",kTRUE);
  tree->SetBranchStatus("ccuChan",kTRUE);
  tree->SetBranchStatus("lldChannel",kTRUE);
  tree->SetBranchStatus("fedId",kTRUE);
  tree->SetBranchStatus("fedCh",kTRUE);
  tree->SetBranchStatus("apvId",kTRUE);
  tree->SetBranchStatus("stripId",kTRUE);
  tree->SetBranchStatus("fitChi2",kTRUE);
  tree->SetBranchStatus("fitChi2Probab",kTRUE);
  tree->SetBranchStatus("kSProbab",kTRUE);
  tree->SetBranchStatus("jBProbab",kTRUE);
  tree->SetBranchStatus("aDProbab",kTRUE);
  tree->SetBranchStatus("fitGausNormalization",kTRUE);
  tree->SetBranchStatus("fitGausMean",kTRUE);
  tree->SetBranchStatus("fitGausSigma",kTRUE);
  tree->SetBranchStatus("fitGausNormalizationError",kTRUE);
  tree->SetBranchStatus("fitGausMeanError",kTRUE);
  tree->SetBranchStatus("fitGausSigmaError",kTRUE);
  tree->SetBranchStatus("noiseSkewness",kTRUE);
  tree->SetBranchStatus("noiseKurtosis",kTRUE);
  tree->SetBranchStatus("noiseDistribution",kTRUE);
  tree->SetBranchStatus("noiseDistributionError",kTRUE);
  tree->SetBranchStatus("nBin",kTRUE);
  tree->SetBranchStatus("xMin",kTRUE);
  tree->SetBranchStatus("xMax",kTRUE);

  tree->SetBranchAddress("detid",&detid);
  tree->SetBranchAddress("fedKey",&fedKey);
  tree->SetBranchAddress("fecCrate",&fecCrate);
  tree->SetBranchAddress("fecSlot",&fecSlot);
  tree->SetBranchAddress("fecRing",&fecRing);
  tree->SetBranchAddress("ccuAdd",&ccuAdd);
  tree->SetBranchAddress("ccuChan",&ccuChan);
  tree->SetBranchAddress("lldChannel",&lldChannel);
  tree->SetBranchAddress("fedId",&fedId);
  tree->SetBranchAddress("fedCh",&fedCh);
  tree->SetBranchAddress("apvId",&apvId);
  tree->SetBranchAddress("stripId",&stripId);
  tree->SetBranchAddress("fitGausNormalization",&fitGausNormalization);
  tree->SetBranchAddress("fitGausMean",&fitGausMean);
  tree->SetBranchAddress("fitGausSigma",&fitGausSigma);
  tree->SetBranchAddress("fitGausNormalizationError",&fitGausNormalizationError);
  tree->SetBranchAddress("fitGausMeanError",&fitGausMeanError);
  tree->SetBranchAddress("fitGausSigmaError",&fitGausSigmaError);
  tree->SetBranchAddress("fitChi2",&fitChi2);
  tree->SetBranchAddress("fitChi2Probab",&fitChi2Probab);
  tree->SetBranchAddress("noiseSkewness",&noiseSkewness);
  tree->SetBranchAddress("noiseKurtosis",&noiseKurtosis);
  tree->SetBranchAddress("kSProbab",&kSProbab);
  tree->SetBranchAddress("aDProbab",&aDProbab);
  tree->SetBranchAddress("jBProbab",&jBProbab);
  tree->SetBranchAddress("noiseDistribution",&noiseDistribution);
  tree->SetBranchAddress("noiseDistributionError",&noiseDistributionError);
  tree->SetBranchAddress("nBin",&nBin);
  tree->SetBranchAddress("xMin",&xMin);
  tree->SetBranchAddress("xMax",&xMax);

  TFile* badStripsNFilledBins = new TFile((outputDIR+"/badStripsNFilledBins.root").c_str(),"RECREATE");
  TFile* badKsTest = new TFile((outputDIR+"/badStripsKsTest.root").c_str(),"RECREATE");
  TFile* badjBTest = new TFile((outputDIR+"/badStripsjBTest.root").c_str(),"RECREATE");
  TFile* badChi2Test = new TFile((outputDIR+"/badStripsChi2Test.root").c_str(),"RECREATE");
  TFile* badaDTest = new TFile((outputDIR+"/badStripsaDTest.root").c_str(),"RECREATE");
  TFile* badCombinedTest = new TFile((outputDIR+"/badStripsCombined.root").c_str(),"RECREATE");
  TFile* badJBNotKSTest = new TFile((outputDIR+"/badStripsjBNotKS.root").c_str(),"RECREATE");
  TFile* badaDNotKSandjBTest = new TFile((outputDIR+"/badStripaDNotKSNotjB.root").c_str(),"RECREATE");
  TFile* badChi2NotKSandjBandaDTest = new TFile((outputDIR+"/badStripsChi2NotKsandjBandaD.root").c_str(),"RECREATE");

  long int nbadNFilledBins = 0;
  long int nbadKsTest = 0;
  long int nbadjBTest = 0;
  long int nbadaDTest = 0;
  long int nbadChi2Test = 0;
  long int nbadCombinedTest = 0;
  long int nbadJBNotKSTest = 0;
  long int nbadaDNotKSandjBTest = 0;
  long int nbadChi2NotKSandjBandaDTest = 0;

  long int nbadDoublePeakDistance = 0;
  long int nbadDoublePeakAshman = 0;
  long int nbadDoublePeakChi2 = 0;
  long int nbadDoublePeakAmplitude = 0;
  long int nbadDoublePeakBimodality = 0;
  long int nbadDoublePeakCombined = 0;

  TCanvas* canvas = new TCanvas("canvas","canvas",600,650);

  map<uint32_t,uint32_t> moduleDenominator;
  map<uint32_t,uint32_t> moduleNumerator;
  //  map<uint32_t,uint32_t> moduleNonEdgeNumerator;
  //  map<uint32_t,uint32_t> moduleAPVEdgeNumerator;

  map<uint32_t,uint32_t> moduleNumeratorFilledBins;
  map<uint32_t,uint32_t> moduleNumeratorKS;
  map<uint32_t,uint32_t> moduleNumeratorJB;
  map<uint32_t,uint32_t> moduleNumeratorDoublePeak;

  vector<TrackerStrip> badStrip;

  TH1F* noiseHist = NULL;
  TF1*  noiseFit  = NULL;
  TF1*  noiseFit2Gaus  = NULL;
  TFitResultPtr result;

  TH1F* chi2Distance       = new TH1F("chi2Distance","",100,0,1);
  chi2Distance->Sumw2();
  TH1F* peakDistance    = new TH1F("peakDistance","",100,0,3);
  peakDistance->Sumw2();
  TH1F* ashmanDistance  = new TH1F("ashmanDistance","",100,0,5);
  ashmanDistance->Sumw2();
  TH1F* bimodalityDistance = new TH1F("bimodalityDistance","",100,0,1);
  bimodalityDistance->Sumw2();
  TH1F* amplitudeRatioDistance = new TH1F("amplitudeRatioDistance","",100,0,3);
  amplitudeRatioDistance->Sumw2();

  TFile* multiPeakChannelsChi2       = new TFile((outputDIR+"/multiPeakChannelsChi2.root").c_str(),"RECREATE");
  TFile* multiPeakChannelsDistance   = new TFile((outputDIR+"/multiPeakChannelsDistance.root").c_str(),"RECREATE");
  TFile* multiPeakChannelsAshman     = new TFile((outputDIR+"/multiPeakChannelsAshman.root").c_str(),"RECREATE");
  TFile* multiPeakChannelsAmplitude  = new TFile((outputDIR+"/multiPeakChannelsAmplitude.root").c_str(),"RECREATE");
  TFile* multiPeakChannelsBimodality = new TFile((outputDIR+"/multiPeakChannelsBimodality.root").c_str(),"RECREATE");
  TFile* multiPeakChannelsCombined   = new TFile((outputDIR+"/multiPeakChannelsCombined.root").c_str(),"RECREATE");

  int nonNullBins = 0;
  float chi2Ratio = 0;
  float distance  = 0;
  float ashman    = 0;
  float bimodality = 0;
  float amplitudeRatio = 0;

  bool isfound = false;
  string fedKeyStr ;
  TString name ;
  std::map<string,string> fitParam;
 
  for(long int iChannel = 0; iChannel < tree->GetEntries(); iChannel++){
    tree->GetEntry(iChannel);
    cout.flush();
    if(iChannel %10000 == 0) cout<<"\r"<<"iChannel "<<100*double(iChannel)/(tree->GetEntries()/reductionFactor)<<" % ";
    if(iChannel > double(tree->GetEntries())/reductionFactor) break;

    // skip problematic fed id
    isfound = false;
    for(auto skipfed : skipFEDid){
      if(fedId == skipfed) isfound = true;
    }
    if(isfound) continue;

    // make selections to identify bad noisy channels (not gaussian ones)
    std::stringstream stream;
    stream << std::hex << fedKey;
    fedKeyStr = stream.str();
    if(fedKeyStr.size() == 4)
      name = Form("fecCrate%d_fecSlot%d_fecRing%d_ccuAdd%d_ccuCh%d_fedKey0x0000%s_lldCh%d_apv%d_strip%d",fecCrate,fecSlot,fecRing,ccuAdd,ccuChan,fedKeyStr.c_str(),lldChannel,apvId,stripId);
    else if(fedKeyStr.size() == 5)
      name = Form("fecCrate%d_fecSlot%d_fecRing%d_ccuAdd%d_ccuCh%d_fedKey0x000%s_lldCh%d_apv%d_strip%d",fecCrate,fecSlot,fecRing,ccuAdd,ccuChan,fedKeyStr.c_str(),lldChannel,apvId,stripId);
  
    fitParam.clear();
    stringstream sMean;
    sMean << std::scientific << fitGausMean;
    fitParam["fitGausMean"]   = sMean.str();
    stringstream sSigma;
    sSigma << std::scientific << fitGausSigma;
    fitParam["fitGausSigma"]  = sSigma.str();
    stringstream sSkew;
    sSkew << std::scientific << noiseSkewness;
    fitParam["noiseSkewness"] = sSkew.str();
    stringstream sKurt;
    sKurt << std::scientific << noiseKurtosis;
    fitParam["noiseKurtosis"] = sKurt.str();
    stringstream sKS;
    sKS << std::scientific << kSProbab;
    fitParam["kSProbab"] = sKS.str();
    stringstream sJB;
    sJB << std::scientific << jBProbab;
    fitParam["jBProbab"] = sJB.str();
    stringstream sChi2;
    sChi2 << std::scientific << fitChi2Probab;
    fitParam["fitChi2Probab"] = sChi2.str();
    stringstream sAD;
    sAD << std::scientific << aDProbab;
    fitParam["aDProbab"] = sAD.str();

    moduleDenominator[detid] = moduleDenominator[detid]+1;
    if(noiseHist == NULL){
      noiseHist = new TH1F ("noiseHist","",nBin,xMin,xMax);
      noiseHist->Sumw2();
    }
    noiseHist->Reset();
    
    for(int iBin = 0; iBin < noiseDistribution->size(); iBin++){
      noiseHist->SetBinContent(iBin+1,noiseDistribution->at(iBin));
      noiseHist->SetBinError(iBin+1,noiseDistributionError->at(iBin));
    }

    if(noiseFit == NULL)
      noiseFit = new TF1 ("noiseFist","gaus(0)",xMin,xMax);
    
    noiseFit->SetRange(xMin,xMax);
    noiseFit->SetParameters(fitGausNormalization,fitGausMean,fitGausSigma);
    noiseFit->SetParError(0,fitGausNormalizationError);
    noiseFit->SetParError(1,fitGausMeanError);
    noiseFit->SetParError(2,fitGausSigmaError);

    nonNullBins = 0;
    for(int iBin = 0; iBin < noiseHist->GetNbinsX(); iBin++){
      if(noiseHist->GetBinContent(iBin+1) != 0) nonNullBins++;
    }

    if(nonNullBins < nFilledBinSelection or noiseHist->GetRMS() < minimumRMS){
      badStripsNFilledBins->cd();
      storeOutputCanvas(canvas,noiseHist,noiseFit,name,fitParam);
      nbadNFilledBins++;
      moduleNumeratorFilledBins[detid] +=1;
      continue;
    }


    if(kSProbab < quantile3sigma){
      badKsTest->cd();
      nbadKsTest++;
      storeOutputCanvas(canvas,noiseHist,noiseFit,name,fitParam);      
      moduleNumeratorKS[detid] += 1;
    }
    
    if(jBProbab < quantile5sigma){
      badjBTest->cd();
      nbadjBTest++;
      storeOutputCanvas(canvas,noiseHist,noiseFit,name,fitParam);      
    }

    if(fitChi2Probab < quantile4sigma){
      badChi2Test->cd();
      nbadChi2Test++;
      storeOutputCanvas(canvas,noiseHist,noiseFit,name,fitParam);      
    }

    if(aDProbab < quantile3sigma){
      badaDTest->cd();
      nbadaDTest++;
      storeOutputCanvas(canvas,noiseHist,noiseFit,name,fitParam);
    }
    if(jBProbab < quantile5sigma and kSProbab > quantile3sigma and kSProbab < quantile){
      badJBNotKSTest->cd();
      nbadJBNotKSTest++;
      storeOutputCanvas(canvas,noiseHist,noiseFit,name,fitParam);      
      moduleNumeratorJB[detid] += 1;
    }

    if(aDProbab < quantile3sigma and jBProbab > quantile5sigma and kSProbab > quantile3sigma and kSProbab < quantile){
      badaDNotKSandjBTest->cd();
      nbadaDNotKSandjBTest++;
      storeOutputCanvas(canvas,noiseHist,noiseFit,name,fitParam);      
    }


    if(fitChi2Probab < quantile4sigma and jBProbab > quantile5sigma and kSProbab > quantile3sigma and kSProbab < quantile and aDProbab > quantile3sigma){
      badChi2NotKSandjBandaDTest->cd();
      nbadChi2NotKSandjBandaDTest++;
      storeOutputCanvas(canvas,noiseHist,noiseFit,name,fitParam);      
    }

    if(kSProbab < quantile3sigma or (kSProbab > quantile3sigma and kSProbab < quantile and jBProbab < quantile5sigma) or (kSProbab > quantile3sigma and kSProbab < quantile and jBProbab > quantile5sigma and aDProbab < quantile3sigma)  or (kSProbab > quantile3sigma and kSProbab < quantile and jBProbab > quantile5sigma and aDProbab > quantile3sigma and fitChi2Probab < quantile4sigma)){
      badCombinedTest->cd();
      nbadCombinedTest++;
      moduleNumerator[detid] = moduleNumerator[detid]+1;
      //if(stripId == 1 or stripId == 128)
      //  moduleAPVEdgeNumerator[detid] = moduleAPVEdgeNumerator[detid]+1;
      //else
      //  moduleNonEdgeNumerator[detid] = moduleNonEdgeNumerator[detid]+1;
      storeOutputCanvas(canvas,noiseHist,noiseFit,name,fitParam);      
      name = Form("fecCrate%d_fecSlot%d_fecRing%d_ccuAdd%d_ccuCh%d_fedKey0x0000%s_lldCh%d_apv%d_strip%d",fecCrate,fecSlot,fecRing,ccuAdd,ccuChan,fedKeyStr.c_str(),lldChannel,apvId,stripId);      
      badStrip.push_back(TrackerStrip(fecCrate,fecSlot,fecRing,ccuAdd,ccuChan,uint32_t(atoi(fedKeyStr.c_str())),lldChannel,apvId,stripId));

      //try to identify double peaked channels
      if(testDoubleGaussianChannels){
	if(noiseFit2Gaus == NULL)
	  // double gaussian in which the sigma is constrained to be the same --> identifing clear two peak channels
	  noiseFit2Gaus = new TF1("dgaus","[0]*exp(-((x-[1])*(x-[1]))/(2*[2]*[2]))+[3]*exp(-((x-[4])*(x-[4]))/(2*[5]*[5]))",xMin,xMax);

	noiseFit2Gaus->SetRange(xMin,xMax);
	noiseFit2Gaus->SetParameter(0,fitGausNormalization/2);
	noiseFit2Gaus->SetParameter(3,fitGausNormalization/2);
	noiseFit2Gaus->SetParameter(1,1.);
	noiseFit2Gaus->SetParameter(4,-1.);
	noiseFit2Gaus->SetParameter(2,fitGausSigma);
	noiseFit2Gaus->SetParameter(5,fitGausSigma);
	noiseFit2Gaus->SetParLimits(1,0.,xMax);
	noiseFit2Gaus->SetParLimits(4,xMin,0);
	result = noiseHist->Fit(noiseFit2Gaus,"QSR");

	chi2Ratio = 0;
	distance  = 0;
	ashman    = 0;
	bimodality = 0;
	amplitudeRatio = 0;
	if(result.Get() or noiseHist->Integral() == 0){

	  //compute the chi2 ratio
	  chi2Ratio = 0.5*ROOT::Math::chisquared_cdf_c((fitChi2/(result->Ndf()+3))/(result->Chi2()/result->Ndf()),1);
	  chi2Distance->Fill(chi2Ratio);			
	  distance = fabs(noiseFit2Gaus->GetParameter(1)-noiseFit2Gaus->GetParameter(4))/(2*sqrt(noiseFit2Gaus->GetParameter(2)*noiseFit2Gaus->GetParameter(5)));
	  peakDistance->Fill(distance);
	  ashman   = TMath::Power(2,0.5)*abs(noiseFit2Gaus->GetParameter(1)-noiseFit2Gaus->GetParameter(4))/(sqrt(pow(noiseFit2Gaus->GetParameter(2),2)+pow(noiseFit2Gaus->GetParameter(5),2)));
	  ashmanDistance->Fill(ashman);	 
	  if(nonNullBins > 3)
	    bimodality = (noiseHist->GetSkewness()*noiseHist->GetSkewness()+1)/(noiseHist->GetKurtosis()+3*(nonNullBins-1)*(nonNullBins-1)/((nonNullBins-2)*(nonNullBins-3)));
	  else
	    bimodality = (noiseHist->GetSkewness()*noiseHist->GetSkewness()+1)/(noiseHist->GetKurtosis());
	  bimodalityDistance->Fill(bimodality);	  
	  amplitudeRatio = std::min(noiseFit2Gaus->GetParameter(0),noiseFit2Gaus->GetParameter(3))/std::max(noiseFit2Gaus->GetParameter(0),noiseFit2Gaus->GetParameter(3));
	  amplitudeRatioDistance->Fill(amplitudeRatio);	
	  
	  if(distance > 1){
	    multiPeakChannelsDistance->cd();
	    storeOutputCanvas(canvas,noiseHist,noiseFit,noiseFit2Gaus,name);
	    nbadDoublePeakDistance++;
	}
	  
	  if(ashman > 2){
	    multiPeakChannelsAshman->cd();
	    storeOutputCanvas(canvas,noiseHist,noiseFit,noiseFit2Gaus,name);
	    nbadDoublePeakAshman++;
	  }
	  
	  if(chi2Ratio < 0.05){
	    multiPeakChannelsChi2->cd();
	    storeOutputCanvas(canvas,noiseHist,noiseFit,noiseFit2Gaus,name);
	    nbadDoublePeakChi2++;
	  }
	  
	  if(amplitudeRatio > 0.85){
	    multiPeakChannelsAmplitude->cd();
	    storeOutputCanvas(canvas,noiseHist,noiseFit,noiseFit2Gaus,name);
	    nbadDoublePeakAmplitude++;
	}
	  
	  if(bimodality > 0.55){
	    multiPeakChannelsBimodality->cd();
	    storeOutputCanvas(canvas,noiseHist,noiseFit,noiseFit2Gaus,name);
	    nbadDoublePeakBimodality++;
	  }
	  
	  if(ashman > 2 && amplitudeRatio > 0.85){
	    multiPeakChannelsCombined->cd();
	    storeOutputCanvas(canvas,noiseHist,noiseFit,noiseFit2Gaus,name);
	    nbadDoublePeakCombined++;
	    moduleNumeratorDoublePeak[detid]++;
	  }
	}
      }
    }
  }

  // plot the chi2 and peak distance
  if(testDoubleGaussianChannels){
    storeOutputCanvas(canvas,chi2Distance,"chi2TestStatistics",outputDIR);
    storeOutputCanvas(canvas,peakDistance,"peakDistanceTestStatistics",outputDIR);
    storeOutputCanvas(canvas,ashmanDistance,"ashmanTestStatistics",outputDIR);
    storeOutputCanvas(canvas,amplitudeRatioDistance,"amplitudeRatioDistance",outputDIR);
    storeOutputCanvas(canvas,bimodalityDistance,"bimodalityDistance",outputDIR);
  }
  
  std::cout<<std::endl;
  badStripsNFilledBins->Close();
  badKsTest->Close();
  badaDTest->Close();
  badjBTest->Close();
  badChi2Test->Close();
  badCombinedTest->Close();
  badJBNotKSTest->Close();
  badaDNotKSandjBTest->Close();
  badChi2NotKSandjBandaDTest->Close();
  multiPeakChannelsCombined->Close();
  //////
  multiPeakChannelsChi2->Close();
  multiPeakChannelsDistance->Close();
  multiPeakChannelsAshman->Close();
  multiPeakChannelsAmplitude->Close();
  multiPeakChannelsBimodality->Close();

  cout<<"#### Bad Nfilled bins "<<nbadNFilledBins<<" --> "<<double(nbadNFilledBins)/(tree->GetEntries()/reductionFactor)<<" % "<<endl;
  cout<<"#### Bad KS Test Channels "<<nbadKsTest<<" ---> "<<double(nbadKsTest)/(tree->GetEntries()/reductionFactor)<<" % "<<endl;
  cout<<"#### Bad JB Test Channels "<<nbadjBTest<<" ---> "<<double(nbadjBTest)/(tree->GetEntries()/reductionFactor)<<" % "<<endl;
  cout<<"#### Bad AD Test Channels "<<nbadaDTest<<" ---> "<<double(nbadaDTest)/(tree->GetEntries()/reductionFactor)<<" % "<<endl;
  cout<<"#### Bad Chi2 Test Channels "<<nbadChi2Test<<" ---> "<<double(nbadChi2Test)/(tree->GetEntries()/reductionFactor)<<" % "<<endl;
  cout<<"#### Bad JB but not KS Test Channels "<<nbadJBNotKSTest<<" ---> "<<double(nbadJBNotKSTest)/(tree->GetEntries()/reductionFactor)<<" % "<<endl;
  cout<<"#### Bad AD but not KS and not JB Test Channels "<<nbadaDNotKSandjBTest<<" ---> "<<double(nbadaDNotKSandjBTest)/(tree->GetEntries()/reductionFactor)<<" % "<<endl;
  cout<<"#### Bad Chi2 but not KS and JB and AD Test Channels "<<nbadChi2NotKSandjBandaDTest<<" ---> "<<double(nbadChi2NotKSandjBandaDTest)/(tree->GetEntries()/reductionFactor)<<" % "<<endl;
  cout<<"#### Bad Combined Test Channels "<<nbadCombinedTest<<" ---> "<<double(nbadCombinedTest)/(tree->GetEntries()/reductionFactor)<<" % "<<endl;

  if(testDoubleGaussianChannels){
    cout<<"###############################"<<endl;
    cout<<"#### Multiple peak finder ####"<<endl;
    cout<<"##############################"<<endl;
    cout<<"Two peak by Chi2 "<<nbadDoublePeakChi2<<" --> "<<double(nbadDoublePeakChi2)/(tree->GetEntries()/reductionFactor)<<" % "<<endl;
    cout<<"Two peak by Distance "<<nbadDoublePeakDistance<<" --> "<<double(nbadDoublePeakDistance)/(tree->GetEntries()/reductionFactor)<<" % "<<endl;
    cout<<"Two peak by Ashman "<<nbadDoublePeakAshman<<" --> "<<double(nbadDoublePeakAshman)/(tree->GetEntries()/reductionFactor)<<" % "<<endl;
    cout<<"Two peak by Amplitude "<<nbadDoublePeakAmplitude<<" --> "<<double(nbadDoublePeakAmplitude)/(tree->GetEntries()/reductionFactor)<<" % "<<endl;
    cout<<"Two peak by Bimodality "<<nbadDoublePeakBimodality<<" --> "<<double(nbadDoublePeakBimodality)/(tree->GetEntries()/reductionFactor)<<" % "<<endl;
    cout<<"Two peak by Combibed "<<nbadDoublePeakCombined<<" ---> "<<double(nbadDoublePeakCombined)/(tree->GetEntries()/reductionFactor)<<" % "<<endl;
  }

  /// -------> 
  ofstream channelMap ((outputDIR+"/fractionOfGoodChannels.txt").c_str());
  for(auto module : moduleDenominator)
    channelMap << module.first <<"  "<< 1. - double(moduleNumerator[module.first])/double(moduleDenominator[module.first]) << "\n";
  channelMap.close();

  /// -------> 
  ofstream nchannelMapFilledBins ((outputDIR+"/numberBadChannelsFilledBins.txt").c_str());
  for(auto module : moduleNumeratorFilledBins)
    nchannelMapFilledBins << module.first <<"  "<< moduleNumeratorFilledBins[module.first] << "\n";
  nchannelMapFilledBins.close();

  /// -------> 
  ofstream nchannelMap ((outputDIR+"/numberBadChannels.txt").c_str());
  for(auto module : moduleNumerator)
    nchannelMap << module.first <<"  "<< moduleNumerator[module.first] << "\n";
  nchannelMap.close();

  /// -------> 
  //  ofstream nNonEdgechannelMap ((outputDIR+"/numberBadChannelsNonEdge.txt").c_str());
  //  for(auto module : moduleNonEdgeNumerator)
  //    nNonEdgechannelMap << module.first <<"  "<< moduleNonEdgeNumerator[module.first] << "\n";
  //  nNonEdgechannelMap.close();

  /// -------> 
  //  ofstream nAPVEdgechannelMap ((outputDIR+"/numberBadChannelsAPVEdge.txt").c_str());
  //  for(auto module : moduleAPVEdgeNumerator)
  //    nAPVEdgechannelMap << module.first <<"  "<< moduleAPVEdgeNumerator[module.first] << "\n";
  //  nAPVEdgechannelMap.close();

  /// -------> 
  ofstream nchannelMapKS ((outputDIR+"/numberBadChannelsKS.txt").c_str());
  for(auto module : moduleNumeratorKS)
    nchannelMapKS << module.first <<"  "<< moduleNumeratorKS[module.first] << "\n";
  nchannelMapKS.close();

  /// -------> 
  ofstream nchannelMapJB ((outputDIR+"/numberBadChannelsJB.txt").c_str());
  for(auto module : moduleNumeratorJB)
    nchannelMapJB << module.first <<"  "<< moduleNumeratorKS[module.first] << "\n";
  nchannelMapJB.close();

  /// -------> 
  ofstream nchannelMapDoublePeak ((outputDIR+"/numberBadChannelsDoublePeak.txt").c_str());
  for(auto module : moduleNumeratorDoublePeak)
    nchannelMapDoublePeak << module.first <<"  "<< moduleNumeratorDoublePeak[module.first] << "\n";
  nchannelMapDoublePeak.close();
  
  // ------> detailed info of bad strips
  ofstream badStripDump ((outputDIR+"/badStripDump.txt").c_str());
  for(auto badstrip : badStrip){
    badStripDump<< badstrip.fecCrate_<<" "<<badstrip.fecSlot_<<" "<<badstrip.fecRing_<<" "<<badstrip.ccuAdd_<<" "<<badstrip.ccuCh_<<" "<<badstrip.fedKey_<<" "<<badstrip.lldCh_<<" "<<badstrip.apvid_<<" "<<badstrip.stripid_<<" \n";
  }
  badStripDump.close();

}
Example #21
0
void cetaflatHEM3t(int nIterN=1, double Ethr1=4, double Ethr2=150) {

    gStyle->SetOptLogz(0);
    gStyle->SetMarkerSize(0.7);
    gStyle->SetMarkerStyle(20);
    gStyle->SetPadGridX(0);
    gStyle->SetPadGridY(0);
    gStyle->SetTitleOffset(1.7,"Y");
    gStyle->SetTitleOffset(0.9,"X");
    //gStyle->SetPadRightMargin(0.12);
    gStyle->SetPadTopMargin(0.06);
    gStyle->SetPadRightMargin(0.03);
    gStyle->SetPadLeftMargin(0.2);
    //gStyle->SetNdivisions(516);
    gStyle->SetStatH(0.09);
    gStyle->SetStatW(0.3);
    gStyle->SetTitleW(0.4);
    gStyle->SetTitleX(0.3);
    gStyle->SetOptStat(0);
    //gStyle->SetOptStat(1111111);
    gROOT->ForceStyle();

    char ctit[145];

    static const double theHBHEEtaBounds[] = { 0.000, 0.087, 0.087*2, 0.087*3, 0.087*4,
                                               0.087*5, 0.087*6, 0.087*7, 0.087*8, 0.087*9,
                                               0.087*10, 0.087*11, 0.087*12, 0.087*13, 0.087*14,
                                               0.087*15, 0.087*16, 0.087*17, 0.087*18, 0.087*19,
                                               1.74, 1.83, 1.93, 2.043, 2.172,
                                               2.332, 2.5, 2.65, 2.868, 3.000
                                             };

    static const double theHFEtaBounds[] = { 2.853, 2.964, 3.139, 3.314, 3.489, 3.664, 3.839,
                                             4.013, 4.191, 4.363, 4.538, 4.716, 4.889, 5.191
                                           };

    // ---------------- Histos input --------------------------------------

    char ftit[145];
    //sprintf(ftit,"%s","phi43val2012A");
    //sprintf(ftit,"%s","phi2012A_May");
    //sprintf(ftit,"%s","phiSym524_2012AB");
    //sprintf(ftit,"%s","phiSym524newGain_2012AB");
    //sprintf(ftit,"%s","phiSym524newGain_2012ABC");
    sprintf(ftit,"%s","phiSym533Corr45Gain507_2012D");

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

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

    TH2F* hmapP = new TH2F("hmapP","E  HEM;i#eta;i#phi",14,-29.5,-15.5,72,0,72);
    TH2F* hmapP0 = new TH2F("hmapP0","E0  HEM;i#eta;i#phi",14,-29.5,-15.5,72,0,72);
    TH2F* hmapPc = new TH2F("hmapPc","corr  HEM;i#eta;i#phi",14,-29.5,-15.5,72,0,72);
    hmapPc->Sumw2();
    TH1F *hcorr1D = new TH1F("hcorr1D","Corr",150,0.5,2);
    TH1F *ht = new TH1F("ht","ht",20000,0,5e7);
    TH1F *htx = new TH1F("htx","htx",20000,0,5e5);
    TH1F *htr = new TH1F("htr","htr",5000,0,3);

    /*  HE mapping:
    if (ieta==16 && depth<3) continue;
    if (ieta==17 && depth>1) continue;
    if (ieta>17 && ieta<27 && depth==3) continue;
    if (ieta==29 && depth==3) continue;
    if (ieta>20 && iphi%2==0) continue;  */


    TH1F *hdatP[14][72], *hdatPx[14][72];
    for (int ii=0; ii<14; ii++) for (int jj=0; jj<72; jj++) {
            sprintf(ctit,"h%d_%d",ii+16,jj+1);
            hdatP[ii][jj] = new TH1F(ctit,ctit,10000,0,250);
        }

    TCanvas *cx[400];
    TSpline5 *tt;

    Double_t x,y,rPL,rPS,mLE,mSE,ermean,rms;
    Double_t xx[4000],yy[4000];
    Int_t nELP, nESP, nIter=0;
    Double_t mcorrL,scorrL,mcorrS,scorrS,erLP,erSP,rLP,drLP,rSP,corrL,corrS,dcorrL,dcorrS;
    double mLEphi[14];

    TCanvas *ccxx = new TCanvas("ccxx","ccxx",0,400,800,400);
    ccxx->Divide(2,1);
    for (int ii=0; ii<14; ii++) {
        int ieta=-(ii+16);

        mLE=mSE=0;   // ------------------for initial condition
        int nmLE=0, nmSE=0;
        ht->Reset();
        htx->Reset();
        for (int ll=0; ll<72; ll++) {
            int iphi=ll+1;

            if (abs(ieta)!=16 && abs(ieta)!=27 && abs(ieta)!=28) continue;
            if (abs(ieta)>20 && iphi%2==0) continue;

            hmapPc->SetBinContent(14-ii,ll+1,1);
            hmapPc->SetBinError(14-ii,ll+1,1.e-6);
            sprintf(ctit,"phaseHF/eHEspec/E_-%d_%d_3",abs(ieta),iphi);
            hdatPx[ii][ll]  =   new TH1F(*((TH1F*)fila->Get(ctit)));
            hdatPx[ii][ll]->SetAxisRange(Ethr1,Ethr2);
            rLP = hdatPx[ii][ll]->Integral()*hdatPx[ii][ll]->GetMean();
            hmapP0->SetBinContent(14-ii,ll+1,rLP);
            if (skipHEChannel(iphi,ieta)) continue;
            if (rLP>0) {
                ht->Fill(rLP);
                htx->Fill(rLP);
                mLE += rLP;
                nmLE++;
                drLP=rLP*sqrt(pow(1./hdatPx[ii][ll]->Integral(),2)+
                              pow(hdatPx[ii][ll]->GetMeanError()/hdatPx[ii][ll]->GetMean(),2));
                hmapP0->SetBinError(14-ii,ll+1,drLP);
            }
            else hmapP0->SetBinError(14-ii,ll+1,0);
        }
        if (nmLE>0) mLE /= nmLE;
        else mLE=0;
        ccxx->cd(1);
        ht->Draw("hist");
        ccxx->cd(2);
        htx->Draw("hist");
        ccxx->Update();
        if (htx->GetBinContent(20001)>1) histspec(ht,mLE,ermean,rms,4,-5);
        else histspec(htx,mLE,ermean,rms,4,-5);
        //histspec(ht,mLE,ermean,rms);
        mLEphi[ii]=mLE;
        printf("ieta %2d :  <E>= %8.1f \n",ieta,mLE);
        if (ht->GetMean()>0) htr->Fill(ht->GetRMS()/ht->GetMean());

        for (int jj=0; jj<72; jj++) {
            int iphi=jj+1;

            if (abs(ieta)!=16 && abs(ieta)!=27 && abs(ieta)!=28) continue;
            if (abs(ieta)>20 && iphi%2==0) continue;
            if (skipHEChannel(iphi,ieta)) {
                hmapP->SetBinContent(14-ii,jj+1,hmapP0->GetBinContent(14-ii,jj+1,rLP));
                continue;
            }

            for (nIter=1; nIter<nIterN; nIter++) { //cout<<nIter<<" |  ";
                if (hmapP0->GetBinContent(14-ii,jj+1)<=0) continue;
                corrL=hmapPc->GetBinContent(14-ii,jj+1);
                hdatP[ii][jj]->Reset();

                for (int kk=1; kk<=hdatPx[ii][jj]->GetNbinsX(); kk++) {
                    xx[kk-1]=hdatPx[ii][jj]->GetBinCenter(kk);
                    yy[kk-1]=hdatPx[ii][jj]->GetBinContent(kk);
                }
                tt = new TSpline5("tt",xx,yy,1000,"",10,20);

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

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

    printf("\nieta      eta  width  dE/dPhidEta\n");
    double xeta[14], weta[14], yield[14];
    int ind=0;
    for (int i=0; i<14; i++) {
        int ieta=-(i+16);
        if (abs(ieta)!=16 && abs(ieta)!=27 && abs(ieta)!=28) continue;
        xeta[ind]=-(theHBHEEtaBounds[i+15]+theHBHEEtaBounds[i+16])/2;
        weta[ind]=(theHBHEEtaBounds[i+16]-theHBHEEtaBounds[i+15]);
        yield[ind]=mLEphi[i];
        if (abs(ieta)<21) yield[ind]*=72/weta[ind];
        else yield[ind]*=36/weta[ind];
        printf("%3d   3 %7.3f%7.3f   %g\n",ieta,xeta[ind],weta[ind],yield[ind]);
        ind++;
    }
    TCanvas *cgL = new TCanvas("cgL","cgL",300,300,600,600);
    TGraphErrors *grL = new TGraphErrors(ind,xeta,yield,0,0);
    grL->SetTitle("HEM ;#eta;E / #Delta#eta ,  GeV");
    grL->Draw("1+PAl");
    cgL->Print("pictHEplot/phiProfHEM3.gif");
    //cgL->Print("HEmc/phiProfM3.gif");


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

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

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

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

        int ieta=-(ii+16);
        if (abs(ieta)!=16 && abs(ieta)!=27 && abs(ieta)!=28) continue;

        sprintf(ctit,"HEMcorr_%d_3",ieta);  // draw corrections
        hprcL[ii] = hmapPc->ProjectionY(ctit,14-ii,14-ii);
        hprcL[ii]->SetTitle(ctit);
        ccc[ii] = new TCanvas(ctit,ctit,800,100,500,500);
        hprcL[ii]->SetMinimum(0.41);
        hprcL[ii]->SetMaximum(hprcL[ii]->GetMaximum()*1.1);
        hprcL[ii]->SetTitleOffset(0.9,"X");
        hprcL[ii]->Draw("e");
        lin1->Draw();
        sprintf(ctit,"pictHEplot/HEM3corr_%d.gif",ieta);
        //sprintf(ctit,"HEmc/HEM3c_4_100G_%d.gif",ieta);
        ccc[ii]->Print(ctit);
        //hprcL[ii]->Write();

        sprintf(ctit,"HEM_E_%d_3;i#phi;GeV",ieta);
        hprL0[ii] = hmapP0->ProjectionY(ctit,14-ii,14-ii);
        hprL0[ii]->SetTitle(ctit);
        sprintf(ctit,"HEM__%d",ieta);
        hprL[ii] = hmapP->ProjectionY(ctit,14-ii,14-ii);
        if (abs(ieta)>20) {
            hprL[ii]->Rebin();
            hprL0[ii]->Rebin();
        }
        cpr[ii] = new TCanvas(ctit,ctit,800,100,500,500);
        hprL0[ii]->SetFillColor(3);
        hprL0[ii]->SetLineColor(3);
        hprL0[ii]->SetLineWidth(1);
        hprL0[ii]->SetTitleOffset(0.9,"X");
        hprL0[ii]->SetMinimum(0);
        hprL0[ii]->Draw("hist");
        hprL[ii]->Draw("samehist");
        sprintf(ctit,"pictHEplot/HEM_E_%d_3.gif",ieta);
        //sprintf(ctit,"HEmc/HEM_E_%d_3.gif",ieta);
        cpr[ii]->Print(ctit);
        //hprL0[ii]->Write();

        for (int jj=0; jj<72; jj++) {
            int ieta=-(ii+16);
            int iphi=jj+1;

            if (abs(ieta)>20 && iphi%2==0) continue;

            corrL=hmapPc->GetBinContent(14-ii,jj+1);
            dcorrL=hmapPc->GetBinError(14-ii,jj+1);
            hcorr1D->Fill(corrL);
            noff++;
            //printf("%2d : %2d / %2d / 3 %8.4f %8.4f\n",noff,ieta,iphi,corrL,dcorrL);
            fprintf(ft1,"%2d   %2d   3 %8.4f %8.4f\n",ieta,iphi,corrL,dcorrL);
        }
    }
    fclose(ft1);

    TCanvas *c1corr =new TCanvas("c1corr","c1corr",30,30,600,600);
    hcorr1D->Draw("hist");
    histStat(hcorr1D,1);
    c1corr->Print("pictHEplot/corrHEM3.gif");
    //c1corr->Print("HEmc/corrHEM3.gif");

    TCanvas *ctr = new TCanvas("ctr","ctr",0,0,650,600);
    htr->Draw("hist");
    ctr->Update();

    TCanvas *chmapP = new TCanvas("chmapP","chmapP",0,0,650,600);
    chmapP->cd();
    chmapP->SetRightMargin(0.12);
    chmapP->SetLogz();
    hmapP->SetAxisRange(hmapP->GetBinContent(14,1)/2,-1111,"Z");
    hmapP->Draw("colz");
    chmapP->Print("pictHEplot/hmapHEM3.gif");
    chmapP->Update();

    TCanvas *chmapP0 = new TCanvas("chmapP0","chmapP0",0,0,650,600);
    chmapP0->cd();
    chmapP0->SetRightMargin(0.12);
    chmapP0->SetLogz();
    hmapP0->SetAxisRange(hmapP0->GetBinContent(14,1)/2,-1111,"Z");
    hmapP0->Draw("colz");
    chmapP0->Print("pictHEplot/hmap0HEM3.gif");
    chmapP0->Update();

    TCanvas *chmapPc = new TCanvas("chmapPc","chmapPc",0,0,650,600);
    chmapPc->cd();
    chmapPc->SetRightMargin(0.12);
    hmapPc->SetAxisRange(0.6,2,"Z");
    hmapPc->Draw("colz");
    chmapPc->Print("pictHEplot/hmapcHEM3.gif");
    chmapPc->Update();

    sprintf(ctit,"HEM3o_%s_%d_%d.root",ftit,((int) Ethr1),((int) Ethr2));
    TFile *histf = new TFile(ctit,"RECREATE");
    hmapP->Write();
    hmapP0->Write();
    hmapPc->Write();
    histf->Close();

}
Example #22
0
void Test() {
  
  TString bgdInputFile    = "samples/backgroundA_3l.root";
  TString dataInputFile   = "samples/data_3l.root";
  TString sigInputFile   =  "samples/hww125.root";
  
  SmurfTree background;
  background.LoadTree(bgdInputFile,-1);
  background.InitTree(0);
  
  SmurfTree data;
  data.LoadTree(dataInputFile,-1);
  data.InitTree(0);
  
  SmurfTree signal;
  signal.LoadTree(sigInputFile,-1);
  signal.InitTree(0);
  
  char output[200];
  sprintf(output,"histo_test.root");     
  TFile* outFileNjets = new TFile(output,"recreate");
  
  TH1F* types = new TH1F("types", "types", 80, -0.5 , 79.5);
  types->Sumw2();
  
  TH1D* bckg_met = new TH1D("bckg_met", "MET", 200, 0, 200);
  bckg_met->Sumw2();
  TH1D* bckg_mllz = new TH1D("bckg_mllz", "m_{ll}", 200, 0, 200);
  bckg_mllz->Sumw2();
  TH1D* bckg_mt = new TH1D("bckg_mt", "m_t", 200, 0, 200);
  bckg_mt->Sumw2();
  TH1D* bckg_ptjet = new TH1D("bckg_ptjet", "P_t of leading jet", 200, 0, 200);
  bckg_ptjet->Sumw2();
  TH1D* bckg_mH = new TH1D("bckg_mH", "m_H", 200, 0, 400);
  bckg_mH->Sumw2();
  TH1D* bckg_mjj = new TH1D("bckg_mjj", "m_jj", 200, 0, 400);
  bckg_mjj->Sumw2();
  TH1D* bckg_dphill = new TH1D("bckg_dphill", "#Delta#phi_{ll}", 200, 0, 3.5);
  bckg_dphill->Sumw2();
  
  TH2D* bckg_mll_mh  = new TH2D("bckg_mll_mh", " ", 100, 40, 120, 100, 0, 200);
  
  TH1D* sig_met = new TH1D("sig_met", "MET", 200, 0, 200);
  sig_met->Sumw2();
  TH1D* sig_mllz = new TH1D("sig_mllz", "m_{ll}", 200, 0, 200);
  sig_mllz->Sumw2();
  TH1D* sig_mt = new TH1D("sig_mt", "m_t", 200, 0, 200);
  sig_mt->Sumw2();
  TH1D* sig_ptjet = new TH1D("sig_ptjet", "P_t of leading jet", 200, 0, 200);
  sig_ptjet->Sumw2();
  TH1D* sig_mH = new TH1D("sig_mH", "m_H", 200, 0, 400);
  sig_mH->Sumw2();
  TH1D* sig_mjj = new TH1D("sig_mjj", "m_jj", 200, 0, 400);
  sig_mjj->Sumw2();
  TH1D* sig_dphill = new TH1D("sig_dphill", "#Delta#phi_{ll}", 200, 0, 3.5);
  sig_dphill->Sumw2();

  TH2D* sig_mll_mh  = new TH2D("sig_mll_mh", " ",100, 40, 120, 100, 0, 200);
  

  double lumi = 12.1;
  double weight = 1;
  double eventsPass = 0;
  int nBgd=background.tree_->GetEntries();
  for (int i=0; i<nBgd; ++i) {
    
    if (i%100000 == 0 && verboseLevel > 0)
      printf("--- reading event %5d of %5d\n",i,nBgd);
    background.tree_->GetEntry(i);
    if (background.njets_ <2 )continue;
    if (!((background.cuts_ & SmurfTree::Lep1FullSelection) == SmurfTree::Lep1FullSelection 
	  && (background.cuts_ & SmurfTree::Lep2FullSelection) == SmurfTree::Lep2FullSelection) ) continue;
  
    weight = 1;
    
    int nFake = 0;
    if(((background.cuts_ & SmurfTree::Lep1LooseMuV2)  == SmurfTree::Lep1LooseMuV2)  && (background.cuts_ & SmurfTree::Lep1FullSelection) != SmurfTree::Lep1FullSelection) nFake++;
    if(((background.cuts_ & SmurfTree::Lep2LooseMuV2)  == SmurfTree::Lep2LooseMuV2)  && (background.cuts_ & SmurfTree::Lep2FullSelection) != SmurfTree::Lep2FullSelection) nFake++;
    if(((background.cuts_ & SmurfTree::Lep3LooseMuV2)  == SmurfTree::Lep3LooseMuV2)  && (background.cuts_ & SmurfTree::Lep3FullSelection) != SmurfTree::Lep3FullSelection) nFake++;
    if(((background.cuts_ & SmurfTree::Lep1LooseEleV4) == SmurfTree::Lep1LooseEleV4) && (background.cuts_ & SmurfTree::Lep1FullSelection) != SmurfTree::Lep1FullSelection) nFake++;
    if(((background.cuts_ & SmurfTree::Lep2LooseEleV4) == SmurfTree::Lep2LooseEleV4) && (background.cuts_ & SmurfTree::Lep2FullSelection) != SmurfTree::Lep2FullSelection) nFake++;
    if(((background.cuts_ & SmurfTree::Lep3LooseEleV4) == SmurfTree::Lep3LooseEleV4) && (background.cuts_ & SmurfTree::Lep3FullSelection) != SmurfTree::Lep3FullSelection) nFake++;
    if (nFake !=0) continue; 
    
    if (nFake > 1) continue; 
    if (nFake == 1) weight = lumi*background.scale1fb_*background.sfWeightPU_*background.sfWeightEff_*background.sfWeightTrig_*background.sfWeightFR_ ;
    else weight = lumi*background.scale1fb_*background.sfWeightPU_*background.sfWeightEff_*background.sfWeightTrig_;
    //weight = lumi*background.scale1fb_*background.sfWeightPU_*background.sfWeightEff_*background.sfWeightTrig_;
  
    if (background.lid3_ == background.lid2_ && background.lid3_ == background.lid1_) continue;
    if (background.lid3_ == background.lid2_ && fabs(background.lid3_) != fabs(background.lid1_)) continue;
    if (background.lid3_ == background.lid1_ && fabs(background.lid3_) != fabs(background.lid2_)) continue;
    if (background.lid2_ == background.lid1_ && fabs(background.lid2_) != fabs(background.lid3_)) continue;
    
    
    double m[3] = {0, 0, 0};
    LorentzVector pair1, pair2, pair3;
    if (fabs(background.lid1_) == fabs(background.lid2_) && background.lq1_*background.lq2_ < 0){
      pair1 = background.lep1_ + background.lep2_ ;
      m[0] = pair1.M();
    }
    if (fabs(background.lid2_) == fabs(background.lid3_) && background.lq2_*background.lq3_ < 0){
      pair2 = background.lep2_ + background.lep3_ ;
      m[1] = pair2.M();
    }
    if (fabs(background.lid1_) == fabs(background.lid3_) && background.lq1_*background.lq3_ < 0){
      pair3 = background.lep1_ + background.lep3_ ;
      m[2] = pair3.M();
    }
    
    if ( (m[0] < 80 || m[0] > 100) &&  (m[1] < 80 || m[1] > 100) &&  (m[2] < 80 || m[2] > 100)) continue;
    //if ( (m[0] < 40 || m[0] > 120) &&  (m[1] < 40 || m[1] > 120) &&  (m[2] < 40 || m[2] > 120)) continue;
    
    double min = TMath::Min(TMath::Min(fabs(mz -m[0]), fabs(mz-m[1])), TMath::Min(fabs(mz -m[0]), fabs(mz-m[2])));
   
    LorentzVector pair, tlepton, pairjet;
    double mt = 0;
    if (min == fabs(mz - m[0])){  pair = pair1; mt =  background.mt3_; tlepton = background.lep3_;} 
    else if (min == fabs(mz - m[1])){  pair = pair2;  mt =  background.mt1_; tlepton = background.lep1_;} 
    else if (min == fabs(mz - m[2])){  pair = pair3;  mt =  background.mt2_; tlepton = background.lep2_;} 
    pairjet = background.jet1_+ background.jet2_;
    
    if (mt < 40 || background.met_ < 25) continue;
    //     if (mt < 40 ) continue;

    // if (pairjet.M() < 65 || pairjet.M() > 95) continue;
  
    types->Fill(background.dstype_);
    bckg_met->Fill(background.met_, weight);
    bckg_mllz->Fill(pair.M(), weight);
    bckg_mt->Fill(mt, weight);
    bckg_ptjet->Fill(background.jet1_.Pt(), weight);
    LorentzVector metvector(background.met_*cos(background.metPhi_), background.met_*sin(background.metPhi_), 0, 0);
    LorentzVector higgsSystem = tlepton + metvector + background.jet1_  + background.jet2_;
    bckg_mH->Fill(higgsSystem.M(), weight);
    bckg_mjj->Fill(pairjet.M(), weight);
    bckg_dphill->Fill(DeltaPhi(pairjet.Phi(),tlepton.Phi()), weight);
    bckg_mll_mh->Fill(pair.M(),higgsSystem.M(), weight); 
    eventsPass += weight;
 
  }
  cout << eventsPass << " background events in " << lumi << " fb" << endl; 
  
  
  int nSig=signal.tree_->GetEntries();
  int nTotal = 0;
  int nZH = 0;
  double eventsPassSig = 0;
  for (int i=0; i<nSig; ++i) {
    
    if (i%100000 == 0 && verboseLevel > 0)
      printf("--- reading event %5d of %5d\n",i,nSig);
    signal.tree_->GetEntry(i);
    
    nTotal++;
    if(signal.processId_==24)  nZH++;
    
    if (signal.njets_ < 2 )continue;

    if(!((signal.cuts_ & SmurfTree::Lep1FullSelection) == SmurfTree::Lep1FullSelection 
	 &&(signal.cuts_ & SmurfTree::Lep2FullSelection) == SmurfTree::Lep2FullSelection)) continue;
     
    
     
    weight = 1;
    
    int nFake = 0;
    if(((signal.cuts_ & SmurfTree::Lep1LooseMuV2)  == SmurfTree::Lep1LooseMuV2)  && (signal.cuts_ & SmurfTree::Lep1FullSelection) != SmurfTree::Lep1FullSelection) nFake++;
    if(((signal.cuts_ & SmurfTree::Lep2LooseMuV2)  == SmurfTree::Lep2LooseMuV2)  && (signal.cuts_ & SmurfTree::Lep2FullSelection) != SmurfTree::Lep2FullSelection) nFake++;
    if(((signal.cuts_ & SmurfTree::Lep3LooseMuV2)  == SmurfTree::Lep3LooseMuV2)  && (signal.cuts_ & SmurfTree::Lep3FullSelection) != SmurfTree::Lep3FullSelection) nFake++;
    if(((signal.cuts_ & SmurfTree::Lep1LooseEleV4) == SmurfTree::Lep1LooseEleV4) && (signal.cuts_ & SmurfTree::Lep1FullSelection) != SmurfTree::Lep1FullSelection) nFake++;
    if(((signal.cuts_ & SmurfTree::Lep2LooseEleV4) == SmurfTree::Lep2LooseEleV4) && (signal.cuts_ & SmurfTree::Lep2FullSelection) != SmurfTree::Lep2FullSelection) nFake++;
    if(((signal.cuts_ & SmurfTree::Lep3LooseEleV4) == SmurfTree::Lep3LooseEleV4) && (signal.cuts_ & SmurfTree::Lep3FullSelection) != SmurfTree::Lep3FullSelection) nFake++;

    weight = lumi*signal.scale1fb_*signal.sfWeightPU_*signal.sfWeightEff_*signal.sfWeightTrig_;
    
    
    if (signal.lid3_ == signal.lid2_ && signal.lid3_ == signal.lid1_) continue;
    if (signal.lid3_ == signal.lid2_ && fabs(signal.lid3_) != fabs(signal.lid1_)) continue;
    if (signal.lid3_ == signal.lid1_ && fabs(signal.lid3_) != fabs(signal.lid2_)) continue;
    if (signal.lid2_ == signal.lid1_ && fabs(signal.lid2_) != fabs(signal.lid3_)) continue;
    
    double m[3] = {0, 0, 0};
    LorentzVector pair1, pair2, pair3;
    if (fabs(signal.lid1_) == fabs(signal.lid2_) && signal.lq1_*signal.lq2_ < 0){
      pair1 = signal.lep1_ + signal.lep2_ ;
      m[0] = pair1.M();
    }
    if (fabs(signal.lid2_) == fabs(signal.lid3_) && signal.lq2_*signal.lq3_ < 0){
      pair2 = signal.lep2_ + signal.lep3_ ;
      m[1] = pair2.M();
    }
    if (fabs(signal.lid1_) == fabs(signal.lid3_) && signal.lq1_*signal.lq3_ < 0){
      pair3 = signal.lep1_ + signal.lep3_ ;
      m[2] = pair3.M();
    }
    
    if ( (m[0] < 80 || m[0] > 100) &&  (m[1] < 80 || m[1] > 100) &&  (m[2] < 80 || m[2] > 100)) continue;
    //   if ( (m[0] < 40 || m[0] > 120) &&  (m[1] < 40 || m[1] > 120) &&  (m[2] < 40 || m[2] > 120)) continue;
        
    double min = TMath::Min(TMath::Min(fabs(mz -m[0]), fabs(mz-m[1])), TMath::Min(fabs(mz -m[0]), fabs(mz-m[2])));
    
    LorentzVector pair, tlepton, pairjet;
    double mt = 0;
    if (min == fabs(mz - m[0])){  pair = pair1; mt =  signal.mt3_; tlepton = signal.lep3_;} 
    else if (min == fabs(mz - m[1])){  pair = pair2;  mt =  signal.mt1_; tlepton = signal.lep1_;} 
    else if (min == fabs(mz - m[2])){  pair = pair3;  mt =  signal.mt2_; tlepton = signal.lep2_;} 
    pairjet = signal.jet1_+ signal.jet2_;
        
     
    if (mt < 40 || signal.met_ < 25) continue;
    // if (mt < 40 ) continue;
    //if (pairjet.M() < 65 || pairjet.M() > 95) continue;
    
    types->Fill(signal.dstype_);
    sig_met->Fill(signal.met_, weight);
    sig_mllz->Fill(pair.M(), weight);
    sig_mt->Fill(mt, weight);
    sig_ptjet->Fill(signal.jet1_.Pt(), weight);  
    LorentzVector metvector(signal.met_*cos(signal.metPhi_), signal.met_*sin(signal.metPhi_), 0, 0);
    LorentzVector higgsSystem = tlepton + metvector + signal.jet1_  + signal.jet2_;
    sig_mH->Fill(higgsSystem.M(), weight);
    sig_mjj->Fill(pairjet.M(), weight);
    sig_dphill->Fill(DeltaPhi(pairjet.Phi(),tlepton.Phi()), weight);
    sig_mll_mh->Fill(pair.M(),higgsSystem.M(), weight); 
    //    cout << signal.njets_ << " - " ;
    eventsPassSig += weight;
  }
  cout << endl;
  
  cout << eventsPassSig << " signal events in " << lumi << " fb" << endl; 
  cout << nTotal << "events, from which " << nZH << "are ZH" << endl;
  int nData=data.tree_->GetEntries();
  double eventsPassData = 0;
  for (int i=0; i<nData; ++i) {
    
    if (i%100000 == 0 && verboseLevel > 0)
      printf("--- reading event %5d of %5d\n",i,nData);
    data.tree_->GetEntry(i);
    if (data.njets_ < 2 )continue;

    if(!((data.cuts_ & SmurfTree::Lep1FullSelection) == SmurfTree::Lep1FullSelection 
	 && (data.cuts_ & SmurfTree::Lep2FullSelection) == SmurfTree::Lep2FullSelection)) continue;

    
    weight = 1;

    int nFake = 0;
    if(((data.cuts_ & SmurfTree::Lep1LooseMuV2)  == SmurfTree::Lep1LooseMuV2)  && (data.cuts_ & SmurfTree::Lep1FullSelection) != SmurfTree::Lep1FullSelection) nFake++;
    if(((data.cuts_ & SmurfTree::Lep2LooseMuV2)  == SmurfTree::Lep2LooseMuV2)  && (data.cuts_ & SmurfTree::Lep2FullSelection) != SmurfTree::Lep2FullSelection) nFake++;
    if(((data.cuts_ & SmurfTree::Lep3LooseMuV2)  == SmurfTree::Lep3LooseMuV2)  && (data.cuts_ & SmurfTree::Lep3FullSelection) != SmurfTree::Lep3FullSelection) nFake++;
    if(((data.cuts_ & SmurfTree::Lep1LooseEleV4) == SmurfTree::Lep1LooseEleV4) && (data.cuts_ & SmurfTree::Lep1FullSelection) != SmurfTree::Lep1FullSelection) nFake++;
    if(((data.cuts_ & SmurfTree::Lep2LooseEleV4) == SmurfTree::Lep2LooseEleV4) && (data.cuts_ & SmurfTree::Lep2FullSelection) != SmurfTree::Lep2FullSelection) nFake++;
    if(((data.cuts_ & SmurfTree::Lep3LooseEleV4) == SmurfTree::Lep3LooseEleV4) && (data.cuts_ & SmurfTree::Lep3FullSelection) != SmurfTree::Lep3FullSelection) nFake++;
    if (nFake !=0) continue; 
 
    if (data.lid3_ == data.lid2_ && data.lid3_ == data.lid1_) continue;
    if (data.lid3_ == data.lid2_ && fabs(data.lid3_) != fabs(data.lid1_)) continue;
    if (data.lid3_ == data.lid1_ && fabs(data.lid3_) != fabs(data.lid2_)) continue;
    if (data.lid2_ == data.lid1_ && fabs(data.lid2_) != fabs(data.lid3_)) continue;
    
    double m[3] = {0, 0, 0};
    LorentzVector pair1, pair2, pair3;
    if (fabs(data.lid1_) == fabs(data.lid2_) && data.lq1_*data.lq2_ < 0){
      pair1 = data.lep1_ + data.lep2_ ;
      m[0] = pair1.M();
    }
    if (fabs(data.lid2_) == fabs(data.lid3_) && data.lq2_*data.lq3_ < 0){
      pair2 = data.lep2_ + data.lep3_ ;
      m[1] = pair2.M();
    }
    if (fabs(data.lid1_) == fabs(data.lid3_) && data.lq1_*data.lq3_ < 0){
      pair3 = data.lep1_ + data.lep3_ ;
      m[2] = pair3.M();
    }
    
    if ( (m[0] < 80 || m[0] > 100) &&  (m[1] < 80 || m[1] > 100) &&  (m[2] < 80 || m[2] > 100)) continue;
    //   if ( (m[0] < 40 || m[0] > 120) &&  (m[1] < 40 || m[1] > 120) &&  (m[2] < 40 || m[2] > 120)) continue;    
    double min = TMath::Min(TMath::Min(fabs(mz -m[0]), fabs(mz-m[1])), TMath::Min(fabs(mz -m[0]), fabs(mz-m[2])));
    
    LorentzVector pair, tlepton, pairjet;
    double mt = 0;
    if (min == fabs(mz - m[0])){  pair = pair1; mt =  data.mt3_; tlepton = data.lep3_;} 
    else if (min == fabs(mz - m[1])){  pair = pair2;  mt =  data.mt1_; tlepton = data.lep1_;} 
    else if (min == fabs(mz - m[2])){  pair = pair3;  mt =  data.mt2_; tlepton = data.lep2_;} 
    pairjet = data.jet1_+ data.jet2_;
        
    
    if (mt < 40 || data.met_ < 25) continue;
    //   if (mt < 40 ) continue;
    //  if (pairjet.M() < 65 || pairjet.M() > 95) continue;

    eventsPassData += weight;
  }
  
  cout << eventsPassData << " data events in " << lumi << " fb" << endl; 

  outFileNjets->Write();
  outFileNjets->Close();
  
  
}
int main (int argc, char** argv)
{
  

  TChain *chain = new TChain ("myanalysis/EcalAnalysisTree") ;
 
  // input files
  chain->Add("/tmp/malberti/SpikesCommissioning10_GOODCOLLV8.root");
  chain->Add("/tmp/malberti/SpikesCommissioning10_Apr1Skim_GOODCOLL-v1.root");
  int nEntries = chain->GetEntries () ;
  std::cout << "FOUND " << nEntries << " ENTRIES\n" ;    

  //ecalVariables variables
  unsigned int BX;
  unsigned int lumiId;
  unsigned int runId;
  unsigned int eventId;
  unsigned int eventNaiveId;

  int nEcalRecHits;
  float ecalRecHitType[1000];
  float ecalRecHitEnergy[1000];
  float ecalRecHitOutOfTimeEnergy[1000];
  float ecalRecHitIEta[1000];
  float ecalRecHitIPhi[1000];
  float ecalRecHitTime[1000];
  float ecalRecHitChi2[1000];
  float ecalRecHitOutOfTimeChi2[1000];
  int ecalRecHitRawId[1000];
  float ecalRecHitCoeff[1000];
  int ecalRecHitRecoFlag[1000];
  float ecalRecHitR9[1000];
  float ecalRecHitS4oS1[1000];
  float ecalRecHitIso03[1000][2];
  float ecalRecHitIso04[1000][2];
  int ecalDigis[1000][10];
  int ecalGainId[1000][10];
  float ecalRecHitMatrix[1000][5][5];
  float ecalRecHitMatrixFlag[1000][5][5];

  // L1 trigger variables
  int techL1Bit[64];
  int algoL1Bit[128];
  
  chain -> SetBranchAddress("BX",            &BX);
  chain -> SetBranchAddress("lumiId",        &lumiId);
  chain -> SetBranchAddress("runId",         &runId);
  chain -> SetBranchAddress("eventId",       &eventId);
  chain -> SetBranchAddress("eventNaiveId",  &eventNaiveId);

  chain -> SetBranchAddress("nEcalRecHits",             &nEcalRecHits);
  chain -> SetBranchAddress("ecalRecHitType",            ecalRecHitType);
  chain -> SetBranchAddress("ecalRecHitEnergy",          ecalRecHitEnergy);
  chain -> SetBranchAddress("ecalRecHitOutOfTimeEnergy", ecalRecHitOutOfTimeEnergy);
  chain -> SetBranchAddress("ecalRecHitIEta",            ecalRecHitIEta);
  chain -> SetBranchAddress("ecalRecHitIPhi",            ecalRecHitIPhi);
  chain -> SetBranchAddress("ecalRecHitTime",            ecalRecHitTime);
  chain -> SetBranchAddress("ecalRecHitChi2",            ecalRecHitChi2);
  chain -> SetBranchAddress("ecalRecHitOutOfTimeChi2",   ecalRecHitOutOfTimeChi2);
  chain -> SetBranchAddress("ecalRecHitRawId",           ecalRecHitRawId);
  chain -> SetBranchAddress("ecalRecHitCoeff",           ecalRecHitCoeff);
  chain -> SetBranchAddress("ecalRecHitRecoFlag",        ecalRecHitRecoFlag);
  chain -> SetBranchAddress("ecalRecHitR9",              ecalRecHitR9);
  chain -> SetBranchAddress("ecalRecHitS4oS1",           ecalRecHitS4oS1);
  chain -> SetBranchAddress("ecalRecHitIso03",           ecalRecHitIso03);
  chain -> SetBranchAddress("ecalRecHitIso04",           ecalRecHitIso04);
  chain -> SetBranchAddress("ecalDigis",                 ecalDigis);
  chain -> SetBranchAddress("ecalGainId",                ecalGainId);
  chain -> SetBranchAddress("ecalRecHitMatrix",          ecalRecHitMatrix);
  chain -> SetBranchAddress("ecalRecHitMatrixFlag",      ecalRecHitMatrixFlag);
  
  chain -> SetBranchAddress("techL1Bit",     techL1Bit);
  chain -> SetBranchAddress("algoL1Bit",     algoL1Bit);
 
  // output file
  std::string outputRootName = "spikeEfficiency_3GeV.root" ;
  
  // output histos

  TH1F *hRun = new TH1F("hRun","hRun",300,132400,132700);

  TH1F *hS1oS9  = new TH1F("hS1oS9","S1oS9 all Rec Hits",120,0,1.2); 
  hS1oS9 -> GetXaxis()-> SetTitle("S1/S9");

  TH1F *hTime[2];
  hTime[0] = new TH1F("hTimeSpike","hTimeSpike",800,-100,100);
  hTime[0]->SetLineColor(2);
  hTime[0]-> GetXaxis()-> SetTitle("t(ns)");
  hTime[1] = new TH1F("hTimeNormal","hTimeNormal",800,-100,100);
  hTime[1]->SetLineColor(3);
  hTime[1]-> GetXaxis()-> SetTitle("t(ns)");

  TH1F *hChi2[2];
  hChi2[0] = new TH1F("hChi2Spike","hChi2Spike",100,0,100);
  hChi2[0] -> SetLineColor(2);
  hChi2[0] -> GetXaxis()-> SetTitle("chi^{2}");
  hChi2[1] = new TH1F("hChi2Normal","hChi2Normal",100,0,100);
  hChi2[1] ->SetLineColor(3);
  hChi2[1] -> GetXaxis()-> SetTitle("chi^{2}");

  TH1F *hOutOfTimeChi2[2];
  hOutOfTimeChi2[0] = new TH1F("hOutOfTimeChi2Spike","hOutOfTimeChi2Spike",100,0,100);
  hOutOfTimeChi2[0] -> SetLineColor(2);
  hOutOfTimeChi2[0] -> GetXaxis()-> SetTitle("OutOfTime chi^{2}");
  hOutOfTimeChi2[1] = new TH1F("hOutOfTimeChi2Normal","hOutOfTimeChi2Normal",100,0,100);
  hOutOfTimeChi2[1] ->SetLineColor(3);
  hOutOfTimeChi2[1] -> GetXaxis()-> SetTitle("OutOfTime chi^{2}");

  int nSpikeTot  = 0 ;
  int nNormalTot = 0 ;
 
  int nSpikeTotEB[2]  = {0} ;
  int nNormalTotEB[2] = {0} ;
 
  int n = 1000;

  int nSpikeChi2[1000] = {0.};
  int nNormalChi2[1000]= {0};

  int nSpikeChi2OutOfTime[1000] = {0};
  int nNormalChi2OutOfTime[1000]= {0};

  int nSpikeTime[1000] = {0};
  int nNormalTime[1000]= {0};


  int nSpikeChi2EB[1000][2] ;
  int nNormalChi2EB[1000][2];

  int nSpikeChi2OutOfTimeEB[1000][2] ;
  int nNormalChi2OutOfTimeEB[1000][2];

  int nSpikeTimeEB[1000][2] ;
  int nNormalTimeEB[1000][2];

  for (int i = 0; i < n ; i++){
    for (int j = 0; j < 2; j++){
      nSpikeChi2EB[i][j] = 0;
      nSpikeChi2OutOfTimeEB[i][j] = 0;
      nSpikeTimeEB[i][j] = 0;
      nNormalChi2EB[i][j] = 0;
      nNormalChi2OutOfTimeEB[i][j] = 0;
      nNormalTimeEB[i][j] = 0;
    }
  }

  //for time resolution parametrization
  float N = 31.;
  float ADCtoGeV = 0.03865 ;
  float rmsNoise = 1.1;
  float cterm = 0.7;

  // loop over entries
  for (int entry = 0; entry < nEntries; ++entry)
    {
      chain->GetEntry (entry) ;
      if(entry%500000 == 0) std::cout << "event n. " << entry << std::endl;
      

      if ((techL1Bit[40]+techL1Bit[41])==0) continue; // c'e' gia'
             
      
      // select the good collisions runs + good lumi sections (no ecal time scans, etc...)
      bool goodrun = false;
      
      if (runId==132440 && lumiId >=86  && lumiId <= 138) goodrun = true;
      if (runId==132440 && lumiId >=141 && lumiId <= 401) goodrun = true;
   
      if (runId==132473 && lumiId >=1   && lumiId <= 29 ) goodrun = true;
      
      if (runId==132476 && lumiId >=23  && lumiId <= 28 ) goodrun = true;
      if (runId==132476 && lumiId >=54  && lumiId <= 57 ) goodrun = true;

      if (runId==132477 && lumiId >=34  && lumiId <= 35 ) goodrun = true;
      if (runId==132477 && lumiId >=63  && lumiId <= 64 ) goodrun = true;
      if (runId==132477 && lumiId >=90  && lumiId <= 93 ) goodrun = true;
      if (runId==132477 && lumiId >=118 && lumiId <= 121) goodrun = true;
      if (runId==132477 && lumiId >=148 && lumiId <= 149) goodrun = true;
      if (runId==132477 && lumiId >=176 && lumiId <= 179) goodrun = true;
      if (runId==132477 && lumiId >=225 && lumiId <= 236) goodrun = true;
      if (runId==132477 && lumiId >=368 && lumiId <= 384) goodrun = true;
      if (runId==132477 && lumiId >=517 && lumiId <= 520) goodrun = true;

      if (runId==132569 && lumiId >=222 && lumiId <= 224) goodrun = true;
      if (runId==132569 && lumiId >=310 && lumiId <= 310) goodrun = true;
      if (runId==132569 && lumiId >=411 && lumiId <= 419) goodrun = true;
      if (runId==132569 && lumiId >=529 && lumiId <= 582) goodrun = true;

      if (runId==132596 && lumiId >=383 && lumiId <= 383) goodrun = true;
      if (runId==132596 && lumiId >=447 && lumiId <= 453) goodrun = true;

      if (runId==132598 && lumiId >=80  && lumiId <= 82 ) goodrun = true;
      if (runId==132598 && lumiId >=174 && lumiId <= 188) goodrun = true;

      if (runId==132599 && lumiId >=1   && lumiId <= 74 ) goodrun = true;

      if (runId==132601 && lumiId >=261 && lumiId <= 1131)goodrun = true;

      if (runId==132602 && lumiId >=1   && lumiId <= 83)  goodrun = true;

      if (runId==132605 && lumiId >=446 && lumiId <= 622) goodrun = true;
      if (runId==132605 && lumiId >=624 && lumiId <= 829) goodrun = true;
      if (runId==132605 && lumiId >=831 && lumiId <= 968) goodrun = true;

      if (runId==132606 && lumiId >=1   && lumiId <= 37 ) goodrun = true;
      
      if (!goodrun) continue;      



      for (int ihit =0 ; ihit < nEcalRecHits; ihit++){
	  
      if (ecalRecHitEnergy[ihit] < 3) continue;
      
      // check gain switch
      bool gainSwitch = false;
      for (int isample = 0; isample < 10 ; isample++){
        if ( (isample > 0 && ecalGainId[ihit][isample]!= ecalGainId[ihit][isample-1]) ||
             ecalGainId[ihit][isample] !=1 ) {
          gainSwitch = true;
          break;
        }
      }

      if (gainSwitch) continue;

      hRun->Fill(runId);


      // c'e' un canale con problemi?
      if ( ecalRecHitIEta[ihit]==58 && ecalRecHitIPhi[ihit]==97 && runId==132569) continue; 


      if (ecalRecHitR9[ihit] > 0.95 ) {
	nSpikeTot++;
	if (ecalRecHitIEta[ihit] < 0)  nSpikeTotEB[0]++;
	if (ecalRecHitIEta[ihit] > 0)  nSpikeTotEB[1]++;
	hTime[0]->Fill(ecalRecHitTime[ihit]);
      }

      if (ecalRecHitR9[ihit] < 0.80 ) {
	nNormalTot++;
	if (ecalRecHitIEta[ihit] < 0)  nNormalTotEB[0]++;
	if (ecalRecHitIEta[ihit] > 0)  nNormalTotEB[1]++;
	hTime[1]->Fill(ecalRecHitTime[ihit]);
	//if (ecalRecHitTime[ihit]> 8) std::cout << ecalRecHitIEta[ihit] << "  " << ecalRecHitIPhi[ihit] << "  " << runId<< std::endl;
	
      }


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

	float chi2cut = (i+1) * 65./n ;

	// for the time cut , use parametrization by Giovanni et al.
	float A = ecalRecHitEnergy[ihit]/ADCtoGeV; 
	float sigmat = sqrt(pow(N/(A/rmsNoise),2) + cterm*cterm );
	float timecut = (i+1)*20./n;

	if ( ecalRecHitR9[ihit] > 0.95 ){

	  if (ecalRecHitChi2[ihit] < chi2cut) nSpikeChi2[i]++;
	  if (ecalRecHitChi2[ihit] < chi2cut  && ecalRecHitIEta[ihit] < 0) nSpikeChi2EB[i][0]++;
	  if (ecalRecHitChi2[ihit] < chi2cut  && ecalRecHitIEta[ihit] > 0) nSpikeChi2EB[i][1]++;
	
	  if (ecalRecHitOutOfTimeChi2[ihit] < chi2cut) nSpikeChi2OutOfTime[i]++;
	  if (ecalRecHitOutOfTimeChi2[ihit] < chi2cut  && ecalRecHitIEta[ihit] < 0) nSpikeChi2OutOfTimeEB[i][0]++;
	  if (ecalRecHitOutOfTimeChi2[ihit] < chi2cut  && ecalRecHitIEta[ihit] > 0) nSpikeChi2OutOfTimeEB[i][1]++;
	  
	  if (fabs(ecalRecHitTime[ihit]/sigmat) < timecut) nSpikeTime[i]++;
	  if (fabs(ecalRecHitTime[ihit]/sigmat ) < timecut && ecalRecHitIEta[ihit] < 0) nSpikeTimeEB[i][0]++;
	  if (fabs(ecalRecHitTime[ihit]/sigmat ) < timecut && ecalRecHitIEta[ihit] > 0) nSpikeTimeEB[i][1]++;

	}

	if ( ecalRecHitR9[ihit] < 0.80 ){
	  


	  if (ecalRecHitChi2[ihit] < chi2cut) nNormalChi2[i]++;
	  if (ecalRecHitChi2[ihit] < chi2cut  && ecalRecHitIEta[ihit] < 0) nNormalChi2EB[i][0]++;
	  if (ecalRecHitChi2[ihit] < chi2cut  && ecalRecHitIEta[ihit] > 0) nNormalChi2EB[i][1]++;
	
	  if (ecalRecHitOutOfTimeChi2[ihit] < chi2cut) nNormalChi2OutOfTime[i]++;
	  if (ecalRecHitOutOfTimeChi2[ihit] < chi2cut  && ecalRecHitIEta[ihit] < 0) nNormalChi2OutOfTimeEB[i][0]++;
	  if (ecalRecHitOutOfTimeChi2[ihit] < chi2cut  && ecalRecHitIEta[ihit] > 0) nNormalChi2OutOfTimeEB[i][1]++;
	  
	  if (fabs(ecalRecHitTime[ihit]/sigmat ) < timecut) nNormalTime[i]++;
	  if (fabs(ecalRecHitTime[ihit]/sigmat ) < timecut && ecalRecHitIEta[ihit] < 0) nNormalTimeEB[i][0]++;
	  if (fabs(ecalRecHitTime[ihit]/sigmat ) < timecut && ecalRecHitIEta[ihit] > 0) nNormalTimeEB[i][1]++;


	  
	}
      }


      }
    } // loop over entries

  TGraph *gTime = new TGraph();
  gTime->SetMarkerStyle(21);
  gTime->SetMarkerSize(0.6);
  gTime->SetMarkerColor(2);

  TGraph *gChi2 = new TGraph();
  gChi2->SetMarkerStyle(21);
  gChi2->SetMarkerSize(0.6);
  gChi2->SetMarkerColor(3);

  TGraph *gOutOfTimeChi2 = new TGraph();
  gOutOfTimeChi2->SetMarkerStyle(21);
  gOutOfTimeChi2->SetMarkerSize(0.6);
  gOutOfTimeChi2->SetMarkerColor(4);


  TGraph *gTimeEBP = new TGraph();
  gTimeEBP->SetMarkerStyle(20);
  gTimeEBP->SetMarkerSize(0.7);
  gTimeEBP->SetMarkerColor(2);

  TGraph *gChi2EBP = new TGraph();
  gChi2EBP->SetMarkerStyle(20);
  gChi2EBP->SetMarkerSize(0.7);
  gChi2EBP->SetMarkerColor(3);

  TGraph *gOutOfTimeChi2EBP = new TGraph();
  gOutOfTimeChi2EBP->SetMarkerStyle(20);
  gOutOfTimeChi2EBP->SetMarkerSize(0.7);
  gOutOfTimeChi2EBP->SetMarkerColor(4);
 
  TGraph *gTimeEBM = new TGraph();
  gTimeEBM->SetMarkerStyle(24);
  gTimeEBM->SetMarkerSize(0.7);
  gTimeEBM->SetMarkerColor(2);

  TGraph *gChi2EBM = new TGraph();
  gChi2EBM->SetMarkerStyle(24);
  gChi2EBM->SetMarkerSize(0.7);
  gChi2EBM->SetMarkerColor(3);

  TGraph *gOutOfTimeChi2EBM = new TGraph();
  gOutOfTimeChi2EBM->SetMarkerStyle(24);
  gOutOfTimeChi2EBM->SetMarkerSize(0.7);
  gOutOfTimeChi2EBM->SetMarkerColor(4);


  float effS, effN;

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

    effN = (float)nNormalTime[i]/(float)nNormalTot;
    effS = (float)nSpikeTime[i]/(float)nSpikeTot;
    gTime->SetPoint(i,effS,effN);

    effN = (float)nNormalChi2[i]/(float)nNormalTot;
    effS = (float)nSpikeChi2[i]/(float)nSpikeTot;
    gChi2->SetPoint(i,effS,effN);

    effN = (float)nNormalChi2OutOfTime[i]/(float)nNormalTot;
    effS = (float)nSpikeChi2OutOfTime[i]/(float)nSpikeTot;
    gOutOfTimeChi2->SetPoint(i,effS,effN);

    //EB-
    effN = (float)nNormalTimeEB[i][0]/(float)nNormalTotEB[0];
    effS = (float)nSpikeTimeEB[i][0]/(float)nSpikeTotEB[0];
    gTimeEBM->SetPoint(i,effS,effN);

    effN = (float)nNormalChi2EB[i][0]/(float)nNormalTotEB[0];
    effS = (float)nSpikeChi2EB[i][0]/(float)nSpikeTotEB[0];
    gChi2EBM->SetPoint(i,effS,effN);

    effN = (float)nNormalChi2OutOfTimeEB[i][0]/(float)nNormalTotEB[0];
    effS = (float)nSpikeChi2OutOfTimeEB[i][0]/(float)nSpikeTotEB[0];
    gOutOfTimeChi2EBM->SetPoint(i,effS,effN);

    //EB+
    effN = (float)nNormalTimeEB[i][1]/(float)nNormalTotEB[1];
    effS = (float)nSpikeTimeEB[i][1]/(float)nSpikeTotEB[1];
    gTimeEBP->SetPoint(i,effS,effN);

    effN = (float)nNormalChi2EB[i][1]/(float)nNormalTotEB[1];
    effS = (float)nSpikeChi2EB[i][1]/(float)nSpikeTotEB[1];
    gChi2EBP->SetPoint(i,effS,effN);

    effN = (float)nNormalChi2OutOfTimeEB[i][1]/(float)nNormalTotEB[1];
    effS = (float)nSpikeChi2OutOfTimeEB[i][1]/(float)nSpikeTotEB[1];
    gOutOfTimeChi2EBP->SetPoint(i,effS,effN);

  }




  TFile saving (outputRootName.c_str (),"recreate") ;
  saving.cd () ;  
  
  // saving distributions
  hRun->Write();

  gTime->Write("g_Time");
  gChi2->Write("g_Chi2");
  gOutOfTimeChi2->Write("g_OutOfTimeChi2");

  gTimeEBP->Write("g_Time_EBP");
  gChi2EBP->Write("g_Chi2_EBP");
  gOutOfTimeChi2EBP->Write("g_OutOfTimeChi2_EBP");

  gTimeEBM->Write("g_Time_EBM");
  gChi2EBM->Write("g_Chi2_EBM");
  gOutOfTimeChi2EBM->Write("g_OutOfTimeChi2_EBM");


  hTime[0]->Write();
  hTime[1]->Write();

  saving.Close () ;
 
  return 0 ;
}
Example #24
0
Bool_t CheckSmearedESD(const char* gAliceFileName = "galice.root",
		       const char* esdFileName = "jstiller_AliESDs.root")
{
  // check the content of the ESD
  
  
  // check values

  Int_t    checkNGenLow = 1;
  
  Double_t checkEffLow = 0.5;
  Double_t checkEffSigma = 3;
  Double_t checkFakeHigh = 0.5;
  Double_t checkFakeSigma = 3;
  
  Double_t checkResPtInvHigh = 5;
  Double_t checkResPtInvSigma = 3;
  Double_t checkResPhiHigh = 10;
  Double_t checkResPhiSigma = 3;
  Double_t checkResThetaHigh = 10;
  Double_t checkResThetaSigma = 3;

  Double_t checkPIDEffLow = 0.5;
  Double_t checkPIDEffSigma = 3;
  Double_t checkResTOFHigh = 500;
  Double_t checkResTOFSigma = 3;

  Double_t checkPHOSNLow = 5;
  Double_t checkPHOSEnergyLow = 0.3;
  Double_t checkPHOSEnergyHigh = 1.0;
  Double_t checkEMCALNLow = 50;
  Double_t checkEMCALEnergyLow = 0.05;
  Double_t checkEMCALEnergyHigh = 1.0;

  Double_t checkMUONNLow = 1;
  Double_t checkMUONPtLow = 0.5;
  Double_t checkMUONPtHigh = 10.;

  Double_t cutPtV0 = 0.3;
  Double_t checkV0EffLow = 0.02;
  Double_t checkV0EffSigma = 3;
  Double_t cutPtCascade = 0.5;
  Double_t checkCascadeEffLow = 0.01;

  // open run loader and load gAlice, kinematics and header

  AliRunLoader* runLoader = AliRunLoader::Open(gAliceFileName);
  if (!runLoader) {
    Error("CheckESD", "getting run loader from file %s failed", 
	    gAliceFileName);
    return kFALSE;
  }
  runLoader->LoadKinematics();
  runLoader->LoadHeader();

  // open the ESD file

  TFile* esdFile = TFile::Open(esdFileName);
  if (!esdFile || !esdFile->IsOpen()) {
    Error("CheckESD", "opening ESD file %s failed", esdFileName);
    return kFALSE;
  }
  AliESDEvent * esd = new AliESDEvent;
  TTree* tree = (TTree*) esdFile->Get("esdTree");
  if (!tree) {
    Error("CheckESD", "no ESD tree found");
    return kFALSE;
  }
  esd->ReadFromTree(tree);

  // efficiency and resolution histograms

  Int_t nBinsPt = 15;
  Float_t minPt = 0.1;
  Float_t maxPt = 3.1;
  TH1F* hGen = CreateHisto("hGen", "generated tracks", 
			   nBinsPt, minPt, maxPt, "p_{t} [GeV/c]", "N");
  TH1F* hRec = CreateHisto("hRec", "reconstructed tracks", 
			   nBinsPt, minPt, maxPt, "p_{t} [GeV/c]", "N");
  Int_t nGen = 0;
  Int_t nRec = 0;
  Int_t nFake = 0;

  TH1F* hResPtInv = CreateHisto("hResPtInv", "", 100, -10, 10, 
           "(p_{t,rec}^{-1}-p_{t,sim}^{-1}) / p_{t,sim}^{-1} [%]", "N");
  TH1F* hResPhi = CreateHisto("hResPhi", "", 100, -20, 20, 
			      "#phi_{rec}-#phi_{sim} [mrad]", "N");
  TH1F* hResTheta = CreateHisto("hResTheta", "", 100, -20, 20, 
				"#theta_{rec}-#theta_{sim} [mrad]", "N");

  // PID

  Int_t partCode[AliPID::kSPECIES] = 
    {kElectron, kMuonMinus, kPiPlus, kKPlus, kProton};
  const char* partName[AliPID::kSPECIES+1] = 
    {"electron", "muon", "pion", "kaon", "proton", "other"};
  Double_t partFrac[AliPID::kSPECIES] = 
    {0.01, 0.01, 0.85, 0.10, 0.05};
  Int_t identified[AliPID::kSPECIES+1][AliPID::kSPECIES];
  for (Int_t iGen = 0; iGen < AliPID::kSPECIES+1; iGen++) {
    for (Int_t iRec = 0; iRec < AliPID::kSPECIES; iRec++) {
      identified[iGen][iRec] = 0;
    }
  }
  Int_t nIdentified = 0;

  // dE/dx and TOF

  TH2F* hDEdxRight = new TH2F("hDEdxRight", "", 300, 0, 3, 100, 0, 400);
  hDEdxRight->SetStats(kFALSE);
  hDEdxRight->GetXaxis()->SetTitle("p [GeV/c]");
  hDEdxRight->GetYaxis()->SetTitle("dE/dx_{TPC}");
  hDEdxRight->SetMarkerStyle(kFullCircle);
  hDEdxRight->SetMarkerSize(0.4);
  TH2F* hDEdxWrong = new TH2F("hDEdxWrong", "", 300, 0, 3, 100, 0, 400);
  hDEdxWrong->SetStats(kFALSE);
  hDEdxWrong->GetXaxis()->SetTitle("p [GeV/c]");
  hDEdxWrong->GetYaxis()->SetTitle("dE/dx_{TPC}");
  hDEdxWrong->SetMarkerStyle(kFullCircle);
  hDEdxWrong->SetMarkerSize(0.4);
  hDEdxWrong->SetMarkerColor(kRed);
  TH1F* hResTOFRight = CreateHisto("hResTOFRight", "", 100, -1000, 1000, 
				   "t_{TOF}-t_{track} [ps]", "N");
  TH1F* hResTOFWrong = CreateHisto("hResTOFWrong", "", 100, -1000, 1000, 
				   "t_{TOF}-t_{track} [ps]", "N");
  hResTOFWrong->SetLineColor(kRed);

  // calorimeters

  TH1F* hEPHOS = CreateHisto("hEPHOS", "PHOS", 100, 0, 50, "E [GeV]", "N");
  TH1F* hEEMCAL = CreateHisto("hEEMCAL", "EMCAL", 100, 0, 50, "E [GeV]", "N");

  // muons

  TH1F* hPtMUON = CreateHisto("hPtMUON", "MUON", 100, 0, 20, 
			      "p_{t} [GeV/c]", "N");

  // V0s and cascades

  TH1F* hMassK0 = CreateHisto("hMassK0", "K^{0}", 100, 0.4, 0.6, 
			      "M(#pi^{+}#pi^{-}) [GeV/c^{2}]", "N");
  TH1F* hMassLambda = CreateHisto("hMassLambda", "#Lambda", 100, 1.0, 1.2, 
				  "M(p#pi^{-}) [GeV/c^{2}]", "N");
  TH1F* hMassLambdaBar = CreateHisto("hMassLambdaBar", "#bar{#Lambda}", 
				     100, 1.0, 1.2, 
				     "M(#bar{p}#pi^{+}) [GeV/c^{2}]", "N");
  Int_t nGenV0s = 0;
  Int_t nRecV0s = 0;
  TH1F* hMassXi = CreateHisto("hMassXi", "#Xi", 100, 1.2, 1.5, 
			      "M(#Lambda#pi) [GeV/c^{2}]", "N");
  TH1F* hMassOmega = CreateHisto("hMassOmega", "#Omega", 100, 1.5, 1.8, 
				 "M(#LambdaK) [GeV/c^{2}]", "N");
  Int_t nGenCascades = 0;
  Int_t nRecCascades = 0;

  // loop over events

  for (Int_t iEvent = 0; iEvent < runLoader->GetNumberOfEvents(); iEvent++) {
    runLoader->GetEvent(iEvent);

    // select simulated primary particles, V0s and cascades

    AliStack* stack = runLoader->Stack();
    Int_t nParticles = stack->GetNtrack();
    TArrayF vertex(3);
    runLoader->GetHeader()->GenEventHeader()->PrimaryVertex(vertex);
    TObjArray selParticles;
    TObjArray selV0s;
    TObjArray selCascades;
    for (Int_t iParticle = 0; iParticle < nParticles; iParticle++) {
      TParticle* particle = stack->Particle(iParticle);
      if (!particle) continue;
      if (particle->Pt() < 0.001) continue;
      if (TMath::Abs(particle->Eta()) > 0.9) continue;
      TVector3 dVertex(particle->Vx() - vertex[0], 
		       particle->Vy() - vertex[1],
		       particle->Vz() - vertex[2]);
      if (dVertex.Mag() > 0.0001) continue;

      switch (TMath::Abs(particle->GetPdgCode())) {
      case kElectron:
      case kMuonMinus:
      case kPiPlus:
      case kKPlus:
      case kProton: {
	if (particle->Pt() > minPt) {
	  selParticles.Add(particle);
	  nGen++;
	  hGen->Fill(particle->Pt());
	}
	break;
      }
      case kK0Short:
      case kLambda0: {
	if (particle->Pt() > cutPtV0) {
	  nGenV0s++;
	  selV0s.Add(particle);
	}
	break;
      }
      case kXiMinus:
      case kOmegaMinus: {
	if (particle->Pt() > cutPtCascade) {
	  nGenCascades++;
	  selCascades.Add(particle);
	}
	break;
      }
      default: break;
      }
    }

    // get the event summary data

    tree->GetEvent(iEvent);
    if (!esd) {
      Error("CheckESD", "no ESD object found for event %d", iEvent);
      return kFALSE;
    }

    // loop over tracks

    for (Int_t iTrack = 0; iTrack < esd->GetNumberOfTracks(); iTrack++) {
      AliESDtrack* track = esd->GetTrack(iTrack);

      // select tracks of selected particles

      Int_t label = TMath::Abs(track->GetLabel());
      if (label > stack->GetNtrack()) continue;     // background

      TParticle* particle = stack->Particle(label);
      if (!selParticles.Contains(particle)) continue;
      if ((track->GetStatus() & AliESDtrack::kITSrefit) == 0) continue;
      if (track->GetConstrainedChi2() > 1e9) continue;
      selParticles.Remove(particle);   // don't count multiple tracks


      nRec++;
      hRec->Fill(particle->Pt());
      if (track->GetLabel() < 0) nFake++;

      // resolutions

      hResPtInv->Fill(100. * (TMath::Abs(track->GetSigned1Pt()) - 1./particle->Pt()) * 
		      particle->Pt());
      hResPhi->Fill(1000. * (track->Phi() - particle->Phi()));
      hResTheta->Fill(1000. * (track->Theta() - particle->Theta()));

      // PID

      if ((track->GetStatus() & AliESDtrack::kESDpid) == 0) continue;
      Int_t iGen = 5;
      for (Int_t i = 0; i < AliPID::kSPECIES; i++) {
	if (TMath::Abs(particle->GetPdgCode()) == partCode[i]) iGen = i;
      }
      Double_t probability[AliPID::kSPECIES];
      track->GetESDpid(probability);
      Double_t pMax = 0;
      Int_t iRec = 0;
      for (Int_t i = 0; i < AliPID::kSPECIES; i++) {
	probability[i] *= partFrac[i];
	if (probability[i] > pMax) {
	  pMax = probability[i];
	  iRec = i;
	}
      }
      identified[iGen][iRec]++;
      if (iGen == iRec) nIdentified++;

      // dE/dx and TOF

      Double_t time[AliPID::kSPECIES];
      track->GetIntegratedTimes(time);
      if (iGen == iRec) {
	hDEdxRight->Fill(particle->P(), track->GetTPCsignal());
        if ((track->GetStatus() & AliESDtrack::kTOFpid) != 0) {
	  hResTOFRight->Fill(track->GetTOFsignal() - time[iRec]);
	}
      } else {
	hDEdxWrong->Fill(particle->P(), track->GetTPCsignal());
        if ((track->GetStatus() & AliESDtrack::kTOFpid) != 0) {
	  hResTOFWrong->Fill(track->GetTOFsignal() - time[iRec]);
	}
      }
    }

    // loop over muon tracks

    {
    for (Int_t iTrack = 0; iTrack < esd->GetNumberOfMuonTracks(); iTrack++) {
      AliESDMuonTrack* muonTrack = esd->GetMuonTrack(iTrack);
      Double_t ptInv = TMath::Abs(muonTrack->GetInverseBendingMomentum());
      if (ptInv > 0.001) {
	hPtMUON->Fill(1./ptInv);
      }
    }
    }

    // loop over V0s

    for (Int_t iV0 = 0; iV0 < esd->GetNumberOfV0s(); iV0++) {
      AliESDv0* v0 = esd->GetV0(iV0);
      if (v0->GetOnFlyStatus()) continue;
      v0->ChangeMassHypothesis(kK0Short);
      hMassK0->Fill(v0->GetEffMass());
      v0->ChangeMassHypothesis(kLambda0);
      hMassLambda->Fill(v0->GetEffMass());
      v0->ChangeMassHypothesis(kLambda0Bar);
      hMassLambdaBar->Fill(v0->GetEffMass());

      Int_t negLabel = TMath::Abs(esd->GetTrack(v0->GetNindex())->GetLabel());
      if (negLabel > stack->GetNtrack()) continue;     // background

      Int_t negMother = stack->Particle(negLabel)->GetMother(0);
      if (negMother < 0) continue;
      Int_t posLabel = TMath::Abs(esd->GetTrack(v0->GetPindex())->GetLabel());
      if (posLabel > stack->GetNtrack()) continue;     // background

      Int_t posMother = stack->Particle(posLabel)->GetMother(0);
      if (negMother != posMother) continue;
      TParticle* particle = stack->Particle(negMother);
      if (!selV0s.Contains(particle)) continue;
      selV0s.Remove(particle);
      nRecV0s++;
    }

    // loop over Cascades

    for (Int_t iCascade = 0; iCascade < esd->GetNumberOfCascades(); 
	 iCascade++) {
      AliESDcascade* cascade = esd->GetCascade(iCascade);
      Double_t v0q;
      cascade->ChangeMassHypothesis(v0q,kXiMinus);
      hMassXi->Fill(cascade->GetEffMassXi());
      cascade->ChangeMassHypothesis(v0q,kOmegaMinus);
      hMassOmega->Fill(cascade->GetEffMassXi());

      Int_t negLabel = TMath::Abs(esd->GetTrack(cascade->GetNindex())
				  ->GetLabel());
      if (negLabel > stack->GetNtrack()) continue;     // background

      Int_t negMother = stack->Particle(negLabel)->GetMother(0);
      if (negMother < 0) continue;
      Int_t posLabel = TMath::Abs(esd->GetTrack(cascade->GetPindex())
				  ->GetLabel());
      if (posLabel > stack->GetNtrack()) continue;     // background

      Int_t posMother = stack->Particle(posLabel)->GetMother(0);
      if (negMother != posMother) continue;
      Int_t v0Mother = stack->Particle(negMother)->GetMother(0);
      if (v0Mother < 0) continue;
      Int_t bacLabel = TMath::Abs(esd->GetTrack(cascade->GetBindex())
				  ->GetLabel());
      if (bacLabel > stack->GetNtrack()) continue;     // background

      Int_t bacMother = stack->Particle(bacLabel)->GetMother(0);
      if (v0Mother != bacMother) continue;
      TParticle* particle = stack->Particle(v0Mother);
      if (!selCascades.Contains(particle)) continue;
      selCascades.Remove(particle);
      nRecCascades++;
    }

    // loop over the clusters

    {
      for (Int_t iCluster=0; iCluster<esd->GetNumberOfCaloClusters(); iCluster++) {
	AliESDCaloCluster * clust = esd->GetCaloCluster(iCluster);
	if (clust->IsPHOS()) hEPHOS->Fill(clust->E());
	if (clust->IsEMCAL()) hEEMCAL->Fill(clust->E());
      }
    }

  }

  // perform checks

  if (nGen < checkNGenLow) {
    Warning("CheckESD", "low number of generated particles: %d", Int_t(nGen));
  }

  TH1F* hEff = CreateEffHisto(hGen, hRec);

  Info("CheckESD", "%d out of %d tracks reconstructed including %d "
	 "fake tracks", nRec, nGen, nFake);
  if (nGen > 0) {
    // efficiency

    Double_t eff = nRec*1./nGen;
    Double_t effError = TMath::Sqrt(eff*(1.-eff) / nGen);
    Double_t fake = nFake*1./nGen;
    Double_t fakeError = TMath::Sqrt(fake*(1.-fake) / nGen);
    Info("CheckESD", "eff = (%.1f +- %.1f) %%  fake = (%.1f +- %.1f) %%",
	 100.*eff, 100.*effError, 100.*fake, 100.*fakeError);

		if(100.*eff<5.0){
			Error("CheckESD", "Efficiency too low!!!");return kFALSE;
		}
    if (eff < checkEffLow - checkEffSigma*effError) {
      Warning("CheckESD", "low efficiency: (%.1f +- %.1f) %%", 
	      100.*eff, 100.*effError);
    }
    if (fake > checkFakeHigh + checkFakeSigma*fakeError) {
      Warning("CheckESD", "high fake: (%.1f +- %.1f) %%", 
	      100.*fake, 100.*fakeError);
    }

    // resolutions

    Double_t res, resError;
    if (FitHisto(hResPtInv, res, resError)) {
      Info("CheckESD", "relative inverse pt resolution = (%.1f +- %.1f) %%",
	   res, resError);
      if (res > checkResPtInvHigh + checkResPtInvSigma*resError) {
	Warning("CheckESD", "bad pt resolution: (%.1f +- %.1f) %%", 
		res, resError);
      }
    }

    if (FitHisto(hResPhi, res, resError)) {
      Info("CheckESD", "phi resolution = (%.1f +- %.1f) mrad", res, resError);
      if (res > checkResPhiHigh + checkResPhiSigma*resError) {
	Warning("CheckESD", "bad phi resolution: (%.1f +- %.1f) mrad", 
		res, resError);
      }
    }

    if (FitHisto(hResTheta, res, resError)) {
      Info("CheckESD", "theta resolution = (%.1f +- %.1f) mrad", 
	   res, resError);
      if (res > checkResThetaHigh + checkResThetaSigma*resError) {
	Warning("CheckESD", "bad theta resolution: (%.1f +- %.1f) mrad", 
		res, resError);
      }
    }
	}

  // draw the histograms if not in batch mode

  if (!gROOT->IsBatch()) {
    new TCanvas;
    hEff->DrawCopy();
    new TCanvas;
    hResPtInv->DrawCopy("E");
    new TCanvas;
    hResPhi->DrawCopy("E");
    new TCanvas;
    hResTheta->DrawCopy("E");
  }

  // write the output histograms to a file

  TFile* outputFile = TFile::Open("check.root", "recreate");
  if (!outputFile || !outputFile->IsOpen()) {
    Error("CheckESD", "opening output file check.root failed");
    return kFALSE;
  }
  hEff->Write();
  hResPtInv->Write();
  hResPhi->Write();
  hResTheta->Write();
  outputFile->Close();
  delete outputFile;

  // clean up

  delete hGen;
  delete hRec;
  delete hEff;
  delete hResPtInv;
  delete hResPhi;
  delete hResTheta;

  delete esd;
  esdFile->Close();
  delete esdFile;

  runLoader->UnloadHeader();
  runLoader->UnloadKinematics();
  delete runLoader;

  // result of check

  Info("CheckESD", "check of ESD was successfull");
  return kTRUE;
}
Example #25
0
int main(int ac, char** av){
	if(ac < 2){
		std::cout << "usage: ./signalAcceptance inputFile[s]" << std::endl;
		return -1;
	}
	
	TH1F* allCategory = new TH1F("allCategory","all Category",11,0.5,11.5);
	TH1F* preselCategory = new TH1F("preselCategory","presel Category",11,0.5,11.5);
	TH1F* photonCategory = new TH1F("photonCategory","reco photon Category",11,0.5,11.5);
	
	TH1F* VisAllCategory = new TH1F("VisAllCategory","all Category, Vis",11,0.5,11.5);
	TH1F* VisPreselCategory = new TH1F("VisPreselCategory","presel Category, Vis",11,0.5,11.5);
	TH1F* VisPhotonCategory = new TH1F("VisPhotonCategory","reco photon Category, Vis",11,0.5,11.5);
	
	
	TH1F* dROtherGen = new TH1F("dROtherGen", "dROtherGen", 800, 0.0, 4.0);
	TH1F* parentage = new TH1F("parentage","parentage",30, 0, 30);	
	TH1F* dptOverpt = new TH1F("dptOverpt","dptOverpt", 400, -2.0, 2.0);
	TH1F* dRrecoGen = new TH1F("dRrecoGen","dRrecoGen", 200, 0.0, 0.2);
	TH1F* dPhiRecoGen = new TH1F("dPhiRecoGen","dPhiRecoGen", 400, 0.0, 0.2);
	TH1F* dEtaRecoGen = new TH1F("dEtaRecoGen","dEtaRecoGen", 800, -0.2, 0.2);
	
	TH1F* dRGenNearJet = new TH1F("dRGenNearJet","dRGenNearJet", 200, 0.0, 1.0);
	TH1F* dPhiGenNearJet = new TH1F("dPhiGenNearJet","dPhiGenNearJet", 100, 0.0, 0.5);
	TH1F* dEtaGenNearJet = new TH1F("dEtaGenNearJet","dEtaGenNearJet", 200, -0.5, 0.5);

	//TH1F* dRGenNextNearJet = new TH1F("dRGenNextNearJet","dRGenNextNearJet", 600, 0.0, 6.0);
	//TH1F* dPhiGenNextNearJet = new TH1F("dPhiGenNextNearJet","dPhiGenNextNearJet", 300, 0.0, 3.0);
	//TH1F* dEtaGenNextNearJet = new TH1F("dEtaGenNextNearJet","dEtaGenNextNearJet", 600, -3.0, 3.0);

	// object selector
	Selector* selectorLoose = new Selector();
	// create event selectors here
	EventPick* evtPickLoose = new EventPick("LoosePhotonID");
	// do not do jet to photon dR cleaning
	evtPickLoose->veto_pho_jet_dR = 0.0;
	
	
	EventTree* tree = new EventTree(ac-1, av+1);
	double PUweight = 1.0;
	
	Long64_t nEntr = tree->GetEntries();
	for(Long64_t entry=0; entry<nEntr; entry++){
		if(entry%10000 == 0) std::cout << "processing entry " << entry << " out of " << nEntr << std::endl;
		tree->GetEntry(entry);
		
		doJER(tree);

		selectorLoose->process_objects(tree);
		evtPickLoose->process_event(tree, selectorLoose, PUweight);

		// fill the histograms
		fillCategory(tree, allCategory, PUweight);
		if(evtPickLoose->passPreSel) fillCategory(tree, preselCategory, PUweight);
		if(evtPickLoose->passAll) fillCategory(tree, photonCategory, PUweight);

		// fill histograms for gen photon passing the acceptance cuts defined in analysis
		bool inAcc = false;
		for(int mcInd=0; mcInd<tree->nMC_; ++mcInd){
			if(tree->mcPID->at(mcInd) == 22 && 
			(tree->mcParentage->at(mcInd)==2 || tree->mcParentage->at(mcInd)==10 || tree->mcParentage->at(mcInd)==26) && 
			tree->mcPt->at(mcInd) > 25 && 
			fabs(tree->mcEta->at(mcInd)) < 1.4442){
				inAcc = true;
			}
		}
		if(inAcc){
			fillCategory(tree, VisAllCategory, PUweight);
			if(evtPickLoose->passPreSel) fillCategory(tree, VisPreselCategory, PUweight);
			if(evtPickLoose->passAll) fillCategory(tree, VisPhotonCategory, PUweight);
		}
		
		// have at least one good photon
		if(!evtPickLoose->passAll) continue;

		// test
		//if(overlapMadGraph(tree)) continue;

		int phoInd = evtPickLoose->Photons.at(0);
		// experiment with delta R cuts for photons
		for(int mcInd=0; mcInd<tree->nMC_; ++mcInd){
			bool etetamatch = dR(tree->mcEta->at(mcInd),tree->mcPhi->at(mcInd),tree->phoEta_->at(phoInd),tree->phoPhi_->at(phoInd)) < 0.2 && 
			(fabs(tree->phoEt_->at(phoInd) - tree->mcPt->at(mcInd)) / tree->mcPt->at(mcInd)) < 1.0;
			if( etetamatch && tree->mcPID->at(mcInd) == 22){
				// test
				if(!(tree->mcParentage->at(mcInd)==2 || tree->mcParentage->at(mcInd)==10 || tree->mcParentage->at(mcInd)==26)) continue;
				
				// fill histograms for mathced photon candidate
				parentage->Fill( tree->mcParentage->at(mcInd) );
				dptOverpt->Fill( (tree->phoEt_->at(phoInd) - tree->mcPt->at(mcInd)) / tree->mcPt->at(mcInd));
				dRrecoGen->Fill( dR(tree->mcEta->at(mcInd),tree->mcPhi->at(mcInd),tree->phoEta_->at(phoInd),tree->phoPhi_->at(phoInd)) );
				dPhiRecoGen->Fill( dPhi( tree->phoPhi_->at(phoInd) - tree->mcPhi->at(mcInd) ) );
				dEtaRecoGen->Fill( tree->phoEta_->at(phoInd) - tree->mcEta->at(mcInd) );
				
				int closestGenInd = secondMinDrIndex( mcInd, tree );
				if(dR(tree->mcEta->at(mcInd), tree->mcPhi->at(mcInd), tree->mcEta->at(closestGenInd), tree->mcPhi->at(closestGenInd)) < 0.01){
					std::cout << "closest PID " << tree->mcPID->at(closestGenInd) << "  MomPID " << tree->mcMomPID->at(closestGenInd) << std::endl;
					std::cout << "photon mother PID " << tree->mcMomPID->at(mcInd) << std::endl;
				}
				dROtherGen->Fill( dR(tree->mcEta->at(mcInd), tree->mcPhi->at(mcInd), tree->mcEta->at(closestGenInd), tree->mcPhi->at(closestGenInd)) );
	
				int closestJetInd = minDrIndex( tree->mcEta->at(mcInd), tree->mcPhi->at(mcInd), tree->jetEta_, tree->jetPhi_ );
				dRGenNearJet->Fill( dR(tree->mcEta->at(mcInd), tree->mcPhi->at(mcInd), tree->jetEta_->at(closestJetInd), tree->jetPhi_->at(closestJetInd) ) );
				dPhiGenNearJet->Fill( dPhi( tree->jetPhi_->at(closestJetInd) - tree->mcPhi->at(mcInd) ) );
				dEtaGenNearJet->Fill( tree->jetEta_->at(closestJetInd) - tree->mcEta->at(mcInd) );
				
				//closestJetInd = secondMinDrIndex( tree->mcEta->at(mcInd), tree->mcPhi->at(mcInd), tree->jetEta_, tree->jetPhi_ );	
				//dRGenNextNearJet->Fill( dR(tree->mcEta->at(mcInd), tree->mcPhi->at(mcInd), tree->jetEta_->at(closestJetInd), tree->jetPhi_->at(closestJetInd) ) );
				//dPhiGenNextNearJet->Fill( dPhi( tree->jetPhi_->at(closestJetInd) - tree->mcPhi->at(mcInd) ) );
				//dEtaGenNextNearJet->Fill( tree->jetEta_->at(closestJetInd) - tree->mcEta->at(mcInd) );
			}
		}
	}

	evtPickLoose->print_cutflow();

	// write histograms
	TFile outFile("signalAcc.root","RECREATE");
	
	saveHist(allCategory, &outFile);
	saveHist(preselCategory, &outFile);
	saveHist(photonCategory, &outFile);
	
	saveHist(VisAllCategory, &outFile);
	saveHist(VisPreselCategory, &outFile);
	saveHist(VisPhotonCategory, &outFile);
	
	saveHist(dROtherGen, &outFile);
	saveHist(parentage, &outFile);
	saveHist(dptOverpt, &outFile);
	saveHist(dRrecoGen, &outFile);
	saveHist(dPhiRecoGen, &outFile);
	saveHist(dEtaRecoGen, &outFile);
	saveHist(dRGenNearJet, &outFile);
	saveHist(dPhiGenNearJet, &outFile);
	saveHist(dEtaGenNearJet, &outFile);
	
	//saveHist(dRGenNextNearJet, &outFile);
	//saveHist(dPhiGenNextNearJet, &outFile);
	//saveHist(dEtaGenNextNearJet, &outFile);

	outFile.Close();

	delete tree;
	return 0;
}
Example #26
0
File: Trig_eff.C Project: XuQiao/HI
void Calc(Char_t *Generatorfile,Char_t *outfile, Char_t *condition, ofstream &fouttxt){

fouttxt<<condition<<" efficiency:"<<endl;

TFile *fin = new TFile(Generatorfile);
TFile *fout =  new TFile(outfile,"update"); 

TH1F *hHFEnergy4 = new TH1F("hHFEnergy","HFEnergy Distribution before Trigger selection",1000,0,100);
hHFEnergy4->Sumw2();
TH1F *hHFEnergy4_tr = new TH1F("hHFEnergy_tr","HFEnergy Distribution after Trigger selection",1000,0,100); 
hHFEnergy4_tr->Sumw2();
TH1F *hHFEnergyPlus4 = new TH1F("hHFEnergyPlus4","HFEnergy Distribution before Trigger selection",1000,0,100);
hHFEnergyPlus4->Sumw2();
TH1F *hHFEnergyPlus4_tr = new TH1F("hHFEnergyPlus4_tr","HFEnergy Distribution after Trigger selection",1000,0,100); 
hHFEnergyPlus4_tr->Sumw2();
TH1F *hNtrack = new TH1F("hNtrack","Ntrack offline Distribution before Trigger selection",300,0,300);
hNtrack->Sumw2();
TH1F *hNtrack_tr = new TH1F("hNtrack_tr","Ntrack offline Distribution after Trigger selection",300,0,300); 
hNtrack_tr->Sumw2();

TTree *tree;
fin->cd();
tree=(TTree*)hiEvtAnalyzer->Get("HiTree");
tree->AddFriend("pptrack=pptracks/trackTree");
tree->AddFriend("skimTree=skimanalysis/HltTree");
tree->AddFriend("hltTree=hltanalysis/HltTree");
tree->AddFriend("hfTree=hfrechits/hfTree");

Float_t hiHF, vz;
Float_t hiHFminus4, hiHFplus4;
Long_t Ev,Nevent;
Int_t Ntrack, n, HLT_PAZeroBiasPixel_SingleTrack_v1, phltPixelClusterShapeFilter, phfPosFilter1, phfNegFilter1, pprimaryvertexFilter, pBeamScrapingFilter, pVertexFilterCutGplus;
Int_t Nskim=0;

Nevent=tree->GetEntries();
cout<<Nevent<<endl;
tree->SetBranchAddress("hiNtracks",&Ntrack);//number of tracks
tree->SetBranchAddress("hiHF",&hiHF);//HF energy
tree->SetBranchAddress("hiHFplusEta4",&hiHFplus4);//HF energy positive 4 to 5
tree->SetBranchAddress("hiHFminusEta4",&hiHFminus4);//HF energy negative -5 to -4
tree->SetBranchAddress("vz",&vz);
tree->SetBranchAddress("n",&n);//HF hits
tree->SetBranchAddress("HLT_PAZeroBiasPixel_SingleTrack_v1",&HLT_PAZeroBiasPixel_SingleTrack_v1);
tree->SetBranchAddress("phltPixelClusterShapeFilter",&phltPixelClusterShapeFilter);
tree->SetBranchAddress("phfPosFilter1",&phfPosFilter1);
tree->SetBranchAddress("phfNegFilter1",&phfNegFilter1);
tree->SetBranchAddress("pprimaryvertexFilter",&pprimaryvertexFilter);
tree->SetBranchAddress("pBeamScrapingFilter",&pBeamScrapingFilter);
tree->SetBranchAddress("pVertexFilterCutGplus",&pVertexFilterCutGplus);

for(Ev=0;Ev<Nevent;Ev++){
if(Ev%5000==0)
cout<<"Have run "<<Ev<<" Events"<<endl;

tree->GetEntry(Ev);

hHFEnergy4->Fill(hiHFplus4+hiHFminus4);
hHFEnergyPlus4->Fill(hiHFplus4);
hNtrack->Fill(Ntrack);

if(condition=="TR"||condition=="ES"||condition=="TRandES"){

if(condition=="TR" && !(HLT_PAZeroBiasPixel_SingleTrack_v1)){
	Nskim++;
	continue;
	}

else if(condition=="ES" && !(pVertexFilterCutGplus && pBeamScrapingFilter && phfPosFilter1 && phfNegFilter1 && pprimaryvertexFilter && TMath::Abs(vz)<15)){
	Nskim++;
	continue;
	}	

else if(condition=="TRandES" && !(HLT_PAZeroBiasPixel_SingleTrack_v1 && pVertexFilterCutGplus && pBeamScrapingFilter && phfPosFilter1 && phfNegFilter1 && pprimaryvertexFilter && TMath::Abs(vz)<15)){
	Nskim++;
	continue;
	}

else{
hHFEnergy4_tr->Fill(hiHFplus4+hiHFminus4);
hHFEnergyPlus4_tr->Fill(hiHFplus4);
hNtrack_tr->Fill(Ntrack);
}

}

else{
cout<<"Error!"<<endl;
break;
}

}

fouttxt<<outfile<<endl;
fouttxt<<"before "<<condition<<" efficiency correction:"<<hHFEnergy4->GetEntries()<<endl;
fouttxt<<"after "<<condition<<" efficiency correction:"<<hHFEnergy4_tr->GetEntries()<<endl;
fouttxt<<"ratio:"<<(double)hHFEnergy4_tr->GetEntries()/hHFEnergy4->GetEntries()<<endl;
fouttxt<<"-----------------------------------------------"<<endl;

fout->cd();
hHFEnergy4->Write("hHFEnergy4",TObject::kOverwrite);
hHFEnergy4_tr->Write("hHFEnergy4_tr",TObject::kOverwrite);

hHFEnergyPlus4->Write("hHFEnergyPlus4",TObject::kOverwrite);
hHFEnergyPlus4_tr->Write("hHFEnergyPlus4_tr",TObject::kOverwrite);

hNtrack->Write("hNtrack",TObject::kOverwrite);
hNtrack_tr->Write("hNtrack_tr",TObject::kOverwrite);

//---------------------------------------------------------------------

TH1F *hEff4 = (TH1F*)hHFEnergy4_tr->Clone();
TGraphAsymmErrors *gEff4 = new TGraphAsymmErrors();
hEff4->SetTitle("Double side |#eta|>4");
hEff4->GetXaxis()->SetTitle("HFEnergy");
hEff4->GetYaxis()->SetTitle("Trigger Efficiency");
gEff4->BayesDivide(hHFEnergy4_tr,hHFEnergy4);
TH1F *hEffPlus4 = (TH1F*)hHFEnergyPlus4_tr->Clone();
hEffPlus4->SetTitle("#eta>4");
hEffPlus4->GetXaxis()->SetTitle("HFEnergy");
hEffPlus4->GetYaxis()->SetTitle("Trigger Efficiency");
TH1F *hEffNtrack = (TH1F*)hNtrack_tr->Clone();
hEffNtrack->SetTitle("");
hEffNtrack->GetXaxis()->SetTitle("Ntrack offline");
hEffNtrack->GetYaxis()->SetTitle("Trigger Efficiency");

for(int ibin=1;ibin<=hHFEnergy4->GetNbinsX();ibin++){
gEff4->SetPointEXlow(ibin,0);
gEff4->SetPointEXhigh(ibin,0);}

hEffPlus4->Divide(hHFEnergyPlus4);
hEffNtrack->Divide(hNtrack);

hEff4->Write("hEff4",TObject::kOverwrite);
hEffPlus4->Write("hEffPlus4",TObject::kOverwrite);
hEffNtrack->Write("hEffNtrack",TObject::kOverwrite);
gEff4->Write("gEff4",TObject::kOverwrite);

fin->Close();
fout->Close();

gROOT->Reset();

}
void ExtractTrackBasedTiming(int runNumber){

    TString fileName = Form ("Run%i/TrackBasedTiming.root", runNumber);
    TString prefix = Form ("Run%i/constants/TrackBasedTiming/",runNumber);
    TString inputPrefix = Form ("Run%i/constants/TDCADCTiming/",runNumber);

    thisFile = TFile::Open( fileName , "UPDATE");
    if (thisFile == 0) {
        cout << "Unable to open file " << fileName.Data() << "...Exiting" << endl;
        return;
    }

    //We need the existing constants, The best we can do here is just read them from the file.
    vector<double> sc_tdc_time_offsets;
    vector<double> sc_fadc_time_offsets;
    vector<double> tof_tdc_time_offsets;
    vector<double> tof_fadc_time_offsets;
    vector<double> tagm_tdc_time_offsets;
    vector<double> tagm_fadc_time_offsets;
    vector<double> tagh_tdc_time_offsets;
    vector<double> tagh_fadc_time_offsets;

    double sc_t_base_fadc;
    double sc_t_base_tdc;
    double tof_t_base_fadc;
    double tof_t_base_tdc;
    double bcal_t_base_fadc;
    double bcal_t_base_tdc;
    double tagm_t_base_fadc;
    double tagm_t_base_tdc;
    double tagh_t_base_fadc;
    double tagh_t_base_tdc;
    double fcal_t_base;
    double cdc_t_base;

    ifstream inFile;
    inFile.open(inputPrefix + "sc_tdc_timing_offsets.txt");
    string line;
    if (inFile.is_open()){
        while (getline (inFile, line)){
            sc_tdc_time_offsets.push_back(atof(line.data()));
        }
    }
    inFile.close();

    ifstream inFile;
    inFile.open(inputPrefix + "sc_adc_timing_offsets.txt");
    string line;
    if (inFile.is_open()){
        while (getline (inFile, line)){
            sc_fadc_time_offsets.push_back(atof(line.data()));
        }
    }
    inFile.close();

    inFile.open(inputPrefix + "tof_tdc_timing_offsets.txt");
    if (inFile.is_open()){
        while (getline (inFile, line)){
            tof_tdc_time_offsets.push_back(atof(line.data()));
        }
    }
    inFile.close();

    inFile.open(inputPrefix + "tof_adc_timing_offsets.txt");
    if (inFile.is_open()){
        while (getline (inFile, line)){
            tof_fadc_time_offsets.push_back(atof(line.data()));
        }
    }
    inFile.close();

    inFile.open(inputPrefix + "tagm_tdc_timing_offsets.txt");
    if (inFile.is_open()){
        while (getline (inFile, line)){
            istringstream iss(line);
            double r, c, offset;
            while (iss>>r>>c>>offset){
                //if (row != 0) continue;
                tagm_tdc_time_offsets.push_back(offset);
            }
        }
    }
    inFile.close();

    inFile.open(inputPrefix + "tagm_adc_timing_offsets.txt");
    if (inFile.is_open()){
        while (getline (inFile, line)){
            istringstream iss(line);
            double r, c, offset;
            while (iss>>r>>c>>offset){
                //if (row != 0) continue;
                tagm_fadc_time_offsets.push_back(offset);
            }
        }
    }
    inFile.close();

    inFile.open(inputPrefix + "tagh_tdc_timing_offsets.txt");
    if (inFile.is_open()){
        while (getline (inFile, line)){
            istringstream iss(line);
            double counter, offset;
            while (iss>>counter>>offset){
                tagh_tdc_time_offsets.push_back(offset);
            }
        }
    }
    inFile.close();

    inFile.open(inputPrefix + "tagh_adc_timing_offsets.txt");
    if (inFile.is_open()){
        while (getline (inFile, line)){
            istringstream iss(line);
            double counter, offset;
            while (iss>>counter>>offset){
                tagh_fadc_time_offsets.push_back(offset);
            }
        }
    }
    inFile.close();

    inFile.open(inputPrefix + "tof_base_time.txt");
    if (inFile.is_open()){
        while (getline (inFile, line)){
            istringstream iss(line);
            iss>>tof_t_base_fadc>>tof_t_base_tdc;
        }
    }
    inFile.close();

    inFile.open(inputPrefix + "sc_base_time.txt");
    if (inFile.is_open()){
        while (getline (inFile, line)){
            istringstream iss(line);
            iss>>sc_t_base_fadc>>sc_t_base_tdc;
        }
    }
    inFile.close();

    inFile.open(inputPrefix + "bcal_base_time.txt");
    if (inFile.is_open()){
        while (getline (inFile, line)){
            istringstream iss(line);
            double adc_offset, tdc_offset;
            iss>>adc_offset>>tdc_offset; // TDC not used currently
            bcal_t_base_fadc = adc_offset;
            bcal_t_base_tdc = tdc_offset;
        }
    }
    inFile.close();

    inFile.open(inputPrefix + "tagm_base_time.txt");
    if (inFile.is_open()){
        while (getline (inFile, line)){
            istringstream iss(line);
            double adc_offset, tdc_offset;
            iss>>adc_offset>>tdc_offset; // TDC not used currently
            tagm_t_base_fadc = adc_offset;
            tagm_t_base_tdc = tdc_offset;
        }
    }

    inFile.close();
    inFile.open(inputPrefix + "tagh_base_time.txt");
    if (inFile.is_open()){
        while (getline (inFile, line)){
            istringstream iss(line);
            double adc_offset, tdc_offset;
            iss>>adc_offset>>tdc_offset; // TDC not used currently
            tagh_t_base_fadc = adc_offset;
            tagh_t_base_tdc = tdc_offset;
        }
    }
    inFile.close();

    inFile.open(inputPrefix + "fcal_base_time.txt");
    if (inFile.is_open()){
        while (getline (inFile, line)){
            istringstream iss(line);
            iss>>fcal_t_base; 
        }
    }
    inFile.close();

    inFile.open(inputPrefix + "cdc_base_time.txt");
    if (inFile.is_open()){
        while (getline (inFile, line)){
            istringstream iss(line);
            iss>>cdc_t_base; 
        }
    }
    inFile.close();


    // Do our final step in the timing alignment with tracking

    //When the RF is present we can try to simply pick out the correct beam bucket for each of the runs
    //First just a simple check to see if we have the appropriate data
    bool useRF = false;
    double RF_Period = 4.0080161;
    TH1I *testHist = Get1DHistogram("HLDetectorTiming", "TAGH_TDC_RF_Compare","Counter ID 001");
    if (testHist != NULL){ // Not great since we rely on channel 1 working, but can be craftier later.
        useRF = true;
    }
    ofstream outFile;
    TH2I *thisHist; 
    thisHist = Get2DHistogram("HLDetectorTiming", "TRACKING", "TAGM - SC Target Time");
    if (useRF) thisHist = Get2DHistogram("HLDetectorTiming", "TRACKING", "TAGM - RFBunch Time");
    if (thisHist != NULL){
        //Statistics on these histograms are really quite low we will have to rebin and do some interpolation
        outFile.open(prefix + "tagm_tdc_timing_offsets.txt", ios::out | ios::trunc);
        outFile.close(); // clear file
        outFile.open(prefix + "tagm_adc_timing_offsets.txt", ios::out | ios::trunc);
        outFile.close(); // clear file
        int nBinsX = thisHist->GetNbinsX();
        int nBinsY = thisHist->GetNbinsY();
        TH1D * selectedTAGMOffset = new TH1D("selectedTAGMOffset", "Selected TAGM Offset; Column; Offset [ns]", nBinsX, 0.5, nBinsX + 0.5);
        TH1I * TAGMOffsetDistribution = new TH1I("TAGMOffsetDistribution", "TAGM Offset; TAGM Offset [ns]; Entries", 500, -250, 250);
        for (int i = 1 ; i <= nBinsX; i++){ 
            TH1D *projY = thisHist->ProjectionY("temp", i, i);
            // Scan over the histogram
            //chose the correct number of bins based on the histogram
            float nsPerBin = (projY->GetBinCenter(projY->GetNbinsX()) - projY->GetBinCenter(1)) / projY->GetNbinsX();
            float timeWindow = 3; //ns (Full Width)
            int binWindow = int(timeWindow / nsPerBin);
            double maxEntries = 0;
            double maxMean = 0;
            for (int j = 1 ; j <= projY->GetNbinsX();j++){
                int minBin = j;
                int maxBin = (j + binWindow) <= projY->GetNbinsX() ? (j + binWindow) : projY->GetNbinsX();
                double sum = 0, nEntries = 0;
                for (int bin = minBin; bin <= maxBin; bin++){
                    sum += projY->GetBinContent(bin) * projY->GetBinCenter(bin);
                    nEntries += projY->GetBinContent(bin);
                    if (bin == maxBin){
                        if (nEntries > maxEntries) {
                            maxMean = sum / nEntries;
                            maxEntries = nEntries;
                        }
                    } 
                }
            }
            //In the case there is RF, our job is to pick just the number of the correct beam bunch, so that's really all we need.
            if(useRF) {
                int beamBucket = int((maxMean / RF_Period) + 0.5); // +0.5 to handle rounding correctly
                selectedTAGMOffset->SetBinContent(i, beamBucket);
                TAGMOffsetDistribution->Fill(beamBucket);
            }
            else{
                selectedTAGMOffset->SetBinContent(i, maxMean);
                TAGMOffsetDistribution->Fill(maxMean);
            }
        }
        /*
        if (!useRF){
            //TFitResultPtr fr1 = selectedTAGMOffset->Fit("pol1", "SQ", "", 0.5, nBinsX + 0.5);
            TFitResultPtr fr1 = selectedTAGMOffset->Fit("pol1", "SQ", "", 5, 50);

            for (int i = 1 ; i <= nBinsX; i++){
                double x0 = fr1->Parameter(0);
                double x1 = fr1->Parameter(1);
                //double x2 = fr1->Parameter(2);
                //double fitResult = x0 + i*x1 + i*i*x2;
                double fitResult = x0 + i*x1;

                double outlierCut = 20;
                double valueToUse = selectedTAGMOffset->GetBinContent(i);
                if (fabs(selectedTAGMOffset->GetBinContent(i) - fitResult) > outlierCut && valueToUse != 0.0){
                    valueToUse = fitResult;
                }

                selectedTAGMOffset->SetBinContent(i, valueToUse);
                if (valueToUse != 0 ) TAGMOffsetDistribution->Fill(valueToUse);
            }
        }
*/
        double meanOffset = TAGMOffsetDistribution->GetMean();
        // This might be in units of beam bunches, so we need to convert
        if (useRF) meanOffset *= RF_Period;
        /*
           for (int i = 1 ; i <= nBinsX; i++){
           double valueToUse = selectedTAGMOffset->GetBinContent(i);
           if (useRF) valueToUse *= RF_Period;
           if (valueToUse == 0) valueToUse = meanOffset;
           outFile.open(prefix + "tagm_tdc_timing_offsets.txt", ios::out | ios::app);
           outFile << "0 " << i << " " << valueToUse + tagm_tdc_time_offsets[i-1] - meanOffset<< endl;
           if (i == 7 || i == 25 || i == 79 || i == 97){
           for(int j = 1; j <= 5; j++){
           outFile << j << " " << i << " " << valueToUse + tagm_tdc_time_offsets[i-1] - meanOffset<< endl;
           }
           }
           outFile.close();
        // Apply the same shift to the adc offsets
        outFile.open(prefix + "tagm_adc_timing_offsets.txt", ios::out | ios::app);
        outFile << "0 " << i << " " << valueToUse + tagm_fadc_time_offsets[i-1] - meanOffset<< endl;
        if (i == 7 || i == 25 || i == 79 || i == 97){
        for(int j = 1; j <= 5; j++){
        outFile << j << " " << i << " " << valueToUse + tagm_fadc_time_offsets[i-1] - meanOffset<< endl;
        }
        }
        outFile.close();
        }
        */

        outFile.open(prefix + "tagm_adc_timing_offsets.txt", ios::out);
        //for (int i = 1 ; i <= nBinsX; i++){
        // Loop over rows
        for (unsigned int column = 1; column <= 102; column++){
            int index = GetCCDBIndexTAGM(column, 0);
            double valueToUse = selectedTAGMOffset->GetBinContent(index);
            if (useRF) valueToUse *= RF_Period;
            if (valueToUse == 0) valueToUse = meanOffset;
            outFile << "0 " << column << " " << valueToUse + tagm_fadc_time_offsets[index-1] - meanOffset<< endl;
            if (column == 9 || column == 27 || column == 81 || column == 99){
                for (unsigned int row = 1; row <= 5; row++){
                    index = GetCCDBIndexTAGM(column, row);
                    valueToUse = selectedTAGMOffset->GetBinContent(index);
                    if (useRF) valueToUse *= RF_Period;
                    if (valueToUse == 0) valueToUse = meanOffset;
                    outFile << row << " " << column << " " << valueToUse + tagm_fadc_time_offsets[index-1] - meanOffset<< endl;
                }
            }
        }
        outFile.close();

        outFile.open(prefix + "tagm_tdc_timing_offsets.txt", ios::out);
        //for (int i = 1 ; i <= nBinsX; i++){
        // Loop over rows
        for (unsigned int column = 1; column <= 102; column++){
            int index = GetCCDBIndexTAGM(column, 0);
            double valueToUse = selectedTAGMOffset->GetBinContent(index);
            if (useRF) valueToUse *= RF_Period;
            if (valueToUse == 0) valueToUse = meanOffset;
            outFile << "0 " << column << " " << valueToUse + tagm_tdc_time_offsets[index-1] - meanOffset << endl;
            if (column == 9 || column == 27 || column == 81 || column == 99){
                for (unsigned int row = 1; row <= 5; row++){
                    index = GetCCDBIndexTAGM(column, row);
                    valueToUse = selectedTAGMOffset->GetBinContent(index);
                    if (useRF) valueToUse *= RF_Period;
                    if (valueToUse == 0) valueToUse = meanOffset;
                    outFile << row << " " << column << " " << valueToUse + tagm_tdc_time_offsets[index-1] - meanOffset << endl;
                }
            }
        }
        outFile.close();
        outFile.open(prefix + "tagm_base_time.txt", ios::out);
        outFile << tagm_t_base_fadc - meanOffset << " " << tagm_t_base_tdc - meanOffset << endl;
        outFile.close();

    }

    thisHist = Get2DHistogram("HLDetectorTiming", "TRACKING", "TAGH - SC Target Time");
    if (useRF) thisHist = Get2DHistogram("HLDetectorTiming", "TRACKING", "TAGH - RFBunch Time");
    if(thisHist != NULL){
        outFile.open(prefix + "tagh_tdc_timing_offsets.txt", ios::out | ios::trunc);
        outFile.close(); // clear file
        outFile.open(prefix + "tagh_adc_timing_offsets.txt", ios::out | ios::trunc);
        outFile.close(); // clear file

        int nBinsX = thisHist->GetNbinsX();
        int nBinsY = thisHist->GetNbinsY();
        TH1D * selectedTAGHOffset = new TH1D("selectedTAGHOffset", "Selected TAGH Offset; ID; Offset [ns]", nBinsX, 0.5, nBinsX + 0.5);
        TH1I * TAGHOffsetDistribution = new TH1I("TAGHOffsetDistribution", "TAGH Offset; TAGH Offset [ns]; Entries", 500, -250, 250);
        for (int i = 1 ; i <= nBinsX; i++){
            TH1D *projY = thisHist->ProjectionY("temp", i, i);
            // Scan over the histogram
            //chose the correct number of bins based on the histogram
            float nsPerBin = (projY->GetBinCenter(projY->GetNbinsX()) - projY->GetBinCenter(1)) / projY->GetNbinsX();
            float timeWindow = 2; //ns (Full Width)
            int binWindow = int(timeWindow / nsPerBin);

            double maxEntries = 0;
            double maxMean = 0;
            for (int j = 1 ; j <= projY->GetNbinsX();j++){
                int minBin = j;
                int maxBin = (j + binWindow) <= projY->GetNbinsX() ? (j + binWindow) : projY->GetNbinsX();
                double sum = 0; 
                double nEntries = 0;
                for (int bin = minBin; bin <= maxBin; bin++){
                    sum += projY->GetBinContent(bin) * projY->GetBinCenter(bin);
                    nEntries += projY->GetBinContent(bin);
                    if (bin == maxBin){
                        if (nEntries > maxEntries){
                            maxMean = sum / nEntries;
                            maxEntries = nEntries;
                        }
                    }
                }
            }

            if(useRF) {
                int beamBucket = int((maxMean / RF_Period) + 0.5); // +0.5 to handle rounding correctly
                selectedTAGHOffset->SetBinContent(i, beamBucket);
                TAGHOffsetDistribution->Fill(beamBucket);
            }
            else{
                selectedTAGHOffset->SetBinContent(i, maxMean);
            }
            /*
               outFile.open("tagh_tdc_timing_offsets.txt", ios::out | ios::app);
               outFile << i << " " << maxMean + tagh_tdc_time_offsets[i] << endl;
               outFile.close();
               outFile.open("tagh_adc_timing_offsets.txt", ios::out | ios::app);
               outFile << i << " " << maxMean + tagh_fadc_time_offsets[i] << endl;
               outFile.close();
               */
        }

        // Fit 1D histogram. If value is far from the fit use the fitted value
        // Two behaviors above and below microscope
        // This isn't working well, so removing...
        /*
           TFitResultPtr fr1 = selectedTAGHOffset->Fit("pol2", "SQ", "", 0.5, 131.5);
           TFitResultPtr fr2 = selectedTAGHOffset->Fit("pol2", "SQ", "", 182.5, 274.5);        

           for (int i = 1 ; i <= nBinsX; i++){
           double fitResult = 0.0;
           if (i < 150){
           double x0 = fr1->Parameter(0);
           double x1 = fr1->Parameter(1);
           double x2 = fr1->Parameter(2);
           fitResult = x0 + i*x1 + i*i*x2;
           }
           else{
           double x0 = fr2->Parameter(0);
           double x1 = fr2->Parameter(1);
           double x2 = fr2->Parameter(2);
           fitResult = x0 + i*x1 + i*i*x2;
           }

           double outlierCut = 7;
           double valueToUse = selectedTAGHOffset->GetBinContent(i);
           if (fabs(selectedTAGHOffset->GetBinContent(i) - fitResult) > outlierCut && valueToUse != 0.0){
           valueToUse = fitResult;
           }

           selectedTAGHOffset->SetBinContent(i, valueToUse);
           if(valueToUse != 0) TAGHOffsetDistribution->Fill(valueToUse);
           }
           */
        double meanOffset = TAGHOffsetDistribution->GetMean();
        if (useRF) meanOffset *= RF_Period;
        for (int i = 1 ; i <= nBinsX; i++){
            valueToUse = selectedTAGHOffset->GetBinContent(i);
            if (useRF) valueToUse *= RF_Period;
            if (valueToUse == 0) valueToUse = meanOffset;
            outFile.open(prefix + "tagh_tdc_timing_offsets.txt", ios::out | ios::app);
            outFile << i << " " << valueToUse + tagh_tdc_time_offsets[i-1] - meanOffset << endl;
            outFile.close();
            outFile.open(prefix + "tagh_adc_timing_offsets.txt", ios::out | ios::app);
            outFile << i << " " << valueToUse + tagh_fadc_time_offsets[i-1] - meanOffset << endl;
            outFile.close();
        }

        outFile.open(prefix + "tagh_base_time.txt", ios::out);
        outFile << tagh_t_base_fadc - meanOffset << " " << tagh_t_base_tdc - meanOffset << endl;
        outFile.close();
    }

    // We can use the RF time to calibrate the SC time (Experimental for now)
    double meanSCOffset = 0.0; // In case we change the time of the SC, we need this in this scope
    if(useRF){
        TH1F * selectedSCSectorOffset = new TH1F("selectedSCSectorOffset", "Selected TDC-RF offset;Sector; Time", 30, 0.5, 30.5);
        TH1F * selectedSCSectorOffsetDistribution = new TH1F("selectedSCSectorOffsetDistribution", "Selected TDC-RF offset;Time;Entries", 100, -3.0, 3.0);
        TF1* f = new TF1("f","pol0(0)+gaus(1)", -3.0, 3.0);
        for (int sector = 1; sector <= 30; sector++){
            TH1I *scRFHist = Get1DHistogram("HLDetectorTiming", "SC_Target_RF_Compare", Form("Sector %.2i", sector));
            if (scRFHist == NULL) continue;
            //Do the fit
            TFitResultPtr fr = scRFHist->Fit("pol0", "SQ", "", -2, 2);
            double p0 = fr->Parameter(0);

            f->FixParameter(0,p0);
            f->SetParLimits(2, -2, 2);
            f->SetParLimits(3, 0, 2);
            f->SetParameter(1, 10);
            f->SetParameter(2, scRFHist->GetBinCenter(scRFHist->GetMaximumBin()));
            f->SetParameter(3, 0);

            fr = scRFHist->Fit(f, "SQ", "", -2, 2);
            double SCOffset = fr->Parameter(2);
            selectedSCSectorOffset->SetBinContent(sector, SCOffset);
            selectedSCSectorOffsetDistribution->Fill(SCOffset);
        }
        // Now write out the offsets
        meanSCOffset = selectedSCSectorOffsetDistribution->GetMean();
        outFile.open(prefix + "sc_tdc_timing_offsets.txt");
        for (int sector = 1; sector <= 30; sector++){
            outFile << sc_tdc_time_offsets[sector-1] + selectedSCSectorOffset->GetBinContent(sector) - meanSCOffset << endl;
        }
        outFile.close();
        outFile.open(prefix + "sc_adc_timing_offsets.txt");
        for (int sector = 1; sector <= 30; sector++){
            outFile << sc_fadc_time_offsets[sector-1] + selectedSCSectorOffset->GetBinContent(sector) - meanSCOffset << endl;
        }
        outFile.close();
        
        outFile.open(prefix + "sc_base_time.txt");
        outFile << sc_t_base_fadc - meanSCOffset << " " << sc_t_base_tdc - meanSCOffset << endl;
        outFile.close();
    }

    TH1I *this1DHist = Get1DHistogram("HLDetectorTiming", "TRACKING", "TOF - SC Target Time");
    if(this1DHist != NULL){
        //Gaussian
        Double_t maximum = this1DHist->GetBinCenter(this1DHist->GetMaximumBin());
        TFitResultPtr fr = this1DHist->Fit("gaus", "S", "", maximum - 1.5, maximum + 1.5);
        float mean = fr->Parameter(1);
        outFile.open(prefix + "tof_base_time.txt");
        outFile << tof_t_base_fadc - mean - meanSCOffset<< " " << tof_t_base_tdc - mean - meanSCOffset<< endl;
        outFile.close();
    }

    this1DHist = Get1DHistogram("HLDetectorTiming", "TRACKING", "BCAL - SC Target Time");
    if(this1DHist != NULL){
        //Gaussian
        Double_t maximum = this1DHist->GetBinCenter(this1DHist->GetMaximumBin());
        TFitResultPtr fr = this1DHist->Fit("gaus", "S", "", maximum - 5, maximum + 5);
        float mean = fr->Parameter(1);
        outFile.open(prefix + "bcal_base_time.txt");
        outFile << bcal_t_base_fadc - mean - meanSCOffset << " " << bcal_t_base_tdc - mean - meanSCOffset << endl; // TDC info not used
        outFile.close();
    }

    this1DHist = Get1DHistogram("HLDetectorTiming", "TRACKING", "FCAL - SC Target Time");
    if(this1DHist != NULL){
        //Gaussian
        Double_t maximum = this1DHist->GetBinCenter(this1DHist->GetMaximumBin());
        TFitResultPtr fr = this1DHist->Fit("gaus", "S", "", maximum - 5, maximum + 5);
        float mean = fr->Parameter(1);
        outFile.open(prefix + "fcal_base_time.txt");
        outFile << fcal_t_base - mean - meanSCOffset<< endl; 
        outFile.close();
    }

    this1DHist = Get1DHistogram("HLDetectorTiming", "TRACKING", "Earliest CDC Time Minus Matched SC Time");
    if(this1DHist != NULL){
        //Gaussian
        Double_t maximum = this1DHist->GetBinCenter(this1DHist->GetMaximumBin());
        TFitResultPtr fr = this1DHist->Fit("gaus", "S", "", maximum - 15, maximum + 10);
        float mean = fr->Parameter(1);
        outFile.open(prefix + "cdc_base_time.txt");
        outFile << cdc_t_base - mean - meanSCOffset << endl;
        outFile.close();
    }
    thisFile->Write();
    return;
    }
Example #28
0
void plot_1411() {
 gROOT->Reset();
 gStyle->SetOptStat(0);
 gStyle->SetTitleOffset(1.,"Y");
 gStyle->SetTitleOffset(.7,"X");
 gStyle->SetLabelSize(0.04,"XY");
 gStyle->SetTitleSize(0.06,"XY");
 gStyle->SetPadLeftMargin(0.12);
TFile *fsimc = new TFile("rootfiles/shms_20cmtarg_20deg_wc_mscat.root");
TTree *tsimc = (TTree*)fsimc->Get("h1411");
//Declaration of leaves types
 Float_t         hsxfp; // position at focal plane ,+X is pointing down
 Float_t         hsyfp; // X x Y = Z so +Y pointing central ray left
 Float_t         hsxpfp; // dx/dz at focal plane
 Float_t         hsypfp; //  dy/dz at focal plane
 Float_t         hsztari; // thrown position along the beam direction
 Float_t         hsytari;  //thrown  horizontal position X x Y = Z so +Y pointing central ray left at plane perpendicular to SHMS at z=0
 Float_t         hsdeltai; // thrown  100*(p - pc)/pc with pc = central SHMS momentum 
 Float_t         hsyptari; // thrown target dy/dz horizontal slope
 Float_t         hsxptari; // thrown target dx/dz vertical slope
 Float_t         hsztar; // reconstructed position along the beam directio
 Float_t         hsytar; //reconstructed horizontal position
 Float_t         hsdelta;//reconstructed
   Float_t         hsyptar;//reconstructed
   Float_t         hsxptar;//reconstructed
   Float_t         hsxtari;// from thrown kinematics , the calculated vertical position at plane perpendicular to SHMS at z=0
   Float_t         yrast;// vertical raster position
   // Set branch addresses.
   tsimc->SetBranchAddress("hsxfp",&hsxfp);
   tsimc->SetBranchAddress("hsyfp",&hsyfp);
   tsimc->SetBranchAddress("hsxpfp",&hsxpfp);
   tsimc->SetBranchAddress("hsypfp",&hsypfp);
   tsimc->SetBranchAddress("hsztari",&hsztari);
   tsimc->SetBranchAddress("hsytari",&hsytari);
   tsimc->SetBranchAddress("hsdeltai",&hsdeltai);
   tsimc->SetBranchAddress("hsyptari",&hsyptari);
   tsimc->SetBranchAddress("hsxptari",&hsxptari);
   tsimc->SetBranchAddress("hsztar",&hsztar);
   tsimc->SetBranchAddress("hsytar",&hsytar);
   tsimc->SetBranchAddress("hsdelta",&hsdelta);
   tsimc->SetBranchAddress("hsyptar",&hsyptar);
   tsimc->SetBranchAddress("hsxptar",&hsxptar);
   tsimc->SetBranchAddress("hsxtari",&hsxtari);
   //
 TH1F *hxptari = new TH1F("hxptari",";Initial xptar ",100,-.1,.1);
 TH1F *hxptarf = new TH1F("hxptarf",";Recon xptar ",100,-.1,.1);
 TH1F *difxptar = new TH1F("difxptar",";Xptar diff (mr) ",50,-5,5.);
 TH2F *difxptarVxptari = new TH2F("difxptarVxptari",";Init xptar (rad);Xptar diff (mr)",25,-.05,.05,50,-5,5.);
 TH2F *difxptarVyptari = new TH2F("difxptarVyptari",";Init yptar (rad);Xptar diff (mr)",30,-.03,.03,50,-5,5.);
 TH2F *difxptarVxfp = new TH2F("difxptarVxfp",";xfp (cm);Xptar diff (mr)",100,-40.,40.,50,-5,5.);
 TH2F *difxptarVyfp = new TH2F("difxptarVyfp",";yfp (cm);Xptar diff (mr)",100,-30.,30.,50,-5,5.);
 TH2F *difxptarVxpfp = new TH2F("difxptarVxpfp",";xpfp (cm);Xptar diff (mr)",100,-.1,.1,50,-5,5.);
 TH2F *difxptarVypfp = new TH2F("difxptarVypfp",";ypfp (cm);Xptar diff (mr)",100,-.05,.05,50,-5,5.);
 TH2F *difxptarVdeltai = new TH2F("difxptarVdeltai",";Init delta ;Xptar diff (mr)",16,-.1,.22,50,-5,5.);
 TH1F *hyptari = new TH1F("hyptari",";Initial yptar ",100,-.05,.05);
 TH1F *hyptarf = new TH1F("hyptarf",";Recon yptar ",100,-.05,.05);
 //
 TH1F *difyptar = new TH1F("difyptar",";Yptar diff (mr) ",50,-5,5.);
 TH2F *difyptarVxptari = new TH2F("difyptarVxptari",";Init xptar (rad);Yptar diff (mr)",25,-.05,.05,50,-5,5.);
 TH2F *difyptarVyptari = new TH2F("difyptarVyptari",";Init yptar (rad);Yptar diff (mr)",30,-.03,.03,50,-5,5.);
 TH2F *difyptarVxfp = new TH2F("difyptarVxfp",";xfp (cm);Yptar diff (mr)",100,-40.,40.,50,-5,5.);
 TH2F *difyptarVyfp = new TH2F("difyptarVyfp",";yfp (cm);Yptar diff (mr)",100,-30.,30.,50,-5,5.);
 TH2F *difyptarVxpfp = new TH2F("difyptarVxpfp",";xpfp (cm);Yptar diff (mr)",100,-.1,.1,50,-5,5.);
 TH2F *difyptarVypfp = new TH2F("difyptarVypfp",";ypfp (cm);Yptar diff (mr)",100,-.05,.05,50,-5,5.);
 TH2F *difyptarVdeltai = new TH2F("difyptarVdeltai",";Init delta ;Yptar diff (mr)",16,-.1,.22,50,-5,5.);
 //
 TH1F *difytar = new TH1F("difytar",";Ytar diff (cm) ",40,-2.,2.);
 TH2F *difytarVxptari = new TH2F("difytarVxptari",";Init xptar (rad);Ytar diff (cm)",25,-.05,.05,40,-2.,2.);
 TH2F *difytarVyptari = new TH2F("difytarVyptari",";Init yptar (rad);Ytar diff (cm)",30,-.03,.03,40,-2.,2.);
 TH2F *difytarVxfp = new TH2F("difytarVxfp",";xfp (cm);Ytar diff (cm)",100,-40.,40.,40,-2.,2.);
 TH2F *difytarVyfp = new TH2F("difytarVyfp",";yfp (cm);Ytar diff (cm)",100,-30.,30.,40,-2.,2.);
 TH2F *difytarVxpfp = new TH2F("difytarVxpfp",";xpfp (cm);Ytar diff (cm)",100,-.1,.1,40,-2.,2.);
 TH2F *difytarVypfp = new TH2F("difytarVypfp",";ypfp (cm);Ytar diff (cm)",100,-.05,.05,40,-2.,2.);
 TH2F *difytarVdeltai = new TH2F("difytarVdeltai",";Init delta ;Ytar diff (cm)",16,-.1,.22,40,-2.,2.);
 //
 TH1F *difdelta = new TH1F("difdelta",";Delta diff (%) ",40,-.1,.1);
 TH2F *difdeltaVxptari = new TH2F("difdeltaVxptari",";Init xptar (rad);Delta diff (%)",25,-.05,.05,40,-.1,.1);
 TH2F *difdeltaVyptari = new TH2F("difdeltaVyptari",";Init yptar (rad);Delta diff (%)",30,-.03,.03,40,-.1,.1);
 TH2F *difdeltaVxfp = new TH2F("difdeltaVxfp",";xfp (cm);Delta diff (%)",100,-40.,40.,40,-.1,.1);
 TH2F *difdeltaVyfp = new TH2F("difdeltaVyfp",";yfp (cm);Delta diff (%)",100,-30.,30.,40,-.1,.1);
 TH2F *difdeltaVxpfp = new TH2F("difdeltaVxpfp",";xpfp (cm);Delta diff (%)",100,-.1,.1,40,-.1,.1);
 TH2F *difdeltaVypfp = new TH2F("difdeltaVypfp",";ypfp (cm);Delta diff (%)",100,-.05,.05,40,-.1,.1);
 TH2F *difdeltaVdeltai = new TH2F("difdeltaVdeltai",";Init delta ;Delta diff (%)",16,-.1,.22,40,-.1,.1);
//
   Long64_t nentries = tsimc->GetEntries();
   for (int i = 0; i < nentries; i++) {
        tsimc->GetEntry(i);
	hxptari->Fill(hsxptari);
	hxptarf->Fill(hsxptar);
	difxptar->Fill(1000*(hsxptar-hsxptari));
	difxptarVxptari->Fill(hsxptari,1000*(hsxptar-hsxptari));
	difxptarVyptari->Fill(hsyptari,1000*(hsxptar-hsxptari));
	difxptarVxfp->Fill(hsxfp,1000*(hsxptar-hsxptari));
	difxptarVyfp->Fill(hsyfp,1000*(hsxptar-hsxptari));
	difxptarVxpfp->Fill(hsxpfp,1000*(hsxptar-hsxptari));
	difxptarVypfp->Fill(hsypfp,1000*(hsxptar-hsxptari));
	difxptarVdeltai->Fill(hsdeltai/100.,1000*(hsxptar-hsxptari));
	//
	difyptar->Fill(1000*(hsyptar-hsyptari));
	difyptarVxptari->Fill(hsxptari,1000*(hsyptar-hsyptari));
	difyptarVyptari->Fill(hsyptari,1000*(hsyptar-hsyptari));
	difyptarVxfp->Fill(hsxfp,1000*(hsyptar-hsyptari));
	difyptarVyfp->Fill(hsyfp,1000*(hsyptar-hsyptari));
	difyptarVxpfp->Fill(hsxpfp,1000*(hsyptar-hsyptari));
	difyptarVypfp->Fill(hsypfp,1000*(hsyptar-hsyptari));
	difyptarVdeltai->Fill(hsdeltai/100.,1000*(hsyptar-hsyptari));
	//
	difdelta->Fill((hsdelta-hsdeltai));
	difdeltaVxptari->Fill(hsxptari,(hsdelta-hsdeltai));
	difdeltaVyptari->Fill(hsyptari,(hsdelta-hsdeltai));
	difdeltaVxfp->Fill(hsxfp,(hsdelta-hsdeltai));
	difdeltaVyfp->Fill(hsyfp,(hsdelta-hsdeltai));
	difdeltaVxpfp->Fill(hsxpfp,(hsdelta-hsdeltai));
	difdeltaVypfp->Fill(hsypfp,(hsdelta-hsdeltai));
	difdeltaVdeltai->Fill(hsdeltai/100.,(hsdelta-hsdeltai));
	//
	difytar->Fill((hsytar-hsytari));
	difytarVxptari->Fill(hsxptari,(hsytar-hsytari));
	difytarVyptari->Fill(hsyptari,(hsytar-hsytari));
	difytarVxfp->Fill(hsxfp,(hsytar-hsytari));
	difytarVyfp->Fill(hsyfp,(hsytar-hsytari));
	difytarVxpfp->Fill(hsxpfp,(hsytar-hsytari));
	difytarVypfp->Fill(hsypfp,(hsytar-hsytari));
	difytarVdeltai->Fill(hsdeltai/100.,(hsytar-hsytari));
   }
   //
TCanvas *cxptar = new TCanvas("cxptar"," Compare Recon/Inital xptar 8 GeV, point target, no wire ch, no mscat",1400,1000);
cxptar->Divide(4,3);
cxptar->cd(4);
difxptar->Draw();
cxptar->cd(1);
difxptarVdeltai->Draw("colz");
cxptar->cd(5);
 difxptarVdeltai->FitSlicesY();
TH1D *difxptarVdeltai_2 = (TH1D*)gDirectory->Get("difxptarVdeltai_2");
 difxptarVdeltai_2->SetTitle(";Init Delta; Fitted Sigma of Xptar diff (mr)");
 difxptarVdeltai_2->Draw();
cxptar->cd(2);
difxptarVxptari->Draw("colz");
cxptar->cd(6);
 difxptarVxptari->FitSlicesY();
TH1D *difxptarVxptari_2 = (TH1D*)gDirectory->Get("difxptarVxptari_2");
 difxptarVxptari_2->SetTitle(";Init Xptar; Fitted Sigma of Xptar diff (mr)");
 difxptarVxptari_2->Draw();
cxptar->cd(3);
difxptarVyptari->Draw("colz");
cxptar->cd(7);
 difxptarVyptari->FitSlicesY();
TH1D *difxptarVyptari_2 = (TH1D*)gDirectory->Get("difxptarVyptari_2");
 difxptarVyptari_2->SetTitle(";Init Yptar; Fitted Sigma of Xptar diff (mr)");
 difxptarVyptari_2->Draw();
cxptar->cd(9);
difxptarVxfp->Draw("colz");
cxptar->cd(10);
difxptarVyfp->Draw("colz");
cxptar->cd(11);
difxptarVxpfp->Draw("colz");
cxptar->cd(12);
difxptarVypfp->Draw("colz");
//
 TCanvas *cyptar = new TCanvas("cyptar"," Compare Recon/Inital yptar 8 GeV, point target, no wire ch, no mscat",1400,1000);
cyptar->Divide(4,3);
cyptar->cd(4);
difyptar->Draw();
cyptar->cd(1);
difyptarVdeltai->Draw("colz");
cyptar->cd(5);
 difyptarVdeltai->FitSlicesY();
TH1D *difyptarVdeltai_2 = (TH1D*)gDirectory->Get("difyptarVdeltai_2");
 difyptarVdeltai_2->SetTitle(";Init Delta; Fitted Sigma of Yptar diff (mr)");
 difyptarVdeltai_2->Draw();
cyptar->cd(2);
difyptarVxptari->Draw("colz");
cyptar->cd(6);
 difyptarVxptari->FitSlicesY();
TH1D *difyptarVxptari_2 = (TH1D*)gDirectory->Get("difyptarVxptari_2");
 difyptarVxptari_2->SetTitle(";Init Xptar; Fitted Sigma of Yptar diff (mr)");
 difyptarVxptari_2->Draw();
cyptar->cd(3);
difyptarVyptari->Draw("colz");
cyptar->cd(7);
 difyptarVyptari->FitSlicesY();
TH1D *difyptarVyptari_2 = (TH1D*)gDirectory->Get("difyptarVyptari_2");
 difyptarVyptari_2->SetTitle(";Init Yptar; Fitted Sigma of Yptar diff (mr)");
 difyptarVyptari_2->Draw();
cyptar->cd(9);
difyptarVxfp->Draw("colz");
cyptar->cd(10);
difyptarVyfp->Draw("colz");
cyptar->cd(11);
difyptarVxpfp->Draw("colz");
cyptar->cd(12);
difyptarVypfp->Draw("colz");
//
 TCanvas *cdelta = new TCanvas("cdelta"," Compare Recon/Inital delta 8 GeV, point target, no wire ch, no mscat",1400,1000);
cdelta->Divide(4,3);
cdelta->cd(4);
difdelta->Draw();
cdelta->cd(1);
difdeltaVdeltai->Draw("colz");
cdelta->cd(5);
 difdeltaVdeltai->FitSlicesY();
TH1D *difdeltaVdeltai_2 = (TH1D*)gDirectory->Get("difdeltaVdeltai_2");
 difdeltaVdeltai_2->SetTitle(";Init Delta; Fitted Sigma of Delta diff (%)");
 difdeltaVdeltai_2->Draw();
cdelta->cd(2);
difdeltaVxptari->Draw("colz");
cdelta->cd(6);
 difdeltaVxptari->FitSlicesY();
TH1D *difdeltaVxptari_2 = (TH1D*)gDirectory->Get("difdeltaVxptari_2");
 difdeltaVxptari_2->SetTitle(";Init Xptar; Fitted Sigma of Delta diff (%)");
 difdeltaVxptari_2->Draw();
cdelta->cd(3);
difdeltaVyptari->Draw("colz");
cdelta->cd(7);
 difdeltaVyptari->FitSlicesY();
TH1D *difdeltaVyptari_2 = (TH1D*)gDirectory->Get("difdeltaVyptari_2");
 difdeltaVyptari_2->SetTitle(";Init Yptar; Fitted Sigma of Delta diff (%)");
 difdeltaVyptari_2->Draw();
cdelta->cd(9);
difdeltaVxfp->Draw("colz");
cdelta->cd(10);
difdeltaVyfp->Draw("colz");
cdelta->cd(11);
difdeltaVxpfp->Draw("colz");
cdelta->cd(12);
difdeltaVypfp->Draw("colz");
//
 TCanvas *cytar = new TCanvas("cytar"," Compare Recon/Inital ytar 8 GeV, point target, no wire ch, no mscat",1400,1000);
cytar->Divide(4,3);
cytar->cd(4);
difytar->Draw();
cytar->cd(1);
difytarVdeltai->Draw("colz");
cytar->cd(5);
 difytarVdeltai->FitSlicesY();
TH1D *difytarVdeltai_2 = (TH1D*)gDirectory->Get("difytarVdeltai_2");
 difytarVdeltai_2->SetTitle(";Init Delta; Fitted Sigma of Ytar diff (cm)");
 difytarVdeltai_2->Draw();
cytar->cd(2);
difytarVxptari->Draw("colz");
cytar->cd(6);
 difytarVxptari->FitSlicesY();
TH1D *difytarVxptari_2 = (TH1D*)gDirectory->Get("difytarVxptari_2");
 difytarVxptari_2->SetTitle(";Init Xptar; Fitted Sigma of Ytar diff (cm)");
 difytarVxptari_2->Draw();
cytar->cd(3);
difytarVyptari->Draw("colz");
cytar->cd(7);
 difytarVyptari->FitSlicesY();
TH1D *difytarVyptari_2 = (TH1D*)gDirectory->Get("difytarVyptari_2");
 difytarVyptari_2->SetTitle(";Init Yptar; Fitted Sigma of Ytar diff (cm)");
 difytarVyptari_2->Draw();
cytar->cd(9);
difytarVxfp->Draw("colz");
cytar->cd(10);
difytarVyfp->Draw("colz");
cytar->cd(11);
difytarVxpfp->Draw("colz");
cytar->cd(12);
difytarVypfp->Draw("colz");
}
Example #29
0
int main(int argc, char** argv) {
  RootWItemCollection myCollection;
  
  RootWTable* myTable = new RootWTable();
  RootWTable* myTable2 = new RootWTable();
  myCollection.addItem(myTable, "table1");
  myCollection.addItem(myTable2, "table2");
  
  for (int x=0; x<10; x++) {
    for(int y=0; y<10; y++) {
      if ((x+y)%3) {
        myTable->setContent(x, y, x);
        myTable2->addContent(x*100);
      } else {
        myTable2->addContent("");
      }
    }
    myTable2->newLine();
  }
  
  TH1F* pippo = new TH1F("pippo", "Test plot here...", 100, 0, 10);
  for (int i = 0; i < 1E4; i++ ) {
    pippo->Fill(int((i*i/3.241234235562433))%10);
  }
  TCanvas* myCanvas = new TCanvas();
  myCanvas->cd();
  pippo->Draw();
  // This is to test the binary file linking:
  RootWBinaryFile *myBinaryFile = new RootWBinaryFile("testFile.png", "A test binary file", "/tmp/testme.png");
  myCanvas->SaveAs("/tmp/testme.png");
  myCollection.addItem(myBinaryFile, "Abinaryfile");

  RootWImage* myPlot = new RootWImage(myCanvas, 1024, 600);
  myPlot->setComment("This is the best plot ever seen...");
  //myPlot->saveFiles(200, 200);

  RootWContent* myContent = new RootWContent("Look at this");
  RootWContent* myContent2 = new RootWContent("Pictures here");
  stringstream testOutput;
  testOutput << "Hello, Europe!" << endl;
  testOutput << "How are you doing?" << endl;

  RootWTextFile* myTextFile = new RootWTextFile("test.txt");
  myTextFile->setDescription("Just another test obect (a file)");
  myTextFile->addText(testOutput);
  

  myContent->addParagraph("Hello, world!");
  myContent->addItem(myTextFile);
  myContent->addParagraph("Can you read this?");
  
  vector<RootWItem*> itemV = myCollection.getOtherItems();
  for (vector<RootWItem*>::iterator it = itemV.begin(); it!=itemV.end(); ++it) {
    myContent->addItem(*it);
  }
  myContent2->addItem(myPlot);
  myContent2->addItem(myPlot);

  RootWSite* mySite = new RootWSite();
  mySite->setTitle("Title of the page");
  mySite->setComment("run summary");
  mySite->setCommentLink("../");
  mySite->addAuthor("Stefano Mersi");
  mySite->addAuthor("Xin Shi");
#ifdef REVISIONNUMBER
  mySite->setRevision(REVISIONNUMBER);
#endif
    

  RootWPage* myPage = new RootWPage("First");
  myPage->setAddress("index.html");
  myPage->addContent(myContent2);
  myPage->addContent(myContent);
 
  RootWPage* myPage2 = new RootWPage("SeconD");
  myPage2->setAddress("two.html");
  myPage2->addContent(myContent2);

  mySite->addPage(myPage);
  mySite->addPage(myPage2);

  RootWPage& myPage3 = mySite->addPage("Ice cream");
  myPage3.addContent("cream");
  RootWContent& aCont3 = myPage3.addContent("fruit",false);
  aCont3.addItem(myPlot);
  RootWImage& aaa = aCont3.addImage(myCanvas, 300,300);
  aaa.setComment("This is the best picture ever");

  // if you want to use the environment variables: 
  std::string targetDirectory = string(getenv(TARGETDIRECTORY));
  if (targetDirectory=="") {
    cerr << "Warning: cannot find the definition of target directory "
         << "by the environment variable " << TARGETDIRECTORY << endl
         << "Using current directory as target directory" << endl;
    targetDirectory=".";
  }
 
  if (!boost::filesystem::exists( targetDirectory )) {
    if (!boost::filesystem::create_directory(targetDirectory)) {
      cerr << "Couldn't create directory " << targetDirectory << endl;
      return 0;
    }
  }
  
  targetDirectory+="/0000test"; 
  mySite->setTargetDirectory(targetDirectory);
  mySite->makeSite(false);

  return 0;
}
Example #30
0
void isis_looper::myLoop(int nsel, int mode, bool silent)
{

  char plotName[300];
  sprintf(plotName,"test");
  
  if (nsel == 0)                	{sprintf(plotName,"tt");}
  else if (nsel == 1)   		{sprintf(plotName,"twdr");}
  else if (nsel == -1)   		{sprintf(plotName,"twds");}
  else if (nsel == 2)   		{sprintf(plotName,"zjets");}
  else if (nsel == 3)   		{sprintf(plotName,"di");}
  else if (nsel == 4)			{sprintf(plotName, "st");}
  else if (nsel == 5)   		{sprintf(plotName,"wjets");}
  else if (nsel == 6)   		{sprintf(plotName,"qcd_mu");}
  else if (nsel == 7)                	{sprintf(plotName,"others");}
  
  else if (nsel == 555)                	{sprintf(plotName,"mc");}
  
  else if (nsel == 666)                	{sprintf(plotName,"data");}
    
  else if (nsel == -10)                   {sprintf(plotName,"tt");}
  else if (nsel ==  10)                   {sprintf(plotName,"tt");}
  
  bool nosf = false;
  
  
  char newRootFile[300];
  double lumi = luminosity; 
  if (mode == 0 )        lumi = 4399; 
  else if ( mode == 1)   lumi = 1000; // to check 
  else if ( mode == 2)   lumi = 5103.58; // to check 
  sprintf(newRootFile,"results/an_%dpb_%d.root", (int)lumi, mode);
  
   if(nsel == -10){
  sprintf(newRootFile,"results/JERsysDown_an_%dpb_%d.root", (int)lumi, mode);
  }else if(nsel == 10 ){
   sprintf(newRootFile,"results/JERsysUp_an_%dpb_%d.root", (int)lumi, mode);
  }
 
  TFile f_var(newRootFile, "UPDATE");
  
  if(!silent){
    std::cout << "[Info:] results root file " << newRootFile << std::endl;
  }
  
  
  //////////
  char title[300];
  sprintf(title,"cuts_%s",plotName);
  TH1F* histo = new TH1F( title, " ", 10,  0, 10 );
  histo->Sumw2();
  
  sprintf(title,"met_high_%s",plotName);
  TH1F* histo_met_high = new TH1F( title, " ", 100,  0, 200 );
  histo_met_high->Sumw2();
  
  sprintf(title,"met_low_%s",plotName);
  TH1F* histo_met_low = new TH1F( title, " ", 100,  0, 200 );
  histo_met_low->Sumw2();
  
  sprintf(title,"promet_%s",plotName);
  TH1F* histo_promet = new TH1F( title, " ", 100,  0, 200 );
  histo_promet->Sumw2();
  
  sprintf(title,"met_cut_%s",plotName);
  TH1F* histo_met_cut = new TH1F( title, " ", 100,  0, 200 );
  histo_met_cut->Sumw2();
  
  sprintf(title,"met_bt_%s",plotName);
  TH1F* histo_met_bt = new TH1F( title, " ", 100,  0, 200 );
  histo_met_bt->Sumw2();
  
  sprintf(title,"mll_after_%s",plotName);
  TH1F* histo_mll_after = new TH1F( title, " ", 100,  0, 200 );
  histo_mll_after->Sumw2();
  
  sprintf(title,"njets_cut_%s",plotName);
  TH1F* histo_njets_cut = new TH1F( title, " ", 10,  -0.5, 9.5 );
  histo_njets_cut->Sumw2();
  
  sprintf(title,"njetsbt_cut_%s",plotName);
  TH1F* histo_njetsbt_cut = new TH1F( title, " ", 10,   -0.5, 9.5 );
  histo_njetsbt_cut->Sumw2();
  
  sprintf(title,"njetsbt_high_%s",plotName);
  TH1F* histo_njetsbt_high = new TH1F( title, " ", 10,   -0.5, 9.5 );
  histo_njetsbt_high->Sumw2();
  
  sprintf(title,"njetsbt_low_%s",plotName);
  TH1F* histo_njetsbt_low = new TH1F( title, " ", 10,   -0.5, 9.5 );
  histo_njetsbt_low->Sumw2();
  
  sprintf(title,"njets_high_%s",plotName);
  TH1F* histo_njets_high = new TH1F( title, " ", 10,   -0.5, 9.5 );
  histo_njets_high->Sumw2();
  
  sprintf(title,"njets_low_%s",plotName);
  TH1F* histo_njets_low = new TH1F( title, " ", 10,   -0.5, 9.5 );
  histo_njets_low->Sumw2();
  
  sprintf(title,"ptsys_high_%s",plotName);
  TH1F* histo_ptsys_high = new TH1F( title, " ", 100,  0, 200 );
  histo_ptsys_high->Sumw2();
  
  sprintf(title,"ptsys_low_%s",plotName);
  TH1F* histo_ptsys_low = new TH1F( title, " ", 100,  0, 200 );
  histo_ptsys_low->Sumw2();
  
  sprintf(title,"ht_high_%s",plotName);
  TH1F* histo_ht_high = new TH1F( title, " ", 300,  0, 600 );
  histo_ht_high->Sumw2();
  
  sprintf(title,"ht_low_%s",plotName);
  TH1F* histo_ht_low = new TH1F( title, " ", 300,  0, 600 );
  histo_ht_low->Sumw2();
  
  sprintf(title,"ht_cut_%s",plotName);
  TH1F* histo_ht_cut = new TH1F( title, " ", 300,  0, 600 );
  histo_ht_cut->Sumw2();
  
  sprintf(title,"pt_max_%s",plotName);
  TH1F* histo_pt_max = new TH1F( title, " ", 100,  0, 200 );
  histo_pt_max->Sumw2();
  
  sprintf(title,"pt_min_%s",plotName);
  TH1F* histo_pt_min = new TH1F( title, " ", 100,  0, 200 );
  histo_pt_min->Sumw2();
  
  sprintf(title,"btagHE_%s",plotName);
  TH2F* histo_btagHE = new TH2F( title, " ", 300,  -200, 100, 100, -2, 7);
  histo_btagHE->Sumw2();
  
  sprintf(title,"btagHP_%s",plotName);
  TH2F* histo_btagHP = new TH2F( title, " ", 300,  -200, 100, 100, -2, 7);
  histo_btagHP->Sumw2();
  
  sprintf(title,"etalepton_%s",plotName);
  TH1F* histo_etalepton = new TH1F( title, " ", 101,  -3, 3);
  histo_etalepton->Sumw2();
  
  sprintf(title,"ht_bf_%s",plotName);
  TH1F* histo_ht_bf = new TH1F( title, " ", 300,  0, 600 );
  histo_ht_bf->Sumw2();
  
  sprintf(title,"ptsys_bf_%s",plotName);
  TH1F* histo_ptsys_bf = new TH1F( title, " ", 100,  0, 200 );
  histo_ptsys_bf->Sumw2();
  
  sprintf(title,"npu_%s",plotName);
  TH1F* histo_npu = new TH1F( title, " ", 30,   -0.5, 29.5 );
  histo_npu->Sumw2();
  
  
  /// Classic plotmaker plots
  sprintf(title,"met_%s",plotName);
  TH1F* histo_met = new TH1F( title, " ", 100,  0, 200 );
  histo_met->Sumw2();
  
  sprintf(title,"mll_%s",plotName);
  TH1F* histo_mll = new TH1F( title, " ", 100,  0, 200 );
  histo_mll->Sumw2();
  
  sprintf(title,"njets_%s",plotName);
  TH1F* histo_njets = new TH1F( title, " ", 10,  0, 10 );
  histo_njets->Sumw2();
  
  sprintf(title,"njetsbt_%s",plotName);
  TH1F* histo_njetsbt = new TH1F( title, " ", 10,  -0.5, 9.5 );
  histo_njetsbt->Sumw2();
  
  sprintf(title,"ptsys_%s",plotName);
  TH1F* histo_ptsys = new TH1F( title, " ", 100,  0, 200 );
  histo_ptsys->Sumw2();
  
  sprintf(title,"ht_%s",plotName);
  TH1F* histo_ht = new TH1F( title, " ", 300,  0, 600 );
  histo_ht->Sumw2();
  
  sprintf(title,"pt_leading_%s",plotName);
  TH1F* histo_pt_leading = new TH1F( title, " ", 100,  0, 200 );
  histo_pt_leading->Sumw2();
  
  
  sprintf(title,"eta_leading_%s",plotName);
  TH1F* histo_eta_leading = new TH1F( title, " ", 101,  -3, 3);
  histo_eta_leading->Sumw2();
  
  sprintf(title,"nvertex_%s",plotName);
  TH1F* histo_nvertex = new TH1F( title, " ", 70,   -0.5, 69.5 );
  histo_nvertex->Sumw2();
 
  
  // 1 jet level
  /// Classic plotmaker plots
  sprintf(title,"met_1j_%s",plotName);
  TH1F* histo_met_1j = new TH1F( title, " ", 100,  0, 200 );
  histo_met_1j->Sumw2();
  
  sprintf(title,"mll_1j_%s",plotName);
  TH1F* histo_mll_1j = new TH1F( title, " ", 100,  0, 200 );
  histo_mll_1j->Sumw2();
  
  sprintf(title,"ptsys_1j_%s",plotName);
  TH1F* histo_ptsys_1j = new TH1F( title, " ", 100,  0, 200 );
  histo_ptsys_1j->Sumw2();
  
  sprintf(title,"ht_1j_%s",plotName);
  TH1F* histo_ht_1j = new TH1F( title, " ", 300,  0, 600 );
  histo_ht_1j->Sumw2();
  
  sprintf(title,"pt_leading_1j_%s",plotName);
  TH1F* histo_pt_leading_1j = new TH1F( title, " ", 100,  0, 200 );
  histo_pt_leading_1j->Sumw2();
  
  sprintf(title,"nvertex_1j_%s",plotName);
  TH1F* histo_nvertex_1j = new TH1F( title, " ", 30,   -0.5, 29.5 );
  histo_nvertex_1j->Sumw2();
  
  // 1 jet level
  /// Classic plotmaker plots
  sprintf(title,"met_1j1t_%s",plotName);
  TH1F* histo_met_1j1t = new TH1F( title, " ", 100,  0, 200 );
  histo_met_1j1t->Sumw2();
  
  sprintf(title,"mll_1j1t_%s",plotName);
  TH1F* histo_mll_1j1t = new TH1F( title, " ", 100,  0, 200 );
  histo_mll_1j1t->Sumw2();
  
  sprintf(title,"ptsys_1j1t_%s",plotName);
  TH1F* histo_ptsys_1j1t = new TH1F( title, " ", 100,  0, 200 );
  histo_ptsys_1j1t->Sumw2();
  
  sprintf(title,"ht_1j1t_%s",plotName);
  TH1F* histo_ht_1j1t = new TH1F( title, " ", 300,  0, 600 );
  histo_ht_1j1t->Sumw2();
  
  sprintf(title,"pt_leading_1j1t_%s",plotName);
  TH1F* histo_pt_leading_1j1t = new TH1F( title, " ", 100,  0, 200 );
  histo_pt_leading_1j1t->Sumw2();
  
  sprintf(title,"nvertex_1j1t_%s",plotName);
  TH1F* histo_nvertex_1j1t = new TH1F( title, " ", 30,   -0.5, 29.5 );
  histo_nvertex_1j1t->Sumw2();
  
  
  // 2j1t
  /// Classic plotmaker plots
  sprintf(title,"met_2j1t_%s",plotName);
  TH1F* histo_met_2j1t = new TH1F( title, " ", 100,  0, 200 );
  histo_met_2j1t->Sumw2();
  
  sprintf(title,"mll_2j1t_%s",plotName);
  TH1F* histo_mll_2j1t = new TH1F( title, " ", 100,  0, 200 );
  histo_mll_2j1t->Sumw2();
  
  sprintf(title,"ptsys_2j1t_%s",plotName);
  TH1F* histo_ptsys_2j1t = new TH1F( title, " ", 100,  0, 200 );
  histo_ptsys_2j1t->Sumw2();
  
  sprintf(title,"ht_2j1t_%s",plotName);
  TH1F* histo_ht_2j1t = new TH1F( title, " ", 300,  0, 600 );
  histo_ht_2j1t->Sumw2();
  
  sprintf(title,"pt_leading_2j1t_%s",plotName);
  TH1F* histo_pt_leading_2j1t = new TH1F( title, " ", 100,  0, 200 );
  histo_pt_leading_2j1t->Sumw2();
  
  sprintf(title,"nvertex_2j1t_%s",plotName);
  TH1F* histo_nvertex_2j1t = new TH1F( title, " ", 30,   -0.5, 29.5 );
  histo_nvertex_2j1t->Sumw2();
  
  
  // 2j2t
  /// Classic plotmaker plots
  sprintf(title,"met_2j2t_%s",plotName);
  TH1F* histo_met_2j2t = new TH1F( title, " ", 100,  0, 200 );
  histo_met_2j2t->Sumw2();
  
  sprintf(title,"mll_2j2t_%s",plotName);
  TH1F* histo_mll_2j2t = new TH1F( title, " ", 100,  0, 200 );
  histo_mll_2j2t->Sumw2();
  
  sprintf(title,"ptsys_2j2t_%s",plotName);
  TH1F* histo_ptsys_2j2t = new TH1F( title, " ", 100,  0, 200 );
  histo_ptsys_2j2t->Sumw2();
  
  sprintf(title,"ht_2j2t_%s",plotName);
  TH1F* histo_ht_2j2t = new TH1F( title, " ", 300,  0, 600 );
  histo_ht_2j2t->Sumw2();
  
  sprintf(title,"pt_leading_2j2t_%s",plotName);
  TH1F* histo_pt_leading_2j2t = new TH1F( title, " ", 100,  0, 200 );
  histo_pt_leading_2j2t->Sumw2();
  
  sprintf(title,"nvertex_2j2t_%s",plotName);
  TH1F* histo_nvertex_2j2t = new TH1F( title, " ", 30,   -0.5, 29.5 );
  histo_nvertex_2j2t->Sumw2();

  
  // all regions
  sprintf(title,"R_%s",plotName);
  TH1F* histo_R = new TH1F( title, " ", 40,  0, 40 );
  histo_R->Sumw2();
  
  
  // checking pu reweighting
  sprintf(title,"nvertex_final_%s",plotName);
  TH1F* histo_nvertex_final = new TH1F( title, " ", 70,   -0.5, 69.5 );
  histo_nvertex_final->Sumw2();
  
  sprintf(title,"nvertex_final_3D_%s",plotName);
  TH1F* histo_nvertex_final_3D = new TH1F( title, " ", 70,   -0.5, 69.5 );
  histo_nvertex_final_3D->Sumw2();
  
  sprintf(title,"nvertex_final_purw_%s",plotName);
  TH1F* histo_nvertex_final_purw = new TH1F( title, " ", 70,   -0.5, 69.5 );
  histo_nvertex_final_purw->Sumw2();
  


  sprintf(title,"nvertex_2lep_%s",plotName);
  TH1F* histo_nvertex_2lep = new TH1F( title, " ", 70,   -0.5, 69.5 );
  histo_nvertex_2lep->Sumw2();
//<<<<<<< isis_looper.C
  
  //_________________________________________________________________________________
  //added by Isis
  
  // -- Leading jet --- 
    sprintf(title,"eta_jet_%s",plotName);
  TH1F* histo_eta_jet = new TH1F( title, " ", 50,-5, 5 );  //#bins - begin - end
  histo_eta_jet->Sumw2();
  
 
     sprintf(title,"eta_jet_110_%s",plotName);
  TH1F* histo_eta_jet_110 = new TH1F( title, " ", 50,-5, 5 );  //#bins - begin - end
  histo_eta_jet_110->Sumw2();
  
      sprintf(title,"eta_jet_90_%s",plotName);
  TH1F* histo_eta_jet_90 = new TH1F( title, " ", 50,-5, 5 );  //#bins - begin - end
  histo_eta_jet_90->Sumw2();
  
  
      sprintf(title,"eta_jet_70_%s",plotName);
  TH1F* histo_eta_jet_70 = new TH1F( title, " ", 50,-5, 5 );  //#bins - begin - end
  histo_eta_jet_70->Sumw2();
  
  
      sprintf(title,"eta_jet_50_%s",plotName);
  TH1F* histo_eta_jet_50 = new TH1F( title, " ", 50,-5, 5 );  //#bins - begin - end
  histo_eta_jet_50->Sumw2();
  
      sprintf(title,"eta_jet_30_%s",plotName);
  TH1F* histo_eta_jet_30 = new TH1F( title, " ", 50,-5, 5 );  //#bins - begin - end
  histo_eta_jet_30->Sumw2();
 
 
   // -- Second Leading jet --- 
    sprintf(title,"eta_jet1_%s",plotName);
  TH1F* histo_eta_jet1 = new TH1F( title, " ", 50,-5, 5 );  //#bins - begin - end
  histo_eta_jet1->Sumw2();
  
 
     sprintf(title,"eta_jet1_110_%s",plotName);
  TH1F* histo_eta_jet1_110 = new TH1F( title, " ", 50,-5, 5 );  //#bins - begin - end
  histo_eta_jet1_110->Sumw2();
  
      sprintf(title,"eta_jet1_90_%s",plotName);
  TH1F* histo_eta_jet1_90 = new TH1F( title, " ", 50,-5, 5 );  //#bins - begin - end
  histo_eta_jet1_90->Sumw2();
  
  
      sprintf(title,"eta_jet1_70_%s",plotName);
  TH1F* histo_eta_jet1_70 = new TH1F( title, " ", 50,-5, 5 );  //#bins - begin - end
  histo_eta_jet1_70->Sumw2();
  
  
      sprintf(title,"eta_jet1_50_%s",plotName);
  TH1F* histo_eta_jet1_50 = new TH1F( title, " ", 50,-5, 5 );  //#bins - begin - end
  histo_eta_jet1_50->Sumw2();
  
      sprintf(title,"eta_jet1_30_%s",plotName);
  TH1F* histo_eta_jet1_30 = new TH1F( title, " ", 50,-5, 5 );  //#bins - begin - end
  histo_eta_jet1_30->Sumw2();
  
  // ---- Z/gamma controlregion 
 
    sprintf(title,"mll_zgamma_%s",plotName);
  TH1F* histo_mll_zgamma = new TH1F( title, " ", 50,  0, 200 );
  histo_mll_zgamma->Sumw2();
  
  
    sprintf(title,"met_zgamma_%s",plotName);
  TH1F* histo_met_zgamma= new TH1F( title, " ", 50,  0, 200 );
  histo_met_zgamma->Sumw2();
  
//=======
//>>>>>>> 1.1.2.3



  

//__________________________________________________ END HISTO DEF _________________________________________________________


  if (fChain == 0) return;
  
  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 (lumi != lum && nsel != 666 && mode !=3){
      if (jentry == 0)std::cout << "[Warning:] This tree was made with a different luminosity (" << lum << ") than " << lumi << std::endl;
      //xlWeight*=(lumi/lum);
    }
    
  //  if(puweight > 5){ continue ;}
    
    if(ptLepton->size() != 2){
      std::cout << "[Warning:] Something is wrong, your Tree is not correctly filled" << std::endl;
      break;
    } else {
      histo->Fill(0.,xlWeight);
      histo_nvertex_2lep->Fill(nvertex,xlWeight);
      TLorentzVector lepton0(pxLepton->at(0),pyLepton->at(0), pzLepton->at(0), eLepton->at(0));
      TLorentzVector lepton1(pxLepton->at(1),pyLepton->at(1), pzLepton->at(1), eLepton->at(1)); 
      TLorentzVector pair = lepton0+lepton1;
      
      double phipairmet_t = 0;
      double pi_m = 3.1416/2;
      phipairmet_t = pi_m;
      
      TVector3 vmet(metPx, metPy, 0);
      
      double promet = metPt*sin(phipairmet_t);
      TVector3 m0(pxLepton->at(0),pyLepton->at(0), pzLepton->at(0));
      TVector3 m1(pxLepton->at(1),pyLepton->at(1), pzLepton->at(1)); 
      if (fabs(m0.DeltaPhi(vmet)) < phipairmet_t) phipairmet_t = fabs(m0.DeltaPhi(vmet));
      if (fabs(m1.DeltaPhi(vmet)) < phipairmet_t) phipairmet_t = fabs(m1.DeltaPhi(vmet));
      
      if (phipairmet_t == pi_m) promet = metPt;
      
      if (pair.M() > 20){
	histo->Fill(1, xlWeight);

	double SFval, SFerror;
	if ( nsel == 666 || nosf){
	  SFval = 1;
	  SFerror = 0;
	} else if (nsel == 0){
	  SFval = 0.95;
	  SFerror = 0.03;
	} else {
	  SFval = 0.97;
	  SFerror = 0.03;
	}
	
	
	int nJetsBT = 0;
	int nTightJetsBT = 0;
	int nJets = 0;
	bool bTagged = false;
	int iJetn[5]={-1, -1,-1,-1,-1};
	int iJet = -5;
	int iSF;
	double tempSF = SFval;
	
	int SFvalue = int(tempSF*100);
	
	for (unsigned int i =0; i < ptJet->size(); i ++){ 
	  TLorentzVector tempJet(pxJet->at(i),pyJet->at(i), pzJet->at(i), eJet->at(i));
	  if (ptJet->at(i) > 30 && TMath::Min(fabs(lepton0.DeltaR(tempJet)), fabs(lepton1.DeltaR(tempJet))) > 0.3) {
	    
	    iJetn[nJets] = i;
	    iJet = i;
	    nJets++;
	    
	    
	    if (btCSVBJet->at(i) > 0.679){
	      iSF = rand() % 100;
	      if (iSF < SFvalue ){
		bTagged = true;
		nJetsBT++;
		nTightJetsBT++;
	      } 
	    } 
	  } else if (btCSVBJet->at(i) > 0.679){
	    iSF = rand() % 100;
	    if (iSF < SFvalue ) nJetsBT++;
	  }  
	  
	}
	
	
        if(nJets){
	 TLorentzVector jet(pxJet->at(iJetn[0]),pyJet->at(iJetn[0]), pzJet->at(iJetn[0]), eJet->at(iJetn[0]));
	// TLorentzVector jet1(pxJet->at(iJetn[1]),pyJet->at(iJetn[1]), pzJet->at(iJetn[1]), eJet->at(iJetn[1])); //2e jet erbij nemen
	 histo_eta_jet->Fill(jet.Eta(),xlWeight);      
	 //histo_eta_jet1->Fill(jet1.Eta(),xlWeight);    // 2e jet in dezelfde plot steken , misschien beter om aparte plot te maken? 
	 
	 if( ptJet->at(iJet) > 110 ){
	   histo_eta_jet_110->Fill(jet.Eta(),xlWeight); 
	  // histo_eta_jet1_110->Fill(jet1.Eta(),xlWeight); 
	}
	 if (ptJet->at(iJet) > 90){
	   histo_eta_jet_90->Fill(jet.Eta(),xlWeight);
	 //  histo_eta_jet1_90->Fill(jet1.Eta(),xlWeight);  
	 }
	 if (ptJet->at(iJet) > 70){
	   histo_eta_jet_70->Fill(jet.Eta(),xlWeight);
	 //  histo_eta_jet1_70->Fill(jet1.Eta(),xlWeight);  
	 }
	 if(ptJet->at(iJet) > 50){
	  histo_eta_jet_50->Fill(jet.Eta(),xlWeight); 
	 // histo_eta_jet1_50->Fill(jet1.Eta(),xlWeight); 
	 }
	 if (ptJet->at(iJet) > 30){
	  histo_eta_jet_30->Fill(jet.Eta(),xlWeight);
	 // histo_eta_jet1_30->Fill(jet1.Eta(),xlWeight); 
	 }
	 
	
	}
	

	histo_pt_max->Fill(TMath::Max(lepton0.Pt(), lepton1.Pt()), xlWeight);
	histo_pt_min->Fill(TMath::Min(lepton0.Pt(), lepton1.Pt()), xlWeight);
	histo_njets->Fill(nJets,  xlWeight);
	histo_njetsbt->Fill(nJetsBT,  xlWeight);
	histo_mll->Fill(pair.M(),  xlWeight);
	histo_met->Fill(metPt,  xlWeight);
	histo_promet->Fill(promet, xlWeight);
	

	if (nvertex > 5){
	  histo_met_high->Fill(metPt,  xlWeight);
	  histo_njets_high->Fill(nJets,  xlWeight);
	  histo_njetsbt_high->Fill(nJetsBT,  xlWeight);
	} else {
	  histo_met_low->Fill(metPt,  xlWeight);
	  histo_njets_low->Fill(nJets,  xlWeight);
	  histo_njetsbt_low->Fill(nJetsBT,  xlWeight);  
	}
	
	if (nJets) histo_pt_leading->Fill(ptJet->at(0), xlWeight);
	
	if (nJets){
	  TLorentzVector jet_aux(pxJet->at(0),pyJet->at(0), pzJet->at(0), eJet->at(0));
	  histo_eta_leading->Fill(jet_aux.Eta(), xlWeight);
	}
	
	if (nJets == 1){
	  histo_etalepton->Fill(lepton0.Eta(), xlWeight);
	  TLorentzVector jet(pxJet->at(iJet),pyJet->at(iJet), pzJet->at(iJet), eJet->at(iJet));
	   
	  double ptSysPx1 = lepton0.Px() + lepton1.Px() + jet.Px() + metPx;
	  double ptSysPy1 = lepton0.Py() + lepton1.Py() + jet.Py() + metPy;
	  double ptSystem1 = sqrt(ptSysPx1*ptSysPx1 + ptSysPy1*ptSysPy1);
	  double ht1 = lepton0.Pt() + lepton1.Pt() + jet.Pt() + metPt; 
	  histo_ptsys_bf->Fill(ptSystem1, xlWeight);
	  histo_ht_bf->Fill(ht1, xlWeight);
	}
	bool invMass = false;
	if      (mode == 0) invMass = true;
	else if (mode == 1  && (pair.M() > invMax || pair.M() < invMin)) invMass = true;
	else if (mode == 2 && (pair.M() > invMax || pair.M() < invMin)) invMass = true;
	
	//____________________________
        //Z/gamma control region
        
	//if (pair.M() > 81 || pair.M() < 101)
	if(!invMass || (mode == 0 && (pair.M() > 81 || pair.M() < 101) )) 
	{	  
	         
		  histo_mll_zgamma->Fill(pair.M(),  xlWeight);
	          histo_met_zgamma->Fill(metPt,  xlWeight);
	          
	}	 

	//______________________________________


	if (invMass){
	  histo->Fill(2, xlWeight);
	  histo_mll_after->Fill(pair.M(),  xlWeight);
	  histo_met_cut->Fill(metPt,  xlWeight);
	  if (metPt >= metCut || mode ==0){
	   
	    histo->Fill(3, xlWeight);
	    histo_njets_cut->Fill(nJets, xlWeight);
	    if (nJets == 1){
	      histo->Fill(4, xlWeight);
	      histo_njetsbt_cut->Fill(nJetsBT, xlWeight);
	      TLorentzVector jet(pxJet->at(iJet),pyJet->at(iJet), pzJet->at(iJet), eJet->at(iJet));
		
	      double ptSysPx = lepton0.Px() + lepton1.Px() + jet.Px() + metPx;
	      double ptSysPy = lepton0.Py() + lepton1.Py() + jet.Py() + metPy;
	      double ptSystem = sqrt(ptSysPx*ptSysPx + ptSysPy*ptSysPy);
	      double ht = lepton0.Pt() + lepton1.Pt() + jet.Pt() + metPt; 
	      
	      histo_mll_1j->Fill(pair.M(),  xlWeight);
	      histo_met_1j->Fill(metPt,  xlWeight);
	      histo_ptsys_1j->Fill(ptSystem, xlWeight);
	      histo_ht_1j->Fill(ht, xlWeight);
	      histo_pt_leading_1j->Fill(jet.Pt(), xlWeight);
	      
	      
	      if (nJets == 1 && nTightJetsBT == 1 && bTagged && nJetsBT == 1){
		histo->Fill(5, xlWeight);
		
	      
	        histo_mll_1j1t->Fill(pair.M(),  xlWeight);
	        histo_met_1j1t->Fill(metPt,  xlWeight);
	        histo_ptsys_1j1t->Fill(ptSystem, xlWeight);
	        histo_ht_1j1t->Fill(ht, xlWeight);
	        histo_pt_leading_1j1t->Fill(jet.Pt(), xlWeight);
	      
		histo_ptsys->Fill(ptSystem, xlWeight);
		histo_ht->Fill(ht, xlWeight);
		
		histo_met_bt->Fill(metPt, xlWeight);
		
		histo_nvertex->Fill(nvertex, xlWeight);
		histo_npu->Fill(npu, xlWeight);
		
		if (nvertex > 5) {
		  histo_ptsys_high->Fill(ptSystem, xlWeight);
		  histo_ht_high->Fill(ht, xlWeight);
		} else {
		  histo_ptsys_low->Fill(ptSystem, xlWeight);
		  histo_ht_low->Fill(ht, xlWeight);
		  
		}
		
		if (ht > htMin || mode !=0){
		  histo->Fill(6, xlWeight);
		  histo_ht_cut->Fill(ht, xlWeight);
		  
		  //Example to access the pu reweighting!
		  histo_nvertex_final->Fill(nvertex, rawWeight);
		  histo_nvertex_final_3D->Fill(nvertex, rawWeight*puweight3D);
		  histo_nvertex_final_purw->Fill(nvertex, rawWeight*puweight);
		  
		}
	      }
	    }
	  }
	  
	  
	  //Filling of all region from here
	  if (metPt >= metCut || mode ==0){
	
	    if (nJets != 0){
	      
	      TLorentzVector jet(pxJet->at(iJet),pyJet->at(iJet), pzJet->at(iJet), eJet->at(iJet));
	      
	      double ptSysPx = lepton0.Px() + lepton1.Px() + jet.Px() + metPx;
	      double ptSysPy = lepton0.Py() + lepton1.Py() + jet.Py() + metPy;
	      double ptSystem = sqrt(ptSysPx*ptSysPx + ptSysPy*ptSysPy);
	      double ht = lepton0.Pt() + lepton1.Pt() + jet.Pt() + metPt; 
	      
	      if (nJets == 2 && nTightJetsBT == 1 && nJetsBT == 1) {
	        histo_mll_2j1t->Fill(pair.M(),  xlWeight);
	        histo_met_2j1t->Fill(metPt,  xlWeight);
	        histo_ptsys_2j1t->Fill(ptSystem, xlWeight);
	        histo_ht_2j1t->Fill(ht, xlWeight);
	        histo_pt_leading_2j1t->Fill(jet.Pt(), xlWeight);
	      } else if (nJets == 2 && nTightJetsBT == 2 && nJetsBT == 2)  {
	        histo_mll_2j2t->Fill(pair.M(),  xlWeight);
	        histo_met_2j2t->Fill(metPt,  xlWeight);
	        histo_ptsys_2j2t->Fill(ptSystem, xlWeight);
	        histo_ht_2j2t->Fill(ht, xlWeight);
	        histo_pt_leading_2j2t->Fill(jet.Pt(), xlWeight);
	      }
	      
	      
	   
		  
	      //All possible regions
	      if (nJets == 1 && nTightJetsBT == 1 && bTagged && nJetsBT == 1 && ptSystem <= ptsysCut && (ht > htMin || mode !=0))histo_R->Fill(1, xlWeight); //signal
	      if (nJets == 1 && nTightJetsBT == 2)  histo_R->Fill(2, xlWeight);
	      if (nJets == 1 && nTightJetsBT > 0)  histo_R->Fill(3, xlWeight);
	      if (nJets == 1 && nTightJetsBT > 1)  histo_R->Fill(4, xlWeight);
	      if (nJets == 2 && nTightJetsBT == 0)  histo_R->Fill(5, xlWeight);
	      if (nJets == 2 && nTightJetsBT == 1)  histo_R->Fill(6, xlWeight); //CR1 no ht no ptsys
	      if (nJets == 2 && nTightJetsBT == 2)  histo_R->Fill(7, xlWeight); //CR2 no ht no ptsys
	      if (nJets == 2 && nTightJetsBT > 0)  histo_R->Fill(8, xlWeight);
	      if (nJets == 2 && nTightJetsBT > 1)  histo_R->Fill(9, xlWeight);
	      if (nJets > 1 && nTightJetsBT == 0)  histo_R->Fill(10, xlWeight);
	      if (nJets > 1 && nTightJetsBT == 1)  histo_R->Fill(11, xlWeight);
	      if (nJets > 1 && nTightJetsBT == 2)  histo_R->Fill(12, xlWeight);
	      if (nJets > 1 && nTightJetsBT !=0 )  histo_R->Fill(13, xlWeight);
	      if (nJets > 1 && nTightJetsBT > 1 )  histo_R->Fill(14, xlWeight);
	      if (nJets == 3 && nTightJetsBT ==3 )  histo_R->Fill(15, xlWeight);
	      if (nJets == 1 && nTightJetsBT ==1 && bTagged && nJetsBT == 1)  histo_R->Fill(16, xlWeight);
	      if (nJets == 2 && nTightJetsBT == 1 && ptSystem <= ptsysCut && (ht > htMin || mode !=0))  histo_R->Fill(17, xlWeight); //CR 1 regular
	      if (nJets == 2 && nTightJetsBT == 2 && ptSystem <= ptsysCut && (ht > htMin || mode !=0))  histo_R->Fill(18, xlWeight); //CR 2 regular
	      if (nJets == 2 && nTightJetsBT == 1 && nJetsBT == 1 && ptSystem <= ptsysCut && (ht > htMin || mode !=0))  histo_R->Fill(19, xlWeight);
	      if (nJets == 2 && nTightJetsBT == 2 && nJetsBT == 2 && ptSystem <= ptsysCut && (ht > htMin || mode !=0))  histo_R->Fill(20, xlWeight);
	      if (nJets == 2 && nJetsBT == 1 && ptSystem <= ptsysCut && (ht > htMin || mode !=0))  histo_R->Fill(21, xlWeight); //CR 1 another way
	      if (nJets == 2 && nJetsBT == 2 && ptSystem <= ptsysCut && (ht > htMin || mode !=0))  histo_R->Fill(22, xlWeight); //CR 2 another way
	      if (nJets == 2 && nTightJetsBT == 1 && nJetsBT == 1)  histo_R->Fill(23, xlWeight); //CR1 no ht no ptsys tighter
	      if (nJets == 2 && nTightJetsBT == 2 && nJetsBT == 2)  histo_R->Fill(24, xlWeight); //CR2 no ht no ptsys tighter
	      if (nJets == 2 && nJetsBT == 1)  histo_R->Fill(25, xlWeight); //CR1 no ht no ptsys another flavor
	      if (nJets == 2 && nJetsBT == 2)  histo_R->Fill(26, xlWeight); //CR2 no ht no ptsys another flavor
	      if (nJets == 1 && nTightJetsBT == 1 && bTagged && nJetsBT == 1 && (ht > htMin || mode !=0))histo_R->Fill(27, xlWeight); //signal no ptsys
	      if (nJets == 1 && nTightJetsBT == 1 && bTagged && nJetsBT == 1 && ptSystem <= ptsysCut)histo_R->Fill(28, xlWeight); //signal no ht
	      if (nJets == 2 && nTightJetsBT == 1 &&  (ht > htMin || mode !=0))  histo_R->Fill(29, xlWeight); //CR 1 
	      if (nJets == 2 && nTightJetsBT == 2 &&  (ht > htMin || mode !=0))  histo_R->Fill(30, xlWeight); //CR 2 
				
	      
	    } //jets in the event
	  } //all CR
	  
	} // mll
      } //mll pre
    } // 2 leptons
  }// event loop.
  
  
  
  if (!silent){ 
    cout << "------------------------------------------" << endl;
    cout << "[Results:] " << plotName <<  endl;
    cout << "------------------------------------------" << endl;  
    for (int i = 2; i < 9; i++){
      if (i == 2) cout << " leptons: " <<  histo->GetBinContent(i) << " +/-  " <<  histo->GetBinError(i)  << endl;
      if (i == 3) cout << " inv. mass: " <<  histo->GetBinContent(i) << " +/-  " <<  histo->GetBinError(i)  << endl;
      if (i == 4) cout << " met: " <<  histo->GetBinContent(i) << " +/-  " <<  histo->GetBinError(i)  << endl;
      if (i == 5) cout << " jet: " <<  histo->GetBinContent(i) << " +/-  " <<  histo->GetBinError(i)  << endl;
      if (i == 6) cout << " jet_bt: " <<  histo->GetBinContent(i) << " +/-  " <<  histo->GetBinError(i)  << endl;
      if (i == 7) cout << " ht: " <<  histo->GetBinContent(i) << " +/-  " <<  histo->GetBinError(i)  << endl;
    }
    cout << "------------------------------------------" << endl; 
    cout << "[eta values:]" << plotName << endl;
    cout << "------------------------------------------" << endl; 
    for (int j =1 ; j<7; j++){
      if(j == 1) {
         double amount = 0; 
	 //double amounterror = 0; 
      
         for(int k = 0; k< 50; k++) {   
	     amount = amount + histo_eta_jet_30->GetBinContent(k); 
	  //   amounterror = sqrt(amounterror^2 + (histo_eta_jet_30->GetBinError(k))^2);
           //cout << "pt higher then 30: " << histo_eta_jet_30->GetBinContent(k) << " +/- " << histo_eta_jet_30->GetBinError(k) << endl; 
         }
	 
	 cout << "pt higher then 30: " << amount <<  endl;
      
      }
        if(j == 2) {
         double amount = 0; 
	 //double amounterror = 0; 
      
         for(int k = 0; k< 50; k++) {   
	     amount = amount + histo_eta_jet_50->GetBinContent(k); 
	  //   amounterror = sqrt(amounterror^2 + (histo_eta_jet_30->GetBinError(k))^2);
           //cout << "pt higher then 50: " << histo_eta_jet_30->GetBinContent(k) << " +/- " << histo_eta_jet_30->GetBinError(k) << endl; 
         }
	 
	 cout << "pt higher then 50: " << amount <<  endl;
      
      }
      
            if(j == 3) {
         double amount = 0; 
	 //double amounterror = 0; 
      
         for(int k = 0; k< 50; k++) {   
	     amount = amount + histo_eta_jet_70->GetBinContent(k); 
	  //   amounterror = sqrt(amounterror^2 + (histo_eta_jet_30->GetBinError(k))^2);
           //cout << "pt higher then 30: " << histo_eta_jet_30->GetBinContent(k) << " +/- " << histo_eta_jet_30->GetBinError(k) << endl; 
         }
	 
	 cout << "pt higher then 70: " << amount <<  endl;
      
      }
            if(j == 4) {
         double amount = 0; 
	 //double amounterror = 0; 
      
         for(int k = 0; k< 50; k++) {   
	     amount = amount + histo_eta_jet_70->GetBinContent(k); 
	  //   amounterror = sqrt(amounterror^2 + (histo_eta_jet_30->GetBinError(k))^2);
           //cout << "pt higher then 30: " << histo_eta_jet_30->GetBinContent(k) << " +/- " << histo_eta_jet_30->GetBinError(k) << endl; 
         }
	 
	 cout << "pt higher then 70: " << amount <<  endl;
      
      }
            if(j == 5) {
         double amount = 0; 
	 //double amounterror = 0; 
      
         for(int k = 0; k< 50; k++) {   
	     amount = amount + histo_eta_jet_90->GetBinContent(k); 
	  //   amounterror = sqrt(amounterror^2 + (histo_eta_jet_30->GetBinError(k))^2);
           //cout << "pt higher then 30: " << histo_eta_jet_30->GetBinContent(k) << " +/- " << histo_eta_jet_30->GetBinError(k) << endl; 
         }
	 
	 cout << "pt higher then 90: " << amount <<  endl;
      
      }
            if(j == 6) {
         double amount = 0; 
	 //double amounterror = 0; 
      
         for(int k = 0; k< 50; k++) {   
	     amount = amount + histo_eta_jet_110->GetBinContent(k); 
	  //   amounterror = sqrt(amounterror^2 + (histo_eta_jet_30->GetBinError(k))^2);
           //cout << "pt higher then 30: " << histo_eta_jet_30->GetBinContent(k) << " +/- " << histo_eta_jet_30->GetBinError(k) << endl; 
         }
	 
	 cout << "pt higher then 110: " << amount <<  endl;
      
      }
    
    }
    
    
    
    
  }
  f_var.Write();
  f_var.Close();
}