diff --git a/.gitignore b/.gitignore index d175ee75b4a..30937e3b9bb 100644 --- a/.gitignore +++ b/.gitignore @@ -44,3 +44,6 @@ prod_alcarereco *.png *.eps *.pdf + +LSF* +ZFitter/output* \ No newline at end of file diff --git a/EOverPCalibration/bin/BuildFile.xml b/EOverPCalibration/bin/BuildFile.xml index 2893a8a0e07..f664bc3cae6 100644 --- a/EOverPCalibration/bin/BuildFile.xml +++ b/EOverPCalibration/bin/BuildFile.xml @@ -14,6 +14,7 @@ + diff --git a/EOverPCalibration/bin/CalibrationMomentum.cpp b/EOverPCalibration/bin/CalibrationMomentum.cpp index 934ea6e4165..0a57d966007 100644 --- a/EOverPCalibration/bin/CalibrationMomentum.cpp +++ b/EOverPCalibration/bin/CalibrationMomentum.cpp @@ -64,11 +64,7 @@ int main(int argc, char** argv) std::string configFileName = argv[1]; -#ifdef CMSSW_7_2_X std::shared_ptr parameterSet = edm::readConfig(configFileName); -#else - boost::shared_ptr parameterSet = edm::readConfig(configFileName); -#endif edm::ParameterSet Options = parameterSet -> getParameter("Options"); // parameterSet.reset(); @@ -161,7 +157,7 @@ int main(int argc, char** argv) //--- weights for MC TFile weightsFile (WeightforMC.c_str(),"READ"); - TH1F* hweights = (TH1F*)weightsFile.Get("hweights"); + TH1F* hweights = (TH1F*)weightsFile.Get("pileup"); float w[100]; for (int ibin = 1; ibin < hweights->GetNbinsX()+1; ibin++){ @@ -184,93 +180,54 @@ int main(int argc, char** argv) std::cout << " MC : " << ntu_MC->GetEntries() << " entries in MC sample" << std::endl; // observables - int isW; - float mZ; - float scEta, scPhi; - float scEta2, scPhi2; - float eleEta, elePhi; - float eleEta2, elePhi2; - float scEne, scEneReg, scEt, scERaw, e3x3, R9; - float scEne2, scEneReg2, scEt2, scERaw2, e3x32, R92; - float charge, charge2; - float pTK,pTK2; - int iphiSeed, ele1_ix, ele1_iy, ele1_iz; - int iphiSeed2, ele2_ix, ele2_iy, ele2_iz; - int npu; + // int isW; + float invMass_SC; + float etaSCEle[3], phiSCEle[3]; + float etaEle[3], phiEle[3]; + float energySCEle[3], rawEnergySCEle[3], R9Ele[3]; + int chargeEle[3]; + float pAtVtxGsfEle[3]; + float seedXSCEle[3], seedYSCEle[3]; + int NPU[1]; + float PtEle[3]; + int ele1_iz, ele2_iz; // Set branch addresses for Data ntu_DA->SetBranchStatus("*",0); - ntu_DA->SetBranchStatus("isW", 1); ntu_DA->SetBranchAddress("isW", &isW); - ntu_DA->SetBranchStatus("ele1_eta", 1); ntu_DA->SetBranchAddress("ele1_eta", &eleEta); - ntu_DA->SetBranchStatus("ele2_eta", 1); ntu_DA->SetBranchAddress("ele2_eta", &eleEta2); - ntu_DA->SetBranchStatus("ele1_phi", 1); ntu_DA->SetBranchAddress("ele1_phi", &elePhi); - ntu_DA->SetBranchStatus("ele2_phi", 1); ntu_DA->SetBranchAddress("ele2_phi", &elePhi2); - ntu_DA->SetBranchStatus("ele1_scEta", 1); ntu_DA->SetBranchAddress("ele1_scEta", &scEta); - ntu_DA->SetBranchStatus("ele2_scEta", 1); ntu_DA->SetBranchAddress("ele2_scEta", &scEta2); - ntu_DA->SetBranchStatus("ele1_scPhi", 1); ntu_DA->SetBranchAddress("ele1_scPhi", &scPhi); - ntu_DA->SetBranchStatus("ele2_scPhi", 1); ntu_DA->SetBranchAddress("ele2_scPhi", &scPhi2); - ntu_DA->SetBranchStatus("ele1_scE", 1); ntu_DA->SetBranchAddress("ele1_scE", &scEne); - ntu_DA->SetBranchStatus("ele2_scE", 1); ntu_DA->SetBranchAddress("ele2_scE", &scEne2); - ntu_DA->SetBranchStatus("ele1_scE_regression", 1); ntu_DA->SetBranchAddress("ele1_scE_regression", &scEneReg); - ntu_DA->SetBranchStatus("ele2_scE_regression", 1); ntu_DA->SetBranchAddress("ele2_scE_regression", &scEneReg2); - ntu_DA->SetBranchStatus("ele1_scEt", 1); ntu_DA->SetBranchAddress("ele1_scEt",&scEt); - ntu_DA->SetBranchStatus("ele2_scEt", 1); ntu_DA->SetBranchAddress("ele2_scEt",&scEt2); - ntu_DA->SetBranchStatus("ele1_scERaw", 1); ntu_DA->SetBranchAddress("ele1_scERaw", &scERaw); - ntu_DA->SetBranchStatus("ele2_scERaw", 1); ntu_DA->SetBranchAddress("ele2_scERaw", &scERaw2); - ntu_DA->SetBranchStatus("ele1_e3x3", 1); ntu_DA->SetBranchAddress("ele1_e3x3", &e3x3); - ntu_DA->SetBranchStatus("ele2_e3x3", 1); ntu_DA->SetBranchAddress("ele2_e3x3", &e3x32); - ntu_DA->SetBranchStatus("ele1ele2_scM", 1); ntu_DA->SetBranchAddress("ele1ele2_scM", &mZ); - ntu_DA->SetBranchStatus("ele1_charge", 1); ntu_DA->SetBranchAddress("ele1_charge", &charge); - ntu_DA->SetBranchStatus("ele2_charge", 1); ntu_DA->SetBranchAddress("ele2_charge", &charge2); - ntu_DA->SetBranchStatus("ele1_tkP", 1); ntu_DA->SetBranchAddress("ele1_tkP", &pTK); - ntu_DA->SetBranchStatus("ele2_tkP", 1); ntu_DA->SetBranchAddress("ele2_tkP", &pTK2); - ntu_DA->SetBranchStatus("ele1_seedIphi", 1); ntu_DA->SetBranchAddress("ele1_seedIphi", &iphiSeed); - ntu_DA->SetBranchStatus("ele2_seedIphi", 1); ntu_DA->SetBranchAddress("ele2_seedIphi", &iphiSeed2); - ntu_DA->SetBranchStatus("ele1_seedIx", 1); ntu_DA->SetBranchAddress("ele1_seedIx", &ele1_ix); - ntu_DA->SetBranchStatus("ele2_seedIx", 1); ntu_DA->SetBranchAddress("ele2_seedIx", &ele2_ix); - ntu_DA->SetBranchStatus("ele1_seedIy", 1); ntu_DA->SetBranchAddress("ele1_seedIy", &ele1_iy); - ntu_DA->SetBranchStatus("ele2_seedIy", 1); ntu_DA->SetBranchAddress("ele2_seedIy", &ele2_iy); - ntu_DA->SetBranchStatus("ele1_seedZside", 1); ntu_DA->SetBranchAddress("ele1_seedZside", &ele1_iz); - ntu_DA->SetBranchStatus("ele2_seedZside", 1); ntu_DA->SetBranchAddress("ele2_seedZside", &ele2_iz); - + // ntu_DA->SetBranchStatus("isW", 1); ntu_DA->SetBranchAddress("isW", &isW); + ntu_DA->SetBranchStatus("etaEle", 1); ntu_DA->SetBranchAddress("etaEle", &etaEle); + ntu_DA->SetBranchStatus("phiEle", 1); ntu_DA->SetBranchAddress("phiEle", &phiEle); + ntu_DA->SetBranchStatus("etaSCEle", 1); ntu_DA->SetBranchAddress("etaSCEle", &etaSCEle); + ntu_DA->SetBranchStatus("phiSCEle", 1); ntu_DA->SetBranchAddress("phiSCEle", &phiSCEle); + ntu_DA->SetBranchStatus("energySCEle", 1); ntu_DA->SetBranchAddress("energySCEle", &energySCEle); + ntu_DA->SetBranchStatus("rawEnergySCEle", 1); ntu_DA->SetBranchAddress("rawEnergySCEle", &rawEnergySCEle); + ntu_DA->SetBranchStatus("PtEle", 1); ntu_DA->SetBranchAddress("PtEle", &PtEle); + ntu_DA->SetBranchStatus("invMass_SC", 1); ntu_DA->SetBranchAddress("invMass_SC", &invMass_SC); + ntu_DA->SetBranchStatus("chargeEle", 1); ntu_DA->SetBranchAddress("chargeEle", &chargeEle); + ntu_DA->SetBranchStatus("pAtVtxGsfEle", 1); ntu_DA->SetBranchAddress("pAtVtxGsfEle", &pAtVtxGsfEle); + ntu_DA->SetBranchStatus("seedXSCEle", 1); ntu_DA->SetBranchAddress("seedXSCEle", &seedXSCEle); + ntu_DA->SetBranchStatus("seedYSCEle", 1); ntu_DA->SetBranchAddress("seedYSCEle", &seedYSCEle); + // Set branch addresses for MC ntu_MC->SetBranchStatus("*",0); - ntu_MC->SetBranchStatus("isW", 1); ntu_MC->SetBranchAddress("isW", &isW); - ntu_MC->SetBranchStatus("ele1_eta", 1); ntu_MC->SetBranchAddress("ele1_eta", &eleEta); - ntu_MC->SetBranchStatus("ele2_eta", 1); ntu_MC->SetBranchAddress("ele2_eta", &eleEta2); - ntu_MC->SetBranchStatus("ele1_phi", 1); ntu_MC->SetBranchAddress("ele1_phi", &elePhi); - ntu_MC->SetBranchStatus("ele2_phi", 1); ntu_MC->SetBranchAddress("ele2_phi", &elePhi2); - ntu_MC->SetBranchStatus("ele1_scEta", 1); ntu_MC->SetBranchAddress("ele1_scEta", &scEta); - ntu_MC->SetBranchStatus("ele2_scEta", 1); ntu_MC->SetBranchAddress("ele2_scEta", &scEta2); - ntu_MC->SetBranchStatus("ele1_scPhi", 1); ntu_MC->SetBranchAddress("ele1_scPhi", &scPhi); - ntu_MC->SetBranchStatus("ele2_scPhi", 1); ntu_MC->SetBranchAddress("ele2_scPhi", &scPhi2); - ntu_MC->SetBranchStatus("ele1_scE", 1); ntu_MC->SetBranchAddress("ele1_scE", &scEne); - ntu_MC->SetBranchStatus("ele2_scE", 1); ntu_MC->SetBranchAddress("ele2_scE", &scEne2); - ntu_MC->SetBranchStatus("ele1_scE_regression", 1); ntu_MC->SetBranchAddress("ele1_scE_regression", &scEneReg); - ntu_MC->SetBranchStatus("ele2_scE_regression", 1); ntu_MC->SetBranchAddress("ele2_scE_regression", &scEneReg2); - ntu_MC->SetBranchStatus("ele1_scEt", 1); ntu_MC->SetBranchAddress("ele1_scEt",&scEt); - ntu_MC->SetBranchStatus("ele2_scEt", 1); ntu_MC->SetBranchAddress("ele2_scEt",&scEt2); - ntu_MC->SetBranchStatus("ele1_scERaw", 1); ntu_MC->SetBranchAddress("ele1_scERaw", &scERaw); - ntu_MC->SetBranchStatus("ele2_scERaw", 1); ntu_MC->SetBranchAddress("ele2_scERaw", &scERaw2); - ntu_MC->SetBranchStatus("ele1_e3x3", 1); ntu_MC->SetBranchAddress("ele1_e3x3", &e3x3); - ntu_MC->SetBranchStatus("ele2_e3x3", 1); ntu_MC->SetBranchAddress("ele2_e3x3", &e3x32); - ntu_MC->SetBranchStatus("ele1ele2_scM", 1); ntu_MC->SetBranchAddress("ele1ele2_scM", &mZ); - ntu_MC->SetBranchStatus("ele1_charge", 1); ntu_MC->SetBranchAddress("ele1_charge", &charge); - ntu_MC->SetBranchStatus("ele2_charge", 1); ntu_MC->SetBranchAddress("ele2_charge", &charge2); - ntu_MC->SetBranchStatus("ele1_tkP", 1); ntu_MC->SetBranchAddress("ele1_tkP", &pTK); - ntu_MC->SetBranchStatus("ele2_tkP", 1); ntu_MC->SetBranchAddress("ele2_tkP", &pTK2); - ntu_MC->SetBranchStatus("ele1_seedIphi", 1); ntu_MC->SetBranchAddress("ele1_seedIphi", &iphiSeed); - ntu_MC->SetBranchStatus("ele2_seedIphi", 1); ntu_MC->SetBranchAddress("ele2_seedIphi", &iphiSeed2); - ntu_MC->SetBranchStatus("ele1_seedIx", 1); ntu_MC->SetBranchAddress("ele1_seedIx", &ele1_ix); - ntu_MC->SetBranchStatus("ele2_seedIx", 1); ntu_MC->SetBranchAddress("ele2_seedIx", &ele2_ix); - ntu_MC->SetBranchStatus("ele1_seedIy", 1); ntu_MC->SetBranchAddress("ele1_seedIy", &ele1_iy); - ntu_MC->SetBranchStatus("ele2_seedIy", 1); ntu_MC->SetBranchAddress("ele2_seedIy", &ele2_iy); - ntu_MC->SetBranchStatus("ele1_seedZside", 1); ntu_MC->SetBranchAddress("ele1_seedZside", &ele1_iz); - ntu_MC->SetBranchStatus("ele2_seedZside", 1); ntu_MC->SetBranchAddress("ele2_seedZside", &ele2_iz); + // ntu_MC->SetBranchStatus("isW", 1); ntu_MC->SetBranchAddress("isW", &isW); + ntu_MC->SetBranchStatus("etaEle", 1); ntu_MC->SetBranchAddress("etaEle", &etaEle); + ntu_MC->SetBranchStatus("phiEle", 1); ntu_MC->SetBranchAddress("phiEle", &phiEle); + ntu_MC->SetBranchStatus("etaSCEle", 1); ntu_MC->SetBranchAddress("etaSCEle", &etaSCEle); + ntu_MC->SetBranchStatus("phiSCEle", 1); ntu_MC->SetBranchAddress("phiSCEle", &phiSCEle); + ntu_MC->SetBranchStatus("energySCEle", 1); ntu_MC->SetBranchAddress("energySCEle", &energySCEle); + ntu_MC->SetBranchStatus("rawEnergySCEle", 1); ntu_MC->SetBranchAddress("rawEnergySCEle", &rawEnergySCEle); + ntu_MC->SetBranchStatus("PtEle", 1); ntu_MC->SetBranchAddress("PtEle", &PtEle); + ntu_MC->SetBranchStatus("invMass_SC", 1); ntu_MC->SetBranchAddress("invMass_SC", &invMass_SC); + ntu_MC->SetBranchStatus("chargeEle", 1); ntu_MC->SetBranchAddress("chargeEle", &chargeEle); + ntu_MC->SetBranchStatus("pAtVtxGsfEle", 1); ntu_MC->SetBranchAddress("pAtVtxGsfEle", &pAtVtxGsfEle); + ntu_MC->SetBranchStatus("seedXSCEle", 1); ntu_MC->SetBranchAddress("seedXSCEle", &seedXSCEle); + ntu_MC->SetBranchStatus("seedYSCEle", 1); ntu_MC->SetBranchAddress("seedYSCEle", &seedYSCEle); + if(usePUweights) { - ntu_MC->SetBranchStatus("PUit_NumInteractions", 1); ntu_MC->SetBranchAddress("PUit_NumInteractions", &npu); + ntu_MC->SetBranchStatus("NPU", 1); ntu_MC->SetBranchAddress("NPU", &NPU); } @@ -471,134 +428,138 @@ int main(int argc, char** argv) ntu_MC->GetEntry(entry); - if( isW == 1 ) continue; - if( fabs(scEta) > etaMax ) continue; - if( fabs(scEta2) > eta2Max ) continue; - if( scEt < 20. ) continue; - if( scEt2 < 20. ) continue; - - R9 = e3x3 / scERaw; - R92 = e3x32 / scERaw2; - + // if( isW == 1 ) continue; + if( fabs(etaSCEle[0]) > etaMax ) continue; + if( fabs(etaSCEle[1]) > eta2Max ) continue; + if( PtEle[0] < 20. ) continue; + if( PtEle[1] < 20. ) continue; + + if ( fabs(etaEle[0]) < 1.479) ele1_iz = 0; + else if (etaEle[0]>0) ele1_iz = 1; + else ele1_iz = -1; + + if ( fabs(etaEle[1]) < 1.479) ele2_iz = 0; + else if (etaEle[1]>0) ele2_iz = 1; + else ele2_iz = -1; //--- PU weights float ww = 1.; - if( usePUweights ) ww *= w[npu]; - - + if( usePUweights ) ww *= w[NPU[0]]; //--- set the mass for ele1 - var = ( mZ * sqrt(pTK/scEne) * sqrt(scEneReg2/scEne2) ) / 91.19; + // var = ( invMass_SC * sqrt(pAtVtxGsfEle[0]/energySCEle[0]) * sqrt(scEneReg2/energySCEle[1]) ) / 91.19; + var = ( invMass_SC * sqrt(pAtVtxGsfEle[0]/energySCEle[0]) ) / 91.19; // simulate e+/e- asymmetry - //if( charge > 0 ) ww *= 1.*(6/5); + //if( chargeEle[0] > 0 ) ww *= 1.*(6/5); //else ww *= 1.*(4/5); - + // MC - BARREL - ele1 - if( ele1_iz == 0 ) + if( ele1_iz == 0 ) { // fill MC templates - int modPhi = int(iphiSeed/(360./nPhiBinsTempEB)); + int modPhi = int(seedYSCEle[0]/(360./nPhiBinsTempEB)); if( modPhi == nPhiBinsTempEB ) modPhi = 0; - int regionId = templIndexEB(typeEB,eleEta,charge,R9); + int regionId = templIndexEB(typeEB,etaEle[0],chargeEle[0],R9Ele[0]); if( regionId == -1 ) continue; (h_template_EB.at(modPhi)).at(regionId) -> Fill(var*var,ww); // fill MC histos in eta bins - int PhibinEB = hPhiBinEB->FindBin(elePhi) - 1; + int PhibinEB = hPhiBinEB->FindBin(phiEle[0]) - 1; if( PhibinEB == nPhiBinsEB ) PhibinEB = 0; - + (h_EoP_EB.at(PhibinEB)).at(regionId) -> Fill(var*var,ww); // This is MC - h_phi_mc_EB[regionId] -> Fill(scPhi,ww); + h_phi_mc_EB[regionId] -> Fill(phiSCEle[0],ww); } // MC - ENDCAP - ele1 else { - int iphi = eRings->GetEndcapIphi(ele1_ix,ele1_iy,ele1_iz); + int iphi = eRings->GetEndcapIphi(seedXSCEle[0],seedYSCEle[0],ele1_iz); - if( ele1_iz == 1 )mapConversionEEp -> SetBinContent(ele1_ix,ele1_iy,scEta); - if( ele1_iz == -1 )mapConversionEEm -> SetBinContent(ele1_ix,ele1_iy,scEta); + if( ele1_iz == 1 )mapConversionEEp -> SetBinContent(seedXSCEle[0],seedYSCEle[0],etaSCEle[0]); + if( ele1_iz == -1 )mapConversionEEm -> SetBinContent(seedXSCEle[0],seedYSCEle[0],etaSCEle[0]); // fill MC templates int modPhi = int (iphi/(360./nPhiBinsTempEE)); if( modPhi == nPhiBinsTempEE ) modPhi = 0; - int regionId = templIndexEE(typeEE,eleEta,charge,R9); + int regionId = templIndexEE(typeEE,etaEle[0],chargeEle[0],R9Ele[0]); if( regionId == -1 ) continue; (h_template_EE.at(modPhi)).at(regionId) -> Fill(var*var,ww); // fill MC histos in eta bins - int PhibinEE = hPhiBinEE->FindBin(elePhi) - 1; + int PhibinEE = hPhiBinEE->FindBin(phiEle[0]) - 1; if( PhibinEE == nPhiBinsEE ) PhibinEE = 0; (h_EoP_EE.at(PhibinEE)).at(regionId) -> Fill(var*var,ww); // This is MC - h_phi_mc_EE[regionId] -> Fill(scPhi,ww); + h_phi_mc_EE[regionId] -> Fill(phiSCEle[0],ww); } //--- set the mass for ele2 - var = ( mZ * sqrt(pTK2/scEne2) * sqrt(scEneReg/scEne) ) / 91.19; + // var = ( invMass_SC * sqrt(pAtVtxGsfEle[1]/energySCEle[1]) * sqrt(scEneReg/energySCEle[0]) ) / 91.19; + var = ( invMass_SC * sqrt(pAtVtxGsfEle[1]/energySCEle[1]) ) / 91.19; // simulate e+/e- asymmetry - //if( charge > 0 ) ww *= 1.*(6/5); + //if( chargeEle[0] > 0 ) ww *= 1.*(6/5); //else ww *= 1.*(4/5); // MC - BARREL - ele2 if( ele2_iz == 0) { // fill MC templates - int modPhi = int (iphiSeed2/(360./nPhiBinsTempEB)); + int modPhi = int (seedYSCEle[1]/(360./nPhiBinsTempEB)); if( modPhi == nPhiBinsTempEB ) modPhi = 0; - int regionId = templIndexEB(typeEB,eleEta2,charge2,R92); + int regionId = templIndexEB(typeEB,etaEle[1],chargeEle[1],R9Ele[1]); if(regionId == -1) continue; (h_template_EB.at(modPhi)).at(regionId)->Fill(var*var,ww); // fill MC histos in eta bins - int PhibinEB = hPhiBinEB->FindBin(elePhi2) - 1; + int PhibinEB = hPhiBinEB->FindBin(phiEle[1]) - 1; if( PhibinEB==nPhiBinsEB ) PhibinEB = 0; (h_EoP_EB.at(PhibinEB)).at(regionId) -> Fill(var*var,ww); // This is MC - h_phi_mc_EB[regionId]->Fill(scPhi2,ww); + h_phi_mc_EB[regionId]->Fill(phiSCEle[1],ww); } // MC - ENDCAP - ele2 else { - if( ele2_iz == 1 ) mapConversionEEp -> SetBinContent(ele2_ix,ele2_iy,scEta2); - if( ele2_iz == -1 ) mapConversionEEm -> SetBinContent(ele2_ix,ele2_iy,scEta2); + if( ele2_iz == 1 ) mapConversionEEp -> SetBinContent(seedXSCEle[1],seedYSCEle[1],etaSCEle[1]); + if( ele2_iz == -1 ) mapConversionEEm -> SetBinContent(seedXSCEle[1],seedYSCEle[1],etaSCEle[1]); - int iphi = eRings->GetEndcapIphi(ele2_ix,ele2_iy,ele2_iz); + int iphi = eRings->GetEndcapIphi(seedXSCEle[1],seedYSCEle[1],ele2_iz); // fill MC templates int modPhi = int (iphi/(360./nPhiBinsTempEE)); if( modPhi == nPhiBinsTempEE ) modPhi = 0; - int regionId = templIndexEE(typeEE,eleEta2,charge2,R92); + int regionId = templIndexEE(typeEE,etaEle[1],chargeEle[1],R9Ele[1]); if(regionId == -1) continue; (h_template_EE.at(modPhi)).at(regionId) -> Fill(var*var,ww); // fill MC histos in eta bins - int PhibinEE = hPhiBinEE->FindBin(elePhi2) - 1; + int PhibinEE = hPhiBinEE->FindBin(phiEle[1]) - 1; if(PhibinEE==nPhiBinsEE) PhibinEE = 0; (h_EoP_EE.at(PhibinEE)).at(regionId) -> Fill(var*var,ww); // This is MC - h_phi_mc_EE[regionId]->Fill(scPhi2,ww); + h_phi_mc_EE[regionId]->Fill(phiSCEle[1],ww); } - h_et_mc ->Fill(scEt, ww); - h_et_mc ->Fill(scEt2,ww); + h_et_mc ->Fill(PtEle[0], ww); + h_et_mc ->Fill(PtEle[1],ww); } @@ -616,97 +577,105 @@ int main(int argc, char** argv) ntu_DA->GetEntry(entry); - if( isW == 1 ) continue; - if( fabs(scEta) > etaMax ) continue; - if( fabs(scEta2) > eta2Max ) continue; - if( scEt < 20. ) continue; - if( scEt2 < 20. ) continue; - - R9 = e3x3 / scERaw; - R92 = e3x32 / scERaw2; + // if( isW == 1 ) continue; + if( fabs(etaSCEle[0]) > etaMax ) continue; + if( fabs(etaSCEle[1]) > eta2Max ) continue; + if( PtEle[0] < 20. ) continue; + if( PtEle[1] < 20. ) continue; float ww = 1.; + if ( fabs(etaEle[0]) < 1.479) ele1_iz = 0; + else if (etaEle[0]>0) ele1_iz = 1; + else ele1_iz = -1; + + if ( fabs(etaEle[1]) < 1.479) ele2_iz = 0; + else if (etaEle[1]>0) ele2_iz = 1; + else ele2_iz = -1; //--- set the mass for ele1 - if( ele1_iz == 0 ) var = ( mZ * sqrt(pTK/scEne) * sqrt(scEneReg2/scEne2) ) / 91.19; - else var = ( mZ * sqrt(pTK/scEne) * sqrt(scEneReg2/scEne2) ) / 91.19; + // if( ele1_iz == 0 ) var = ( invMass_SC * sqrt(pAtVtxGsfEle[0]/energySCEle[0]) * sqrt(scEneReg2/energySCEle[1]) ) / 91.19; + // else var = ( invMass_SC * sqrt(pAtVtxGsfEle[0]/energySCEle[0]) * sqrt(scEneReg2/energySCEle[1]) ) / 91.19; + if( ele1_iz == 0 ) var = ( invMass_SC * sqrt(pAtVtxGsfEle[0]/energySCEle[0]) ) / 91.19; + else var = ( invMass_SC * sqrt(pAtVtxGsfEle[0]/energySCEle[0]) ) / 91.19; // simulate e+/e- asymmetry - //if( charge > 0 ) ww *= 1.*(6/5); + //if( chargeEle[0] > 0 ) ww *= 1.*(6/5); //else ww *= 1.*(4/5); // DATA - BARREL - ele1 if( ele1_iz == 0 ) { - int PhibinEB = hPhiBinEB->FindBin(elePhi) - 1; + int PhibinEB = hPhiBinEB->FindBin(phiEle[0]) - 1; if( PhibinEB == nPhiBinsEB ) PhibinEB = 0; - int regionId = templIndexEB(typeEB,eleEta,charge,R9); + int regionId = templIndexEB(typeEB,etaEle[0],chargeEle[0],R9Ele[0]); if(regionId == -1) continue; (h_EoC_EB.at(PhibinEB)).at(regionId) -> Fill(var*var,ww); // This is DATA - (h_Phi_EB.at(PhibinEB)).at(regionId) -> Fill(elePhi); - h_phi_data_EB[regionId]->Fill(elePhi); + (h_Phi_EB.at(PhibinEB)).at(regionId) -> Fill(phiEle[0]); + h_phi_data_EB[regionId]->Fill(phiEle[0]); } // DATA - ENDCAP - ele1 else { - if( ele1_iz == 1 ) mapConversionEEp -> SetBinContent(ele1_ix,ele1_iy,scEta); - if( ele1_iz == -1 ) mapConversionEEm -> SetBinContent(ele1_ix,ele1_iy,scEta); + if( ele1_iz == 1 ) mapConversionEEp -> SetBinContent(seedXSCEle[0],seedYSCEle[0],etaSCEle[0]); + if( ele1_iz == -1 ) mapConversionEEm -> SetBinContent(seedXSCEle[0],seedYSCEle[0],etaSCEle[0]); - int PhibinEE = hPhiBinEE->FindBin(elePhi) - 1; + int PhibinEE = hPhiBinEE->FindBin(phiEle[0]) - 1; if( PhibinEE == nPhiBinsEE ) PhibinEE = 0; - int regionId = templIndexEE(typeEE,eleEta,charge,R9); + int regionId = templIndexEE(typeEE,etaEle[0],chargeEle[0],R9Ele[0]); if( regionId == -1 ) continue; (h_EoC_EE.at(PhibinEE)).at(regionId) -> Fill(var*var,ww); // This is DATA - (h_Phi_EE.at(PhibinEE)).at(regionId) -> Fill(elePhi); - h_phi_data_EE[regionId] -> Fill(elePhi); + (h_Phi_EE.at(PhibinEE)).at(regionId) -> Fill(phiEle[0]); + h_phi_data_EE[regionId] -> Fill(phiEle[0]); } //--- set the mass for ele2 - if( ele2_iz == 0 ) var = ( mZ * sqrt(pTK2/scEne2) * sqrt(scEneReg/scEne) ) / 91.19; - else var = ( mZ * sqrt(pTK2/scEne2) * sqrt(scEneReg/scEne) ) / 91.19; + // if( ele2_iz == 0 ) var = ( invMass_SC * sqrt(pAtVtxGsfEle[1]/energySCEle[1]) * sqrt(scEneReg/energySCEle[0]) ) / 91.19; + // else var = ( invMass_SC * sqrt(pAtVtxGsfEle[1]/energySCEle[1]) * sqrt(scEneReg/energySCEle[0]) ) / 91.19; + if( ele2_iz == 0 ) var = ( invMass_SC * sqrt(pAtVtxGsfEle[1]/energySCEle[1]) ) / 91.19; + else var = ( invMass_SC * sqrt(pAtVtxGsfEle[1]/energySCEle[1]) ) / 91.19; // simulate e+/e- asymmetry - //if( charge2 > 0 ) ww *= 1.*(6/5); + //if( chargeEle[0]Ele[1] > 0 ) ww *= 1.*(6/5); //else ww *= 1.*(4/5); // DATA - BARREL - ele2 if( ele2_iz == 0 ) { - int PhibinEB = hPhiBinEB->FindBin(elePhi2) - 1; + int PhibinEB = hPhiBinEB->FindBin(phiEle[1]) - 1; if( PhibinEB == nPhiBinsEB ) PhibinEB = 0; - int regionId = templIndexEB(typeEB,eleEta2,charge2,R92); + int regionId = templIndexEB(typeEB,etaEle[1],chargeEle[1],R9Ele[1]); if( regionId == -1 ) continue; (h_EoC_EB.at(PhibinEB)).at(regionId) -> Fill(var*var,ww); // This is DATA - (h_Phi_EB.at(PhibinEB)).at(regionId) -> Fill(elePhi2); - h_phi_data_EB[regionId] -> Fill(elePhi2); + (h_Phi_EB.at(PhibinEB)).at(regionId) -> Fill(phiEle[1]); + h_phi_data_EB[regionId] -> Fill(phiEle[1]); } else { - if( ele2_iz == 1 ) mapConversionEEp -> SetBinContent(ele2_ix,ele2_iy,scEta2); - if( ele2_iz == -1 ) mapConversionEEm -> SetBinContent(ele2_ix,ele2_iy,scEta2); + if( ele2_iz == 1 ) mapConversionEEp -> SetBinContent(seedXSCEle[1],seedYSCEle[1],etaSCEle[1]); + if( ele2_iz == -1 ) mapConversionEEm -> SetBinContent(seedXSCEle[1],seedYSCEle[1],etaSCEle[1]); - int PhibinEE = hPhiBinEE->FindBin(elePhi2) - 1; + int PhibinEE = hPhiBinEE->FindBin(phiEle[1]) - 1; if( PhibinEE == nPhiBinsEE ) PhibinEE = 0; - int regionId = templIndexEE(typeEE,eleEta2,charge2,R92); + int regionId = templIndexEE(typeEE,etaEle[1],chargeEle[1],R9Ele[1]); if( regionId == -1 ) continue; (h_EoC_EE.at(PhibinEE)).at(regionId) -> Fill(var*var,ww); // This is DATA - (h_Phi_EE.at(PhibinEE)).at(regionId) -> Fill(elePhi2); - h_phi_data_EE[regionId] ->Fill(elePhi2); + (h_Phi_EE.at(PhibinEE)).at(regionId) -> Fill(phiEle[1]); + h_phi_data_EE[regionId] ->Fill(phiEle[1]); } - h_et_data ->Fill(scEt); - h_et_data ->Fill(scEt2); + h_et_data ->Fill(PtEle[0]); + h_et_data ->Fill(PtEle[1]); } std::cout << "End loop: Analyze events " << endl; @@ -813,6 +782,7 @@ int main(int argc, char** argv) std::cout << "***** Fitting MC EB " << flPhi << " (" << i << "," << j << "): "; TFitResultPtr rp; int fStatus; + std::cout<<"entries: "<<(h_EoP_EB.at(i)).at(j)->GetEntries()< SetParameter(1, 0.99); diff --git a/EOverPCalibration/bin/CalibrationPlots.cpp b/EOverPCalibration/bin/CalibrationPlots.cpp index 26bb1ac17bf..2ded28dfefd 100644 --- a/EOverPCalibration/bin/CalibrationPlots.cpp +++ b/EOverPCalibration/bin/CalibrationPlots.cpp @@ -60,11 +60,7 @@ int main(int argc, char **argv) } std::string configFileName = argv[1]; -#ifdef CMSSW_7_2_X std::shared_ptr parameterSet = edm::readConfig(configFileName); -#else - boost::shared_ptr parameterSet = edm::readConfig(configFileName); -#endif edm::ParameterSet Options = parameterSet -> getParameter("Options"); @@ -113,6 +109,17 @@ int main(int argc, char **argv) else{ std::cout<<" Exit from code, no odd input file"< > corrMomentum(1); + + for (int k=0; k<1; k++) { + for(int i = 0; i <2; ++i){ + std::cout<Get(Name)) ); + } + } //------------ @@ -154,6 +161,8 @@ int main(int argc, char **argv) //----------------------- // map for dead TT centre + + std::cout<<"debug"< > > TT_centre; if( isEB == true ) @@ -181,6 +190,7 @@ int main(int argc, char **argv) } + std::cout<<"debug"< h2_corrP; + std::map h2_IC_corr; // get the IC maps as they come from the algorithm std::map h2_IC_raw; @@ -267,8 +281,10 @@ int main(int argc, char **argv) } else { + std::cout<<"debug"<Get("h_scale_EEM") ); h2_IC_raw[1] = (TH2F*)( inFile->Get("h_scale_EEP") ); + std::cout<<"debug"<Clone("h2_IC_raw_phiNorm_EEM") ); h2_IC_raw_phiNorm[1] = (TH2F*)( h2_IC_raw[1] ->Clone("h2_IC_raw_phiNorm_EEP") ); @@ -276,13 +292,31 @@ int main(int argc, char **argv) h2_IC_raw_phiNorm[1] -> Reset("ICEMS"); h2_IC_raw_phiNorm[-1] -> ResetStats(); h2_IC_raw_phiNorm[1] -> ResetStats(); + + h2_corrP[-1] = (TH2F*)( h2_IC_raw[-1]->Clone("h2_corrP_EEM") ); + h2_corrP[1] = (TH2F*)( h2_IC_raw[1] ->Clone("h2_corrP_EEP") ); + h2_corrP[-1] -> Reset("ICEMS"); + h2_corrP[1] -> Reset("ICEMS"); + h2_corrP[-1] -> ResetStats(); + h2_corrP[1] -> ResetStats(); + + h2_IC_corr[-1] = (TH2F*)( h2_IC_raw[-1]->Clone("h2_IC_corr_EEM") ); + h2_IC_corr[1] = (TH2F*)( h2_IC_raw[1] ->Clone("h2_IC_corr_EEP") ); + h2_IC_corr[-1] -> Reset("ICEMS"); + h2_IC_corr[1] -> Reset("ICEMS"); + h2_IC_corr[-1] -> ResetStats(); + h2_IC_corr[1] -> ResetStats(); + + std::cout<<"debug"<Get("h_scale_EEM") ); h2_ICEven_raw[1] = (TH2F*)( inFileEven->Get("h_scale_EEP") ); h2_ICOdd_raw[-1 ] = (TH2F*)( inFileOdd ->Get("h_scale_EEM") ); h2_ICOdd_raw[1] = (TH2F*)( inFileOdd ->Get("h_scale_EEP") ); + std::cout<<"debug"<Clone("h2_IC_raw_phiNorm_even_EEM") ); h2_IC_raw_phiNorm_even[1] = (TH2F*)( h2_ICEven_raw[1] ->Clone("h2_IC_raw_phiNorm_even_EEP") ); @@ -290,6 +324,7 @@ int main(int argc, char **argv) h2_IC_raw_phiNorm_even[1] -> Reset("ICEMS"); h2_IC_raw_phiNorm_even[-1] -> ResetStats(); h2_IC_raw_phiNorm_even[1] -> ResetStats(); + std::cout<<"debug"<Clone("h2_IC_raw_phiNorm_odd_EEM") ); h2_IC_raw_phiNorm_odd[1] = (TH2F*)( h2_ICOdd_raw[1] ->Clone("h2_IC_raw_phiNorm_odd_EEP") ); @@ -301,6 +336,7 @@ int main(int argc, char **argv) } + std::cout<<"debug"< mkdir("crackCorr"); outFile -> cd("crackCorr"); @@ -688,47 +726,82 @@ int main(int argc, char **argv) { DrawICMap(h2_IC_raw_phiNorm[0], outputFolder+"/EB_h2_IC_raw_phiNorm", "png",isEB); DrawICMap(h2_IC_crackCorr_phiNorm[0],outputFolder+"/EB_h2_IC_crackCorr_phiNorm","png",isEB); + DrawICMap(h2_IC_raw_phiNorm[0], outputFolder+"/EB_h2_IC_raw_phiNorm", "pdf",isEB); + DrawICMap(h2_IC_crackCorr_phiNorm[0],outputFolder+"/EB_h2_IC_crackCorr_phiNorm","pdf",isEB); DrawSpreadHisto(h_spread[0], outputFolder+"/EB_h_spread", "f_EB_spread_vsEta", "png",isEB); DrawSpreadHisto(h_spread_crackCorr,outputFolder+"/EB_h_spread_crackCorr","f_EB_spread_vsEta_crackCorr","png",isEB); + DrawSpreadHisto(h_spread[0], outputFolder+"/EB_h_spread", "f_EB_spread_vsEta", "pdf",isEB); + DrawSpreadHisto(h_spread_crackCorr,outputFolder+"/EB_h_spread_crackCorr","f_EB_spread_vsEta_crackCorr","pdf",isEB); DrawSpreadGraph(g_spread_vsEta[0], outputFolder+"/EB_g_spread_vsEta", "png",isEB,g_stat_vsEta[0]); DrawSpreadGraph(g_spread_vsEta_crackCorr,outputFolder+"/EB_g_spread_vsEta_crackCorr","png",isEB,g_stat_vsEta_crackCorr); + DrawSpreadGraph(g_spread_vsEta[0], outputFolder+"/EB_g_spread_vsEta", "pdf",isEB,g_stat_vsEta[0]); + DrawSpreadGraph(g_spread_vsEta_crackCorr,outputFolder+"/EB_g_spread_vsEta_crackCorr","pdf",isEB,g_stat_vsEta_crackCorr); DrawResidualGraph(g_residual_vsEta[0], outputFolder+"/EB_g_residual_vsEta", "png",isEB); DrawResidualGraph(g_residual_vsEta_crackCorr,outputFolder+"/EB_g_residual_vsEta_crackCorr","png",isEB); + DrawResidualGraph(g_residual_vsEta[0], outputFolder+"/EB_g_residual_vsEta", "pdf",isEB); + DrawResidualGraph(g_residual_vsEta_crackCorr,outputFolder+"/EB_g_residual_vsEta_crackCorr","pdf",isEB); DrawPhiAvgICSpread(h_phiAvgICSpread[0], outputFolder+"/EB_h_phiAvgICSpread", "png",isEB); DrawPhiAvgICSpread(h_phiAvgICSpread_crackCorr,outputFolder+"/EB_h_phiAvgICSpread_crackCorr","png",isEB); + DrawPhiAvgICSpread(h_phiAvgICSpread[0], outputFolder+"/EB_h_phiAvgICSpread", "pdf",isEB); + DrawPhiAvgICSpread(h_phiAvgICSpread_crackCorr,outputFolder+"/EB_h_phiAvgICSpread_crackCorr","pdf",isEB); DrawAvgICVsPhiGraph(g_avgIC_vsPhi[0], outputFolder+"/EB_g_avgIC_vsPhi", "png",kRed+2, isEB); DrawAvgICVsPhiGraph(g_avgIC_vsPhi_crackCorr,outputFolder+"/EB_g_avgIC_vsPhi_crackCorr","png",kGreen+2,isEB); + DrawAvgICVsPhiGraph(g_avgIC_vsPhi[0], outputFolder+"/EB_g_avgIC_vsPhi", "pdf",kRed+2, isEB); + DrawAvgICVsPhiGraph(g_avgIC_vsPhi_crackCorr,outputFolder+"/EB_g_avgIC_vsPhi_crackCorr","pdf",kGreen+2,isEB); DrawAvgICVsPhiFoldGraph(g_avgIC_vsPhiFold_EBM,g_avgIC_vsPhiFold_crackCorr_EBM,outputFolder+"/EBM_g_avgIC_vsPhiFold","png",isEB); DrawAvgICVsPhiFoldGraph(g_avgIC_vsPhiFold_EBP,g_avgIC_vsPhiFold_crackCorr_EBP,outputFolder+"/EBP_g_avgIC_vsPhiFold","png",isEB); + DrawAvgICVsPhiFoldGraph(g_avgIC_vsPhiFold_EBM,g_avgIC_vsPhiFold_crackCorr_EBM,outputFolder+"/EBM_g_avgIC_vsPhiFold","pdf",isEB); + DrawAvgICVsPhiFoldGraph(g_avgIC_vsPhiFold_EBP,g_avgIC_vsPhiFold_crackCorr_EBP,outputFolder+"/EBP_g_avgIC_vsPhiFold","pdf",isEB); } else { DrawICMap(h2_IC_raw_phiNorm[-1],outputFolder+"/EEM_h2_IC_raw_phiNorm","png",isEB); DrawICMap(h2_IC_raw_phiNorm[+1],outputFolder+"/EEP_h2_IC_raw_phiNorm","png",isEB); + DrawICMap(h2_IC_raw_phiNorm[-1],outputFolder+"/EEM_h2_IC_raw_phiNorm","pdf",isEB); + DrawICMap(h2_IC_raw_phiNorm[+1],outputFolder+"/EEP_h2_IC_raw_phiNorm","pdf",isEB); + + // DrawICMap(h2_corrP[-1],outputFolder+"/EEM_h2_corrP","png",isEB); + // DrawICMap(h2_corrP[+1],outputFolder+"/EEP_h2_corrP","png",isEB); + + // DrawICMap(h2_IC_corr[-1],outputFolder+"/EEM_h2_IC_corr","png",isEB); + //DrawICMap(h2_IC_corr[+1],outputFolder+"/EEP_h2_IC_corr","png",isEB); DrawSpreadHisto(h_spread[-1],outputFolder+"/EEM_h_spread","f_EE_spread_vsEta_EEM","png",isEB); DrawSpreadHisto(h_spread[0], outputFolder+"/EE_h_spread","f_EE_spread_vsEta_EE", "png",isEB); DrawSpreadHisto(h_spread[+1],outputFolder+"/EEP_h_spread","f_EE_spread_vsEta_EEP","png",isEB); + DrawSpreadHisto(h_spread[-1],outputFolder+"/EEM_h_spread","f_EE_spread_vsEta_EEM","pdf",isEB); + DrawSpreadHisto(h_spread[0], outputFolder+"/EE_h_spread","f_EE_spread_vsEta_EE", "pdf",isEB); + DrawSpreadHisto(h_spread[+1],outputFolder+"/EEP_h_spread","f_EE_spread_vsEta_EEP","pdf",isEB); DrawSpreadGraph(g_spread_vsEta[-1],outputFolder+"/EEM_g_spread_vsEta","png",isEB,g_stat_vsEta[-1]); DrawSpreadGraph(g_spread_vsEta[0], outputFolder+"/EE_g_spread_vsEta","png",isEB,g_stat_vsEta[0]); DrawSpreadGraph(g_spread_vsEta[+1],outputFolder+"/EEP_g_spread_vsEta","png",isEB,g_stat_vsEta[+1]); + DrawSpreadGraph(g_spread_vsEta[-1],outputFolder+"/EEM_g_spread_vsEta","pdf",isEB,g_stat_vsEta[-1]); + DrawSpreadGraph(g_spread_vsEta[0], outputFolder+"/EE_g_spread_vsEta","pdf",isEB,g_stat_vsEta[0]); + DrawSpreadGraph(g_spread_vsEta[+1],outputFolder+"/EEP_g_spread_vsEta","pdf",isEB,g_stat_vsEta[+1]); DrawResidualGraph(g_residual_vsEta[-1],outputFolder+"/EEM_g_residual_vsEta","png",isEB); DrawResidualGraph(g_residual_vsEta[0], outputFolder+"/EE_g_residual_vsEta","png",isEB); DrawResidualGraph(g_residual_vsEta[+1],outputFolder+"/EEP_g_residual_vsEta","png",isEB); + DrawResidualGraph(g_residual_vsEta[-1],outputFolder+"/EEM_g_residual_vsEta","pdf",isEB); + DrawResidualGraph(g_residual_vsEta[0], outputFolder+"/EE_g_residual_vsEta","pdf",isEB); + DrawResidualGraph(g_residual_vsEta[+1],outputFolder+"/EEP_g_residual_vsEta","pdf",isEB); DrawPhiAvgICSpread(h_phiAvgICSpread[-1],outputFolder+"/EEM_h_phiAvgICSpread","png",isEB); DrawPhiAvgICSpread(h_phiAvgICSpread[+1],outputFolder+"/EEP_h_phiAvgICSpread","png",isEB); + DrawPhiAvgICSpread(h_phiAvgICSpread[-1],outputFolder+"/EEM_h_phiAvgICSpread","pdf",isEB); + DrawPhiAvgICSpread(h_phiAvgICSpread[+1],outputFolder+"/EEP_h_phiAvgICSpread","pdf",isEB); DrawAvgICVsPhiGraph(g_avgIC_vsPhi[-1],outputFolder+"/EEM_g_avgIC_vsPhi","png",kRed+2,isEB); DrawAvgICVsPhiGraph(g_avgIC_vsPhi[+1],outputFolder+"/EEP_g_avgIC_vsPhi","png",kRed+2,isEB); + DrawAvgICVsPhiGraph(g_avgIC_vsPhi[-1],outputFolder+"/EEM_g_avgIC_vsPhi","pdf",kRed+2,isEB); + DrawAvgICVsPhiGraph(g_avgIC_vsPhi[+1],outputFolder+"/EEP_g_avgIC_vsPhi","pdf",kRed+2,isEB); } outFile -> Close(); @@ -835,7 +908,7 @@ int main(int argc, char **argv) << std::fixed << std::setprecision(0) << std::setw(10) << h2_final[iz]->GetYaxis()->GetBinLowEdge(iy) << std::fixed << std::setprecision(0) << std::setw(10) << iz << std::fixed << std::setprecision(6) << std::setw(15) << IC - << std::fixed << std::setprecision(6) << std::setw(15) << sqrt( statPrec*statPrec + sysPrec*sysPrec ) + << std::fixed << std::setprecision(6) << std::setw(15) << sqrt( statPrec*statPrec )//+ sysPrec*sysPrec ) << std::endl; } else diff --git a/EOverPCalibration/bin/CompareICSet.cpp b/EOverPCalibration/bin/CompareICSet.cpp index bdffc82cc49..855d4772d04 100644 --- a/EOverPCalibration/bin/CompareICSet.cpp +++ b/EOverPCalibration/bin/CompareICSet.cpp @@ -48,7 +48,9 @@ if(!File2.is_open()){ return -1; } - + std::ofstream FileRatio("ratio.txt"); + std::ofstream FileAbsolute("absolute.txt"); + std::ofstream FileMiscalib("miscalib.txt"); // Set style options /*gROOT->Reset(); @@ -58,8 +60,10 @@ gROOT->SetStyle("Plain"); gStyle->SetPadTickX(1); gStyle->SetPadTickY(1); gStyle->SetOptTitle(1); -gStyle->SetOptStat(1111111); -gStyle->SetFitFormat("6.3g"); +gStyle->SetOptStat(00000000); +gStyle->SetOptFit(1111); +//gStyle->SetOptStat(0000000); +//gStyle->SetFitFormat("6.3g"); gStyle->SetPalette(1); gStyle->SetOptTitle(0); @@ -123,14 +127,14 @@ std::cout<<" End second file "<> iEta1 >> iPhi1 >> iz1 >> ic1 >> eic1 ; File4 >> iEta2 >> iPhi2 >> iz2 >> ic2 >> eic2; - if (ic1!=ic2) - std::cout<<"iEta: "<Clone("ratiomapEEm"); ratiomap_EEm->Reset(); +Name = Form("absolutemapEB"); +TH2F * absolutemap_EB = (TH2F*) map1_EB->Clone("absolutemapEB"); +absolutemap_EB->Reset(); + +Name = Form("absolutemapEEp"); +TH2F * absolutemap_EEp = (TH2F*) map1_EEp->Clone("absolutemapEEp"); +absolutemap_EEp->Reset(); + +Name = Form("absolutemapEEm"); +TH2F * absolutemap_EEm = (TH2F*) map1_EEm->Clone("absolutemapEEm"); +absolutemap_EEm->Reset(); + Name = Form("diffHistEB"); -TH1F * diffHistEB = new TH1F(Name,Name,100,-0.6,0.6); +TH1F * diffHistEB = new TH1F(Name,Name,500,-0.3,0.3); diffHistEB->SetLineWidth(2); +Name = Form("diffHistEB_0_20"); +TH1F * diffHistEB_0_20 = new TH1F(Name,Name,200,-1,1); +diffHistEB_0_20->SetLineWidth(2); + +Name = Form("diffHistEB_20_40"); +TH1F * diffHistEB_20_40 = new TH1F(Name,Name,200,-1,1); +diffHistEB_20_40->SetLineWidth(2); + +Name = Form("diffHistEB_40_60"); +TH1F * diffHistEB_40_60 = new TH1F(Name,Name,200,-1,1); +diffHistEB_40_60->SetLineWidth(2); + +Name = Form("diffHistEB_60_85"); +TH1F * diffHistEB_60_85 = new TH1F(Name,Name,200,-1,1); +diffHistEB_60_85->SetLineWidth(2); + Name = Form("diffHistEEp"); -TH1F * diffHistEEp = new TH1F(Name,Name,100,-0.6,0.6); +TH1F * diffHistEEp = new TH1F(Name,Name,100,-0.4,0.4); diffHistEEp->SetLineWidth(2); +Name = Form("diffHistEEp_0_5"); +TH1F * diffHistEEp_0_5 = new TH1F(Name,Name,50,-1,1); +diffHistEEp_0_5->SetLineWidth(2); + +Name = Form("diffHistEEp_5_15"); +TH1F * diffHistEEp_5_15 = new TH1F(Name,Name,50,-1,1); +diffHistEEp_5_15->SetLineWidth(2); + +Name = Form("diffHistEEp_15_25"); +TH1F * diffHistEEp_15_25 = new TH1F(Name,Name,50,-1,1); +diffHistEEp_15_25->SetLineWidth(2); + +Name = Form("diffHistEEp_25_35"); +TH1F * diffHistEEp_25_35 = new TH1F(Name,Name,50,-1,1); +diffHistEEp_25_35->SetLineWidth(2); + Name = Form("diffHistEEm"); -TH1F * diffHistEEm = new TH1F(Name,Name,100,-0.6,0.6); +TH1F * diffHistEEm = new TH1F(Name,Name,100,-0.4,0.4); diffHistEEm->SetLineWidth(2); +Name = Form("diffHistEEm_0_5"); +TH1F * diffHistEEm_0_5 = new TH1F(Name,Name,50,-1,1); +diffHistEEm_0_5->SetLineWidth(2); + +Name = Form("diffHistEEm_5_15"); +TH1F * diffHistEEm_5_15 = new TH1F(Name,Name,50,-1,1); +diffHistEEm_5_15->SetLineWidth(2); + +Name = Form("diffHistEEm_15_25"); +TH1F * diffHistEEm_15_25 = new TH1F(Name,Name,50,-1,1); +diffHistEEm_15_25->SetLineWidth(2); + +Name = Form("diffHistEEm_25_35"); +TH1F * diffHistEEm_25_35 = new TH1F(Name,Name,50,-1,1); +diffHistEEm_25_35->SetLineWidth(2); + + Name = Form("correlationEB"); -TH2F * correlationEB = new TH2F(Name,Name,100,0.2,2.,100,0.2,2.); +TH2F * correlationEB = new TH2F(Name,Name,100,0.9,1.1,100,0.9,1.1); Name = Form("correlationEEp"); -TH2F * correlationEEp= new TH2F(Name,Name,100,0.2,2.,100,0.2,2.); +TH2F * correlationEEp= new TH2F(Name,Name,100,0.8,1.2,100,0.8,1.2); Name = Form("correlationEEm"); -TH2F * correlationEEm= new TH2F(Name,Name,100,0.2,2.,100,0.2,2.); +TH2F * correlationEEm= new TH2F(Name,Name,100,0.8,1.2,100,0.8,1.2); + +TEndcapRings *eRings = new TEndcapRings(); + float sumEB=0, sum2EB=0; + float sumEEp=0, sum2EEp=0; + float sumEEm=0, sum2EEm=0; + float sumEB_0_20=0, sum2EB_0_20=0; + float sumEB_20_40=0, sum2EB_20_40=0; + float sumEB_40_60=0, sum2EB_40_60=0; + float sumEB_60_85=0, sum2EB_60_85=0; + float sumEEp_0_5=0, sum2EEp_0_5=0; + float sumEEp_5_15=0, sum2EEp_5_15=0; + float sumEEp_15_25=0, sum2EEp_15_25=0; + float sumEEp_25_35=0, sum2EEp_25_35=0; + float sumEEm_0_5=0, sum2EEm_0_5=0; + float sumEEm_5_15=0, sum2EEm_5_15=0; + float sumEEm_15_25=0, sum2EEm_15_25=0; + float sumEEm_25_35=0, sum2EEm_25_35=0; -for(int iPhi =1; iPhiGetNbinsX()+1; iPhi++){ for(int iEta=1; iEtaGetNbinsY()+1; iEta++){ + if (iEta==86) continue; + for(int iPhi =1; iPhiGetNbinsX()+1; iPhi++){ + int eta = iEta-86; if(map1_EB->GetBinContent(iPhi,iEta)==-1. || map2_EB->GetBinContent(iPhi,iEta)==-1.){ diffmap_EB->SetBinContent(iPhi,iEta,-1.); ratiomap_EB->SetBinContent(iPhi,iEta,-1.); + absolutemap_EB->SetBinContent(iPhi,iEta,map1_EB->GetBinContent(iPhi,iEta)); + FileRatio << eta << "\t" << iPhi << "\t" << 0 << "\t" << -1. << "\t" << -999. << std::endl; + FileAbsolute << eta << "\t" << iPhi << "\t" << 0 << "\t" << map1_EB->GetBinContent(iPhi,iEta) << "\t" << -999. << std::endl; + FileMiscalib << eta << "\t" << iPhi << "\t" << 0 << "\t" << map1_EB->GetBinContent(iPhi,iEta) << "\t" << -999. << std::endl; + continue;} + sumEB+=map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta); + sum2EB+=(map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta))*(map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta)); + if (abs(eta)<20) { + sumEB_0_20+=map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta); + sum2EB_0_20+=(map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta))*(map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta)); + diffHistEB_0_20->Fill(map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta)); + } + else if (abs(eta)<40) { + sumEB_20_40+=map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta); + sum2EB_20_40+=(map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta))*(map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta)); + diffHistEB_20_40->Fill(map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta)); + } + else if (abs(eta)<60) { + sumEB_40_60+=map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta); + sum2EB_40_60+=(map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta))*(map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta)); + diffHistEB_40_60->Fill(map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta)); + } + else { + sumEB_60_85+=map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta); + sum2EB_60_85+=(map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta))*(map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta)); + diffHistEB_60_85->Fill(map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta)); + } + diffmap_EB->SetBinContent(iPhi,iEta,map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta)); diffHistEB->Fill(map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta)); ratiomap_EB->SetBinContent(iPhi,iEta,map1_EB->GetBinContent(iPhi,iEta)/map2_EB->GetBinContent(iPhi,iEta)); + absolutemap_EB->SetBinContent(iPhi,iEta,map1_EB->GetBinContent(iPhi,iEta)*map2_EB->GetBinContent(iPhi,iEta)); + FileRatio << eta << "\t" << iPhi << "\t" << 0 << "\t" << map1_EB->GetBinContent(iPhi,iEta)/map2_EB->GetBinContent(iPhi,iEta) << "\t" << -999. << std::endl; + FileAbsolute << eta << "\t" << iPhi << "\t" << 0 << "\t" << map1_EB->GetBinContent(iPhi,iEta)*map2_EB->GetBinContent(iPhi,iEta) << "\t" << -999. << std::endl; correlationEB->Fill(map1_EB->GetBinContent(iPhi,iEta),map2_EB->GetBinContent(iPhi,iEta)); + if ( (iPhi>20 && iPhi<40) || (iPhi>60 && iPhi<80) || (iPhi>100 && iPhi<120) || (iPhi>140 && iPhi<160)) + FileMiscalib << eta << "\t" << iPhi << "\t" << 0 << "\t" << map1_EB->GetBinContent(iPhi,iEta)*1.3 << "\t" << -999. << std::endl; + else if ((iPhi>200 && iPhi<240) || (iPhi>280 && iPhi<300) || (iPhi>340 && iPhi<360)) + FileMiscalib << eta << "\t" << iPhi << "\t" << 0 << "\t" << map1_EB->GetBinContent(iPhi,iEta)*0.7 << "\t" << -999. << std::endl; + else + FileMiscalib << eta << "\t" << iPhi << "\t" << 0 << "\t" << map1_EB->GetBinContent(iPhi,iEta) << "\t" << -999. << std::endl; + } } @@ -206,38 +328,219 @@ for(int iPhi =1; iPhiGetNbinsX()+1; iPhi++){ for(int ix =1; ixGetNbinsX()+1; ix++){ for(int iy=1; iyGetNbinsY()+1; iy++){ + if(map1_EEp->GetBinContent(ix,iy)==0 || map2_EEp->GetBinContent(ix,iy)==0) continue; + if(map1_EEp->GetBinContent(ix,iy)==-1. || map2_EEp->GetBinContent(ix,iy)==-1.){ diffmap_EEp->SetBinContent(ix,iy,-1.); ratiomap_EEp->SetBinContent(ix,iy,-1.); + absolutemap_EEp->SetBinContent(ix,iy,map1_EEp->GetBinContent(ix,iy)); + FileRatio << ix << "\t" << iy << "\t" << 1 << "\t" << -1. << "\t" << -999. << std::endl; + FileAbsolute << ix << "\t" << iy << "\t" << 1 << "\t" << map1_EEp->GetBinContent(ix,iy) << "\t" << -999. << std::endl; + FileMiscalib << ix << "\t" << iy << "\t" << 1 << "\t" << map1_EEp->GetBinContent(ix,iy) << "\t" << -999. << std::endl; + continue;} + sumEEp+=map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy); + sum2EEp+=(map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy))*(map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy)); + + int iEta = int(eRings->GetEndcapIeta(ix,iy,1))-86; + + if (abs(iEta)<5) { + sumEEp_0_5+=map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy); + sum2EEp_0_5+=(map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy))*(map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy)); + diffHistEEp_0_5->Fill(map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy)); + } + else if (abs(iEta)<15) { + sumEEp_5_15+=map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy); + sum2EEp_5_15+=(map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy))*(map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy)); + diffHistEEp_5_15->Fill(map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy)); + } + else if (abs(iEta)<25) { + sumEEp_15_25+=map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy); + sum2EEp_15_25+=(map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy))*(map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy)); + diffHistEEp_15_25->Fill(map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy)); + } + else { + sumEEp_25_35+=map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy); + sum2EEp_25_35+=(map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy))*(map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy)); + diffHistEEp_25_35->Fill(map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy)); + } + diffmap_EEp->SetBinContent(ix,iy,map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy)); diffHistEEp->Fill(map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy)); ratiomap_EEp->SetBinContent(ix,iy,map1_EEp->GetBinContent(ix,iy)/map2_EEp->GetBinContent(ix,iy)); + absolutemap_EEp->SetBinContent(ix,iy,map1_EEp->GetBinContent(ix,iy)*map2_EEp->GetBinContent(ix,iy)); + FileRatio << ix << "\t" << iy << "\t" << 1 << "\t" << map1_EEp->GetBinContent(ix,iy)/map2_EEp->GetBinContent(ix,iy) << "\t" << -999. << std::endl; + FileAbsolute << ix << "\t" << iy << "\t" << 1 << "\t" << map1_EEp->GetBinContent(ix,iy)*map2_EEp->GetBinContent(ix,iy) << "\t" << -999. << std::endl; correlationEEp->Fill(map1_EEp->GetBinContent(ix,iy),map2_EEp->GetBinContent(ix,iy)); + if ( (ix>20 && ix<30) || (ix>50 && ix<55) || (ix>80 && ix<90)) + FileMiscalib << ix << "\t" << iy << "\t" << 1 << "\t" << map1_EEp->GetBinContent(ix,iy)*1.3 << "\t" << -999. << std::endl; + else if ((ix>5 && ix<15) || (ix>40 && ix<45) || (ix>60 && ix<70)) + FileMiscalib << ix << "\t" << iy << "\t" << 1 << "\t" << map1_EEp->GetBinContent(ix,iy)*0.7 << "\t" << -999. << std::endl; + else + FileMiscalib << ix << "\t" << iy << "\t" << 1 << "\t" << map1_EEp->GetBinContent(ix,iy) << "\t" << -999. << std::endl; + } } + for(int ix =1; ixGetNbinsX()+1; ix++){ for(int iy=1; iyGetNbinsY()+1; iy++){ + if(map1_EEm->GetBinContent(ix,iy)==0 || map2_EEm->GetBinContent(ix,iy)==0) continue; + if(map1_EEm->GetBinContent(ix,iy)==-1. || map2_EEm->GetBinContent(ix,iy)==-1.){ diffmap_EEm->SetBinContent(ix,iy,-1.); ratiomap_EEm->SetBinContent(ix,iy,-1.); + absolutemap_EEm->SetBinContent(ix,iy,map1_EEm->GetBinContent(ix,iy)); + FileRatio << ix << "\t" << iy << "\t" << -1 << "\t" << map1_EEm->GetBinContent(ix,iy) << "\t" << -999. << std::endl; + FileAbsolute << ix << "\t" << iy << "\t" << -1 << "\t" << -1. << "\t" << -999. << std::endl; continue;} + sumEEm+=map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy); + sum2EEm+=(map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy))*(map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy)); + + int iEta = int(eRings->GetEndcapIeta(ix,iy,1))-86; + + if (abs(iEta)<5) { + sumEEm_0_5+=map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy); + sum2EEm_0_5+=(map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy))*(map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy)); + diffHistEEm_0_5->Fill(map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy)); + } + else if (abs(iEta)<15) { + sumEEm_5_15+=map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy); + sum2EEm_5_15+=(map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy))*(map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy)); + diffHistEEm_5_15->Fill(map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy)); + } + else if (abs(iEta)<25) { + sumEEm_15_25+=map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy); + sum2EEm_15_25+=(map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy))*(map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy)); + diffHistEEm_15_25->Fill(map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy)); + } + else { + sumEEm_25_35+=map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy); + sum2EEm_25_35+=(map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy))*(map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy)); + diffHistEEm_25_35->Fill(map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy)); + } + diffmap_EEm->SetBinContent(ix,iy,map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy)); diffHistEEm->Fill(map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy)); ratiomap_EEm->SetBinContent(ix,iy,map1_EEm->GetBinContent(ix,iy)/map2_EEm->GetBinContent(ix,iy)); + absolutemap_EEm->SetBinContent(ix,iy,map1_EEm->GetBinContent(ix,iy)*map2_EEm->GetBinContent(ix,iy)); + FileRatio << ix << "\t" << iy << "\t" << -1 << "\t" << map1_EEm->GetBinContent(ix,iy)/map2_EEm->GetBinContent(ix,iy) << "\t" << -999. << std::endl; + FileAbsolute << ix << "\t" << iy << "\t" << -1 << "\t" << map1_EEm->GetBinContent(ix,iy)*map2_EEm->GetBinContent(ix,iy) << "\t" << -999. << std::endl; correlationEEm->Fill(map1_EEm->GetBinContent(ix,iy),map2_EEm->GetBinContent(ix,iy)); + if ( (ix>20 && ix<30) || (ix>50 && ix<55) || (ix>80 && ix<90)) + FileMiscalib << ix << "\t" << iy << "\t" << -1 << "\t" << map1_EEm->GetBinContent(ix,iy)*1.3 << "\t" << -999. << std::endl; + else if ((ix>5 && ix<15) || (ix>40 && ix<45) || (ix>60 && ix<70)) + FileMiscalib << ix << "\t" << iy << "\t" << -1 << "\t" << map1_EEm->GetBinContent(ix,iy)*0.7 << "\t" << -999. << std::endl; + else + FileMiscalib << ix << "\t" << iy << "\t" << -1 << "\t" << map1_EEm->GetBinContent(ix,iy) << "\t" << -999. << std::endl; + } } +TF1 *fgaus2 = new TF1("fgaus2","gaus",-0.02,0.02); + + std::cout<<"FIT: "<SetParameter(1,0); +fgaus2->SetParameter(2,diffHistEB->GetRMS()); +//fgaus2->SetRange(0-0.5*diffHistEB->GetRMS(),0+0.5*diffHistEB->GetRMS()); +fgaus2->SetRange(-0.03,0.03); +fgaus2->SetLineColor(kRed); +//diffHistEB->Fit("fgaus2","QRME"); +cout<<" EB-Mean: "<GetParameter(1)<<" RMSFit: "<GetParameter(2)<GetChisquare()/fgaus2->GetNDF()<Fit("fgaus2","QRME"); +cout<<" EB_0_20-Mean: "<GetParameter(1)<<" RMSFit: "<GetParameter(2)<GetChisquare()/fgaus2->GetNDF()<Fit("fgaus2","QRME"); +cout<<" EB_20_40-Mean: "<GetParameter(1)<<" RMSFit: "<GetParameter(2)<GetChisquare()/fgaus2->GetNDF()<Fit("fgaus2","QRME"); +cout<<" EB_40_60-Mean: "<GetParameter(1)<<" RMSFit: "<GetParameter(2)<GetChisquare()/fgaus2->GetNDF()<Fit("fgaus2","QRME"); +cout<<" EB_60_85-Mean: "<GetParameter(1)<<" RMSFit: "<GetParameter(2)<GetChisquare()/fgaus2->GetNDF()<SetParameter(1,0); +fgaus2->SetParameter(2,diffHistEEp->GetRMS()); +fgaus2->SetRange(-0.1,0.08); +//fgaus2->SetRange(0-0.5*diffHistEEp->GetRMS(),0+0.5*diffHistEEp->GetRMS()); +fgaus2->SetLineColor(kRed); +//diffHistEEp->Fit("fgaus2","QRME"); +cout<<" EEp-Mean: "<GetParameter(1)<<" RMSFit: "<GetParameter(2)<GetChisquare()/fgaus2->GetNDF()<Fit("fgaus2","QRME"); +cout<<" EEp_0_5-Mean: "<GetParameter(1)<<" RMSFit: "<GetParameter(2)<GetChisquare()/fgaus2->GetNDF()<Fit("fgaus2","QRME"); +cout<<" EEp_5_15-Mean: "<GetParameter(1)<<" RMSFit: "<GetParameter(2)<GetChisquare()/fgaus2->GetNDF()<Fit("fgaus2","QRME"); +cout<<" EEp_15_25-Mean: "<GetParameter(1)<<" RMSFit: "<GetParameter(2)<GetChisquare()/fgaus2->GetNDF()<Fit("fgaus2","QRME"); +cout<<" EEp_25_35-Mean: "<GetParameter(1)<<" RMSFit: "<GetParameter(2)<GetChisquare()/fgaus2->GetNDF()<SetParameter(1,0); +fgaus2->SetParameter(2,diffHistEEm->GetRMS()); +fgaus2->SetRange(-0.1,0.08); +//fgaus2->SetRange(0-0.5*diffHistEEm->GetRMS(),0+0.5*diffHistEEm->GetRMS()); +fgaus2->SetLineColor(kRed); +fgaus2->SetLineColor(kRed); +//diffHistEEm->Fit("fgaus2","QRME"); +cout<<" EEm-Mean: "<GetParameter(1)<<" RMSFit: "<GetParameter(2)<GetChisquare()/fgaus2->GetNDF()<Fit("fgaus2","QRME"); +cout<<" EEm_0_5-Mean: "<GetParameter(1)<<" RMSFit: "<GetParameter(2)<GetChisquare()/fgaus2->GetNDF()<Fit("fgaus2","QRME"); +cout<<" EEm_5_15-Mean: "<GetParameter(1)<<" RMSFit: "<GetParameter(2)<GetChisquare()/fgaus2->GetNDF()<Fit("fgaus2","QRME"); +cout<<" EEm_15_25-Mean: "<GetParameter(1)<<" RMSFit: "<GetParameter(2)<GetChisquare()/fgaus2->GetNDF()<Fit("fgaus2","QRME"); +cout<<" EEm_25_35-Mean: "<GetParameter(1)<<" RMSFit: "<GetParameter(2)<GetChisquare()/fgaus2->GetNDF()<GetMean()<<" RMSdist "<GetRMS()<GetMean()<<" RMSdist "<GetRMS()<GetMean()<<" RMSdist "<GetRMS()<GetMean()<<" RMSdist "<GetRMS()<GetMean()<<" RMSdist "<GetRMS()<GetMean()<<" RMSdist "<GetRMS()<GetMean()<<" RMSdist "<GetRMS()<GetMean()<<" RMSdist "<GetRMS()<GetMean()<<" RMSdist "<GetRMS()<GetMean()<<" RMSdist "<GetRMS()<GetMean()<<" RMSdist "<GetRMS()<GetMean()<<" RMSdist "<GetRMS()<GetMean()<<" RMSdist "<GetRMS()<GetMean()<<" RMSdist "<GetRMS()<GetMean()<<" RMSdist "<GetRMS()<GetNbinsX()+1; iPhi++){ /// Profile along phi for EE+: -TEndcapRings *eRings = new TEndcapRings(); std::vector vectSum; std::vector vectCounter; @@ -781,7 +1083,7 @@ cout<<" Second Set : Mean dist = "<GetMean()<<" RMS dist "<SetLeftMargin(0.1); @@ -800,7 +1102,7 @@ cout<<" Second Set : Mean dist = "<GetMean()<<" RMS dist "<SetRightMargin(0.13); c[1]->SetLogy(); - diffHistEB->GetXaxis()->SetTitle("c_{#pi}-c_{ele}"); + diffHistEB->GetXaxis()->SetTitle("c_{1}-c_{2}"); diffHistEB->Draw(); @@ -824,10 +1126,11 @@ cout<<" Second Set : Mean dist = "<GetMean()<<" RMS dist "<GetXaxis()->SetNdivisions(1020); correlationEB->GetXaxis() -> SetLabelSize(0.03); - correlationEB->GetXaxis() ->SetTitle("c_{#pi}"); - correlationEB->GetYaxis() ->SetTitle("c_{ele}"); + correlationEB->GetXaxis() ->SetTitle("c_{1}"); + correlationEB->GetYaxis() ->SetTitle("c_{2}"); correlationEB->Draw("COLZ"); + std::cout<<"correlation EB: "<GetCorrelationFactor()<SetLeftMargin(0.1); @@ -846,7 +1149,7 @@ cout<<" Second Set : Mean dist = "<GetMean()<<" RMS dist "<SetRightMargin(0.13); c[5]->SetLogy(); - diffHistEEp->GetXaxis()->SetTitle("c_{#pi}-c_{ele}"); + diffHistEEp->GetXaxis()->SetTitle("c_{1}-c_{2}"); diffHistEEp->Draw(); c[6] = new TCanvas("hratioEEp","hratioEEp"); @@ -869,10 +1172,12 @@ cout<<" Second Set : Mean dist = "<GetMean()<<" RMS dist "<GetXaxis()->SetNdivisions(1020); correlationEEp->GetXaxis() -> SetLabelSize(0.03); - correlationEEp->GetXaxis() ->SetTitle("c_{#pi}"); - correlationEEp->GetYaxis() ->SetTitle("c_{ele}"); + correlationEEp->GetXaxis() ->SetTitle("c_{1}"); + correlationEEp->GetYaxis() ->SetTitle("c_{2}"); correlationEEp->Draw("COLZ"); + std::cout<<"correlation EE+: "<GetCorrelationFactor()<SetLeftMargin(0.1); c[8]->SetRightMargin(0.13); @@ -890,7 +1195,7 @@ cout<<" Second Set : Mean dist = "<GetMean()<<" RMS dist "<SetRightMargin(0.13); c[9]->SetLogy(); - diffHistEEm->GetXaxis()->SetTitle("c_{#pi}-c_{ele}"); + diffHistEEm->GetXaxis()->SetTitle("c_{1}-c_{2}"); diffHistEEm->Draw(); @@ -915,10 +1220,12 @@ cout<<" Second Set : Mean dist = "<GetMean()<<" RMS dist "<GetXaxis()->SetNdivisions(1020); correlationEEm->GetXaxis() -> SetLabelSize(0.03); - correlationEEm->GetXaxis() ->SetTitle("c_{#pi}"); - correlationEEm->GetYaxis() ->SetTitle("c_{ele}"); + correlationEEm->GetXaxis() ->SetTitle("c_{1}"); + correlationEEm->GetYaxis() ->SetTitle("c_{2}"); correlationEEm->Draw("COLZ"); + std::cout<<"correlation EE-: "<GetCorrelationFactor()<SetGridx(); @@ -1132,7 +1439,133 @@ cout<<" Second Set : Mean dist = "<GetMean()<<" RMS dist "<AddEntry(phiProfileEEm2,"EE- Projection II set ", "LP"); leg12->Draw("same"); - theApp->Run(); + c[24] = new TCanvas("habsoluteEB","habsoluteEB"); + c[24]->SetLeftMargin(0.1); + c[24]->SetRightMargin(0.13); + c[24]->SetGridx(); + + absolutemap_EB->GetXaxis()->SetNdivisions(1020); + absolutemap_EB->GetXaxis() -> SetLabelSize(0.03); + absolutemap_EB->GetXaxis() ->SetTitle("i#phi"); + absolutemap_EB->GetYaxis() ->SetTitle("i#eta"); + absolutemap_EB->GetZaxis() ->SetRangeUser(0.85,1.15); + absolutemap_EB->Draw("COLZ"); + + c[25] = new TCanvas("habsoluteEEp","habsoluteEEp"); + c[25]->SetLeftMargin(0.1); + c[25]->SetRightMargin(0.13); + c[25]->SetGridx(); + + absolutemap_EEp->GetXaxis()->SetNdivisions(1020); + absolutemap_EEp->GetXaxis() -> SetLabelSize(0.03); + absolutemap_EEp->GetXaxis() ->SetTitle("ix"); + absolutemap_EEp->GetYaxis() ->SetTitle("iy"); + absolutemap_EEp->GetZaxis() ->SetRangeUser(0.7,1.3); + absolutemap_EEp->Draw("COLZ"); + + + c[26] = new TCanvas("habsoluteEEm","habsoluteEEm"); + c[26]->SetLeftMargin(0.1); + c[26]->SetRightMargin(0.13); + c[26]->SetGridx(); + + absolutemap_EEm->GetXaxis()->SetNdivisions(1020); + absolutemap_EEm->GetXaxis() -> SetLabelSize(0.03); + absolutemap_EEm->GetXaxis() ->SetTitle("ix"); + absolutemap_EEm->GetYaxis() ->SetTitle("iy"); + absolutemap_EEm->GetZaxis() ->SetRangeUser(0.7,1.3); + absolutemap_EEm->Draw("COLZ"); + + + c[27] = new TCanvas("map1_EB","map1_EB"); + c[27]->SetLeftMargin(0.1); + c[27]->SetRightMargin(0.13); + c[27]->SetGridx(); + + map1_EB->GetXaxis()->SetNdivisions(1020); + map1_EB->GetXaxis() -> SetLabelSize(0.03); + map1_EB->GetXaxis() ->SetTitle("i#phi"); + map1_EB->GetYaxis() ->SetTitle("i#eta"); + map1_EB->GetZaxis() ->SetRangeUser(0.6,1.4); + map1_EB->Draw("COLZ"); + + + c[28] = new TCanvas("map1_EEp","map1_EEp"); + c[28]->SetLeftMargin(0.1); + c[28]->SetRightMargin(0.13); + c[28]->SetGridx(); + + map1_EEp->GetXaxis()->SetNdivisions(1020); + map1_EEp->GetXaxis() -> SetLabelSize(0.03); + map1_EEp->GetXaxis() ->SetTitle("i#phi"); + map1_EEp->GetYaxis() ->SetTitle("i#eta"); + map1_EEp->GetZaxis() ->SetRangeUser(0.6,1.4); + map1_EEp->Draw("COLZ"); + + + c[29] = new TCanvas("map1_EEm","map1_EEm"); + c[29]->SetLeftMargin(0.1); + c[29]->SetRightMargin(0.13); + c[29]->SetGridx(); + + map1_EEm->GetXaxis()->SetNdivisions(1020); + map1_EEm->GetXaxis() -> SetLabelSize(0.03); + map1_EEm->GetXaxis() ->SetTitle("i#phi"); + map1_EEm->GetYaxis() ->SetTitle("i#eta"); + map1_EEm->GetZaxis() ->SetRangeUser(0.6,1.4); + map1_EEm->Draw("COLZ"); + + + c[30] = new TCanvas("map2_EB","map2_EB"); + c[30]->SetLeftMargin(0.1); + c[30]->SetRightMargin(0.13); + c[30]->SetGridx(); + + map2_EB->GetXaxis()->SetNdivisions(1020); + map2_EB->GetXaxis() -> SetLabelSize(0.03); + map2_EB->GetXaxis() ->SetTitle("i#phi"); + map2_EB->GetYaxis() ->SetTitle("i#eta"); + map2_EB->GetZaxis() ->SetRangeUser(0.6,1.4); + map2_EB->Draw("COLZ"); + + + c[31] = new TCanvas("map2_EEp","map2_EEp"); + c[31]->SetLeftMargin(0.1); + c[31]->SetRightMargin(0.13); + c[31]->SetGridx(); + + map2_EEp->GetXaxis()->SetNdivisions(1020); + map2_EEp->GetXaxis() -> SetLabelSize(0.03); + map2_EEp->GetXaxis() ->SetTitle("i#phi"); + map2_EEp->GetYaxis() ->SetTitle("i#eta"); + map2_EEp->GetZaxis() ->SetRangeUser(0.6,1.4); + map2_EEp->Draw("COLZ"); + + + c[32] = new TCanvas("map2_EEm","map2_EEm"); + c[32]->SetLeftMargin(0.1); + c[32]->SetRightMargin(0.13); + c[32]->SetGridx(); + + map2_EEm->GetXaxis()->SetNdivisions(1020); + map2_EEm->GetXaxis() -> SetLabelSize(0.03); + map2_EEm->GetXaxis() ->SetTitle("i#phi"); + map2_EEm->GetYaxis() ->SetTitle("i#eta"); + map2_EEm->GetZaxis() ->SetRangeUser(0.6,1.4); + map2_EEm->Draw("COLZ"); + + + TFile f("compareIC.root","recreate"); + f.cd(); + + for (int i=0; i<33; i++) { + c[i]->Write(); + } + + f.Write(); + // f.close(); + + // theApp->Run(); return 0; diff --git a/EOverPCalibration/bin/CompareICSet_ratio.cpp b/EOverPCalibration/bin/CompareICSet_ratio.cpp new file mode 100644 index 00000000000..a70f6aafb7e --- /dev/null +++ b/EOverPCalibration/bin/CompareICSet_ratio.cpp @@ -0,0 +1,1674 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "TStyle.h" +#include "TROOT.h" +#include "TH1F.h" +#include "TH2F.h" +#include "TFile.h" +#include "TCanvas.h" +#include "TString.h" +#include "TGraphErrors.h" +#include "../interface/TEndcapRings.h" +#include "TLegend.h" +#include "TApplication.h" + +using namespace std; + +int main (int argc, char**argv){ + +if(argc<3){ + std::cerr<<" Wrongs input "<Reset(); +gROOT->SetStyle("Plain"); +*/ + +gStyle->SetPadTickX(1); +gStyle->SetPadTickY(1); +gStyle->SetOptTitle(1); +gStyle->SetOptStat(00000000); +gStyle->SetOptFit(1111); +//gStyle->SetOptStat(0000000); +//gStyle->SetFitFormat("6.3g"); +gStyle->SetPalette(1); +gStyle->SetOptTitle(0); + + +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(); + + + + +int iPhi, iEta, iz; +double ic, eic; + +/*int iPhi1, iEta1, iz1; +double ic1, eic1; +int iPhi2, iEta2, iz2; +double ic2, eic2; +int iPhi3, iEta3, iz3; +double ic3, eic3; +int iPhi4, iEta4, iz4; +double ic4, eic4; +*/ +/// Histo for first ic set +TString Name = Form("mapEB_%s",inputFile1.c_str()); +TH2F * map1_EB = new TH2F(Name,Name,360,1, 361, 171, -85, 86); +Name = Form("mapEEp_%s",inputFile1.c_str()); +TH2F * map1_EEp = new TH2F(Name,Name,100,1, 101, 100, 1, 101); +Name = Form("mapEEm_%s",inputFile1.c_str()); +TH2F * map1_EEm = new TH2F(Name,Name,100,1, 101, 100, 1, 101); + +std::cout<<" Opening first file ..... reading "<> iEta >> iPhi >> iz >> ic >> eic ; +if(iz==0) map1_EB->Fill(iPhi,iEta,ic); +if(iz==1) map1_EEp->Fill(iEta,iPhi,ic); +if(iz==-1)map1_EEm->Fill(iEta,iPhi,ic); +} +std::cout<<" End first file "<> iEta >> iPhi >> iz >> ic >> eic ; +if(iz==0) map2_EB->Fill(iPhi,iEta,ic); +if(iz==1) map2_EEp->Fill(iEta,iPhi,ic); +if(iz==-1) map2_EEm->Fill(iEta,iPhi,ic); +} +std::cout<<" End second file "<> iEta1 >> iPhi1 >> iz1 >> ic1 >> eic1 ; + File1d >> iEta2 >> iPhi2 >> iz2 >> ic2 >> eic2; + +File2p >> iEta3 >> iPhi3 >> iz3 >> ic3 >> eic3 ; + File2d >> iEta4 >> iPhi4 >> iz4 >> ic4 >> eic4; + // if (ic1!=ic2) + // std::cout<<"iEta: "<> iEta >> iPhi >> iz >> ic >> eic ; +if(iz==0) map1p_EB->Fill(iPhi,iEta,ic); +if(iz==1) map1p_EEp->Fill(iEta,iPhi,ic); +if(iz==-1)map1p_EEm->Fill(iEta,iPhi,ic); +// std::cout<> iEta >> iPhi >> iz >> ic >> eic ; +if(iz==0) map1d_EB->Fill(iPhi,iEta,ic); +if(iz==1) map1d_EEp->Fill(iEta,iPhi,ic); +if(iz==-1)map1d_EEm->Fill(iEta,iPhi,ic); +} + + +Name = Form("mapEB_%s",inputFile2p.c_str()); +TH2F * map2p_EB = new TH2F(Name,Name,360,1, 361, 171, -85, 86); +Name = Form("mapEEp_%s",inputFile2p.c_str()); +TH2F * map2p_EEp = new TH2F(Name,Name,100,1, 101, 100, 1, 101); +Name = Form("mapEEm_%s",inputFile2p.c_str()); +TH2F * map2p_EEm = new TH2F(Name,Name,100,1, 101, 100, 1, 101); + +std::cout<<" Opening first file ..... reading "<> iEta >> iPhi >> iz >> ic >> eic ; +if(iz==0) map2p_EB->Fill(iPhi,iEta,ic); +if(iz==1) map2p_EEp->Fill(iEta,iPhi,ic); +if(iz==-1)map2p_EEm->Fill(iEta,iPhi,ic); +} +std::cout<<" End first file "<> iEta >> iPhi >> iz >> ic >> eic ; +if(iz==0) map2d_EB->Fill(iPhi,iEta,ic); +if(iz==1) map2d_EEp->Fill(iEta,iPhi,ic); +if(iz==-1)map2d_EEm->Fill(iEta,iPhi,ic); +} + + + // TApplication* theApp = new TApplication("Application",&argc, argv); + + + +/// Set of two ic sets + +Name = Form("diffmapEB"); +TH2F * diffmap_EB = (TH2F*) map1_EB->Clone("diffmapEB"); +diffmap_EB->Reset(); + +Name = Form("diffmapEEp"); +TH2F * diffmap_EEp = (TH2F*) map1_EEp->Clone("diffmapEEp"); +diffmap_EEp->Reset(); + +Name = Form("diffmapEEm"); +TH2F * diffmap_EEm = (TH2F*) map1_EEm->Clone("diffmapEEm"); +diffmap_EEm->Reset(); + +Name = Form("ratiomapEB"); +TH2F * ratiomap_EB = (TH2F*) map1_EB->Clone("ratiomapEB"); +ratiomap_EB->Reset(); + +Name = Form("ratiomapEEp"); +TH2F * ratiomap_EEp = (TH2F*) map1_EEp->Clone("ratiomapEEp"); +ratiomap_EEp->Reset(); + +Name = Form("ratiomapEEm"); +TH2F * ratiomap_EEm = (TH2F*) map1_EEm->Clone("ratiomapEEm"); +ratiomap_EEm->Reset(); + +Name = Form("absolutemapEB"); +TH2F * absolutemap_EB = (TH2F*) map1_EB->Clone("absolutemapEB"); +absolutemap_EB->Reset(); + +Name = Form("absolutemapEEp"); +TH2F * absolutemap_EEp = (TH2F*) map1_EEp->Clone("absolutemapEEp"); +absolutemap_EEp->Reset(); + +Name = Form("absolutemapEEm"); +TH2F * absolutemap_EEm = (TH2F*) map1_EEm->Clone("absolutemapEEm"); +absolutemap_EEm->Reset(); + +Name = Form("diffHistEB"); +TH1F * diffHistEB = new TH1F(Name,Name,500,0.9,1.1); +diffHistEB->SetLineWidth(2); + +Name = Form("diffHistEB_0_20"); +TH1F * diffHistEB_0_20 = new TH1F(Name,Name,200,-1,1); +diffHistEB_0_20->SetLineWidth(2); + +Name = Form("diffHistEB_20_40"); +TH1F * diffHistEB_20_40 = new TH1F(Name,Name,200,-1,1); +diffHistEB_20_40->SetLineWidth(2); + +Name = Form("diffHistEB_40_60"); +TH1F * diffHistEB_40_60 = new TH1F(Name,Name,200,-1,1); +diffHistEB_40_60->SetLineWidth(2); + +Name = Form("diffHistEB_60_85"); +TH1F * diffHistEB_60_85 = new TH1F(Name,Name,200,-1,1); +diffHistEB_60_85->SetLineWidth(2); + +Name = Form("diffHistEEp"); +TH1F * diffHistEEp = new TH1F(Name,Name,200,0.8,1.2); +diffHistEEp->SetLineWidth(2); + +Name = Form("diffHistEEp_0_5"); +TH1F * diffHistEEp_0_5 = new TH1F(Name,Name,50,-1,1); +diffHistEEp_0_5->SetLineWidth(2); + +Name = Form("diffHistEEp_5_15"); +TH1F * diffHistEEp_5_15 = new TH1F(Name,Name,50,-1,1); +diffHistEEp_5_15->SetLineWidth(2); + +Name = Form("diffHistEEp_15_25"); +TH1F * diffHistEEp_15_25 = new TH1F(Name,Name,50,-1,1); +diffHistEEp_15_25->SetLineWidth(2); + +Name = Form("diffHistEEp_25_35"); +TH1F * diffHistEEp_25_35 = new TH1F(Name,Name,50,-1,1); +diffHistEEp_25_35->SetLineWidth(2); + +Name = Form("diffHistEEm"); +TH1F * diffHistEEm = new TH1F(Name,Name,200,0.8,1.2); +diffHistEEm->SetLineWidth(2); + +Name = Form("diffHistEEm_0_5"); +TH1F * diffHistEEm_0_5 = new TH1F(Name,Name,50,-1,1); +diffHistEEm_0_5->SetLineWidth(2); + +Name = Form("diffHistEEm_5_15"); +TH1F * diffHistEEm_5_15 = new TH1F(Name,Name,50,-1,1); +diffHistEEm_5_15->SetLineWidth(2); + +Name = Form("diffHistEEm_15_25"); +TH1F * diffHistEEm_15_25 = new TH1F(Name,Name,50,-1,1); +diffHistEEm_15_25->SetLineWidth(2); + +Name = Form("diffHistEEm_25_35"); +TH1F * diffHistEEm_25_35 = new TH1F(Name,Name,50,-1,1); +diffHistEEm_25_35->SetLineWidth(2); + + +Name = Form("correlationEB"); +TH2F * correlationEB = new TH2F(Name,Name,100,0.9,1.1,100,0.9,1.1); + +Name = Form("correlationEEp"); +TH2F * correlationEEp= new TH2F(Name,Name,100,0.8,1.2,100,0.8,1.2); + +Name = Form("correlationEEm"); +TH2F * correlationEEm= new TH2F(Name,Name,100,0.8,1.2,100,0.8,1.2); + +TEndcapRings *eRings = new TEndcapRings(); + + + float sumEB=0, sum2EB=0; + float sumEEp=0, sum2EEp=0; + float sumEEm=0, sum2EEm=0; + + float sumEB_0_20=0, sum2EB_0_20=0; + float sumEB_20_40=0, sum2EB_20_40=0; + float sumEB_40_60=0, sum2EB_40_60=0; + float sumEB_60_85=0, sum2EB_60_85=0; + + float sumEEp_0_5=0, sum2EEp_0_5=0; + float sumEEp_5_15=0, sum2EEp_5_15=0; + float sumEEp_15_25=0, sum2EEp_15_25=0; + float sumEEp_25_35=0, sum2EEp_25_35=0; + + float sumEEm_0_5=0, sum2EEm_0_5=0; + float sumEEm_5_15=0, sum2EEm_5_15=0; + float sumEEm_15_25=0, sum2EEm_15_25=0; + float sumEEm_25_35=0, sum2EEm_25_35=0; + + for(int iEta=1; iEtaGetNbinsY()+1; iEta++){ + if (iEta==86) continue; + for(int iPhi =1; iPhiGetNbinsX()+1; iPhi++){ + + int eta = iEta-86; + if(map1_EB->GetBinContent(iPhi,iEta)==-1. || map2_EB->GetBinContent(iPhi,iEta)==-1.){ + diffmap_EB->SetBinContent(iPhi,iEta,-1.); + ratiomap_EB->SetBinContent(iPhi,iEta,-1.); + absolutemap_EB->SetBinContent(iPhi,iEta,map1_EB->GetBinContent(iPhi,iEta)); + FileRatio << eta << "\t" << iPhi << "\t" << 0 << "\t" << -1. << "\t" << -999. << std::endl; + FileAbsolute << eta << "\t" << iPhi << "\t" << 0 << "\t" << map1_EB->GetBinContent(iPhi,iEta) << "\t" << -999. << std::endl; + FileMiscalib << eta << "\t" << iPhi << "\t" << 0 << "\t" << map1_EB->GetBinContent(iPhi,iEta) << "\t" << -999. << std::endl; + + continue;} + + sumEB+=map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta); + sum2EB+=(map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta))*(map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta)); + if (abs(eta)<20) { + sumEB_0_20+=map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta); + sum2EB_0_20+=(map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta))*(map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta)); + diffHistEB_0_20->Fill(map1_EB->GetBinContent(iPhi,iEta)/map2_EB->GetBinContent(iPhi,iEta)); + } + else if (abs(eta)<40) { + sumEB_20_40+=map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta); + sum2EB_20_40+=(map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta))*(map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta)); + diffHistEB_20_40->Fill(map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta)); + } + else if (abs(eta)<60) { + sumEB_40_60+=map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta); + sum2EB_40_60+=(map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta))*(map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta)); + diffHistEB_40_60->Fill(map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta)); + } + else { + sumEB_60_85+=map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta); + sum2EB_60_85+=(map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta))*(map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta)); + diffHistEB_60_85->Fill(map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta)); + } + + diffmap_EB->SetBinContent(iPhi,iEta,map1_EB->GetBinContent(iPhi,iEta)-map2_EB->GetBinContent(iPhi,iEta)); + diffHistEB->Fill(map1_EB->GetBinContent(iPhi,iEta)/map2_EB->GetBinContent(iPhi,iEta)); + ratiomap_EB->SetBinContent(iPhi,iEta,map1_EB->GetBinContent(iPhi,iEta)/map2_EB->GetBinContent(iPhi,iEta)); + absolutemap_EB->SetBinContent(iPhi,iEta,map1_EB->GetBinContent(iPhi,iEta)*map2_EB->GetBinContent(iPhi,iEta)); + FileRatio << eta << "\t" << iPhi << "\t" << 0 << "\t" << map1_EB->GetBinContent(iPhi,iEta)/map2_EB->GetBinContent(iPhi,iEta) << "\t" << + abs(map1p_EB->GetBinContent(iPhi,iEta)/map2p_EB->GetBinContent(iPhi,iEta) - map1d_EB->GetBinContent(iPhi,iEta)/map2d_EB->GetBinContent(iPhi,iEta))/ + (map1p_EB->GetBinContent(iPhi,iEta)/map2p_EB->GetBinContent(iPhi,iEta) + map1d_EB->GetBinContent(iPhi,iEta)/map2d_EB->GetBinContent(iPhi,iEta))<< std::endl; + FileAbsolute << eta << "\t" << iPhi << "\t" << 0 << "\t" << map1_EB->GetBinContent(iPhi,iEta)*map2_EB->GetBinContent(iPhi,iEta) << "\t" << -999. << std::endl; + correlationEB->Fill(map1_EB->GetBinContent(iPhi,iEta),map2_EB->GetBinContent(iPhi,iEta)); + + if ( (iPhi>20 && iPhi<40) || (iPhi>60 && iPhi<80) || (iPhi>100 && iPhi<120) || (iPhi>140 && iPhi<160)) + FileMiscalib << eta << "\t" << iPhi << "\t" << 0 << "\t" << map1_EB->GetBinContent(iPhi,iEta)*1.3 << "\t" << -999. << std::endl; + else if ((iPhi>200 && iPhi<240) || (iPhi>280 && iPhi<300) || (iPhi>340 && iPhi<360)) + FileMiscalib << eta << "\t" << iPhi << "\t" << 0 << "\t" << map1_EB->GetBinContent(iPhi,iEta)*0.7 << "\t" << -999. << std::endl; + else + FileMiscalib << eta << "\t" << iPhi << "\t" << 0 << "\t" << map1_EB->GetBinContent(iPhi,iEta) << "\t" << -999. << std::endl; + + } +} + + +for(int ix =1; ixGetNbinsX()+1; ix++){ + for(int iy=1; iyGetNbinsY()+1; iy++){ + + if(map1_EEp->GetBinContent(ix,iy)==0 || map2_EEp->GetBinContent(ix,iy)==0) continue; + + if(map1_EEp->GetBinContent(ix,iy)==-1. || map2_EEp->GetBinContent(ix,iy)==-1.){ + diffmap_EEp->SetBinContent(ix,iy,-1.); + ratiomap_EEp->SetBinContent(ix,iy,-1.); + absolutemap_EEp->SetBinContent(ix,iy,map1_EEp->GetBinContent(ix,iy)); + FileRatio << ix << "\t" << iy << "\t" << 1 << "\t" << -1. << "\t" << -999. << std::endl; + FileAbsolute << ix << "\t" << iy << "\t" << 1 << "\t" << map1_EEp->GetBinContent(ix,iy) << "\t" << -999. << std::endl; + FileMiscalib << ix << "\t" << iy << "\t" << 1 << "\t" << map1_EEp->GetBinContent(ix,iy) << "\t" << -999. << std::endl; + + continue;} + + sumEEp+=map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy); + sum2EEp+=(map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy))*(map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy)); + + int iEta = int(eRings->GetEndcapIeta(ix,iy,1))-86; + + if (abs(iEta)<5) { + sumEEp_0_5+=map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy); + sum2EEp_0_5+=(map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy))*(map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy)); + diffHistEEp_0_5->Fill(map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy)); + } + else if (abs(iEta)<15) { + sumEEp_5_15+=map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy); + sum2EEp_5_15+=(map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy))*(map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy)); + diffHistEEp_5_15->Fill(map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy)); + } + else if (abs(iEta)<25) { + sumEEp_15_25+=map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy); + sum2EEp_15_25+=(map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy))*(map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy)); + diffHistEEp_15_25->Fill(map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy)); + } + else { + sumEEp_25_35+=map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy); + sum2EEp_25_35+=(map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy))*(map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy)); + diffHistEEp_25_35->Fill(map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy)); + } + + diffmap_EEp->SetBinContent(ix,iy,map1_EEp->GetBinContent(ix,iy)-map2_EEp->GetBinContent(ix,iy)); + diffHistEEp->Fill(map1_EEp->GetBinContent(ix,iy)/map2_EEp->GetBinContent(ix,iy)); + ratiomap_EEp->SetBinContent(ix,iy,map1_EEp->GetBinContent(ix,iy)/map2_EEp->GetBinContent(ix,iy)); + absolutemap_EEp->SetBinContent(ix,iy,map1_EEp->GetBinContent(ix,iy)*map2_EEp->GetBinContent(ix,iy)); + FileRatio << ix << "\t" << iy << "\t" << 1 << "\t" << map1_EEp->GetBinContent(ix,iy)/map2_EEp->GetBinContent(ix,iy) << "\t" << + abs(map1p_EEp->GetBinContent(iPhi,iEta)/map2p_EEp->GetBinContent(iPhi,iEta) - map1d_EEp->GetBinContent(iPhi,iEta)/map2d_EEp->GetBinContent(iPhi,iEta))/ + (map1p_EEp->GetBinContent(iPhi,iEta)/map2p_EEp->GetBinContent(iPhi,iEta) + map1d_EEp->GetBinContent(iPhi,iEta)/map2d_EEp->GetBinContent(iPhi,iEta))<< std::endl; + FileAbsolute << ix << "\t" << iy << "\t" << 1 << "\t" << map1_EEp->GetBinContent(ix,iy)*map2_EEp->GetBinContent(ix,iy) << "\t" << -999. << std::endl; + correlationEEp->Fill(map1_EEp->GetBinContent(ix,iy),map2_EEp->GetBinContent(ix,iy)); + + if ( (ix>20 && ix<30) || (ix>50 && ix<55) || (ix>80 && ix<90)) + FileMiscalib << ix << "\t" << iy << "\t" << 1 << "\t" << map1_EEp->GetBinContent(ix,iy)*1.3 << "\t" << -999. << std::endl; + else if ((ix>5 && ix<15) || (ix>40 && ix<45) || (ix>60 && ix<70)) + FileMiscalib << ix << "\t" << iy << "\t" << 1 << "\t" << map1_EEp->GetBinContent(ix,iy)*0.7 << "\t" << -999. << std::endl; + else + FileMiscalib << ix << "\t" << iy << "\t" << 1 << "\t" << map1_EEp->GetBinContent(ix,iy) << "\t" << -999. << std::endl; + + } +} + + + +for(int ix =1; ixGetNbinsX()+1; ix++){ + for(int iy=1; iyGetNbinsY()+1; iy++){ + + if(map1_EEm->GetBinContent(ix,iy)==0 || map2_EEm->GetBinContent(ix,iy)==0) continue; + + if(map1_EEm->GetBinContent(ix,iy)==-1. || map2_EEm->GetBinContent(ix,iy)==-1.){ + diffmap_EEm->SetBinContent(ix,iy,-1.); + ratiomap_EEm->SetBinContent(ix,iy,-1.); + absolutemap_EEm->SetBinContent(ix,iy,map1_EEm->GetBinContent(ix,iy)); + FileRatio << ix << "\t" << iy << "\t" << -1 << "\t" << map1_EEm->GetBinContent(ix,iy) << "\t" << -999. << std::endl; + FileAbsolute << ix << "\t" << iy << "\t" << -1 << "\t" << -1. << "\t" << -999. << std::endl; + continue;} + + sumEEm+=map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy); + sum2EEm+=(map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy))*(map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy)); + + int iEta = int(eRings->GetEndcapIeta(ix,iy,1))-86; + + if (abs(iEta)<5) { + sumEEm_0_5+=map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy); + sum2EEm_0_5+=(map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy))*(map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy)); + diffHistEEm_0_5->Fill(map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy)); + } + else if (abs(iEta)<15) { + sumEEm_5_15+=map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy); + sum2EEm_5_15+=(map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy))*(map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy)); + diffHistEEm_5_15->Fill(map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy)); + } + else if (abs(iEta)<25) { + sumEEm_15_25+=map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy); + sum2EEm_15_25+=(map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy))*(map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy)); + diffHistEEm_15_25->Fill(map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy)); + } + else { + sumEEm_25_35+=map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy); + sum2EEm_25_35+=(map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy))*(map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy)); + diffHistEEm_25_35->Fill(map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy)); + } + + diffmap_EEm->SetBinContent(ix,iy,map1_EEm->GetBinContent(ix,iy)-map2_EEm->GetBinContent(ix,iy)); + diffHistEEm->Fill(map1_EEm->GetBinContent(ix,iy)/map2_EEm->GetBinContent(ix,iy)); + ratiomap_EEm->SetBinContent(ix,iy,map1_EEm->GetBinContent(ix,iy)/map2_EEm->GetBinContent(ix,iy)); + absolutemap_EEm->SetBinContent(ix,iy,map1_EEm->GetBinContent(ix,iy)*map2_EEm->GetBinContent(ix,iy)); + FileRatio << ix << "\t" << iy << "\t" << -1 << "\t" << map1_EEm->GetBinContent(ix,iy)/map2_EEm->GetBinContent(ix,iy) << "\t" << + abs(map1p_EEm->GetBinContent(iPhi,iEta)/map2p_EEm->GetBinContent(iPhi,iEta) - map1d_EEm->GetBinContent(iPhi,iEta)/map2d_EEm->GetBinContent(iPhi,iEta))/ + (map1p_EEm->GetBinContent(iPhi,iEta)/map2p_EEm->GetBinContent(iPhi,iEta) + map1d_EEm->GetBinContent(iPhi,iEta)/map2d_EEm->GetBinContent(iPhi,iEta))<< std::endl; + FileAbsolute << ix << "\t" << iy << "\t" << -1 << "\t" << map1_EEm->GetBinContent(ix,iy)*map2_EEm->GetBinContent(ix,iy) << "\t" << -999. << std::endl; + correlationEEm->Fill(map1_EEm->GetBinContent(ix,iy),map2_EEm->GetBinContent(ix,iy)); + + if ( (ix>20 && ix<30) || (ix>50 && ix<55) || (ix>80 && ix<90)) + FileMiscalib << ix << "\t" << iy << "\t" << -1 << "\t" << map1_EEm->GetBinContent(ix,iy)*1.3 << "\t" << -999. << std::endl; + else if ((ix>5 && ix<15) || (ix>40 && ix<45) || (ix>60 && ix<70)) + FileMiscalib << ix << "\t" << iy << "\t" << -1 << "\t" << map1_EEm->GetBinContent(ix,iy)*0.7 << "\t" << -999. << std::endl; + else + FileMiscalib << ix << "\t" << iy << "\t" << -1 << "\t" << map1_EEm->GetBinContent(ix,iy) << "\t" << -999. << std::endl; + + } +} + + + +TF1 *fgaus2 = new TF1("fgaus2","gaus",-0.02,0.02); + + std::cout<<"FIT: "<SetParameter(1,0); +fgaus2->SetParameter(2,diffHistEB->GetRMS()); +//fgaus2->SetRange(0-0.5*diffHistEB->GetRMS(),0+0.5*diffHistEB->GetRMS()); +fgaus2->SetRange(-0.03,0.03); +fgaus2->SetLineColor(kRed); +//diffHistEB->Fit("fgaus2","QRME"); +cout<<" EB-Mean: "<GetParameter(1)<<" RMSFit: "<GetParameter(2)<GetChisquare()/fgaus2->GetNDF()<Fit("fgaus2","QRME"); +cout<<" EB_0_20-Mean: "<GetParameter(1)<<" RMSFit: "<GetParameter(2)<GetChisquare()/fgaus2->GetNDF()<Fit("fgaus2","QRME"); +cout<<" EB_20_40-Mean: "<GetParameter(1)<<" RMSFit: "<GetParameter(2)<GetChisquare()/fgaus2->GetNDF()<Fit("fgaus2","QRME"); +cout<<" EB_40_60-Mean: "<GetParameter(1)<<" RMSFit: "<GetParameter(2)<GetChisquare()/fgaus2->GetNDF()<Fit("fgaus2","QRME"); +cout<<" EB_60_85-Mean: "<GetParameter(1)<<" RMSFit: "<GetParameter(2)<GetChisquare()/fgaus2->GetNDF()<SetParameter(1,0); +fgaus2->SetParameter(2,diffHistEEp->GetRMS()); +fgaus2->SetRange(-0.1,0.08); +//fgaus2->SetRange(0-0.5*diffHistEEp->GetRMS(),0+0.5*diffHistEEp->GetRMS()); +fgaus2->SetLineColor(kRed); +//diffHistEEp->Fit("fgaus2","QRME"); +cout<<" EEp-Mean: "<GetParameter(1)<<" RMSFit: "<GetParameter(2)<GetChisquare()/fgaus2->GetNDF()<Fit("fgaus2","QRME"); +cout<<" EEp_0_5-Mean: "<GetParameter(1)<<" RMSFit: "<GetParameter(2)<GetChisquare()/fgaus2->GetNDF()<Fit("fgaus2","QRME"); +cout<<" EEp_5_15-Mean: "<GetParameter(1)<<" RMSFit: "<GetParameter(2)<GetChisquare()/fgaus2->GetNDF()<Fit("fgaus2","QRME"); +cout<<" EEp_15_25-Mean: "<GetParameter(1)<<" RMSFit: "<GetParameter(2)<GetChisquare()/fgaus2->GetNDF()<Fit("fgaus2","QRME"); +cout<<" EEp_25_35-Mean: "<GetParameter(1)<<" RMSFit: "<GetParameter(2)<GetChisquare()/fgaus2->GetNDF()<SetParameter(1,0); +fgaus2->SetParameter(2,diffHistEEm->GetRMS()); +fgaus2->SetRange(-0.1,0.08); +//fgaus2->SetRange(0-0.5*diffHistEEm->GetRMS(),0+0.5*diffHistEEm->GetRMS()); +fgaus2->SetLineColor(kRed); +fgaus2->SetLineColor(kRed); +//diffHistEEm->Fit("fgaus2","QRME"); +cout<<" EEm-Mean: "<GetParameter(1)<<" RMSFit: "<GetParameter(2)<GetChisquare()/fgaus2->GetNDF()<Fit("fgaus2","QRME"); +cout<<" EEm_0_5-Mean: "<GetParameter(1)<<" RMSFit: "<GetParameter(2)<GetChisquare()/fgaus2->GetNDF()<Fit("fgaus2","QRME"); +cout<<" EEm_5_15-Mean: "<GetParameter(1)<<" RMSFit: "<GetParameter(2)<GetChisquare()/fgaus2->GetNDF()<Fit("fgaus2","QRME"); +cout<<" EEm_15_25-Mean: "<GetParameter(1)<<" RMSFit: "<GetParameter(2)<GetChisquare()/fgaus2->GetNDF()<Fit("fgaus2","QRME"); +cout<<" EEm_25_35-Mean: "<GetParameter(1)<<" RMSFit: "<GetParameter(2)<GetChisquare()/fgaus2->GetNDF()<GetMean()<<" RMSdist "<GetRMS()<GetMean()<<" RMSdist "<GetRMS()<GetMean()<<" RMSdist "<GetRMS()<GetMean()<<" RMSdist "<GetRMS()<GetMean()<<" RMSdist "<GetRMS()<GetMean()<<" RMSdist "<GetRMS()<GetMean()<<" RMSdist "<GetRMS()<GetMean()<<" RMSdist "<GetRMS()<GetMean()<<" RMSdist "<GetRMS()<GetMean()<<" RMSdist "<GetRMS()<GetMean()<<" RMSdist "<GetRMS()<GetMean()<<" RMSdist "<GetRMS()<GetMean()<<" RMSdist "<GetRMS()<GetMean()<<" RMSdist "<GetRMS()<GetMean()<<" RMSdist "<GetRMS()<SetMarkerStyle(20); +phiProjectionEB1->SetMarkerSize(1); +phiProjectionEB1->SetMarkerColor(kBlue); + +TGraphErrors *phiProjectionEB2 = new TGraphErrors(); +phiProjectionEB2->SetMarkerStyle(20); +phiProjectionEB2->SetMarkerSize(1); +phiProjectionEB2->SetMarkerColor(kRed); + + +for(int iPhi =1; iPhiGetNbinsX()+1; iPhi++){ + double sumEta=0, nEta=0; + + for(int iEta =1; iEtaGetNbinsY()+1; iEta++){ + if(map1_EB->GetBinContent(iPhi,iEta)==-1. || map1_EB->GetBinContent(iPhi,iEta)==0.) continue; + sumEta=sumEta+map1_EB->GetBinContent(iPhi,iEta); + nEta++; + } + phiProjectionEB1->SetPoint(iPhi-1,iPhi-1,sumEta/nEta); + phiProjectionEB1->SetPointError(iPhi-1,0.,0.002); + } + + +for(int iPhi =1; iPhiGetNbinsX()+1; iPhi++){ + double sumEta=0, nEta=0; + + for(int iEta =1; iEtaGetNbinsY()+1; iEta++){ + if(map2_EB->GetBinContent(iPhi,iEta)==-1.||map2_EB->GetBinContent(iPhi,iEta)==0. ) continue; + sumEta=sumEta+map2_EB->GetBinContent(iPhi,iEta); + nEta++; + } + phiProjectionEB2->SetPoint(iPhi-1,iPhi-1,sumEta/nEta); + phiProjectionEB2->SetPointError(iPhi-1,0.,0.002); + } + + +/// Profile along phi for EE+: + +std::vector vectSum; +std::vector vectCounter; + +vectCounter.assign(360,0.); +vectSum.assign(360,0.); + + +TGraphErrors *phiProjectionEEp1 = new TGraphErrors(); +phiProjectionEEp1->SetMarkerStyle(20); +phiProjectionEEp1->SetMarkerSize(1); +phiProjectionEEp1->SetMarkerColor(kBlue); + +TGraphErrors *phiProjectionEEp2 = new TGraphErrors(); +phiProjectionEEp2->SetMarkerStyle(20); +phiProjectionEEp2->SetMarkerSize(1); +phiProjectionEEp2->SetMarkerColor(kRed); + + for(int ix=1; ixGetNbinsX()+1;ix++){ + for(int iy=1; iyGetNbinsY()+1;iy++){ + if(map1_EEp->GetBinContent(ix,iy)==-1. || map1_EEp->GetBinContent(ix,iy)==0. ) continue; + int iPhi = int(eRings->GetEndcapIphi(ix,iy,1)); + if (iPhi==360) iPhi=0; + vectSum.at(iPhi)=vectSum.at(iPhi)+map1_EEp->GetBinContent(ix,iy); + vectCounter.at(iPhi)=vectCounter.at(iPhi)+1; + } + } + + + int j=0; + for(unsigned int i=0; iSetPoint(j,i,vectSum.at(i)/vectCounter.at(i)); + j++; + } + + for(unsigned int i=0; iGetNbinsX()+1;ix++){ + for(int iy=1; iyGetNbinsY()+1;iy++){ + if(map2_EEp->GetBinContent(ix,iy)==-1. ||map2_EEp->GetBinContent(ix,iy)==0.) continue; + int iPhi = int(eRings->GetEndcapIphi(ix,iy,1)); + if (iPhi==360) iPhi=0; + vectSum.at(iPhi)=vectSum.at(iPhi)+map2_EEp->GetBinContent(ix,iy); + vectCounter.at(iPhi)=vectCounter.at(iPhi)+1; + } + } + + + j=0; + for(unsigned int i=0; iSetPoint(j,i,vectSum.at(i)/vectCounter.at(i)); + j++; + } + + for(unsigned int i=0; iSetMarkerStyle(20); +phiProjectionEEm1->SetMarkerSize(1); +phiProjectionEEm1->SetMarkerColor(kBlue); + +TGraphErrors *phiProjectionEEm2 = new TGraphErrors(); +phiProjectionEEm2->SetMarkerStyle(20); +phiProjectionEEm2->SetMarkerSize(1); +phiProjectionEEm2->SetMarkerColor(kRed); + + for(int ix=1; ixGetNbinsX()+1;ix++){ + for(int iy=1; iyGetNbinsY()+1;iy++){ + if(map1_EEm->GetBinContent(ix,iy)==-1. || map1_EEm->GetBinContent(ix,iy)==0. ) continue; + int iPhi = int(eRings->GetEndcapIphi(ix,iy,-1)); + if (iPhi==360) iPhi=0; + vectSum.at(iPhi)=vectSum.at(iPhi)+map1_EEm->GetBinContent(ix,iy); + vectCounter.at(iPhi)=vectCounter.at(iPhi)+1; + } + } + + + j=0; + for(unsigned int i=0; iSetPoint(j,i,vectSum.at(i)/vectCounter.at(i)); + j++; + } + for(unsigned int i=0; iGetNbinsX()+1;ix++){ + for(int iy=1; iyGetNbinsY()+1;iy++){ + if(map2_EEm->GetBinContent(ix,iy)==-1. || map2_EEm->GetBinContent(ix,iy)==0.) continue; + int iPhi = int(eRings->GetEndcapIphi(ix,iy,-1)); + if (iPhi==360) iPhi=0; + vectSum.at(iPhi)=vectSum.at(iPhi)+map2_EEm->GetBinContent(ix,iy); + vectCounter.at(iPhi)=vectCounter.at(iPhi)+1; + } + } + + + j=0; + for(unsigned int i=0; iSetPoint(j,i,vectSum.at(i)/vectCounter.at(i)); + j++; +} + + for(unsigned int i=0; iSetMarkerStyle(20); +etaProjectionEB1->SetMarkerSize(1); +etaProjectionEB1->SetMarkerColor(kBlue); + +TGraphErrors *etaProjectionEB2 = new TGraphErrors(); +etaProjectionEB2->SetMarkerStyle(20); +etaProjectionEB2->SetMarkerSize(1); +etaProjectionEB2->SetMarkerColor(kRed); + + +for(int iEta =1; iEtaGetNbinsY()+1; iEta++){ + double sumPhi=0, nPhi=0; + + // float prec = abs(map1p_EB->GetBinContent(iPhi,iEta)/map2p_EB->GetBinContent(iPhi,iEta) - map1d_EB->GetBinContent(iPhi,iEta)/map2d_EB->GetBinContent(iPhi,iEta))/(map1p_EB->GetBinContent(iPhi,iEta)/map2p_EB->GetBinContent(iPhi,iEta) + map1d_EB->GetBinContent(iPhi,iEta)/map2d_EB->GetBinContent(iPhi,iEta)); + + for(int iPhi =1; iPhiGetNbinsX()+1; iPhi++){ + if(map1_EB->GetBinContent(iPhi,iEta)==-1.) continue; + // sumPhi=sumPhi+map1_EB->GetBinContent(iPhi,iEta); + sumPhi=sumPhi+abs(map1p_EB->GetBinContent(iPhi,iEta)/map2p_EB->GetBinContent(iPhi,iEta) - map1d_EB->GetBinContent(iPhi,iEta)/map2d_EB->GetBinContent(iPhi,iEta))/(map1p_EB->GetBinContent(iPhi,iEta)/map2p_EB->GetBinContent(iPhi,iEta) + map1d_EB->GetBinContent(iPhi,iEta)/map2d_EB->GetBinContent(iPhi,iEta)); + nPhi++; + } + + // std::cout<SetPoint(iEta-1,iEta-1,sumPhi/nPhi); + etaProjectionEB1->SetPointError(iEta-1,0.,0.); + } + + +for(int iEta =1; iEtaGetNbinsY()+1; iEta++){ + double sumPhi=0, nPhi=0; + + for(int iPhi =1; iPhiGetNbinsX()+1; iPhi++){ + if(map2_EB->GetBinContent(iPhi,iEta)==-1.) continue; + sumPhi=sumPhi+map2_EB->GetBinContent(iPhi,iEta); + nPhi++; + } + etaProjectionEB2->SetPoint(iEta-1,iEta-1,sumPhi/nPhi); + etaProjectionEB2->SetPointError(iEta-1,0.,0.002); + } + + + +/// projection along eta for EE+: + +TGraphErrors *etaProjectionEEp1 = new TGraphErrors(); +etaProjectionEEp1->SetMarkerStyle(20); +etaProjectionEEp1->SetMarkerSize(1); +etaProjectionEEp1->SetMarkerColor(kBlue); + +TGraphErrors *etaProjectionEEp2 = new TGraphErrors(); +etaProjectionEEp2->SetMarkerStyle(20); +etaProjectionEEp2->SetMarkerSize(1); +etaProjectionEEp2->SetMarkerColor(kRed); + +vectCounter.clear(); +vectSum.clear(); +vectCounter.assign(360,0.); +vectSum.assign(360,0.); + + for(int ix=1; ixGetNbinsX()+1;ix++){ + for(int iy=1; iyGetNbinsY()+1;iy++){ + if(map1_EEp->GetBinContent(ix,iy)==-1. || map1_EEp->GetBinContent(ix,iy)==0.) continue; + int iEta = int(eRings->GetEndcapIeta(ix,iy,1)); + if(iEta<0 || iEta>360)continue; + // vectSum.at(iEta)=vectSum.at(iEta)+map1_EEp->GetBinContent(ix,iy); + vectSum.at(iEta)=vectSum.at(iEta)+abs(map1p_EEp->GetBinContent(ix,iy)/map2p_EEp->GetBinContent(ix,iy) - map1d_EEp->GetBinContent(ix,iy)/map2d_EEp->GetBinContent(ix,iy))/(map1p_EEp->GetBinContent(ix,iy)/map2p_EEp->GetBinContent(ix,iy) + map1d_EEp->GetBinContent(ix,iy)/map2d_EEp->GetBinContent(ix,iy)); + + vectCounter.at(iEta)=vectCounter.at(iEta)+1; + } + + } + + j=0; + for(unsigned int i=0; iSetPoint(j,i,vectSum.at(i)/vectCounter.at(i)); + j++; + } + + + for(unsigned int i=0; iGetNbinsX()+1;ix++){ + for(int iy=1; iyGetNbinsY()+1;iy++){ + if(map2_EEp->GetBinContent(ix,iy)==-1. || map2_EEp->GetBinContent(ix,iy)==0. ) continue; + int iEta = int(eRings->GetEndcapIeta(ix,iy,1)); + if(iEta<0 || iEta>360)continue; + vectSum.at(iEta)=vectSum.at(iEta)+map2_EEp->GetBinContent(ix,iy); + vectCounter.at(iEta)=vectCounter.at(iEta)+1; + } + } + + + j=0; + for(unsigned int i=0; iSetPoint(j,i,vectSum.at(i)/vectCounter.at(i)); + j++; + } + + + for(unsigned int i=0; iSetMarkerStyle(20); +etaProjectionEEm1->SetMarkerSize(1); +etaProjectionEEm1->SetMarkerColor(kBlue); + +TGraphErrors *etaProjectionEEm2 = new TGraphErrors(); +etaProjectionEEm2->SetMarkerStyle(20); +etaProjectionEEm2->SetMarkerSize(1); +etaProjectionEEm2->SetMarkerColor(kRed); + + for(int ix=1; ixGetNbinsX()+1;ix++){ + for(int iy=1; iyGetNbinsY()+1;iy++){ + if(map1_EEm->GetBinContent(ix,iy)==-1.||map1_EEm->GetBinContent(ix,iy)==0.) continue; + int iEta = int(eRings->GetEndcapIeta(ix,iy,1)); + if(iEta<0 || iEta>360)continue; + // vectSum.at(iEta)=vectSum.at(iEta)+map1_EEm->GetBinContent(ix,iy); + vectSum.at(iEta)=vectSum.at(iEta)+abs(map1p_EEm->GetBinContent(ix,iy)/map2p_EEm->GetBinContent(ix,iy) - map1d_EEm->GetBinContent(ix,iy)/map2d_EEm->GetBinContent(ix,iy))/(map1p_EEm->GetBinContent(ix,iy)/map2p_EEm->GetBinContent(ix,iy) + map1d_EEm->GetBinContent(ix,iy)/map2d_EEm->GetBinContent(ix,iy)); + vectCounter.at(iEta)=vectCounter.at(iEta)+1; + } + } + + + j=0; + for(unsigned int i=0; iSetPoint(j,i,vectSum.at(i)/vectCounter.at(i)); + j++; + } + + for(unsigned int i=0; iGetNbinsX()+1;ix++){ + for(int iy=1; iyGetNbinsY()+1;iy++){ + if(map2_EEm->GetBinContent(ix,iy)==-1. || map2_EEm->GetBinContent(ix,iy)==0.) continue; + int iEta = int(eRings->GetEndcapIeta(ix,iy,1)); + if(iEta<0 || iEta>171)continue; + vectSum.at(iEta)=vectSum.at(iEta)+map2_EEm->GetBinContent(ix,iy); + vectCounter.at(iEta)=vectCounter.at(iEta)+1; + } + } + + + j=0; + for(unsigned int i=0; iSetPoint(j,i,vectSum.at(i)/vectCounter.at(i)); + j++; + } + + for(unsigned int i=0; iGetN() ; i++){ + double x=0,y=0; + phiProjectionEB1->GetPoint(i,x,y); + phiProfileEB1->Fill(y); + } + +for(int i=0; iGetN() ; i++){ + double x=0,y=0; + phiProjectionEB2->GetPoint(i,x,y); + phiProfileEB2->Fill(y); + } + +TF1 *fgaus = new TF1("fgaus","gaus",-10,10); + +fgaus->SetParameter(1,1); +fgaus->SetParameter(2,phiProfileEB1->GetRMS()); +fgaus->SetRange(1-5*phiProfileEB1->GetRMS(),1+5*phiProfileEB1->GetRMS()); +fgaus->SetLineColor(kBlue); +phiProfileEB1->Fit("fgaus","QRME"); +cout<<" First Set : Mean Fit = "<GetParameter(1)<<" RMS Fit = "<GetParameter(2)<<" chi2/ndf = "<GetChisquare()/fgaus->GetNDF()<GetRMS()<SetParameter(1,1); +fgaus->SetParameter(2,phiProfileEB2->GetRMS()); +fgaus->SetRange(1-5*phiProfileEB2->GetRMS(),1+5*phiProfileEB2->GetRMS()); +fgaus->SetLineColor(kRed); +phiProfileEB2->Fit("fgaus","QRME"); +cout<<" Second Set : Mean Fit = "<GetParameter(1)<<" RMS Fit = "<GetParameter(2)<<" chi2/ndf = "<GetChisquare()/fgaus->GetNDF()<GetRMS()<GetN() ; i++){ + double x=0,y=0; + phiProjectionEEp1->GetPoint(i,x,y); + phiProfileEEp1->Fill(y); + } + +for(int i=0; iGetN() ; i++){ + double x=0,y=0; + phiProjectionEEp2->GetPoint(i,x,y); + phiProfileEEp2->Fill(y); + } + +fgaus->SetParameter(1,1); +fgaus->SetParameter(2,phiProfileEEp1->GetRMS()); +fgaus->SetRange(1-5*phiProfileEEp1->GetRMS(),1+5*phiProfileEEp1->GetRMS()); +fgaus->SetLineColor(kBlue); +phiProfileEEp1->Fit("fgaus","QRME"); +cout<<" First Set : Mean Fit = "<GetParameter(1)<<" RMS Fit = "<GetParameter(2)<<" chi2/ndf = "<GetChisquare()/fgaus->GetNDF()<GetRMS()<SetParameter(1,1); +fgaus->SetParameter(2,phiProfileEEp2->GetRMS()); +fgaus->SetRange(1-5*phiProfileEEp2->GetRMS(),1+5*phiProfileEEp2->GetRMS()); +fgaus->SetLineColor(kRed); +phiProfileEEp2->Fit("fgaus","QRME"); +cout<<" Second Set : Mean Fit = "<GetParameter(1)<<" RMS Fit = "<GetParameter(2)<<" chi2/ndf = "<GetChisquare()/fgaus->GetNDF()<GetRMS()<GetN() ; i++){ + double x=0,y=0; + phiProjectionEEm1->GetPoint(i,x,y); + phiProfileEEm1->Fill(y); + } + +for(int i=0; iGetN() ; i++){ + double x=0,y=0; + phiProjectionEEm2->GetPoint(i,x,y); + phiProfileEEm2->Fill(y); + } + +fgaus->SetParameter(1,1); +fgaus->SetParameter(2,phiProfileEEm1->GetRMS()); +fgaus->SetRange(1-5*phiProfileEEm1->GetRMS(),1+5*phiProfileEEm1->GetRMS()); +fgaus->SetLineColor(kBlue); +phiProfileEEm1->Fit("fgaus","QRME"); +cout<<" First Set : Mean Fit = "<GetParameter(1)<<" RMS Fit = "<GetParameter(2)<<" chi2/ndf = "<GetChisquare()/fgaus->GetNDF()<GetRMS()<SetParameter(1,1); +fgaus->SetParameter(2,phiProfileEEm2->GetRMS()); +fgaus->SetRange(1-5*phiProfileEEm2->GetRMS(),1+5*phiProfileEEm2->GetRMS()); +fgaus->SetLineColor(kRed); +phiProfileEEm2->Fit("fgaus","QRME"); +cout<<" Second Set : Mean Fit = "<GetParameter(1)<<" RMS Fit = "<GetParameter(2)<<" chi2/ndf = "<GetChisquare()/fgaus->GetNDF()<GetRMS()<GetN() ; i++){ + double x=0,y=0; + etaProjectionEB1->GetPoint(i,x,y); + etaProfileEB1->Fill(y); + } + +for(int i=0; iGetN() ; i++){ + double x=0,y=0; + etaProjectionEB2->GetPoint(i,x,y); + etaProfileEB2->Fill(y); + } + +fgaus->SetParameter(1,1); +fgaus->SetParameter(2,etaProfileEB1->GetRMS()); +fgaus->SetRange(1-5*etaProfileEB1->GetRMS(),1+5*etaProfileEB1->GetRMS()); +fgaus->SetLineColor(kBlue); +etaProfileEB1->Fit("fgaus","QRME"); +cout<<" First Set : Mean Fit = "<GetParameter(1)<<" RMS Fit = "<GetParameter(2)<<" chi2/ndf = "<GetChisquare()/fgaus->GetNDF()<GetRMS()<SetParameter(1,1); +fgaus->SetParameter(2,etaProfileEB2->GetRMS()); +fgaus->SetRange(1-5*etaProfileEB2->GetRMS(),1+5*etaProfileEB2->GetRMS()); +fgaus->SetLineColor(kRed); +etaProfileEB2->Fit("fgaus","QRME"); +cout<<" Second Set : Mean Fit = "<GetParameter(1)<<" RMS Fit = "<GetParameter(2)<<" chi2/ndf = "<GetChisquare()/fgaus->GetNDF()<GetRMS()<GetN() ; i++){ + double x=0,y=0; + etaProjectionEEp1->GetPoint(i,x,y); + etaProfileEEp1->Fill(y); + } + +for(int i=0; iGetN() ; i++){ + double x=0,y=0; + etaProjectionEEp2->GetPoint(i,x,y); + etaProfileEEp2->Fill(y); + } + +fgaus->SetParameter(1,1); +fgaus->SetParameter(2,etaProfileEEp1->GetRMS()); +fgaus->SetRange(1-5*etaProfileEEp1->GetRMS(),1+5*etaProfileEEp1->GetRMS()); +fgaus->SetLineColor(kBlue); +etaProfileEEp1->Fit("fgaus","QRME"); +cout<<" First Set : Mean Fit = "<GetParameter(1)<<" RMS Fit = "<GetParameter(2)<<" chi2/ndf = "<GetChisquare()/fgaus->GetNDF()<GetRMS()<SetParameter(1,1); +fgaus->SetParameter(2,etaProfileEEp2->GetRMS()); +fgaus->SetRange(1-5*etaProfileEEp2->GetRMS(),1+5*etaProfileEEp2->GetRMS()); +fgaus->SetLineColor(kRed); +etaProfileEEp2->Fit("fgaus","QRME"); +cout<<" Second Set : Mean Fit = "<GetParameter(1)<<" RMS Fit = "<GetParameter(2)<<" chi2/ndf = "<GetChisquare()/fgaus->GetNDF()<GetRMS()<GetN() ; i++){ + double x=0,y=0; + etaProjectionEEm1->GetPoint(i,x,y); + etaProfileEEm1->Fill(y); + } + +for(int i=0; iGetN() ; i++){ + double x=0,y=0; + etaProjectionEEm2->GetPoint(i,x,y); + etaProfileEEm2->Fill(y); + } + +fgaus->SetParameter(1,1); +fgaus->SetParameter(2,etaProfileEEm1->GetRMS()); +fgaus->SetRange(1-5*etaProfileEEm1->GetRMS(),1+5*etaProfileEEm1->GetRMS()); +fgaus->SetLineColor(kBlue); +etaProfileEEm1->Fit("fgaus","QRME"); +cout<<" First Set : Mean Fit = "<GetParameter(1)<<" RMS Fit = "<GetParameter(2)<<" chi2/ndf = "<GetChisquare()/fgaus->GetNDF()<GetRMS()<SetParameter(1,1); +fgaus->SetParameter(2,etaProfileEEm2->GetRMS()); +fgaus->SetRange(1-5*etaProfileEEm2->GetRMS(),1+5*etaProfileEEm2->GetRMS()); +fgaus->SetLineColor(kRed); +etaProfileEEm2->Fit("fgaus","QRME"); +cout<<" Second Set : Mean Fit = "<GetParameter(1)<<" RMS Fit = "<GetParameter(2)<<" chi2/ndf = "<GetChisquare()/fgaus->GetNDF()<GetRMS()<SetLeftMargin(0.1); + c[0]->SetRightMargin(0.13); + c[0]->SetGridx(); + + diffmap_EB->GetXaxis()->SetNdivisions(1020); + diffmap_EB->GetXaxis() -> SetLabelSize(0.03); + diffmap_EB->GetXaxis() ->SetTitle("i#phi"); + diffmap_EB->GetYaxis() ->SetTitle("i#eta"); + diffmap_EB->GetZaxis() ->SetRangeUser(-0.1,0.1); + diffmap_EB->Draw("COLZ"); + + c[1] = new TCanvas("histdiffEB","histdiffEB"); + c[1]->SetLeftMargin(0.1); + c[1]->SetRightMargin(0.13); + c[1]->SetLogy(); + + diffHistEB->GetXaxis()->SetTitle("c_{1}-c_{2}"); + diffHistEB->Draw(); + + + c[2] = new TCanvas("hratioEB","hratioEB"); + c[2]->SetLeftMargin(0.1); + c[2]->SetRightMargin(0.13); + c[2]->SetGridx(); + + ratiomap_EB->GetXaxis()->SetNdivisions(1020); + ratiomap_EB->GetXaxis() -> SetLabelSize(0.03); + ratiomap_EB->GetXaxis() ->SetTitle("i#phi"); + ratiomap_EB->GetYaxis() ->SetTitle("i#eta"); + ratiomap_EB->GetZaxis() ->SetRangeUser(0.95,1.05); + ratiomap_EB->Draw("COLZ"); + + c[3] = new TCanvas("correlationEB","correlationEB"); + c[3]->SetLeftMargin(0.1); + c[3]->SetRightMargin(0.13); + c[3]->SetGridx(); + c[3]->SetGridy(); + + correlationEB->GetXaxis()->SetNdivisions(1020); + correlationEB->GetXaxis() -> SetLabelSize(0.03); + correlationEB->GetXaxis() ->SetTitle("c_{1}"); + correlationEB->GetYaxis() ->SetTitle("c_{2}"); + correlationEB->Draw("COLZ"); + + std::cout<<"correlation EB: "<GetCorrelationFactor()<SetLeftMargin(0.1); + c[4]->SetRightMargin(0.13); + c[4]->SetGridx(); + + diffmap_EEp->GetXaxis()->SetNdivisions(1020); + diffmap_EEp->GetXaxis() -> SetLabelSize(0.03); + diffmap_EEp->GetXaxis() ->SetTitle("ix"); + diffmap_EEp->GetYaxis() ->SetTitle("iy"); + diffmap_EEp->GetZaxis() ->SetRangeUser(-0.15,0.15); + diffmap_EEp->Draw("COLZ"); + + c[5] = new TCanvas("histdiffEEp","histdiffEEp"); + c[5]->SetLeftMargin(0.1); + c[5]->SetRightMargin(0.13); + c[5]->SetLogy(); + + diffHistEEp->GetXaxis()->SetTitle("c_{1}-c_{2}"); + diffHistEEp->Draw(); + + c[6] = new TCanvas("hratioEEp","hratioEEp"); + c[6]->SetLeftMargin(0.1); + c[6]->SetRightMargin(0.13); + c[6]->SetGridx(); + + ratiomap_EEp->GetXaxis()->SetNdivisions(1020); + ratiomap_EEp->GetXaxis() -> SetLabelSize(0.03); + ratiomap_EEp->GetXaxis() ->SetTitle("ix"); + ratiomap_EEp->GetYaxis() ->SetTitle("iy"); + ratiomap_EEp->GetZaxis() ->SetRangeUser(0.9,1.1); + ratiomap_EEp->Draw("COLZ"); + + c[7] = new TCanvas("correlationEEp","correlationEEp"); + c[7]->SetLeftMargin(0.1); + c[7]->SetRightMargin(0.13); + c[7]->SetGridx(); + c[7]->SetGridy(); + + correlationEEp->GetXaxis()->SetNdivisions(1020); + correlationEEp->GetXaxis() -> SetLabelSize(0.03); + correlationEEp->GetXaxis() ->SetTitle("c_{1}"); + correlationEEp->GetYaxis() ->SetTitle("c_{2}"); + correlationEEp->Draw("COLZ"); + + std::cout<<"correlation EE+: "<GetCorrelationFactor()<SetLeftMargin(0.1); + c[8]->SetRightMargin(0.13); + c[8]->SetGridx(); + + diffmap_EEm->GetXaxis()->SetNdivisions(1020); + diffmap_EEm->GetXaxis() -> SetLabelSize(0.03); + diffmap_EEm->GetXaxis() ->SetTitle("ix"); + diffmap_EEm->GetYaxis() ->SetTitle("iy"); + diffmap_EEm->GetZaxis() ->SetRangeUser(-0.15,0.15); + diffmap_EEm->Draw("COLZ"); + + c[9] = new TCanvas("histdiffEEm","histdiffEEm"); + c[9]->SetLeftMargin(0.1); + c[9]->SetRightMargin(0.13); + c[9]->SetLogy(); + + diffHistEEm->GetXaxis()->SetTitle("c_{1}-c_{2}"); + diffHistEEm->Draw(); + + + + c[10] = new TCanvas("hratioEEm","hratioEEm"); + c[10]->SetLeftMargin(0.1); + c[10]->SetRightMargin(0.13); + c[10]->SetGridx(); + + ratiomap_EEm->GetXaxis()->SetNdivisions(1020); + ratiomap_EEm->GetXaxis() -> SetLabelSize(0.03); + ratiomap_EEm->GetXaxis() ->SetTitle("ix"); + ratiomap_EEm->GetYaxis() ->SetTitle("iy"); + ratiomap_EEm->GetZaxis() ->SetRangeUser(0.9,1.1); + ratiomap_EEm->Draw("COLZ"); + + c[11] = new TCanvas("correlationEEm","correlationEEm"); + c[11]->SetLeftMargin(0.1); + c[11]->SetRightMargin(0.13); + c[11]->SetGridx(); + c[11]->SetGridy(); + + correlationEEm->GetXaxis()->SetNdivisions(1020); + correlationEEm->GetXaxis() -> SetLabelSize(0.03); + correlationEEm->GetXaxis() ->SetTitle("c_{1}"); + correlationEEm->GetYaxis() ->SetTitle("c_{2}"); + correlationEEm->Draw("COLZ"); + + std::cout<<"correlation EE-: "<GetCorrelationFactor()<SetGridx(); + c[12]->SetGridy(); + phiProjectionEB1->GetHistogram()->GetYaxis()-> SetRangeUser(0.85,1.1); + phiProjectionEB1->GetHistogram()->GetXaxis()-> SetRangeUser(1,361); + phiProjectionEB1->GetHistogram()->GetYaxis()-> SetTitle("Mean IC"); + phiProjectionEB1->GetHistogram()->GetXaxis()-> SetTitle("i#phi"); + phiProjectionEB1->Draw("apl"); + phiProjectionEB2->Draw("plsame"); + + TLegend * leg1 = new TLegend(0.75,0.75,0.89, 0.89); + leg1->AddEntry(phiProjectionEB1,"IC set 1","LP"); + leg1->AddEntry(phiProjectionEB2,"IC set 2","LP"); + leg1->SetFillColor(0); + leg1->Draw("same"); + + c[13] = new TCanvas("phiProjectionEEp","phiProjectionEEp"); + c[13]->SetGridx(); + c[13]->SetGridy(); + phiProjectionEEp1->GetHistogram()->GetYaxis()-> SetRangeUser(0.7,1.4); + phiProjectionEEp1->GetHistogram()->GetXaxis()-> SetRangeUser(1,361); + phiProjectionEEp1->GetHistogram()->GetYaxis()-> SetTitle("Mean IC"); + phiProjectionEEp1->GetHistogram()->GetXaxis()-> SetTitle("i#phi"); + phiProjectionEEp1->Draw("apl"); + phiProjectionEEp2->Draw("plsame"); + + TLegend * leg2 = new TLegend(0.75,0.75,0.89, 0.89); + leg2->AddEntry(phiProjectionEEp1,"IC set 1","LP"); + leg2->AddEntry(phiProjectionEEp2,"IC set 2","LP"); + leg2->SetFillColor(0); + leg2->Draw("same"); + + + c[14] = new TCanvas("phiProjectionEEm","phiProjectionEEm"); + c[14]->SetGridx(); + c[14]->SetGridy(); + phiProjectionEEm1->GetHistogram()->GetYaxis()-> SetRangeUser(0.7,1.4); + phiProjectionEEm1->GetHistogram()->GetXaxis()-> SetRangeUser(1,361); + phiProjectionEEm1->GetHistogram()->GetYaxis()-> SetTitle("Mean IC"); + phiProjectionEEm1->GetHistogram()->GetXaxis()-> SetTitle("i#phi"); + phiProjectionEEm1->Draw("apl"); + phiProjectionEEm2->Draw("plsame"); + + TLegend * leg3 = new TLegend(0.75,0.75,0.89, 0.89); + leg3->AddEntry(phiProjectionEEm1,"IC set 1","LP"); + leg3->AddEntry(phiProjectionEEm2,"IC set 2","LP"); + leg3->SetFillColor(0); + leg3->Draw("same"); + + c[15] = new TCanvas("etaProjectionEB","etaProjectionEB"); + c[15]->SetGridx(); + c[15]->SetGridy(); + // etaProjectionEB1->GetHistogram()->GetYaxis()-> SetRangeUser(0.9,1.1); + etaProjectionEB1->GetHistogram()->GetYaxis()-> SetRangeUser(0.,1.1); + etaProjectionEB1->GetHistogram()->GetXaxis()-> SetRangeUser(0,171); + etaProjectionEB1->GetHistogram()->GetYaxis()-> SetTitle("Mean IC"); + etaProjectionEB1->GetHistogram()->GetXaxis()-> SetTitle("i#eta"); + etaProjectionEB1->Draw("apl"); + // etaProjectionEB2->Draw("plsame"); + + TLegend * leg4 = new TLegend(0.75,0.75,0.89, 0.89); + leg4->AddEntry(etaProjectionEB1,"IC set 1","LP"); + leg4->AddEntry(etaProjectionEB2,"IC set 2","LP"); + leg4->SetFillColor(0); + leg1->Draw("same"); + + c[16] = new TCanvas("etaProjectionEEp","etaProjectionEEp"); + c[16]->SetGridx(); + c[16]->SetGridy(); + // etaProjectionEEp1->GetHistogram()->GetYaxis()-> SetRangeUser(0.55,1.5); + etaProjectionEEp1->GetHistogram()->GetYaxis()-> SetRangeUser(0.,1.5); + etaProjectionEEp1->GetHistogram()->GetXaxis()-> SetRangeUser(85,125); + etaProjectionEEp1->GetHistogram()->GetYaxis()-> SetTitle("Mean IC"); + etaProjectionEEp1->GetHistogram()->GetXaxis()-> SetTitle("i#eta"); + etaProjectionEEp1->Draw("apl"); + // etaProjectionEEp2->Draw("plsame"); + + TLegend * leg5 = new TLegend(0.75,0.75,0.89, 0.89); + leg5->AddEntry(etaProjectionEEp1,"IC set 1","LP"); + leg5->AddEntry(etaProjectionEEp2,"IC set 2","LP"); + leg5->SetFillColor(0); + leg5->Draw("same"); + + + c[17] = new TCanvas("etaProjectionEEm","etaProjectionEEm"); + c[17]->SetGridx(); + c[17]->SetGridy(); + // etaProjectionEEm1->GetHistogram()->GetYaxis()-> SetRangeUser(0.55,1.5); + etaProjectionEEm1->GetHistogram()->GetYaxis()-> SetRangeUser(0.,1.5); + etaProjectionEEm1->GetHistogram()->GetXaxis()-> SetRangeUser(85,125); + etaProjectionEEm1->GetHistogram()->GetYaxis()-> SetTitle("Mean IC"); + etaProjectionEEm1->GetHistogram()->GetXaxis()-> SetTitle("i#eta"); + etaProjectionEEm1->Draw("apl"); + // etaProjectionEEm2->Draw("plsame"); + + TLegend * leg6 = new TLegend(0.75,0.75,0.89, 0.89); + leg6->AddEntry(etaProjectionEEm1,"IC set 1","LP"); + leg6->AddEntry(etaProjectionEEm2,"IC set 2","LP"); + leg6->SetFillColor(0); + leg6->Draw("same"); + + c[18] = new TCanvas("phiProfileEB","phiProfileEB"); + c[18]->SetGridx(); + c[18]->SetGridy(); + phiProfileEB1->GetXaxis()->SetTitle("#bar{IC}"); + phiProfileEB1->SetLineColor(kBlue); + phiProfileEB1->SetMarkerSize(0.8); + phiProfileEB1->SetLineWidth(2); + phiProfileEB2->SetLineColor(kRed); + phiProfileEB2->SetMarkerSize(0.8); + phiProfileEB2->SetLineWidth(2); + phiProfileEB1->Draw(); + phiProfileEB2->Draw("same"); + + TLegend * leg7 = new TLegend(0.6,0.7,0.89, 0.89); + leg7->SetFillColor(0); + leg7->AddEntry(phiProfileEB1,"EB Projection I set ", "LP"); + leg7->AddEntry(phiProfileEB2,"EB Projection II set ", "LP"); + leg7->Draw("same"); + + c[19] = new TCanvas("phiProfileEEp","phiProfileEEp"); + c[19]->SetGridx(); + c[19]->SetGridy(); + phiProfileEEp1->GetXaxis()->SetTitle("#bar{IC}"); + phiProfileEEp1->SetLineColor(kBlue); + phiProfileEEp1->SetMarkerSize(0.8); + phiProfileEEp1->SetLineWidth(2); + phiProfileEEp2->SetLineColor(kRed); + phiProfileEEp2->SetMarkerSize(0.8); + phiProfileEEp2->SetLineWidth(2); + phiProfileEEp1->Draw(); + phiProfileEEp2->Draw("same"); + + TLegend * leg8 = new TLegend(0.6,0.7,0.89, 0.89); + leg8->SetFillColor(0); + leg8->AddEntry(phiProfileEEp1,"EE+ Projection I set ", "LP"); + leg8->AddEntry(phiProfileEEp2,"EE+ Projection II set ", "LP"); + leg8->Draw("same"); + + c[20] = new TCanvas("phiProfileEEm","phiProfileEEm"); + c[20]->SetGridx(); + c[20]->SetGridy(); + phiProfileEEm1->GetXaxis()->SetTitle("#bar{IC}"); + phiProfileEEm1->SetLineColor(kBlue); + phiProfileEEm1->SetMarkerSize(0.8); + phiProfileEEm1->SetLineWidth(2); + phiProfileEEm2->SetLineColor(kRed); + phiProfileEEm2->SetMarkerSize(0.8); + phiProfileEEm2->SetLineWidth(2); + phiProfileEEm1->Draw(); + phiProfileEEm2->Draw("same"); + + TLegend * leg9 = new TLegend(0.6,0.7,0.89, 0.89); + leg9->SetFillColor(0); + leg9->AddEntry(phiProfileEEm1,"EE- Projection I set ", "LP"); + leg9->AddEntry(phiProfileEEm2,"EE- Projection II set ", "LP"); + leg9->Draw("same"); + + c[21] = new TCanvas("etaProfileEB","etaProfileEB"); + c[21]->SetGridx(); + c[21]->SetGridy(); + etaProfileEB1->GetXaxis()->SetTitle("#bar{IC}"); + etaProfileEB1->SetLineColor(kBlue); + etaProfileEB1->SetMarkerSize(0.8); + etaProfileEB1->SetLineWidth(2); + etaProfileEB2->SetLineColor(kRed); + etaProfileEB2->SetMarkerSize(0.8); + etaProfileEB2->SetLineWidth(2); + etaProfileEB1->Draw(); + etaProfileEB2->Draw("same"); + + TLegend * leg10 = new TLegend(0.6,0.7,0.89, 0.89); + leg10->SetFillColor(0); + leg10->AddEntry(etaProfileEB1,"EB Projection I set ", "LP"); + leg10->AddEntry(etaProfileEB2,"EB Projection II set ", "LP"); + leg10->Draw("same"); + + c[22] = new TCanvas("etaProfileEEp","etaProfileEEp"); + c[22]->SetGridx(); + c[22]->SetGridy(); + etaProfileEEp1->GetXaxis()->SetTitle("#bar{IC}"); + etaProfileEEp1->SetLineColor(kBlue); + etaProfileEEp1->SetMarkerSize(0.8); + etaProfileEEp1->SetLineWidth(2); + etaProfileEEp2->SetLineColor(kRed); + etaProfileEEp2->SetMarkerSize(0.8); + etaProfileEEp2->SetLineWidth(2); + etaProfileEEp1->Draw(); + etaProfileEEp2->Draw("same"); + + TLegend * leg11 = new TLegend(0.6,0.7,0.89, 0.89); + leg11->SetFillColor(0); + leg11->AddEntry(phiProfileEEp1,"EE+ Projection I set ", "LP"); + leg11->AddEntry(phiProfileEEp2,"EE+ Projection II set ", "LP"); + leg11->Draw("same"); + + c[23] = new TCanvas("etaProfileEEm","etaProfileEEm"); + c[23]->SetGridx(); + c[23]->SetGridy(); + etaProfileEEm1->GetXaxis()->SetTitle("#bar{IC}"); + etaProfileEEm1->SetLineColor(kBlue); + etaProfileEEm1->SetMarkerSize(0.8); + etaProfileEEm1->SetLineWidth(2); + etaProfileEEm2->SetLineColor(kRed); + etaProfileEEm2->SetMarkerSize(0.8); + etaProfileEEm2->SetLineWidth(2); + etaProfileEEm1->Draw(); + etaProfileEEm2->Draw("same"); + + TLegend * leg12 = new TLegend(0.6,0.7,0.89, 0.89); + leg12->SetFillColor(0); + leg12->AddEntry(phiProfileEEm1,"EE- Projection I set ", "LP"); + leg12->AddEntry(phiProfileEEm2,"EE- Projection II set ", "LP"); + leg12->Draw("same"); + + c[24] = new TCanvas("habsoluteEB","habsoluteEB"); + c[24]->SetLeftMargin(0.1); + c[24]->SetRightMargin(0.13); + c[24]->SetGridx(); + + absolutemap_EB->GetXaxis()->SetNdivisions(1020); + absolutemap_EB->GetXaxis() -> SetLabelSize(0.03); + absolutemap_EB->GetXaxis() ->SetTitle("i#phi"); + absolutemap_EB->GetYaxis() ->SetTitle("i#eta"); + absolutemap_EB->GetZaxis() ->SetRangeUser(0.85,1.15); + absolutemap_EB->Draw("COLZ"); + + c[25] = new TCanvas("habsoluteEEp","habsoluteEEp"); + c[25]->SetLeftMargin(0.1); + c[25]->SetRightMargin(0.13); + c[25]->SetGridx(); + + absolutemap_EEp->GetXaxis()->SetNdivisions(1020); + absolutemap_EEp->GetXaxis() -> SetLabelSize(0.03); + absolutemap_EEp->GetXaxis() ->SetTitle("ix"); + absolutemap_EEp->GetYaxis() ->SetTitle("iy"); + absolutemap_EEp->GetZaxis() ->SetRangeUser(0.7,1.3); + absolutemap_EEp->Draw("COLZ"); + + + c[26] = new TCanvas("habsoluteEEm","habsoluteEEm"); + c[26]->SetLeftMargin(0.1); + c[26]->SetRightMargin(0.13); + c[26]->SetGridx(); + + absolutemap_EEm->GetXaxis()->SetNdivisions(1020); + absolutemap_EEm->GetXaxis() -> SetLabelSize(0.03); + absolutemap_EEm->GetXaxis() ->SetTitle("ix"); + absolutemap_EEm->GetYaxis() ->SetTitle("iy"); + absolutemap_EEm->GetZaxis() ->SetRangeUser(0.7,1.3); + absolutemap_EEm->Draw("COLZ"); + + + c[27] = new TCanvas("map1_EB","map1_EB"); + c[27]->SetLeftMargin(0.1); + c[27]->SetRightMargin(0.13); + c[27]->SetGridx(); + + map1_EB->GetXaxis()->SetNdivisions(1020); + map1_EB->GetXaxis() -> SetLabelSize(0.03); + map1_EB->GetXaxis() ->SetTitle("i#phi"); + map1_EB->GetYaxis() ->SetTitle("i#eta"); + map1_EB->GetZaxis() ->SetRangeUser(0.6,1.4); + map1_EB->Draw("COLZ"); + + + c[28] = new TCanvas("map1_EEp","map1_EEp"); + c[28]->SetLeftMargin(0.1); + c[28]->SetRightMargin(0.13); + c[28]->SetGridx(); + + map1_EEp->GetXaxis()->SetNdivisions(1020); + map1_EEp->GetXaxis() -> SetLabelSize(0.03); + map1_EEp->GetXaxis() ->SetTitle("i#phi"); + map1_EEp->GetYaxis() ->SetTitle("i#eta"); + map1_EEp->GetZaxis() ->SetRangeUser(0.6,1.4); + map1_EEp->Draw("COLZ"); + + + c[29] = new TCanvas("map1_EEm","map1_EEm"); + c[29]->SetLeftMargin(0.1); + c[29]->SetRightMargin(0.13); + c[29]->SetGridx(); + + map1_EEm->GetXaxis()->SetNdivisions(1020); + map1_EEm->GetXaxis() -> SetLabelSize(0.03); + map1_EEm->GetXaxis() ->SetTitle("i#phi"); + map1_EEm->GetYaxis() ->SetTitle("i#eta"); + map1_EEm->GetZaxis() ->SetRangeUser(0.6,1.4); + map1_EEm->Draw("COLZ"); + + + c[30] = new TCanvas("map2_EB","map2_EB"); + c[30]->SetLeftMargin(0.1); + c[30]->SetRightMargin(0.13); + c[30]->SetGridx(); + + map2_EB->GetXaxis()->SetNdivisions(1020); + map2_EB->GetXaxis() -> SetLabelSize(0.03); + map2_EB->GetXaxis() ->SetTitle("i#phi"); + map2_EB->GetYaxis() ->SetTitle("i#eta"); + map2_EB->GetZaxis() ->SetRangeUser(0.6,1.4); + map2_EB->Draw("COLZ"); + + + c[31] = new TCanvas("map2_EEp","map2_EEp"); + c[31]->SetLeftMargin(0.1); + c[31]->SetRightMargin(0.13); + c[31]->SetGridx(); + + map2_EEp->GetXaxis()->SetNdivisions(1020); + map2_EEp->GetXaxis() -> SetLabelSize(0.03); + map2_EEp->GetXaxis() ->SetTitle("i#phi"); + map2_EEp->GetYaxis() ->SetTitle("i#eta"); + map2_EEp->GetZaxis() ->SetRangeUser(0.6,1.4); + map2_EEp->Draw("COLZ"); + + + c[32] = new TCanvas("map2_EEm","map2_EEm"); + c[32]->SetLeftMargin(0.1); + c[32]->SetRightMargin(0.13); + c[32]->SetGridx(); + + map2_EEm->GetXaxis()->SetNdivisions(1020); + map2_EEm->GetXaxis() -> SetLabelSize(0.03); + map2_EEm->GetXaxis() ->SetTitle("i#phi"); + map2_EEm->GetYaxis() ->SetTitle("i#eta"); + map2_EEm->GetZaxis() ->SetRangeUser(0.6,1.4); + map2_EEm->Draw("COLZ"); + + + TFile f("compareIC.root","recreate"); + f.cd(); + + for (int i=0; i<33; i++) { + c[i]->Write(); + } + + f.Write(); + // f.close(); + + // theApp->Run(); + +return 0; + +} + + diff --git a/EOverPCalibration/bin/CompareSCalibMCTruth_EB.cpp b/EOverPCalibration/bin/CompareSCalibMCTruth_EB.cpp index 253013cf2e3..dc5919fbc20 100644 --- a/EOverPCalibration/bin/CompareSCalibMCTruth_EB.cpp +++ b/EOverPCalibration/bin/CompareSCalibMCTruth_EB.cpp @@ -52,11 +52,7 @@ int main(int argc, char**argv){ } std::string configFileName = argv[1]; -#ifdef CMSSW_7_2_X std::shared_ptr parameterSet = edm::readConfig(configFileName); -#else - boost::shared_ptr parameterSet = edm::readConfig(configFileName); -#endif edm::ParameterSet Options = parameterSet -> getParameter("Options"); std::string inputFile = "NULL"; diff --git a/EOverPCalibration/bin/CompareSCalibMCTruth_EE.cpp b/EOverPCalibration/bin/CompareSCalibMCTruth_EE.cpp index e8248f2a93c..a23fe5cbdeb 100644 --- a/EOverPCalibration/bin/CompareSCalibMCTruth_EE.cpp +++ b/EOverPCalibration/bin/CompareSCalibMCTruth_EE.cpp @@ -35,11 +35,7 @@ int main (int argc, char **argv) { std::string configFileName = argv[1]; -#ifdef CMSSW_7_2_X std::shared_ptr parameterSet = edm::readConfig(configFileName); -#else - boost::shared_ptr parameterSet = edm::readConfig(configFileName); -#endif edm::ParameterSet Options = parameterSet -> getParameter("Options"); std::string inputFile = "NULL"; diff --git a/EOverPCalibration/bin/NormalizeIC_EE.cpp b/EOverPCalibration/bin/NormalizeIC_EE.cpp index 41495106c52..66314758069 100644 --- a/EOverPCalibration/bin/NormalizeIC_EE.cpp +++ b/EOverPCalibration/bin/NormalizeIC_EE.cpp @@ -70,11 +70,7 @@ int main( int argc, char **argv){ std::string configFileName = argv[1]; -#ifdef CMSSW_7_2_X std::shared_ptr parameterSet = edm::readConfig(configFileName); -#else - boost::shared_ptr parameterSet = edm::readConfig(configFileName); -#endif edm::ParameterSet Options = parameterSet -> getParameter("Options"); // parameterSet.reset(); diff --git a/EOverPCalibration/cfg/calibrationMomentum_cfg.py b/EOverPCalibration/cfg/calibrationMomentum_cfg.py index 710e5f6f530..50ee397d421 100644 --- a/EOverPCalibration/cfg/calibrationMomentum_cfg.py +++ b/EOverPCalibration/cfg/calibrationMomentum_cfg.py @@ -1,14 +1,14 @@ import FWCore.ParameterSet.Config as cms -process = cms.Process("calibrationMomentumparameters") +process = cms.Process("CalibrationMomentum") process.Options = cms.PSet( TreeName = cms.string("selected"), infileDATA = cms.string("cfg/listDATA_momentumCalibration.txt"), - infileMC = cms.string("cfg/listMC2012_momentumCalibration.txt"), - WeightforMC = cms.string("CommonTools/PUweights_DYJetsToLL_Summer12_Prompt_TrueNumInteractions.root"), - usePUweights = cms.bool(false), + infileMC = cms.string("cfg/listDATA_momentumCalibration.txt"), + WeightforMC = cms.string("pileupDataRun2016B_71p3mb.root"), + usePUweights = cms.bool(False), nPhiBinsEB = cms.int32(360), nPhiBinsEE = cms.int32(360), nEtaBinsEB = cms.int32(1), @@ -17,7 +17,9 @@ nPhiBinsTempEE = cms.int32(1), rebinEB = cms.int32(10), rebinEE = cms.int32(20), - outputFile = cms.string("output/MomentumCalibration2012.root") + outputFile = cms.string("output/MomentumCalibration2016.root"), + typeEB = cms.string("eta1"), + typeEE = cms.string("eta1") ) diff --git a/EOverPCalibration/cfg/listDATA_momentumCalibration.txt b/EOverPCalibration/cfg/listDATA_momentumCalibration.txt index 134a62475a9..79cb419a477 100644 --- a/EOverPCalibration/cfg/listDATA_momentumCalibration.txt +++ b/EOverPCalibration/cfg/listDATA_momentumCalibration.txt @@ -1,5 +1,18 @@ -##/gwteray/users/benaglia/CALIBRATION/NTUPLES_EOverP/ReReco/DoubleElectron_Run2011AB-29Jun2012.root -/gwteray/users/benaglia/CALIBRATION/NTUPLES_EOverP/ReReco/Cal_Dic2012/DoubleElectron-ZSkim-RUN2012A-13Jul-v1.root -/gwteray/users/benaglia/CALIBRATION/NTUPLES_EOverP/ReReco/Cal_Dic2012/DoubleElectron-ZSkim-RUN2012B-13Jul-v1.root -/gwteray/users/benaglia/CALIBRATION/NTUPLES_EOverP/ReReco/Cal_Dic2012/DoubleElectron-ZSkim-RUN2012C-v2.root -/gwteray/users/benaglia/CALIBRATION/NTUPLES_EOverP/ReReco/Cal_Dic2012/DoubleElectron-ZSkim-RUN2012C-v3.root +##MULTIFIT + +#eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016B-ZSkim-Prompt_v2/273150-275376/271036_279931-Cal_Sep2016/withExtras2/DoubleEG-Run2016B-ZSkim-Prompt_v2-273150-275376.root +#eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016C-ZSkim-Prompt_v2/275420-276283/271036_279931-Cal_Sep2016/withExtras2/DoubleEG-Run2016C-ZSkim-Prompt_v2-275420-276283.root +#eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016D-ZSkim-Prompt_v2/276315-276811/271036_279931-Cal_Sep2016/withExtras2/DoubleEG-Run2016D-ZSkim-Prompt_v2-276315-276811.root +#eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016E-ZSkim-Prompt-v2/276830-277420/271036_279931-Cal_Sep2016/withExtras2/DoubleEG-Run2016E-ZSkim-Prompt-v2-276830-277420.root +#eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016F-ZSkim-Prompt-v1/277820-278808/271036_279931-Cal_Sep2016/withExtras2/DoubleEG-Run2016F-ZSkim-Prompt-v1-277820-278808.root +#eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016G-ZSkim-Prompt-v1/278817-279588/271036_279931-Cal_Sep2016/withExtras2/DoubleEG-Run2016G-ZSkim-Prompt-v1-278817-279588.root +#eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016G-ZSkim-Prompt-v1/279589-279931/271036_279931-Cal_Sep2016/withExtras2/DoubleEG-Run2016G-ZSkim-Prompt-v1-279589-279931.root + +##WEIGHTS +eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016B-ZSkim-Prompt_v2-weightsReco/273150-275376/271036_279931-Cal_Sep2016/withExtras/DoubleEG-Run2016B-ZSkim-Prompt_v2-weightsReco-273150-275376.root +eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016C-ZSkim-Prompt_v2-weightsReco/275420-276283/271036_279931-Cal_Sep2016/withExtras/DoubleEG-Run2016C-ZSkim-Prompt_v2-weightsReco-275420-276283.root +eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016D-ZSkim-Prompt_v2-weightsReco/276315-276811/271036_279931-Cal_Sep2016/withExtras/DoubleEG-Run2016D-ZSkim-Prompt_v2-weightsReco-276315-276811.root +eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016E-ZSkim-Prompt-v2-weightsReco/276830-277420/271036_279931-Cal_Sep2016/withExtras/DoubleEG-Run2016E-ZSkim-Prompt-v2-weightsReco-276830-277420.root +eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016F-ZSkim-Prompt-v1-weightsReco/277820-278808/271036_279931-Cal_Sep2016/withExtras/DoubleEG-Run2016F-ZSkim-Prompt-v1-weightsReco-277820-278808.root +eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016G-ZSkim-Prompt-v1-weightsReco/278817-279588/271036_279931-Cal_Sep2016/withExtras/DoubleEG-Run2016G-ZSkim-Prompt-v1-weightsReco-278817-279588.root +eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016G-ZSkim-Prompt-v1-weightsReco/279589-279931/271036_279931-Cal_Sep2016/withExtras/DoubleEG-Run2016G-ZSkim-Prompt-v1-weightsReco-279589-279931.root diff --git a/EOverPCalibration/cfg/listMC2012_momentumCalibration.txt b/EOverPCalibration/cfg/listMC2012_momentumCalibration.txt index 485a82a821d..b3fd65498c3 100644 --- a/EOverPCalibration/cfg/listMC2012_momentumCalibration.txt +++ b/EOverPCalibration/cfg/listMC2012_momentumCalibration.txt @@ -1,6 +1,11 @@ -##/gwteray/users/benaglia/CALIBRATION/NTUPLES_EOverP/MC/DYJets-Summer12.root -##/gwteray/users/benaglia/CALIBRATION/NTUPLES_EOverP/ReReco/DoubleElectron_Run2011AB-29Jun2012.root -/gwteray/users/benaglia/CALIBRATION/NTUPLES_EOverP/ReReco/Cal_Dic2012/DoubleElectron-ZSkim-RUN2012A-13Jul-v1.root -/gwteray/users/benaglia/CALIBRATION/NTUPLES_EOverP/ReReco/Cal_Dic2012/DoubleElectron-ZSkim-RUN2012B-13Jul-v1.root -/gwteray/users/benaglia/CALIBRATION/NTUPLES_EOverP/ReReco/Cal_Dic2012/DoubleElectron-ZSkim-RUN2012C-v2.root -/gwteray/users/benaglia/CALIBRATION/NTUPLES_EOverP/ReReco/Cal_Dic2012/DoubleElectron-ZSkim-RUN2012C-v3.root +##MULTIFIT + +eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016B-ZSkim-Prompt_v2/273150-275376/271036_279931-Cal_Sep2016/withExtras2/DoubleEG-Run2016B-ZSkim-Prompt_v2-273150-275376.root +eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016C-ZSkim-Prompt_v2/275420-276283/271036_279931-Cal_Sep2016/withExtras2/DoubleEG-Run2016C-ZSkim-Prompt_v2-275420-276283.root +eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016D-ZSkim-Prompt_v2/276315-276811/271036_279931-Cal_Sep2016/withExtras2/DoubleEG-Run2016D-ZSkim-Prompt_v2-276315-276811.root +eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016E-ZSkim-Prompt-v2/276830-277420/271036_279931-Cal_Sep2016/withExtras2/DoubleEG-Run2016E-ZSkim-Prompt-v2-276830-277420.root +eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016F-ZSkim-Prompt-v1/277820-278808/271036_279931-Cal_Sep2016/withExtras2/DoubleEG-Run2016F-ZSkim-Prompt-v1-277820-278808.root +eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016G-ZSkim-Prompt-v1/278817-279588/271036_279931-Cal_Sep2016/withExtras2/DoubleEG-Run2016G-ZSkim-Prompt-v1-278817-279588.root +eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016G-ZSkim-Prompt-v1/279589-279931/271036_279931-Cal_Sep2016/withExtras2/DoubleEG-Run2016G-ZSkim-Prompt-v1-279589-279931.root + +##WEIGHTS diff --git a/EOverPCalibration/interface/CalibrationUtils.h b/EOverPCalibration/interface/CalibrationUtils.h index 29a979c76d9..8567155672c 100644 --- a/EOverPCalibration/interface/CalibrationUtils.h +++ b/EOverPCalibration/interface/CalibrationUtils.h @@ -6,7 +6,9 @@ #include "../interface/TEndcapRings.h" +void DrawCorr_EE(TH2F* h_scale_EEM, TH2F* h_scale_EEP, TH2F* hcmap_EEM, TH2F* hcmap_EEP, const std::vector< std::pair > & TT_centre_EEM, const std::vector< std::pair > & TT_centre_EEP, std::vector > & correctionMomentum, TEndcapRings *eRings, bool skip = true, int nEtaBinsEE=5, float etaMin=1.4, float etaMax=2.5); +void DrawICCorr_EE(TH2F* h_scale_EEM, TH2F* h_scale_EEP, TH2F* hcmap_EEM, TH2F* hcmap_EEP, const std::vector< std::pair > & TT_centre_EEM, const std::vector< std::pair > & TT_centre_EEP, std::vector > & correctionMomentum, TEndcapRings *eRings, bool skip = true, int nEtaBinsEE=5, float etaMin=1.4, float etaMax=2.5, int shift=0); //############## ECAL BARREL #################### /// Check if the crystal is near to a dead one diff --git a/EOverPCalibration/interface/ConvoluteTemplate.h b/EOverPCalibration/interface/ConvoluteTemplate.h new file mode 100644 index 00000000000..745b2d8945a --- /dev/null +++ b/EOverPCalibration/interface/ConvoluteTemplate.h @@ -0,0 +1,14 @@ +#ifndef ConvoluteTemplate_h +#define ConvoluteTemplate_h + +#include "histoFunc.h" + +#include "TH1.h" +#include "TF1.h" +#include "TVirtualFFT.h" + + +TH1F* ConvoluteTemplate(const std::string& name, TH1F* h_template, TH1F* h_smearing, + int nPoints, double min, double max); + +#endif diff --git a/EOverPCalibration/interface/FastCalibratorEB.h b/EOverPCalibration/interface/FastCalibratorEB.h index c107689dd6f..ce3efe8563c 100644 --- a/EOverPCalibration/interface/FastCalibratorEB.h +++ b/EOverPCalibration/interface/FastCalibratorEB.h @@ -33,7 +33,7 @@ class FastCalibratorEB { ///! List of class methods - FastCalibratorEB(TTree *tree, std::vector & inputMomentumScale, const std::string& typeEB, TString outEPDistribution="NULL"); + FastCalibratorEB(TTree *tree, std::vector & inputMomentumScale, std::vector & inputEnergyScale, const std::string& typeEB, TString outEPDistribution="NULL"); virtual ~FastCalibratorEB(); @@ -49,9 +49,9 @@ class FastCalibratorEB { virtual void FillScalibMap (TString miscalibMap); - virtual void Loop(int, int, int, int, int,bool,bool,bool,bool,float,bool,float,bool,float,bool,std::map > >, float, TString); + virtual void Loop(int, int, int, int, int,bool,bool,int,bool,bool,bool,bool,float,float,int,bool,float,bool,float,bool,std::map > >, float, TString); - virtual void BuildEoPeta_ele(int,int,int,int,std::vector,bool,bool,float,bool,float,bool,float,bool); + virtual void BuildEoPeta_ele(int,int,int,int,bool,bool,int,std::vector,bool,bool,float,bool,float,bool,float,bool); virtual void saveEoPeta(TFile * f2); @@ -63,6 +63,7 @@ class FastCalibratorEB { // Public Variables std::vector myMomentumScale; + std::vector myEnergyScale; std::string myTypeEB; TTree *fChain; //!pointer to the analyzed TTree or TChain diff --git a/EOverPCalibration/interface/FastCalibratorEE.h b/EOverPCalibration/interface/FastCalibratorEE.h index 84c40200a68..6e404b0ba97 100644 --- a/EOverPCalibration/interface/FastCalibratorEE.h +++ b/EOverPCalibration/interface/FastCalibratorEE.h @@ -33,7 +33,7 @@ class FastCalibratorEE{ public : ///! Class methods - FastCalibratorEE(TTree *tree, std::vector & inputMomentumScale, const std::string& typeEE, TString outEPDistribution="NULL"); + FastCalibratorEE(TTree *tree, std::vector & inputMomentumScale, std::vector & inputEnergyScale, const std::string& typeEE, TString outEPDistribution="NULL"); virtual ~FastCalibratorEE(); @@ -49,8 +49,8 @@ class FastCalibratorEE{ virtual void FillScalibMap (TString miscalibMap); - virtual void Loop(int, int, int, int, int, bool,bool,bool,bool,float,bool,float,bool,float,bool,std::map > >, float, TString); - virtual void BuildEoPeta_ele(int,int,int,int,std::vector ,bool,bool,float,bool,float,bool,float,bool); + virtual void Loop(int, int, int, int, int, bool, bool, int, bool,bool,bool,bool,float,float,int,bool,float,bool,float,bool,std::map > >, float, TString); + virtual void BuildEoPeta_ele(int,int,int,int,bool,bool,int, std::vector ,bool,bool,float,bool,float,bool,float,bool); virtual void saveEoPeta(TFile * f2); @@ -60,6 +60,7 @@ class FastCalibratorEE{ std::vector myMomentumScale; + std::vector myEnergyScale; std::string myTypeEE; TTree *fChain; //!pointer to the analyzed TTree or TChain diff --git a/EOverPCalibration/interface/LaserMonitoringEoP.h b/EOverPCalibration/interface/LaserMonitoringEoP.h new file mode 100644 index 00000000000..3ce2c4c8171 --- /dev/null +++ b/EOverPCalibration/interface/LaserMonitoringEoP.h @@ -0,0 +1,76 @@ +////////////////////////////////////////////////////////// +// Class for the monitoring of laser corrections with E/p +////////////////////////////////////////////////////////// + +#ifndef LaserMonitoringEoP_h +#define LaserMonitoringEoP_h + +#include +#include +#include +#include +#include +#include +#include +#include "../interface/hChain.h" +#include "../interface/h2Chain.h" +#include +#include +#include "TVirtualFitter.h" +#include "TLatex.h" +#include "TSystem.h" +#include "TStyle.h" +#include "TColor.h" +//#include "../../ZFitter/interface/setTDRStyle.h" + +#include "../interface/ntpleUtils.h" +#include "../interface/CalibrationUtils.h" +#include "../interface/FastCalibratorEB.h" +#include "../interface/FastCalibratorEE.h" + +#include "../interface/TEndcapRings.h" +#include "../CommonTools/histoFunc.h" +//#include "treeReader.h" +//#include "setTDRStyle.h" +#include "../interface/ntpleUtils2.h" +#include "../interface/ConvoluteTemplate.h" +#include "../interface/stabilityUtils.h" +#include "../interface/geometryUtils.h" +//#include "Math/PtEtaPhiE4D.h" +//#include "Math/PtEtaPhiM4D.h" +//#include "Math/LorentzVector.h" + +class LaserMonitoringEoP { + + public : + + ///! List of class methods + + LaserMonitoringEoP(TTree *tree, TTree *treeMC, int useRegression); + + virtual ~LaserMonitoringEoP(); + + virtual void Init(TTree *tree, TTree *treeMC, int useRegression); + + virtual void Loop(float, float, std::string, int, int, std::string, std::string, std::string, std::string, int); + + virtual void setLaserPlotStyle(); + + TTree *fChain; //!pointer to the analyzed TTree or TChain + TTree *fChainMC; //!pointer to the analyzed TTree or TChain + Int_t fCurrent; //!current Tree number in a TChain + Int_t fCurrentMC; //!current Tree number in a TChain + + ///! Declaration of leaf types + + int runNumber; + int runTime; + int nPU; + int nPV; + float avgLCSCEle[3], etaSCEle[3], phiSCEle[3], energySCEle[3], esEnergySCEle[3], pAtVtxGsfEle[3], energySCEle_corr[3]; + int seedXSCEle[3], seedYSCEle[3];//, seedZside; + // float seedLaserAlphaSCEle1; + +}; + +#endif diff --git a/EOverPCalibration/interface/histoFunc.h b/EOverPCalibration/interface/histoFunc.h new file mode 100644 index 00000000000..956d87a6568 --- /dev/null +++ b/EOverPCalibration/interface/histoFunc.h @@ -0,0 +1,87 @@ +#ifndef histoFunc_h +#define histoFunc_h + +#include "TH1.h" + + + + + + +class histoFunc +{ + public: + + + //! ctor + histoFunc(TH1F* histo) + { + histo_p = histo; + }; + + + //! dtor + ~histoFunc() + {}; + + + //! operator() + double operator()(double* x, double* par) + { + double xx = par[1] * (x[0] - par[2]); + + double xMin = histo_p -> GetBinCenter(1); + double xMax = histo_p -> GetBinCenter(histo_p -> GetNbinsX()); + + + + if( (xx < xMin) || (xx >= xMax) ) + return 1.e-10; + + else + { + int bin = histo_p -> FindBin(xx); + int bin1 = 0; + int bin2 = 0; + + if(xx >= histo_p -> GetBinCenter(bin)) + { + bin1 = bin; + bin2 = bin+1; + } + + else + { + bin1 = bin-1; + bin2 = bin; + } + + + double x1 = histo_p -> GetBinCenter(bin1); + double y1 = histo_p -> GetBinContent(bin1); + + double x2 = histo_p -> GetBinCenter(bin2); + double y2 = histo_p -> GetBinContent(bin2); + + double m = 1. * (y2 - y1) / (x2 - x1); + + + + if( (y1 + m * (xx - x1)) < 1.e-10) + return 1.e-10; + + + return par[0] * par[1] * (y1 + m * (xx - x1)); + } + + return 1.e-10; + } + + + + private: + + TH1F* histo_p; +}; + +#endif diff --git a/EOverPCalibration/interface/ntpleUtils2.h b/EOverPCalibration/interface/ntpleUtils2.h new file mode 100644 index 00000000000..d88d3838133 --- /dev/null +++ b/EOverPCalibration/interface/ntpleUtils2.h @@ -0,0 +1,79 @@ +#ifndef ntupleUtils2_h +#define ntupleUtils2_h + +#include +#include +#include +#include + + +#include "TFile.h" +#include "TChain.h" +#include "TCanvas.h" +#include "TH1F.h" +#include "TF1.h" + +#ifdef _MAKECINT_ +#pragma link C++ class vector+; +#pragma link C++ class vector+; +#pragma link C++ class map+; +#pragma link C++ class map+; +#endif + + +extern TH1F* templateHisto; +extern TF1* templateFunc; + +extern std::vector* mydata; + +void FitTemplate(const bool& draw = false); + +/*** double crystall ball ***/ +double crystalBallLowHigh_v2(double* x, double* par); + +/*** time sort a tree ***/ +struct Sorter +{ + int time; + int entry; + + bool operator() (const Sorter& s1, const Sorter& s2) + { + return s1.time < s2.time; + } +}; + +/*** time sort a tree ***/ +struct myEvent +{ + int runId; + int timeStampHigh; + + int region; + + float scE; + float P; + + float scLaserCorr; + float seedLaserAlpha; + + bool operator() (const myEvent& s1, const myEvent& s2) + { + return s1.timeStampHigh < s2.timeStampHigh; + } +}; + +/*** time sort a tree ***/ +struct SorterLC +{ + float laserCorr; + int entry; + + bool operator() (const SorterLC& s1, const SorterLC& s2) + { + return s1.laserCorr < s2.laserCorr; + } +}; + + +#endif diff --git a/EOverPCalibration/interface/stabilityUtils.h b/EOverPCalibration/interface/stabilityUtils.h new file mode 100644 index 00000000000..717a323d688 --- /dev/null +++ b/EOverPCalibration/interface/stabilityUtils.h @@ -0,0 +1,24 @@ +#ifndef stabilityUtils_h +#define stabilityUtils_h + +#include "histoFunc.h" +#include +#include +#include + +#include +#include + +#include "TH1F.h" +#include "TF1.h" + +#include +#include + +int dateToInt(const std::string& date); + +void SetHistoStyle(TH1* h, const std::string& label = ""); + +TH1F* MellinConvolution(const std::string& name, TH1F* h_template, TH1F* h_Las); + +#endif diff --git a/EOverPCalibration/pileupDataRun2016B_71p3mb.root b/EOverPCalibration/pileupDataRun2016B_71p3mb.root new file mode 100644 index 00000000000..5a9e9b39cf8 Binary files /dev/null and b/EOverPCalibration/pileupDataRun2016B_71p3mb.root differ diff --git a/EOverPCalibration/src/CalibrationUtils.cc b/EOverPCalibration/src/CalibrationUtils.cc index 32649b773ae..e6bdc4948ef 100644 --- a/EOverPCalibration/src/CalibrationUtils.cc +++ b/EOverPCalibration/src/CalibrationUtils.cc @@ -5,6 +5,283 @@ +void DrawCorr_EE(TH2F* h_scale_EEM, TH2F* h_scale_EEP, + TH2F* hcmap_EEM, TH2F* hcmap_EEP, + const std::vector< std::pair >& TT_centre_EEM, + const std::vector< std::pair >& TT_centre_EEP, + std::vector >& correctionMomentum, TEndcapRings* eRings, bool skip , int nEtaBinsEE, float etaMin, float etaMax) +{ + std::map h_scale_EE; + std::map hcmap_EE; + + h_scale_EE[0] = h_scale_EEM; + h_scale_EE[1] = h_scale_EEP; + + hcmap_EE[0] = hcmap_EEM; + hcmap_EE[1] = hcmap_EEP; + + + + std::map > sumIC; + std::map > numIC; + + (sumIC[0]).assign(40,0.); + (sumIC[1]).assign(40,0.); + + (numIC[0]).assign(40,0); + (numIC[1]).assign(40,0); + + + + // mean over phi corrected skipping dead channel + for(int k = 0; k < 2; ++k) + for(int ix = 1; ix <= h_scale_EE[k] -> GetNbinsX(); ++ix) + for(int iy = 1; iy <= h_scale_EE[k] -> GetNbinsY(); ++iy) + { + int ring = eRings->GetEndcapRing(ix,iy,k); + if( ring == -1 ) continue; + + bool isGood = CheckxtalIC_EE(h_scale_EE[k],ix,iy,ring); + bool isGoodTT; + if( k == 0 ) isGoodTT = CheckxtalTT_EE(ix,iy,ring,TT_centre_EEM); + else isGoodTT = CheckxtalTT_EE(ix,iy,ring,TT_centre_EEP); + + if( isGoodTT && isGood ) + { + (sumIC[k]).at(ring) += h_scale_EE[k]->GetBinContent(ix,iy); + (numIC[k]).at(ring) += 1; + } + } + + // normalize IC skipping bad channels and bad TTs + for(int k = 0; k < 2; ++k) + for(int ix = 1; ix <= h_scale_EE[k]->GetNbinsX(); ++ix) + for(int iy = 1; iy <= h_scale_EE[k]->GetNbinsY(); ++iy) + { + int ring = eRings->GetEndcapRing(ix,iy,k); + if( ring == -1 ) continue; + + if( !skip ) + { + if( ring > 33 ) + { + hcmap_EE[k] -> Fill(ix,iy,0.); + continue; + } + else + { + if( (numIC[k]).at(ring) != 0 && (sumIC[k]).at(ring) != 0 ) { + int zside=0; + if (k==0) zside=-1; + if (k==1) zside=1; + int iPhi = eRings->GetEndcapIphi(ix,iy,zside); + float phi = ((float)iPhi*2.*TMath::Pi()/360. - TMath::Pi()); + // int iRing = 85 + eRings -> GetEndcapRing(ix,iy,zside); + //float eta = eRings -> GetEtaFromIRing(iRing); + + //int etaBin = int((fabs(eta)-etaMin)/float((etaMax-etaMin)/nEtaBinsEE)); + //if (fabs(eta)etaMax) etaBin=nEtaBinsEE-1; + // std::cout< Fill(ix,iy,correctionMomentum.at(0).at(k)->Eval(phi)); + } + } + } + + if( skip ) + { + bool isGood = CheckxtalIC_EE(h_scale_EE[k],ix,iy,ring); + bool isGoodTT; + + if( k == 0 ) isGoodTT = CheckxtalTT_EE(ix,iy,ring,TT_centre_EEM); + else isGoodTT = CheckxtalTT_EE(ix,iy,ring,TT_centre_EEP); + + if( isGood && isGoodTT ) + { + if( ring > 33 ) + { + hcmap_EE[k] -> Fill(ix,iy,0.); + continue; + } + else + { + if( (numIC[k]).at(ring) != 0 && (sumIC[k]).at(ring) != 0 ) { + int zside=0; + if (k==0) zside=-1; + if (k==1) zside=1; + int iPhi = eRings->GetEndcapIphi(ix,iy,zside); + float phi = ((float)iPhi*2.*TMath::Pi()/360. - TMath::Pi()); + /* + int iRing = 85 + eRings -> GetEndcapRing(ix,iy,zside); + float eta = eRings -> GetEtaFromIRing(iRing); + + int etaBin = int((fabs(eta)-etaMin)/float((etaMax-etaMin)/nEtaBinsEE)); + if (fabs(eta)etaMax) etaBin=nEtaBinsEE-1; + // std::cout< Fill(ix,iy,correctionMomentum.at(0).at(k)->Eval(phi)); + if (ix==30 && iy==32 && k==1) + std::cout<<"corr: "<Eval(phi)< >& TT_centre_EEM, + const std::vector< std::pair >& TT_centre_EEP, + std::vector > & correctionMomentum, TEndcapRings* eRings, bool skip , int nEtaBinsEE, float etaMin, float etaMax, + int shift) +{ + std::map h_scale_EE; + std::map hcmap_EE; + + h_scale_EE[0] = h_scale_EEM; + h_scale_EE[1] = h_scale_EEP; + + hcmap_EE[0] = hcmap_EEM; + hcmap_EE[1] = hcmap_EEP; + + + + std::map > sumIC; + std::map > numIC; + + (sumIC[0]).assign(40,0.); + (sumIC[1]).assign(40,0.); + + (numIC[0]).assign(40,0); + (numIC[1]).assign(40,0); + + // mean over phi corrected skipping dead channel + for(int k = 0; k < 2; ++k) + for(int ix = 1; ix <= h_scale_EE[k] -> GetNbinsX(); ++ix) + for(int iy = 1; iy <= h_scale_EE[k] -> GetNbinsY(); ++iy) + { + int ring = eRings->GetEndcapRing(ix,iy,k); + if( ring == -1 ) continue; + + bool isGood = CheckxtalIC_EE(h_scale_EE[k],ix,iy,ring); + bool isGoodTT; + if( k == 0 ) isGoodTT = CheckxtalTT_EE(ix,iy,ring,TT_centre_EEM); + else isGoodTT = CheckxtalTT_EE(ix,iy,ring,TT_centre_EEP); + + if( isGoodTT && isGood ) + { + int zside=0; + if (k==0) zside=-1; + if (k==1) zside=1; + int iPhi = eRings->GetEndcapIphi(ix,iy,zside); + if (iPhi+shift>=360) iPhi-=360; + /* + int iRing = 85 + eRings -> GetEndcapRing(ix,iy,zside); + float eta = eRings -> GetEtaFromIRing(iRing); + + int etaBin = int((fabs(eta)-etaMin)/float((etaMax-etaMin)/nEtaBinsEE)); + if (fabs(eta)etaMax) etaBin=nEtaBinsEE-1; + // std::cout<GetBinContent(ix,iy);///correctionMomentum.at(etaBin).at(k)->Eval(iPhi+shift); + (numIC[k]).at(ring) += 1; + } + } + + // normalize IC skipping bad channels and bad TTs + for(int k = 0; k < 2; ++k) + for(int ix = 1; ix <= h_scale_EE[k]->GetNbinsX(); ++ix) + for(int iy = 1; iy <= h_scale_EE[k]->GetNbinsY(); ++iy) + { + int ring = eRings->GetEndcapRing(ix,iy,k); + if( ring == -1 ) continue; + + if( !skip ) + { + if( ring > 33 ) + { + hcmap_EE[k] -> Fill(ix,iy,0.); + continue; + } + else + { + if( (numIC[k]).at(ring) != 0 && (sumIC[k]).at(ring) != 0 ) { + int zside=0; + if (k==0) zside=-1; + if (k==1) zside=1; + int iPhi = eRings->GetEndcapIphi(ix,iy,zside); + float phi = ((float)iPhi*2.*TMath::Pi()/360. - TMath::Pi()); + if (iPhi+shift>=360) iPhi-=360; + /* + int iRing = 85 + eRings -> GetEndcapRing(ix,iy,zside); + float eta = eRings -> GetEtaFromIRing(iRing); + + int etaBin = int((fabs(eta)-etaMin)/float((etaMax-etaMin)/nEtaBinsEE)); + if (fabs(eta)etaMax) etaBin=nEtaBinsEE-1; + // std::cout< Fill(ix,iy,(h_scale_EE[k]->GetBinContent(ix,iy)/correctionMomentum.at(0).at(k)->Eval(phi))/((sumIC[k]).at(ring)/(numIC[k]).at(ring))); + } + } + } + + if( skip ) + { + bool isGood = CheckxtalIC_EE(h_scale_EE[k],ix,iy,ring); + bool isGoodTT; + + if( k == 0 ) isGoodTT = CheckxtalTT_EE(ix,iy,ring,TT_centre_EEM); + else isGoodTT = CheckxtalTT_EE(ix,iy,ring,TT_centre_EEP); + + if( isGood && isGoodTT ) + { + if( ring > 33 ) + { + hcmap_EE[k] -> Fill(ix,iy,0.); + continue; + } + else + { + if( (numIC[k]).at(ring) != 0 && (sumIC[k]).at(ring) != 0 ) { + int zside=0; + if (k==0) zside=-1; + if (k==1) zside=1; + int iPhi = eRings->GetEndcapIphi(ix,iy,zside); + float phi = ((float)iPhi*2.*TMath::Pi()/360. - TMath::Pi()); + if (iPhi+shift>=360) iPhi-=360; + /* + int iRing = 85 + eRings -> GetEndcapRing(ix,iy,zside); + float eta = eRings -> GetEtaFromIRing(iRing); + + int etaBin = int((fabs(eta)-etaMin)/float((etaMax-etaMin)/nEtaBinsEE)); + if (fabs(eta)etaMax) etaBin=nEtaBinsEE-1; + // std::cout< Fill(ix,iy,(h_scale_EE[k]->GetBinContent(ix,iy)/correctionMomentum.at(0).at(k)->Eval(phi))/((sumIC[k]).at(ring)/(numIC[k]).at(ring))); + if (ix==30 && iy==32 && k==1) + std::cout<<"IC_corr: "<<(h_scale_EE[k]->GetBinContent(ix,iy)/correctionMomentum.at(0).at(k)->Eval(phi))/((sumIC[k]).at(ring)/(numIC[k]).at(ring))<GetBinContent(ix,iy)<<" "<Eval(iPhi+shift)< >& TT_centre) TT_centre.push_back(std::pair (-8,53)); TT_centre.push_back(std::pair (-3,63)); TT_centre.push_back(std::pair (-53,128)); + TT_centre.push_back(std::pair (-28,168)); TT_centre.push_back(std::pair (-53,183)); TT_centre.push_back(std::pair (-83,193)); TT_centre.push_back(std::pair (-74,218)); TT_centre.push_back(std::pair (-8,223)); + TT_centre.push_back(std::pair (-48,273)); TT_centre.push_back(std::pair (-68,303)); TT_centre.push_back(std::pair (-43,328)); + TT_centre.push_back(std::pair (-43,243)); } void InitializeDeadTT_EB2012(std::vector >& TT_centre) @@ -838,14 +1118,20 @@ void InitializeDeadTT_EB2012(std::vector >& TT_centre) void InitializeDeadTTEEP(std::vector >& TT_centre) { + // TT_centre.push_back(std::pair (78,78)); + // TT_centre.push_back(std::pair (83,28)); + // TT_centre.push_back(std::pair (83,23)); TT_centre.push_back(std::pair (78,78)); TT_centre.push_back(std::pair (83,28)); - TT_centre.push_back(std::pair (83,23)); + TT_centre.push_back(std::pair (33,18)); } void InitializeDeadTTEEM(std::vector >& TT_centre) { - TT_centre.push_back(std::pair (53,28)); + // TT_centre.push_back(std::pair (53,28)); + TT_centre.push_back(std::pair (53,28)); + TT_centre.push_back(std::pair (28,33)); + TT_centre.push_back(std::pair (89,80)); } void InitializeDeadTTEEP2012(std::vector >& TT_centre) diff --git a/EOverPCalibration/src/ConvoluteTemplate.cc b/EOverPCalibration/src/ConvoluteTemplate.cc new file mode 100644 index 00000000000..dce8053f1fb --- /dev/null +++ b/EOverPCalibration/src/ConvoluteTemplate.cc @@ -0,0 +1,157 @@ +#include "../interface/ConvoluteTemplate.h" + + + +TH1F* ConvoluteTemplate(const std::string& name, TH1F* h_template, TH1F* h_smearing, + int nPoints, double min, double max) +{ + double width = 1.*(max-min)/nPoints; + + double* FFT_re_func1 = new double[nPoints]; + double* FFT_im_func1 = new double[nPoints]; + double* FFT_re_func2 = new double[nPoints]; + double* FFT_im_func2 = new double[nPoints]; + double* FFT_re_convolution = new double[nPoints]; + double* FFT_im_convolution = new double[nPoints]; + + + + //----------------------------- + // define the initial functions + + char funcName[50]; + + + sprintf(funcName,"f_template_temp"); + histoFunc* hf_template = new histoFunc(h_template); + TF1* f_template = new TF1(funcName, hf_template, min, max, 3, "histoFunc"); + + f_template -> FixParameter(0,1.); + f_template -> FixParameter(1,1.); + f_template -> FixParameter(2,0.); + + + sprintf(funcName,"f_smearing_temp"); + histoFunc* hf_smearing = new histoFunc(h_smearing); + TF1* f_smearing = new TF1(funcName, hf_smearing, min, max, 3, "histoFunc"); + f_smearing -> FixParameter(0,1.); + f_smearing -> FixParameter(1,1.); + f_smearing -> FixParameter(2,-1.*h_smearing->GetMean()); + + + // use a gaussian as smearing function + //TF1* f_smearing = new TF1("f_smearing","1./([0]*sqrt(2.*3.14159))*exp(-1.*x*x/(2.*[0]*[0]))",min,max); + //f_smearing -> FixParameter(0,0.05); + + + + //----------------------------------------- + // define the histograms to contain the FFT + TH1D* h_func1 = new TH1D("h_func1", "",nPoints,min,max); + TH1D* h_func1_FFT = new TH1D("h_func1_FFT","",nPoints,min,max); + + TH1D* h_func2 = new TH1D("h_func2", "",nPoints,min,max); + TH1D* h_func2_FFT = new TH1D("h_func2_FFT","",nPoints,min,max); + + for(int bin = 1; bin <= nPoints; ++bin) + { + h_func1 -> SetBinContent(bin,f_template->Eval(min+width*(bin-1))); + h_func2 -> SetBinContent(bin,f_smearing->Eval(min+width*(bin-1))); + } + + //h_func1 -> Write(); + //h_func2 -> Write(); + + + + //----------- + // do the FFT + + h_func1 -> FFT(h_func1_FFT,"MAG R2C M"); + TVirtualFFT* FFT_func1 = TVirtualFFT::GetCurrentTransform(); + FFT_func1 -> GetPointsComplex(FFT_re_func1,FFT_im_func1); + FFT_func1 -> Delete(); + + h_func2 -> FFT(h_func2_FFT, "MAG R2C M"); + TVirtualFFT* FFT_func2 = TVirtualFFT::GetCurrentTransform(); + FFT_func2 -> GetPointsComplex(FFT_re_func2,FFT_im_func2); + FFT_func2 -> Delete(); + + + + //--------------------------------- + // convolution in the Fourier space + + for(int bin = 1; bin <= nPoints; ++bin) + { + FFT_re_convolution[bin-1] = FFT_re_func1[bin-1]*FFT_re_func2[bin-1] - FFT_im_func1[bin-1]*FFT_im_func2[bin-1]; + FFT_im_convolution[bin-1] = FFT_re_func1[bin-1]*FFT_im_func2[bin-1] + FFT_im_func1[bin-1]*FFT_re_func2[bin-1]; + } + + + + //---------------- + // do the anti FFT + + TVirtualFFT* AFFT_convolution = TVirtualFFT::FFT(1, &nPoints, "C2R M K"); + AFFT_convolution -> SetPointsComplex(FFT_re_convolution,FFT_im_convolution); + AFFT_convolution -> Transform(); + + TH1* h_convolution_temp = NULL; + h_convolution_temp = TH1::TransformHisto(AFFT_convolution,h_convolution_temp,"Re"); + h_convolution_temp -> SetName("h_convolution_temp"); + h_convolution_temp -> Scale((max-min)/nPoints/nPoints); + AFFT_convolution -> Delete(); + + TH1D* h_convolution = new TH1D("h_convolution","",nPoints,min,max); + for(int bin = 1; bin <= nPoints; ++bin) + { + h_convolution -> Fill((max-min)/nPoints*(bin-1),h_convolution_temp->GetBinContent(bin)); + } + + histoFunc* convolutionHistoFunc = new histoFunc((TH1F*)(h_convolution)); + TF1* f_convolution = new TF1("f_convolution", convolutionHistoFunc, min, max, 3, "histoFunc"); + f_convolution -> FixParameter(0, 1); + f_convolution -> FixParameter(1, 1); + f_convolution -> FixParameter(2, 0.); + + + + int nBins = h_template->GetNbinsX(); + float xMin = h_template->GetBinLowEdge(1); + float xMax = h_template->GetBinLowEdge(nBins) + h_template->GetBinWidth(nBins); + float xWidth = (xMax-xMin)/nBins; + TH1F* h_final = new TH1F(name.c_str(),"",nBins,xMin,xMax); + + for(int bin = 1; bin <=nBins; ++bin) + { + float xMinBin = h_final->GetBinLowEdge(bin); + float xMaxBin = h_final->GetBinLowEdge(bin) + xWidth; + + h_final -> SetBinContent(bin,f_convolution->Integral(xMinBin,xMaxBin)/xWidth); + } + + h_final -> Scale(h_template->Integral()/h_final->Integral()); + //h_final -> Write(); + + + + f_template -> Delete(); + f_smearing -> Delete(); + + h_func1_FFT -> Delete(); + h_func1 -> Delete(); + + h_func2_FFT -> Delete(); + h_func2 -> Delete(); + + h_convolution_temp -> Delete(); + h_convolution -> Delete(); + + f_convolution -> Delete(); + delete convolutionHistoFunc; + + + + return h_final; +} diff --git a/EOverPCalibration/src/DrawingUtils.cc b/EOverPCalibration/src/DrawingUtils.cc index d2c20a79288..a0f33fc33f5 100644 --- a/EOverPCalibration/src/DrawingUtils.cc +++ b/EOverPCalibration/src/DrawingUtils.cc @@ -88,7 +88,7 @@ void DrawSpreadGraph(TGraphErrors* g, const std::string& fileName, const std::st { TCanvas* c; - SetLabelAndTitle(g); + SetLabelAndTitle(g_stat); if( isEB == true ) { @@ -96,11 +96,11 @@ void DrawSpreadGraph(TGraphErrors* g, const std::string& fileName, const std::st c -> SetGridx(); c -> SetGridy(); - g -> GetXaxis() -> SetRangeUser(0.,85.999); - g -> GetYaxis() -> SetRangeUser(0.00,0.05); - g -> GetXaxis() -> SetTitle("|i#eta|"); - g -> GetYaxis() -> SetTitle("#sigma"); - g -> Draw("AP"); + g_stat -> GetXaxis() -> SetRangeUser(0.,85.999); + g_stat -> GetYaxis() -> SetRangeUser(0.00,0.05); + g_stat -> GetXaxis() -> SetTitle("|i#eta|"); + g_stat -> GetYaxis() -> SetTitle("#sigma"); + g_stat -> Draw("AP"); } else { @@ -108,28 +108,30 @@ void DrawSpreadGraph(TGraphErrors* g, const std::string& fileName, const std::st c -> SetGridx(); c -> SetGridy(); - g -> GetXaxis() -> SetRangeUser(-1.,38.999); - g -> GetYaxis() -> SetRangeUser(0.00,0.30); - g -> GetXaxis() -> SetTitle("iRing"); - g -> GetYaxis() -> SetTitle("#sigma"); - g -> Draw("AP"); + g_stat -> GetXaxis() -> SetRangeUser(-1.,38.999); + g_stat -> GetYaxis() -> SetRangeUser(0.00,0.05); + g_stat -> GetXaxis() -> SetTitle("iRing"); + g_stat -> GetYaxis() -> SetTitle("#sigma"); + g_stat -> Draw("AP"); } TLegend* leg = new TLegend(0.15,0.74,0.43,0.89); leg -> SetFillColor(0); leg -> SetTextFont(42); leg -> SetTextSize(0.05); - leg -> AddEntry(g,"IC spread","P"); + // leg -> AddEntry(g,"IC spread","P"); + leg -> AddEntry(g_stat,"Statistical precision","P"); - if( g_stat != NULL ) + /* if( g_stat != NULL ) { g_stat -> Draw("P,same"); leg -> AddEntry(g_stat,"statistical precision","P"); } - + */ leg -> Draw("same"); - c -> Print((fileName+".png").c_str(),"png"); + c -> Print((fileName+"."+fileType).c_str(),fileType.c_str()); + // c -> Print((fileName+".png").c_str(),"png"); delete c; } diff --git a/EOverPCalibration/src/FastCalibratorEB.cc b/EOverPCalibration/src/FastCalibratorEB.cc index aa3375ca566..ea87f85029c 100644 --- a/EOverPCalibration/src/FastCalibratorEB.cc +++ b/EOverPCalibration/src/FastCalibratorEB.cc @@ -16,7 +16,7 @@ ///==== Default constructor Contructor -FastCalibratorEB::FastCalibratorEB(TTree *tree, std::vector & inputMomentumScale, const std::string& typeEB, TString outEPDistribution): +FastCalibratorEB::FastCalibratorEB(TTree *tree, std::vector & inputMomentumScale, std::vector & inputEnergyScale, const std::string& typeEB, TString outEPDistribution): outEPDistribution_p(outEPDistribution){ // if parameter tree is not specified (or zero), connect the file @@ -32,6 +32,7 @@ outEPDistribution_p(outEPDistribution){ // Set my momentum scale using the input graphs myMomentumScale = inputMomentumScale; + myEnergyScale = inputEnergyScale; myTypeEB = typeEB; } @@ -127,7 +128,8 @@ void FastCalibratorEB::Init(TTree *tree){ fChain->SetBranchStatus("PtEle", 1); fChain->SetBranchAddress("PtEle", &PtEle, &b_PtEle); fChain->SetBranchStatus("phiEle", 1); fChain->SetBranchAddress("phiEle", &phiEle, &b_phiEle); fChain->SetBranchStatus("rawEnergySCEle", 1); fChain->SetBranchAddress("rawEnergySCEle", &rawEnergySCEle, &b_rawEnergySCEle); - fChain->SetBranchStatus("energySCEle", 1); fChain->SetBranchAddress("energySCEle", &energySCEle, &b_energySCEle); + fChain->SetBranchStatus("energySCEle_must", 1); fChain->SetBranchAddress("energySCEle_must", &energySCEle, &b_energySCEle); + // fChain->SetBranchStatus("energySCEle", 1); fChain->SetBranchAddress("energySCEle", &energySCEle, &b_energySCEle); fChain->SetBranchStatus("etaSCEle", 1); fChain->SetBranchAddress("etaSCEle", &etaSCEle, &b_etaSCEle); fChain->SetBranchStatus("esEnergySCEle", 1); fChain->SetBranchAddress("esEnergySCEle", &esEnergySCEle, &b_esEnergySCEle); fChain->SetBranchStatus("pAtVtxGsfEle", 1); fChain->SetBranchAddress("pAtVtxGsfEle", &pAtVtxGsfEle, &b_pAtVtxGsfEle); @@ -199,7 +201,7 @@ void FastCalibratorEB::bookHistos(int nLoops){ //! Build E/p distribution for both ele1 and ele2 -void FastCalibratorEB::BuildEoPeta_ele(int iLoop, int nentries , int useW, int useZ, std::vector theScalibration, bool isSaveEPDistribution, bool isR9selection, +void FastCalibratorEB::BuildEoPeta_ele(int iLoop, int nentries , int useW, int useZ, bool applyMomentumCorrection, bool applyEnergyCorrection, int useRawEnergy, std::vector theScalibration, bool isSaveEPDistribution, bool isR9selection, float R9Min, bool isfbrem, float fbremMax, bool isPtCut, float PtMin, bool isMCTruth){ if(iLoop ==0){ @@ -225,12 +227,17 @@ void FastCalibratorEB::BuildEoPeta_ele(int iLoop, int nentries , int useW, int u if (!(jentry%1000000))std::cerr<<"building E/p distribution ----> "<276243) continue; //LUCATEMP ///! Tight electron from W or Z only barrel (if chargeEle[1]==-100: event from W) if ( fabs(etaSCEle[0]) < 1.479 && (( useW == 1 && chargeEle[1]==-100 ) || ( useZ== 1 && chargeEle[1]!=-100 ))) { FdiEta = energySCEle[0]/rawEnergySCEle[0]; /// FEta approximation + if (useRawEnergy==1) + FdiEta = 1.; + if (applyEnergyCorrection) + FdiEta /= myEnergyScale[0] -> Eval( phiEle[0] ); float thisE = 0; int iseed = 0 ; @@ -244,6 +251,7 @@ void FastCalibratorEB::BuildEoPeta_ele(int iLoop, int nentries , int useW, int u float thisIC = 1.; int thisIndex = GetHashedIndexEB(XRecHitSCEle1->at(iRecHit), YRecHitSCEle1->at(iRecHit), ZRecHitSCEle1->at(iRecHit)); + if (thisIndex<0) continue; if(energyRecHitSCEle1 -> at(iRecHit) > E_seed && recoFlagRecHitSCEle1->at(iRecHit) < 4 ) /// control if this recHit is good { @@ -263,6 +271,7 @@ void FastCalibratorEB::BuildEoPeta_ele(int iLoop, int nentries , int useW, int u float thisIC = 1.; int thisIndex = GetHashedIndexEB(XRecHitSCEle1->at(iRecHit), YRecHitSCEle1->at(iRecHit), ZRecHitSCEle1->at(iRecHit)); + if (thisIndex<0) continue; ///! 3x3 matrix informations in order to apply R9 selection @@ -281,15 +290,16 @@ void FastCalibratorEB::BuildEoPeta_ele(int iLoop, int nentries , int useW, int u ///! different E/p if I am using MCThruth informations or not if(!isMCTruth) { pIn = pAtVtxGsfEle[0]; - int regionId = templIndexEB(myTypeEB,etaEle[0],chargeEle[0],thisE3x3/thisE); - pIn /= myMomentumScale[regionId] -> Eval( phiEle[0] ); + // int regionId = templIndexEB(myTypeEB,etaEle[0],chargeEle[0],thisE3x3/thisE); + if (applyMomentumCorrection) + pIn /= myMomentumScale[0] -> Eval( phiEle[0] ); } else{ pIn = energyMCEle[0]; ele1_DR = TMath::Sqrt((etaMCEle[0]-etaEle[0])*(etaMCEle[0]-etaEle[0])+(phiMCEle[0]-phiEle[0])*(phiMCEle[0]-phiEle[0])) ; if(fabs(ele1_DR)>0.1) skipElectron = true; /// No macthing beetween gen ele and reco ele } - + /// R9 Selection if( fabs(thisE3x3/thisE) < R9Min && isR9selection == true ) skipElectron = true; @@ -309,6 +319,10 @@ void FastCalibratorEB::BuildEoPeta_ele(int iLoop, int nentries , int useW, int u if ( fabs(etaSCEle[1]) < 1.479 && ( useZ == 1 && chargeEle[1]!=-100 ) ){ FdiEta = energySCEle[1]/rawEnergySCEle[1]; /// FEta approximation + if (useRawEnergy==1) + FdiEta = 1.; + if (applyEnergyCorrection) + FdiEta /= myEnergyScale[0] -> Eval( phiEle[1] ); float thisE = 0; int iseed = 0 ; @@ -322,6 +336,7 @@ void FastCalibratorEB::BuildEoPeta_ele(int iLoop, int nentries , int useW, int u float thisIC = 1.; int thisIndex = GetHashedIndexEB(XRecHitSCEle2->at(iRecHit), YRecHitSCEle2->at(iRecHit), ZRecHitSCEle2->at(iRecHit)); + if (thisIndex<0) continue; if(energyRecHitSCEle2 -> at(iRecHit) > E_seed && recoFlagRecHitSCEle2->at(iRecHit) < 4) { @@ -342,6 +357,7 @@ void FastCalibratorEB::BuildEoPeta_ele(int iLoop, int nentries , int useW, int u float thisIC = 1.; int thisIndex = GetHashedIndexEB(XRecHitSCEle2->at(iRecHit), YRecHitSCEle2->at(iRecHit), ZRecHitSCEle2->at(iRecHit)); + if (thisIndex<0) continue; if (iLoop > 0) thisIC = h_scale_EB_hashedIndex -> GetBinContent(thisIndex+1); @@ -360,8 +376,10 @@ void FastCalibratorEB::BuildEoPeta_ele(int iLoop, int nentries , int useW, int u /// MCTruth analysis option if(!isMCTruth) { pIn = pAtVtxGsfEle[1]; - int regionId = templIndexEB(myTypeEB,etaEle[1],ele2_charge,thisE3x3/thisE); - pIn /= myMomentumScale[regionId] -> Eval( phiEle[1] ); + // int regionId = templIndexEB(myTypeEB,etaEle[1],ele2_charge,thisE3x3/thisE); + if (applyMomentumCorrection) + pIn /= myMomentumScale[0] -> Eval( phiEle[0] ); + // pIn /= myMomentumScale[regionId] -> Eval( phiEle[1] ); } else{ pIn = energyMCEle[1]; @@ -397,8 +415,8 @@ void FastCalibratorEB::BuildEoPeta_ele(int iLoop, int nentries , int useW, int u /// Calibration Loop over the ntu events -void FastCalibratorEB::Loop( int nentries, int useZ, int useW, int splitStat, int nLoops, bool isMiscalib,bool isSaveEPDistribution, - bool isEPselection,bool isR9selection, float R9Min, bool isfbrem, float fbremMax, bool isPtCut, float PtMin, +void FastCalibratorEB::Loop( int nentries, int useZ, int useW, int splitStat, int nLoops, bool applyMomentumCorrection, bool applyEnergyCorrection, int useRawEnergy, bool isMiscalib,bool isSaveEPDistribution, + bool isEPselection,bool isR9selection, float R9Min, float EPMin, int smoothCut, bool isfbrem, float fbremMax, bool isPtCut, float PtMin, bool isMCTruth, std::map > > jsonMap, float miscalibMethod, TString miscalibMap){ if (fChain == 0) return; @@ -412,7 +430,8 @@ void FastCalibratorEB::Loop( int nentries, int useZ, int useW, int splitStat, in /// Define the number of crystal you want to calibrate int m_regions = 0; - + + // float EPMin=0.15; /// Define useful numbers static const int MIN_IETA = 1; @@ -465,6 +484,8 @@ void FastCalibratorEB::Loop( int nentries, int useZ, int useW, int splitStat, in } /// ----------------- Calibration Loops -----------------------------// + + float EPCutValue=100.; for ( int iLoop = 0; iLoop < nLoops; iLoop++ ) { @@ -474,11 +495,19 @@ void FastCalibratorEB::Loop( int nentries, int useZ, int useW, int splitStat, in std::vector theNumerator(m_regions, 0.); std::vector theDenominator(m_regions, 0.); - + + if (iLoop==0) EPCutValue = 100.; + // else if (iLoop==1) EPCutValue = 0.50; + // else if (iLoop==7) EPCutValue = 0.10; + //else if (iLoop==13) EPCutValue = 0.05; + //else if (iLoop==1) EPCutValue = EPMin; + //else EPCutValue = EPCutValue*0.82; + else EPCutValue = EPMin; + std::cout << "Number of analyzed events = " << nentries << std::endl; ///==== build E/p distribution ele 1 and 2 - BuildEoPeta_ele(iLoop,nentries,useW,useZ,theScalibration,isSaveEPDistribution,isR9selection,R9Min,isfbrem,fbremMax,isPtCut,PtMin,isMCTruth); + BuildEoPeta_ele(iLoop,nentries,useW,useZ,applyMomentumCorrection,applyEnergyCorrection,useRawEnergy,theScalibration,isSaveEPDistribution,isR9selection,R9Min,isfbrem,fbremMax,isPtCut,PtMin,isMCTruth); // define map with events std::map >,int> eventsMap; @@ -497,17 +526,18 @@ void FastCalibratorEB::Loop( int nentries, int useZ, int useW, int splitStat, in //********************************* // JSON FILE AND DUPLIACTES IN DATA + // if (runNumber>276243) continue; //LUCATEMP bool skipEvent = false; - if( isMCTruth == 0 ) + /* if( isMCTruth == 0 ) { - if(AcceptEventByRunAndLumiSection(runNumber,lumiBlock,jsonMap) == false) skipEvent = true; + // if(AcceptEventByRunAndLumiSection(runNumber,lumiBlock,jsonMap) == false) skipEvent = true; std::pair eventLSandID(lumiBlock,eventNumber); std::pair > eventRUNandLSandID(runNumber,eventLSandID); if( eventsMap[eventRUNandLSandID] == 1 ) skipEvent = true; else eventsMap[eventRUNandLSandID] = 1; - } + }*/ if( skipEvent == true ) continue; @@ -522,6 +552,10 @@ void FastCalibratorEB::Loop( int nentries, int useZ, int useW, int splitStat, in /// SCL energy containment correction FdiEta = energySCEle[0]/rawEnergySCEle[0]; + if (useRawEnergy==1) + FdiEta = 1.; + if (applyEnergyCorrection) + FdiEta /= myEnergyScale[0] -> Eval( phiEle[0] ); float thisE = 0; int iseed = 0 ; @@ -537,6 +571,7 @@ void FastCalibratorEB::Loop( int nentries, int useZ, int useW, int splitStat, in float thisIC = 1.; int thisIndex = GetHashedIndexEB(XRecHitSCEle1->at(iRecHit), YRecHitSCEle1->at(iRecHit), ZRecHitSCEle1->at(iRecHit)); + if (thisIndex<0) continue; if (iLoop > 0 ) thisIC = h_scale_EB_hashedIndex -> GetBinContent(thisIndex+1); @@ -558,6 +593,7 @@ void FastCalibratorEB::Loop( int nentries, int useZ, int useW, int splitStat, in float thisIC = 1.; int thisIndex = GetHashedIndexEB(XRecHitSCEle1->at(iRecHit), YRecHitSCEle1->at(iRecHit), ZRecHitSCEle1->at(iRecHit)); + if (thisIndex<0) continue; if (iLoop > 0) thisIC = h_scale_EB_hashedIndex -> GetBinContent(thisIndex+1); @@ -571,8 +607,9 @@ void FastCalibratorEB::Loop( int nentries, int useZ, int useW, int splitStat, in ///! if MCTruth Analysis if(!isMCTruth) { pIn = pAtVtxGsfEle[0]; - int regionId = templIndexEB(myTypeEB,etaEle[0],chargeEle[0],thisE3x3/thisE); - pIn /= myMomentumScale[regionId] -> Eval( phiEle[0] ); + // int regionId = templIndexEB(myTypeEB,etaEle[0],chargeEle[0],thisE3x3/thisE); + if (applyMomentumCorrection) + pIn /= myMomentumScale[0] -> Eval( phiEle[0] ); } else{ pIn = energyMCEle[0]; @@ -601,6 +638,7 @@ void FastCalibratorEB::Loop( int nentries, int useZ, int useW, int splitStat, in int thisIndex = GetHashedIndexEB(XRecHitSCEle1->at(iRecHit), YRecHitSCEle1->at(iRecHit), ZRecHitSCEle1->at(iRecHit)); float thisIC = 1.; + if (thisIndex<0) continue; if (iLoop > 0) thisIC = h_scale_EB_hashedIndex -> GetBinContent(thisIndex+1); @@ -612,23 +650,31 @@ void FastCalibratorEB::Loop( int nentries, int useZ, int useW, int splitStat, in /// use full statistics if ( splitStat == 0 ) { - - int EoPbin = EoPHisto->FindBin(thisE/pIn); /// factor use to reweight the evemts - theNumerator[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle1 -> at(iRecHit)*FdiEta*thisIC/thisE*pIn/thisE*EoPHisto->GetBinContent(EoPbin); - theDenominator[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle1 -> at(iRecHit)*FdiEta*thisIC/thisE*EoPHisto->GetBinContent(EoPbin); + float EoPweight = EoPHisto->GetBinContent(EoPHisto->FindBin(thisE/pIn)); + if (fabs(thisE/pIn-1)GetBinContent(EoPHisto->FindBin(thisE/pIn)); + else if (fabs(thisE/pIn-1)GetBinContent(EoPHisto->FindBin(1)); + else EoPweight=0.00000001; + theNumerator[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle1 -> at(iRecHit)*FdiEta*thisIC/thisE*pIn/thisE*EoPweight; + theDenominator[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle1 -> at(iRecHit)*FdiEta*thisIC/thisE*EoPweight; } /// Use Half Statistic only even - else if ( splitStat == 1 && jentry%2 == 0 ) { - int EoPbin = EoPHisto->FindBin(thisE/pIn); - theNumerator[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle1 -> at(iRecHit)*FdiEta*thisIC/thisE*pIn/thisE*EoPHisto->GetBinContent(EoPbin); - theDenominator[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle1 -> at(iRecHit)*FdiEta*thisIC/thisE*EoPHisto->GetBinContent(EoPbin); + else if ( splitStat == 1 && eventNumber%2 == 0 ) { + float EoPweight = EoPHisto->GetBinContent(EoPHisto->FindBin(thisE/pIn)); + if (fabs(thisE/pIn-1)GetBinContent(EoPHisto->FindBin(thisE/pIn)); + else if (fabs(thisE/pIn-1)GetBinContent(EoPHisto->FindBin(1)); + else EoPweight=0.00000001; + theNumerator[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle1 -> at(iRecHit)*FdiEta*thisIC/thisE*pIn/thisE*EoPweight; + theDenominator[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle1 -> at(iRecHit)*FdiEta*thisIC/thisE*EoPweight; } /// use odd event - else if ( splitStat == -1 && jentry%2 != 0 ) { - int EoPbin = EoPHisto->FindBin(thisE/pIn); - theNumerator[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle1 -> at(iRecHit)*FdiEta*thisIC/thisE*pIn/thisE*EoPHisto->GetBinContent(EoPbin); - theDenominator[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle1 -> at(iRecHit)*FdiEta*thisIC/thisE*EoPHisto->GetBinContent(EoPbin); + else if ( splitStat == -1 && eventNumber%2 != 0 ) { + float EoPweight = EoPHisto->GetBinContent(EoPHisto->FindBin(thisE/pIn)); + if (fabs(thisE/pIn-1)GetBinContent(EoPHisto->FindBin(thisE/pIn)); + else if (fabs(thisE/pIn-1)GetBinContent(EoPHisto->FindBin(1)); + else EoPweight=0.00000001; + theNumerator[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle1 -> at(iRecHit)*FdiEta*thisIC/thisE*pIn/thisE*EoPweight; + theDenominator[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle1 -> at(iRecHit)*FdiEta*thisIC/thisE*EoPweight; } } @@ -647,6 +693,11 @@ void FastCalibratorEB::Loop( int nentries, int useZ, int useW, int splitStat, in if ( fabs(etaSCEle[1]) < 1.479 && ( useZ == 1 && chargeEle[1]!=-100 ) ) { FdiEta = energySCEle[1]/rawEnergySCEle[1]; + if (useRawEnergy==1) + FdiEta = 1.; + if (applyEnergyCorrection) + FdiEta /= myEnergyScale[0] -> Eval( phiEle[1] ); + // Electron energy float thisE = 0; int iseed = 0 ; @@ -660,6 +711,8 @@ void FastCalibratorEB::Loop( int nentries, int useZ, int useW, int splitStat, in float thisIC = 1.; int thisIndex = GetHashedIndexEB(XRecHitSCEle2->at(iRecHit), YRecHitSCEle2->at(iRecHit), ZRecHitSCEle2->at(iRecHit)); + if (thisIndex<0) continue; + if (iLoop > 0) thisIC = h_scale_EB_hashedIndex -> GetBinContent(thisIndex+1); if(recoFlagRecHitSCEle2->at(iRecHit) < 4) @@ -681,6 +734,8 @@ void FastCalibratorEB::Loop( int nentries, int useZ, int useW, int splitStat, in float thisIC = 1.; int thisIndex = GetHashedIndexEB(XRecHitSCEle2->at(iRecHit), YRecHitSCEle2->at(iRecHit), ZRecHitSCEle2->at(iRecHit)); + if (thisIndex<0) continue; + // IC obtained from previous Loops if (iLoop > 0) thisIC = h_scale_EB_hashedIndex -> GetBinContent(thisIndex+1); @@ -696,8 +751,9 @@ void FastCalibratorEB::Loop( int nentries, int useZ, int useW, int splitStat, in ///! Option for MCTruth analysis if(!isMCTruth){ pIn = pAtVtxGsfEle[1]; - int regionId = templIndexEB(myTypeEB,etaEle[1],ele2_charge,thisE3x3/thisE); - pIn /= myMomentumScale[regionId] -> Eval( phiEle[1] ); + // int regionId = templIndexEB(myTypeEB,etaEle[1],ele2_charge,thisE3x3/thisE); + if (applyMomentumCorrection) + pIn /= myMomentumScale[0] -> Eval( phiEle[1] ); } else{ pIn = energyMCEle[1]; @@ -722,6 +778,7 @@ void FastCalibratorEB::Loop( int nentries, int useZ, int useW, int splitStat, in if (recoFlagRecHitSCEle2->at(iRecHit) >= 4) continue ; int thisIndex = GetHashedIndexEB(XRecHitSCEle2->at(iRecHit), YRecHitSCEle2->at(iRecHit), ZRecHitSCEle2->at(iRecHit)); + if (thisIndex<0) continue; // std::cout<<"DEBUG: "<at(iRecHit)<<" "<at(iRecHit)<<" "<at(iRecHit)<FindBin(thisE/pIn); - theNumerator[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle2 -> at(iRecHit)*FdiEta*thisIC/thisE*pIn/thisE*EoPHisto->GetBinContent(EoPbin); - theDenominator[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle2 -> at(iRecHit)*FdiEta*thisIC/thisE*EoPHisto->GetBinContent(EoPbin); + float EoPweight = EoPHisto->GetBinContent(EoPHisto->FindBin(thisE/pIn)); + if (fabs(thisE/pIn-1)GetBinContent(EoPHisto->FindBin(thisE/pIn)); + else if (fabs(thisE/pIn-1)GetBinContent(EoPHisto->FindBin(1)); + else EoPweight=0.00000001; + theNumerator[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle2 -> at(iRecHit)*FdiEta*thisIC/thisE*pIn/thisE*EoPweight; + theDenominator[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle2 -> at(iRecHit)*FdiEta*thisIC/thisE*EoPweight; } /// use evens - else if ( splitStat == 1 && jentry%2 == 0 ) { - int EoPbin = EoPHisto->FindBin(thisE/pIn); - theNumerator[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle2 -> at(iRecHit)*FdiEta*thisIC/thisE*pIn/thisE*EoPHisto->GetBinContent(EoPbin); - theDenominator[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle2 -> at(iRecHit)*FdiEta*thisIC/thisE*EoPHisto->GetBinContent(EoPbin); + else if ( splitStat == 1 && eventNumber%2 == 0 ) { + float EoPweight = EoPHisto->GetBinContent(EoPHisto->FindBin(thisE/pIn)); + if (fabs(thisE/pIn-1)GetBinContent(EoPHisto->FindBin(thisE/pIn)); + else if (fabs(thisE/pIn-1)GetBinContent(EoPHisto->FindBin(1)); + else EoPweight=0.00000001; + theNumerator[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle2 -> at(iRecHit)*FdiEta*thisIC/thisE*pIn/thisE*EoPweight; + theDenominator[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle2 -> at(iRecHit)*FdiEta*thisIC/thisE*EoPweight; } /// use odds - else if ( splitStat == -1 && jentry%2 != 0 ) { - int EoPbin = EoPHisto->FindBin(thisE/pIn); - theNumerator[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle2 -> at(iRecHit)*FdiEta*(thisIC/thisE)*pIn/thisE*EoPHisto->GetBinContent(EoPbin); - theDenominator[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle2 -> at(iRecHit)*FdiEta*thisIC/thisE*EoPHisto->GetBinContent(EoPbin); + else if ( splitStat == -1 && eventNumber%2 != 0 ) { + float EoPweight = EoPHisto->GetBinContent(EoPHisto->FindBin(thisE/pIn)); + if (fabs(thisE/pIn-1)GetBinContent(EoPHisto->FindBin(thisE/pIn)); + else if (fabs(thisE/pIn-1)GetBinContent(EoPHisto->FindBin(1)); + else EoPweight=0.00000001; + theNumerator[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle2 -> at(iRecHit)*FdiEta*(thisIC/thisE)*pIn/thisE*EoPweight; + theDenominator[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle2 -> at(iRecHit)*FdiEta*thisIC/thisE*EoPweight; } } diff --git a/EOverPCalibration/src/FastCalibratorEE.cc b/EOverPCalibration/src/FastCalibratorEE.cc index 7f6d259683d..5cc4b5f9c64 100644 --- a/EOverPCalibration/src/FastCalibratorEE.cc +++ b/EOverPCalibration/src/FastCalibratorEE.cc @@ -8,7 +8,7 @@ /// Default constructor -FastCalibratorEE::FastCalibratorEE(TTree *tree, std::vector & inputMomentumScale, const std::string& typeEE, TString outEPDistribution): +FastCalibratorEE::FastCalibratorEE(TTree *tree, std::vector & inputMomentumScale, std::vector & inputEnergyScale, const std::string& typeEE, TString outEPDistribution): outEPDistribution_p(outEPDistribution){ // if parameter tree is not specified (or zero), connect the file @@ -35,6 +35,7 @@ outEPDistribution_p(outEPDistribution){ // Set my momentum scale using the input graphs myMomentumScale = inputMomentumScale; + myEnergyScale = inputEnergyScale; myTypeEE = typeEE; } @@ -129,7 +130,7 @@ void FastCalibratorEE::Init(TTree *tree){ fChain->SetBranchStatus("PtEle", 1); fChain->SetBranchAddress("PtEle", &PtEle, &b_PtEle); fChain->SetBranchStatus("phiEle", 1); fChain->SetBranchAddress("phiEle", &phiEle, &b_phiEle); fChain->SetBranchStatus("rawEnergySCEle", 1); fChain->SetBranchAddress("rawEnergySCEle", &rawEnergySCEle, &b_rawEnergySCEle); - fChain->SetBranchStatus("energySCEle", 1); fChain->SetBranchAddress("energySCEle", &energySCEle, &b_energySCEle); + fChain->SetBranchStatus("energySCEle_must", 1); fChain->SetBranchAddress("energySCEle_must", &energySCEle, &b_energySCEle); fChain->SetBranchStatus("etaSCEle", 1); fChain->SetBranchAddress("etaSCEle", &etaSCEle, &b_etaSCEle); fChain->SetBranchStatus("esEnergySCEle", 1); fChain->SetBranchAddress("esEnergySCEle", &esEnergySCEle, &b_esEnergySCEle); fChain->SetBranchStatus("pAtVtxGsfEle", 1); fChain->SetBranchAddress("pAtVtxGsfEle", &pAtVtxGsfEle, &b_pAtVtxGsfEle); @@ -213,7 +214,7 @@ void FastCalibratorEE::bookHistos(int nLoops){ ///===== Build E/p for electron 1 and 2 -void FastCalibratorEE::BuildEoPeta_ele(int iLoop, int nentries , int useW, int useZ, std::vector theScalibration, bool isSaveEPDistribution, bool isR9selection, float R9Min, bool isfbrem, float fbremMax, bool isPtCut, float PtMin, bool isMCTruth){ +void FastCalibratorEE::BuildEoPeta_ele(int iLoop, int nentries , int useW, int useZ, bool applyMomentumCorrection, bool applyEnergyCorrection, int useRawEnergy, std::vector theScalibration, bool isSaveEPDistribution, bool isR9selection, float R9Min, bool isfbrem, float fbremMax, bool isPtCut, float PtMin, bool isMCTruth){ if(iLoop ==0){ TString name = Form ("hC_EoP_eta_%d",iLoop); @@ -233,15 +234,23 @@ void FastCalibratorEE::BuildEoPeta_ele(int iLoop, int nentries , int useW, int u if (ientry < 0) break; nb = fChain->GetEntry(jentry); nbytes += nb; - //std::cerr<<"building E/p distribution ----> "< "< "<276243) continue; //LUCATEMP float pIn, FdiEta; ///=== electron tight W or Z only Endcap if ( fabs(etaSCEle[0]) > 1.479 && (( useW == 1 && chargeEle[1] == -100 ) || ( useZ== 1 && chargeEle[1]!=-100 ))) { FdiEta = energySCEle[0]/(rawEnergySCEle[0]+esEnergySCEle[0]); /// Cluster containment approximation using ps infos + if (useRawEnergy==1) + FdiEta = 1.; + if (applyEnergyCorrection) { + int regionId = templIndexEE(myTypeEE,etaEle[0],chargeEle[0],1.); + FdiEta /= myEnergyScale[regionId] -> Eval( phiEle[0] ); + } float thisE = 0; int iseed = 0 ; @@ -254,7 +263,7 @@ void FastCalibratorEE::BuildEoPeta_ele(int iLoop, int nentries , int useW, int u float thisIC = 1.; int thisIndex = GetHashedIndexEE(XRecHitSCEle1->at(iRecHit), YRecHitSCEle1->at(iRecHit), ZRecHitSCEle1->at(iRecHit)); - // if (thisIndex<0) continue; + if (thisIndex<0) continue; if(YRecHitSCEle1->at(iRecHit)>100) continue; if(energyRecHitSCEle1 -> at(iRecHit) > E_seed && recoFlagRecHitSCEle1 -> at(iRecHit) < 4 ){ seed_hashedIndex=GetHashedIndexEE(XRecHitSCEle1->at(iRecHit), YRecHitSCEle1->at(iRecHit), ZRecHitSCEle1->at(iRecHit)); @@ -273,6 +282,7 @@ void FastCalibratorEE::BuildEoPeta_ele(int iLoop, int nentries , int useW, int u float thisIC = 1.; int thisIndex = GetHashedIndexEE(XRecHitSCEle1->at(iRecHit), YRecHitSCEle1->at(iRecHit), ZRecHitSCEle1->at(iRecHit)); + if (thisIndex<0) continue; if(YRecHitSCEle1->at(iRecHit)>100) continue; if (iLoop > 0) thisIC = h_scale_hashedIndex_EE -> GetBinContent(thisIndex+1); @@ -289,11 +299,14 @@ void FastCalibratorEE::BuildEoPeta_ele(int iLoop, int nentries , int useW, int u bool skipElectron = false; + /// Option for MCTruth analysis if(!isMCTruth){ pIn = pAtVtxGsfEle[0]; - int regionId = templIndexEE(myTypeEE,etaEle[0],chargeEle[0],thisE3x3/thisE); - pIn /= myMomentumScale[regionId] -> Eval( phiEle[0] ); + if (applyMomentumCorrection) { + // int regionId = templIndexEE(myTypeEE,etaEle[0],chargeEle[0],thisE3x3/thisE); + pIn /= myMomentumScale[0] -> Eval( phiEle[0] ); + } } else{ pIn = energyMCEle[0]; @@ -320,18 +333,25 @@ void FastCalibratorEE::BuildEoPeta_ele(int iLoop, int nentries , int useW, int u if ( fabs(etaSCEle[1]) >= 1.479 && ( useZ== 1 && chargeEle[1]!=-100 )) { FdiEta = energySCEle[1]/(rawEnergySCEle[1]+esEnergySCEle[1]); + if (useRawEnergy==1) + FdiEta = 1.; + if (applyEnergyCorrection) { + int regionId = templIndexEE(myTypeEE,etaEle[1],chargeEle[1],1.); + FdiEta /= myEnergyScale[regionId] -> Eval( phiEle[1] ); + } float thisE = 0; int iseed = 0 ; int seed_hashedIndex = 0; float E_seed = 0; float thisE3x3 = 0; - + /// Cycle on the all the recHits of the Event: to get the old IC and the corrected SC energy for (unsigned int iRecHit = 0; iRecHit < energyRecHitSCEle2->size(); iRecHit++ ) { float thisIC = 1.; int thisIndex = GetHashedIndexEE(XRecHitSCEle2->at(iRecHit), YRecHitSCEle2->at(iRecHit), ZRecHitSCEle2->at(iRecHit)); + if (thisIndex<0) continue; if(YRecHitSCEle2->at(iRecHit)>100) continue; if(energyRecHitSCEle2 -> at(iRecHit) > E_seed && recoFlagRecHitSCEle2 -> at(iRecHit) < 4 ){ seed_hashedIndex=GetHashedIndexEE(XRecHitSCEle2->at(iRecHit), YRecHitSCEle2->at(iRecHit), ZRecHitSCEle2->at(iRecHit)); @@ -339,18 +359,17 @@ void FastCalibratorEE::BuildEoPeta_ele(int iLoop, int nentries , int useW, int u E_seed=energyRecHitSCEle2 -> at(iRecHit); } - if (iLoop > 0) thisIC = h_scale_hashedIndex_EE -> GetBinContent(thisIndex+1); - - if(recoFlagRecHitSCEle2 -> at(iRecHit) < 4) /// Only Good channels - thisE += theScalibration[thisIndex]*energyRecHitSCEle2 -> at(iRecHit)*FdiEta*thisIC; - + + if(recoFlagRecHitSCEle2 -> at(iRecHit) < 4) /// Only Good channels + thisE += theScalibration[thisIndex]*energyRecHitSCEle2 -> at(iRecHit)*FdiEta*thisIC; } for (unsigned int iRecHit = 0; iRecHit < energyRecHitSCEle2->size(); iRecHit++ ) { float thisIC = 1.; int thisIndex = GetHashedIndexEE(XRecHitSCEle2->at(iRecHit), YRecHitSCEle2->at(iRecHit), ZRecHitSCEle2->at(iRecHit)); + if (thisIndex<0) continue; if(YRecHitSCEle2->at(iRecHit)>100) continue; // IC obtained from previous Loops if (iLoop > 0) thisIC = h_scale_hashedIndex_EE -> GetBinContent(thisIndex+1); @@ -369,8 +388,10 @@ void FastCalibratorEE::BuildEoPeta_ele(int iLoop, int nentries , int useW, int u /// Option for MCTruth Analysis if(!isMCTruth){ pIn = pAtVtxGsfEle[1]; - int regionId = templIndexEE(myTypeEE,etaEle[1],chargeEle[1],thisE3x3/thisE); - pIn /= myMomentumScale[regionId] -> Eval( phiEle[1] ); + if (applyMomentumCorrection) { + // int regionId = templIndexEE(myTypeEE,etaEle[1],chargeEle[1],thisE3x3/thisE); + pIn /= myMomentumScale[0] -> Eval( phiEle[1] ); + } } else{ pIn = energyMCEle[1]; @@ -409,8 +430,8 @@ void FastCalibratorEE::BuildEoPeta_ele(int iLoop, int nentries , int useW, int u /// L3 Loop method ----> Calibration Loop function -void FastCalibratorEE::Loop( int nentries, int useZ, int useW, int splitStat, int nLoops, bool isMiscalib,bool isSaveEPDistribution, - bool isEPselection, bool isR9selection, float R9Min, bool isfbrem, float fbremMax, bool isPtCut, float PtMin, +void FastCalibratorEE::Loop( int nentries, int useZ, int useW, int splitStat, int nLoops, bool applyMomentumCorrection, bool applyEnergyCorrection, int useRawEnergy, bool isMiscalib,bool isSaveEPDistribution, + bool isEPselection, bool isR9selection, float R9Min, float EPMin, int smoothCut, bool isfbrem, float fbremMax, bool isPtCut, float PtMin, bool isMCTruth, std::map > > jsonMap, float miscalibMethod, TString miscalibMap){ if (fChain == 0) return; @@ -425,6 +446,8 @@ void FastCalibratorEE::Loop( int nentries, int useZ, int useW, int splitStat, in /// Define the number of crystal you want to calibrate int m_regions = kEEhalf; + + // float EPMin=0.15; std::cout << "m_regions " << m_regions << std::endl; @@ -462,7 +485,8 @@ void FastCalibratorEE::Loop( int nentries, int useZ, int useW, int splitStat, in } } - + + float EPCutValue=100.; /// ----------------- Calibration Loops -----------------------------// for ( int iLoop = 0; iLoop < nLoops; iLoop++ ) { @@ -473,9 +497,24 @@ void FastCalibratorEE::Loop( int nentries, int useZ, int useW, int splitStat, in std::vector theDenominator_EEP(m_regions*2+1, 0.); std::vector theNumerator_EEM(m_regions+1, 0.); std::vector theDenominator_EEM(m_regions+1, 0.); + + if (iLoop==0) EPCutValue = 100.; + // else if (iLoop==1) EPCutValue = 0.50; + //else if (iLoop==7) EPCutValue = 0.10; + //else if (iLoop==13) EPCutValue = 0.05; + //if (iLoop==0) EPCutValue = 100.; + //else if (iLoop==1) EPCutValue = 0.15; + //else if (iLoop==6) EPCutValue = 0.10; + //else if (iLoop==11) EPCutValue = 0.05; + //else if (iLoop==1) EPCutValue = EPMin; + + //if (iLoop==0) EPCutValue = 100.; + // else if (iLoop==1) EPCutValue = EPMin; + // else EPCutValue = EPCutValue*0.82; + else EPCutValue = EPMin; ///==== build E/p distribution ele 1 and 2 - BuildEoPeta_ele(iLoop,nentries,useW,useZ,theScalibration,isSaveEPDistribution,isR9selection,R9Min,isfbrem,fbremMax,isPtCut,PtMin,isMCTruth); + BuildEoPeta_ele(iLoop,nentries,useW,useZ,applyMomentumCorrection,applyEnergyCorrection,useRawEnergy,theScalibration,isSaveEPDistribution,isR9selection,R9Min,isfbrem,fbremMax,isPtCut,PtMin,isMCTruth); // define map with events std::map >,int> eventsMap; @@ -493,20 +532,22 @@ void FastCalibratorEE::Loop( int nentries, int useZ, int useW, int splitStat, in nb = fChain->GetEntry(jentry); nbytes += nb; + if (eventNumber==471368767) continue; //this event needs to be debugged.. + // if (runNumber>276243) continue; //LUCATEMP //********************************* // JSON FILE AND DUPLIACTES IN DATA - + bool skipEvent = false; - if( isMCTruth == 0 ){ + /* if( isMCTruth == 0 ){ - if(AcceptEventByRunAndLumiSection(runNumber,lumiBlock,jsonMap) == false) skipEvent = true; + // if(AcceptEventByRunAndLumiSection(runNumber,lumiBlock,jsonMap) == false) skipEvent = true; std::pair eventLSandID(lumiBlock,eventNumber); std::pair > eventRUNandLSandID(runNumber,eventLSandID); if( eventsMap[eventRUNandLSandID] == 1 ) skipEvent = true; else eventsMap[eventRUNandLSandID] = 1; - } + } */ if( skipEvent == true ) continue; @@ -520,6 +561,12 @@ void FastCalibratorEE::Loop( int nentries, int useZ, int useW, int splitStat, in if ( fabs(etaSCEle[0]) >= 1.479 && (( useW == 1 && chargeEle[1]==-100 ) || ( useZ== 1 && chargeEle[1]!=-100 ))) { /// SCL energy containment correction FdiEta = energySCEle[0]/(rawEnergySCEle[0]+esEnergySCEle[0]); + if (useRawEnergy==1) + FdiEta = 1.; + if (applyEnergyCorrection) { + int regionId = templIndexEE(myTypeEE,etaEle[0],chargeEle[0],1.); + FdiEta /= myEnergyScale[regionId] -> Eval( phiEle[0] ); + } float thisE = 0; float thisE3x3 =0 ; @@ -533,6 +580,7 @@ void FastCalibratorEE::Loop( int nentries, int useZ, int useW, int splitStat, in float thisIC = 1.; int thisIndex = GetHashedIndexEE(XRecHitSCEle1->at(iRecHit), YRecHitSCEle1->at(iRecHit), ZRecHitSCEle1->at(iRecHit)); + if (thisIndex<0) continue; if(YRecHitSCEle1->at(iRecHit)>100) continue; if (iLoop > 0) thisIC = h_scale_hashedIndex_EE -> GetBinContent(thisIndex+1); @@ -551,6 +599,7 @@ void FastCalibratorEE::Loop( int nentries, int useZ, int useW, int splitStat, in float thisIC = 1.; int thisIndex = GetHashedIndexEE(XRecHitSCEle1->at(iRecHit), YRecHitSCEle1->at(iRecHit), ZRecHitSCEle1->at(iRecHit)); + if (thisIndex<0) continue; if(YRecHitSCEle1->at(iRecHit)>100) continue; if (iLoop > 0) thisIC = h_scale_hashedIndex_EE -> GetBinContent(thisIndex+1); @@ -574,8 +623,10 @@ void FastCalibratorEE::Loop( int nentries, int useZ, int useW, int splitStat, in /// MCTruth option if(!isMCTruth) { pIn = pAtVtxGsfEle[0]; - int regionId = templIndexEE(myTypeEE,etaEle[0],chargeEle[0],thisE3x3/thisE); - pIn /= myMomentumScale[regionId] -> Eval( phiEle[0] ); + if (applyMomentumCorrection) { + // int regionId = templIndexEE(myTypeEE,etaEle[0],chargeEle[0],thisE3x3/thisE); + pIn /= myMomentumScale[0] -> Eval( phiEle[0] ); + } } else{ pIn = energyMCEle[0]; @@ -606,6 +657,7 @@ void FastCalibratorEE::Loop( int nentries, int useZ, int useW, int splitStat, in if(recoFlagRecHitSCEle1 -> at(iRecHit) >= 4) continue; int thisIndex = GetHashedIndexEE(XRecHitSCEle1->at(iRecHit), YRecHitSCEle1->at(iRecHit), ZRecHitSCEle1->at(iRecHit)); + if (thisIndex<0) continue; if(YRecHitSCEle1->at(iRecHit)>100) continue; float thisIC = 1.; if( iLoop > 0 ) thisIC = h_scale_hashedIndex_EE -> GetBinContent(thisIndex+1); @@ -616,62 +668,80 @@ void FastCalibratorEE::Loop( int nentries, int useZ, int useW, int splitStat, in if ( GetZsideFromHashedIndex(thisIndex) < 0 ) h_occupancy_EEM -> Fill(GetIxFromHashedIndex(thisIndex), GetIyFromHashedIndex(thisIndex) ); else h_occupancy_EEP -> Fill(GetIxFromHashedIndex(thisIndex), GetIyFromHashedIndex(thisIndex) ); } - + ///Use full statistic if( splitStat == 0 ){ if(thisCaliBlock == 0){ - int EoPbin = EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[0])); + float EoPweight = EoPHisto->GetBinContent(EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[0]))); + if (fabs(thisE/(pIn-esEnergySCEle[0])-1)GetBinContent(EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[0]))); + else if (fabs(thisE/(pIn-esEnergySCEle[0])-1)GetBinContent(EoPHisto->FindBin(1)); + else EoPweight=0.00000001; theNumerator_EEM[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle1 -> at(iRecHit)*FdiEta*thisIC / - thisE*(pIn-esEnergySCEle[0])/thisE*EoPHisto->GetBinContent(EoPbin); + thisE*(pIn-esEnergySCEle[0])/thisE*EoPweight; theDenominator_EEM[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle1 -> at(iRecHit)*FdiEta*thisIC / - thisE*EoPHisto->GetBinContent(EoPbin); + thisE*EoPweight; } if( thisCaliBlock == 1 ){ - int EoPbin = EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[0])); + float EoPweight = EoPHisto->GetBinContent(EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[0]))); + if (fabs(thisE/(pIn-esEnergySCEle[0])-1)GetBinContent(EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[0]))); + else if (fabs(thisE/(pIn-esEnergySCEle[0])-1)GetBinContent(EoPHisto->FindBin(1)); + else EoPweight=0.00000001; theNumerator_EEP[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle1 -> at(iRecHit)*FdiEta*thisIC / - thisE*(pIn-esEnergySCEle[0])/thisE*EoPHisto->GetBinContent(EoPbin); + thisE*(pIn-esEnergySCEle[0])/thisE*EoPweight; theDenominator_EEP[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle1 -> at(iRecHit)*FdiEta*thisIC / - thisE*EoPHisto->GetBinContent(EoPbin); + thisE*EoPweight; } } /// use evens - if( splitStat == 1 && jentry%2 == 0 ){ + if( splitStat == 1 && eventNumber%2 == 0 ){ if( thisCaliBlock == 0 ){ - int EoPbin = EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[0])); + float EoPweight = EoPHisto->GetBinContent(EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[0]))); + if (fabs(thisE/(pIn-esEnergySCEle[0])-1)GetBinContent(EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[0]))); + else if (fabs(thisE/(pIn-esEnergySCEle[0])-1)GetBinContent(EoPHisto->FindBin(1)); + else EoPweight=0.00000001; theNumerator_EEM[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle1 -> at(iRecHit)*FdiEta*thisIC / - thisE*(pIn-esEnergySCEle[0])/thisE*EoPHisto->GetBinContent(EoPbin); + thisE*(pIn-esEnergySCEle[0])/thisE*EoPweight; theDenominator_EEM[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle1 -> at(iRecHit)*FdiEta*thisIC / - thisE*EoPHisto->GetBinContent(EoPbin); + thisE*EoPweight; } if(thisCaliBlock == 1){ - int EoPbin = EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[0])); + float EoPweight = EoPHisto->GetBinContent(EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[0]))); + if (fabs(thisE/(pIn-esEnergySCEle[0])-1)GetBinContent(EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[0]))); + else if (fabs(thisE/(pIn-esEnergySCEle[0])-1)GetBinContent(EoPHisto->FindBin(1)); + else EoPweight=0.00000001; theNumerator_EEP[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle1 -> at(iRecHit)*FdiEta*thisIC / - thisE*(pIn-esEnergySCEle[0])/thisE*EoPHisto->GetBinContent(EoPbin); + thisE*(pIn-esEnergySCEle[0])/thisE*EoPweight; theDenominator_EEP[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle1 -> at(iRecHit)*FdiEta*thisIC / - thisE*EoPHisto->GetBinContent(EoPbin); + thisE*EoPweight; } } /// use odd - if( splitStat == -1 && jentry%2 != 0 ){ + if( splitStat == -1 && eventNumber%2 != 0 ){ if(thisCaliBlock == 0){ - int EoPbin = EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[0])); + float EoPweight = EoPHisto->GetBinContent(EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[0]))); + if (fabs(thisE/(pIn-esEnergySCEle[0])-1)GetBinContent(EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[0]))); + else if (fabs(thisE/(pIn-esEnergySCEle[0])-1)GetBinContent(EoPHisto->FindBin(1)); + else EoPweight=0.00000001; theNumerator_EEM[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle1 -> at(iRecHit)*FdiEta*thisIC / - thisE*(pIn-esEnergySCEle[0])/thisE*EoPHisto->GetBinContent(EoPbin); + thisE*(pIn-esEnergySCEle[0])/thisE*EoPweight; theDenominator_EEM[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle1 -> at(iRecHit)*FdiEta*thisIC / - thisE*EoPHisto->GetBinContent(EoPbin); + thisE*EoPweight; } if(thisCaliBlock == 1){ - int EoPbin = EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[0])); + float EoPweight = EoPHisto->GetBinContent(EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[0]))); + if (fabs(thisE/(pIn-esEnergySCEle[0])-1)GetBinContent(EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[0]))); + else if (fabs(thisE/(pIn-esEnergySCEle[0])-1)GetBinContent(EoPHisto->FindBin(1)); + else EoPweight=0.00000001; theNumerator_EEP[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle1 -> at(iRecHit)*FdiEta*thisIC / - thisE*(pIn-esEnergySCEle[0])/thisE*EoPHisto->GetBinContent(EoPbin); + thisE*(pIn-esEnergySCEle[0])/thisE*EoPweight; theDenominator_EEP[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle1 -> at(iRecHit)*FdiEta*thisIC / - thisE*EoPHisto->GetBinContent(EoPbin); + thisE*EoPweight; } } } @@ -688,7 +758,13 @@ void FastCalibratorEE::Loop( int nentries, int useZ, int useW, int splitStat, in if ( fabs(etaSCEle[1]) >= 1.479 && ( useZ== 1 && chargeEle[1]!=-100 )) { /// SCL energy containment correction FdiEta = energySCEle[1]/(rawEnergySCEle[1]+esEnergySCEle[1]); - + if (useRawEnergy==1) + FdiEta = 1.; + if (applyEnergyCorrection) { + int regionId = templIndexEE(myTypeEE,etaEle[1],chargeEle[1],1.); + FdiEta /= myEnergyScale[regionId] -> Eval( phiEle[1] ); + } + float thisE = 0; float thisE3x3 =0 ; int iseed = 0 ; @@ -700,6 +776,7 @@ void FastCalibratorEE::Loop( int nentries, int useZ, int useW, int splitStat, in for(unsigned int iRecHit = 0; iRecHit < energyRecHitSCEle2->size(); iRecHit++ ){ float thisIC = 1.; int thisIndex = GetHashedIndexEE(XRecHitSCEle2->at(iRecHit), YRecHitSCEle2->at(iRecHit), ZRecHitSCEle2->at(iRecHit)); + if (thisIndex<0) continue; if(YRecHitSCEle2->at(iRecHit)>100) continue; if (iLoop > 0) thisIC = h_scale_hashedIndex_EE -> GetBinContent(thisIndex+1); @@ -717,6 +794,7 @@ void FastCalibratorEE::Loop( int nentries, int useZ, int useW, int splitStat, in { float thisIC = 1.; int thisIndex = GetHashedIndexEE(XRecHitSCEle2->at(iRecHit), YRecHitSCEle2->at(iRecHit), ZRecHitSCEle2->at(iRecHit)); + if (thisIndex<0) continue; if(YRecHitSCEle2->at(iRecHit)>100) continue; if (iLoop > 0) thisIC = h_scale_hashedIndex_EE -> GetBinContent(thisIndex+1); @@ -739,8 +817,10 @@ void FastCalibratorEE::Loop( int nentries, int useZ, int useW, int splitStat, in /// Option for MCTruth Analysis if(!isMCTruth) { pIn = pAtVtxGsfEle[1]; - int regionId = templIndexEE(myTypeEE,etaEle[1],chargeEle[1],thisE3x3/thisE); - pIn /= myMomentumScale[regionId] -> Eval( phiEle[1] ); + if (applyMomentumCorrection) { + // int regionId = templIndexEE(myTypeEE,etaEle[1],chargeEle[1],thisE3x3/thisE); + pIn /= myMomentumScale[0] -> Eval( phiEle[1] ); + } } else{ pIn = energyMCEle[1]; @@ -774,6 +854,7 @@ void FastCalibratorEE::Loop( int nentries, int useZ, int useW, int splitStat, in int thisIndex = GetHashedIndexEE(XRecHitSCEle2->at(iRecHit), YRecHitSCEle2->at(iRecHit), ZRecHitSCEle2->at(iRecHit)); float thisIC = 1.; + if (thisIndex<0) continue; if(YRecHitSCEle2->at(iRecHit)>100) continue; if(iLoop > 0) thisIC = h_scale_hashedIndex_EE -> GetBinContent(thisIndex+1); @@ -787,57 +868,75 @@ void FastCalibratorEE::Loop( int nentries, int useZ, int useW, int splitStat, in /// Use full statistic if( splitStat == 0){ if(thisCaliBlock == 0){ - int EoPbin = EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[1])); + float EoPweight = EoPHisto->GetBinContent(EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[1]))); + if (fabs(thisE/(pIn-esEnergySCEle[1])-1)GetBinContent(EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[1]))); + else if (fabs(thisE/(pIn-esEnergySCEle[1])-1)GetBinContent(EoPHisto->FindBin(1)); + else EoPweight=0.00000001; theNumerator_EEM[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle2 -> at(iRecHit)*FdiEta*thisIC / - thisE*(pIn-esEnergySCEle[1])/thisE*EoPHisto->GetBinContent(EoPbin); + thisE*(pIn-esEnergySCEle[1])/thisE*EoPweight; theDenominator_EEM[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle2 -> at(iRecHit)*FdiEta*thisIC / - thisE*EoPHisto->GetBinContent(EoPbin); + thisE*EoPweight; } if( thisCaliBlock == 1 ){ - int EoPbin = EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[1])); + float EoPweight = EoPHisto->GetBinContent(EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[1]))); + if (fabs(thisE/(pIn-esEnergySCEle[1])-1)GetBinContent(EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[1]))); + else if (fabs(thisE/(pIn-esEnergySCEle[1])-1)GetBinContent(EoPHisto->FindBin(1)); + else EoPweight=0.00000001; theNumerator_EEP[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle2 -> at(iRecHit)*FdiEta*thisIC / - thisE*(pIn-esEnergySCEle[1])/thisE*EoPHisto->GetBinContent(EoPbin); + thisE*(pIn-esEnergySCEle[1])/thisE*EoPweight; theDenominator_EEP[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle2 -> at(iRecHit)*FdiEta*thisIC / - thisE*EoPHisto->GetBinContent(EoPbin); + thisE*EoPweight; } } /// use evens - if( splitStat == 1 && jentry%2 == 0 ){ + if( splitStat == 1 && eventNumber%2 == 0 ){ if( thisCaliBlock == 0 ){ - int EoPbin = EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[1])); + float EoPweight = EoPHisto->GetBinContent(EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[1]))); + if (fabs(thisE/(pIn-esEnergySCEle[1])-1)GetBinContent(EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[1]))); + else if (fabs(thisE/(pIn-esEnergySCEle[1])-1)GetBinContent(EoPHisto->FindBin(1)); + else EoPweight=0.00000001; theNumerator_EEM[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle2 -> at(iRecHit)*FdiEta*thisIC / - thisE*(pIn-esEnergySCEle[1])/thisE*EoPHisto->GetBinContent(EoPbin); + thisE*(pIn-esEnergySCEle[1])/thisE*EoPweight; theDenominator_EEM[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle2 -> at(iRecHit)*FdiEta*thisIC / - thisE*EoPHisto->GetBinContent(EoPbin); + thisE*EoPweight; } if( thisCaliBlock == 1 ){ - int EoPbin = EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[1])); + float EoPweight = EoPHisto->GetBinContent(EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[1]))); + if (fabs(thisE/(pIn-esEnergySCEle[1])-1)GetBinContent(EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[1]))); + else if (fabs(thisE/(pIn-esEnergySCEle[1])-1)GetBinContent(EoPHisto->FindBin(1)); + else EoPweight=0.00000001; theNumerator_EEP[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle2 -> at(iRecHit)*FdiEta*thisIC / - thisE*(pIn-esEnergySCEle[1])/thisE*EoPHisto->GetBinContent(EoPbin); + thisE*(pIn-esEnergySCEle[1])/thisE*EoPweight; theDenominator_EEP[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle2 -> at(iRecHit)*FdiEta*thisIC / - thisE*EoPHisto->GetBinContent(EoPbin); + thisE*EoPweight; } } /// use odd - if( splitStat == -1 && jentry%2 != 0 ){ + if( splitStat == -1 && eventNumber%2 != 0 ){ if(thisCaliBlock == 0){ - int EoPbin = EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[1])); + float EoPweight = EoPHisto->GetBinContent(EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[1]))); + if (fabs(thisE/(pIn-esEnergySCEle[1])-1)GetBinContent(EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[1]))); + else if (fabs(thisE/(pIn-esEnergySCEle[1])-1)GetBinContent(EoPHisto->FindBin(1)); + else EoPweight=0.00000001; theNumerator_EEM[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle2 -> at(iRecHit)*FdiEta*thisIC / - thisE*(pIn-esEnergySCEle[1])/thisE*EoPHisto->GetBinContent(EoPbin); + thisE*(pIn-esEnergySCEle[1])/thisE*EoPweight; theDenominator_EEM[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle2 -> at(iRecHit)*FdiEta*thisIC / - thisE*EoPHisto->GetBinContent(EoPbin);} + thisE*EoPweight;} if( thisCaliBlock == 1 ){ - int EoPbin = EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[1])); + float EoPweight = EoPHisto->GetBinContent(EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[1]))); + if (fabs(thisE/(pIn-esEnergySCEle[1])-1)GetBinContent(EoPHisto->FindBin(thisE/(pIn-esEnergySCEle[1]))); + else if (fabs(thisE/(pIn-esEnergySCEle[1])-1)GetBinContent(EoPHisto->FindBin(1)); + else EoPweight=0.00000001; theNumerator_EEP[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle2 -> at(iRecHit)*FdiEta*thisIC / - thisE*(pIn-esEnergySCEle[0])/thisE*EoPHisto->GetBinContent(EoPbin); + thisE*(pIn-esEnergySCEle[0])/thisE*EoPweight; theDenominator_EEP[thisIndex] += theScalibration[thisIndex]*energyRecHitSCEle2 -> at(iRecHit)*FdiEta*thisIC / - thisE*EoPHisto->GetBinContent(EoPbin); + thisE*EoPweight; } } } diff --git a/EOverPCalibration/src/LaserMonitoringEoP.cc b/EOverPCalibration/src/LaserMonitoringEoP.cc new file mode 100644 index 00000000000..13d2e6e7017 --- /dev/null +++ b/EOverPCalibration/src/LaserMonitoringEoP.cc @@ -0,0 +1,1861 @@ +//Class for the monitoring of laser corrections with E/p + +#include "../interface/LaserMonitoringEoP.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +///==== Default constructor Contructor + +LaserMonitoringEoP::LaserMonitoringEoP(TTree *tree, TTree *treeMC, int useRegression) + { + // if parameter tree is not specified (or zero), connect the file + // used to generate this class and read the Tree. + if (tree == 0) { + TFile *f = (TFile*)gROOT->GetListOfFiles()->FindObject("/data1/dimatteo/Calibration/Ntuples/Run2011A/WZAnalysisSingleXtal/WZAnalysis_SingleElectron_Run2011A-WElectron-May10ReReco-v1.root"); + if (!f) { + f = new TFile("/data1/dimatteo/Calibration/Ntuples/Run2011A/WZAnalysisSingleXtal/WZAnalysis_SingleElectron_Run2011A-WElectron-May10ReReco-v1.root"); + } + tree = (TTree*)gDirectory->Get("ntu"); + } + Init(tree, treeMC, useRegression); + // Init(treeMC); + +} + +///==== deconstructor + +LaserMonitoringEoP::~LaserMonitoringEoP(){ + + if (!fChain) return; + delete fChain->GetCurrentFile(); + if (!fChainMC) return; + delete fChainMC->GetCurrentFile(); +} + + +///==== Variables initialization + +void LaserMonitoringEoP::Init(TTree *tree, TTree *treeMC, int useRegression){ + + /// Set branch addresses and branch pointers + + if (!tree) return; + fChain = tree; + fCurrent = -1; + fChain->SetMakeClass(1); + + fChain->SetBranchStatus("*", 0); + + fChain->SetBranchStatus("*",0); + fChain->SetBranchStatus("runNumber",1); + fChain->SetBranchStatus("runTime",1); + fChain->SetBranchStatus("nPU",1); + fChain->SetBranchStatus("nPV",1); + fChain->SetBranchStatus("avgLCSCEle",1); + // fChain->SetBranchStatus("seedLaserAlphaSCEle1",1); + // fChain->SetBranchStatus("ele1_EOverP",1); + fChain->SetBranchStatus("etaSCEle",1); + fChain->SetBranchStatus("phiSCEle",1); + fChain->SetBranchStatus("energySCEle_must",1); + fChain->SetBranchStatus("energySCEle_corr",1); + fChain->SetBranchStatus("esEnergySCEle",1); + fChain->SetBranchStatus("pAtVtxGsfEle",1); + fChain->SetBranchStatus("seedXSCEle",1); + fChain->SetBranchStatus("seedYSCEle",1); + // fChain->SetBranchStatus("ele1_seedZside",1); + + fChain->SetBranchAddress("runNumber", &runNumber); + fChain->SetBranchAddress("runTime", &runTime); + fChain->SetBranchAddress("nPU", &nPU); + fChain->SetBranchAddress("nPV", &nPV); + fChain->SetBranchAddress("avgLCSCEle", &avgLCSCEle[0]); + //fChain->SetBranchAddress("seedLaserAlphaSCEle1", &seedLaserAlphaSCEle1); + // fChain->SetBranchAddress("ele1_EOverP", &EoP); + fChain->SetBranchAddress("etaSCEle", &etaSCEle); + fChain->SetBranchAddress("phiSCEle", &phiSCEle); + if( useRegression < 1 ) + fChain->SetBranchAddress("energySCEle_must", &energySCEle); + else + fChain->SetBranchAddress("energySCEle_corr", &energySCEle_corr); + // fChain->SetBranchAddress("energySCEle_corr", &energySCEle); + fChain->SetBranchAddress("esEnergySCEle", &esEnergySCEle); + fChain->SetBranchAddress("pAtVtxGsfEle", &pAtVtxGsfEle); + fChain->SetBranchAddress("seedXSCEle", &seedXSCEle); + fChain->SetBranchAddress("seedYSCEle", &seedYSCEle); + // fChain->SetBranchAddress("ele1_seedZside", &seedZside); + + + /// Set branch addresses and branch pointers for MC + + if (!treeMC) return; + fChainMC = treeMC; + fCurrentMC = -1; + fChainMC->SetMakeClass(1); + + fChainMC->SetBranchStatus("*", 0); + + + fChainMC->SetBranchStatus("*",0); + fChainMC->SetBranchStatus("runNumber",1); + fChainMC->SetBranchStatus("runTime",1); + fChainMC->SetBranchStatus("nPU",1); + fChainMC->SetBranchStatus("nPV",1); + fChainMC->SetBranchStatus("avgLCSCEle",1); + // fChainMC->SetBranchStatus("seedLaserAlphaSCEle1",1); + // fChainMC->SetBranchStatus("ele1_EOverP",1); + fChainMC->SetBranchStatus("etaSCEle",1); + fChainMC->SetBranchStatus("phiSCEle",1); + fChainMC->SetBranchStatus("energySCEle_must",1); + fChainMC->SetBranchStatus("energySCEle_corr",1); + fChainMC->SetBranchStatus("esEnergySCEle",1); + fChainMC->SetBranchStatus("pAtVtxGsfEle",1); + fChainMC->SetBranchStatus("seedXSCEle",1); + fChainMC->SetBranchStatus("seedYSCEle",1); + // fChainMC->SetBranchStatus("ele1_seedZside",1); + + fChainMC->SetBranchAddress("runNumber", &runNumber); + fChainMC->SetBranchAddress("runTime", &runTime); + fChainMC->SetBranchAddress("nPU", &nPU); + fChainMC->SetBranchAddress("nPV", &nPV); + fChainMC->SetBranchAddress("avgLCSCEle", &avgLCSCEle[0]); + //fChainMC->SetBranchAddress("seedLaserAlphaSCEle1", &seedLaserAlphaSCEle1); + // fChainMC->SetBranchAddress("ele1_EOverP", &EoP); + fChainMC->SetBranchAddress("etaSCEle", &etaSCEle); + fChainMC->SetBranchAddress("phiSCEle", &phiSCEle); + if( useRegression < 1 ) + fChainMC->SetBranchAddress("energySCEle_must", &energySCEle); + else + fChainMC->SetBranchAddress("energySCEle_corr", &energySCEle_corr); + // fChainMC->SetBranchAddress("energySCEle_corr", &energySCEle); + fChainMC->SetBranchAddress("esEnergySCEle", &esEnergySCEle); + fChainMC->SetBranchAddress("pAtVtxGsfEle", &pAtVtxGsfEle); + fChainMC->SetBranchAddress("seedXSCEle", &seedXSCEle); + fChainMC->SetBranchAddress("seedYSCEle", &seedYSCEle); + // fChainMC->SetBranchAddress("ele1_seedZside", &seedZside); + +} + + +/// Calibration Loop over the ntu events +void LaserMonitoringEoP::Loop( float yMIN, float yMAX, std::string EBEE, int evtsPerPoint, int useRegression, std::string dayMin, std::string dayMax, std::string dayZOOM, + std::string LUMI, int vsPU) { + if (fChain == 0) return; + if (fChainMC == 0) return; + + /// ----------------- Calibration Loops -----------------------------// + + float timeLapse = 24.; // in hours + // int t1 = 1267401600; // 1 Mar 2010 + //int t2 = 1325289600; // 31 Dec 2011 + //int t1 = 1400000000; + //int t2 = 1600000000; + + // float yMIN = 0.65; + //float yMAX = 1.10; + + + // Set style options + setLaserPlotStyle(); + gStyle->SetPadTickX(1); + gStyle->SetPadTickY(1); + gStyle->SetOptTitle(0); + gStyle->SetOptStat(1110); + gStyle->SetOptFit(1); + + // Set fitting options + TVirtualFitter::SetDefaultFitter("Fumili2"); + + + + //----------------- + // Input parameters + + + std::cout << "\n***************************************************************************************************************************" << std::endl; + + // std::string dayMin = ""; + //std::string dayMax = ""; + std::string dayMinLabel = ""; + std::string dayMaxLabel = ""; + std::string dayZOOMLabel =""; + float absEtaMin = -1.; + float absEtaMax = -1.; + int IetaMin = -1; + int IetaMax = -1; + int IphiMin = -1; + int IphiMax = -1; + + + int t1 = dateToInt(dayMin); + int t2 = dateToInt(dayMax); + int t3 = dateToInt(dayZOOM); + + if (vsPU) { + t1=0; + t2=60; + t3=0; + } + + /* + if(argc >= 5) + { + dayMin = std::string(argv[4])+" "+std::string(argv[5])+" "+std::string(argv[6]); + dayMax = std::string(argv[7])+" "+std::string(argv[8])+" "+std::string(argv[9]); + dayMinLabel = std::string(argv[4])+"_"+std::string(argv[5])+"_"+std::string(argv[6]); + dayMaxLabel = std::string(argv[7])+"_"+std::string(argv[8])+"_"+std::string(argv[9]); + + } + if(argc >= 11) + { + yMIN = atof(argv[10]); + yMAX = atof(argv[11]); + } + if(argc >= 13) + { + absEtaMin = atof(argv[12]); + absEtaMax = atof(argv[13]); + } + if(argc >= 15) + { + IetaMin = atoi(argv[14]); + IetaMax = atoi(argv[15]); + IphiMin = atoi(argv[16]); + IphiMax = atoi(argv[17]); + } + */ + + std::cout << "EBEE: " << EBEE << std::endl; + std::cout << "evtsPerPoint: " << evtsPerPoint << std::endl; + std::cout << "useRegression: " << useRegression << std::endl; + std::cout << "dayMin: " << dayMin << std::endl; + std::cout << "dayZOOM: " << dayZOOM << std::endl; + std::cout << "dayMax: " << dayMax << std::endl; + std::cout << "yMin: " << yMIN << std::endl; + std::cout << "yMax: " << yMAX << std::endl; + std::cout << "absEtaMin: " << absEtaMin << std::endl; + std::cout << "absEtaMax: " << absEtaMax << std::endl; + std::cout << "IetaMin: " << IetaMin << std::endl; + std::cout << "IetaMax: " << IetaMax << std::endl; + std::cout << "IphiMin: " << IphiMin << std::endl; + std::cout << "IphiMax: " << IphiMax << std::endl; + std::cout << "t1: " << t1 << std::endl; + std::cout << "t2: " << t2 << std::endl; + std::cout << "t3" << t3 << std::endl; + + dayZOOM = ""; + dayMin = ""; + dayMax = ""; + + + //------------------- + // Define in/outfiles + + std::string folderName = std::string(EBEE) + "_" + dayMinLabel + "_" + dayMaxLabel; + if( (absEtaMin != -1.) && (absEtaMax != -1.) ) + { + char absEtaBuffer[50]; + sprintf(absEtaBuffer,"_%.2f-%.2f",absEtaMin,absEtaMax); + folderName += std::string(absEtaBuffer); + } + + if( (IetaMin != -1.) && (IetaMax != -1.) && (IphiMin != -1.) && (IphiMax != -1.) ) + { + char absEtaBuffer[50]; + sprintf(absEtaBuffer,"_Ieta_%d-%d_Iphi_%d-%d",IetaMin,IetaMax,IphiMin,IphiMax); + folderName += std::string(absEtaBuffer); + } + + gSystem->mkdir(folderName.c_str()); + TFile* o = new TFile((folderName+"/"+folderName+"_histos.root").c_str(),"RECREATE"); + + + + // Get trees + std::cout << std::endl; + + /* + TChain* ntu_DA = new TChain("simpleNtupleEoverP/SimpleNtupleEoverP"); + FillChain(ntu_DA,"inputDATA.txt"); + std::cout << " DATA: " << std::setw(8) << ntu_DA->GetEntries() << " entries" << std::endl; + + TChain* ntu_MC = new TChain("simpleNtupleEoverP/SimpleNtupleEoverP"); + FillChain(ntu_MC,"inputMC.txt"); + std::cout << "REFERENCE: " << std::setw(8) << ntu_MC->GetEntries() << " entries" << std::endl; + */ + + if (fChain->GetEntries() == 0 || fChainMC->GetEntries() == 0 ) + { + std::cout << "Error: At least one file is empty" << std::endl; + return; + } + + + + + + + //-------------------------------------------------------- + // Define PU correction (to be used if useRegression == 0) + + // corr = p0 + p1 * nPU + float p0_EB; + float p1_EB; + float p0_EE; + float p1_EE; + + if( useRegression == 0 ) + { + //2012 EB + p0_EB = 0.9991; + p1_EB = 0.0001635; + //2012 EE + p0_EE = 0.9968; + p1_EE = 0.001046; + } + else + { + //2012 EB + p0_EB = 1.001; + p1_EB = -0.000143; + //2012 EE + p0_EE = 1.00327; + p1_EE = -0.000432; + } + + float p0 = -1.; + float p1 = -1.; + + if( strcmp(EBEE.c_str(),"EB") == 0 ) + { + p0 = p0_EB; + p1 = p1_EB; + } + else + { + p0 = p0_EE; + p1 = p1_EE; + } + + //2015 + p0=1.; + p1=0.; + + + + + //--------------------------------- + // Build the reference distribution + + std::cout << std::endl; + std::cout << "***** Build reference for " << EBEE << " *****" << std::endl; + + TH1F* h_template = new TH1F("template", "", 2000, 0., 5.); + + for(int ientry = 0; ientry < fChainMC->GetEntries(); ++ientry) + { + if( (ientry%10000 == 0) ) std::cout << "reading MC entry " << ientry <<"/"<GetEntries()<< "\r" << std::endl;//std::flush; + fChainMC->GetEntry(ientry); + + // selections + if( (strcmp(EBEE.c_str(),"EB") == 0) && (fabs(etaSCEle[0]) > 1.479) ) continue; // barrel + if( (strcmp(EBEE.c_str(),"EB_0_1") == 0) && (fabs(etaSCEle[0]) > 1.0)) continue; // inner barrel + if( (strcmp(EBEE.c_str(),"EB_1_1479") == 0) && (fabs(etaSCEle[0]) < 1.0 || fabs(etaSCEle[0]) > 1.479) ) continue; // barrel + if( (strcmp(EBEE.c_str(),"EE") == 0) && (fabs(etaSCEle[0]) < 1.479 || fabs(etaSCEle[0])>2.5) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EE_1479_2") == 0) && (fabs(etaSCEle[0]) < 1.479 || fabs(etaSCEle[0])>2.0) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EE_2_25") == 0) && (fabs(etaSCEle[0]) < 2.0 || fabs(etaSCEle[0])>2.5) ) continue; // endcap + + if( (strcmp(EBEE.c_str(),"EEp") == 0) && (etaSCEle[0] < 1.479 || etaSCEle[0]>2.5 ) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_1479_2") == 0) && (etaSCEle[0] < 1.479 || etaSCEle[0]>2.0) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_2_25") == 0) && (etaSCEle[0] < 2.0 || etaSCEle[0]>2.5) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_2_225") == 0) && (etaSCEle[0] < 2.0 || etaSCEle[0]>2.25) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_225_25") == 0) && (etaSCEle[0] < 2.25 || etaSCEle[0]>2.25) ) continue; // endcap + + if( (strcmp(EBEE.c_str(),"EEm") == 0) && (etaSCEle[0] > -1.479 || etaSCEle[0]<-2.5 ) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_1479_2") == 0) && (etaSCEle[0] > -1.479 || etaSCEle[0]<-2.0) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_2_25") == 0) && (etaSCEle[0] > -2.0 || etaSCEle[0]<-2.5) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_2_225") == 0) && (etaSCEle[0] > -2.0 || etaSCEle[0]<-2.25) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_225_25") == 0) && (etaSCEle[0] > -2.25 || etaSCEle[0]<-2.5) ) continue; // endcap + + if( (absEtaMin != -1.) && (absEtaMax != -1.) ) + { + if( (fabs(etaSCEle[0]) < absEtaMin) || (fabs(etaSCEle[0]) > absEtaMax) ) continue; + } + + if( (IetaMin != -1.) && (IetaMax != -1.) && (IphiMin != -1.) && (IphiMax != -1.) ) + { + if( (seedXSCEle[0] < IetaMin) || (seedXSCEle[0] > IetaMax) ) continue; + if( (seedYSCEle[0] < IphiMin) || (seedYSCEle[0] > IphiMax) ) continue; + } + + // PU correction + float PUCorr = (p0 + p1*nPU); + //std::cout << "p0: " << p0 << " p1: " << p1 << " nPU: " << nPU << std::endl; + + // fill the template histogram + h_template -> Fill( (energySCEle[0]-esEnergySCEle[0])/(pAtVtxGsfEle[0]-esEnergySCEle[0]) / PUCorr ); + } + + std::cout << "Reference built for " << EBEE << " - " << h_template->GetEntries() << " events" << std::endl; + + + + + + + //--------------------- + // Loop and sort events + + std::cout << std::endl; + std::cout << "***** Sort events and define bins *****" << std::endl; + + int nEntries = fChain -> GetEntriesFast(); + int nSavePts = 0; + std::vector isSavedEntries(nEntries); + std::vector sortedEntries; + std::vector timeStampFirst; + + for(int ientry = 0; ientry < nEntries; ++ientry) + { + fChain -> GetEntry(ientry); + isSavedEntries.at(ientry) = false; + + if( (ientry%10000 == 0) ) std::cout << "reading data entry " << ientry << "\r" << std::endl;//std::flush; + + // selections + if( (strcmp(EBEE.c_str(),"EB") == 0) && (fabs(etaSCEle[0]) > 1.479) ) continue; // barrel + if( (strcmp(EBEE.c_str(),"EB_0_1") == 0) && (fabs(etaSCEle[0]) > 1.0)) continue; // inner barrel + if( (strcmp(EBEE.c_str(),"EB_1_1479") == 0) && (fabs(etaSCEle[0]) < 1.0 || fabs(etaSCEle[0]) > 1.479) ) continue; // barrel + if( (strcmp(EBEE.c_str(),"EE") == 0) && (fabs(etaSCEle[0]) < 1.479 || fabs(etaSCEle[0])>2.5) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EE_1479_2") == 0) && (fabs(etaSCEle[0]) < 1.479 || fabs(etaSCEle[0])>2.0) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EE_2_25") == 0) && (fabs(etaSCEle[0]) < 2.0 || fabs(etaSCEle[0])>2.5) ) continue; // endcap + + if( (strcmp(EBEE.c_str(),"EEp") == 0) && (etaSCEle[0] < 1.479 || etaSCEle[0]>2.5 ) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_1479_2") == 0) && (etaSCEle[0] < 1.479 || etaSCEle[0]>2.0) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_2_25") == 0) && (etaSCEle[0] < 2.0 || etaSCEle[0]>2.5) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_2_225") == 0) && (etaSCEle[0] < 2.0 || etaSCEle[0]>2.25) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_225_25") == 0) && (etaSCEle[0] < 2.25 || etaSCEle[0]>2.25) ) continue; // endcap + + if( (strcmp(EBEE.c_str(),"EEm") == 0) && (etaSCEle[0] > -1.479 || etaSCEle[0]<-2.5 ) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_1479_2") == 0) && (etaSCEle[0] > -1.479 || etaSCEle[0]<-2.0) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_2_25") == 0) && (etaSCEle[0] > -2.0 || etaSCEle[0]<-2.5) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_2_225") == 0) && (etaSCEle[0] > -2.0 || etaSCEle[0]<-2.25) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_225_25") == 0) && (etaSCEle[0] > -2.25 || etaSCEle[0]<-2.5) ) continue; // endcap + + if( (absEtaMin != -1.) && (absEtaMax != -1.) ) + { + if( (fabs(etaSCEle[0]) < absEtaMin) || (fabs(etaSCEle[0]) > absEtaMax) ) continue; + } + + if( (IetaMin != -1.) && (IetaMax != -1.) && (IphiMin != -1.) && (IphiMax != -1.) ) + { + if( (seedXSCEle[0] < IetaMin) || (seedXSCEle[0] > IetaMax) ) continue; + if( (seedYSCEle[0] < IphiMin) || (seedYSCEle[0] > IphiMax) ) continue; + } + + if (vsPU==0) { + if( runTime < t1 ) continue; + if( runTime > t2 ) continue; + } + else { + if( nPV < t1 ) continue; + if( nPV > t2 ) continue; + } + + if( avgLCSCEle[0] <= 0. ) continue; + + isSavedEntries.at(ientry) = true; + + + // fill sorter + Sorter dummy; + if (vsPU==0) dummy.time = runTime; + else dummy.time = nPV; + dummy.entry = ientry; + sortedEntries.push_back(dummy); + + ++nSavePts; + } + + // sort events + std::sort(sortedEntries.begin(),sortedEntries.end(),Sorter()); + std::cout << "Data sorted in " << EBEE << " - " << nSavePts << " events" << std::endl; + + std::map antiMap; + for(unsigned int iSaved = 0; iSaved < sortedEntries.size(); ++iSaved) + antiMap[sortedEntries.at(iSaved).entry] = iSaved; + + + //--------------------- + // Loop and define bins + + // "wide" bins - find events with time separation bigger than 1 day + int nWideBins = 1; + std::vector wideBinEntryMax; + int timeStampOld = -1; + + // TEventList* evlist=new TEventList("events"); + // data->Draw(">>events","","goff"); + // TEventList* evlist = (TEventList*) gDirectory->Get("events"); + + wideBinEntryMax.push_back(0); + + if (vsPU==0) { + for(int iSaved = 0; iSaved < nSavePts; ++iSaved) + { + if( iSaved%10000 == 0 ) std::cout << "reading saved entry " << iSaved << "\r" << std::endl;//std::flush; + fChain->GetEntry(sortedEntries[iSaved].entry); + // data->GetEntry(evlist->GetEntry(sortedEntries[iSaved].entry)); + + if( iSaved == 0 ) + { + timeStampOld = runTime; + continue; + } + + if( (runTime-timeStampOld)/3600. > timeLapse ) + { + ++nWideBins; + wideBinEntryMax.push_back(iSaved-1); + } + + timeStampOld = runTime; + } + } + std::cout << std::endl; + wideBinEntryMax.push_back(nSavePts); + + + // bins with approximatively evtsPerPoint events per bin + int nBins = 0; + std::vector binEntryMax; + + binEntryMax.push_back(0); + for(int wideBin = 0; wideBin < nWideBins; ++wideBin) + { + int nTempBins = std::max(1,int( (wideBinEntryMax.at(wideBin+1)-wideBinEntryMax.at(wideBin))/evtsPerPoint )); + int nTempBinEntries = int( (wideBinEntryMax.at(wideBin+1)-wideBinEntryMax.at(wideBin))/nTempBins ); + + for(int tempBin = 0; tempBin < nTempBins; ++tempBin) + { + ++nBins; + if( tempBin < nTempBins - 1 ) + binEntryMax.push_back( wideBinEntryMax.at(wideBin) + (tempBin+1)*nTempBinEntries ); + else + binEntryMax.push_back( wideBinEntryMax.at(wideBin+1) ); + } + } + + std::cout << "nBins = " << nBins << std::endl; + //for(int bin = 0; bin < nBins; ++bin) + // std::cout << "bin: " << bin + // << " entry min: " << setw(6) << binEntryMax.at(bin) + // << " entry max: " << setw(6) << binEntryMax.at(bin+1) + // << " events: " << setw(6) << binEntryMax.at(bin+1)-binEntryMax.at(bin) + // << std::endl; + + + // histogram definition + + TH1F* h_scOccupancy_eta = new TH1F("h_scOccupancy_eta","", 298, -2.6, 2.6); + TH1F* h_scOccupancy_phi = new TH1F("h_scOccupancy_phi","", 363, -3.1765, 3.159); + SetHistoStyle(h_scOccupancy_eta); + SetHistoStyle(h_scOccupancy_phi); + + TH2F* h_seedOccupancy_EB = new TH2F("h_seedOccupancy_EB","", 171, -86., 85., 361, 0.,361.); + TH2F* h_seedOccupancy_EEp = new TH2F("h_seedOccupancy_EEp","", 101, 0.,101., 100, 0.,101.); + TH2F* h_seedOccupancy_EEm = new TH2F("h_seedOccupancy_EEm","", 101, 0.,101., 100, 0.,101.); + SetHistoStyle(h_seedOccupancy_EB); + SetHistoStyle(h_seedOccupancy_EEp); + SetHistoStyle(h_seedOccupancy_EEm); + + TH1F* h_EoP_spread = new TH1F("h_EoP_spread","",100,yMIN,yMAX); + TH1F* h_EoC_spread = new TH1F("h_EoC_spread","",100,yMIN,yMAX); + TH1F* h_EoP_spread_run = new TH1F("h_EoP_spread_run","",100,yMIN,yMAX); + TH1F* h_EoC_spread_run = new TH1F("h_EoC_spread_run","",100,yMIN,yMAX); + SetHistoStyle(h_EoP_spread,"EoP"); + SetHistoStyle(h_EoC_spread,"EoC"); + SetHistoStyle(h_EoP_spread_run,"EoP"); + SetHistoStyle(h_EoC_spread_run,"EoC"); + + TH1F* h_EoP_chi2 = new TH1F("h_EoP_chi2","",50,0.,5.); + TH1F* h_EoC_chi2 = new TH1F("h_EoC_chi2","",50,0.,5.); + SetHistoStyle(h_EoP_chi2,"EoP"); + SetHistoStyle(h_EoC_chi2,"EoC"); + + TH1F** h_EoP = new TH1F*[nBins]; + TH1F** h_EoC = new TH1F*[nBins]; + TH1F** h_Las = new TH1F*[nBins]; + TH1F** h_Tsp = new TH1F*[nBins]; + TH1F** h_Cvl = new TH1F*[nBins]; + + for(int i = 0; i < nBins; ++i) + { + char histoName[80]; + + sprintf(histoName, "EoP_%d", i); + h_EoP[i] = new TH1F(histoName, histoName, 2000, 0., 5.); + SetHistoStyle(h_EoP[i],"EoP"); + + sprintf(histoName, "EoC_%d", i); + h_EoC[i] = new TH1F(histoName, histoName, 2000, 0., 5.); + SetHistoStyle(h_EoC[i],"EoC"); + + sprintf(histoName, "Las_%d", i); + h_Las[i] = new TH1F(histoName, histoName, 500, 0.5, 1.5); + + sprintf(histoName, "Tsp_%d", i); + h_Tsp[i] = new TH1F(histoName, histoName, 500, 0.5, 1.5); + + } + + + // function definition + TF1** f_EoP = new TF1*[nBins]; + TF1** f_EoC = new TF1*[nBins]; + + + // graphs definition + TGraphAsymmErrors* g_fit = new TGraphAsymmErrors(); + TGraphAsymmErrors* g_c_fit = new TGraphAsymmErrors(); + + TGraphAsymmErrors* g_fit_run = new TGraphAsymmErrors(); + TGraphAsymmErrors* g_c_fit_run = new TGraphAsymmErrors(); + + TGraph* g_las = new TGraph(); + + TGraphErrors* g_LT = new TGraphErrors(); + + g_fit->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00"); + g_fit->GetXaxis()->SetTimeDisplay(1); + g_c_fit->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00"); + g_c_fit->GetXaxis()->SetTimeDisplay(1); + g_las->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00"); + g_las->GetXaxis()->SetTimeDisplay(1); + g_LT->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00"); + g_LT->GetXaxis()->SetTimeDisplay(1); + + + + //------------------------------------ + // loop on the saved and sorted events + + std::cout << std::endl; + std::cout << "***** Fill and fit histograms *****" << std::endl; + + std::vector Entries(nBins); + std::vector AveTime(nBins); + std::vector MinTime(nBins); + std::vector MaxTime(nBins); + std::vector AveRun(nBins); + std::vector MinRun(nBins); + std::vector MaxRun(nBins); + std::vector AveLT(nBins); + std::vector AveLT2(nBins); + + int iSaved = -1; + for(int ientry = 0; ientry < nEntries; ++ientry) + { + if( (ientry%100000 == 0) ) std::cout << "reading entry " << ientry << "\r" << std::endl;//std::flush; + + if( isSavedEntries.at(ientry) == false ) continue; + + ++iSaved; + + int iSaved = antiMap[ientry]; + int bin = -1; + for(bin = 0; bin < nBins; ++bin) + if( iSaved >= binEntryMax.at(bin) && iSaved < binEntryMax.at(bin+1) ) + break; + + //std::cout << "bin = " << bin << " iSaved = "<< iSaved << std::endl; + fChain->GetEntry(ientry); + + + + Entries[bin] += 1; + + if(vsPU==0) { + if( iSaved == binEntryMax.at(bin)+1 ) MinTime[bin] = runTime; + if( iSaved == binEntryMax.at(bin+1)-1 ) MaxTime[bin] = runTime; + AveTime[bin] += runTime; + } + else { + if( iSaved == binEntryMax.at(bin)+1 ) MinTime[bin] = nPV; + if( iSaved == binEntryMax.at(bin+1)-1 ) MaxTime[bin] = nPV; + AveTime[bin] += nPV; + } + + if( iSaved == binEntryMax.at(bin)+1 ) MinRun[bin] = runNumber; + if( iSaved == binEntryMax.at(bin+1)-1 ) MaxRun[bin] = runNumber; + AveRun[bin] += runNumber; + + // float LT = (-1. / seedLaserAlphaSCEle1 * log(avgLCSCEle[0])); + float LT = 1.; + AveLT[bin] += LT; + AveLT2[bin] += LT*LT; + + // PU correction + float PUCorr = (p0 + p1*nPU); + + // fill the histograms + (h_EoP[bin]) -> Fill( (energySCEle[0]-esEnergySCEle[0])/(pAtVtxGsfEle[0]-esEnergySCEle[0]) / avgLCSCEle[0] / PUCorr); + (h_EoC[bin]) -> Fill( (energySCEle[0]-esEnergySCEle[0])/(pAtVtxGsfEle[0]-esEnergySCEle[0]) / PUCorr ); + + (h_Las[bin]) -> Fill(avgLCSCEle[0]); + (h_Tsp[bin]) -> Fill(1./avgLCSCEle[0]); + + h_scOccupancy_eta -> Fill(etaSCEle[0]); + h_scOccupancy_phi -> Fill(phiSCEle[0]); + if(fabs(etaSCEle[0])<1.449) + h_seedOccupancy_EB -> Fill(seedXSCEle[0],seedYSCEle[0]); + else if(etaSCEle[0]>1.449) + h_seedOccupancy_EEp -> Fill(seedXSCEle[0],seedYSCEle[0]); + else if(etaSCEle[0]<-1.449) + h_seedOccupancy_EEm -> Fill(seedXSCEle[0],seedYSCEle[0]); + } + + for(int bin = 0; bin < nBins; ++bin) + { + AveTime[bin] = 1. * AveTime[bin] / (binEntryMax.at(bin+1)-binEntryMax.at(bin)); + AveRun[bin] = 1. * AveRun[bin] / (binEntryMax.at(bin+1)-binEntryMax.at(bin)); + AveLT[bin] = 1. * AveLT[bin] / (binEntryMax.at(bin+1)-binEntryMax.at(bin)); + AveLT2[bin] = 1. * AveLT2[bin] / (binEntryMax.at(bin+1)-binEntryMax.at(bin)); + //std::cout << date << " " << AveTime[i] << " " << MinTime[i] << " " << MaxTime[i] << std::endl; + } + + + + + + + int rebin = 2; + if( strcmp(EBEE.c_str(),"EE") == 0 ) rebin *= 2; + + h_template -> Rebin(rebin); + + + + float EoP_scale = 0.; + float EoP_err = 0.; + int EoP_nActiveBins = 0; + + float EoC_scale = 0.; + float EoC_err = 0.; + int EoC_nActiveBins = 0; + + float LCInv_scale = 0; + + std::vector validBins; + for(int i = 0; i < nBins; ++i) + { + bool isValid = true; + + h_EoP[i] -> Rebin(rebin); + h_EoC[i] -> Rebin(rebin); + + + + //------------------------------------ + // Fill the graph for uncorrected data + + // define the fitting function + // N.B. [0] * ( [1] * f( [1]*(x-[2]) ) ) + + //o -> cd(); + char convolutionName[50]; + sprintf(convolutionName,"h_convolution_%d",i); + //h_Cvl[i] = ConvoluteTemplate(std::string(convolutionName),h_template,h_Las[i],32768,-5.,5.); + h_Cvl[i] = MellinConvolution(std::string(convolutionName),h_template,h_Tsp[i]); + + histoFunc* templateHistoFunc = new histoFunc(h_template); + histoFunc* templateConvolutedHistoFunc = new histoFunc(h_Cvl[i]); + char funcName[50]; + + sprintf(funcName,"f_EoP_%d",i); + + if( strcmp(EBEE.c_str(),"EB") == 0 ) + f_EoP[i] = new TF1(funcName, templateConvolutedHistoFunc, 0.8*(h_Tsp[i]->GetMean()), 1.4*(h_Tsp[i]->GetMean()), 3, "histoFunc"); + else + f_EoP[i] = new TF1(funcName, templateConvolutedHistoFunc, 0.75*(h_Tsp[i]->GetMean()), 1.5*(h_Tsp[i]->GetMean()), 3, "histoFunc"); + + f_EoP[i] -> SetParName(0,"Norm"); + f_EoP[i] -> SetParName(1,"Scale factor"); + f_EoP[i] -> SetLineWidth(1); + f_EoP[i] -> SetNpx(10000); + + double xNorm = h_EoP[i]->GetEntries()/h_template->GetEntries() * + h_EoP[i]->GetBinWidth(1)/h_template->GetBinWidth(1); + + f_EoP[i] -> FixParameter(0, xNorm); + f_EoP[i] -> SetParameter(1, 1.); + f_EoP[i] -> FixParameter(2, 0.); + f_EoP[i] -> SetLineColor(kRed+2); + + int fStatus = 0; + int nTrials = 0; + TFitResultPtr rp; + + rp = h_EoP[i] -> Fit(funcName, "ERLS+"); + while( (fStatus != 0) && (nTrials < 10) ) + { + rp = h_EoP[i] -> Fit(funcName, "ERLS+"); + fStatus = rp; + if(fStatus == 0) break; + ++nTrials; + } + + // fill the graph + double eee = f_EoP[i]->GetParError(1); + //float k = f_EoP[i]->GetParameter(1); + float k = f_EoP[i]->GetParameter(1) / h_Tsp[i]->GetMean(); //needed when using mellin's convolution + + /* + std::cout << i <<"--nocorr---- "<< 1./k << std::endl; + std::cout <<" condizione 1: " << h_EoP[i]->GetEntries() << " fStatus: " << fStatus << " eee: " << eee << "con eee che ci piace essere maggiore di : " << 0.05*h_template->GetRMS()/sqrt(evtsPerPoint) << std::endl ; + getchar(); + */ + + + // if( (h_EoP[i]->GetEntries() > 3) && (fStatus == 0) && (eee > 0.05*h_template->GetRMS()/sqrt(evtsPerPoint)) ) + if( (h_EoP[i]->GetEntries() > 500) && (fStatus == 0) ) + { + float date = (float)AveTime[i]; + float dLow = (float)(AveTime[i]-MinTime[i]); + float dHig = (float)(MaxTime[i]-AveTime[i]); + float run = (float)AveRun[i]; + float rLow = (float)(AveRun[i]-MinRun[i]); + float rHig = (float)(MaxRun[i]-AveRun[i]); + + g_fit -> SetPoint(i, date , 1./k); + g_fit -> SetPointError(i, dLow , dHig, eee/k/k, eee/k/k); + + g_fit_run -> SetPoint(i, run , 1./k); + g_fit_run -> SetPointError(i, rLow , rHig, eee/k/k, eee/k/k); + + std::cout <<"************-------------------*****************" < Fill(f_EoP[i]->GetChisquare()/f_EoP[i]->GetNDF()); + + EoP_scale += 1./k; + EoP_err += eee/k/k; + ++EoP_nActiveBins; + } + else + { + std::cout << "Fitting uncorrected time bin: " << i << " Fail status: " << fStatus << " sigma: " << eee << std::endl; + isValid = false; + } + + //---------------------------------- + // Fill the graph for corrected data + + // define the fitting function + // N.B. [0] * ( [1] * f( [1]*(x-[2]) ) ) + + sprintf(funcName,"f_EoC_%d",i); + if( strcmp(EBEE.c_str(),"EB") == 0 ) + f_EoC[i] = new TF1(funcName, templateHistoFunc, 0.8, 1.4, 3, "histoFunc"); + else + f_EoC[i] = new TF1(funcName, templateHistoFunc, 0.75, 1.5, 3, "histoFunc"); + f_EoC[i] -> SetParName(0,"Norm"); + f_EoC[i] -> SetParName(1,"Scale factor"); + f_EoC[i] -> SetLineWidth(1); + f_EoC[i] -> SetNpx(10000); + + xNorm = h_EoC[i]->GetEntries()/h_template->GetEntries() * + h_EoC[i]->GetBinWidth(1)/h_template->GetBinWidth(1); + + f_EoC[i] -> FixParameter(0, xNorm); + f_EoC[i] -> SetParameter(1, 0.99); + f_EoC[i] -> FixParameter(2, 0.); + f_EoC[i] -> SetLineColor(kGreen+2); + + + rp = h_EoC[i] -> Fit(funcName, "ERLS+"); + fStatus = rp; + nTrials = 0; + while( (fStatus != 0) && (nTrials < 10) ) + { + rp = h_EoC[i] -> Fit(funcName, "ERLS+"); + fStatus = rp; + if(fStatus == 0) break; + ++nTrials; + } + + + // fill the graph + k = f_EoC[i]->GetParameter(1); + eee = f_EoC[i]->GetParError(1); + + /* std::cout << i <<"--corr---- "<< 1./k << std::endl; + std::cout <<" condizione 1: " << h_EoP[i]->GetEntries() << " fStatus: " << fStatus << " eee: " << eee << "con eee che ci piace essere maggiore di : " << 0.05*h_template->GetRMS()/sqrt(evtsPerPoint) << std::endl ; + getchar(); + */ + + + if( (h_EoC[i]->GetEntries() > 500) && (fStatus == 0) ) + // if( (h_EoC[i]->GetEntries() > 10) && (fStatus == 0) && (eee > 0.05*h_template->GetRMS()/sqrt(evtsPerPoint)) ) + { + float date = (float)AveTime[i]; + float dLow = (float)(AveTime[i]-MinTime[i]); + float dHig = (float)(MaxTime[i]-AveTime[i]); + float run = (float)AveRun[i]; + float rLow = (float)(AveRun[i]-MinRun[i]); + float rHig = (float)(MaxRun[i]-AveRun[i]); + + g_c_fit -> SetPoint(i, date , 1./k); + g_c_fit -> SetPointError(i, dLow , dHig , eee/k/k, eee/k/k); + + g_c_fit_run -> SetPoint(i, run , 1./k); + g_c_fit_run -> SetPointError(i, rLow , rHig, eee/k/k, eee/k/k); + std::cout <<"************-------------------*****************" < Fill(f_EoC[i]->GetChisquare()/f_EoP[i]->GetNDF()); + + EoC_scale += 1./k; + EoC_err += eee/k/k; + ++EoC_nActiveBins; + } + else + { + std::cout << "Fitting corrected time bin: " << i << " Fail status: " << fStatus << " sigma: " << eee << std::endl; + isValid = false; + } + + if( isValid == true ) validBins.push_back(i); + } + + EoP_scale /= EoP_nActiveBins; + EoP_err /= EoP_nActiveBins; + + EoC_scale /= EoC_nActiveBins; + EoC_err /= EoC_nActiveBins; + + + + + + + //---------------------------------------- + // Fill the graph for avg laser correction + + //fede + for(unsigned int itr = 0; itr < validBins.size(); ++itr) + { + int i = validBins.at(itr); + g_las -> SetPoint(itr, (float)AveTime[i], h_Tsp[i]->GetMean()); + g_LT -> SetPoint(itr, (float)AveTime[i], AveLT[i] ); + g_LT -> SetPointError(itr, 0., sqrt(AveLT2[i]-AveLT[i]*AveLT[i]) / sqrt(Entries[i]) ); + + LCInv_scale += h_Tsp[i]->GetMean(); + } + + LCInv_scale /= validBins.size(); + + + + + + + //--------------- + // Rescale graphs + + float yscale = 1.; + //float yscale = 1./EoC_scale; + + for(unsigned int itr = 0; itr < validBins.size(); ++itr) + { + double x,y; + g_fit -> GetPoint(itr,x,y); + g_fit -> SetPoint(itr,x,y*yscale); + if ( (x > t1) && (x < t2) ) h_EoP_spread -> Fill(y*yscale); + + g_c_fit -> GetPoint(itr,x,y); + g_c_fit -> SetPoint(itr,x,y*yscale); + if ( (x > t1) && (x < t2) ) h_EoC_spread -> Fill(y*yscale); + + g_fit_run -> GetPoint(itr,x,y); + g_fit_run -> SetPoint(itr,x,y*yscale); + if ( (x > t1) && (x < t2) ) h_EoP_spread_run -> Fill(y*yscale); + + g_c_fit_run -> GetPoint(itr,x,y); + g_c_fit_run -> SetPoint(itr,x,y*yscale); + if ( (x > t1) && (x < t2) ) h_EoC_spread_run -> Fill(y*yscale); + + g_las -> GetPoint(itr,x,y); + g_las -> SetPoint(itr,x,y*yscale*EoP_scale/LCInv_scale); + } + TF1 EoC_pol0("EoC_pol0","pol0",t1,t2); + EoC_pol0.SetLineColor(kGreen+2); + EoC_pol0.SetLineWidth(2); + EoC_pol0.SetLineStyle(2); + g_c_fit -> Fit("EoC_pol0","QNR"); + + + + + + + + + //---------------------------- + // Print out global quantities + + std::cout << std::endl; + std::cout << "***** Mean scales and errors *****" << std::endl; + std::cout << std::fixed; + std::cout << std::setprecision(4); + std::cout << "Mean EoP scale: " << std::setw(6) << EoP_scale << " mean EoP error: " << std::setw(8) << EoP_err << std::endl; + std::cout << "Mean EoC scale: " << std::setw(6) << EoC_scale << " mean EoC error: " << std::setw(8) << EoC_err << std::endl; + std::cout << "Mean 1/LC scale: " << std::setw(6) << LCInv_scale << std::endl; + + + + + + + //----------------- + // Occupancy plots + //----------------- + + TCanvas* c_scOccupancy = new TCanvas("c_scOccupancy","SC occupancy",0,0,1000,500); + c_scOccupancy -> Divide(2,1); + + c_scOccupancy -> cd(1); + h_scOccupancy_eta -> GetXaxis() -> SetTitle("sc #eta"); + h_scOccupancy_eta -> GetYaxis() -> SetTitle("events"); + h_scOccupancy_eta -> Draw(); + + c_scOccupancy -> cd(2); + h_scOccupancy_phi -> GetXaxis() -> SetTitle("sc #phi"); + h_scOccupancy_phi -> GetYaxis() -> SetTitle("events"); + h_scOccupancy_phi -> Draw(); + + TCanvas* c_seedOccupancy = new TCanvas("c_seedOccupancy","seed occupancy",0,0,1500,500); + c_seedOccupancy -> Divide(3,1); + + c_seedOccupancy -> cd(1); + h_seedOccupancy_EB -> GetXaxis() -> SetTitle("seed i#eta"); + h_seedOccupancy_EB -> GetYaxis() -> SetTitle("seed i#phi"); + h_seedOccupancy_EB -> Draw("COLZ"); + + c_seedOccupancy -> cd(2); + h_seedOccupancy_EEp -> GetXaxis() -> SetTitle("seed ix"); + h_seedOccupancy_EEp -> GetYaxis() -> SetTitle("seed iy"); + h_seedOccupancy_EEp -> Draw("COLZ"); + + c_seedOccupancy -> cd(3); + h_seedOccupancy_EEm -> GetXaxis() -> SetTitle("seed ix"); + h_seedOccupancy_EEm -> GetYaxis() -> SetTitle("seed iy"); + h_seedOccupancy_EEm -> Draw("COLZ"); + + + + //----------- + // Chi2 plots + //----------- + + TCanvas* c_chi2 = new TCanvas("c_chi2","fit chi2",0,0,500,500); + c_chi2 -> cd(); + + h_EoC_chi2 -> GetXaxis() -> SetTitle("#chi^{2}/N_{dof}"); + h_EoC_chi2 -> Draw(""); + gPad -> Update(); + + TPaveStats* s_EoC = new TPaveStats; + s_EoC = (TPaveStats*)(h_EoC_chi2->GetListOfFunctions()->FindObject("stats")); + s_EoC -> SetStatFormat("1.4g"); + s_EoC -> SetTextColor(kGreen+2); + s_EoC->SetY1NDC(0.59); + s_EoC->SetY2NDC(0.79); + s_EoC -> Draw("sames"); + gPad -> Update(); + + h_EoP_chi2 -> GetXaxis() -> SetTitle("#chi^{2}/N_{dof}"); + h_EoP_chi2 -> Draw("sames"); + gPad -> Update(); + + TPaveStats* s_EoP = new TPaveStats; + s_EoP = (TPaveStats*)(h_EoP_chi2->GetListOfFunctions()->FindObject("stats")); + s_EoP -> SetStatFormat("1.4g"); + s_EoP -> SetTextColor(kRed+2); + s_EoP->SetY1NDC(0.79); + s_EoP->SetY2NDC(0.99); + s_EoP -> Draw("sames"); + gPad -> Update(); + + //ciao + //------------------- + // RMS vs Num evts -BARREL + //------------------- + double x[13]={2.,4.,6.,8.,10.,12.,14.,16.,18.,20.,22.,24.,30.}; + double y[13]={0.001049,0.001114,0.0009367,0.0008480,0.0007669,0.0007892,0.0006699,0.0006473,0.0006235,0.0005903,0.0005815,0.0005459,0.0005506}; + + TCanvas* RMSeb = new TCanvas("plot", "plot",0,0,500,500); + TGraph* gRMSeb = new TGraph(13,x,y); + + gRMSeb->Draw("APC"); + gRMSeb -> SetMarkerColor(38); + gRMSeb -> SetLineColor(38); + gRMSeb->GetXaxis()->SetTitle("Number of Events - Barrel"); + gRMSeb->GetYaxis()->SetTitle("RMS"); + + RMSeb -> Print((folderName+"/"+folderName+"_RMSeb"+".png").c_str(),"png"); + RMSeb -> Print((folderName+"/"+folderName+"_RMSeb"+".pdf").c_str(),"pdf"); + + //------------------- + // RMS vs Num evts -ENDCAP + //------------------- + + double xx[11]={2.,4.,6.,8.,10.,12.,14.,16.,18.,20.,22.}; + double yy[11]={0.007234,0.005759,0.004174,0.004255,0.003833,0.004037,0.003912,0.004251,0.003598,0.004067,0.004138}; + + TCanvas* RMSee = new TCanvas("plot", "plot",0,0,500,500); + TGraph* gRMSee = new TGraph(11,xx,yy); + + gRMSee->Draw("APC"); + gRMSee -> SetMarkerColor(38); + gRMSee -> SetLineColor(38); + gRMSee->GetXaxis()->SetTitle("Number of Events - Endcap"); + gRMSee->GetYaxis()->SetTitle("RMS"); + + + RMSee -> Print((folderName+"/"+folderName+"_RMSee"+".png").c_str(),"png"); + RMSee -> Print((folderName+"/"+folderName+"_RMSee"+".pdf").c_str(),"pdf"); + + + //ciao + //------------------- + // histos + //------------------- + + + /* + for ( int i = 0; i < nBins; ++i) + { + + TCanvas* histoEoP = new TCanvas("histo","histo",0,0,500,500); + histoEoP -> cd(); + + h_EoP[i] -> Draw(); + f_EoP[i] -> SetLineWidth(2); + f_EoP[i] -> SetLineColor(4); + f_EoP[i] -> Draw("same"); + // histoEoP -> Update(); + + histoEoP -> Print((folderName+"/"+folderName+"_histoEoP"+std::to_string(i)+".png").c_str(),"png"); + histoEoP -> Print((folderName+"/"+folderName+"_histoEoP"+std::to_string(i)+".pdf").c_str(),"pdf"); + + + TCanvas* histoEoC = new TCanvas("histo","histo",0,0,500,500); + histoEoC -> cd(); + + h_EoC[i] -> Draw(); + f_EoC[i] -> SetLineWidth(2); + f_EoC[i] -> SetLineColor(4); + f_EoC[i] -> Draw("same"); + //histoEoC -> Update(); + + histoEoC -> Print((folderName+"/"+folderName+"_histoEoC"+to_string(i)+".png").c_str(),"png"); + histoEoC -> Print((folderName+"/"+folderName+"_histoEoC"+to_string(i)+".pdf").c_str(),"pdf"); + + } + */ + + //------------------- + // Final Plot vs date + //------------------- + + TCanvas* cplot = new TCanvas("cplot", "history plot vs date",100,100,1000,500); + cplot->cd(); + + TPad *cLeft = new TPad("pad_0","pad_0",0.00,0.00,0.75,1.00); + TPad *cRight = new TPad("pad_1","pad_1",0.75,0.00,1.00,1.00); + + cLeft->SetLeftMargin(0.15); + cLeft->SetRightMargin(0.025); + cRight->SetLeftMargin(0.025); + + cLeft->Draw(); + cRight->Draw(); + + float tYoffset = 1.0; + float labSize = 0.05; + float labSize2 = 0.06; + + cLeft->cd(); + + cLeft->SetGridx(); + cLeft->SetGridy(); + + TH1F *hPad = (TH1F*)gPad->DrawFrame(t1,0.9,t2,1.05); + + //hPad->GetXaxis()->SetLimits(t3,t2); + hPad->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00"); + hPad->GetXaxis()->SetTimeDisplay(1); + hPad->GetXaxis() -> SetRangeUser(MinTime[0]-43200,MaxTime[nBins-1]+43200); + hPad->GetXaxis()->SetTitle("date (day/month)"); + //ciao + //hPad->GetXaxis()->SetLabelSize(0.025); + + if( strcmp(EBEE.c_str(),"EB") == 0 ) + hPad->GetYaxis()->SetTitle("Relative E/p scale"); + else + hPad->GetYaxis()->SetTitle("Relative E/p scale"); + hPad->GetYaxis()->SetTitleOffset(tYoffset); + hPad->GetXaxis()->SetTitleOffset(0.8); + hPad->GetXaxis()->SetLabelSize(0.03); + hPad->GetXaxis()->SetTitleSize(labSize2); + hPad->GetYaxis()->SetLabelSize(labSize); + hPad->GetYaxis()->SetTitleSize(labSize2); + hPad -> SetMinimum(yMIN); + hPad -> SetMaximum(yMAX); + + // draw history plot + g_fit -> SetMarkerStyle(24); + g_fit -> SetMarkerSize(0.7); + g_fit -> SetMarkerColor(kRed+2); + g_fit -> SetLineColor(kRed+2); + g_fit -> Draw("P"); + g_c_fit -> SetMarkerStyle(20); + g_c_fit -> SetMarkerColor(kGreen+2); + g_c_fit -> SetLineColor(kGreen+2); + g_c_fit -> SetMarkerSize(0.7); + g_c_fit -> Draw("EP,same"); + g_las -> SetLineColor(kAzure-2); + g_las -> SetLineWidth(2); + // g_las -> Draw("L,same"); + + TLegend* legend = new TLegend(0.60,0.78,0.90,0.94); + legend -> SetLineColor(kWhite); + legend -> SetLineWidth(0); + legend -> SetFillColor(kWhite); + legend -> SetFillStyle(0); + legend -> SetTextFont(42); + legend -> SetTextSize(0.04); + legend -> AddEntry(g_c_fit,"with LM correction","PL"); + legend -> AddEntry(g_fit, "without LM correction","PL"); + // legend -> AddEntry(g_las, "1 / LM correction","L"); + legend -> Draw("same"); + + char latexBuffer[250]; + + sprintf(latexBuffer,"CMS 2016 Preliminary"); + TLatex* latex = new TLatex(0.18,0.89,latexBuffer); + latex -> SetNDC(); + latex -> SetTextFont(62); + latex -> SetTextSize(0.05); + latex -> Draw("same"); + + //sprintf(latexBuffer,"#sqrt{s} = 8 TeV L = 3.95 fb^{-1}"); + sprintf(latexBuffer,"#sqrt{s} = 13 TeV, L =%s fb^{-1} ", LUMI.c_str()); + + // sprintf(latexBuffer, LUMI.c_str()); + TLatex* latex2 = new TLatex(0.18,0.84,latexBuffer); + latex2 -> SetNDC(); + latex2 -> SetTextFont(42); + latex2 -> SetTextSize(0.05); + latex2 -> Draw("same"); + + if( strcmp(EBEE.c_str(),"EB") == 0 || strcmp(EBEE.c_str(),"EB_0_1") == 0 || strcmp(EBEE.c_str(),"EB_1_1479") == 0) + sprintf(latexBuffer,"ECAL Barrel"); + else + sprintf(latexBuffer,"ECAL Endcap"); + TLatex* latex3 = new TLatex(0.18,0.19,latexBuffer); + latex3 -> SetNDC(); + latex3 -> SetTextFont(42); + latex3 -> SetTextSize(0.05); + latex3 -> Draw("same"); + + //sprintf(latexBuffer,"%.2E events",1.*nSavePts); + //TLatex* latex4 = new TLatex(0.18,0.24,latexBuffer); + //latex4 -> SetNDC(); + //latex4 -> SetTextFont(42); + //latex4 -> SetTextSize(0.04); + //latex4 -> Draw("same"); + // + //sprintf(latexBuffer,"%d events/bin - %d bins",evtsPerPoint,nBins); + //TLatex* latex5 = new TLatex(0.18,0.19,latexBuffer); + //latex5 -> SetNDC(); + //latex5 -> SetTextFont(42); + //latex5 -> SetTextSize(0.04); + //latex5 -> Draw("same"); + + + cRight -> cd(); + + TPaveStats* s_EoP_spread = new TPaveStats(); + TPaveStats* s_EoC_spread = new TPaveStats(); + + + h_EoC_spread -> SetFillStyle(3001); + h_EoC_spread -> SetFillColor(kGreen+2); + h_EoC_spread->GetYaxis()->SetLabelSize(0.09); + h_EoC_spread->GetYaxis()->SetLabelOffset(-0.03); + h_EoC_spread->GetYaxis()->SetTitleSize(0.08); + h_EoC_spread->GetYaxis()->SetNdivisions(505); + h_EoC_spread->GetXaxis()->SetLabelOffset(1000); + + h_EoC_spread -> Draw("hbar"); + gPad -> Update(); + + s_EoC_spread = (TPaveStats*)(h_EoC_spread->GetListOfFunctions()->FindObject("stats")); + s_EoC_spread -> SetStatFormat("1.4g"); + s_EoC_spread->SetX1NDC(0.06); //new x start position + s_EoC_spread->SetX2NDC(0.71); //new x end position + s_EoC_spread->SetY1NDC(0.43); //new x start position + s_EoC_spread->SetY2NDC(0.34); //new x end position + s_EoC_spread -> SetOptStat(1100); + s_EoC_spread ->SetTextColor(kGreen+2); + s_EoC_spread ->SetTextSize(0.08); + s_EoC_spread -> Draw("sames"); + + + h_EoP_spread -> SetFillStyle(3001); + h_EoP_spread -> SetFillColor(kRed+2); + h_EoP_spread -> Draw("hbarsames"); + gPad -> Update(); + s_EoP_spread = (TPaveStats*)(h_EoP_spread->GetListOfFunctions()->FindObject("stats")); + s_EoP_spread -> SetStatFormat("1.4g"); + s_EoP_spread->SetX1NDC(0.06); //new x start position + s_EoP_spread->SetX2NDC(0.71); //new x end position + s_EoP_spread->SetY1NDC(0.33); //new x start position + s_EoP_spread->SetY2NDC(0.24); //new x end position + s_EoP_spread ->SetOptStat(1100); + s_EoP_spread ->SetTextColor(kRed+2); + s_EoP_spread ->SetTextSize(0.08); + s_EoP_spread -> Draw("sames"); + + /* + h_EoP_spread -> SetFillStyle(3001); + h_EoP_spread -> SetFillColor(kRed+2); + h_EoP_spread -> Draw("hbarsame"); + gPad -> Update(); + */ + + + + //------------------ + // Final plot vs run + //------------------ + if (vsPU==0) { + + TCanvas* cplot_run = new TCanvas("cplot_run", "history plot vs run",100,100,1000,500); + cplot_run->cd(); + + cLeft = new TPad("pad_0_run","pad_0_run",0.00,0.00,0.75,1.00); + cRight = new TPad("pad_1_run","pad_1_run",0.75,0.00,1.00,1.00); + + cLeft->SetLeftMargin(0.15); + cLeft->SetRightMargin(0.025); + cRight->SetLeftMargin(0.025); + + cLeft->Draw(); + cRight->Draw(); + + tYoffset = 1.5; + labSize = 0.04; + labSize2 = 0.07; + + cLeft->cd(); + + cLeft->SetGridx(); + cLeft->SetGridy(); + + hPad = (TH1F*)gPad->DrawFrame(MinRun[0]-1000,0.9,MaxRun[nBins-1]+1000,1.05); + hPad->GetXaxis()->SetTitle("run"); + if( strcmp(EBEE.c_str(),"EB") == 0 ) + hPad->GetYaxis()->SetTitle("Relative E/p scale"); + else + hPad->GetYaxis()->SetTitle("Relative E/p scale"); + hPad->GetYaxis()->SetTitleOffset(tYoffset); + hPad->GetYaxis()->SetTitleOffset(0.8); + hPad->GetXaxis()->SetLabelSize(labSize); + hPad->GetXaxis()->SetTitleSize(labSize); + hPad->GetYaxis()->SetLabelSize(labSize); + hPad->GetYaxis()->SetTitleSize(labSize); + hPad -> SetMinimum(yMIN); + hPad -> SetMaximum(yMAX); + + // draw history plot + g_fit_run -> SetMarkerStyle(20); + g_fit_run -> SetMarkerSize(0.7); + g_fit_run -> SetMarkerColor(kRed+2); + g_fit_run -> SetLineColor(kRed+2); + g_fit_run -> Draw("P"); + g_c_fit_run -> SetMarkerStyle(20); + g_c_fit_run -> SetMarkerColor(kGreen+2); + g_c_fit_run -> SetLineColor(kGreen+2); + g_c_fit_run -> SetMarkerSize(0.7); + g_c_fit_run -> Draw("P,same"); + + + cRight -> cd(); + + s_EoP_spread = new TPaveStats(); + s_EoC_spread = new TPaveStats(); + + + h_EoC_spread_run -> SetFillStyle(3001); + h_EoC_spread_run -> SetFillColor(kGreen+2); + h_EoC_spread_run->GetYaxis()->SetLabelSize(labSize2); + h_EoC_spread_run->GetYaxis()->SetTitleSize(labSize2); + h_EoC_spread_run->GetYaxis()->SetNdivisions(505); + h_EoC_spread_run->GetYaxis()->SetLabelOffset(-0.02); + h_EoC_spread_run->GetXaxis()->SetLabelOffset(1000); + + h_EoC_spread_run -> Draw("hbar"); + gPad -> Update(); + + s_EoC_spread = (TPaveStats*)(h_EoC_spread_run->GetListOfFunctions()->FindObject("stats")); + s_EoC_spread ->SetTextColor(kGreen+2); + s_EoC_spread ->SetTextSize(0.06); + s_EoC_spread->SetX1NDC(0.49); //new x start position + + s_EoC_spread->SetX2NDC(0.99); //new x end position + s_EoC_spread->SetY1NDC(0.475); //new x start position + s_EoC_spread->SetY2NDC(0.590); //new x end position + s_EoC_spread -> SetOptStat(1100); + s_EoC_spread -> Draw("sames"); + + h_EoP_spread_run -> SetFillStyle(3001); + h_EoP_spread_run -> SetFillColor(kRed+2); + h_EoP_spread_run -> Draw("hbarsames"); + gPad -> Update(); + + s_EoP_spread = (TPaveStats*)(h_EoP_spread_run->GetListOfFunctions()->FindObject("stats")); + s_EoP_spread->SetX1NDC(0.49); //new x start position + s_EoP_spread->SetX2NDC(0.99); //new x end position + s_EoP_spread->SetY1NDC(0.350); //new x start position + s_EoP_spread->SetY2NDC(0.475); //new x end position + s_EoP_spread ->SetOptStat(1100); + s_EoP_spread ->SetTextColor(kRed+2); + s_EoP_spread ->SetTextSize(0.06); + s_EoP_spread -> Draw("sames"); + + + + + c_chi2 -> Print((folderName+"/"+folderName+"_fitChi2.png").c_str(),"png"); + c_scOccupancy -> Print((folderName+"/"+folderName+"_scOccupancy.png").c_str(),"png"); + c_seedOccupancy -> Print((folderName+"/"+folderName+"_seedOccupancy.png").c_str(),"png"); + cplot -> Print((folderName+"/"+folderName+"_history_vsTime.png").c_str(),"png"); + cplot_run -> Print((folderName+"/"+folderName+"_history_vsRun.png").c_str(),"png"); + + c_chi2 -> Print((folderName+"/"+folderName+"_fitChi2.pdf").c_str(),"pdf"); + c_scOccupancy -> Print((folderName+"/"+folderName+"_scOccupancy.pdf").c_str(),"pdf"); + c_seedOccupancy -> Print((folderName+"/"+folderName+"_seedOccupancy.pdf").c_str(),"pdf"); + cplot -> Print((folderName+"/"+folderName+"_history_vsTime.pdf").c_str(),"pdf"); + cplot_run -> Print((folderName+"/"+folderName+"_history_vsRun.pdf").c_str(),"pdf"); + + cplot -> SaveAs((folderName+"/"+folderName+"_history_vsTime.C").c_str()); + cplot_run -> SaveAs((folderName+"/"+folderName+"_history_vsRun.C").c_str()); + + cplot -> SaveAs((folderName+"/"+folderName+"_history_vsTime.root").c_str()); + cplot_run -> SaveAs((folderName+"/"+folderName+"_history_vsRun.root").c_str()); + + } + + + else { + + /////////////////////////PLOT + TCanvas* cplot = new TCanvas("cplot", "history plot vs Vertex",100,100,1000,500); + cplot->cd(); + + TPad *cLeft = new TPad("pad_0","pad_0",0.00,0.00,0.75,1.00); + TPad *cRight = new TPad("pad_1","pad_1",0.75,0.00,1.00,1.00); + + cLeft->SetLeftMargin(0.15); + cLeft->SetRightMargin(0.025); + cRight->SetLeftMargin(0.025); + + cLeft->Draw(); + cRight->Draw(); + + float tYoffset = 1.0; + float labSize = 0.05; + float labSize2 = 0.06; + + cLeft->cd(); + + cLeft->SetGridx(); + cLeft->SetGridy(); + + TH1F *hPad = (TH1F*)gPad->DrawFrame(t1,0.9,t2,1.05); + + hPad->GetXaxis()->SetLimits(0,46); + //hPad->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00"); + //hPad->GetXaxis()->SetTimeDisplay(1); + //hPad->GetXaxis() -> SetRangeUser(MinTime[0]-43200,MaxTime[nBins-1]+43200); + hPad->GetXaxis()->SetTitle(" Number of Vertices"); + hPad->GetXaxis()->SetTitleOffset(0.8); + + //ciao + + + if( strcmp(EBEE.c_str(),"EB") == 0 ) + hPad->GetYaxis()->SetTitle("Relative E/p scale"); + else + hPad->GetYaxis()->SetTitle("Relative E/p scale"); + hPad->GetYaxis()->SetTitleOffset(tYoffset); + hPad->GetXaxis()->SetLabelSize(labSize); + hPad->GetXaxis()->SetTitleSize(labSize2); + hPad->GetYaxis()->SetLabelSize(labSize); + hPad->GetYaxis()->SetTitleSize(labSize2); + hPad -> SetMinimum(yMIN); + hPad -> SetMaximum(yMAX); + + // draw history plot + g_fit -> SetMarkerStyle(24); + g_fit -> SetMarkerSize(0.7); + g_fit -> SetMarkerColor(kRed+2); + g_fit -> SetLineColor(kRed+2); + //g_fit -> Draw("P"); + g_c_fit -> SetMarkerStyle(20); + g_c_fit -> SetMarkerColor(kGreen+2); + g_c_fit -> SetLineColor(kGreen+2); + g_c_fit -> SetMarkerSize(0.7); + g_c_fit -> Draw("EP"); + g_las -> SetLineColor(kAzure-2); + g_las -> SetLineWidth(2); + //g_las -> Draw("L,same"); + + TLegend* legend = new TLegend(0.60,0.78,0.90,0.94); + legend -> SetLineColor(kWhite); + legend -> SetLineWidth(0); + legend -> SetFillColor(kWhite); + legend -> SetFillStyle(0); + legend -> SetTextFont(42); + legend -> SetTextSize(0.04); + legend -> AddEntry(g_c_fit,"with LM correction","PL"); + //legend -> AddEntry(g_fit, "without LM correction","PL"); + //legend -> AddEntry(g_las, "1 / LM correction","L"); + legend -> Draw("same"); + + char latexBuffer[250]; + + sprintf(latexBuffer,"CMS 2015 Preliminary"); + TLatex* latex = new TLatex(0.18,0.89,latexBuffer); + latex -> SetNDC(); + latex -> SetTextFont(62); + latex -> SetTextSize(0.05); + latex -> Draw("same"); + + //sprintf(latexBuffer,"#sqrt{s} = 8 TeV L = 3.95 fb^{-1}"); + sprintf(latexBuffer,"#sqrt{s} = 13 TeV"); + TLatex* latex2 = new TLatex(0.18,0.84,latexBuffer); + latex2 -> SetNDC(); + latex2 -> SetTextFont(42); + latex2 -> SetTextSize(0.05); + latex2 -> Draw("same"); + + if( strcmp(EBEE.c_str(),"EB") == 0 || strcmp(EBEE.c_str(),"EB_0_1") == 0 || strcmp(EBEE.c_str(),"EB_1_1479") == 0) + sprintf(latexBuffer,"ECAL Barrel"); + else + sprintf(latexBuffer,"ECAL Endcap"); + TLatex* latex3 = new TLatex(0.18,0.19,latexBuffer); + latex3 -> SetNDC(); + latex3 -> SetTextFont(42); + latex3 -> SetTextSize(0.05); + latex3 -> Draw("same"); + + //sprintf(latexBuffer,"%.2E events",1.*nSavePts); + //TLatex* latex4 = new TLatex(0.18,0.24,latexBuffer); + //latex4 -> SetNDC(); + //latex4 -> SetTextFont(42); + //latex4 -> SetTextSize(0.04); + //latex4 -> Draw("same"); + // + //sprintf(latexBuffer,"%d events/bin - %d bins",evtsPerPoint,nBins); + //TLatex* latex5 = new TLatex(0.18,0.19,latexBuffer); + //latex5 -> SetNDC(); + //latex5 -> SetTextFont(42); + //latex5 -> SetTextSize(0.04); + //latex5 -> Draw("same"); + + + cRight -> cd(); + + TPaveStats* s_EoP_spread = new TPaveStats(); + TPaveStats* s_EoC_spread = new TPaveStats(); + + + h_EoC_spread -> SetFillStyle(3001); + h_EoC_spread -> SetFillColor(kGreen+2); + h_EoC_spread->GetYaxis()->SetLabelSize(0.09); + h_EoC_spread->GetYaxis()->SetLabelOffset(-0.03); + h_EoC_spread->GetYaxis()->SetTitleSize(0.08); + h_EoC_spread->GetYaxis()->SetNdivisions(505); + h_EoC_spread->GetXaxis()->SetLabelOffset(1000); + + h_EoC_spread -> Draw("hbar"); + gPad -> Update(); + + s_EoC_spread = (TPaveStats*)(h_EoC_spread->GetListOfFunctions()->FindObject("stats")); + s_EoC_spread -> SetStatFormat("1.4g"); + s_EoC_spread->SetX1NDC(0.06); //new x start position + s_EoC_spread->SetX2NDC(0.71); //new x end position + s_EoC_spread->SetY1NDC(0.43); //new x start position + s_EoC_spread->SetY2NDC(0.34); //new x end position + s_EoC_spread -> SetOptStat(1100); + s_EoC_spread ->SetTextColor(kGreen+2); + s_EoC_spread ->SetTextSize(0.08); + s_EoC_spread -> Draw("sames"); + + + h_EoP_spread -> SetFillStyle(3001); + h_EoP_spread -> SetFillColor(kRed+2); + h_EoP_spread -> Draw("hbarsames"); + gPad -> Update(); + s_EoP_spread = (TPaveStats*)(h_EoP_spread->GetListOfFunctions()->FindObject("stats")); + s_EoP_spread -> SetStatFormat("1.4g"); + s_EoP_spread->SetX1NDC(0.06); //new x start position + s_EoP_spread->SetX2NDC(0.71); //new x end position + s_EoP_spread->SetY1NDC(0.33); //new x start position + s_EoP_spread->SetY2NDC(0.24); //new x end position + s_EoP_spread ->SetOptStat(1100); + s_EoP_spread ->SetTextColor(kRed+2); + s_EoP_spread ->SetTextSize(0.08); + s_EoP_spread -> Draw("sames"); + + /* + h_EoP_spread -> SetFillStyle(3001); + h_EoP_spread -> SetFillColor(kRed+2); + h_EoP_spread -> Draw("hbarsame"); + gPad -> Update(); + */ + + + + + + cplot -> Print((folderName+"/"+folderName+"_history_vsVertex.png").c_str(),"png"); + + cplot -> Print((folderName+"/"+folderName+"_history_vsVertex.pdf").c_str(),"pdf"); + + cplot -> SaveAs((folderName+"/"+folderName+"_history_vsVertex.C").c_str()); + + } + + + + + + /////////////////////////// + + o -> cd(); + + h_template -> Write(); + + h_scOccupancy_eta -> Write(); + h_scOccupancy_phi -> Write(); + h_seedOccupancy_EB -> Write(); + h_seedOccupancy_EEp -> Write(); + h_seedOccupancy_EEm -> Write(); + + g_fit -> Write("g_fit"); + g_c_fit -> Write("g_c_fit"); + g_fit_run -> Write("g_fit_run"); + g_c_fit_run -> Write("g_c_fit_run"); + g_las -> Write("g_las"); + g_LT -> Write("g_LT"); + + h_EoP_chi2 -> Write(); + h_EoC_chi2 -> Write(); + + //ciao + + for(int i = 0; i < nBins; ++i) + { + gStyle->SetOptFit(1111); + + h_EoP[i] -> Write(); + h_EoC[i] -> Write(); + f_EoP[i] -> Write(); + f_EoC[i] -> Write(); + // h_Tsp[i] -> Write(); + // + // h_Cvl[i] -> Write(); + } + + o -> Close(); + + } + + +void LaserMonitoringEoP::setLaserPlotStyle() +{ + TStyle* laserPlotStyle = new TStyle("laserPlotStyle","Style for P-TDR"); + + // For the canvas: + laserPlotStyle->SetCanvasBorderMode(0); + laserPlotStyle->SetCanvasColor(kWhite); + laserPlotStyle->SetCanvasDefH(600); //Height of canvas + laserPlotStyle->SetCanvasDefW(700); //Width of canvas + //laserPlotStyle->SetCanvasDefW(800); //Width of canvas + laserPlotStyle->SetCanvasDefX(0); //POsition on screen + laserPlotStyle->SetCanvasDefY(0); + + // For the Pad: + laserPlotStyle->SetPadBorderMode(0); + // laserPlotStyle->SetPadBorderSize(Width_t size = 1); + laserPlotStyle->SetPadColor(kWhite); + laserPlotStyle->SetPadGridX(false); + laserPlotStyle->SetPadGridY(false); + laserPlotStyle->SetGridColor(0); + laserPlotStyle->SetGridStyle(3); + laserPlotStyle->SetGridWidth(1); + + // For the frame: + laserPlotStyle->SetFrameBorderMode(0); + laserPlotStyle->SetFrameBorderSize(1); + laserPlotStyle->SetFrameFillColor(0); + laserPlotStyle->SetFrameFillStyle(0); + laserPlotStyle->SetFrameLineColor(1); + laserPlotStyle->SetFrameLineStyle(1); + laserPlotStyle->SetFrameLineWidth(1); + + // For the histo: + // laserPlotStyle->SetHistFillColor(1); + // laserPlotStyle->SetHistFillStyle(0); + laserPlotStyle->SetHistLineColor(1); + laserPlotStyle->SetHistLineStyle(0); + laserPlotStyle->SetHistLineWidth(1); + // laserPlotStyle->SetLegoInnerR(Float_t rad = 0.5); + // laserPlotStyle->SetNumberContours(Int_t number = 20); + + laserPlotStyle->SetEndErrorSize(2); + // laserPlotStyle->SetErrorMarker(20); + //laserPlotStyle->SetErrorX(0.); + + laserPlotStyle->SetMarkerStyle(20); + + //For the fit/function: + laserPlotStyle->SetOptFit(0); + laserPlotStyle->SetFitFormat("5.4g"); + laserPlotStyle->SetFuncColor(2); + laserPlotStyle->SetFuncStyle(1); + laserPlotStyle->SetFuncWidth(1); + + //For the date: + laserPlotStyle->SetOptDate(0); + // laserPlotStyle->SetDateX(Float_t x = 0.01); + // laserPlotStyle->SetDateY(Float_t y = 0.01); + + // For the statistics box: + laserPlotStyle->SetOptFile(0); + laserPlotStyle->SetOptStat(0); // To display the mean and RMS: SetOptStat("mr"); + laserPlotStyle->SetStatColor(kWhite); + laserPlotStyle->SetStatFont(42); + laserPlotStyle->SetStatFontSize(0.025); + laserPlotStyle->SetStatTextColor(1); + laserPlotStyle->SetStatFormat("6.4g"); + laserPlotStyle->SetStatBorderSize(1); + laserPlotStyle->SetStatH(0.1); + laserPlotStyle->SetStatW(0.15); + // laserPlotStyle->SetStatStyle(Style_t style = 1001); + // laserPlotStyle->SetStatX(Float_t x = 0); + // laserPlotStyle->SetStatY(Float_t y = 0); + + // Margins: + laserPlotStyle->SetPadTopMargin(0.05); + laserPlotStyle->SetPadBottomMargin(0.13); + laserPlotStyle->SetPadLeftMargin(0.13); + laserPlotStyle->SetPadRightMargin(0.17); + //laserPlotStyle->SetPadRightMargin(0.25); + + // For the Global title: + laserPlotStyle->SetOptTitle(0); + laserPlotStyle->SetTitleFont(42); + laserPlotStyle->SetTitleColor(1); + laserPlotStyle->SetTitleTextColor(1); + laserPlotStyle->SetTitleFillColor(10); + laserPlotStyle->SetTitleFontSize(0.05); + // laserPlotStyle->SetTitleH(0); // Set the height of the title box + // laserPlotStyle->SetTitleW(0); // Set the width of the title box + // laserPlotStyle->SetTitleX(0); // Set the position of the title box + // laserPlotStyle->SetTitleY(0.985); // Set the position of the title box + // laserPlotStyle->SetTitleStyle(Style_t style = 1001); + // laserPlotStyle->SetTitleBorderSize(2); + + // For the axis titles: + laserPlotStyle->SetTitleColor(1, "XYZ"); + laserPlotStyle->SetTitleFont(42, "XYZ"); + laserPlotStyle->SetTitleSize(0.05, "XYZ"); + // laserPlotStyle->SetTitleXSize(Float_t size = 0.02); // Another way to set the size? + // laserPlotStyle->SetTitleYSize(Float_t size = 0.02); + laserPlotStyle->SetTitleXOffset(1.20); + laserPlotStyle->SetTitleYOffset(1.40); + laserPlotStyle->SetTitleOffset(1.30, "Z"); + // laserPlotStyle->SetTitleOffset(1.1, "Y"); // Another way to set the Offset + + // For the axis labels: + laserPlotStyle->SetLabelColor(1, "XYZ"); + laserPlotStyle->SetLabelFont(42, "XYZ"); + laserPlotStyle->SetLabelOffset(0.005, "XYZ"); + laserPlotStyle->SetLabelSize(0.04, "XYZ"); + + // For the axis: + laserPlotStyle->SetAxisColor(1, "XYZ"); + laserPlotStyle->SetStripDecimals(kTRUE); + laserPlotStyle->SetTickLength(0.03, "XYZ"); + laserPlotStyle->SetNdivisions(510, "XYZ"); + laserPlotStyle->SetPadTickX(1); // To get tick marks on the opposite side of the frame + laserPlotStyle->SetPadTickY(1); + + // Change for log plots: + laserPlotStyle->SetOptLogx(0); + laserPlotStyle->SetOptLogy(0); + laserPlotStyle->SetOptLogz(0); + + // Postscript options: + laserPlotStyle->SetPaperSize(20.,20.); + // laserPlotStyle->SetLineScalePS(Float_t scale = 3); + // laserPlotStyle->SetLineStyleString(Int_t i, const char* text); + // laserPlotStyle->SetHeaderPS(const char* header); + // laserPlotStyle->SetTitlePS(const char* pstitle); + + //laserPlotStyle->SetBarOffset(Float_t baroff = 0.5); + //laserPlotStyle->SetBarWidth(Float_t barwidth = 0.5); + //laserPlotStyle->SetPaintTextFormat(const char* format = "g"); + laserPlotStyle->SetPalette(1); + //laserPlotStyle->SetTimeOffset(Double_t toffset); + //laserPlotStyle->SetHistMinimumZero(kTRUE); + + + + const Int_t NRGBs = 5; + const Int_t NCont = 255; + + Double_t stops[NRGBs] = { 0.00, 0.34, 0.61, 0.84, 1.00 }; + Double_t red[NRGBs] = { 0.00, 0.00, 0.87, 1.00, 0.51 }; + Double_t green[NRGBs] = { 0.00, 0.81, 1.00, 0.20, 0.00 }; + Double_t blue[NRGBs] = { 0.51, 1.00, 0.12, 0.00, 0.00 }; + TColor::CreateGradientColorTable(NRGBs, stops, red, green, blue, NCont); + TColor::CreateGradientColorTable(NRGBs, stops, red, green, blue, NCont); + laserPlotStyle->SetNumberContours(NCont); + + //TLatex *lab = new TLatex(0.70,0.85, "CMS 2008"); + //lab->SetNDC(); + //lab->SetTextFont(42); + //lab->SetTextSize(0.05); + //lab->Draw("same"); + + + + gROOT -> ForceStyle(); + + laserPlotStyle->cd(); +} diff --git a/EOverPCalibration/src/TEndcapRings.cc b/EOverPCalibration/src/TEndcapRings.cc index ddb38b1fbc5..6f0d21ef8c0 100644 --- a/EOverPCalibration/src/TEndcapRings.cc +++ b/EOverPCalibration/src/TEndcapRings.cc @@ -14,7 +14,7 @@ TEndcapRings::TEndcapRings() iEndcapRing[ix][iy][iz] = -1; FILE *fRing; - fRing = fopen("../EOverPCalibration/CommonTools/eerings.dat","r"); + fRing = fopen("/afs/cern.ch/user/l/lbrianza/work/PHD/DEF_ECALELF/CHE_SUCCEDE_IN_ECALELF/CALIBRAZIONI/CMSSW_7_4_12/src/Calibration/EOverPCalibration/CommonTools/eerings.dat","r"); std::cout << "Inizializing endcap geometry from: eerings.dat"<< std::endl; int ix,iy,iz,ir; while(fscanf(fRing,"(%d,%d,%d) %d \n",&ix,&iy,&iz,&ir) !=EOF ) diff --git a/EOverPCalibration/src/ntpleUtils2.cc b/EOverPCalibration/src/ntpleUtils2.cc new file mode 100644 index 00000000000..486097c5d85 --- /dev/null +++ b/EOverPCalibration/src/ntpleUtils2.cc @@ -0,0 +1,83 @@ +#include "../interface/ntpleUtils2.h" + +TH1F* templateHisto; +TF1* templateFunc; + +std::vector* mydata; + +/*** fit the template ***/ +void FitTemplate(const bool& draw) +{ + TCanvas* c_template; + if( draw ) + { + c_template = new TCanvas("c_template","template"); + c_template -> cd(); + c_template -> SetGridx(); + c_template -> SetGridy(); + + templateHisto -> Scale(1./templateHisto->GetEntries()); + templateHisto -> SetFillColor(kCyan+2); + templateHisto -> Draw(); + } + + templateFunc = new TF1("templateFunc", crystalBallLowHigh_v2, 0., 10., 8); + templateFunc -> SetNpx(10000); + templateFunc -> SetLineWidth(2); + templateFunc -> SetLineColor(kRed); + + templateFunc -> SetParameters(templateHisto->GetMaximum(),1.,0.05,1.,2.,2.,1.,1.); + templateFunc -> FixParameter(7,1.); + templateFunc -> SetParLimits(3,0.,10.); + templateFunc -> SetParLimits(5,0.,10.); + + templateFunc -> SetParName(0,"N"); + templateFunc -> SetParName(1,"#mu"); + templateFunc -> SetParName(2,"#sigma"); + templateFunc -> SetParName(3,"#alpha_{high}"); + templateFunc -> SetParName(4,"n_{high}"); + templateFunc -> SetParName(5,"#alpha_{low}"); + templateFunc -> SetParName(6,"n_{low}"); + + templateHisto -> Fit("templateFunc","NQR+","",0.5,3.); + + if( draw ) + templateFunc -> Draw("same"); +} + + +/*** double crystall ball ***/ +double crystalBallLowHigh_v2(double* x, double* par) +{ + //[0] = N + //[1] = mean + //[2] = sigma + //[3] = alpha + //[4] = n + //[5] = alpha2 + //[6] = n2 + //[7] = scale + double xx = x[0] * par[7]; + double mean = par[1]; + double sigma = par[2]; + double alpha = par[3]; + double n = par[4]; + double alpha2 = par[5]; + double n2 = par[6]; + if( (xx-mean)/sigma > fabs(alpha) ) + { + double A = pow(n/fabs(alpha), n) * exp(-0.5 * alpha*alpha); + double B = n/fabs(alpha) - fabs(alpha); + return par[0] * par[7] * A * pow(B + (xx-mean)/sigma, -1.*n); + } + else if( (xx-mean)/sigma < -1.*fabs(alpha2) ) + { + double A = pow(n2/fabs(alpha2), n2) * exp(-0.5 * alpha2*alpha2); + double B = n2/fabs(alpha2) - fabs(alpha2); + return par[0] * par[7] * A * pow(B - (xx-mean)/sigma, -1.*n2); + } + else + { + return par[0] * par[7] * exp(-1. * (xx-mean)*(xx-mean) / (2*sigma*sigma) ); + } +} diff --git a/EOverPCalibration/src/stabilityUtils.cc b/EOverPCalibration/src/stabilityUtils.cc new file mode 100644 index 00000000000..308a24e33ff --- /dev/null +++ b/EOverPCalibration/src/stabilityUtils.cc @@ -0,0 +1,146 @@ +#include "../interface/stabilityUtils.h" + +using namespace std; + +int dateToInt(const std::string& date) +{ + int day; + int month; + int year; + int tempo; + + TString date2 = date; + + TObjArray *splitted = date2.Tokenize("-"); + + TObjString *Objstring1 = (TObjString *) splitted->At(0); + TObjString *Objstring2 = (TObjString *) splitted->At(1); + TObjString *Objstring3 = (TObjString *) splitted->At(2); + + + TString string1 = Objstring1->GetString(); + TString string2 = Objstring2->GetString(); + TString string3 = Objstring3->GetString(); + + + std::cout<< "day: " << string1 << std::endl; + std::cout<< "month: " << string2 << std::endl; + std::cout<< "year: " << string3 << std::endl; + + + std::string stringday = string1.Data(); + std::string stringmonth = string2.Data(); + std::string stringyear = string3.Data(); + + day = atoi(stringday.c_str()); + month = atoi(stringmonth.c_str()); + year = atoi(stringyear.c_str()); + /* + istringstream buffer1(stringday); + buffer1 >> day; + istringstream buffer2(stringmonth); + buffer2 >> month; + istringstream buffer3(stringyear); + buffer3 >> year; + */ + + + std::cout<< "day: " < SetLineWidth(2); + + h -> GetXaxis() -> SetTitleSize(0.04); + h -> GetXaxis() -> SetLabelSize(0.04); + + h -> GetYaxis() -> SetTitleSize(0.04); + h -> GetYaxis() -> SetLabelSize(0.04); + + h -> GetYaxis() -> SetTitleOffset(1.5); + + if( label == "EoP") + { + h -> SetMarkerColor(kRed+2); + h -> SetLineColor(kRed+2); + h -> SetFillColor(kRed+2); + h -> SetFillStyle(3004); + h -> SetMarkerStyle(7); + } + + if( label == "EoC") + { + h -> SetMarkerColor(kGreen+2); + h -> SetLineColor(kGreen+2); + h -> SetFillColor(kGreen+2); + h -> SetFillStyle(3004); + h -> SetMarkerStyle(7); + } +} + + + + + + +TH1F* MellinConvolution(const std::string& name, TH1F* h_template, TH1F* h_Las) +{ + histoFunc* templateHistoFunc = new histoFunc(h_template); + + TF1* f_template = new TF1("f_template", templateHistoFunc, 0.8*(h_Las->GetMean()), 1.4*(h_Las->GetMean()), 3, "histoFunc"); + + f_template -> SetNpx(10000); + f_template -> FixParameter(0, 1.); + f_template -> SetParameter(1, 1.); + f_template -> FixParameter(2, 0.); + + TH1F* h_convolutedTemplate = (TH1F*)( h_template->Clone(name.c_str()) ); + h_convolutedTemplate -> Reset(); + + for(int bin = 1; bin <= h_Las->GetNbinsX(); ++bin) + { + float scale = h_Las->GetBinCenter(bin); + float weight = h_Las->GetBinContent(bin); + + if( weight > 0. ) + { + f_template -> SetParameter(0,weight); + f_template -> SetParameter(1,1./scale); + + for(int bin2 = 1; bin2 <= h_convolutedTemplate->GetNbinsX(); ++bin2) + { + float binCenter = h_convolutedTemplate -> GetBinCenter(bin2); + h_convolutedTemplate -> Fill(binCenter,f_template->Eval(binCenter)); + } + } + } + + h_convolutedTemplate -> Scale(h_template->Integral()/h_convolutedTemplate->Integral()); + + return h_convolutedTemplate; +} diff --git a/EcalAlCaRecoProducers/config/reRecoTags/Run2015B_WF2_ICtransp2012_v5.py b/EcalAlCaRecoProducers/config/reRecoTags/Run2015B_WF2_ICtransp2012_v5.py new file mode 100644 index 00000000000..0f607d5be42 --- /dev/null +++ b/EcalAlCaRecoProducers/config/reRecoTags/Run2015B_WF2_ICtransp2012_v5.py @@ -0,0 +1,17 @@ +import FWCore.ParameterSet.Config as cms +from CondCore.DBCommon.CondDBSetup_cfi import * + +# rereco of cycle Run2015B_WF2 +# other infos + +RerecoGlobalTag = cms.ESSource("PoolDBESSource", + CondDBSetup, + connect = cms.string('frontier://FrontierProd/CMS_CONDITIONS'), + globaltag = cms.string('74X_dataRun2_Prompt_v0'), + toGet = cms.VPSet( + cms.PSet(record = cms.string("EcalIntercalibConstantsRcd"), + tag = cms.string("EcalIntercalibConstants_transport2012to2015_V5"), + connect = cms.untracked.string("sqlite_file:/afs/cern.ch/cms/CAF/CMSALCA/ALCA_ECALCALIB/RunII-IC/Run2015B_WF2/EcalIntercalibConstants_transport2012to2015_V5.db") + ) + ), + ) diff --git a/EcalAlCaRecoProducers/python/ALCARECOEcalCalIsolElectron_Output_cff.py b/EcalAlCaRecoProducers/python/ALCARECOEcalCalIsolElectron_Output_cff.py index e2ddf3be919..e47d73362a4 100644 --- a/EcalAlCaRecoProducers/python/ALCARECOEcalCalIsolElectron_Output_cff.py +++ b/EcalAlCaRecoProducers/python/ALCARECOEcalCalIsolElectron_Output_cff.py @@ -23,7 +23,7 @@ OutALCARECOEcalCalElectron_noDrop = cms.PSet( # put this if you have a filter SelectEvents = cms.untracked.PSet( - SelectEvents = cms.vstring('pathALCARECOEcalCalZElectron', 'pathALCARECOEcalCalWElectron', 'pathALCARECOEcalCalZSCElectron') + SelectEvents = cms.vstring('pathALCARECOEcalCalZElectron', 'pathALCARECOEcalCalWElectron', 'pathALCARECOEcalCalZSCElectron','pathALCARECOEcalCalZElectronStream', 'pathALCARECOEcalCalWElectronStream') ), outputCommands = cms.untracked.vstring( 'keep uint_bunchSpacingProducer_*_*', @@ -64,7 +64,10 @@ 'keep *EcalRecHit*_alCaIsolatedElectrons_*_*', 'keep EcalRecHitsSorted_reducedEcalRecHitsES_*_*', 'keep *EcalRecHit*_*ecalPreshowerRecHit*_*EcalRecHitsES*_*', - + 'keep *CaloCluster*_*particleFlowEGamma*_*EBEEClusters*_*', + 'keep *CaloCluster*_*particleFlowEGamma*_*ESClusters*_*', + 'keep *_hltFixedGridRhoFastjetAllCaloForMuons_*_*', #for electron stream + 'keep *_hltMet_*_*', #for electron stream ) ) @@ -80,6 +83,12 @@ OutALCARECOEcalCalWElectron_noDrop.SelectEvents = cms.untracked.PSet( SelectEvents = cms.vstring('pathALCARECOEcalCalWElectron') ) +OutALCARECOEcalCalWElectronStream=copy.deepcopy(OutALCARECOEcalCalElectron) +OutALCARECOEcalCalWElectronStream_noDrop=copy.deepcopy(OutALCARECOEcalCalElectron_noDrop) +OutALCARECOEcalCalWElectronStream.SelectEvents = cms.untracked.PSet( + SelectEvents = cms.vstring('pathALCARECOEcalCalWElectronStream') ) +OutALCARECOEcalCalWElectronStream_noDrop.SelectEvents = cms.untracked.PSet( + SelectEvents = cms.vstring('pathALCARECOEcalCalWElectronStream') ) OutALCARECOEcalCalZElectron=copy.deepcopy(OutALCARECOEcalCalElectron) OutALCARECOEcalCalZElectron_noDrop=copy.deepcopy(OutALCARECOEcalCalElectron_noDrop) diff --git a/EcalAlCaRecoProducers/python/ALCARECOEcalCalIsolElectron_cff.py b/EcalAlCaRecoProducers/python/ALCARECOEcalCalIsolElectron_cff.py index ead46c318a6..896940cb63e 100644 --- a/EcalAlCaRecoProducers/python/ALCARECOEcalCalIsolElectron_cff.py +++ b/EcalAlCaRecoProducers/python/ALCARECOEcalCalIsolElectron_cff.py @@ -62,6 +62,8 @@ seqALCARECOEcalCalZElectron = cms.Sequence(ZeeSkimFilterSeq * ALCARECOEcalCalElectronSeq) seqALCARECOEcalCalZSCElectron = cms.Sequence(ZSCSkimFilterSeq * ALCARECOEcalCalElectronSeq) seqALCARECOEcalCalWElectron = cms.Sequence(WenuSkimFilterSeq * ALCARECOEcalCalElectronSeq) +seqALCARECOEcalCalZElectronStream = cms.Sequence(ZeeSkimFilterSeqElectronStream * ALCARECOEcalCalElectronSeq) +seqALCARECOEcalCalWElectronStream = cms.Sequence(WenuSkimFilterSeqElectronStream * ALCARECOEcalCalElectronSeq) seqALCARECOEcalCalPhoton = cms.Sequence( alCaIsolatedElectrons + diff --git a/EcalAlCaRecoProducers/python/ALCARECOEcalUncalIsolElectron_Output_cff.py b/EcalAlCaRecoProducers/python/ALCARECOEcalUncalIsolElectron_Output_cff.py index 4ee95ffca23..f431292192f 100644 --- a/EcalAlCaRecoProducers/python/ALCARECOEcalUncalIsolElectron_Output_cff.py +++ b/EcalAlCaRecoProducers/python/ALCARECOEcalUncalIsolElectron_Output_cff.py @@ -20,10 +20,12 @@ 'drop *EcalRecHit*_reducedEcalRecHitsES*_*_*', 'drop *EcalRecHit*_*_*_*', 'keep reco*Clusters_pfElectronTranslator_*_*' + 'keep *_hltFixedGridRhoFastjetAllCaloForMuons_*_*', + 'keep *_hltMet_*_*', ) OutALCARECOEcalUncalElectron.SelectEvents = cms.untracked.PSet( - SelectEvents = cms.vstring('pathALCARECOEcalUncalZElectron', 'pathALCARECOEcalUncalZSCElectron', 'pathALCARECOEcalUncalWElectron') + SelectEvents = cms.vstring('pathALCARECOEcalUncalZElectron', 'pathALCARECOEcalUncalZSCElectron', 'pathALCARECOEcalUncalWElectron', 'pathALCARECOEcalUncalWElectronStream', 'pathALCARECOEcalUncalZElectron') ) diff --git a/EcalAlCaRecoProducers/python/ALCARECOEcalUncalIsolElectron_cff.py b/EcalAlCaRecoProducers/python/ALCARECOEcalUncalIsolElectron_cff.py index 6824c237a8d..e4803000aef 100644 --- a/EcalAlCaRecoProducers/python/ALCARECOEcalUncalIsolElectron_cff.py +++ b/EcalAlCaRecoProducers/python/ALCARECOEcalUncalIsolElectron_cff.py @@ -19,3 +19,5 @@ seqALCARECOEcalUncalZSCElectron = cms.Sequence(ZSCSkimFilterSeq * ALCARECOEcalCalElectronNonECALSeq * ALCARECOEcalUncalElectronECALSeq) seqALCARECOEcalUncalWElectron = cms.Sequence(WenuSkimFilterSeq * ALCARECOEcalCalElectronNonECALSeq * ALCARECOEcalUncalElectronECALSeq) seqALCARECOEcalUncalElectron = cms.Sequence( ALCARECOEcalCalElectronNonECALSeq * ALCARECOEcalUncalElectronECALSeq) +seqALCARECOEcalUncalWElectronStream = cms.Sequence(WenuSkimFilterSeqElectronStream * ALCARECOEcalCalElectronNonECALSeq * ALCARECOEcalUncalElectronECALSeq) +seqALCARECOEcalUncalZElectronStream = cms.Sequence(ZeeSkimFilterSeqElectronStream * ALCARECOEcalCalElectronNonECALSeq * ALCARECOEcalUncalElectronECALSeq) diff --git a/EcalAlCaRecoProducers/python/WZElectronSkims_cff.py b/EcalAlCaRecoProducers/python/WZElectronSkims_cff.py index f1b2b6e6325..c049f88aa0b 100644 --- a/EcalAlCaRecoProducers/python/WZElectronSkims_cff.py +++ b/EcalAlCaRecoProducers/python/WZElectronSkims_cff.py @@ -139,6 +139,31 @@ ) ) + +# This are the cuts at trigger level except ecalIso +PassingVetoIdElectronStream = selectedECALElectrons.clone( + cut = cms.string( + selectedECALElectrons.cut.value() + + " && (gsfTrack.hitPattern().numberOfHits(\'MISSING_INNER_HITS\')<=2)" + " && ((isEB" + " && ( ((pfIsolationVariables().sumChargedHadronPt + max(0.0,pfIsolationVariables().sumNeutralHadronEt + pfIsolationVariables().sumPhotonEt - 0.5 * pfIsolationVariables().sumPUPt))/p4.pt)<0.164369)" + " && (sigmaIetaIeta<0.011100)" +# " && (full5x5_sigmaIetaIeta<0.011100)" #why this one cuts all the events? + " && ( - 0.252044 %f && daughter(1).pt > %f && "+MT+" > %f") % (MET_CUT_MIN, W_ELECTRON_ET_CUT_MIN, MT_CUT_MIN)) ) +WenuSelectorElectronStream = cms.EDProducer("CandViewShallowCloneCombiner", + decay = cms.string("pfMet PassingVetoIdElectronStream"), # charge coniugate states are implied + checkCharge = cms.bool(False), +# cut = cms.string(("daughter(0).pt > %f && daughter(1).pt > %f && "+MT+" > %f") % (MET_CUT_MIN, W_ELECTRON_ET_CUT_MIN, MT_CUT_MIN)) + cut = cms.string(("daughter(1).pt > %f") % (W_ELECTRON_ET_CUT_MIN)) +) + EleSCSelector = cms.EDProducer("CandViewShallowCloneCombiner", decay = cms.string("PassingVetoId eleSC"), @@ -224,11 +266,21 @@ cut = cms.string("40 < mass < 140") ) +EleSCSelectorElectronStream = cms.EDProducer("CandViewShallowCloneCombiner", + decay = cms.string("PassingVetoIdElectronStream eleSC"), + checkCharge = cms.bool(False), + cut = cms.string("40 < mass < 140") + ) + # for filtering events passing at least one of the filters WZSelector = cms.EDProducer("CandViewMerger", src = cms.VInputTag("WenuSelector", "ZeeSelector", "EleSCSelector") ) +WZSelectorElectronStream = cms.EDProducer("CandViewMerger", + src = cms.VInputTag("WenuSelectorElectronStream", "ZeeSelectorElectronStream", "EleSCSelectorElectronStream") + ) + ############################################################ # Filters ############################## @@ -247,6 +299,22 @@ minNumber = cms.uint32(1) ) +WenuFilterElectronStream = cms.EDFilter("CandViewCountFilter", + src = cms.InputTag("WenuSelectorElectronStream"), + minNumber = cms.uint32(1) + ) + +ZeeFilterElectronStream = cms.EDFilter("CandViewCountFilter", + src = cms.InputTag("ZeeSelectorElectronStream"), + minNumber = cms.uint32(1) + ) + +ZSCFilterElectronStream = cms.EDFilter("CandViewCountFilter", + src = cms.InputTag("EleSCSelectorElectronStream"), + minNumber = cms.uint32(1) + ) + + # filter for events passing at least one of the other filters WZFilter = cms.EDFilter("CandViewCountFilter", src = cms.InputTag("WZSelector"), @@ -270,8 +338,20 @@ WenuSkimFilterSeq = cms.Sequence(preFilterSeq * selectorProducerSeq * ~ZeeFilter * ~ZSCFilter * WenuFilter) +### sequences for the electron stream +selectorProducerSeqWElectronStream = cms.Sequence(eleSelSeqElectronStream * (ZeeSelectorElectronStream + WenuSelectorElectronStream + EleSCSelectorElectronStream) * WZSelectorElectronStream) + +selectorProducerSeqZElectronStream = cms.Sequence(eleSelSeqElectronStream * (ZeeSelectorElectronStream)) + +WenuSkimFilterSeqElectronStream = cms.Sequence(preFilterSeq * selectorProducerSeqWElectronStream * ~ZeeFilterElectronStream * ~ZSCFilterElectronStream * + WenuFilterElectronStream) + +ZeeSkimFilterSeqElectronStream = cms.Sequence(preFilterSeq * selectorProducerSeqZElectronStream * + ZeeFilterElectronStream) + checkMCZSeq = cms.Sequence(genEleFromZ * combZ * ZFilterMC) #sequence to check Zskim efficiency respect to the MC checkMCWSeq = cms.Sequence(genEleFromW * genNuFromW * combW * WFilterMC) #sequence to check Wskim efficiency respect to the MC FilterMuSeq = cms.Sequence(muSelSeq * (ZeeSelector + WenuSelector + EleSCSelector) * WZSelector) + diff --git a/EcalAlCaRecoProducers/python/alcaSkimming.py b/EcalAlCaRecoProducers/python/alcaSkimming.py index 9908b55ae55..e362a56f0e6 100644 --- a/EcalAlCaRecoProducers/python/alcaSkimming.py +++ b/EcalAlCaRecoProducers/python/alcaSkimming.py @@ -16,6 +16,11 @@ VarParsing.VarParsing.multiplicity.singleton, # singleton or list VarParsing.VarParsing.varType.int, # string, int, or float "change files path in case of local test: isCrab=0 if you are running it locally with cmsRun") +options.register('MC', + 0, # default Value = falce + VarParsing.VarParsing.multiplicity.singleton, # singleton or list + VarParsing.VarParsing.varType.int, # string, int, or float + "force MC: isMC=1 if you are running on MC") options.register ('type', "ALCARAW", VarParsing.VarParsing.multiplicity.singleton, @@ -61,7 +66,12 @@ VarParsing.VarParsing.multiplicity.singleton, VarParsing.VarParsing.varType.int, "50=50ns, 25=25ns,0=multifit auto,-1=weights") - +options.register('electronStream', + 0, #default value False + VarParsing.VarParsing.multiplicity.singleton, # singleton or list + VarParsing.VarParsing.varType.int, # string, int, or float + "bool: isElectronStream=1 true, isElectronStream=0 false") + ### setup any defaults you want options.output="alcaSkimALCARAW.root" options.secondaryOutput="ntuple.root" @@ -95,7 +105,8 @@ sys.exit(-1) -MC = False # please specify it if starting from AOD +MC = options.MC +#MC = False # please specify it if starting from AOD if(options.type == "ALCARAW"): processName = 'ALCASKIM' elif(options.type == "ALCARERECO"): @@ -105,7 +116,7 @@ MC = True elif(options.type == "ALCARECO"): processName = 'ALCARECO' - MC = False +# MC = False elif(options.type == 'SKIMEFFTEST'): processName = 'SKIMEFFTEST' MC = True @@ -156,6 +167,9 @@ process.load('Calibration.EcalAlCaRecoProducers.ALCARECOEcalUncalIsolElectron_cff') # reduction of recHits process.load('Calibration.EcalAlCaRecoProducers.ALCARECOEcalUncalIsolElectron_Output_cff') +from Calibration.EcalAlCaRecoProducers.ALCARECOEcalCalIsolElectron_cff import * +from Calibration.EcalAlCaRecoProducers.ALCARECOEcalUncalIsolElectron_cff import * + # this module provides: # process.seqALCARECOEcalRecalElectron process.load('Calibration.EcalAlCaRecoProducers.ALCARECOEcalRecalIsolElectron_cff') @@ -298,15 +312,26 @@ process.source.fileNames=[ 'root://cms-xrd-global.cern.ch//store/data/Run2012D/DoubleElectron/AOD/15Apr2014-v1/00000/0EA11D35-0CD5-E311-862E-0025905A6070.root' ] elif(re.match("CMSSW_7_5_.*",CMSSW_VERSION)): if(MC): - print "[INFO] Using GT auto:run2_data" - process.GlobalTag.globaltag = 'auto:run2_data' + print "[INFO] Using GT auto:run2_mc" + from Configuration.AlCa.GlobalTag import GlobalTag + process.GlobalTag = GlobalTag(process.GlobalTag, 'auto:run2_mc', '') else: - process.GlobalTag.globaltag = 'auto:run2_data' - if(options.files==""): + print "[INFO] Using GT auto:run2_data" + from Configuration.AlCa.GlobalTag import GlobalTag + process.GlobalTag = GlobalTag(process.GlobalTag, 'auto:run2_data', '') + if(options.files==""): process.source.fileNames=[ 'root://cms-xrd-global.cern.ch//store/data/Run2012D/DoubleElectron/AOD/15Apr2014-v1/00000/0EA11D35-0CD5-E311-862E-0025905A6070.root' ] - else: - print "[ERROR]::Global Tag not set for CMSSW_VERSION: ", CMSSW_VERSION - sys.exit(1) + else: #assuming a Run2 release + if (MC): + print "[INFO] Using GT auto:run2_mc" + from Configuration.AlCa.GlobalTag import GlobalTag + process.GlobalTag = GlobalTag(process.GlobalTag, 'auto:run2_mc', '') + else: + print "[INFO] Using GT auto:run2_data" + from Configuration.AlCa.GlobalTag import GlobalTag + process.GlobalTag = GlobalTag(process.GlobalTag, 'auto:run2_data', '') + if(options.files==""): + process.source.fileNames=[ 'root://cms-xrd-global.cern.ch//store/data/Run2012D/DoubleElectron/AOD/15Apr2014-v1/00000/0EA11D35-0CD5-E311-862E-0025905A6070.root' ] if(re.match("CMSSW_7_.*",CMSSW_VERSION)): myEleCollection = cms.InputTag("gedGsfElectrons") @@ -375,11 +400,22 @@ process.ZEEHltFilter.HLTPaths = [ "HLT_Ele17_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_Ele8_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_*"] process.filterSeq *= process.ZEEHltFilter + + +##for the stream +process.pathALCARECOEcalCalWElectronStream = cms.Path(seqALCARECOEcalCalWElectronStream) +process.pathALCARECOEcalUncalWElectronStream = cms.Path(seqALCARECOEcalUncalWElectronStream) +process.pathALCARECOEcalCalZElectronStream = cms.Path(seqALCARECOEcalCalZElectronStream) +process.pathALCARECOEcalUncalZElectronStream = cms.Path(seqALCARECOEcalUncalZElectronStream) + + from HLTrigger.HLTfilters.hltHighLevel_cfi import * process.NtupleFilter = copy.deepcopy(hltHighLevel) process.NtupleFilter.throw = cms.bool(False) process.NtupleFilter.HLTPaths = [ 'pathALCARECOEcalUncalZElectron', 'pathALCARECOEcalUncalWElectron', 'pathALCARECOEcalCalZElectron', 'pathALCARECOEcalCalWElectron', + 'pathALCARECOEcalUncalZElectronStream', 'pathALCARECOEcalUncalWElectronStream', + 'pathALCARECOEcalCalZElectronStream', 'pathALCARECOEcalCalWElectronStream', 'pathALCARECOEcalUncalZSCElectron', 'pathALCARECOEcalCalZSCElectron', 'pathALCARECOEcalUncalSingleElectron', 'pathALCARECOEcalCalSingleElectron', ## in case of no skim ] @@ -389,6 +425,8 @@ else: process.NtupleFilter.TriggerResultsTag = cms.InputTag("TriggerResults","","ALCARECO") +if(options.electronStream == 1): + process.NtupleFilter.TriggerResultsTag = cms.InputTag("TriggerResults","","RECO") process.NtupleFilterSeq = cms.Sequence() if(ZSkim): @@ -396,11 +434,13 @@ # process.NtupleFilterSeq= cms.Sequence(process.NtupleFilter) process.NtupleFilter.HLTPaths = [ 'pathALCARECOEcalCalZElectron', 'pathALCARECOEcalUncalZElectron', 'pathALCARECOEcalCalZSCElectron', 'pathALCARECOEcalUncalZSCElectron', + 'pathALCARECOEcalCalZElectronStream', 'pathALCARECOEcalUncalZElectronStream', ] elif(WSkim): process.NtupleFilterSeq = cms.Sequence(process.WZFilter) # process.NtupleFilterSeq= cms.Sequence(process.NtupleFilter) - process.NtupleFilter.HLTPaths = [ 'pathALCARECOEcalCalWElectron', 'pathALCARECOEcalUncalWElectron' ] + process.NtupleFilter.HLTPaths = [ 'pathALCARECOEcalCalWElectron', 'pathALCARECOEcalUncalWElectron', + 'pathALCARECOEcalCalWElectronStream', 'pathALCARECOEcalUncalWElectronStream'] elif(ZmmgSkim): process.NtupleFilterSeq = cms.Sequence(process.ZmmgSkimSeq) process.NtupleFilter.HLTPaths = [ 'pathALCARECOEcalCalZmmgPhoton', 'pathALCARECOEcalUncalZmmgPhoton' ] @@ -426,8 +466,7 @@ #============================== - - + try: EcalTrivialConditionRetriever except NameError: @@ -459,7 +498,7 @@ process.ntupleSeq = cms.Sequence(process.jsonFilter * process.patSequence) else: process.load('PhysicsTools.PatAlgos.slimming.MiniAODfromMiniAOD_cff') - process.ntupleSeq = cms.Sequence(process.jsonFilter * process.EIsequence) + process.ntupleSeq = cms.Sequence(process.jsonFilter * process.eleNewEnergiesProducer * process.EIsequence) if(options.doTree==2 or options.doTree==4 or options.doTree==6 or options.doTree==8): process.zNtupleDumper.doStandardTree = cms.bool(False) @@ -694,17 +733,17 @@ ############################## if(options.skim=='WSkim'): process.outputALCARAW.SelectEvents = cms.untracked.PSet( - SelectEvents = cms.vstring('pathALCARECOEcalUncalWElectron') + SelectEvents = cms.vstring('pathALCARECOEcalUncalWElectron','pathALCARECOEcalUncalWElectronStream') ) process.outputALCARECO.SelectEvents = cms.untracked.PSet( - SelectEvents = cms.vstring('pathALCARECOEcalCalWElectron') + SelectEvents = cms.vstring('pathALCARECOEcalCalWElectron','pathALCARECOEcalCalWElectronStream') ) elif(options.skim=='ZSkim'): process.outputALCARAW.SelectEvents = cms.untracked.PSet( - SelectEvents = cms.vstring('pathALCARECOEcalUncalZElectron', 'pathALCARECOEcalUncalZSCElectron') + SelectEvents = cms.vstring('pathALCARECOEcalUncalZElectron', 'pathALCARECOEcalUncalZSCElectron','pathALCARECOEcalUncalZElectronStream') ) process.outputALCARECO.SelectEvents = cms.untracked.PSet( - SelectEvents = cms.vstring('pathALCARECOEcalCalZElectron', 'pathALCARECOEcalCalZSCElectron') + SelectEvents = cms.vstring('pathALCARECOEcalCalZElectron', 'pathALCARECOEcalCalZSCElectron','pathALCARECOEcalUncalZElectronStream') ) elif(options.skim=='ZmmgSkim'): process.outputALCARAW.SelectEvents = cms.untracked.PSet( @@ -750,6 +789,8 @@ process.NtuplePath = cms.Path(process.pdfWeightsSeq * process.ntupleSeq) process.schedule = cms.Schedule(process.NtuplePath, process.NtupleEndPath) process.zNtupleDumper.WZSkimResultsCollection = cms.InputTag('TriggerResults::ALCARECO') + if (options.electronStream==1): + process.zNtupleDumper.WZSkimResultsCollection = cms.InputTag('TriggerResults::RECO') else: if(options.doTree==0): process.schedule = cms.Schedule(process.pathALCARECOEcalCalZElectron, process.pathALCARECOEcalCalWElectron, @@ -823,11 +864,26 @@ if(options.type!="MINIAODNTUPLE"): process.eleNewEnergiesProducer.recHitCollectionEB = cms.InputTag("alCaIsolatedElectrons", "alcaBarrelHits") process.eleNewEnergiesProducer.recHitCollectionEE = cms.InputTag("alCaIsolatedElectrons", "alcaEndcapHits") + #configure everything for MINIAOD + process.eleNewEnergiesProducer.electronCollection = cms.InputTag("patElectrons","","@skipCurrentProcess") + process.eleNewEnergiesProducer.photonCollection = cms.InputTag("patPhotons","","@skipCurrentProcess") + else: - process.eleNewEnergiesProducer.recHitCollectionEB = cms.InputTag("reducedEgamma", "reducedEBRecHits") - process.eleNewEnergiesProducer.recHitCollectionEE = cms.InputTag("reducedEgamma", "reducedEERecHits") - process.eleNewEnergiesProducer.recHitCollectionES = cms.InputTag("reducedEgamma", "reducedESRecHits") + #configure everything for MINIAOD + process.eleNewEnergiesProducer.scEnergyCorrectorSemiParm.ecalRecHitsEB = cms.InputTag("reducedEgamma", "reducedEBRecHits") + process.eleNewEnergiesProducer.scEnergyCorrectorSemiParm.ecalRecHitsEE = cms.InputTag("reducedEgamma", "reducedEERecHits") + process.eleNewEnergiesProducer.scEnergyCorrectorSemiParm.vertexCollection = cms.InputTag('offlineSlimmedPrimaryVertices') + process.eleNewEnergiesProducer.electronCollection = cms.InputTag("slimmedElectrons","","@skipCurrentProcess") + process.eleNewEnergiesProducer.photonCollection = cms.InputTag("slimmedPhotons","","@skipCurrentProcess") + + # load new energies in the slimmedElectrons process + from Calibration.ZNtupleDumper.miniAODnewEnergies import * + process.slimmedElectrons.modifierConfig.modifications=electron_energy_modifications + process.zNtupleDumper.useIDforPresel = cms.bool(False) + process.zNtupleDumper.recHitCollectionEB = cms.InputTag("reducedEgamma", "reducedEBRecHits") + process.zNtupleDumper.recHitCollectionEE = cms.InputTag("reducedEgamma", "reducedEERecHits") + process.zNtupleDumper.recHitCollectionES = cms.InputTag("reducedEgamma", "reducedESRecHits") process.zNtupleDumper.rhoFastJet = cms.InputTag("fixedGridRhoFastjetAll") process.zNtupleDumper.pileupInfo = cms.InputTag("slimmedAddPileupInfo") process.zNtupleDumper.vertexCollection = cms.InputTag('offlineSlimmedPrimaryVertices') @@ -839,8 +895,6 @@ process.zNtupleDumper.eleID_medium = cms.string("cutBasedElectronID-Spring15-25ns-V1-standalone-medium") process.zNtupleDumper.eleID_tight = cms.string("cutBasedElectronID-Spring15-25ns-V1-standalone-tight") -process.eleNewEnergiesProducer.electronCollection = myEleCollection - if(options.type=="ALCARERECO"): recalibElectronSrc = cms.InputTag("electronRecalibSCAssociator") #now done by EcalRecal(process) process = EcalRecal(process) @@ -849,13 +903,13 @@ process.eleSelectionProducers.chIsoVals = cms.InputTag('elPFIsoValueCharged03PFIdRecalib') process.eleSelectionProducers.emIsoVals = cms.InputTag('elPFIsoValueGamma03PFIdRecalib') process.eleSelectionProducers.nhIsoVals = cms.InputTag('elPFIsoValueNeutral03PFIdRecalib') - process.eleNewEnergiesProducer.electronCollection = recalibElectronSrc + #process.eleNewEnergiesProducer.electronCollection = recalibElectronSrc process.outputALCARECO.outputCommands += process.OutALCARECOEcalRecalElectron.outputCommands process.outputALCARECO.fileName=cms.untracked.string('EcalRecalElectron.root') process.MinEleNumberFilter.src = recalibElectronSrc process.zNtupleDumper.WZSkimResultsCollection = cms.InputTag('TriggerResults::RECO') ## how and why and where is it used? - process.eleNewEnergiesProducer.electronCollection = recalibElectronSrc + #process.eleNewEnergiesProducer.electronCollection = recalibElectronSrc if(options.bunchSpacing==25): print "bunchSpacing", options.bunchSpacing @@ -879,8 +933,14 @@ process.patElectrons.reducedBarrelRecHitCollection = process.eleNewEnergiesProducer.recHitCollectionEB process.patElectrons.reducedEndcapRecHitCollection = process.eleNewEnergiesProducer.recHitCollectionEE -process.zNtupleDumper.recHitCollectionEB = process.eleNewEnergiesProducer.recHitCollectionEB -process.zNtupleDumper.recHitCollectionEE = process.eleNewEnergiesProducer.recHitCollectionEE +#process.zNtupleDumper.recHitCollectionEB = process.eleNewEnergiesProducer.recHitCollectionEB +#process.zNtupleDumper.recHitCollectionEE = process.eleNewEnergiesProducer.recHitCollectionEE + +if (options.electronStream==1): + process.zNtupleDumper.caloMetCollection = cms.InputTag('hltMet') + process.zNtupleDumper.rhoFastJet = cms.InputTag('hltFixedGridRhoFastjetAllCaloForMuons') + process.zNtupleDumper.electronStream = cms.bool(True) + process.eleSelectionProducers.rhoFastJet = cms.InputTag('hltFixedGridRhoFastjetAllCaloForMuons') if(options.type=="ALCARECOSIM"): process.zNtupleDumper.recHitCollectionES = cms.InputTag("reducedEcalRecHitsES") diff --git a/EcalAlCaRecoProducers/scripts/prodNtuples.sh b/EcalAlCaRecoProducers/scripts/prodNtuples.sh index ddcda027aae..cc795dc3948 100755 --- a/EcalAlCaRecoProducers/scripts/prodNtuples.sh +++ b/EcalAlCaRecoProducers/scripts/prodNtuples.sh @@ -126,13 +126,13 @@ do MINIAOD| miniAOD) TYPE=MINIAODNTUPLE if [ "${isMC}" == "1" ]; then - TYPE=MINIAODNTUPLE; + TYPE=MINIAODMCNTUPLE; else TYPE=MINIAODNTUPLE fi ;; miniAODSIM) - TYPE=MINIAODNTUPLE + TYPE=MINIAODMCNTUPLE isMC=1 ;; alcarereco | ALCARERECO) @@ -400,6 +400,17 @@ jobtype=cmssw EOF case ${ORIGIN_REMOTE_DIR_BASE} in database) + case $DATASETPATH in + *USER) + if [ -z ${DBS_URL} ];then + DBS_URL=phys03 + fi + ;; + esac + if [ -n "${DBS_URL}" ];then + echo "dbs_url=${DBS_URL}" >> ${crabFile} + fi + if [ "$isMC" != "1" ];then cat >> ${crabFile} < >') handleRecHitsEE_ALCARECO = Handle('edm::SortedCollection >') +handleMET = Handle('std::vector') + if (file_format == 'ALCARECO'): processName="ALCASKIM" electronTAG = 'electronRecalibSCAssociator' @@ -193,7 +195,7 @@ electronTAG = 'electronRecalibSCAssociator' - +metTAG = 'hltMet' EErecHitmap_ele1 = TH2F("EErecHitmap_ele1", "EErecHitmap_ele1", 100,0,100, @@ -230,6 +232,9 @@ # print file_format, file, electronTAG electrons = handleElectrons.product() + event.getByLabel(metTAG, handleMET) + met = handleMET.product() + # event.getByLabel("reducedEcalRecHitsEB", "", processName, handleRecHitsEB) # event.getByLabel("reducedEcalRecHitsEE", "", processName, handleRecHitsEE) if(file_format=="sandbox"): diff --git a/EcalAlCaRecoProducers/test/reco_RAW2DIGI_RECO_alcastreamElectron.py b/EcalAlCaRecoProducers/test/reco_RAW2DIGI_RECO_alcastreamElectron.py new file mode 100644 index 00000000000..83c3b0f54f8 --- /dev/null +++ b/EcalAlCaRecoProducers/test/reco_RAW2DIGI_RECO_alcastreamElectron.py @@ -0,0 +1,133 @@ +# Auto generated configuration file +# using: +# Revision: 1.19 +# Source: /local/reps/CMSSW/CMSSW/Configuration/Applications/python/ConfigBuilder.py,v +# with command line options: reco -s RAW2DIGI,RECO -n 100 --filein=/store/data/Run2012D/SingleElectron/RAW/v1/000/208/307/0085A34B-BD3A-E211-B6E9-003048D2BC4C.root --data --conditions=auto:run2_data --nThreads=4 --dirout=./ +import FWCore.ParameterSet.Config as cms +import os, sys, imp, re +import FWCore.ParameterSet.VarParsing as VarParsing +import subprocess +import copy + + +process = cms.Process('RECO') + +# import of standard configurations +process.load('Configuration.StandardSequences.Services_cff') +process.load('SimGeneral.HepPDTESSource.pythiapdt_cfi') +process.load('FWCore.MessageService.MessageLogger_cfi') +process.load('Configuration.EventContent.EventContent_cff') +process.load('Configuration.StandardSequences.GeometryRecoDB_cff') +process.load('Configuration.StandardSequences.MagneticField_AutoFromDBCurrent_cff') +process.load('Configuration.StandardSequences.RawToDigi_Data_cff') +process.load('Configuration.StandardSequences.Reconstruction_Data_cff') +process.load('Configuration.StandardSequences.EndOfProcess_cff') +process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_condDBv2_cff') + +options = VarParsing.VarParsing('standard') + +options.register ('tagFile', + "", + VarParsing.VarParsing.multiplicity.singleton, + VarParsing.VarParsing.varType.string, + "path of the file with the reReco tags") + +options.parseArguments() + +print options + +process.maxEvents = cms.untracked.PSet( + input = cms.untracked.int32(100) +) + +# Input source +process.source = cms.Source("PoolSource", + fileNames = cms.untracked.vstring('/store/data/Run2015D/AlCaElectron/RAW/v1/000/256/673/00000/5AD13995-DF5C-E511-8DDB-02163E013516.root'), +# fileNames = cms.untracked.vstring('root://xrootd.unl.edu//store/data/Run2015C/AlCaElectron/RAW/v1/000/254/313/00000/88935D49-C842-E511-BA1F-02163E014330.root'), + secondaryFileNames = cms.untracked.vstring() +) + +process.options = cms.untracked.PSet( + +) + +# Production Info +process.configurationMetadata = cms.untracked.PSet( + annotation = cms.untracked.string('reco nevts:100'), + name = cms.untracked.string('Applications'), + version = cms.untracked.string('$Revision: 1.19 $') +) + +# Output definition + +process.RECOSIMoutput = cms.OutputModule("PoolOutputModule", + dataset = cms.untracked.PSet( + dataTier = cms.untracked.string(''), + filterName = cms.untracked.string('') + ), + eventAutoFlushCompressedSize = cms.untracked.int32(5242880), + fileName = cms.untracked.string('./reco_RAW2DIGI_RECO.root'), + outputCommands = process.RECOSIMEventContent.outputCommands, + splitLevel = cms.untracked.int32(0) +) + +# Additional output definition + +# Other statements +from Configuration.AlCa.GlobalTag_condDBv2 import GlobalTag + +if(len(options.tagFile)>0): + execfile(options.tagFile) # load the GT + process.GlobalTag = RerecoGlobalTag +else: + print "******************************" + print "[ERROR] no file with tags specified" + sys.exit(1) + +#process.GlobalTag = GlobalTag(process.GlobalTag, '74X_dataRun2_Prompt_v1', '') + +# Path and EndPath definitions +process.raw2digi_step = cms.Path(process.RawToDigi) +process.reconstruction_step = cms.Path(process.reconstruction) +process.endjob_step = cms.EndPath(process.endOfProcess) +process.RECOSIMoutput_step = cms.EndPath(process.RECOSIMoutput) + +### some fix for the stream +process.csctfDigis.producer = cms.InputTag("hltSelectedElectronFEDListProducerGsf:StreamElectronRawFed") + +process.dttfDigis.DTTF_FED_Source = cms.InputTag("hltSelectedElectronFEDListProducerGsf:StreamElectronRawFed") + +process.ecalDigis.InputLabel = cms.InputTag("hltSelectedElectronFEDListProducerGsf:StreamElectronRawFed") + +process.ecalPreshowerDigis.sourceTag = cms.InputTag("hltSelectedElectronFEDListProducerGsf:StreamElectronRawFed") + +process.castorDigis.InputLabel = cms.InputTag("hltSelectedElectronFEDListProducerGsf:StreamElectronRawFed") + +process.gctDigis.inputLabel = cms.InputTag("hltSelectedElectronFEDListProducerGsf:StreamElectronRawFed") + +process.gtDigis.DaqGtInputTag = cms.InputTag("hltSelectedElectronFEDListProducerGsf:StreamElectronRawFed") + +process.gtEvmDigis.EvmGtInputTag = cms.InputTag("hltSelectedElectronFEDListProducerGsf:StreamElectronRawFed") + +process.hcalDigis.InputLabel = cms.InputTag("hltSelectedElectronFEDListProducerGsf:StreamElectronRawFed") + +process.muonCSCDigis.InputObjects = cms.InputTag("hltSelectedElectronFEDListProducerGsf:StreamElectronRawFed") + +process.muonDTDigis.inputLabel = cms.InputTag("hltSelectedElectronFEDListProducerGsf:StreamElectronRawFed") + +process.muonRPCDigis.InputLabel = cms.InputTag("hltSelectedElectronFEDListProducerGsf:StreamElectronRawFed") + +process.scalersRawToDigi.scalersInputTag = cms.InputTag("hltSelectedElectronFEDListProducerGsf:StreamElectronRawFed") + +process.siPixelDigis.InputLabel = cms.InputTag("hltSelectedElectronFEDListProducerGsf:StreamElectronRawFed") + +process.siStripDigis.ProductLabel = cms.InputTag("hltSelectedElectronFEDListProducerGsf:StreamElectronRawFed") + +# Schedule definition +process.schedule = cms.Schedule(process.raw2digi_step,process.reconstruction_step,process.endjob_step,process.RECOSIMoutput_step) + +#Setup FWK for multithreaded +process.options.numberOfThreads=cms.untracked.uint32(4) +process.options.numberOfStreams=cms.untracked.uint32(0) + + diff --git a/EcalAlCaRecoProducers/test/run_alcareco_alcastreamElectron.py b/EcalAlCaRecoProducers/test/run_alcareco_alcastreamElectron.py new file mode 100644 index 00000000000..9b44ee59587 --- /dev/null +++ b/EcalAlCaRecoProducers/test/run_alcareco_alcastreamElectron.py @@ -0,0 +1,29 @@ +from WMCore.Configuration import Configuration +config = Configuration() +config.section_('General') +config.General.transferOutputs = True +config.General.requestName = 'AlCaElectron_alcareco_RUN2015D' +config.General.workArea = 'AlCaElectron_alcareco_RUN2015D' +config.section_('JobType') +config.JobType.psetName = 'reco_ALCA.py' +config.JobType.pluginName = 'Analysis' +#config.JobType.pyCfgParams = ['global_tag=74X_dataRun2_Prompt_v1', 'MC=False', 'isCrab=True'] +config.JobType.allowUndistributedCMSSW = True +#config.JobType.inputFiles = ['PHYS14_25_V2_All_L1FastJet_AK8PFchs.txt','PHYS14_25_V2_All_L2Relative_AK8PFchs.txt','PHYS14_25_V2_All_L3Absolute_AK8PFchs.txt','PHYS14_25_V2_All_L1FastJet_AK4PFchs.txt','PHYS14_25_V2_All_L2Relative_AK4PFchs.txt','PHYS14_25_V2_All_L3Absolute_AK4PFchs.txt' ] +config.section_('Data') +config.Data.inputDataset = '/AlCaElectron/lbrianza-crab_reco_stream_runD-00000000000000000000000000000000/USER' +config.Data.unitsPerJob = 1 +config.Data.lumiMask = '/afs/cern.ch/cms/CAF/CMSCOMM/COMM_DQM/certification/Collisions15/13TeV/Cert_246908-260627_13TeV_PromptReco_Collisions15_25ns_JSON_Silver.txt' +config.JobType.maxMemoryMB = 2500 # 2.5 GB +config.JobType.maxJobRuntimeMin = 1400 +#config.Data.lumiMask = 'Cert_246908-251883_13TeV_PromptReco_Collisions15_JSON_v2.txt' +config.Data.inputDBS = 'phys03' #'http://cmsdbsprod.cern.ch/cms_dbs_prod_global/servlet/DBSServlet' +config.Data.splitting = 'FileBased' +config.Data.outLFNDirBase = '/store/group/dpg_ecal/alca_ecalcalib/ecalMIBI/lbrianza/AlCaElectron_alcareco_RUN2015D/' +config.Data.useParent = True +config.Data.publication = True +#config.Data.ignoreLocality = True +config.section_('User') +config.section_('Site') +config.Site.storageSite = 'T2_CH_CERN' +#config.Site.whitelist = ['T2_US_Caltech', 'T2_US_Florida', 'T2_US_MIT', 'T2_US_Nebraska', 'T2_US_Purdue', 'T2_US_UCSD', 'T2_US_Vanderbilt'] diff --git a/EcalAlCaRecoProducers/test/run_ntuple_alcastreamElectron.py b/EcalAlCaRecoProducers/test/run_ntuple_alcastreamElectron.py new file mode 100644 index 00000000000..47f4a8049b6 --- /dev/null +++ b/EcalAlCaRecoProducers/test/run_ntuple_alcastreamElectron.py @@ -0,0 +1,27 @@ +from WMCore.Configuration import Configuration +config = Configuration() +config.section_('General') +config.General.transferOutputs = True +config.General.requestName = 'ntuple_AlCaElectron_RUN2015D' +config.General.workArea = 'ntuple_AlCaElectron_RUN2015D' +config.section_('JobType') +config.JobType.psetName = 'EcalAlCaRecoProducers/python/alcaSkimming.py' +#config.JobType.psetName = 'processDump.py' +config.JobType.pluginName = 'Analysis' +config.JobType.outputFiles= ['ntuple.root','extraCalibTree.root'] +config.JobType.pyCfgParams = ['isCrab=1', 'skim=WSkim', 'maxEvents=-1', 'type=ALCARECO', 'tagFile=EcalAlCaRecoProducers/config/reRecoTags/test75x.py','doTreeOnly=1', 'electronStream=1','doTree=3'] +config.JobType.allowUndistributedCMSSW = True +#config.JobType.inputFiles = ['PHYS14_25_V2_All_L1FastJet_AK8PFchs.txt','PHYS14_25_V2_All_L2Relative_AK8PFchs.txt','PHYS14_25_V2_All_L3Absolute_AK8PFchs.txt','PHYS14_25_V2_All_L1FastJet_AK4PFchs.txt','PHYS14_25_V2_All_L2Relative_AK4PFchs.txt','PHYS14_25_V2_All_L3Absolute_AK4PFchs.txt' ] +config.section_('Data') +#config.Data.inputDataset = '/AlCaElectron/lbrianza-crab_alcareco_stream_runC-e468ed1ee444b924f5c474c9b5bffcd2/USER' +config.Data.inputDataset = '/AlCaElectron/lbrianza-crab_AlCaElectron_alcareco_RUN2015D-c2f08da413a109f58849306beef921b4/USER' +config.Data.unitsPerJob = 10 +config.Data.lumiMask = '/afs/cern.ch/cms/CAF/CMSCOMM/COMM_DQM/certification/Collisions15/13TeV/Cert_246908-260627_13TeV_PromptReco_Collisions15_25ns_JSON_Silver.txt' +config.Data.inputDBS = 'phys03' #'http://cmsdbsprod.cern.ch/cms_dbs_prod_global/servlet/DBSServlet' +config.Data.splitting = 'FileBased' +config.Data.outLFNDirBase = '/store/group/dpg_ecal/alca_ecalcalib/ecalMIBI/lbrianza/ntuple_AlCaElectron_RUN2015D/' +#config.Data.useParent = True +#config.Data.publication = True +config.section_('User') +config.section_('Site') +config.Site.storageSite = 'T2_CH_CERN' diff --git a/EcalAlCaRecoProducers/test/run_reco_alcastreamElectron_crab.py b/EcalAlCaRecoProducers/test/run_reco_alcastreamElectron_crab.py new file mode 100644 index 00000000000..3853e3988d7 --- /dev/null +++ b/EcalAlCaRecoProducers/test/run_reco_alcastreamElectron_crab.py @@ -0,0 +1,25 @@ +from WMCore.Configuration import Configuration +config = Configuration() +config.section_('General') +config.General.transferOutputs = True +config.General.requestName = 'reco_stream_runD' +config.General.workArea = 'reco_stream_runD' +config.section_('JobType') +config.JobType.psetName = 'python/reco_RAW2DIGI_RECO_alcastreamElectron.py' +config.JobType.pluginName = 'Analysis' +#config.JobType.pyCfgParams = ['global_tag=74X_dataRun2_Prompt_v1', 'MC=False', 'isCrab=True'] +config.JobType.allowUndistributedCMSSW = True +#config.JobType.inputFiles = ['PHYS14_25_V2_All_L1FastJet_AK8PFchs.txt','PHYS14_25_V2_All_L2Relative_AK8PFchs.txt','PHYS14_25_V2_All_L3Absolute_AK8PFchs.txt','PHYS14_25_V2_All_L1FastJet_AK4PFchs.txt','PHYS14_25_V2_All_L2Relative_AK4PFchs.txt','PHYS14_25_V2_All_L3Absolute_AK4PFchs.txt' ] +config.section_('Data') +#config.Data.inputDataset = '/ElectronStream/Run2015B-v1/RAW' +config.Data.inputDataset = '/AlCaElectron/Run2015D-v1/RAW' +config.Data.unitsPerJob = 10 +#config.Data.lumiMask = 'json/Cert_246908-251883_13TeV_PromptReco_Collisions15_JSON_v2.txt' +config.Data.inputDBS = 'global' #'http://cmsdbsprod.cern.ch/cms_dbs_prod_global/servlet/DBSServlet' +config.Data.splitting = 'LumiBased' +config.Data.outLFNDirBase = '/store/group/dpg_ecal/alca_ecalcalib/ecalMIBI/lbrianza/AlCaElectron-Run2015D-v1-RECO/' +config.Data.publication = True +config.section_('User') +config.section_('Site') +config.Site.storageSite = 'T2_CH_CERN' +config.Site.whitelist = ['T2_CH_CERN'] diff --git a/ZFitter/bin/ZFitter.cpp b/ZFitter/bin/ZFitter.cpp index 55cadf15941..7997672f043 100644 --- a/ZFitter/bin/ZFitter.cpp +++ b/ZFitter/bin/ZFitter.cpp @@ -5,26 +5,49 @@ The aim of the program is to provide a common interface to all the Z fitting algorithms reading and combining in the proper way the configuration files. - \todo +\todo - remove commonCut from category name and add it in the ZFit_class in order to not repeate the cut - make alpha fitting more generic (look for alphaName) - Implement the iterative Et dependent scale corrections */ - -#include + #include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include #include -#include #include #include +#include #include #include #include +#include +#include #include #include +#include "TROOT.h" +#include "TSystem.h" +#include "TStyle.h" +#include "TFile.h" +#include "TCanvas.h" +#include "TGraphErrors.h" +#include "TGraphAsymmErrors.h" +#include "TPaveStats.h" +#include "TLegend.h" +#include "TChain.h" +#include "TVirtualFitter.h" +#include "TLatex.h" + /// @cond SHOW /// \code @@ -45,6 +68,17 @@ configuration files. #include "../../EOverPCalibration/interface/CalibrationUtils.h" #include "../../EOverPCalibration/interface/FastCalibratorEB.h" #include "../../EOverPCalibration/interface/FastCalibratorEE.h" +#include "../../EOverPCalibration/interface/LaserMonitoringEoP.h" + +#include "../../EOverPCalibration/interface/TEndcapRings.h" +#include "../../EOverPCalibration/CommonTools/histoFunc.h" +//#include "treeReader.h" +//#include "setTDRStyle.h" +#include "../../EOverPCalibration/interface/ntpleUtils2.h" +#include "../../EOverPCalibration/interface/ConvoluteTemplate.h" +#include "../../EOverPCalibration/interface/stabilityUtils.h" +#include "../../EOverPCalibration/interface/geometryUtils.h" + /// \endcode /// @endcond @@ -168,7 +202,7 @@ void Dump(tag_chain_map_t& tagChainMap, TString tag="s", Long64_t firstentry=0){ /** * \param tagChainMap map of all the tags declared in the validation config file * \param tag name of the new \b tag created by the function, all the existent tags with name starting with -b tag are merged in the new \b tag + b tag are merged in the new \b tag * * A new tagChain with name=tag is added to the tagChainMap. All the tagChains with tag starting with \b tag are merged * After the merging the friend list is updated by \ref UpdateFriends @@ -182,10 +216,10 @@ void MergeSamples(tag_chain_map_t& tagChainMap, TString regionsFileNameTag, TStr for(tag_chain_map_t::const_iterator tag_chain_itr=tagChainMap.begin(); tag_chain_itr!=tagChainMap.end(); tag_chain_itr++){ - + // consider tags matching the tag input parameter if(tag_chain_itr->first.CompareTo(tag)==0 || !tag_chain_itr->first.Contains(tag)) continue; //do it for each sample - + // loop over all the trees for(chain_map_t::const_iterator chain_itr=tag_chain_itr->second.begin(); chain_itr!=tag_chain_itr->second.end(); @@ -252,7 +286,6 @@ TString energyBranchNameFromInvMassName(TString invMass_var){ return TString( (energyBranchNameFromInvMassName(std::string(invMass_var))).c_str()); } - int main(int argc, char **argv) { TStopwatch myClock; TStopwatch globalClock; @@ -298,10 +331,16 @@ int main(int argc, char **argv) { std::string minimType; std::vector branchList; + + + + //options for E/p std::string jsonFileName; std::string miscalibMap; bool isMiscalib; + bool applyPcorr; + bool applyEcorr; bool isSaveEPDistribution; bool isMCTruth; bool isEPselection; @@ -311,20 +350,35 @@ int main(int argc, char **argv) { float fbremMax; bool isR9selection; float R9Min; + float EPMin; + int smoothCut; int miscalibMethod; std::string inputMomentumScale; + std::string inputEnergyScale; std::string typeEB; std::string typeEE; std::string outputPath; std::string outputFile; int numberOfEvents; int useZ, useW; - int isBarrel; + int useRawEnergy; + // int isBarrel; int splitStat; int nLoops; bool isDeadTriggerTower; std::string inputFileDeadXtal; - + std::string EBEE; + std::string EBEEpu; + int evtsPerPoint; + + int useRegression; + float yMIN; + float yMAX; + std::string dayMin; + std::string dayMax; + std::string dayZOOM; + std::string LUMI; + int EoPvsPU; //------------------------------ setting option categories po::options_description desc("Main options"); po::options_description outputOption("Output options"); @@ -333,6 +387,9 @@ int main(int argc, char **argv) { po::options_description smearerOption("Z smearer options"); po::options_description toyOption("toyMC options"); po::options_description EoverPOption("EoverP options"); + po::options_description laserMonitoringEPOption("laser monitoring with E/p options"); + + //po::options_description cmd_line_options; //cmd_line_options.add(desc).add(fitOption).add(smearOption); @@ -438,12 +495,25 @@ int main(int argc, char **argv) { ("constTermToy", po::value(&constTermToy)->default_value(0.01),"") ("eventsPerToy", po::value(&nEventsPerToy)->default_value(0),"=0: all events") ; + laserMonitoringEPOption.add_options() + ("laserMonitoringEP", "call the laser monitoring with E/p") + ("yMIN", po::value(&yMIN)->default_value(0.65),"y min") + ("yMAX", po::value(&yMAX)->default_value(1.05),"y max") + ("EBEE", po::value(&EBEE)->default_value("EB"),"barrel or endcap") + ("evtsPerPoint", po::value(&evtsPerPoint)->default_value(1000),"events per point") + ("useRegression", po::value(&useRegression)->default_value(0),"use regression") + ("dayMin", po::value(&dayMin)->default_value("1-7-2015"),"day min") + ("dayMax", po::value(&dayMax)->default_value("15-11-2015"),"day max") + ("dayZOOM", po::value(&dayZOOM)->default_value("10-8-2015"),"day ZOOM") + ("LUMI", po::value(&LUMI)->default_value("1.9"),"LUMI") + ("EoPvsPU", po::value(&EoPvsPU)->default_value(0),"EoPvsPU") + ; EoverPOption.add_options() ("EOverPCalib", "call the E/p calibration") - ("isBarrel", po::value(&isBarrel)->default_value(1),"1=barrel, 0=endcap") + // ("isBarrel", po::value(&isBarrel)->default_value(1),"1=barrel, 0=endcap") ("doEB", "do EoP IC calibration for EB") ("doEE", "do EoP IC calibration for EE") - ("jsonFileName", po::value(&jsonFileName)->default_value("../EOverPCalibration/json/Cert_190456-208686_8TeV_PromptReco_Collisions12_JSON.txt"), "jsonFileName") + ("jsonFileName", po::value(&jsonFileName)->default_value("/afs/cern.ch/cms/CAF/CMSCOMM/COMM_DQM/certification/Collisions15/13TeV/Cert_246908-258750_13TeV_PromptReco_Collisions15_25ns_JSON.txt"), "jsonFileName") ("isMiscalib", po::value(&isMiscalib)->default_value(false),"apply the initial miscalibration") ("miscalibMethod", po::value(&miscalibMethod)->default_value(1),"miscalibration method") ("miscalibMap", po::value(&miscalibMap)->default_value("/gwteray/users/brianza/scalibMap2.txt"), "map for the miscalibration") @@ -456,27 +526,34 @@ int main(int argc, char **argv) { ("fbremMax", po::value(&fbremMax)->default_value(100.),"fbrem treshold") ("isR9selection", po::value(&isR9selection)->default_value(false),"apply R9 selection") ("R9Min", po::value(&R9Min)->default_value(-1.),"R9 treshold") - ("inputMomentumScale", po::value(&inputMomentumScale)->default_value("/afs/cern.ch/cms/CAF/CMSALCA/ALCA_ECALCALIB/ECALELF/EOverPCalibration/MomentumCalibration2012"),"input momentum scale") + ("applyPcorr", po::value(&applyPcorr)->default_value(true),"apply momentum correction") + ("inputMomentumScale", po::value(&inputMomentumScale)->default_value("/afs/cern.ch/user/l/lbrianza/work/public/EoP_additionalFiles/MomentumCalibration2015_eta1_eta1.root"),"input momentum scale") + ("applyEcorr", po::value(&applyEcorr)->default_value(false),"apply energy correction") + ("inputEnergyScale", po::value(&inputEnergyScale)->default_value("/afs/cern.ch/user/l/lbrianza/work/public/EoP_additionalFiles/momentumCalibration2015_EB_scE.root"),"input energy scale") ("typeEB", po::value(&typeEB)->default_value("eta1"),"") ("typeEE", po::value(&typeEE)->default_value("eta1"),"") ("outputPath", po::value(&outputPath)->default_value("output/output_runD/"),"output dir for E/P calibration") - ("outputFile", po::value(&outputFile)->default_value("FastCalibrator_Oct22_Run2012ABC_Cal_Dic2012"),"output file for E/P calibration") + ("outputFile", po::value(&outputFile)->default_value("FastCalibrator_Oct2015_runD"),"output file for E/P calibration") ("numberOfEvents", po::value(&numberOfEvents)->default_value(-1),"number of events (-1=all)") + ("useRawEnergy", po::value(&useRawEnergy)->default_value(0),"use raw energy") ("useZ", po::value(&useZ)->default_value(1),"use Z events") ("useW", po::value(&useW)->default_value(1),"use W events") ("splitStat", po::value(&splitStat)->default_value(1),"split statistic") ("nLoops", po::value(&nLoops)->default_value(20),"number of iteration of the L3 algorithm") ("isDeadTriggerTower", po::value(&isDeadTriggerTower)->default_value(false),"") ("inputFileDeadXtal", po::value(&inputFileDeadXtal)->default_value("NULL"),"") + ("EPMin", po::value(&EPMin)->default_value(100.),"E/p window") + ("smoothCut", po::value(&smoothCut)->default_value(0),"apply smooth cut on the E/p window") ; - + desc.add(inputOption); desc.add(outputOption); desc.add(fitterOption); desc.add(smearerOption); desc.add(toyOption); desc.add(EoverPOption); - + desc.add(laserMonitoringEPOption); + po::variables_map vm; // // po::store(po::parse_command_line(argc, argv, smearOption), vm); @@ -510,7 +587,7 @@ int main(int argc, char **argv) { if(!vm.count("regionsFile") && !vm.count("runDivide") && !vm.count("savePUTreeWeight") && - !vm.count("saveR9TreeWeight") && !vm.count("saveCorrEleTree") && !vm.count("EOverPCalib") + !vm.count("saveR9TreeWeight") && !vm.count("saveCorrEleTree") && !vm.count("EOverPCalib") && !vm.count("laserMonitoringEP") //&& !vm.count("saveRootMacro") ){ std::cerr << "[ERROR] Missing mandatory option \"regionsFile\"" << std::endl; @@ -555,6 +632,22 @@ int main(int argc, char **argv) { if(!checkDirectories && !vm.count("EOverPCalib")){ std::cerr << "[ERROR] Directory " << outDirImgData << " not found" << std::endl; } + checkDirectories=checkDirectories && !system("[ -d "+TString(outDirFitResMC)+" ]"); + if(!checkDirectories && !vm.count("EOverPCalib") && !vm.count("laserMonitoringEP")){ + std::cerr << "[ERROR] Directory " << outDirFitResMC << " not found" << std::endl; + } + checkDirectories=checkDirectories && !system("[ -d "+TString(outDirFitResData)+" ]"); + if(!checkDirectories && !vm.count("EOverPCalib") && !vm.count("laserMonitoringEP")){ + std::cerr << "[ERROR] Directory " << outDirFitResData << " not found" << std::endl; + } + checkDirectories=checkDirectories && !system("[ -d "+TString(outDirImgMC)+" ]"); + if(!checkDirectories && !vm.count("EOverPCalib") && !vm.count("laserMonitoringEP")){ + std::cerr << "[ERROR] Directory " << outDirImgMC << " not found" << std::endl; + } + checkDirectories=checkDirectories && !system("[ -d "+TString(outDirImgData)+" ]"); + if(!checkDirectories && !vm.count("EOverPCalib") && !vm.count("laserMonitoringEP")){ + std::cerr << "[ERROR] Directory " << outDirImgData << " not found" << std::endl; + } // checkDirectories=checkDirectories && !system("[ -d "+TString(outDirTable)+" ]"); // if(!checkDirectories){ // std::cerr << "[ERROR] Directory " << outDirTable << " not found" << std::endl; @@ -566,6 +659,7 @@ int main(int argc, char **argv) { && !vm.count("saveR9TreeWeight") && !vm.count("saveRootMacro") && !vm.count("EOverPCalib") + && !vm.count("laserMonitoringEP") ) return 1; if(!dataPUFileName.empty()) dataPUFileNameVec.push_back(dataPUFileName.c_str()); @@ -632,6 +726,7 @@ int main(int argc, char **argv) { #endif } + //init chains and print for(tag_chain_map_t::const_iterator tag_chain_itr=tagChainMap.begin(); @@ -790,12 +885,13 @@ int main(int argc, char **argv) { } // end of data samples loop } // end of r9Weight - + //============================== // if(vm.count("dataPU")==0 && (tagChainMap["s"]).count("pileupHist")==0 && (tagChainMap["s"]).count("pileup")==0){ - if(vm.count("noPU")==0 && !vm.count("runToy")){ + if(vm.count("noPU")==0 && !vm.count("runToy") && !vm.count("laserMonitoringEP") && + !vm.count("EOverPCalib")){ if(dataPUFileNameVec.empty() && (tagChainMap.count("s")!=0) && (tagChainMap["s"]).count("pileup")==0){ std::cerr << "[ERROR] Nor pileup mc tree configured in chain list file either dataPU histograms are not provided" << std::endl; return 1; @@ -998,6 +1094,8 @@ int main(int argc, char **argv) { } //end of sample loop } //end of branches loop + + //(tagChainMap["s"])["selected"]->GetEntries(); UpdateFriends(tagChainMap, regionsFileNameTag); @@ -1174,245 +1272,126 @@ int main(int argc, char **argv) { mc = (tagChainMap["s"])["selected"]; } + + +//------------------------------ LASER MONITORING WITH E/P ------------------------------------------------------ + + if(vm.count("laserMonitoringEP")) { + + std::cout<<"start monitoring. "< > > jsonMap; jsonMap = readJSONFile(jsonFileName); - std::cout<<"JSON file: "< g_EoC_EB; + // for(int i = 0; i < nRegionsEB; ++i){ + // TString Name = Form("g_pData_EB_0_%d",i); + TString Name = Form("g_EoC_EB_0"); + g_EoC_EB.push_back( (TGraphErrors*)(momentumscale->Get(Name)) ); + // } + + std::cout<<"momentum calibration file correctly opened"< g_EoE_EB; + for(int i = 0; i < nRegionsEB; ++i){ - TString Name = Form("g_EoC_EB_%d",i); - g_EoC_EB.push_back( (TGraphErrors*)(momentumscale->Get(Name)) ); + TString Name = Form("g_pData_EB_0_%d",i); + g_EoE_EB.push_back( (TGraphErrors*)(energyscale->Get(Name)) ); } + std::cout<<"energy calibration file correctly opened"<GetEntries(); - + + std::cout<<"number of events: "< exit "< exit "< > > jsonMap; @@ -1423,13 +1402,23 @@ int main(int argc, char **argv) { system(("mkdir -p "+outputPath).c_str()); /// open calibration momentum graph - TFile* f4 = new TFile((inputMomentumScale+"_"+typeEB+"_"+typeEE+".root").c_str()); + TFile* f4 = new TFile((inputMomentumScale.c_str()));//+"_"+typeEB+"_"+typeEE+".root").c_str()); std::vector g_EoC_EE; - for(int i = 0; i < nRegionsEE; ++i){ - TString Name = Form("g_EoC_EE_%d",i); + // for(int i = 0; i < nRegionsEE; ++i){ + // TString Name = Form("g_pData_EE_0_%d",i); + TString Name = Form("g_EoC_EE_0"); g_EoC_EE.push_back( (TGraphErrors*)(f4->Get(Name)) ); - } + // } + + /// open calibration energy graph + TFile* f5 = new TFile((inputEnergyScale.c_str()));//+"_"+typeEB+"_"+typeEE+".root").c_str()); + std::vector g_EoE_EE; + + for(int i = 0; i < nRegionsEE; ++i){ + TString Name = Form("g_pData_EE_0_%d",i); + g_EoE_EE.push_back( (TGraphErrors*)(f5->Get(Name)) ); + } ///Use the whole sample statistics if numberOfEvents < 0 if ( numberOfEvents < 0 ) numberOfEvents = data->GetEntries(); @@ -1439,206 +1428,60 @@ int main(int argc, char **argv) { if ( splitStat == 0 ) { TString name ; - TString name_tmp; - - if(isMiscalib == true && useZ == 1 && isR9selection ==true && isEPselection == false && isfbrem == false && isPtCut ==false ) - name_tmp = Form ("%s_WZ_R9_miscalib_EE",outputFile.c_str()); - else if(isMiscalib == true && useZ == 1 && isR9selection ==false && isEPselection == false && isfbrem == true && isPtCut ==false ) - name_tmp = Form ("%s_WZ_Fbrem_miscalib_EE",outputFile.c_str()); - else if(isMiscalib == true && useZ == 1 && isR9selection ==true && isEPselection == false && isfbrem == false && isPtCut ==true ) - name_tmp = Form ("%s_WZ_PT_miscalib_EE",outputFile.c_str()); - else if(isMiscalib == true && useZ == 1 && isR9selection ==true && isEPselection == true && isfbrem == false && isPtCut ==false ) - name_tmp = Form ("%s_WZ_EP_miscalib_EE",outputFile.c_str()); - else if(isMiscalib == true && useZ == 1 && isEPselection ==false && isR9selection==false && isPtCut ==false && isfbrem ==false ) - name_tmp =Form ("%s_WZ_noEP_miscalib_EE",outputFile.c_str()); - - else if(isMiscalib == false && useZ == 1 && isR9selection ==true && isEPselection == false && isfbrem == false && isPtCut ==false ) - name_tmp = Form ("%s_WZ_R9_EE",outputFile.c_str()); - else if(isMiscalib == false && useZ == 1 && isR9selection ==false && isEPselection == false && isfbrem == true && isPtCut ==false ) - name_tmp = Form ("%s_WZ_Fbrem_EE",outputFile.c_str()); - else if(isMiscalib == false && useZ == 1 && isR9selection ==true && isEPselection == false && isfbrem == false && isPtCut ==true ) - name_tmp = Form ("%s_WZ_PT_EE",outputFile.c_str()); - else if(isMiscalib == false && useZ == 1 && isR9selection ==true && isEPselection == true && isfbrem == false && isPtCut ==false ) - name_tmp = Form ("%s_WZ_EP_EE",outputFile.c_str()); - else if(isMiscalib == false && useZ == 1 && isEPselection ==false && isR9selection==false && isPtCut ==false && isfbrem ==false ) - name_tmp =Form ("%s_WZ_noEP_EE",outputFile.c_str()); - - - - else if(isMiscalib == true && useZ == 0 && isR9selection ==true && isEPselection == false && isfbrem == false && isPtCut ==false ) - name_tmp = Form ("%s_W_R9_miscalib_EE",outputFile.c_str()); - else if(isMiscalib == true && useZ == 0 && isR9selection ==false && isEPselection == false && isfbrem == true && isPtCut ==false ) - name_tmp = Form ("%s_W_Fbrem_miscalib_EE",outputFile.c_str()); - else if(isMiscalib == true && useZ == 0 && isR9selection ==true && isEPselection == false && isfbrem == false && isPtCut ==true ) - name_tmp = Form ("%s_W_PT_miscalib_EE",outputFile.c_str()); - else if(isMiscalib == true && useZ == 0 && isR9selection ==true && isEPselection == true && isfbrem == false && isPtCut ==false ) - name_tmp = Form ("%s_W_EP_miscalib_EE",outputFile.c_str()); - else if(isMiscalib == true && useZ == 0 && isEPselection ==false && isR9selection==false && isPtCut ==false && isfbrem ==false ) - name_tmp =Form ("%s_W_noEP_miscalib_EE",outputFile.c_str()); - - else if(isMiscalib == false && useZ == 0 && isR9selection ==true && isEPselection == false && isfbrem == false && isPtCut ==false ) - name_tmp = Form ("%s_WZ_R9_EE",outputFile.c_str()); - else if(isMiscalib == false && useZ == 0 && isR9selection ==false && isEPselection == false && isfbrem == true && isPtCut ==false ) - name_tmp = Form ("%s_W_Fbrem_EE",outputFile.c_str()); - else if(isMiscalib == false && useZ == 0 && isR9selection ==true && isEPselection == false && isfbrem == false && isPtCut ==true ) - name_tmp = Form ("%s_W_PT_EE",outputFile.c_str()); - else if(isMiscalib == false && useZ == 0 && isR9selection ==true && isEPselection == true && isfbrem == false && isPtCut ==false ) - name_tmp = Form ("%s_W_EP_EE",outputFile.c_str()); - else if(isMiscalib == false && useZ == 0 && isEPselection ==false && isR9selection==false && isPtCut ==false && isfbrem ==false ) - name_tmp =Form ("%s_W_noEP_EE",outputFile.c_str()); - else { std::cout<<" Option not considered --> exit "< exit "< +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include "TROOT.h" +#include "TSystem.h" +#include "TStyle.h" +#include "TFile.h" +#include "TCanvas.h" +#include "TGraphErrors.h" +#include "TGraphAsymmErrors.h" +#include "TPaveStats.h" +#include "TLegend.h" +#include "TChain.h" +#include "TVirtualFitter.h" +#include "TLatex.h" + + +/// @cond SHOW +/// \code +#include "../interface/ZFit_class.hh" +#include "../interface/puWeights_class.hh" +#include "../interface/r9Weights_class.hh" +#include "../interface/ZPtWeights_class.hh" + +#include "../interface/runDivide_class.hh" +#include "../interface/EnergyScaleCorrection_class.hh" +#include "../interface/addBranch_class.hh" + +#include "../interface/RooSmearer.hh" + +#include "../interface/nllProfile.hh" + +#include "../../EOverPCalibration/interface/ntpleUtils.h" +#include "../../EOverPCalibration/interface/CalibrationUtils.h" +#include "../../EOverPCalibration/interface/FastCalibratorEB.h" +#include "../../EOverPCalibration/interface/FastCalibratorEE.h" + +#include "../../EOverPCalibration/interface/TEndcapRings.h" +#include "../../EOverPCalibration/CommonTools/histoFunc.h" +//#include "treeReader.h" +//#include "setTDRStyle.h" +#include "../../EOverPCalibration/interface/ntpleUtils2.h" +#include "../../EOverPCalibration/interface/ConvoluteTemplate.h" +#include "../../EOverPCalibration/interface/stabilityUtils.h" +#include "../../EOverPCalibration/interface/geometryUtils.h" + +/// \endcode +/// @endcond + +#include +//#include +//#include +//#include +#include +#include +#include "RooBinning.h" +//#include "../src/ShervinMinuit.cc" +//#include +#include + +#include "Math/Minimizer.h" + +#include +#include +#include + +#include + +#include +#include + +#define profile + +//#define DEBUG +#define smooth + +//#include "../macro/loop.C" // a way to use compiled macros with ZFitter + +//using namespace std; +using namespace RooStats; + +///\endcond + + +/// map that associates the name of the tree and the pointer to the chain +typedef std::map< TString, TChain* > chain_map_t; + +/** \brief map that associates the name of the tag to the chain_map_t + * + * the logic is better described in \ref validationConfig + */ +typedef std::map< TString, chain_map_t > tag_chain_map_t; + + +/** Function parsing the region files + * \retval vector of strings, each string is the name of one region + */ +std::vector ReadRegionsFromFile(TString fileName){ + ifstream file(fileName); + std::vector regions; + TString region; + + while(file.peek()!=EOF && file.good()){ + if(file.peek()==10){ // 10 = \n + file.get(); + continue; + } + + if(file.peek() == 35){ // 35 = # + file.ignore(1000,10); // ignore the rest of the line until \n + continue; + } + + file >> region; + file.ignore(1000,10); // ignore the rest of the line until \n +#ifdef DEBUG + std::cout << "[DEBUG] Reading region: " << region<< std::endl; +#endif + regions.push_back(region); + + } + return regions; +} + + +/** + * This function reassociates the chains as friends of the "selected" tree. + * + * This function should be run when new chains or files are added to the tagChainMap. + * + */ +void UpdateFriends(tag_chain_map_t& tagChainMap, TString regionsFileNameTag){ +//void UpdateFriends(tag_chain_map_t& tagChainMap){ + // loop over all the tags + for(tag_chain_map_t::const_iterator tag_chain_itr=tagChainMap.begin(); + tag_chain_itr!=tagChainMap.end(); + tag_chain_itr++){ + // take the selected tree of that tag + TChain *chain = (tag_chain_itr->second.find("selected"))->second; + + // loop over all the trees + for(chain_map_t::const_iterator chain_itr=tag_chain_itr->second.begin(); + chain_itr!=tag_chain_itr->second.end(); + chain_itr++){ + + if(chain_itr->first!="selected"){ //except the selected + if(chain->GetFriend(chain_itr->first)==NULL){ + std::cout << "[STATUS] Adding friend branch: " << chain_itr->first + << " to tag " << tag_chain_itr->first << std::endl; + chain->AddFriend(chain_itr->second); + } // already added + } + + if(chain->GetEntries()!= chain_itr->second->GetEntries()){ + std::cerr << "[ERROR] Not the same number of events: " << chain->GetEntries() << "\t" << chain_itr->second->GetEntries() << std::endl; + exit(1); + } + } + } + return; +} + +void Dump(tag_chain_map_t& tagChainMap, TString tag="s", Long64_t firstentry=0){ + (tagChainMap[tag])["selected"]->Scan("etaEle:R9Ele:energySCEle_regrCorrSemiParV5_pho/cosh(etaSCEle):smearerCat:catName","","col=5:4:5:3:50",5,firstentry); +} + +/** + * \param tagChainMap map of all the tags declared in the validation config file + * \param tag name of the new \b tag created by the function, all the existent tags with name starting with + b tag are merged in the new \b tag + * + * A new tagChain with name=tag is added to the tagChainMap. All the tagChains with tag starting with \b tag are merged + * After the merging the friend list is updated by \ref UpdateFriends + */ +void MergeSamples(tag_chain_map_t& tagChainMap, TString regionsFileNameTag, TString tag="s"){ + + std::pair pair_tmp_tag(tag,chain_map_t()); // make_pair not work with scram b + tagChainMap.insert(pair_tmp_tag); + + //loop over all the tags + for(tag_chain_map_t::const_iterator tag_chain_itr=tagChainMap.begin(); + tag_chain_itr!=tagChainMap.end(); + tag_chain_itr++){ + + // consider tags matching the tag input parameter + if(tag_chain_itr->first.CompareTo(tag)==0 || !tag_chain_itr->first.Contains(tag)) continue; //do it for each sample + + // loop over all the trees + for(chain_map_t::const_iterator chain_itr=tag_chain_itr->second.begin(); + chain_itr!=tag_chain_itr->second.end(); + chain_itr++){ + TString chainName = chain_itr->first; + if(tagChainMap.count(chainName)==0){ // create the new chain if does not exist for tag + std::pair pair_tmp(chainName, new TChain(chainName)); + (tagChainMap[tag]).insert(pair_tmp); + (tagChainMap[tag])[chainName]->SetTitle(tag); + } + (tagChainMap[tag])[chainName]->Add(chain_itr->second); + std::cout << tag << "\t" << tag_chain_itr->first << "\t" << chainName << "\t" << chain_itr->second << "\t" << chain_itr->second->GetTitle() << std::endl; + + } + } + UpdateFriends(tagChainMap, regionsFileNameTag); + return; +} + + +/** + * \brief Function returning the name of the energy branch given the name of the invariant mass + */ +std::string energyBranchNameFromInvMassName(std::string invMass_var){ + + std::string energyBranchName=""; + if(invMass_var=="invMass_SC_regrCorr_ele") energyBranchName = "energySCEle_regrCorr_ele"; + else if(invMass_var=="invMass_SC_regrCorr_pho") energyBranchName = "energySCEle_regrCorr_pho"; + else if(invMass_var=="invMass_regrCorr_fra") energyBranchName = "energyEle_regrCorr_fra"; + else if(invMass_var=="invMass_regrCorr_egamma") energyBranchName = "energyEle_regrCorr_egamma"; + else if(invMass_var=="invMass_SC") energyBranchName = "energySCEle"; + else if(invMass_var=="invMass_SC_must") energyBranchName = "energySCEle_must"; + else if(invMass_var=="invMass_SC_must_regrCorr_ele") energyBranchName = "energySCEle_must_regrCorr_ele"; + else if(invMass_var=="invMass_rawSC") energyBranchName = "rawEnergySCEle"; + else if(invMass_var=="invMass_rawSC_esSC") energyBranchName = "rawEnergySCEle+esEnergySCEle"; + else if(invMass_var=="invMass_SC_corr") energyBranchName = "energySCEle_corr"; + else if(invMass_var=="invMass_SC_regrCorrSemiParV4_ele") energyBranchName = "energySCEle_regrCorrSemiParV4_ele"; + else if(invMass_var=="invMass_SC_regrCorrSemiParV4_pho") energyBranchName = "energySCEle_regrCorrSemiParV4_pho"; + else if(invMass_var=="invMass_SC_regrCorrSemiParV5_ele") energyBranchName = "energySCEle_regrCorrSemiParV5_ele"; + else if(invMass_var=="invMass_SC_regrCorrSemiParV5_pho") energyBranchName = "energySCEle_regrCorrSemiParV5_pho"; + else if(invMass_var=="invMass_SC_regrCorrSemiParV6_ele") energyBranchName = "energySCEle_regrCorrSemiParV6_ele"; + else if(invMass_var=="invMass_SC_regrCorrSemiParV6_pho") energyBranchName = "energySCEle_regrCorrSemiParV6_pho"; + else if(invMass_var=="invMass_SC_regrCorrSemiParV7_ele") energyBranchName = "energySCEle_regrCorrSemiParV7_ele"; + else if(invMass_var=="invMass_SC_regrCorrSemiParV7_pho") energyBranchName = "energySCEle_regrCorrSemiParV7_pho"; + else if(invMass_var=="invMass_SC_regrCorrSemiParV8_ele") energyBranchName = "energySCEle_regrCorrSemiParV8_ele"; + else if(invMass_var=="invMass_SC_regrCorrSemiParV8_pho") energyBranchName = "energySCEle_regrCorrSemiParV8_pho"; + else if(invMass_var=="invMass_SC_regrCorrSemiPar7TeVtrainV6_ele") energyBranchName = "energySCEle_regrCorrSemiPar7TeVtrainV6_ele"; + else if(invMass_var=="invMass_SC_regrCorrSemiPar7TeVtrainV6_pho") energyBranchName = "energySCEle_regrCorrSemiPar7TeVtrainV6_pho"; + else if(invMass_var=="invMass_SC_regrCorrSemiPar7TeVtrainV7_ele") energyBranchName = "energySCEle_regrCorrSemiPar7TeVtrainV7_ele"; + else if(invMass_var=="invMass_SC_regrCorrSemiPar7TeVtrainV7_pho") energyBranchName = "energySCEle_regrCorrSemiPar7TeVtrainV7_pho"; + else if(invMass_var=="invMass_SC_regrCorrSemiPar7TeVtrainV8_ele") energyBranchName = "energySCEle_regrCorrSemiPar7TeVtrainV8_ele"; + else if(invMass_var=="invMass_SC_regrCorrSemiPar7TeVtrainV8_pho") energyBranchName = "energySCEle_regrCorrSemiPar7TeVtrainV8_pho"; + + else { + std::cerr << "Energy branch name not define for invariant mass branch: " << invMass_var << std::endl; + exit(1); + } + return energyBranchName; +} + + + +TString energyBranchNameFromInvMassName(TString invMass_var){ + return TString( (energyBranchNameFromInvMassName(std::string(invMass_var))).c_str()); +} + +int main(int argc, char **argv) { + TStopwatch myClock; + TStopwatch globalClock; + globalClock.Start(); + + puWeights_class puWeights; + std::cout << "============================== Z General Fitter" << std::endl; + + //------------------------------------------------------------ + // parsing input options to the program + using namespace boost; + namespace po = boost::program_options; + unsigned int nEvents_runDivide=100000; + std::string chainFileListName; + std::string regionsFileName; + std::string runRangesFileName; + std::string dataPUFileName, mcPUFileName; + std::vector dataPUFileNameVec, mcPUFileNameVec; + std::string r9WeightFile; + std::string ZPtWeightFile; + std::string initFileName; + // bool savePUweightTree; + std::string imgFormat="eps", outDirFitResMC="test/MC/fitres", outDirFitResData="test/dato/fitres", outDirImgMC="test/MC/img", outDirImgData="test/dato/img", outDirTable="test/dato/table", selection; + TString eleID=""; + //std::vector signalFiles, bkgFiles, dataFiles; + std::string commonCut; + std::string corrEleFile, corrEleType; + std::string smearEleFile, smearEleType; + double smearingCBAlpha=1, smearingCBPower=5; + std::string invMass_var; + float invMass_min=0, invMass_max=0, invMass_binWidth=0.250; + int fit_type_value=1; + int signal_type_value=0; + unsigned long long int nToys = 0; + float constTermToy=0; + unsigned long long int nEventsPerToy = 0; + unsigned int nIter =0; + unsigned int nEventsMinDiag=0; + unsigned int nEventsMinOffDiag=0; + unsigned int nSmearToy=1; + + int pdfSystWeightIndex=-1; + std::string minimType; + std::vector branchList; + + + + + +//options for E/p + std::string jsonFileName; + std::string miscalibMap; + bool isMiscalib; + bool applyPcorr; + bool applyEcorr; + bool isSaveEPDistribution; + bool isMCTruth; + bool isEPselection; + bool isPtCut; + float PtMin; + bool isfbrem; + float fbremMax; + bool isR9selection; + float R9Min; + float EPMin; + int smoothCut; + int miscalibMethod; + std::string inputMomentumScale; + std::string inputEnergyScale; + std::string typeEB; + std::string typeEE; + std::string outputPath; + std::string outputFile; + int numberOfEvents; + int useZ, useW; + int useRawEnergy; + // int isBarrel; + int splitStat; + int nLoops; + bool isDeadTriggerTower; + std::string inputFileDeadXtal; + std::string EBEE; + std::string EBEEpu; + int evtsPerPoint; + + int useRegression; + int targetTypeEB, targetTypeEE; + float R9cutEB, R9cutEE; + int energyTypeEB, energyTypeEE; + float yMIN; + float yMAX; + std::string dayMin; + std::string dayMax; + std::string dayZOOM; + std::string LUMI; + //------------------------------ setting option categories + po::options_description desc("Main options"); + po::options_description outputOption("Output options"); + po::options_description inputOption("Input options"); + po::options_description fitterOption("Z fitter options"); + po::options_description smearerOption("Z smearer options"); + po::options_description toyOption("toyMC options"); + po::options_description EoverPOption("EoverP options"); + po::options_description momentumCorrectionEB("run the momentum calibration for barrel"); + po::options_description momentumCorrectionEE("run the momentum calibration for endcap"); + po::options_description laserMonitoringEPOption("laser monitoring with E/p options"); + po::options_description laserMonitoringEPvsPUOption("laser monitoring with E/p versus Pile Up options"); + + + + //po::options_description cmd_line_options; + //cmd_line_options.add(desc).add(fitOption).add(smearOption); + + //------------------------------ adding options' description + desc.add_options() + ("help,h","Help message") + ("loop","") + + ("runDivide", "execute the run division") + ("nEvents_runDivide", po::value(&nEvents_runDivide)->default_value(100000), "Minimum number of events in a run range") + + // + ("dataPU", po::value< string >(&dataPUFileName), "") + ("mcPU", po::value(&mcPUFileName),"") + ("noPU", "") + ("savePUTreeWeight","") + // + ("corrEleFile", po::value(&corrEleFile),"File with energy scale corrections") + ("corrEleType", po::value(&corrEleType),"Correction type/step") + ("saveCorrEleTree", "") + + ("smearEleFile", po::value(&smearEleFile),"File with energy smearings") + ("smearEleType", po::value(&smearEleType),"Correction type/step") + ("smearingCBAlpha", po::value(&smearingCBAlpha),"Correction type/step") + ("smearingCBPower", po::value(&smearingCBPower),"Correction type/step") + // + ("r9WeightFile", po::value(&r9WeightFile),"File with r9 photon-electron weights") + ("useR9weight", "use r9 photon-electron weights") + ("saveR9TreeWeight", "") + ("ZPtWeightFile", po::value(&ZPtWeightFile),"File with ZPt weights") + ("useZPtweight", "use ZPt weights") + ("useFSRweight", "activate the FSR weight in MC") + ("useWEAKweight", "activate the WEAK interference weight in MC") + ("saveRootMacro","") + // + ("selection", po::value(&selection)->default_value("loose25nsRun2"),"") + ("commonCut", po::value(&commonCut)->default_value("Et_25"),"") + ("invMass_var", po::value(&invMass_var)->default_value("invMass_SC_must"),"") + ("invMass_min", po::value(&invMass_min)->default_value(65.),"") + ("invMass_max", po::value(&invMass_max)->default_value(115.),"") + ("invMass_binWidth", po::value(&invMass_binWidth)->default_value(0.25),"Smearing binning") + ("isOddMC", "Activate if use only odd events in MC") + ("isOddData", "Activate if use only odd events in data") + // + ("readDirect","") //read correction directly from config file instead of passing as a command line arg + //("addPtBranches", "") //add new pt branches ( 3 by default, fra, ele, pho) + ("addBranch", po::value< std::vector >(&branchList), "") + ("saveAddBranchTree","") + // ("signal,s", po::value< std::vector >(&signalFiles), "Signal file (can be called multiple times putting the files in a chain") + // ("bkg,b", po::value< std::vector >(&bkgFiles), "Bkg file (can be called multiple times putting the files in a chain") + // ("data,d", po::value< std::vector >(&dataFiles), "Data file (can be called multiple times putting the files in a chain") + //("_ZFit_class", "call the Z fitter") + //; + // + // po::options_description fitOption("Z Fit options"); + // po::options_description smearOption("Z smearing options"); + // smearOption.add_options() + ; + fitterOption.add_options() + ("fit_type_value", po::value(&fit_type_value)->default_value(1),"0=floating tails, 1=fixed tails") + ("signal_type_value", po::value(&signal_type_value)->default_value(0),"0=BW+CB, 1=Cruijff") + ("forceNewFit", "refit MC also if fit exists") + ("updateOnly", "do not fit data if fit exists") + ;; + smearerOption.add_options() + ("smearerFit", "call the smearing") + ("smearerType", po::value(&minimType)->default_value("profile"), "minimization algo") + ("onlyDiagonal","if want to use only diagonal categories") + ("autoBin", "") + ("autoNsmear", "") + ("smearscan", "") + ("isDataSmeared","") + ("plotOnly", "active if you don't want to do the smearing") + ("profileOnly", "") + ("numIter", po::value(&nIter)->default_value(300), "number of MCMC steps") + ("nEventsMinDiag", po::value(&nEventsMinDiag)->default_value(1000), "min num events in diagonal categories") + ("nEventsMinOffDiag", po::value(&nEventsMinOffDiag)->default_value(2000), "min num events in off-diagonal categories") + ("onlyScale", "fix the smearing to constant") + ("constTermFix", "constTerm not depending on Et") + ("alphaGoldFix", "alphaTerm for gold electrons fixed to the low eta region") + ("smearingEt", "alpha term depend on sqrt(Et) and not on sqrt(E)") + ("nSmearToy", po::value(&nSmearToy)->default_value(0), "") + ("pdfSystWeightIndex", po::value(&pdfSystWeightIndex)->default_value(-1), "Index of the weight to be used") + ; + inputOption.add_options() + ("chainFileList,f", po::value< string >(&chainFileListName), "Configuration file with input file list") + ("regionsFile", po::value< string >(®ionsFileName), "Configuration file with regions") + ("runRangesFile", po::value< string >(&runRangesFileName), "Configuration file with run ranges") + ("initFile", po::value< string >(&initFileName), "Configuration file with init values of fit model") + ; + outputOption.add_options() + ("imgFormat", po::value(&imgFormat)->default_value("eps"),"") + ("outDirFitResMC", po::value(&outDirFitResMC),"") + ("outDirFitResData", po::value(&outDirFitResData),"") + ("outDirImgMC", po::value(&outDirImgMC),"") + ("outDirImgData", po::value(&outDirImgData),"") + //("outDirTable", po::value(&outDirTable),"") + ; + toyOption.add_options() + ("runToy","") + ("nToys", po::value(&nToys)->default_value(1000),"") + ("constTermToy", po::value(&constTermToy)->default_value(0.01),"") + ("eventsPerToy", po::value(&nEventsPerToy)->default_value(0),"=0: all events") + ; + momentumCorrectionEE.add_options() + ("momentumCorrectionEE", "run the momentum calibration for endcap") + ("targetTypeEE", po::value(&targetTypeEE)->default_value(1),"compute corrections on: 1=pTk, 2=energy, 3=E/p") + ("R9cutEE", po::value(&R9cutEE)->default_value(0.),"apply R9 cut") + ("energyTypeEE", po::value(&energyTypeEE)->default_value(0),"0=rawEnergy, 1=scEnergy") + ; + momentumCorrectionEB.add_options() + ("momentumCorrectionEB", "run the momentum calibration for barrel") + ("targetTypeEB", po::value(&targetTypeEB)->default_value(1),"compute corrections on: 1=pTk, 2=energy, 3=E/p") + ("R9cutEB", po::value(&R9cutEB)->default_value(0.),"apply R9 cut") + ("energyTypeEB", po::value(&energyTypeEB)->default_value(0),"0=rawEnergy, 1=scEnergy") + ; + laserMonitoringEPOption.add_options() + ("laserMonitoringEP", "call the laser monitoring with E/p") + ("yMIN", po::value(&yMIN)->default_value(0.65),"y min") + ("yMAX", po::value(&yMAX)->default_value(1.05),"y max") + ("EBEE", po::value(&EBEE)->default_value("EB"),"barrel or endcap") + ("evtsPerPoint", po::value(&evtsPerPoint)->default_value(1000),"events per point") + ("useRegression", po::value(&useRegression)->default_value(0),"use regression") + ("dayMin", po::value(&dayMin)->default_value("1-7-2015"),"day min") + ("dayMax", po::value(&dayMax)->default_value("15-11-2015"),"day max") + ("dayZOOM", po::value(&dayZOOM)->default_value("10-8-2015"),"day ZOOM") + ("LUMI", po::value(&LUMI)->default_value("1.9"),"LUMI") + ; + laserMonitoringEPvsPUOption.add_options() + ("laserMonitoringEPvsPU", "call the laser monitoring with E/p") + // ("EBEEpu", po::value(&EBEEpu)->default_value("EB"),"barrel or endcap") + //("evtsPerPointpu", po::value(&evtsPerPoint)->default_value(1000),"events per point") + // ("useRegression", po::value(&useRegression)->default_value(0),"use regression") + // ("dayMin", po::value(&dayMin)->default_value("1-6-2015"),"day min") + // ("dayMax", po::value(&dayMax)->default_value("1-10-2015"),"day max") + // ("dayZOOM", po::value(&dayZOOM)->default_value("10-8-2015"),"day ZOOM") + ; + EoverPOption.add_options() + ("EOverPCalib", "call the E/p calibration") + // ("isBarrel", po::value(&isBarrel)->default_value(1),"1=barrel, 0=endcap") + ("doEB", "do EoP IC calibration for EB") + ("doEE", "do EoP IC calibration for EE") + ("jsonFileName", po::value(&jsonFileName)->default_value("/afs/cern.ch/cms/CAF/CMSCOMM/COMM_DQM/certification/Collisions15/13TeV/Cert_246908-258750_13TeV_PromptReco_Collisions15_25ns_JSON.txt"), "jsonFileName") + ("isMiscalib", po::value(&isMiscalib)->default_value(false),"apply the initial miscalibration") + ("miscalibMethod", po::value(&miscalibMethod)->default_value(1),"miscalibration method") + ("miscalibMap", po::value(&miscalibMap)->default_value("/gwteray/users/brianza/scalibMap2.txt"), "map for the miscalibration") + ("isSaveEPDistribution", po::value(&isSaveEPDistribution)->default_value(false),"save E/P distribution") + ("isMCTruth", po::value(&isMCTruth)->default_value(false),"option for MC") + ("isEPselection", po::value(&isEPselection)->default_value(false),"apply E/p selection") + ("isPtCut", po::value(&isPtCut)->default_value(false),"apply Pt cut") + ("PtMin", po::value(&PtMin)->default_value(0.),"treshold for the Pt cut") + ("isfbrem", po::value(&isfbrem)->default_value(false),"apply fbrem cut") + ("fbremMax", po::value(&fbremMax)->default_value(100.),"fbrem treshold") + ("isR9selection", po::value(&isR9selection)->default_value(false),"apply R9 selection") + ("R9Min", po::value(&R9Min)->default_value(-1.),"R9 treshold") + ("applyPcorr", po::value(&applyPcorr)->default_value(true),"apply momentum correction") + ("inputMomentumScale", po::value(&inputMomentumScale)->default_value("/afs/cern.ch/user/l/lbrianza/work/public/EoP_additionalFiles/MomentumCalibration2015_eta1_eta1.root"),"input momentum scale") + ("applyEcorr", po::value(&applyEcorr)->default_value(false),"apply energy correction") + ("inputEnergyScale", po::value(&inputEnergyScale)->default_value("/afs/cern.ch/user/l/lbrianza/work/public/EoP_additionalFiles/momentumCalibration2015_EB_scE.root"),"input energy scale") + ("typeEB", po::value(&typeEB)->default_value("eta1"),"") + ("typeEE", po::value(&typeEE)->default_value("eta1"),"") + ("outputPath", po::value(&outputPath)->default_value("output/output_runD/"),"output dir for E/P calibration") + ("outputFile", po::value(&outputFile)->default_value("FastCalibrator_Oct2015_runD"),"output file for E/P calibration") + ("numberOfEvents", po::value(&numberOfEvents)->default_value(-1),"number of events (-1=all)") + ("useRawEnergy", po::value(&useRawEnergy)->default_value(0),"use raw energy") + ("useZ", po::value(&useZ)->default_value(1),"use Z events") + ("useW", po::value(&useW)->default_value(1),"use W events") + ("splitStat", po::value(&splitStat)->default_value(1),"split statistic") + ("nLoops", po::value(&nLoops)->default_value(20),"number of iteration of the L3 algorithm") + ("isDeadTriggerTower", po::value(&isDeadTriggerTower)->default_value(false),"") + ("inputFileDeadXtal", po::value(&inputFileDeadXtal)->default_value("NULL"),"") + ("EPMin", po::value(&EPMin)->default_value(100.),"E/p window") + ("smoothCut", po::value(&smoothCut)->default_value(0),"apply smooth cut on the E/p window") + ; + + desc.add(inputOption); + desc.add(outputOption); + desc.add(fitterOption); + desc.add(smearerOption); + desc.add(toyOption); + desc.add(momentumCorrectionEE); + desc.add(momentumCorrectionEB); + desc.add(EoverPOption); + desc.add(laserMonitoringEPOption); + desc.add(laserMonitoringEPvsPUOption); + + po::variables_map vm; + // + // po::store(po::parse_command_line(argc, argv, smearOption), vm); + po::store(po::parse_command_line(argc, argv, desc), vm); + po::notify(vm); + + + //------------------------------ checking options + if(!vm.count("invMass_binWidth") && !vm.count("smearerFit")){ + std::cout << "[INFO] Bin Width=0.5" << std::endl; + invMass_binWidth=0.5; + } + + if (vm.count("help")) { + cout << desc << "\n"; + return 1; + } + + if(vm.count("useZPtweight") && !vm.count("pdfSystWeightIndex")){ + std::cerr << "[ERROR] Asked for ZPt weights but no pdfSystWeightIndex indicated" << std::endl; + exit(1); + } + + TString energyBranchName=energyBranchNameFromInvMassName(invMass_var).c_str(); + + if(!vm.count("chainFileList") && !vm.count("runToy")){ + std::cerr << "[ERROR] Missing mandatory option \"chainFile\"" << std::endl; + return 1; + } + + + if(!vm.count("regionsFile") && + !vm.count("runDivide") && !vm.count("savePUTreeWeight") && + !vm.count("saveR9TreeWeight") && !vm.count("saveCorrEleTree") && !vm.count("EOverPCalib") && !vm.count("momentumCorrectionEE") && !vm.count("momentumCorrectionEB") && !vm.count("laserMonitoringEP") && !vm.count("laserMonitoringEPvsPU") + //&& !vm.count("saveRootMacro") + ){ + std::cerr << "[ERROR] Missing mandatory option \"regionsFile\"" << std::endl; + return 1; + } + // if(!vm.count("runRangesFile")){ + // std::cerr << "[ERROR] Missing mandatory option \"runRangesFile\"" << std::endl; + // return 1; + // } + + if(vm.count("dataPU") != vm.count("mcPU")){ + std::cerr << "[ERROR] One PU distribution (data or mc) are not provided" << std::endl; + return 1; + } + + + //if((vm.count("corrEleType") != vm.count("corrEleFile"))&&(vm.count("corrEleType") != vm.count("readDirect")) ){ + //std::cout << "[ERROR] Either provide correction file name, or provide read direct option" << std::endl; + //return 1; + //} + + if( vm.count("corrEleType") && vm.count("corrEleFile") && vm.count("readDirect") ){ + std::cout << "[ERROR] Either provide correction file name, or provide read direct option - choose only one" << std::endl; + return 1; + } + + //============================== Check output folders + bool checkDirectories=true; + checkDirectories=checkDirectories && !system("[ -d "+TString(outDirFitResMC)+" ]"); + if(!checkDirectories && !vm.count("EOverPCalib") && !vm.count("momentumCorrectionEE") && !vm.count("momentumCorrectionEB")){ + std::cerr << "[ERROR] Directory " << outDirFitResMC << " not found" << std::endl; + } + checkDirectories=checkDirectories && !system("[ -d "+TString(outDirFitResData)+" ]"); + if(!checkDirectories && !vm.count("EOverPCalib") && !vm.count("momentumCorrectionEE") && !vm.count("momentumCorrectionEB")){ + std::cerr << "[ERROR] Directory " << outDirFitResData << " not found" << std::endl; + } + checkDirectories=checkDirectories && !system("[ -d "+TString(outDirImgMC)+" ]"); + if(!checkDirectories && !vm.count("EOverPCalib") && !vm.count("momentumCorrectionEE") && !vm.count("momentumCorrectionEB")){ + std::cerr << "[ERROR] Directory " << outDirImgMC << " not found" << std::endl; + } + checkDirectories=checkDirectories && !system("[ -d "+TString(outDirImgData)+" ]"); + if(!checkDirectories && !vm.count("EOverPCalib") && !vm.count("momentumCorrectionEE") && !vm.count("momentumCorrectionEB")){ + std::cerr << "[ERROR] Directory " << outDirImgData << " not found" << std::endl; + } + checkDirectories=checkDirectories && !system("[ -d "+TString(outDirFitResMC)+" ]"); + if(!checkDirectories && !vm.count("EOverPCalib") && !vm.count("laserMonitoringEP") && !vm.count("laserMonitoringEPvsPU")){ + std::cerr << "[ERROR] Directory " << outDirFitResMC << " not found" << std::endl; + } + checkDirectories=checkDirectories && !system("[ -d "+TString(outDirFitResData)+" ]"); + if(!checkDirectories && !vm.count("EOverPCalib") && !vm.count("laserMonitoringEP") && !vm.count("laserMonitoringEPvsPU")){ + std::cerr << "[ERROR] Directory " << outDirFitResData << " not found" << std::endl; + } + checkDirectories=checkDirectories && !system("[ -d "+TString(outDirImgMC)+" ]"); + if(!checkDirectories && !vm.count("EOverPCalib") && !vm.count("laserMonitoringEP") && !vm.count("laserMonitoringEPvsPU")){ + std::cerr << "[ERROR] Directory " << outDirImgMC << " not found" << std::endl; + } + checkDirectories=checkDirectories && !system("[ -d "+TString(outDirImgData)+" ]"); + if(!checkDirectories && !vm.count("EOverPCalib") && !vm.count("laserMonitoringEP") && !vm.count("laserMonitoringEPvsPU")){ + std::cerr << "[ERROR] Directory " << outDirImgData << " not found" << std::endl; + } + // checkDirectories=checkDirectories && !system("[ -d "+TString(outDirTable)+" ]"); + // if(!checkDirectories){ + // std::cerr << "[ERROR] Directory " << outDirTable << " not found" << std::endl; + // } + if(!checkDirectories + && !vm.count("runDivide") + && !vm.count("savePUTreeWeight") + && !vm.count("saveCorrEleTree") + && !vm.count("saveR9TreeWeight") + && !vm.count("saveRootMacro") + && !vm.count("EOverPCalib") + && !vm.count("momentumCorrectionEE") + && !vm.count("momentumCorrectionEB") + && !vm.count("laserMonitoringEP") + && !vm.count("laserMonitoringEPvsPU") + ) return 1; + + if(!dataPUFileName.empty()) dataPUFileNameVec.push_back(dataPUFileName.c_str()); + if(!mcPUFileName.empty()) mcPUFileNameVec.push_back(mcPUFileName.c_str()); + //============================== Reading the config file with the list of chains + tag_chain_map_t tagChainMap; + TString tag, chainName, fileName; + + TString chainFileListTag=chainFileListName; + chainFileListTag.Remove(0,chainFileListTag.Last('/')+1); + chainFileListTag.ReplaceAll(".dat",""); + + TString regionsFileNameTag=regionsFileName; + regionsFileNameTag.Remove(0,regionsFileNameTag.Last('/')+1); + regionsFileNameTag.ReplaceAll(".dat",""); + + std::ifstream chainFileList(chainFileListName.c_str()); + while(chainFileList >> tag, chainFileList.good()){ + if(tag.Contains('#')){ + chainFileList.ignore(1000,'\n'); + continue; + } + chainFileList >> chainName >> fileName; + if(chainName.Contains("Hist")){ + // use these value only if not provided by the command line + if(tag.Contains("d") && dataPUFileName.empty()) dataPUFileNameVec.push_back(fileName); + else if(tag.Contains("s") && mcPUFileName.empty()) mcPUFileNameVec.push_back(fileName); + else std::cerr << "[ERROR] in configuration file Hist not recognized" << std::endl; + continue; + } + + // discard file with energy corrections different from the specified type + if(chainName.Contains("scaleEle")){ + if(chainName!="scaleEle_"+corrEleType) continue; + } + + // discard file with energy smearings different from the specified type + if(chainName.Contains("smearEle")){ + if(chainName!="smearEle_"+smearEleType) continue; + } + + // discard file with categories for "smearingMethod" different from the region file name + if(chainName.Contains("smearerCat")){ + if(chainName!="smearerCat_"+regionsFileNameTag) continue; + } + + if(!tagChainMap.count(tag)){ +#ifdef DEBUG + std::cout << "[DEBUG] Create new tag map for tag: " << tag << std::endl; +#endif + std::pair pair_tmp(tag,chain_map_t()); // make_pair not work with scram b + tagChainMap.insert(pair_tmp); + } + + if(!tagChainMap[tag].count(chainName)){ + std::pair pair_tmp(chainName, new TChain(chainName)); + (tagChainMap[tag]).insert(pair_tmp); + (tagChainMap[tag])[chainName]->SetTitle(tag); + } + std::cout <<"Adding file: " << tag << "\t" << chainName << "\t" << fileName<< std::endl; + if((tagChainMap[tag])[chainName]->Add(fileName,-1)==0) exit(1); +#ifdef DEBUG + std::cout << "[DEBUG] " << tag << "\t" << chainName << "\t" << fileName << "\t" << (tagChainMap[tag])[chainName]->GetEntries() << std::endl; +#endif + + } + + + //init chains and print + for(tag_chain_map_t::const_iterator tag_chain_itr=tagChainMap.begin(); + tag_chain_itr!=tagChainMap.end(); + tag_chain_itr++){ +#ifdef DEBUG + std::cout << tag_chain_itr->first << std::endl; +#endif + for(chain_map_t::const_iterator chain_itr=tag_chain_itr->second.begin(); + chain_itr!=tag_chain_itr->second.end(); + chain_itr++){ + //#ifdef DEBUG + std::cout << " - " << chain_itr->first << "\t" << chain_itr->second->GetName() << "\t" << chain_itr->second->GetTitle() << "\t" << chain_itr->second->GetEntries() << std::endl; + //#endif + chain_itr->second->GetEntries(); + } + } + + + ///------------------------------ to obtain run ranges + if(vm.count("runDivide")){ + runDivide_class runDivider; + std::vector v=runDivider.Divide((tagChainMap["d"])["selected"], "data/runRanges/runRangeLimits.dat", nEvents_runDivide); + runDivider.PrintRunRangeEvents(); + std::vector runRanges; + if(runRangesFileName!="") runRanges = ReadRegionsFromFile(runRangesFileName); + for(std::vector::const_iterator itr = runRanges.begin(); + itr != runRanges.end(); + itr++){ + std::cout << *itr << "\t" << "-1" << "\t" << runDivider.GetRunRangeTime(*itr) << std::endl; + } + + return 0; + } + + + + TString r(regionsFileName.c_str()); + r.Remove(0,r.Last('/')+1); r.ReplaceAll(".dat",""); + + std::vector regions = ReadRegionsFromFile(regionsFileName); + std::vector runRanges = ReadRegionsFromFile(runRangesFileName); + std::vector categories; + for(std::vector::const_iterator region_itr = regions.begin(); + region_itr != regions.end(); + region_itr++){ + if(runRanges.size()>0){ + for(std::vector::const_iterator runRange_itr = runRanges.begin(); + runRange_itr!=runRanges.end(); + runRange_itr++){ + TString token1,token2; + //Ssiz_t ss=0; + //runRange_itr->Tokenize(token1,ss,"-"); + //ss=runRange_itr->First('-'); + //runRange_itr->Tokenize(token2,ss,"-"); + TObjArray *tx = runRange_itr->Tokenize("-"); + token1 = ((TObjString *)(tx->At(0)))->String(); + token2 = ((TObjString *)(tx->At(1)))->String(); + categories.push_back((*region_itr)+"-runNumber_"+token1+"_"+token2+"-"+commonCut.c_str()); + } + }else categories.push_back((*region_itr)+"-"+commonCut.c_str()); + } + + + + ///------------------------------ to obtain r9weights + if(vm.count("saveR9TreeWeight") && !vm.count("r9WeightFile")){ + std::cerr << "[ERROR] No r9WeightFile specified" << std::endl; + return 1; + } + if(vm.count("r9WeightFile")){ + std::cout << "------------------------------------------------------------" << std::endl; + std::cout << "[STATUS] Getting r9Weights from file: " << r9WeightFile << std::endl; + r9Weights_class r9Weights; + r9Weights.ReadFromFile(r9WeightFile); + + TString treeName="r9Weight"; + + // mc // save it in a file and reload it as a chain to be safe against the reference directory for the tree + for(tag_chain_map_t::const_iterator tag_chain_itr=tagChainMap.begin(); + tag_chain_itr!=tagChainMap.end(); + tag_chain_itr++){ + if(tag_chain_itr->first.CompareTo("d")==0 || tag_chain_itr->first.CompareTo("s")==0) continue; + if(tag_chain_itr->second.count(treeName)!=0) continue; //skip if already present + TChain *ch = (tag_chain_itr->second.find("selected"))->second; + + TString filename="tmp/r9Weight_"+tag_chain_itr->first+"-"+chainFileListTag+".root"; + std::cout << "[STATUS] Saving r9Weights tree to root file:" << filename << std::endl; + + TFile f(filename,"recreate"); + if(!f.IsOpen() || f.IsZombie()){ + std::cerr << "[ERROR] File for r9Weights: " << filename << " not opened" << std::endl; + exit(1); + } + TTree *corrTree = r9Weights.GetTreeWeight(ch); + f.cd(); + corrTree->Write(); + std::cout << "[INFO] Data entries: " << ch->GetEntries() << std::endl; + std::cout << " r9Weights entries: " << corrTree->GetEntries() << std::endl; + delete corrTree; + + f.Write(); + f.Close(); + std::pair pair_tmp(treeName, new TChain(treeName)); + chain_map_t::iterator chain_itr= ((tagChainMap[tag_chain_itr->first]).insert(pair_tmp)).first; + chain_itr->second->SetTitle(tag_chain_itr->first); + chain_itr->second->Add(filename); + + } // end of data samples loop + } // end of r9Weight + + + if(vm.count("saveR9TreeWeight")) return 0; + + ///------------------------------ to obtain ZPt weights + if(vm.count("ZPtWeightFile")){ + std::cout << "------------------------------------------------------------" << std::endl; + std::cout << "[STATUS] Getting ZPtWeights from file: " << ZPtWeightFile << std::endl; + UpdateFriends(tagChainMap, regionsFileNameTag); + ZPtWeights_class ZPtWeights; + ZPtWeights.ReadFromFile(ZPtWeightFile); + + TString treeName="ZPtWeight"; + + // mc // save it in a file and reload it as a chain to be safe against the reference directory for the tree + for(tag_chain_map_t::const_iterator tag_chain_itr=tagChainMap.begin(); + tag_chain_itr!=tagChainMap.end(); + tag_chain_itr++){ + if(tag_chain_itr->first.Contains("d")) continue; /// \todo ZPtWeight only on MC! because from PdfWeights, to make it more general + if(tag_chain_itr->first.CompareTo("d")==0 || tag_chain_itr->first.CompareTo("s")==0) continue; + if(tag_chain_itr->second.count(treeName)!=0) continue; //skip if already present + TChain *ch = (tag_chain_itr->second.find("selected"))->second; + + TString filename="tmp/ZPtWeight_"+tag_chain_itr->first+"-"+chainFileListTag+".root"; + std::cout << "[STATUS] Saving r9Weights tree to root file:" << filename << std::endl; + + TFile f(filename,"recreate"); + if(!f.IsOpen() || f.IsZombie()){ + std::cerr << "[ERROR] File for ZPtWeights: " << filename << " not opened" << std::endl; + exit(1); + } + TTree *corrTree = ZPtWeights.GetTreeWeight(ch, "ZPt_"+energyBranchName); + f.cd(); + corrTree->Write(); + std::cout << "[INFO] Data entries: " << ch->GetEntries() << std::endl; + std::cout << " ZPtWeights entries: " << corrTree->GetEntries() << std::endl; + delete corrTree; + + f.Write(); + f.Close(); + std::pair pair_tmp(treeName, new TChain(treeName)); + chain_map_t::iterator chain_itr= ((tagChainMap[tag_chain_itr->first]).insert(pair_tmp)).first; + chain_itr->second->SetTitle(tag_chain_itr->first); + chain_itr->second->Add(filename); + + } // end of data samples loop + } // end of r9Weight + + + //============================== + + // if(vm.count("dataPU")==0 && (tagChainMap["s"]).count("pileupHist")==0 && (tagChainMap["s"]).count("pileup")==0){ + + if(vm.count("noPU")==0 && !vm.count("runToy") && !vm.count("correctionMomentum") && !vm.count("laserMonitoringEP") && !vm.count("laserMonitoringEPvsPU") && + !vm.count("EOverPCalib")){ + if(dataPUFileNameVec.empty() && (tagChainMap.count("s")!=0) && (tagChainMap["s"]).count("pileup")==0){ + std::cerr << "[ERROR] Nor pileup mc tree configured in chain list file either dataPU histograms are not provided" << std::endl; + return 1; + }else if( !vm.count("runToy") && (vm.count("dataPU")!=0 || (!dataPUFileNameVec.empty() && ((tagChainMap.count("s")==0) || (tagChainMap["s"]).count("pileup")==0)))){ + std::cout << "[STATUS] Creating pileup weighting tree and saving it" << std::endl; + for(unsigned int i=0; i < mcPUFileNameVec.size(); i++){ + TString mcPUFileName_=mcPUFileNameVec[i]; + TString dataPUFileName_=dataPUFileNameVec[i]; + TString runMin_ = ""; + if(!mcPUFileName_.Contains("nPU")){ +// if(mcPUFileName_.Index(".runMin_")!=-1){ + runMin_=mcPUFileName_; + runMin_.Remove(0,runMin_.Last('/')+1); + runMin_.Remove(runMin_.First('-')); +// runMin_.Remove(runMin_.First('.')); +// runMin_.ReplaceAll("runMin_",""); + } + int runMin = runMin_.Sizeof()>1 ? runMin_.Atoi() : 1; + std::cout << "********* runMin = " << runMin << "\t" << runMin_ << std::endl; + puWeights.ReadFromFiles(mcPUFileName_.Data(),dataPUFileName_.Data(), runMin); + } + + // for each mc sample create a tree with the per-event-weight + // but exclude the chain "s" since it's supposed to be created mergin alle the s-type samples + for(tag_chain_map_t::const_iterator tag_chain_itr=tagChainMap.begin(); + tag_chain_itr!=tagChainMap.end(); + tag_chain_itr++){ + if(tag_chain_itr->first.CompareTo("s")==0 || !tag_chain_itr->first.Contains("s")) continue; + TChain *ch = (tag_chain_itr->second.find("selected"))->second; + if((tag_chain_itr->second.count("pileup"))) continue; + TString treeName="pileup"; + TString filename="tmp/mcPUtree"+tag_chain_itr->first+".root"; + TFile f(filename,"recreate"); + if(f.IsOpen()){ + f.cd(); + + TTree *puTree = puWeights.GetTreeWeight(ch,true); + puTree->SetName(treeName); + puTree->Write(); + delete puTree; + f.Write(); + f.Close(); + std::pair pair_tmp(treeName, new TChain(treeName)); + chain_map_t::iterator chain_itr= ((tagChainMap[tag_chain_itr->first]).insert(pair_tmp)).first; + chain_itr->second->SetTitle(tag_chain_itr->first); + chain_itr->second->Add(filename); + } + } + } + } + + //read corrections directly from file + if (vm.count("corrEleType") && corrEleFile!=""){ + std::cout << "------------------------------------------------------------" << std::endl; + std::cout << "[STATUS] Getting energy scale corrections from file: " << corrEleFile << std::endl; + TString treeName="scaleEle_"+corrEleType; + EnergyScaleCorrection_class eScaler(corrEleFile); + + for(tag_chain_map_t::const_iterator tag_chain_itr=tagChainMap.begin(); + tag_chain_itr!=tagChainMap.end(); + tag_chain_itr++){ + if(tag_chain_itr->first.CompareTo("d")==0 || !tag_chain_itr->first.Contains("d")) continue; //only data + if(tag_chain_itr->second.count(treeName)!=0) continue; //skip if already present + TChain *ch = (tag_chain_itr->second.find("selected"))->second; + + TString filename="tmp/scaleEle_"+corrEleType+"_"+tag_chain_itr->first+"-"+chainFileListTag+".root"; + std::cout << "[STATUS] Saving electron scale corrections to root file:" << filename << std::endl; + + TFile f(filename,"recreate"); + if(!f.IsOpen() || f.IsZombie()){ + std::cerr << "[ERROR] File for scale corrections: " << filename << " not opened" << std::endl; + exit(1); + } + TTree *corrTree = eScaler.GetCorrTree(ch, "runNumber", "R9Eleprime"); + corrTree->SetName(TString("scaleEle_")+corrEleType.c_str()); + corrTree->SetTitle(corrEleType.c_str()); + f.cd(); + corrTree->Write(); + std::cout << "[INFO] Data entries: " << ch->GetEntries() << std::endl; + std::cout << " corrEle entries: " << corrTree->GetEntries() << std::endl; + delete corrTree; + + f.Write(); + f.Close(); + std::pair pair_tmp(treeName, new TChain(treeName)); + chain_map_t::iterator chain_itr= ((tagChainMap[tag_chain_itr->first]).insert(pair_tmp)).first; + chain_itr->second->SetTitle(tag_chain_itr->first); + chain_itr->second->Add(filename); + + } // end of data samples loop + } // end of corrEle loop + + + //read corrections directly from file + if (vm.count("smearEleType")){ + std::cout << "------------------------------------------------------------" << std::endl; + std::cout << "[STATUS] Getting energy smearings from file: " << smearEleFile << std::endl; + TString treeName="smearEle_"+smearEleType; + EnergyScaleCorrection_class eScaler("", smearEleFile); + for(tag_chain_map_t::const_iterator tag_chain_itr=tagChainMap.begin(); + tag_chain_itr!=tagChainMap.end(); + tag_chain_itr++){ + if(tag_chain_itr->first.CompareTo("s")==0 || !tag_chain_itr->first.Contains("s")) continue; //only data + if(tag_chain_itr->second.count(treeName)!=0) continue; //skip if already present + TChain *ch = (tag_chain_itr->second.find("selected"))->second; + + TString filename="tmp/smearEle_"+smearEleType+"_"+tag_chain_itr->first+"-"+chainFileListTag+".root"; + std::cout << "[STATUS] Saving electron smearings to root file:" << filename << std::endl; + + TFile f(filename,"recreate"); + if(!f.IsOpen() || f.IsZombie()){ + std::cerr << "[ERROR] File for scale corrections: " << filename << " not opened" << std::endl; + exit(1); + } + if(TString(smearEleType).Contains("CB")){ + eScaler.SetSmearingType(1); + eScaler.SetSmearingCBAlpha(smearingCBAlpha); + } + + TTree *corrTree = eScaler.GetSmearTree(ch, true, energyBranchName ); + f.cd(); + corrTree->SetName(TString("smearEle_")+smearEleType.c_str()); + corrTree->SetTitle(smearEleType.c_str()); + corrTree->Write(); + std::cout << "[INFO] Data entries: " << ch->GetEntries() << std::endl; + std::cout << " smearEle entries: " << corrTree->GetEntries() << std::endl; + delete corrTree; + + f.Write(); + f.Close(); + std::pair pair_tmp(treeName, new TChain(treeName)); + chain_map_t::iterator chain_itr= ((tagChainMap[tag_chain_itr->first]).insert(pair_tmp)).first; + chain_itr->second->SetTitle(tag_chain_itr->first); + chain_itr->second->Add(filename); + } + // \todo need the data part in case of needs + } + + + addBranch_class newBrancher; + newBrancher._commonCut=commonCut.c_str(); + newBrancher._regionList=categories; + + for( std::vector::const_iterator branch_itr = branchList.begin(); + branch_itr != branchList.end(); + branch_itr++){ + UpdateFriends(tagChainMap, regionsFileNameTag); + + TString treeName=*branch_itr; + TString t; + if(treeName=="smearerCat_s"){ + treeName.ReplaceAll("_s",""); + t="s"; + } + if(treeName=="smearerCat_d"){ + treeName.ReplaceAll("_d",""); + t="d"; + } + TString branchName=treeName; + std::cout << "#### --> " << treeName << "\t" << t << "\t" << *branch_itr <first.CompareTo("s")==0 || tag_chain_itr->first.CompareTo("d")==0)) continue; //only data + if(tag_chain_itr->second.count(treeName)!=0) continue; //skip if already present + if(t!="" && !tag_chain_itr->first.Contains(t)) continue; + TChain *ch = (tag_chain_itr->second.find("selected"))->second; + + //data + std::cout <<"[STATUS] Adding branch " << branchName << " to " << tag_chain_itr->first <first+"-"+chainFileListTag+".root"; + + TTree *newTree = newBrancher.AddBranch(ch,treeName, branchName,true,tag_chain_itr->first.Contains("s")); + if(newTree==NULL){ + std::cerr << "[ERROR] New tree for branch " << treeName << " is NULL" << std::endl; + return 1; + } + + TFile f(filename,"recreate"); + if (!f.IsOpen()){ + std::cerr << "[ERROR] File for branch " << branchName << " not created" << std::endl; + return 1; + } + f.cd(); + newTree->SetTitle(tag_chain_itr->first); + newTree->Write(); + delete newTree; + //f.Write(); + f.Close(); + std::pair pair_tmp(treeName, new TChain(treeName)); + chain_map_t::iterator chain_itr= ((tagChainMap[tag_chain_itr->first]).insert(pair_tmp)).first; + chain_itr->second->SetTitle(tag_chain_itr->first); + chain_itr->second->Add(filename); + } //end of sample loop + } //end of branches loop + + + + //(tagChainMap["s"])["selected"]->GetEntries(); + UpdateFriends(tagChainMap, regionsFileNameTag); + + //create tag "s" if not present (due to multiple mc samples) + if(!tagChainMap.count("s")){ + //#ifdef DEBUG + std::cout << "==============================" << std::endl; + std::cout << "==============================" << std::endl; + MergeSamples(tagChainMap, regionsFileNameTag, "s"); + MergeSamples(tagChainMap, regionsFileNameTag, "d"); + } + +// Dump(tagChainMap, "s",0); +// Dump(tagChainMap, "s",(tagChainMap["s1"])["selected"]->GetEntries()); +// Dump(tagChainMap, "s",(tagChainMap["s2"])["selected"]->GetEntries()); +// exit(0); + if(vm.count("saveRootMacro")){ + for(tag_chain_map_t::const_iterator tag_chain_itr=tagChainMap.begin(); + tag_chain_itr!=tagChainMap.end(); + tag_chain_itr++){ + for(chain_map_t::const_iterator chain_itr=tag_chain_itr->second.begin(); + chain_itr!=tag_chain_itr->second.end(); + chain_itr++){ + chain_itr->second->SaveAs("tmp/"+tag_chain_itr->first+"_"+chain_itr->first+"_chain.root"); + //chain_itr->second->SavePrimitive(std::cout); // not implemented + } + } + } + + if( + vm.count("saveRootMacro") + || vm.count("saveCorrEleTree") + || vm.count("saveAddBranchTree") + || vm.count("savePUTreeWeight") + || vm.count("runDivide") + || vm.count("saveCorrEleTree") + || vm.count("saveR9TreeWeight") + ) return 0; + + eleID+=selection.c_str(); + eleID.ReplaceAll("_",""); + + //------------------------------ RooSmearer + RooArgSet args; + std::vector args_vec; + + for(std::vector::const_iterator region_itr = categories.begin(); + region_itr != categories.end(); + region_itr++){ + RooRealVar *scale_ = new RooRealVar("scale_"+*region_itr, "scale_"+*region_itr,1.0, 0.95,1.05,"GeV"); //0.9,1.1,"GeV") + scale_->setError(0.005); // 1% + // scale_->setConstant(); + // scale_->setBinning(RooBinning( + args.add(*scale_); + + TString varName=*region_itr; + TPRegexp reg("Et_[0-9]*_[0-9]*"); + reg.Substitute(varName,""); + TPRegexp reg2("energySC_[0-9]*_[0-9]*"); + reg2.Substitute(varName,""); + varName.ReplaceAll("--","-"); + if(varName.First("-")==0) varName.Remove(0,1); + + //RooRealVar *const_term_ = new RooRealVar("constTerm_"+*region_itr, "constTerm_"+*region_itr, 0.01, 0.0005, 0.05); + RooAbsReal *const_term_=NULL; + RooRealVar *const_term_v = args.getSize() ==0 ? NULL : (RooRealVar *) args.find("constTerm_"+varName); + if(const_term_v==NULL){ + if(vm.count("constTermFix")==0) const_term_v = new RooRealVar("constTerm_"+*region_itr, "constTerm_"+varName,0.00, 0.000,0.05); + else const_term_v = new RooRealVar("constTerm_"+varName, "constTerm_"+varName,0.00, 0.000,0.02); + const_term_v->setError(0.03); // 1% + //const_term_v->setConstant(true); + args.add(*const_term_v); + } + if((reg.MatchB(*region_itr) || reg2.MatchB(*region_itr) )&& vm.count("constTermFix")==1){ + const_term_ = new RooFormulaVar("constTerm_"+*region_itr, "constTerm_"+varName,"@0", *const_term_v); + const_term_v->setConstant(false); + } else const_term_ = const_term_v; + + + + RooAbsReal *alpha_=NULL; + RooRealVar *alpha_v = args.getSize() ==0 ? NULL : (RooRealVar *) args.find("alpha_"+varName); + if(alpha_v==NULL){ + alpha_v = new RooRealVar("alpha_"+varName, "alpha_"+varName,0.0, 0.,0.20); + alpha_v->setError(0.01); + alpha_v->setConstant(true); + //alpha_v->Print(); + if(!vm.count("alphaGoldFix") || !region_itr->Contains("absEta_1_1.4442-gold")){ + args.add(*alpha_v); + } + } + if(reg.MatchB(*region_itr) && vm.count("constTermFix")==1){ + if(vm.count("alphaGoldFix") && region_itr->Contains("absEta_1_1.4442-gold")){ + std::cout << "[STATUS] Fixing alpha term to low eta region " << *region_itr << std::endl; + std::cerr << "[STATUS] Fixing alpha term to low eta region " << *region_itr << std::endl; + TString lowRegionVarName=varName; lowRegionVarName.ReplaceAll("absEta_1_1.4442","absEta_0_1"); + alpha_v = (RooRealVar *)args.find("alpha_"+lowRegionVarName); + alpha_ = new RooFormulaVar("alpha_"+*region_itr, "alpha_"+lowRegionVarName,"@0", *alpha_v); + } else { + alpha_ = new RooFormulaVar("alpha_"+*region_itr, "alpha_"+varName,"@0", *alpha_v); + } + alpha_v->setConstant(false); + } else alpha_ = alpha_v; + + args_vec.push_back(RooArgSet(*scale_, *alpha_, *const_term_)); + } + + if(vm.count("onlyScale")){ + TIterator *it1=NULL; + it1 = args.createIterator(); + for(RooRealVar *var = (RooRealVar *) it1->Next(); var!=NULL; + var = (RooRealVar *) it1->Next()){ + TString name(var->GetName()); + if(name.Contains("scale")) continue; + var->setConstant(true); + } + } + + args.sort(kFALSE); + if(vm.count("smearerFit")){ + std::cout << "------------------------------ smearer parameters" << std::endl; + args.writeToStream(std::cout, kFALSE); + } + + TRandom3 g(0); + Long64_t randomInt=g.Integer(1000000); + TString filename="tmp/tmpFile-"; filename+=randomInt;filename+=".root"; + TFile *tmpFile = new TFile(filename,"recreate"); + tmpFile->cd(); + RooSmearer smearer("smearer",(tagChainMap["d"])["selected"], (tagChainMap["s"])["selected"], NULL, + categories, + args_vec, args, energyBranchName); + smearer._isDataSmeared=vm.count("isDataSmeared"); + if(vm.count("runToy")) smearer.SetPuWeight(false); + smearer.SetOnlyDiagonal(vm.count("onlyDiagonal")); + smearer._autoBin=vm.count("autoBin"); + smearer._autoNsmear=vm.count("autoNsmear"); + smearer.smearscan=vm.count("smearscan"); + //smearer.nEventsMinDiag = nEventsMinDiag; + smearer._deactive_minEventsOffDiag = nEventsMinOffDiag; + smearer.SetSmearingEt(vm.count("smearingEt")); + smearer.SetR9Weight(vm.count("useR9weight")); + smearer.SetPdfSystWeight(pdfSystWeightIndex); + smearer.SetZPtWeight(vm.count("useZPtweight")); + smearer.SetFsrWeight(vm.count("useFSRweight")); + smearer.SetWeakWeight(vm.count("useWEAKweight")); + + if(nSmearToy>0) smearer._nSmearToy = nSmearToy; + + + //------------------------------ Take the list of branches needed for the defined categories + ElectronCategory_class cutter; + cutter.energyBranchName=energyBranchName; + std::set activeBranchList; + for(std::vector::const_iterator region_itr = categories.begin(); + region_itr != categories.end(); + region_itr++){ + std::set tmpList = cutter.GetBranchNameNtuple(*region_itr); + activeBranchList.insert(tmpList.begin(),tmpList.end()); + // add also the friend branches! + } + + if(vm.count("loop")){ +// TFile *file = new TFile("evList.root","read"); + +// Loop((tagChainMap["s1"])["selected"],file); + return 0; + } + //------------------------------ ZFit_class declare and set the options + TChain *data = NULL; + TChain *mc = NULL; + if(!vm.count("smearerFit")){ + data= (tagChainMap["d"])["selected"]; + mc = (tagChainMap["s"])["selected"]; + } + + + +//------------------------------ LASER MONITORING WITH E/P ------------------------------------------------------ + + if(vm.count("laserMonitoringEP")) { + + float timeLapse = 24.; // in hours + // int t1 = 1267401600; // 1 Mar 2010 + //int t2 = 1325289600; // 31 Dec 2011 + //int t1 = 1400000000; + //int t2 = 1600000000; + + // float yMIN = 0.65; + //float yMAX = 1.10; + + + // Set style options + setTDRStyle(); + gStyle->SetPadTickX(1); + gStyle->SetPadTickY(1); + gStyle->SetOptTitle(0); + gStyle->SetOptStat(1110); + gStyle->SetOptFit(1); + + // Set fitting options + TVirtualFitter::SetDefaultFitter("Fumili2"); + + + + //----------------- + // Input parameters + + + std::cout << "\n***************************************************************************************************************************" << std::endl; + + // std::string dayMin = ""; + //std::string dayMax = ""; + std::string dayMinLabel = ""; + std::string dayMaxLabel = ""; + std::string dayZOOMLabel =""; + float absEtaMin = -1.; + float absEtaMax = -1.; + int IetaMin = -1; + int IetaMax = -1; + int IphiMin = -1; + int IphiMax = -1; + + + + + int t1 = dateToInt(dayMin); + int t2 = dateToInt(dayMax); + int t3 = dateToInt(dayZOOM); + + /* + if(argc >= 5) + { + dayMin = std::string(argv[4])+" "+std::string(argv[5])+" "+std::string(argv[6]); + dayMax = std::string(argv[7])+" "+std::string(argv[8])+" "+std::string(argv[9]); + dayMinLabel = std::string(argv[4])+"_"+std::string(argv[5])+"_"+std::string(argv[6]); + dayMaxLabel = std::string(argv[7])+"_"+std::string(argv[8])+"_"+std::string(argv[9]); + + } + if(argc >= 11) + { + yMIN = atof(argv[10]); + yMAX = atof(argv[11]); + } + if(argc >= 13) + { + absEtaMin = atof(argv[12]); + absEtaMax = atof(argv[13]); + } + if(argc >= 15) + { + IetaMin = atoi(argv[14]); + IetaMax = atoi(argv[15]); + IphiMin = atoi(argv[16]); + IphiMax = atoi(argv[17]); + } + */ + + std::cout << "EBEE: " << EBEE << std::endl; + std::cout << "evtsPerPoint: " << evtsPerPoint << std::endl; + std::cout << "useRegression: " << useRegression << std::endl; + std::cout << "dayMin: " << dayMin << std::endl; + std::cout << "dayZOOM: " << dayZOOM << std::endl; + std::cout << "dayMax: " << dayMax << std::endl; + std::cout << "yMin: " << yMIN << std::endl; + std::cout << "yMax: " << yMAX << std::endl; + std::cout << "absEtaMin: " << absEtaMin << std::endl; + std::cout << "absEtaMax: " << absEtaMax << std::endl; + std::cout << "IetaMin: " << IetaMin << std::endl; + std::cout << "IetaMax: " << IetaMax << std::endl; + std::cout << "IphiMin: " << IphiMin << std::endl; + std::cout << "IphiMax: " << IphiMax << std::endl; + std::cout << "t1: " << t1 << std::endl; + std::cout << "t2: " << t2 << std::endl; + std::cout << "t3" << t3 << std::endl; + + std::string dayZOOM = ""; + std::string dayMin = ""; + std::string dayMax = ""; + + + //------------------- + // Define in/outfiles + + std::string folderName = std::string(EBEE) + "_" + dayMinLabel + "_" + dayMaxLabel; + if( (absEtaMin != -1.) && (absEtaMax != -1.) ) + { + char absEtaBuffer[50]; + sprintf(absEtaBuffer,"_%.2f-%.2f",absEtaMin,absEtaMax); + folderName += std::string(absEtaBuffer); + } + + if( (IetaMin != -1.) && (IetaMax != -1.) && (IphiMin != -1.) && (IphiMax != -1.) ) + { + char absEtaBuffer[50]; + sprintf(absEtaBuffer,"_Ieta_%d-%d_Iphi_%d-%d",IetaMin,IetaMax,IphiMin,IphiMax); + folderName += std::string(absEtaBuffer); + } + + gSystem->mkdir(folderName.c_str()); + TFile* o = new TFile((folderName+"/"+folderName+"_histos.root").c_str(),"RECREATE"); + + + + // Get trees + std::cout << std::endl; + + /* + TChain* ntu_DA = new TChain("simpleNtupleEoverP/SimpleNtupleEoverP"); + FillChain(ntu_DA,"inputDATA.txt"); + std::cout << " DATA: " << std::setw(8) << ntu_DA->GetEntries() << " entries" << std::endl; + + TChain* ntu_MC = new TChain("simpleNtupleEoverP/SimpleNtupleEoverP"); + FillChain(ntu_MC,"inputMC.txt"); + std::cout << "REFERENCE: " << std::setw(8) << ntu_MC->GetEntries() << " entries" << std::endl; + */ + + if (data->GetEntries() == 0 || mc->GetEntries() == 0 ) + { + std::cout << "Error: At least one file is empty" << std::endl; + return -1; + } + + + + // Set branch addresses + int runNumber; + int runTime; + int nPU; + float avgLCSCEle[3], etaSCEle[3], phiSCEle[3], energySCEle[3], esEnergySCEle[3], pAtVtxGsfEle[3], energySCEle_corr[3]; + int seedXSCEle[3], seedYSCEle[3];//, seedZside; + // float seedLaserAlphaSCEle1; + + data->SetBranchStatus("*",0); + data->SetBranchStatus("runNumber",1); + data->SetBranchStatus("runTime",1); + data->SetBranchStatus("nPU",1); + data->SetBranchStatus("avgLCSCEle",1); + // data->SetBranchStatus("seedLaserAlphaSCEle1",1); + // data->SetBranchStatus("ele1_EOverP",1); + data->SetBranchStatus("etaSCEle",1); + data->SetBranchStatus("phiSCEle",1); + data->SetBranchStatus("energySCEle_must",1); + data->SetBranchStatus("energySCEle_corr",1); + data->SetBranchStatus("esEnergySCEle",1); + data->SetBranchStatus("pAtVtxGsfEle",1); + data->SetBranchStatus("seedXSCEle",1); + data->SetBranchStatus("seedYSCEle",1); + // data->SetBranchStatus("ele1_seedZside",1); + + data->SetBranchAddress("runNumber", &runNumber); + data->SetBranchAddress("runTime", &runTime); + data->SetBranchAddress("nPU", &nPU); + data->SetBranchAddress("avgLCSCEle", &avgLCSCEle[0]); + //data->SetBranchAddress("seedLaserAlphaSCEle1", &seedLaserAlphaSCEle1); + // data->SetBranchAddress("ele1_EOverP", &EoP); + data->SetBranchAddress("etaSCEle", &etaSCEle); + data->SetBranchAddress("phiSCEle", &phiSCEle); + if( useRegression < 1 ) + data->SetBranchAddress("energySCEle_must", &energySCEle); + else + data->SetBranchAddress("energySCEle_corr", &energySCEle_corr); + // data->SetBranchAddress("energySCEle_corr", &energySCEle); + data->SetBranchAddress("esEnergySCEle", &esEnergySCEle); + data->SetBranchAddress("pAtVtxGsfEle", &pAtVtxGsfEle); + data->SetBranchAddress("seedXSCEle", &seedXSCEle); + data->SetBranchAddress("seedYSCEle", &seedYSCEle); + // data->SetBranchAddress("ele1_seedZside", &seedZside); + + + mc->SetBranchStatus("*",0); + mc->SetBranchStatus("runNumber",1); + mc->SetBranchStatus("runTime",1); + mc->SetBranchStatus("nPU",1); + mc->SetBranchStatus("avgLCSCEle",1); + // mc->SetBranchStatus("seedLaserAlphaSCEle1",1); + // mc->SetBranchStatus("ele1_EOverP",1); + mc->SetBranchStatus("etaSCEle",1); + mc->SetBranchStatus("phiSCEle",1); + mc->SetBranchStatus("energySCEle_must",1); + mc->SetBranchStatus("energySCEle_corr",1); + mc->SetBranchStatus("esEnergySCEle",1); + mc->SetBranchStatus("pAtVtxGsfEle",1); + mc->SetBranchStatus("seedXSCEle",1); + mc->SetBranchStatus("seedYSCEle",1); + // mc->SetBranchStatus("ele1_seedZside",1); + + mc->SetBranchAddress("runNumber", &runNumber); + mc->SetBranchAddress("runTime", &runTime); + mc->SetBranchAddress("nPU", &nPU); + mc->SetBranchAddress("avgLCSCEle", &avgLCSCEle[0]); + //mc->SetBranchAddress("seedLaserAlphaSCEle1", &seedLaserAlphaSCEle1); + // mc->SetBranchAddress("ele1_EOverP", &EoP); + mc->SetBranchAddress("etaSCEle", &etaSCEle); + mc->SetBranchAddress("phiSCEle", &phiSCEle); + if( useRegression < 1 ) + mc->SetBranchAddress("energySCEle_must", &energySCEle); + else + mc->SetBranchAddress("energySCEle_corr", &energySCEle_corr); + // mc->SetBranchAddress("energySCEle_corr", &energySCEle); + mc->SetBranchAddress("esEnergySCEle", &esEnergySCEle); + mc->SetBranchAddress("pAtVtxGsfEle", &pAtVtxGsfEle); + mc->SetBranchAddress("seedXSCEle", &seedXSCEle); + mc->SetBranchAddress("seedYSCEle", &seedYSCEle); + // mc->SetBranchAddress("ele1_seedZside", &seedZside); + + + + + + + //-------------------------------------------------------- + // Define PU correction (to be used if useRegression == 0) + + // corr = p0 + p1 * nPU + float p0_EB; + float p1_EB; + float p0_EE; + float p1_EE; + + if( useRegression == 0 ) + { + //2012 EB + p0_EB = 0.9991; + p1_EB = 0.0001635; + //2012 EE + p0_EE = 0.9968; + p1_EE = 0.001046; + } + else + { + //2012 EB + p0_EB = 1.001; + p1_EB = -0.000143; + //2012 EE + p0_EE = 1.00327; + p1_EE = -0.000432; + } + + float p0 = -1.; + float p1 = -1.; + + if( strcmp(EBEE.c_str(),"EB") == 0 ) + { + p0 = p0_EB; + p1 = p1_EB; + } + else + { + p0 = p0_EE; + p1 = p1_EE; + } + + //2015 + p0=1.; + p1=0.; + + + + + //--------------------------------- + // Build the reference distribution + + std::cout << std::endl; + std::cout << "***** Build reference for " << EBEE << " *****" << std::endl; + + TH1F* h_template = new TH1F("template", "", 2000, 0., 5.); + + for(int ientry = 0; ientry < mc->GetEntries(); ++ientry) + { + if( (ientry%10000 == 0) ) std::cout << "reading MC entry " << ientry <<"/"<GetEntries()<< "\r" << std::endl;//std::flush; + mc->GetEntry(ientry); + + // selections + if( (strcmp(EBEE.c_str(),"EB") == 0) && (fabs(etaSCEle[0]) > 1.479) ) continue; // barrel + if( (strcmp(EBEE.c_str(),"EB_0_1") == 0) && (fabs(etaSCEle[0]) > 1.0)) continue; // inner barrel + if( (strcmp(EBEE.c_str(),"EB_1_1479") == 0) && (fabs(etaSCEle[0]) < 1.0 || fabs(etaSCEle[0]) > 1.479) ) continue; // barrel + if( (strcmp(EBEE.c_str(),"EE") == 0) && (fabs(etaSCEle[0]) < 1.479 || fabs(etaSCEle[0])>2.5) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EE_1479_2") == 0) && (fabs(etaSCEle[0]) < 1.479 || fabs(etaSCEle[0])>2.0) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EE_2_25") == 0) && (fabs(etaSCEle[0]) < 2.0 || fabs(etaSCEle[0])>2.5) ) continue; // endcap + + if( (strcmp(EBEE.c_str(),"EEp") == 0) && (etaSCEle[0] < 1.479 || etaSCEle[0]>2.5 ) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_1479_2") == 0) && (etaSCEle[0] < 1.479 || etaSCEle[0]>2.0) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_2_25") == 0) && (etaSCEle[0] < 2.0 || etaSCEle[0]>2.5) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_2_225") == 0) && (etaSCEle[0] < 2.0 || etaSCEle[0]>2.25) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_225_25") == 0) && (etaSCEle[0] < 2.25 || etaSCEle[0]>2.25) ) continue; // endcap + + if( (strcmp(EBEE.c_str(),"EEm") == 0) && (etaSCEle[0] > -1.479 || etaSCEle[0]<-2.5 ) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_1479_2") == 0) && (etaSCEle[0] > -1.479 || etaSCEle[0]<-2.0) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_2_25") == 0) && (etaSCEle[0] > -2.0 || etaSCEle[0]<-2.5) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_2_225") == 0) && (etaSCEle[0] > -2.0 || etaSCEle[0]<-2.25) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_225_25") == 0) && (etaSCEle[0] > -2.25 || etaSCEle[0]<-2.5) ) continue; // endcap + + if( (absEtaMin != -1.) && (absEtaMax != -1.) ) + { + if( (fabs(etaSCEle[0]) < absEtaMin) || (fabs(etaSCEle[0]) > absEtaMax) ) continue; + } + + if( (IetaMin != -1.) && (IetaMax != -1.) && (IphiMin != -1.) && (IphiMax != -1.) ) + { + if( (seedXSCEle[0] < IetaMin) || (seedXSCEle[0] > IetaMax) ) continue; + if( (seedYSCEle[0] < IphiMin) || (seedYSCEle[0] > IphiMax) ) continue; + } + + // PU correction + float PUCorr = (p0 + p1*nPU); + //std::cout << "p0: " << p0 << " p1: " << p1 << " nPU: " << nPU << std::endl; + + // fill the template histogram + h_template -> Fill( (energySCEle[0]-esEnergySCEle[0])/(pAtVtxGsfEle[0]-esEnergySCEle[0]) / (avgLCSCEle[0]/pow(avgLCSCEle[0],0.9)) / PUCorr ); + } + + std::cout << "Reference built for " << EBEE << " - " << h_template->GetEntries() << " events" << std::endl; + + + + + + + //--------------------- + // Loop and sort events + + std::cout << std::endl; + std::cout << "***** Sort events and define bins *****" << std::endl; + + int nEntries = data -> GetEntriesFast(); + int nSavePts = 0; + std::vector isSavedEntries(nEntries); + std::vector sortedEntries; + std::vector timeStampFirst; + + for(int ientry = 0; ientry < nEntries; ++ientry) + { + data -> GetEntry(ientry); + isSavedEntries.at(ientry) = false; + + if( (ientry%10000 == 0) ) std::cout << "reading data entry " << ientry << "\r" << std::endl;//std::flush; + + // selections + if( (strcmp(EBEE.c_str(),"EB") == 0) && (fabs(etaSCEle[0]) > 1.479) ) continue; // barrel + if( (strcmp(EBEE.c_str(),"EB_0_1") == 0) && (fabs(etaSCEle[0]) > 1.0)) continue; // inner barrel + if( (strcmp(EBEE.c_str(),"EB_1_1479") == 0) && (fabs(etaSCEle[0]) < 1.0 || fabs(etaSCEle[0]) > 1.479) ) continue; // barrel + if( (strcmp(EBEE.c_str(),"EE") == 0) && (fabs(etaSCEle[0]) < 1.479 || fabs(etaSCEle[0])>2.5) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EE_1479_2") == 0) && (fabs(etaSCEle[0]) < 1.479 || fabs(etaSCEle[0])>2.0) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EE_2_25") == 0) && (fabs(etaSCEle[0]) < 2.0 || fabs(etaSCEle[0])>2.5) ) continue; // endcap + + if( (strcmp(EBEE.c_str(),"EEp") == 0) && (etaSCEle[0] < 1.479 || etaSCEle[0]>2.5 ) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_1479_2") == 0) && (etaSCEle[0] < 1.479 || etaSCEle[0]>2.0) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_2_25") == 0) && (etaSCEle[0] < 2.0 || etaSCEle[0]>2.5) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_2_225") == 0) && (etaSCEle[0] < 2.0 || etaSCEle[0]>2.25) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_225_25") == 0) && (etaSCEle[0] < 2.25 || etaSCEle[0]>2.25) ) continue; // endcap + + if( (strcmp(EBEE.c_str(),"EEm") == 0) && (etaSCEle[0] > -1.479 || etaSCEle[0]<-2.5 ) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_1479_2") == 0) && (etaSCEle[0] > -1.479 || etaSCEle[0]<-2.0) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_2_25") == 0) && (etaSCEle[0] > -2.0 || etaSCEle[0]<-2.5) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_2_225") == 0) && (etaSCEle[0] > -2.0 || etaSCEle[0]<-2.25) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_225_25") == 0) && (etaSCEle[0] > -2.25 || etaSCEle[0]<-2.5) ) continue; // endcap + + if( (absEtaMin != -1.) && (absEtaMax != -1.) ) + { + if( (fabs(etaSCEle[0]) < absEtaMin) || (fabs(etaSCEle[0]) > absEtaMax) ) continue; + } + + if( (IetaMin != -1.) && (IetaMax != -1.) && (IphiMin != -1.) && (IphiMax != -1.) ) + { + if( (seedXSCEle[0] < IetaMin) || (seedXSCEle[0] > IetaMax) ) continue; + if( (seedYSCEle[0] < IphiMin) || (seedYSCEle[0] > IphiMax) ) continue; + } + + if( runTime < t1 ) continue; + if( runTime > t2 ) continue; + + if( avgLCSCEle[0] <= 0. ) continue; + + isSavedEntries.at(ientry) = true; + + + // fill sorter + Sorter dummy; + dummy.time = runTime; + dummy.entry = ientry; + sortedEntries.push_back(dummy); + + ++nSavePts; + } + + // sort events + std::sort(sortedEntries.begin(),sortedEntries.end(),Sorter()); + std::cout << "Data sorted in " << EBEE << " - " << nSavePts << " events" << std::endl; + + std::map antiMap; + for(unsigned int iSaved = 0; iSaved < sortedEntries.size(); ++iSaved) + antiMap[sortedEntries.at(iSaved).entry] = iSaved; + + + //--------------------- + // Loop and define bins + + // "wide" bins - find events with time separation bigger than 1 day + int nWideBins = 1; + std::vector wideBinEntryMax; + int timeStampOld = -1; + + // TEventList* evlist=new TEventList("events"); + // data->Draw(">>events","","goff"); + // TEventList* evlist = (TEventList*) gDirectory->Get("events"); + + wideBinEntryMax.push_back(0); + for(int iSaved = 0; iSaved < nSavePts; ++iSaved) + { + if( iSaved%10000 == 0 ) std::cout << "reading saved entry " << iSaved << "\r" << std::endl;//std::flush; + data->GetEntry(sortedEntries[iSaved].entry); + // data->GetEntry(evlist->GetEntry(sortedEntries[iSaved].entry)); + + if( iSaved == 0 ) + { + timeStampOld = runTime; + continue; + } + + if( (runTime-timeStampOld)/3600. > timeLapse ) + { + ++nWideBins; + wideBinEntryMax.push_back(iSaved-1); + } + + timeStampOld = runTime; + } + std::cout << std::endl; + wideBinEntryMax.push_back(nSavePts); + + + // bins with approximatively evtsPerPoint events per bin + int nBins = 0; + std::vector binEntryMax; + + binEntryMax.push_back(0); + for(int wideBin = 0; wideBin < nWideBins; ++wideBin) + { + int nTempBins = std::max(1,int( (wideBinEntryMax.at(wideBin+1)-wideBinEntryMax.at(wideBin))/evtsPerPoint )); + int nTempBinEntries = int( (wideBinEntryMax.at(wideBin+1)-wideBinEntryMax.at(wideBin))/nTempBins ); + + for(int tempBin = 0; tempBin < nTempBins; ++tempBin) + { + ++nBins; + if( tempBin < nTempBins - 1 ) + binEntryMax.push_back( wideBinEntryMax.at(wideBin) + (tempBin+1)*nTempBinEntries ); + else + binEntryMax.push_back( wideBinEntryMax.at(wideBin+1) ); + } + } + + std::cout << "nBins = " << nBins << std::endl; + //for(int bin = 0; bin < nBins; ++bin) + // std::cout << "bin: " << bin + // << " entry min: " << setw(6) << binEntryMax.at(bin) + // << " entry max: " << setw(6) << binEntryMax.at(bin+1) + // << " events: " << setw(6) << binEntryMax.at(bin+1)-binEntryMax.at(bin) + // << std::endl; + + + + + + + //--------------------- + // histogram definition + + TH1F* h_scOccupancy_eta = new TH1F("h_scOccupancy_eta","", 298, -2.6, 2.6); + TH1F* h_scOccupancy_phi = new TH1F("h_scOccupancy_phi","", 363, -3.1765, 3.159); + SetHistoStyle(h_scOccupancy_eta); + SetHistoStyle(h_scOccupancy_phi); + + TH2F* h_seedOccupancy_EB = new TH2F("h_seedOccupancy_EB","", 171, -86., 85., 361, 0.,361.); + TH2F* h_seedOccupancy_EEp = new TH2F("h_seedOccupancy_EEp","", 101, 0.,101., 100, 0.,101.); + TH2F* h_seedOccupancy_EEm = new TH2F("h_seedOccupancy_EEm","", 101, 0.,101., 100, 0.,101.); + SetHistoStyle(h_seedOccupancy_EB); + SetHistoStyle(h_seedOccupancy_EEp); + SetHistoStyle(h_seedOccupancy_EEm); + + TH1F* h_EoP_spread = new TH1F("h_EoP_spread","",100,yMIN,yMAX); + TH1F* h_EoC_spread = new TH1F("h_EoC_spread","",100,yMIN,yMAX); + TH1F* h_EoP_spread_run = new TH1F("h_EoP_spread_run","",100,yMIN,yMAX); + TH1F* h_EoC_spread_run = new TH1F("h_EoC_spread_run","",100,yMIN,yMAX); + SetHistoStyle(h_EoP_spread,"EoP"); + SetHistoStyle(h_EoC_spread,"EoC"); + SetHistoStyle(h_EoP_spread_run,"EoP"); + SetHistoStyle(h_EoC_spread_run,"EoC"); + + TH1F* h_EoP_chi2 = new TH1F("h_EoP_chi2","",50,0.,5.); + TH1F* h_EoC_chi2 = new TH1F("h_EoC_chi2","",50,0.,5.); + SetHistoStyle(h_EoP_chi2,"EoP"); + SetHistoStyle(h_EoC_chi2,"EoC"); + + TH1F** h_EoP = new TH1F*[nBins]; + TH1F** h_EoC = new TH1F*[nBins]; + TH1F** h_Las = new TH1F*[nBins]; + TH1F** h_Tsp = new TH1F*[nBins]; + TH1F** h_Cvl = new TH1F*[nBins]; + + for(int i = 0; i < nBins; ++i) + { + char histoName[80]; + + sprintf(histoName, "EoP_%d", i); + h_EoP[i] = new TH1F(histoName, histoName, 2000, 0., 5.); + SetHistoStyle(h_EoP[i],"EoP"); + + sprintf(histoName, "EoC_%d", i); + h_EoC[i] = new TH1F(histoName, histoName, 2000, 0., 5.); + SetHistoStyle(h_EoC[i],"EoC"); + + sprintf(histoName, "Las_%d", i); + h_Las[i] = new TH1F(histoName, histoName, 500, 0.5, 1.5); + + sprintf(histoName, "Tsp_%d", i); + h_Tsp[i] = new TH1F(histoName, histoName, 500, 0.5, 1.5); + + } + + + // function definition + TF1** f_EoP = new TF1*[nBins]; + TF1** f_EoC = new TF1*[nBins]; + + + // graphs definition + TGraphAsymmErrors* g_fit = new TGraphAsymmErrors(); + TGraphAsymmErrors* g_c_fit = new TGraphAsymmErrors(); + + TGraphAsymmErrors* g_fit_run = new TGraphAsymmErrors(); + TGraphAsymmErrors* g_c_fit_run = new TGraphAsymmErrors(); + + TGraph* g_las = new TGraph(); + + TGraphErrors* g_LT = new TGraphErrors(); + + g_fit->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00"); + g_fit->GetXaxis()->SetTimeDisplay(1); + g_c_fit->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00"); + g_c_fit->GetXaxis()->SetTimeDisplay(1); + g_las->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00"); + g_las->GetXaxis()->SetTimeDisplay(1); + g_LT->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00"); + g_LT->GetXaxis()->SetTimeDisplay(1); + + + + + + + //------------------------------------ + // loop on the saved and sorted events + + std::cout << std::endl; + std::cout << "***** Fill and fit histograms *****" << std::endl; + + std::vector Entries(nBins); + std::vector AveTime(nBins); + std::vector MinTime(nBins); + std::vector MaxTime(nBins); + std::vector AveRun(nBins); + std::vector MinRun(nBins); + std::vector MaxRun(nBins); + std::vector AveLT(nBins); + std::vector AveLT2(nBins); + + int iSaved = -1; + for(int ientry = 0; ientry < nEntries; ++ientry) + { + if( (ientry%100000 == 0) ) std::cout << "reading entry " << ientry << "\r" << std::endl;//std::flush; + + if( isSavedEntries.at(ientry) == false ) continue; + + ++iSaved; + + int iSaved = antiMap[ientry]; + int bin = -1; + for(bin = 0; bin < nBins; ++bin) + if( iSaved >= binEntryMax.at(bin) && iSaved < binEntryMax.at(bin+1) ) + break; + + //std::cout << "bin = " << bin << " iSaved = "<< iSaved << std::endl; + data->GetEntry(ientry); + + + + Entries[bin] += 1; + + if( iSaved == binEntryMax.at(bin)+1 ) MinTime[bin] = runTime; + if( iSaved == binEntryMax.at(bin+1)-1 ) MaxTime[bin] = runTime; + AveTime[bin] += runTime; + + if( iSaved == binEntryMax.at(bin)+1 ) MinRun[bin] = runNumber; + if( iSaved == binEntryMax.at(bin+1)-1 ) MaxRun[bin] = runNumber; + AveRun[bin] += runNumber; + + // float LT = (-1. / seedLaserAlphaSCEle1 * log(avgLCSCEle[0])); + float LT = 1.; + AveLT[bin] += LT; + AveLT2[bin] += LT*LT; + + // PU correction + float PUCorr = (p0 + p1*nPU); + + // fill the histograms + (h_EoP[bin]) -> Fill( (energySCEle[0]-esEnergySCEle[0])/(pAtVtxGsfEle[0]-esEnergySCEle[0]) / pow(avgLCSCEle[0],0.9) / PUCorr); + (h_EoC[bin]) -> Fill( (energySCEle[0]-esEnergySCEle[0])/(pAtVtxGsfEle[0]-esEnergySCEle[0]) / (avgLCSCEle[0]/pow(avgLCSCEle[0],0.9)) / PUCorr ); + + (h_Las[bin]) -> Fill(pow(avgLCSCEle[0],0.9)); + (h_Tsp[bin]) -> Fill(1./pow(avgLCSCEle[0],0.9)); + + h_scOccupancy_eta -> Fill(etaSCEle[0]); + h_scOccupancy_phi -> Fill(phiSCEle[0]); + if(fabs(etaSCEle[0])<1.449) + h_seedOccupancy_EB -> Fill(seedXSCEle[0],seedYSCEle[0]); + else if(etaSCEle[0]>1.449) + h_seedOccupancy_EEp -> Fill(seedXSCEle[0],seedYSCEle[0]); + else if(etaSCEle[0]<-1.449) + h_seedOccupancy_EEm -> Fill(seedXSCEle[0],seedYSCEle[0]); + } + + for(int bin = 0; bin < nBins; ++bin) + { + AveTime[bin] = 1. * AveTime[bin] / (binEntryMax.at(bin+1)-binEntryMax.at(bin)); + AveRun[bin] = 1. * AveRun[bin] / (binEntryMax.at(bin+1)-binEntryMax.at(bin)); + AveLT[bin] = 1. * AveLT[bin] / (binEntryMax.at(bin+1)-binEntryMax.at(bin)); + AveLT2[bin] = 1. * AveLT2[bin] / (binEntryMax.at(bin+1)-binEntryMax.at(bin)); + //std::cout << date << " " << AveTime[i] << " " << MinTime[i] << " " << MaxTime[i] << std::endl; + } + + + + + + + int rebin = 2; + if( strcmp(EBEE.c_str(),"EE") == 0 ) rebin *= 2; + + h_template -> Rebin(rebin); + + + + float EoP_scale = 0.; + float EoP_err = 0.; + int EoP_nActiveBins = 0; + + float EoC_scale = 0.; + float EoC_err = 0.; + int EoC_nActiveBins = 0; + + float LCInv_scale = 0; + + std::vector validBins; + for(int i = 0; i < nBins; ++i) + { + bool isValid = true; + + h_EoP[i] -> Rebin(rebin); + h_EoC[i] -> Rebin(rebin); + + + + //------------------------------------ + // Fill the graph for uncorrected data + + // define the fitting function + // N.B. [0] * ( [1] * f( [1]*(x-[2]) ) ) + + //o -> cd(); + char convolutionName[50]; + sprintf(convolutionName,"h_convolution_%d",i); + //h_Cvl[i] = ConvoluteTemplate(std::string(convolutionName),h_template,h_Las[i],32768,-5.,5.); + h_Cvl[i] = MellinConvolution(std::string(convolutionName),h_template,h_Tsp[i]); + + histoFunc* templateHistoFunc = new histoFunc(h_template); + histoFunc* templateConvolutedHistoFunc = new histoFunc(h_Cvl[i]); + char funcName[50]; + + sprintf(funcName,"f_EoP_%d",i); + + if( strcmp(EBEE.c_str(),"EB") == 0 ) + f_EoP[i] = new TF1(funcName, templateConvolutedHistoFunc, 0.8*(h_Tsp[i]->GetMean()), 1.4*(h_Tsp[i]->GetMean()), 3, "histoFunc"); + else + f_EoP[i] = new TF1(funcName, templateConvolutedHistoFunc, 0.75*(h_Tsp[i]->GetMean()), 1.5*(h_Tsp[i]->GetMean()), 3, "histoFunc"); + + f_EoP[i] -> SetParName(0,"Norm"); + f_EoP[i] -> SetParName(1,"Scale factor"); + f_EoP[i] -> SetLineWidth(1); + f_EoP[i] -> SetNpx(10000); + + double xNorm = h_EoP[i]->GetEntries()/h_template->GetEntries() * + h_EoP[i]->GetBinWidth(1)/h_template->GetBinWidth(1); + + f_EoP[i] -> FixParameter(0, xNorm); + f_EoP[i] -> SetParameter(1, 1.); + f_EoP[i] -> FixParameter(2, 0.); + f_EoP[i] -> SetLineColor(kRed+2); + + int fStatus = 0; + int nTrials = 0; + TFitResultPtr rp; + + rp = h_EoP[i] -> Fit(funcName, "ERLS+"); + while( (fStatus != 0) && (nTrials < 10) ) + { + rp = h_EoP[i] -> Fit(funcName, "ERLS+"); + fStatus = rp; + if(fStatus == 0) break; + ++nTrials; + } + + // fill the graph + double eee = f_EoP[i]->GetParError(1); + //float k = f_EoP[i]->GetParameter(1); + float k = f_EoP[i]->GetParameter(1) / h_Tsp[i]->GetMean(); //needed when using mellin's convolution + + /* + std::cout << i <<"--nocorr---- "<< 1./k << std::endl; + std::cout <<" condizione 1: " << h_EoP[i]->GetEntries() << " fStatus: " << fStatus << " eee: " << eee << "con eee che ci piace essere maggiore di : " << 0.05*h_template->GetRMS()/sqrt(evtsPerPoint) << std::endl ; + getchar(); + */ + + + // if( (h_EoP[i]->GetEntries() > 3) && (fStatus == 0) && (eee > 0.05*h_template->GetRMS()/sqrt(evtsPerPoint)) ) + if( (h_EoP[i]->GetEntries() > 500) && (fStatus == 0) ) + { + float date = (float)AveTime[i]; + float dLow = (float)(AveTime[i]-MinTime[i]); + float dHig = (float)(MaxTime[i]-AveTime[i]); + float run = (float)AveRun[i]; + float rLow = (float)(AveRun[i]-MinRun[i]); + float rHig = (float)(MaxRun[i]-AveRun[i]); + + g_fit -> SetPoint(i, date , 1./k); + g_fit -> SetPointError(i, dLow , dHig, eee/k/k, eee/k/k); + + g_fit_run -> SetPoint(i, run , 1./k); + g_fit_run -> SetPointError(i, rLow , rHig, eee/k/k, eee/k/k); + + std::cout <<"************-------------------*****************" < Fill(f_EoP[i]->GetChisquare()/f_EoP[i]->GetNDF()); + + EoP_scale += 1./k; + EoP_err += eee/k/k; + ++EoP_nActiveBins; + } + else + { + std::cout << "Fitting uncorrected time bin: " << i << " Fail status: " << fStatus << " sigma: " << eee << std::endl; + isValid = false; + } + + //---------------------------------- + // Fill the graph for corrected data + + // define the fitting function + // N.B. [0] * ( [1] * f( [1]*(x-[2]) ) ) + + sprintf(funcName,"f_EoC_%d",i); + if( strcmp(EBEE.c_str(),"EB") == 0 ) + f_EoC[i] = new TF1(funcName, templateHistoFunc, 0.8, 1.4, 3, "histoFunc"); + else + f_EoC[i] = new TF1(funcName, templateHistoFunc, 0.75, 1.5, 3, "histoFunc"); + f_EoC[i] -> SetParName(0,"Norm"); + f_EoC[i] -> SetParName(1,"Scale factor"); + f_EoC[i] -> SetLineWidth(1); + f_EoC[i] -> SetNpx(10000); + + xNorm = h_EoC[i]->GetEntries()/h_template->GetEntries() * + h_EoC[i]->GetBinWidth(1)/h_template->GetBinWidth(1); + + f_EoC[i] -> FixParameter(0, xNorm); + f_EoC[i] -> SetParameter(1, 0.99); + f_EoC[i] -> FixParameter(2, 0.); + f_EoC[i] -> SetLineColor(kGreen+2); + + + rp = h_EoC[i] -> Fit(funcName, "ERLS+"); + fStatus = rp; + nTrials = 0; + while( (fStatus != 0) && (nTrials < 10) ) + { + rp = h_EoC[i] -> Fit(funcName, "ERLS+"); + fStatus = rp; + if(fStatus == 0) break; + ++nTrials; + } + + + // fill the graph + k = f_EoC[i]->GetParameter(1); + eee = f_EoC[i]->GetParError(1); + + /* std::cout << i <<"--corr---- "<< 1./k << std::endl; + std::cout <<" condizione 1: " << h_EoP[i]->GetEntries() << " fStatus: " << fStatus << " eee: " << eee << "con eee che ci piace essere maggiore di : " << 0.05*h_template->GetRMS()/sqrt(evtsPerPoint) << std::endl ; + getchar(); + */ + + + if( (h_EoC[i]->GetEntries() > 500) && (fStatus == 0) ) + // if( (h_EoC[i]->GetEntries() > 10) && (fStatus == 0) && (eee > 0.05*h_template->GetRMS()/sqrt(evtsPerPoint)) ) + { + float date = (float)AveTime[i]; + float dLow = (float)(AveTime[i]-MinTime[i]); + float dHig = (float)(MaxTime[i]-AveTime[i]); + float run = (float)AveRun[i]; + float rLow = (float)(AveRun[i]-MinRun[i]); + float rHig = (float)(MaxRun[i]-AveRun[i]); + + g_c_fit -> SetPoint(i, date , 1./k); + g_c_fit -> SetPointError(i, dLow , dHig , eee/k/k, eee/k/k); + + g_c_fit_run -> SetPoint(i, run , 1./k); + g_c_fit_run -> SetPointError(i, rLow , rHig, eee/k/k, eee/k/k); + std::cout <<"************-------------------*****************" < Fill(f_EoC[i]->GetChisquare()/f_EoP[i]->GetNDF()); + + EoC_scale += 1./k; + EoC_err += eee/k/k; + ++EoC_nActiveBins; + } + else + { + std::cout << "Fitting corrected time bin: " << i << " Fail status: " << fStatus << " sigma: " << eee << std::endl; + isValid = false; + } + + if( isValid == true ) validBins.push_back(i); + } + + EoP_scale /= EoP_nActiveBins; + EoP_err /= EoP_nActiveBins; + + EoC_scale /= EoC_nActiveBins; + EoC_err /= EoC_nActiveBins; + + + + + + + //---------------------------------------- + // Fill the graph for avg laser correction + + //fede + for(unsigned int itr = 0; itr < validBins.size(); ++itr) + { + int i = validBins.at(itr); + g_las -> SetPoint(itr, (float)AveTime[i], h_Tsp[i]->GetMean()); + g_LT -> SetPoint(itr, (float)AveTime[i], AveLT[i] ); + g_LT -> SetPointError(itr, 0., sqrt(AveLT2[i]-AveLT[i]*AveLT[i]) / sqrt(Entries[i]) ); + + LCInv_scale += h_Tsp[i]->GetMean(); + } + + LCInv_scale /= validBins.size(); + + + + + + + //--------------- + // Rescale graphs + + float yscale = 1.; + //float yscale = 1./EoC_scale; + + for(unsigned int itr = 0; itr < validBins.size(); ++itr) + { + double x,y; + g_fit -> GetPoint(itr,x,y); + g_fit -> SetPoint(itr,x,y*yscale); + if ( (x > t1) && (x < t2) ) h_EoP_spread -> Fill(y*yscale); + + g_c_fit -> GetPoint(itr,x,y); + g_c_fit -> SetPoint(itr,x,y*yscale); + if ( (x > t1) && (x < t2) ) h_EoC_spread -> Fill(y*yscale); + + g_fit_run -> GetPoint(itr,x,y); + g_fit_run -> SetPoint(itr,x,y*yscale); + if ( (x > t1) && (x < t2) ) h_EoP_spread_run -> Fill(y*yscale); + + g_c_fit_run -> GetPoint(itr,x,y); + g_c_fit_run -> SetPoint(itr,x,y*yscale); + if ( (x > t1) && (x < t2) ) h_EoC_spread_run -> Fill(y*yscale); + + g_las -> GetPoint(itr,x,y); + g_las -> SetPoint(itr,x,y*yscale*EoP_scale/LCInv_scale); + } + TF1 EoC_pol0("EoC_pol0","pol0",t1,t2); + EoC_pol0.SetLineColor(kGreen+2); + EoC_pol0.SetLineWidth(2); + EoC_pol0.SetLineStyle(2); + g_c_fit -> Fit("EoC_pol0","QNR"); + + + + + + + + + //---------------------------- + // Print out global quantities + + std::cout << std::endl; + std::cout << "***** Mean scales and errors *****" << std::endl; + std::cout << std::fixed; + std::cout << std::setprecision(4); + std::cout << "Mean EoP scale: " << std::setw(6) << EoP_scale << " mean EoP error: " << std::setw(8) << EoP_err << std::endl; + std::cout << "Mean EoC scale: " << std::setw(6) << EoC_scale << " mean EoC error: " << std::setw(8) << EoC_err << std::endl; + std::cout << "Mean 1/LC scale: " << std::setw(6) << LCInv_scale << std::endl; + + + + + + + //----------------- + // Occupancy plots + //----------------- + + TCanvas* c_scOccupancy = new TCanvas("c_scOccupancy","SC occupancy",0,0,1000,500); + c_scOccupancy -> Divide(2,1); + + c_scOccupancy -> cd(1); + h_scOccupancy_eta -> GetXaxis() -> SetTitle("sc #eta"); + h_scOccupancy_eta -> GetYaxis() -> SetTitle("events"); + h_scOccupancy_eta -> Draw(); + + c_scOccupancy -> cd(2); + h_scOccupancy_phi -> GetXaxis() -> SetTitle("sc #phi"); + h_scOccupancy_phi -> GetYaxis() -> SetTitle("events"); + h_scOccupancy_phi -> Draw(); + + TCanvas* c_seedOccupancy = new TCanvas("c_seedOccupancy","seed occupancy",0,0,1500,500); + c_seedOccupancy -> Divide(3,1); + + c_seedOccupancy -> cd(1); + h_seedOccupancy_EB -> GetXaxis() -> SetTitle("seed i#eta"); + h_seedOccupancy_EB -> GetYaxis() -> SetTitle("seed i#phi"); + h_seedOccupancy_EB -> Draw("COLZ"); + + c_seedOccupancy -> cd(2); + h_seedOccupancy_EEp -> GetXaxis() -> SetTitle("seed ix"); + h_seedOccupancy_EEp -> GetYaxis() -> SetTitle("seed iy"); + h_seedOccupancy_EEp -> Draw("COLZ"); + + c_seedOccupancy -> cd(3); + h_seedOccupancy_EEm -> GetXaxis() -> SetTitle("seed ix"); + h_seedOccupancy_EEm -> GetYaxis() -> SetTitle("seed iy"); + h_seedOccupancy_EEm -> Draw("COLZ"); + + + + //----------- + // Chi2 plots + //----------- + + TCanvas* c_chi2 = new TCanvas("c_chi2","fit chi2",0,0,500,500); + c_chi2 -> cd(); + + h_EoC_chi2 -> GetXaxis() -> SetTitle("#chi^{2}/N_{dof}"); + h_EoC_chi2 -> Draw(""); + gPad -> Update(); + + TPaveStats* s_EoC = new TPaveStats; + s_EoC = (TPaveStats*)(h_EoC_chi2->GetListOfFunctions()->FindObject("stats")); + s_EoC -> SetStatFormat("1.4g"); + s_EoC -> SetTextColor(kGreen+2); + s_EoC->SetY1NDC(0.59); + s_EoC->SetY2NDC(0.79); + s_EoC -> Draw("sames"); + gPad -> Update(); + + h_EoP_chi2 -> GetXaxis() -> SetTitle("#chi^{2}/N_{dof}"); + h_EoP_chi2 -> Draw("sames"); + gPad -> Update(); + + TPaveStats* s_EoP = new TPaveStats; + s_EoP = (TPaveStats*)(h_EoP_chi2->GetListOfFunctions()->FindObject("stats")); + s_EoP -> SetStatFormat("1.4g"); + s_EoP -> SetTextColor(kRed+2); + s_EoP->SetY1NDC(0.79); + s_EoP->SetY2NDC(0.99); + s_EoP -> Draw("sames"); + gPad -> Update(); + + //ciao + //------------------- + // RMS vs Num evts -BARREL + //------------------- + double x[13]={2.,4.,6.,8.,10.,12.,14.,16.,18.,20.,22.,24.,30.}; + double y[13]={0.001049,0.001114,0.0009367,0.0008480,0.0007669,0.0007892,0.0006699,0.0006473,0.0006235,0.0005903,0.0005815,0.0005459,0.0005506}; + + TCanvas* RMSeb = new TCanvas("plot", "plot",0,0,500,500); + TGraph* gRMSeb = new TGraph(13,x,y); + + gRMSeb->Draw("APC"); + gRMSeb -> SetMarkerColor(38); + gRMSeb -> SetLineColor(38); + gRMSeb->GetXaxis()->SetTitle("Number of Events - Barrel"); + gRMSeb->GetYaxis()->SetTitle("RMS"); + + RMSeb -> Print((folderName+"/"+folderName+"_RMSeb"+".png").c_str(),"png"); + RMSeb -> Print((folderName+"/"+folderName+"_RMSeb"+".pdf").c_str(),"pdf"); + + //------------------- + // RMS vs Num evts -ENDCAP + //------------------- + + double xx[11]={2.,4.,6.,8.,10.,12.,14.,16.,18.,20.,22.}; + double yy[11]={0.007234,0.005759,0.004174,0.004255,0.003833,0.004037,0.003912,0.004251,0.003598,0.004067,0.004138}; + + TCanvas* RMSee = new TCanvas("plot", "plot",0,0,500,500); + TGraph* gRMSee = new TGraph(11,xx,yy); + + gRMSee->Draw("APC"); + gRMSee -> SetMarkerColor(38); + gRMSee -> SetLineColor(38); + gRMSee->GetXaxis()->SetTitle("Number of Events - Endcap"); + gRMSee->GetYaxis()->SetTitle("RMS"); + + + RMSee -> Print((folderName+"/"+folderName+"_RMSee"+".png").c_str(),"png"); + RMSee -> Print((folderName+"/"+folderName+"_RMSee"+".pdf").c_str(),"pdf"); + + + //ciao + //------------------- + // histos + //------------------- + + + /* + for ( int i = 0; i < nBins; ++i) + { + + TCanvas* histoEoP = new TCanvas("histo","histo",0,0,500,500); + histoEoP -> cd(); + + h_EoP[i] -> Draw(); + f_EoP[i] -> SetLineWidth(2); + f_EoP[i] -> SetLineColor(4); + f_EoP[i] -> Draw("same"); + // histoEoP -> Update(); + + histoEoP -> Print((folderName+"/"+folderName+"_histoEoP"+std::to_string(i)+".png").c_str(),"png"); + histoEoP -> Print((folderName+"/"+folderName+"_histoEoP"+std::to_string(i)+".pdf").c_str(),"pdf"); + + + TCanvas* histoEoC = new TCanvas("histo","histo",0,0,500,500); + histoEoC -> cd(); + + h_EoC[i] -> Draw(); + f_EoC[i] -> SetLineWidth(2); + f_EoC[i] -> SetLineColor(4); + f_EoC[i] -> Draw("same"); + //histoEoC -> Update(); + + histoEoC -> Print((folderName+"/"+folderName+"_histoEoC"+to_string(i)+".png").c_str(),"png"); + histoEoC -> Print((folderName+"/"+folderName+"_histoEoC"+to_string(i)+".pdf").c_str(),"pdf"); + + } + */ + + //------------------- + // Final Plot vs date + //------------------- + + TCanvas* cplot = new TCanvas("cplot", "history plot vs date",100,100,1000,500); + cplot->cd(); + + TPad *cLeft = new TPad("pad_0","pad_0",0.00,0.00,0.75,1.00); + TPad *cRight = new TPad("pad_1","pad_1",0.75,0.00,1.00,1.00); + + cLeft->SetLeftMargin(0.15); + cLeft->SetRightMargin(0.025); + cRight->SetLeftMargin(0.025); + + cLeft->Draw(); + cRight->Draw(); + + float tYoffset = 1.0; + float labSize = 0.05; + float labSize2 = 0.06; + + cLeft->cd(); + + cLeft->SetGridx(); + cLeft->SetGridy(); + + TH1F *hPad = (TH1F*)gPad->DrawFrame(t1,0.9,t2,1.05); + + //hPad->GetXaxis()->SetLimits(t3,t2); + hPad->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00"); + hPad->GetXaxis()->SetTimeDisplay(1); + hPad->GetXaxis() -> SetRangeUser(MinTime[0]-43200,MaxTime[nBins-1]+43200); + hPad->GetXaxis()->SetTitle("date (day/month)"); + //ciao + //hPad->GetXaxis()->SetLabelSize(0.025); + + if( strcmp(EBEE.c_str(),"EB") == 0 ) + hPad->GetYaxis()->SetTitle("Relative E/p scale"); + else + hPad->GetYaxis()->SetTitle("Relative E/p scale"); + hPad->GetYaxis()->SetTitleOffset(tYoffset); + hPad->GetXaxis()->SetTitleOffset(0.8); + hPad->GetXaxis()->SetLabelSize(0.03); + hPad->GetXaxis()->SetTitleSize(labSize2); + hPad->GetYaxis()->SetLabelSize(labSize); + hPad->GetYaxis()->SetTitleSize(labSize2); + hPad -> SetMinimum(yMIN); + hPad -> SetMaximum(yMAX); + + // draw history plot + g_fit -> SetMarkerStyle(24); + g_fit -> SetMarkerSize(0.7); + g_fit -> SetMarkerColor(kRed+2); + g_fit -> SetLineColor(kRed+2); + g_fit -> Draw("P"); + g_c_fit -> SetMarkerStyle(20); + g_c_fit -> SetMarkerColor(kGreen+2); + g_c_fit -> SetLineColor(kGreen+2); + g_c_fit -> SetMarkerSize(0.7); + g_c_fit -> Draw("EP,same"); + g_las -> SetLineColor(kAzure-2); + g_las -> SetLineWidth(2); + // g_las -> Draw("L,same"); + + TLegend* legend = new TLegend(0.60,0.78,0.90,0.94); + legend -> SetLineColor(kWhite); + legend -> SetLineWidth(0); + legend -> SetFillColor(kWhite); + legend -> SetFillStyle(0); + legend -> SetTextFont(42); + legend -> SetTextSize(0.04); + legend -> AddEntry(g_c_fit,"with LM correction","PL"); + legend -> AddEntry(g_fit, "without LM correction","PL"); + // legend -> AddEntry(g_las, "1 / LM correction","L"); + legend -> Draw("same"); + + char latexBuffer[250]; + + sprintf(latexBuffer,"CMS 2016 Preliminary"); + TLatex* latex = new TLatex(0.18,0.89,latexBuffer); + latex -> SetNDC(); + latex -> SetTextFont(62); + latex -> SetTextSize(0.05); + latex -> Draw("same"); + + //sprintf(latexBuffer,"#sqrt{s} = 8 TeV L = 3.95 fb^{-1}"); + sprintf(latexBuffer,"#sqrt{s} = 13 TeV, L =%s fb^{-1} ", LUMI.c_str()); + + // sprintf(latexBuffer, LUMI.c_str()); + TLatex* latex2 = new TLatex(0.18,0.84,latexBuffer); + latex2 -> SetNDC(); + latex2 -> SetTextFont(42); + latex2 -> SetTextSize(0.05); + latex2 -> Draw("same"); + + if( strcmp(EBEE.c_str(),"EB") == 0 || strcmp(EBEE.c_str(),"EB_0_1") == 0 || strcmp(EBEE.c_str(),"EB_1_1479") == 0) + sprintf(latexBuffer,"ECAL Barrel"); + else + sprintf(latexBuffer,"ECAL Endcap"); + TLatex* latex3 = new TLatex(0.18,0.19,latexBuffer); + latex3 -> SetNDC(); + latex3 -> SetTextFont(42); + latex3 -> SetTextSize(0.05); + latex3 -> Draw("same"); + + //sprintf(latexBuffer,"%.2E events",1.*nSavePts); + //TLatex* latex4 = new TLatex(0.18,0.24,latexBuffer); + //latex4 -> SetNDC(); + //latex4 -> SetTextFont(42); + //latex4 -> SetTextSize(0.04); + //latex4 -> Draw("same"); + // + //sprintf(latexBuffer,"%d events/bin - %d bins",evtsPerPoint,nBins); + //TLatex* latex5 = new TLatex(0.18,0.19,latexBuffer); + //latex5 -> SetNDC(); + //latex5 -> SetTextFont(42); + //latex5 -> SetTextSize(0.04); + //latex5 -> Draw("same"); + + + cRight -> cd(); + + TPaveStats* s_EoP_spread = new TPaveStats(); + TPaveStats* s_EoC_spread = new TPaveStats(); + + + h_EoC_spread -> SetFillStyle(3001); + h_EoC_spread -> SetFillColor(kGreen+2); + h_EoC_spread->GetYaxis()->SetLabelSize(0.09); + h_EoC_spread->GetYaxis()->SetLabelOffset(-0.03); + h_EoC_spread->GetYaxis()->SetTitleSize(0.08); + h_EoC_spread->GetYaxis()->SetNdivisions(505); + h_EoC_spread->GetXaxis()->SetLabelOffset(1000); + + h_EoC_spread -> Draw("hbar"); + gPad -> Update(); + + s_EoC_spread = (TPaveStats*)(h_EoC_spread->GetListOfFunctions()->FindObject("stats")); + s_EoC_spread -> SetStatFormat("1.4g"); + s_EoC_spread->SetX1NDC(0.06); //new x start position + s_EoC_spread->SetX2NDC(0.71); //new x end position + s_EoC_spread->SetY1NDC(0.43); //new x start position + s_EoC_spread->SetY2NDC(0.34); //new x end position + s_EoC_spread -> SetOptStat(1100); + s_EoC_spread ->SetTextColor(kGreen+2); + s_EoC_spread ->SetTextSize(0.08); + s_EoC_spread -> Draw("sames"); + + + h_EoP_spread -> SetFillStyle(3001); + h_EoP_spread -> SetFillColor(kRed+2); + h_EoP_spread -> Draw("hbarsames"); + gPad -> Update(); + s_EoP_spread = (TPaveStats*)(h_EoP_spread->GetListOfFunctions()->FindObject("stats")); + s_EoP_spread -> SetStatFormat("1.4g"); + s_EoP_spread->SetX1NDC(0.06); //new x start position + s_EoP_spread->SetX2NDC(0.71); //new x end position + s_EoP_spread->SetY1NDC(0.33); //new x start position + s_EoP_spread->SetY2NDC(0.24); //new x end position + s_EoP_spread ->SetOptStat(1100); + s_EoP_spread ->SetTextColor(kRed+2); + s_EoP_spread ->SetTextSize(0.08); + s_EoP_spread -> Draw("sames"); + + /* + h_EoP_spread -> SetFillStyle(3001); + h_EoP_spread -> SetFillColor(kRed+2); + h_EoP_spread -> Draw("hbarsame"); + gPad -> Update(); + */ + + + + //------------------ + // Final plot vs run + //------------------ + + TCanvas* cplot_run = new TCanvas("cplot_run", "history plot vs run",100,100,1000,500); + cplot_run->cd(); + + cLeft = new TPad("pad_0_run","pad_0_run",0.00,0.00,0.75,1.00); + cRight = new TPad("pad_1_run","pad_1_run",0.75,0.00,1.00,1.00); + + cLeft->SetLeftMargin(0.15); + cLeft->SetRightMargin(0.025); + cRight->SetLeftMargin(0.025); + + cLeft->Draw(); + cRight->Draw(); + + tYoffset = 1.5; + labSize = 0.04; + labSize2 = 0.07; + + cLeft->cd(); + + cLeft->SetGridx(); + cLeft->SetGridy(); + + hPad = (TH1F*)gPad->DrawFrame(MinRun[0]-1000,0.9,MaxRun[nBins-1]+1000,1.05); + hPad->GetXaxis()->SetTitle("run"); + if( strcmp(EBEE.c_str(),"EB") == 0 ) + hPad->GetYaxis()->SetTitle("Relative E/p scale"); + else + hPad->GetYaxis()->SetTitle("Relative E/p scale"); + hPad->GetYaxis()->SetTitleOffset(tYoffset); + hPad->GetYaxis()->SetTitleOffset(0.8); + hPad->GetXaxis()->SetLabelSize(labSize); + hPad->GetXaxis()->SetTitleSize(labSize); + hPad->GetYaxis()->SetLabelSize(labSize); + hPad->GetYaxis()->SetTitleSize(labSize); + hPad -> SetMinimum(yMIN); + hPad -> SetMaximum(yMAX); + + // draw history plot + g_fit_run -> SetMarkerStyle(20); + g_fit_run -> SetMarkerSize(0.7); + g_fit_run -> SetMarkerColor(kRed+2); + g_fit_run -> SetLineColor(kRed+2); + g_fit_run -> Draw("P"); + g_c_fit_run -> SetMarkerStyle(20); + g_c_fit_run -> SetMarkerColor(kGreen+2); + g_c_fit_run -> SetLineColor(kGreen+2); + g_c_fit_run -> SetMarkerSize(0.7); + g_c_fit_run -> Draw("P,same"); + + + cRight -> cd(); + + s_EoP_spread = new TPaveStats(); + s_EoC_spread = new TPaveStats(); + + + h_EoC_spread_run -> SetFillStyle(3001); + h_EoC_spread_run -> SetFillColor(kGreen+2); + h_EoC_spread_run->GetYaxis()->SetLabelSize(labSize2); + h_EoC_spread_run->GetYaxis()->SetTitleSize(labSize2); + h_EoC_spread_run->GetYaxis()->SetNdivisions(505); + h_EoC_spread_run->GetYaxis()->SetLabelOffset(-0.02); + h_EoC_spread_run->GetXaxis()->SetLabelOffset(1000); + + h_EoC_spread_run -> Draw("hbar"); + gPad -> Update(); + + s_EoC_spread = (TPaveStats*)(h_EoC_spread_run->GetListOfFunctions()->FindObject("stats")); + s_EoC_spread ->SetTextColor(kGreen+2); + s_EoC_spread ->SetTextSize(0.06); + s_EoC_spread->SetX1NDC(0.49); //new x start position + s_EoC_spread->SetX2NDC(0.99); //new x end position + s_EoC_spread->SetY1NDC(0.475); //new x start position + s_EoC_spread->SetY2NDC(0.590); //new x end position + s_EoC_spread -> SetOptStat(1100); + s_EoC_spread -> Draw("sames"); + + h_EoP_spread_run -> SetFillStyle(3001); + h_EoP_spread_run -> SetFillColor(kRed+2); + h_EoP_spread_run -> Draw("hbarsames"); + gPad -> Update(); + + s_EoP_spread = (TPaveStats*)(h_EoP_spread_run->GetListOfFunctions()->FindObject("stats")); + s_EoP_spread->SetX1NDC(0.49); //new x start position + s_EoP_spread->SetX2NDC(0.99); //new x end position + s_EoP_spread->SetY1NDC(0.350); //new x start position + s_EoP_spread->SetY2NDC(0.475); //new x end position + s_EoP_spread ->SetOptStat(1100); + s_EoP_spread ->SetTextColor(kRed+2); + s_EoP_spread ->SetTextSize(0.06); + s_EoP_spread -> Draw("sames"); + + + + + c_chi2 -> Print((folderName+"/"+folderName+"_fitChi2.png").c_str(),"png"); + c_scOccupancy -> Print((folderName+"/"+folderName+"_scOccupancy.png").c_str(),"png"); + c_seedOccupancy -> Print((folderName+"/"+folderName+"_seedOccupancy.png").c_str(),"png"); + cplot -> Print((folderName+"/"+folderName+"_history_vsTime.png").c_str(),"png"); + cplot_run -> Print((folderName+"/"+folderName+"_history_vsRun.png").c_str(),"png"); + + c_chi2 -> Print((folderName+"/"+folderName+"_fitChi2.pdf").c_str(),"pdf"); + c_scOccupancy -> Print((folderName+"/"+folderName+"_scOccupancy.pdf").c_str(),"pdf"); + c_seedOccupancy -> Print((folderName+"/"+folderName+"_seedOccupancy.pdf").c_str(),"pdf"); + cplot -> Print((folderName+"/"+folderName+"_history_vsTime.pdf").c_str(),"pdf"); + cplot_run -> Print((folderName+"/"+folderName+"_history_vsRun.pdf").c_str(),"pdf"); + + cplot -> SaveAs((folderName+"/"+folderName+"_history_vsTime.C").c_str()); + cplot_run -> SaveAs((folderName+"/"+folderName+"_history_vsRun.C").c_str()); + + cplot -> SaveAs((folderName+"/"+folderName+"_history_vsTime.root").c_str()); + cplot_run -> SaveAs((folderName+"/"+folderName+"_history_vsRun.root").c_str()); + + + + o -> cd(); + + h_template -> Write(); + + h_scOccupancy_eta -> Write(); + h_scOccupancy_phi -> Write(); + h_seedOccupancy_EB -> Write(); + h_seedOccupancy_EEp -> Write(); + h_seedOccupancy_EEm -> Write(); + + g_fit -> Write("g_fit"); + g_c_fit -> Write("g_c_fit"); + g_fit_run -> Write("g_fit_run"); + g_c_fit_run -> Write("g_c_fit_run"); + g_las -> Write("g_las"); + g_LT -> Write("g_LT"); + + h_EoP_chi2 -> Write(); + h_EoC_chi2 -> Write(); + + //ciao + + for(int i = 0; i < nBins; ++i) + { + gStyle->SetOptFit(1111); + + h_EoP[i] -> Write(); + h_EoC[i] -> Write(); + f_EoP[i] -> Write(); + f_EoC[i] -> Write(); + // h_Tsp[i] -> Write(); + // + // h_Cvl[i] -> Write(); + } + + o -> Close(); + + return 0; + } + //------------------------------ LASER MONITORING WITH E/P versus PILE UP ------------------------------------------------------ + + if(vm.count("laserMonitoringEPvsPU")) { + + + //float yMIN = 0.95; + //float yMAX = 1.05; + + + // Set style options + setTDRStyle(); + gStyle->SetPadTickX(1); + gStyle->SetPadTickY(1); + gStyle->SetOptTitle(0); + gStyle->SetOptStat(1110); + gStyle->SetOptFit(1); + + // Set fitting options + TVirtualFitter::SetDefaultFitter("Fumili2"); + + + + //----------------- + // Input parameters + + + std::cout << "\n***************************************************************************************************************************" << std::endl; + + std::string dayMinLabel = ""; + std::string dayMaxLabel = ""; + std::string dayZOOMLabel =""; + float absEtaMin = -1.; + float absEtaMax = -1.; + int IetaMin = -1; + int IetaMax = -1; + int IphiMin = -1; + int IphiMax = -1; + + + + + int t1 = 0; + int t2 = 60; + + std::cout << "EBEE: " << EBEE << std::endl; + std::cout << "evtsPerPoint: " << evtsPerPoint << std::endl; + std::cout << "useRegression: " << useRegression << std::endl; + std::cout << "dayMin: " << dayMin << std::endl; + std::cout << "dayZOOM: " << dayZOOM << std::endl; + std::cout << "dayMax: " << dayMax << std::endl; + std::cout << "yMin: " << yMIN << std::endl; + std::cout << "yMax: " << yMAX << std::endl; + std::cout << "absEtaMin: " << absEtaMin << std::endl; + std::cout << "absEtaMax: " << absEtaMax << std::endl; + std::cout << "IetaMin: " << IetaMin << std::endl; + std::cout << "IetaMax: " << IetaMax << std::endl; + std::cout << "IphiMin: " << IphiMin << std::endl; + std::cout << "IphiMax: " << IphiMax << std::endl; + std::cout << "t1: " << t1 << std::endl; + std::cout << "t2: " << t2 << std::endl; + + + std::string dayZOOM = ""; + std::string dayMin = ""; + std::string dayMax = ""; + + + //------------------- + // Define in/outfiles + + std::string folderName = std::string(EBEE) + "_" + dayMinLabel + "_" + dayMaxLabel; + if( (absEtaMin != -1.) && (absEtaMax != -1.) ) + { + char absEtaBuffer[50]; + sprintf(absEtaBuffer,"_%.2f-%.2f",absEtaMin,absEtaMax); + folderName += std::string(absEtaBuffer); + } + + if( (IetaMin != -1.) && (IetaMax != -1.) && (IphiMin != -1.) && (IphiMax != -1.) ) + { + char absEtaBuffer[50]; + sprintf(absEtaBuffer,"_Ieta_%d-%d_Iphi_%d-%d",IetaMin,IetaMax,IphiMin,IphiMax); + folderName += std::string(absEtaBuffer); + } + + gSystem->mkdir(folderName.c_str()); + TFile* o = new TFile((folderName+"/"+folderName+"_histos.root").c_str(),"RECREATE"); + + + + // Get trees + std::cout << std::endl; + + + if (data->GetEntries() == 0 || mc->GetEntries() == 0 ) + { + std::cout << "Error: At least one file is empty" << std::endl; + return -1; + } + + + + // Set branch addresses + int runNumber; + int nPV; + int nPU; + float avgLCSCEle[3], seedLaserAlphaSCEle1, etaSCEle[3], phiSCEle[3], energySCEle[3], esEnergySCEle[3], pAtVtxGsfEle[3], energySCEle_corr[3]; + int seedXSCEle[3], seedYSCEle[3];//, seedZside; + + data->SetBranchStatus("*",0); + data->SetBranchStatus("runNumber",1); + data->SetBranchStatus("nPV",1); + data->SetBranchStatus("nPU",1); + data->SetBranchStatus("avgLCSCEle",1); + data->SetBranchStatus("seedLaserAlphaSCEle1",1); + // data->SetBranchStatus("ele1_EOverP",1); + data->SetBranchStatus("etaSCEle",1); + data->SetBranchStatus("phiSCEle",1); + data->SetBranchStatus("energySCEle_must",1); + data->SetBranchStatus("energySCEle_corr",1); + data->SetBranchStatus("esEnergySCEle",1); + data->SetBranchStatus("pAtVtxGsfEle",1); + data->SetBranchStatus("seedXSCEle",1); + data->SetBranchStatus("seedYSCEle",1); + // data->SetBranchStatus("ele1_seedZside",1); + + data->SetBranchAddress("runNumber", &runNumber); + data->SetBranchAddress("nPV", &nPV); + data->SetBranchAddress("nPU", &nPU); + data->SetBranchAddress("avgLCSCEle", &avgLCSCEle[0]); + data->SetBranchAddress("seedLaserAlphaSCEle1", &seedLaserAlphaSCEle1); + // data->SetBranchAddress("ele1_EOverP", &EoP); + data->SetBranchAddress("etaSCEle", &etaSCEle); + data->SetBranchAddress("phiSCEle", &phiSCEle); + if( useRegression < 1 ) + data->SetBranchAddress("energySCEle_must", &energySCEle); + else + data->SetBranchAddress("energySCEle_corr", &energySCEle_corr); + // data->SetBranchAddress("energySCEle", &energySCEle); + data->SetBranchAddress("esEnergySCEle", &esEnergySCEle); + data->SetBranchAddress("pAtVtxGsfEle", &pAtVtxGsfEle); + data->SetBranchAddress("seedXSCEle", &seedXSCEle); + data->SetBranchAddress("seedYSCEle", &seedYSCEle); + // data->SetBranchAddress("ele1_seedZside", &seedZside); + + + mc->SetBranchStatus("*",0); + mc->SetBranchStatus("runNumber",1); + mc->SetBranchStatus("nPV",1); + mc->SetBranchStatus("nPU",1); + mc->SetBranchStatus("avgLCSCEle",1); + mc->SetBranchStatus("seedLaserAlphaSCEle1",1); + // mc->SetBranchStatus("ele1_EOverP",1); + mc->SetBranchStatus("etaSCEle",1); + mc->SetBranchStatus("phiSCEle",1); + mc->SetBranchStatus("energySCEle_must",1); + mc->SetBranchStatus("energySCEle_corr",1); + mc->SetBranchStatus("esEnergySCEle",1); + mc->SetBranchStatus("pAtVtxGsfEle",1); + mc->SetBranchStatus("seedXSCEle",1); + mc->SetBranchStatus("seedYSCEle",1); + // mc->SetBranchStatus("ele1_seedZside",1); + + mc->SetBranchAddress("runNumber", &runNumber); + mc->SetBranchAddress("nPV", &nPV); + mc->SetBranchAddress("nPU", &nPU); + mc->SetBranchAddress("avgLCSCEle", &avgLCSCEle[0]); + mc->SetBranchAddress("seedLaserAlphaSCEle1", &seedLaserAlphaSCEle1); + // mc->SetBranchAddress("ele1_EOverP", &EoP); + mc->SetBranchAddress("etaSCEle", &etaSCEle); + mc->SetBranchAddress("phiSCEle", &phiSCEle); + if( useRegression < 1 ) + mc->SetBranchAddress("energySCEle_must", &energySCEle); + else + mc->SetBranchAddress("energySCEle_corr", &energySCEle_corr); + // mc->SetBranchAddress("energySCEle", &energySCEle); + mc->SetBranchAddress("esEnergySCEle", &esEnergySCEle); + mc->SetBranchAddress("pAtVtxGsfEle", &pAtVtxGsfEle); + mc->SetBranchAddress("seedXSCEle", &seedXSCEle); + mc->SetBranchAddress("seedYSCEle", &seedYSCEle); + // mc->SetBranchAddress("ele1_seedZside", &seedZside); + + + + + + + //-------------------------------------------------------- + // Define PU correction (to be used if useRegression == 0) + + // corr = p0 + p1 * nPU + float p0_EB; + float p1_EB; + float p0_EE; + float p1_EE; + + if( useRegression == 0 ) + { + //2012 EB + p0_EB = 0.9991; + p1_EB = 0.0001635; + //2012 EE + p0_EE = 0.9968; + p1_EE = 0.001046; + } + else + { + //2012 EB + p0_EB = 1.001; + p1_EB = -0.000143; + //2012 EE + p0_EE = 1.00327; + p1_EE = -0.000432; + } + + float p0 = -1.; + float p1 = -1.; + + if( strcmp(EBEE.c_str(),"EB") == 0 ) + { + p0 = p0_EB; + p1 = p1_EB; + } + else + { + p0 = p0_EE; + p1 = p1_EE; + } + + //2015 + p0=1.; + p1=0.; + + + + + //--------------------------------- + // Build the reference distribution + + std::cout << std::endl; + std::cout << "***** Build reference for " << EBEE << " *****" << std::endl; + + TH1F* h_template = new TH1F("template", "", 2000, 0., 5.); + + for(int ientry = 0; ientry < mc->GetEntries(); ++ientry) + { + if( (ientry%100000 == 0) ) std::cout << "reading MC entry " << ientry << "\r" << std::endl;//std::flush; + mc->GetEntry(ientry); + + // selections + if( (strcmp(EBEE.c_str(),"EB") == 0) && (fabs(etaSCEle[0]) > 1.479) ) continue; // barrel + if( (strcmp(EBEE.c_str(),"EB_0_1") == 0) && (fabs(etaSCEle[0]) > 1.0)) continue; // inner barrel + if( (strcmp(EBEE.c_str(),"EB_1_1479") == 0) && (fabs(etaSCEle[0]) < 1.0 || fabs(etaSCEle[0]) > 1.479) ) continue; // barrel + if( (strcmp(EBEE.c_str(),"EE") == 0) && (fabs(etaSCEle[0]) < 1.479 || fabs(etaSCEle[0])>2.5) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EE_1479_2") == 0) && (fabs(etaSCEle[0]) < 1.479 || fabs(etaSCEle[0])>2.0) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EE_2_25") == 0) && (fabs(etaSCEle[0]) < 2.0 || fabs(etaSCEle[0])>2.5) ) continue; // endcap + + if( (strcmp(EBEE.c_str(),"EEp") == 0) && (etaSCEle[0] < 1.479 || etaSCEle[0]>2.5 ) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_1479_2") == 0) && (etaSCEle[0] < 1.479 || etaSCEle[0]>2.0) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_2_25") == 0) && (etaSCEle[0] < 2.0 || etaSCEle[0]>2.5) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_2_225") == 0) && (etaSCEle[0] < 2.0 || etaSCEle[0]>2.25) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_225_25") == 0) && (etaSCEle[0] < 2.25 || etaSCEle[0]>2.25) ) continue; // endcap + + if( (strcmp(EBEE.c_str(),"EEm") == 0) && (etaSCEle[0] > -1.479 || etaSCEle[0]<-2.5 ) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_1479_2") == 0) && (etaSCEle[0] > -1.479 || etaSCEle[0]<-2.0) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_2_25") == 0) && (etaSCEle[0] > -2.0 || etaSCEle[0]<-2.5) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_2_225") == 0) && (etaSCEle[0] > -2.0 || etaSCEle[0]<-2.25) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_225_25") == 0) && (etaSCEle[0] > -2.25 || etaSCEle[0]<-2.5) ) continue; // endcap + + if( (absEtaMin != -1.) && (absEtaMax != -1.) ) + { + if( (fabs(etaSCEle[0]) < absEtaMin) || (fabs(etaSCEle[0]) > absEtaMax) ) continue; + } + + if( (IetaMin != -1.) && (IetaMax != -1.) && (IphiMin != -1.) && (IphiMax != -1.) ) + { + if( (seedXSCEle[0] < IetaMin) || (seedXSCEle[0] > IetaMax) ) continue; + if( (seedYSCEle[0] < IphiMin) || (seedYSCEle[0] > IphiMax) ) continue; + } + + // PU correction + float PUCorr = (p0 + p1*nPU); + //std::cout << "p0: " << p0 << " p1: " << p1 << " nPU: " << nPU << std::endl; + + // fill the template histogram + h_template -> Fill( (energySCEle[0]-esEnergySCEle[0])/(pAtVtxGsfEle[0]-esEnergySCEle[0]) / PUCorr ); + } + + std::cout << "Reference built for " << EBEE << " - " << h_template->GetEntries() << " events" << std::endl; + + + + + + + //--------------------- + // Loop and sort events + + std::cout << std::endl; + std::cout << "***** Sort events and define bins *****" << std::endl; + + int nEntries = data -> GetEntriesFast(); + int nSavePts = 0; + std::vector isSavedEntries(nEntries); + std::vector sortedEntries; + std::vector timeStampFirst; + + for(int ientry = 0; ientry < nEntries; ++ientry) + { + data -> GetEntry(ientry); + isSavedEntries.at(ientry) = false; + + // selections + if( (strcmp(EBEE.c_str(),"EB") == 0) && (fabs(etaSCEle[0]) > 1.479) ) continue; // barrel + if( (strcmp(EBEE.c_str(),"EB_0_1") == 0) && (fabs(etaSCEle[0]) > 1.0)) continue; // inner barrel + if( (strcmp(EBEE.c_str(),"EB_1_1479") == 0) && (fabs(etaSCEle[0]) < 1.0 || fabs(etaSCEle[0]) > 1.479) ) continue; // barrel + if( (strcmp(EBEE.c_str(),"EE") == 0) && (fabs(etaSCEle[0]) < 1.479 || fabs(etaSCEle[0])>2.5) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EE_1479_2") == 0) && (fabs(etaSCEle[0]) < 1.479 || fabs(etaSCEle[0])>2.0) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EE_2_25") == 0) && (fabs(etaSCEle[0]) < 2.0 || fabs(etaSCEle[0])>2.5) ) continue; // endcap + + if( (strcmp(EBEE.c_str(),"EEp") == 0) && (etaSCEle[0] < 1.479 || etaSCEle[0]>2.5 ) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_1479_2") == 0) && (etaSCEle[0] < 1.479 || etaSCEle[0]>2.0) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_2_25") == 0) && (etaSCEle[0] < 2.0 || etaSCEle[0]>2.5) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_2_225") == 0) && (etaSCEle[0] < 2.0 || etaSCEle[0]>2.25) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_225_25") == 0) && (etaSCEle[0] < 2.25 || etaSCEle[0]>2.25) ) continue; // endcap + + if( (strcmp(EBEE.c_str(),"EEm") == 0) && (etaSCEle[0] > -1.479 || etaSCEle[0]<-2.5 ) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_1479_2") == 0) && (etaSCEle[0] > -1.479 || etaSCEle[0]<-2.0) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_2_25") == 0) && (etaSCEle[0] > -2.0 || etaSCEle[0]<-2.5) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_2_225") == 0) && (etaSCEle[0] > -2.0 || etaSCEle[0]<-2.25) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_225_25") == 0) && (etaSCEle[0] > -2.25 || etaSCEle[0]<-2.5) ) continue; // endcap + + if( (absEtaMin != -1.) && (absEtaMax != -1.) ) + { + if( (fabs(etaSCEle[0]) < absEtaMin) || (fabs(etaSCEle[0]) > absEtaMax) ) continue; + } + + if( (IetaMin != -1.) && (IetaMax != -1.) && (IphiMin != -1.) && (IphiMax != -1.) ) + { + if( (seedXSCEle[0] < IetaMin) || (seedXSCEle[0] > IetaMax) ) continue; + if( (seedYSCEle[0] < IphiMin) || (seedYSCEle[0] > IphiMax) ) continue; + } + + if( nPV < t1 ) continue; + if( nPV > t2 ) continue; + + if( avgLCSCEle[0] <= 0. ) continue; + + isSavedEntries.at(ientry) = true; + + + // fill sorter + Sorter dummy; + dummy.time = nPV; + dummy.entry = ientry; + sortedEntries.push_back(dummy); + + ++nSavePts; + } + + // sort events + std::sort(sortedEntries.begin(),sortedEntries.end(),Sorter()); + std::cout << "Data sorted in " << EBEE << " - " << nSavePts << " events" << std::endl; + + std::map antiMap; + for(unsigned int iSaved = 0; iSaved < sortedEntries.size(); ++iSaved) + antiMap[sortedEntries.at(iSaved).entry] = iSaved; + + + //--------------------- + // Loop and define bins + + // "wide" bins - find events with time separation bigger than 1 day + int nWideBins = 1; + std::vector wideBinEntryMax; + //int timeStampOld = -1; + + wideBinEntryMax.push_back(0); + + for(int iSaved = 0; iSaved < nSavePts; ++iSaved) + { + /* if( iSaved%100000 == 0 ) std::cout << "reading saved entry " << iSaved << "\r" << std::flush; + data->GetEntry(sortedEntries[iSaved].entry); + + if( iSaved == 0 ) + { + timeStampOld = nPV; + continue; + } + + if( (nPV-timeStampOld)/3600. > timeLapse ) + { + ++nWideBins; + wideBinEntryMax.push_back(iSaved-1); + } + + + timeStampOld = nPV; + */ + } + + + std::cout << std::endl; + wideBinEntryMax.push_back(nSavePts); + + // bins with approximatively evtsPerPoint events per bin + int nBins = 0; + std::vector binEntryMax; + + binEntryMax.push_back(0); + for(int wideBin = 0; wideBin < nWideBins; ++wideBin) + { + int nTempBins = std::max(1,int( (wideBinEntryMax.at(wideBin+1)-wideBinEntryMax.at(wideBin))/evtsPerPoint )); + int nTempBinEntries = int( (wideBinEntryMax.at(wideBin+1)-wideBinEntryMax.at(wideBin))/nTempBins ); + + for(int tempBin = 0; tempBin < nTempBins; ++tempBin) + { + ++nBins; + if( tempBin < nTempBins - 1 ) + binEntryMax.push_back( wideBinEntryMax.at(wideBin) + (tempBin+1)*nTempBinEntries ); + else + binEntryMax.push_back( wideBinEntryMax.at(wideBin+1) ); + } + } + + // std::cout << "nBins = " << nBins << std::endl; + //for(int bin = 0; bin < nBins; ++bin) + // std::cout << "bin: " << bin + // << " entry min: " << setw(6) << binEntryMax.at(bin) + // << " entry max: " << setw(6) << binEntryMax.at(bin+1) + // << " events: " << setw(6) << binEntryMax.at(bin+1)-binEntryMax.at(bin) + // << std::endl; + + + + + + + //--------------------- + // histogram definition + + TH1F* h_scOccupancy_eta = new TH1F("h_scOccupancy_eta","", 298, -2.6, 2.6); + TH1F* h_scOccupancy_phi = new TH1F("h_scOccupancy_phi","", 363, -3.1765, 3.159); + SetHistoStyle(h_scOccupancy_eta); + SetHistoStyle(h_scOccupancy_phi); + + TH2F* h_seedOccupancy_EB = new TH2F("h_seedOccupancy_EB","", 171, -86., 85., 361, 0.,361.); + TH2F* h_seedOccupancy_EEp = new TH2F("h_seedOccupancy_EEp","", 101, 0.,101., 100, 0.,101.); + TH2F* h_seedOccupancy_EEm = new TH2F("h_seedOccupancy_EEm","", 101, 0.,101., 100, 0.,101.); + SetHistoStyle(h_seedOccupancy_EB); + SetHistoStyle(h_seedOccupancy_EEp); + SetHistoStyle(h_seedOccupancy_EEm); + + TH1F* h_EoP_spread = new TH1F("h_EoP_spread","",100,yMIN,yMAX); + TH1F* h_EoC_spread = new TH1F("h_EoC_spread","",100,yMIN,yMAX); + TH1F* h_EoP_spread_run = new TH1F("h_EoP_spread_run","",100,yMIN,yMAX); + TH1F* h_EoC_spread_run = new TH1F("h_EoC_spread_run","",100,yMIN,yMAX); + SetHistoStyle(h_EoP_spread,"EoP"); + SetHistoStyle(h_EoC_spread,"EoC"); + SetHistoStyle(h_EoP_spread_run,"EoP"); + SetHistoStyle(h_EoC_spread_run,"EoC"); + + TH1F* h_EoP_chi2 = new TH1F("h_EoP_chi2","",50,0.,5.); + TH1F* h_EoC_chi2 = new TH1F("h_EoC_chi2","",50,0.,5.); + SetHistoStyle(h_EoP_chi2,"EoP"); + SetHistoStyle(h_EoC_chi2,"EoC"); + + TH1F** h_EoP = new TH1F*[nBins]; + TH1F** h_EoC = new TH1F*[nBins]; + TH1F** h_Las = new TH1F*[nBins]; + TH1F** h_Tsp = new TH1F*[nBins]; + TH1F** h_Cvl = new TH1F*[nBins]; + + for(int i = 0; i < nBins; ++i) + { + char histoName[80]; + + sprintf(histoName, "EoP_%d", i); + h_EoP[i] = new TH1F(histoName, histoName, 2000, 0., 5.); + SetHistoStyle(h_EoP[i],"EoP"); + + sprintf(histoName, "EoC_%d", i); + h_EoC[i] = new TH1F(histoName, histoName, 2000, 0., 5.); + SetHistoStyle(h_EoC[i],"EoC"); + + sprintf(histoName, "Las_%d", i); + h_Las[i] = new TH1F(histoName, histoName, 500, 0.5, 1.5); + + sprintf(histoName, "Tsp_%d", i); + h_Tsp[i] = new TH1F(histoName, histoName, 500, 0.5, 1.5); + + } + + + // function definition + TF1** f_EoP = new TF1*[nBins]; + TF1** f_EoC = new TF1*[nBins]; + + + // graphs definition + TGraphAsymmErrors* g_fit = new TGraphAsymmErrors(); + TGraphAsymmErrors* g_c_fit = new TGraphAsymmErrors(); + + TGraphAsymmErrors* g_fit_run = new TGraphAsymmErrors(); + TGraphAsymmErrors* g_c_fit_run = new TGraphAsymmErrors(); + + TGraph* g_las = new TGraph(); + + TGraphErrors* g_LT = new TGraphErrors(); + + g_fit->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00"); + g_fit->GetXaxis()->SetTimeDisplay(1); + g_c_fit->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00"); + g_c_fit->GetXaxis()->SetTimeDisplay(1); + g_las->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00"); + g_las->GetXaxis()->SetTimeDisplay(1); + g_LT->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00"); + g_LT->GetXaxis()->SetTimeDisplay(1); + + + + + + + //------------------------------------ + // loop on the saved and sorted events + + std::cout << std::endl; + std::cout << "***** Fill and fit histograms *****" << std::endl; + + std::vector Entries(nBins); + std::vector AveTime(nBins); + std::vector MinTime(nBins); + std::vector MaxTime(nBins); + std::vector AveRun(nBins); + std::vector MinRun(nBins); + std::vector MaxRun(nBins); + std::vector AveLT(nBins); + std::vector AveLT2(nBins); + + int iSaved = -1; + for(int ientry = 0; ientry < nEntries; ++ientry) + { + if( (ientry%100000 == 0) ) std::cout << "reading entry " << ientry << "\r" << std::endl;//std::flush; + + if( isSavedEntries.at(ientry) == false ) continue; + + ++iSaved; + + int iSaved = antiMap[ientry]; + int bin = -1; + for(bin = 0; bin < nBins; ++bin) + if( iSaved >= binEntryMax.at(bin) && iSaved < binEntryMax.at(bin+1) ) + break; + + //std::cout << "bin = " << bin << " iSaved = "<< iSaved << std::endl; + data->GetEntry(ientry); + + + + Entries[bin] += 1; + + if( iSaved == binEntryMax.at(bin)+1 ) MinTime[bin] = nPV; + if( iSaved == binEntryMax.at(bin+1)-1 ) MaxTime[bin] = nPV; + AveTime[bin] += nPV; + + if( iSaved == binEntryMax.at(bin)+1 ) MinRun[bin] = runNumber; + if( iSaved == binEntryMax.at(bin+1)-1 ) MaxRun[bin] = runNumber; + AveRun[bin] += runNumber; + + float LT = (-1. / seedLaserAlphaSCEle1 * log(avgLCSCEle[0])); + AveLT[bin] += LT; + AveLT2[bin] += LT*LT; + + // PU correction + float PUCorr = (p0 + p1*nPU); + + // fill the histograms + (h_EoP[bin]) -> Fill( (energySCEle[0]-esEnergySCEle[0])/(pAtVtxGsfEle[0]-esEnergySCEle[0]) / avgLCSCEle[0] / PUCorr); + (h_EoC[bin]) -> Fill( (energySCEle[0]-esEnergySCEle[0])/(pAtVtxGsfEle[0]-esEnergySCEle[0]) / PUCorr ); + + (h_Las[bin]) -> Fill(avgLCSCEle[0]); + (h_Tsp[bin]) -> Fill(1./avgLCSCEle[0]); + + h_scOccupancy_eta -> Fill(etaSCEle[0]); + h_scOccupancy_phi -> Fill(phiSCEle[0]); + if(fabs(etaSCEle[0])<1.449) + h_seedOccupancy_EB -> Fill(seedXSCEle[0],seedYSCEle[0]); + else if(etaSCEle[0]>1.449) + h_seedOccupancy_EEp -> Fill(seedXSCEle[0],seedYSCEle[0]); + else if(etaSCEle[0]<-1.449) + h_seedOccupancy_EEm -> Fill(seedXSCEle[0],seedYSCEle[0]); + } + + for(int bin = 0; bin < nBins; ++bin) + { + AveTime[bin] = 1. * AveTime[bin] / (binEntryMax.at(bin+1)-binEntryMax.at(bin)); + AveRun[bin] = 1. * AveRun[bin] / (binEntryMax.at(bin+1)-binEntryMax.at(bin)); + AveLT[bin] = 1. * AveLT[bin] / (binEntryMax.at(bin+1)-binEntryMax.at(bin)); + AveLT2[bin] = 1. * AveLT2[bin] / (binEntryMax.at(bin+1)-binEntryMax.at(bin)); + //std::cout << date << " " << AveTime[i] << " " << MinTime[i] << " " << MaxTime[i] << std::endl; + } + + + + + + + int rebin = 2; + if( strcmp(EBEE.c_str(),"EE") == 0 ) rebin *= 2; + + h_template -> Rebin(rebin); + + + + float EoP_scale = 0.; + float EoP_err = 0.; + int EoP_nActiveBins = 0; + + float EoC_scale = 0.; + float EoC_err = 0.; + int EoC_nActiveBins = 0; + + float LCInv_scale = 0; + + std::vector validBins; + for(int i = 0; i < nBins; ++i) + { + bool isValid = true; + + h_EoP[i] -> Rebin(rebin); + h_EoC[i] -> Rebin(rebin); + + + + //------------------------------------ + // Fill the graph for uncorrected data + + // define the fitting function + // N.B. [0] * ( [1] * f( [1]*(x-[2]) ) ) + + //o -> cd(); + char convolutionName[50]; + sprintf(convolutionName,"h_convolution_%d",i); + //h_Cvl[i] = ConvoluteTemplate(std::string(convolutionName),h_template,h_Las[i],32768,-5.,5.); + h_Cvl[i] = MellinConvolution(std::string(convolutionName),h_template,h_Tsp[i]); + + histoFunc* templateHistoFunc = new histoFunc(h_template); + histoFunc* templateConvolutedHistoFunc = new histoFunc(h_Cvl[i]); + char funcName[50]; + + sprintf(funcName,"f_EoP_%d",i); + + if( strcmp(EBEE.c_str(),"EB") == 0 ) + f_EoP[i] = new TF1(funcName, templateConvolutedHistoFunc, 0.8*(h_Tsp[i]->GetMean()), 1.4*(h_Tsp[i]->GetMean()), 3, "histoFunc"); + else + f_EoP[i] = new TF1(funcName, templateConvolutedHistoFunc, 0.75*(h_Tsp[i]->GetMean()), 1.5*(h_Tsp[i]->GetMean()), 3, "histoFunc"); + + f_EoP[i] -> SetParName(0,"Norm"); + f_EoP[i] -> SetParName(1,"Scale factor"); + f_EoP[i] -> SetLineWidth(1); + f_EoP[i] -> SetNpx(10000); + + double xNorm = h_EoP[i]->GetEntries()/h_template->GetEntries() * + h_EoP[i]->GetBinWidth(1)/h_template->GetBinWidth(1); + + f_EoP[i] -> FixParameter(0, xNorm); + f_EoP[i] -> SetParameter(1, 1.); + f_EoP[i] -> FixParameter(2, 0.); + f_EoP[i] -> SetLineColor(kRed+2); + + int fStatus = 0; + int nTrials = 0; + TFitResultPtr rp; + + rp = h_EoP[i] -> Fit(funcName, "ERLS+"); + while( (fStatus != 0) && (nTrials < 10) ) + { + rp = h_EoP[i] -> Fit(funcName, "ERLS+"); + fStatus = rp; + if(fStatus == 0) break; + ++nTrials; + } + + // fill the graph + double eee = f_EoP[i]->GetParError(1); + //float k = f_EoP[i]->GetParameter(1); + float k = f_EoP[i]->GetParameter(1) / h_Tsp[i]->GetMean(); //needed when using mellin's convolution + // std::cout << "noCORR" << std::endl; + // std::cout << "eee: " << f_EoP[i]->GetParError(1) << "k: " << f_EoP[i]->GetParameter(1) / h_Tsp[i]->GetMean() << std::endl; + + /* + std::cout << i <<"--nocorr---- "<< 1./k << std::endl; + std::cout <<" condizione 1: " << h_EoP[i]->GetEntries() << " fStatus: " << fStatus << " eee: " << eee << "con eee che ci piace essere maggiore di : " << 0.05*h_template->GetRMS()/sqrt(evtsPerPoint) << std::endl ; + getchar(); + */ + // if( (h_EoP[i]->GetEntries() > 3) && (fStatus == 0) && (eee > 0.05*h_template->GetRMS()/sqrt(evtsPerPoint)) ) + + if( (h_EoP[i]->GetEntries() > 500) && (fStatus == 0) ) + { + float date = (float)AveTime[i]; + float dLow = (float)(AveTime[i]-MinTime[i]); + float dHig = (float)(MaxTime[i]-AveTime[i]); + float run = (float)AveRun[i]; + float rLow = (float)(AveRun[i]-MinRun[i]); + float rHig = (float)(MaxRun[i]-AveRun[i]); + g_fit -> SetPoint(i, date , 1./k); + g_fit -> SetPointError(i, dLow , dHig, eee/k/k, eee/k/k); + g_fit_run -> SetPoint(i, run , 1./k); + g_fit_run -> SetPointError(i, rLow , rHig, eee/k/k, eee/k/k); + + std::cout <<"************-------------------*****************" < Fill(f_EoP[i]->GetChisquare()/f_EoP[i]->GetNDF()); + + EoP_scale += 1./k; + EoP_err += eee/k/k; + ++EoP_nActiveBins; + } + else + { + std::cout << "Fitting uncorrected time bin: " << i << " Fail status: " << fStatus << " sigma: " << eee << std::endl; + isValid = false; + } + + //---------------------------------- + // Fill the graph for corrected data + + // define the fitting function + // N.B. [0] * ( [1] * f( [1]*(x-[2]) ) ) + + sprintf(funcName,"f_EoC_%d",i); + if( strcmp(EBEE.c_str(),"EB") == 0 ) + f_EoC[i] = new TF1(funcName, templateHistoFunc, 0.8, 1.4, 3, "histoFunc"); + else + f_EoC[i] = new TF1(funcName, templateHistoFunc, 0.75, 1.5, 3, "histoFunc"); + f_EoC[i] -> SetParName(0,"Norm"); + f_EoC[i] -> SetParName(1,"Scale factor"); + f_EoC[i] -> SetLineWidth(1); + f_EoC[i] -> SetNpx(10000); + + xNorm = h_EoC[i]->GetEntries()/h_template->GetEntries() * + h_EoC[i]->GetBinWidth(1)/h_template->GetBinWidth(1); + + f_EoC[i] -> FixParameter(0, xNorm); + f_EoC[i] -> SetParameter(1, 0.99); + f_EoC[i] -> FixParameter(2, 0.); + f_EoC[i] -> SetLineColor(kGreen+2); + + + rp = h_EoC[i] -> Fit(funcName, "ERLS+"); + fStatus = rp; + nTrials = 0; + while( (fStatus != 0) && (nTrials < 10) ) + { + rp = h_EoC[i] -> Fit(funcName, "ERLS+"); + fStatus = rp; + if(fStatus == 0) break; + ++nTrials; + } + + + // fill the graph + k = f_EoC[i]->GetParameter(1); + eee = f_EoC[i]->GetParError(1); + //std::cout << "CORR" << std::endl; + //std::cout << "eee: " << f_EoP[i]->GetParError(1) << "k: " << f_EoP[i]->GetParameter(1) / h_Tsp[i]->GetMean() << std::endl; + //getchar(); + /* std::cout << i <<"--corr---- "<< 1./k << std::endl; + std::cout <<" condizione 1: " << h_EoP[i]->GetEntries() << " fStatus: " << fStatus << " eee: " << eee << "con eee che ci piace essere maggiore di : " << 0.05*h_template->GetRMS()/sqrt(evtsPerPoint) << std::endl ; + getchar(); + */ + + + if( (h_EoC[i]->GetEntries() > 500) && (fStatus == 0) ) + // if( (h_EoC[i]->GetEntries() > 10) && (fStatus == 0) && (eee > 0.05*h_template->GetRMS()/sqrt(evtsPerPoint)) ) + { + float date = (float)AveTime[i]; + float dLow = (float)(AveTime[i]-MinTime[i]); + float dHig = (float)(MaxTime[i]-AveTime[i]); + float run = (float)AveRun[i]; + float rLow = (float)(AveRun[i]-MinRun[i]); + float rHig = (float)(MaxRun[i]-AveRun[i]); + + g_c_fit -> SetPoint(i, date , 1./k); + g_c_fit -> SetPointError(i, dLow , dHig , eee/k/k, eee/k/k); + + g_c_fit_run -> SetPoint(i, run , 1./k); + g_c_fit_run -> SetPointError(i, rLow , rHig, eee/k/k, eee/k/k); + std::cout <<"************-------------------*****************" < Fill(f_EoC[i]->GetChisquare()/f_EoP[i]->GetNDF()); + + EoC_scale += 1./k; + EoC_err += eee/k/k; + ++EoC_nActiveBins; + } + else + { + std::cout << "Fitting corrected time bin: " << i << " Fail status: " << fStatus << " sigma: " << eee << std::endl; + isValid = false; + } + + if( isValid == true ) validBins.push_back(i); + } + + EoP_scale /= EoP_nActiveBins; + EoP_err /= EoP_nActiveBins; + + EoC_scale /= EoC_nActiveBins; + EoC_err /= EoC_nActiveBins; + + + + + + + //---------------------------------------- + // Fill the graph for avg laser correction + + + for(unsigned int itr = 0; itr < validBins.size(); ++itr) + { + //float k0 = f_EoP[0]->GetParameter(1) / h_Tsp[0]->GetMean(); + int i = validBins.at(itr); + // g_las -> SetPoint(itr, (float)AveTime[i], (h_Tsp[i]->GetMean())+((1/k0)-(h_Tsp[0]->GetMean())) ); + g_las -> SetPoint(itr, (float)AveTime[i], h_Tsp[i]->GetMean() ); + + + //g_las -> SetPointffa(itr, (float)AveTime[i], h_Tsp[i]->GetMean()); + g_LT -> SetPoint(itr, (float)AveTime[i], AveLT[i] ); + g_LT -> SetPointError(itr, 0., sqrt(AveLT2[i]-AveLT[i]*AveLT[i]) / sqrt(Entries[i]) ); + + LCInv_scale += h_Tsp[i]->GetMean(); + } + + LCInv_scale /= validBins.size(); + + + + + + + //--------------- + // Rescale graphs + + float yscale = 1.; + //float yscale = 1./EoC_scale; + + for(unsigned int itr = 0; itr < validBins.size(); ++itr) + { + double x,y; + g_fit -> GetPoint(itr,x,y); + g_fit -> SetPoint(itr,x,y*yscale); + if ( (x > t1) && (x < t2) ) h_EoP_spread -> Fill(y*yscale); + + g_c_fit -> GetPoint(itr,x,y); + g_c_fit -> SetPoint(itr,x,y*yscale); + if ( (x > t1) && (x < t2) ) h_EoC_spread -> Fill(y*yscale); + + g_fit_run -> GetPoint(itr,x,y); + g_fit_run -> SetPoint(itr,x,y*yscale); + if ( (x > t1) && (x < t2) ) h_EoP_spread_run -> Fill(y*yscale); + + g_c_fit_run -> GetPoint(itr,x,y); + g_c_fit_run -> SetPoint(itr,x,y*yscale); + if ( (x > t1) && (x < t2) ) h_EoC_spread_run -> Fill(y*yscale); + + g_las -> GetPoint(itr,x,y); + g_las -> SetPoint(itr,x,y*yscale*EoP_scale/LCInv_scale); + } + //ciao + TF1 EoC_pol0("EoC_pol0","pol0",t1,t2); + EoC_pol0.SetLineColor(kGreen+2); + EoC_pol0.SetLineWidth(2); + EoC_pol0.SetLineStyle(2); + g_c_fit -> Fit("EoC_pol0","QNR"); + + + + + + + + + //---------------------------- + // Print out global quantities + + std::cout << std::endl; + std::cout << "***** Mean scales and errors *****" << std::endl; + std::cout << std::fixed; + std::cout << std::setprecision(4); + std::cout << "Mean EoP scale: " << std::setw(6) << EoP_scale << " mean EoP error: " << std::setw(8) << EoP_err << std::endl; + std::cout << "Mean EoC scale: " << std::setw(6) << EoC_scale << " mean EoC error: " << std::setw(8) << EoC_err << std::endl; + std::cout << "Mean 1/LC scale: " << std::setw(6) << LCInv_scale << std::endl; + + + + + + + //------------------- + // Final Plot vs Vertex + //------------------- + + TCanvas* cplot = new TCanvas("cplot", "history plot vs Vertex",100,100,1000,500); + cplot->cd(); + + TPad *cLeft = new TPad("pad_0","pad_0",0.00,0.00,0.75,1.00); + TPad *cRight = new TPad("pad_1","pad_1",0.75,0.00,1.00,1.00); + + cLeft->SetLeftMargin(0.15); + cLeft->SetRightMargin(0.025); + cRight->SetLeftMargin(0.025); + + cLeft->Draw(); + cRight->Draw(); + + float tYoffset = 1.0; + float labSize = 0.05; + float labSize2 = 0.06; + + cLeft->cd(); + + cLeft->SetGridx(); + cLeft->SetGridy(); + + TH1F *hPad = (TH1F*)gPad->DrawFrame(t1,0.9,t2,1.05); + + hPad->GetXaxis()->SetLimits(0,46); + //hPad->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00"); + //hPad->GetXaxis()->SetTimeDisplay(1); + //hPad->GetXaxis() -> SetRangeUser(MinTime[0]-43200,MaxTime[nBins-1]+43200); + hPad->GetXaxis()->SetTitle(" Number of Vertices"); + hPad->GetXaxis()->SetTitleOffset(0.8); + + //ciao + + + if( strcmp(EBEE.c_str(),"EB") == 0 ) + hPad->GetYaxis()->SetTitle("Relative E/p scale"); + else + hPad->GetYaxis()->SetTitle("Relative E/p scale"); + hPad->GetYaxis()->SetTitleOffset(tYoffset); + hPad->GetXaxis()->SetLabelSize(labSize); + hPad->GetXaxis()->SetTitleSize(labSize2); + hPad->GetYaxis()->SetLabelSize(labSize); + hPad->GetYaxis()->SetTitleSize(labSize2); + hPad -> SetMinimum(yMIN); + hPad -> SetMaximum(yMAX); + + // draw history plot + g_fit -> SetMarkerStyle(24); + g_fit -> SetMarkerSize(0.7); + g_fit -> SetMarkerColor(kRed+2); + g_fit -> SetLineColor(kRed+2); + //g_fit -> Draw("P"); + g_c_fit -> SetMarkerStyle(20); + g_c_fit -> SetMarkerColor(kGreen+2); + g_c_fit -> SetLineColor(kGreen+2); + g_c_fit -> SetMarkerSize(0.7); + g_c_fit -> Draw("EP"); + g_las -> SetLineColor(kAzure-2); + g_las -> SetLineWidth(2); + //g_las -> Draw("L,same"); + + TLegend* legend = new TLegend(0.60,0.78,0.90,0.94); + legend -> SetLineColor(kWhite); + legend -> SetLineWidth(0); + legend -> SetFillColor(kWhite); + legend -> SetFillStyle(0); + legend -> SetTextFont(42); + legend -> SetTextSize(0.04); + legend -> AddEntry(g_c_fit,"with LM correction","PL"); + //legend -> AddEntry(g_fit, "without LM correction","PL"); + //legend -> AddEntry(g_las, "1 / LM correction","L"); + legend -> Draw("same"); + + char latexBuffer[250]; + + sprintf(latexBuffer,"CMS 2015 Preliminary"); + TLatex* latex = new TLatex(0.18,0.89,latexBuffer); + latex -> SetNDC(); + latex -> SetTextFont(62); + latex -> SetTextSize(0.05); + latex -> Draw("same"); + + //sprintf(latexBuffer,"#sqrt{s} = 8 TeV L = 3.95 fb^{-1}"); + sprintf(latexBuffer,"#sqrt{s} = 13 TeV"); + TLatex* latex2 = new TLatex(0.18,0.84,latexBuffer); + latex2 -> SetNDC(); + latex2 -> SetTextFont(42); + latex2 -> SetTextSize(0.05); + latex2 -> Draw("same"); + + if( strcmp(EBEE.c_str(),"EB") == 0 || strcmp(EBEE.c_str(),"EB_0_1") == 0 || strcmp(EBEE.c_str(),"EB_1_1479") == 0) + sprintf(latexBuffer,"ECAL Barrel"); + else + sprintf(latexBuffer,"ECAL Endcap"); + TLatex* latex3 = new TLatex(0.18,0.19,latexBuffer); + latex3 -> SetNDC(); + latex3 -> SetTextFont(42); + latex3 -> SetTextSize(0.05); + latex3 -> Draw("same"); + + //sprintf(latexBuffer,"%.2E events",1.*nSavePts); + //TLatex* latex4 = new TLatex(0.18,0.24,latexBuffer); + //latex4 -> SetNDC(); + //latex4 -> SetTextFont(42); + //latex4 -> SetTextSize(0.04); + //latex4 -> Draw("same"); + // + //sprintf(latexBuffer,"%d events/bin - %d bins",evtsPerPoint,nBins); + //TLatex* latex5 = new TLatex(0.18,0.19,latexBuffer); + //latex5 -> SetNDC(); + //latex5 -> SetTextFont(42); + //latex5 -> SetTextSize(0.04); + //latex5 -> Draw("same"); + + + cRight -> cd(); + + TPaveStats* s_EoP_spread = new TPaveStats(); + TPaveStats* s_EoC_spread = new TPaveStats(); + + + h_EoC_spread -> SetFillStyle(3001); + h_EoC_spread -> SetFillColor(kGreen+2); + h_EoC_spread->GetYaxis()->SetLabelSize(0.09); + h_EoC_spread->GetYaxis()->SetLabelOffset(-0.03); + h_EoC_spread->GetYaxis()->SetTitleSize(0.08); + h_EoC_spread->GetYaxis()->SetNdivisions(505); + h_EoC_spread->GetXaxis()->SetLabelOffset(1000); + + h_EoC_spread -> Draw("hbar"); + gPad -> Update(); + + s_EoC_spread = (TPaveStats*)(h_EoC_spread->GetListOfFunctions()->FindObject("stats")); + s_EoC_spread -> SetStatFormat("1.4g"); + s_EoC_spread->SetX1NDC(0.06); //new x start position + s_EoC_spread->SetX2NDC(0.71); //new x end position + s_EoC_spread->SetY1NDC(0.43); //new x start position + s_EoC_spread->SetY2NDC(0.34); //new x end position + s_EoC_spread -> SetOptStat(1100); + s_EoC_spread ->SetTextColor(kGreen+2); + s_EoC_spread ->SetTextSize(0.08); + s_EoC_spread -> Draw("sames"); + + + h_EoP_spread -> SetFillStyle(3001); + h_EoP_spread -> SetFillColor(kRed+2); + h_EoP_spread -> Draw("hbarsames"); + gPad -> Update(); + s_EoP_spread = (TPaveStats*)(h_EoP_spread->GetListOfFunctions()->FindObject("stats")); + s_EoP_spread -> SetStatFormat("1.4g"); + s_EoP_spread->SetX1NDC(0.06); //new x start position + s_EoP_spread->SetX2NDC(0.71); //new x end position + s_EoP_spread->SetY1NDC(0.33); //new x start position + s_EoP_spread->SetY2NDC(0.24); //new x end position + s_EoP_spread ->SetOptStat(1100); + s_EoP_spread ->SetTextColor(kRed+2); + s_EoP_spread ->SetTextSize(0.08); + s_EoP_spread -> Draw("sames"); + + /* + h_EoP_spread -> SetFillStyle(3001); + h_EoP_spread -> SetFillColor(kRed+2); + h_EoP_spread -> Draw("hbarsame"); + gPad -> Update(); + */ + + + + + + cplot -> Print((folderName+"/"+folderName+"_history_vsVertex.png").c_str(),"png"); + + cplot -> Print((folderName+"/"+folderName+"_history_vsVertex.pdf").c_str(),"pdf"); + + cplot -> SaveAs((folderName+"/"+folderName+"_history_vsVertex.C").c_str()); + + + + o -> cd(); + + h_template -> Write(); + + h_scOccupancy_eta -> Write(); + h_scOccupancy_phi -> Write(); + h_seedOccupancy_EB -> Write(); + h_seedOccupancy_EEp -> Write(); + h_seedOccupancy_EEm -> Write(); + + g_fit -> Write("g_fit"); + g_c_fit -> Write("g_c_fit"); + g_fit_run -> Write("g_fit_run"); + g_c_fit_run -> Write("g_c_fit_run"); + g_las -> Write("g_las"); + g_LT -> Write("g_LT"); + + h_EoP_chi2 -> Write(); + h_EoC_chi2 -> Write(); + + //ciao + + for(int i = 0; i < nBins; ++i) + { + gStyle->SetOptFit(1111); + + h_EoP[i] -> Write(); + h_EoC[i] -> Write(); + f_EoP[i] -> Write(); + f_EoC[i] -> Write(); + // h_Tsp[i] -> Write(); + // + // h_Cvl[i] -> Write(); + } + + o -> Close(); + + return 0; + } + ///////////--------------------------- E/P calibration ---------------------------------------------------------------------- + + + /////////////////////////////Momentum correction BARREL + +//////////////////////////////////Momentum correction + if(vm.count("momentumCorrectionEB")) { +///////// produce P corrections + + std::string typeEB = "eta1"; + int nRegionsEB = 1; + int nPhiBinsEB = 360; + int nPhiBinsTempEB = 1; + int nEtaBinsEB = 1; + int nEtaBinsTempEB = 1; + int rebinEB = 20; + std::string outputFile = "momentumCalibration2015_EB.root"; + int nEntriesMC = -1; + int nEntriesData = -1; + + // int nRegionsEB = GetNRegionsEB(typeEB); + + std::cout<<"REGIONI: "<GetEntries() << " entries in Data sample" << std::endl; + + // Set branch addresses + float etaSCEle[3], phiSCEle[3], etaEle[3], phiEle[3], esEnergySCEle[3], pAtVtxGsfEle[3], energySCEle[3], R9Ele[3]; + int seedXSCEle[3], seedYSCEle[3], chargeEle[3];//, seedZside; + + int debug=0; + + std::cout<<"debug: "<SetBranchStatus("*",0); + data->SetBranchStatus("etaSCEle",1); + data->SetBranchStatus("phiSCEle",1); + data->SetBranchStatus("etaEle",1); + data->SetBranchStatus("phiEle",1); + data->SetBranchStatus("rawEnergySCEle",1); + data->SetBranchStatus("energySCEle",1); + data->SetBranchStatus("esEnergySCEle",1); + data->SetBranchStatus("pAtVtxGsfEle",1); + data->SetBranchStatus("seedXSCEle",1); + data->SetBranchStatus("seedYSCEle",1); + data->SetBranchStatus("chargeEle",1); + data->SetBranchStatus("R9Ele",1); + + data->SetBranchAddress("etaSCEle", &etaSCEle); + data->SetBranchAddress("phiSCEle", &phiSCEle); + data->SetBranchAddress("etaEle", &etaEle); + data->SetBranchAddress("phiEle", &phiEle); + if (energyTypeEB==0) + data->SetBranchAddress("rawEnergySCEle", &energySCEle); + else + data->SetBranchAddress("energySCEle", &energySCEle); + data->SetBranchAddress("esEnergySCEle", &esEnergySCEle); + data->SetBranchAddress("pAtVtxGsfEle", &pAtVtxGsfEle); + //data->SetBranchAddress("energySCEle", &pAtVtxGsfEle); + data->SetBranchAddress("seedXSCEle", &seedXSCEle); + data->SetBranchAddress("seedYSCEle", &seedYSCEle); + data->SetBranchAddress("chargeEle", &chargeEle); + data->SetBranchAddress("R9Ele", &R9Ele); + + std::cout<<"debug: "<SetBranchStatus("*",0); + mc->SetBranchStatus("etaSCEle",1); + mc->SetBranchStatus("phiSCEle",1); + mc->SetBranchStatus("etaEle",1); + mc->SetBranchStatus("phiEle",1); + mc->SetBranchStatus("rawEnergySCEle",1); + mc->SetBranchStatus("energySCEle",1); + mc->SetBranchStatus("esEnergySCEle",1); + mc->SetBranchStatus("pAtVtxGsfEle",1); + mc->SetBranchStatus("seedXSCEle",1); + mc->SetBranchStatus("seedYSCEle",1); + mc->SetBranchStatus("chargeEle",1); + mc->SetBranchStatus("R9Ele",1); + + mc->SetBranchAddress("etaSCEle", &etaSCEle); + mc->SetBranchAddress("phiSCEle", &phiSCEle); + mc->SetBranchAddress("etaEle", &etaEle); + mc->SetBranchAddress("phiEle", &phiEle); + if (energyTypeEB==0) + mc->SetBranchAddress("rawEnergySCEle", &energySCEle); + else + mc->SetBranchAddress("energySCEle", &energySCEle); + mc->SetBranchAddress("esEnergySCEle", &esEnergySCEle); + mc->SetBranchAddress("pAtVtxGsfEle", &pAtVtxGsfEle); + //mc->SetBranchAddress("energySCEle", &pAtVtxGsfEle); + mc->SetBranchAddress("seedXSCEle", &seedXSCEle); + mc->SetBranchAddress("seedYSCEle", &seedYSCEle); + mc->SetBranchAddress("chargeEle", &chargeEle); + mc->SetBranchAddress("R9Ele", &R9Ele); + + std::cout<<"debug: "< > h_Phi_EB(nPhiBinsEB); // used to map iEta (as defined for Barrel and Endcap geom) into eta + // std::vector > h_Eta_EB(nEtaBinsEB); // used to map iEta (as defined for Barrel and Endcap geom) into eta + TH1F* h_pData_EB[nPhiBinsEB][nEtaBinsEB][nRegionsEB]; + // std::vector > > h_pData_EB(nPhiBinsEB); + TF1* f_pData_EB[nPhiBinsEB][nEtaBinsEB][nRegionsEB]; + + TH1F* histoPull_EB[nEtaBinsEB][nRegionsEB]; + std::cout<<"debug: "< vect1(nEtaBinsEB); + + // Initializate histos in EB + std::cout << ">>> Initialize EB histos" << std::endl; + // std::vector >tempVect(nEtaBinsEB); + for (int k=0; kSumw2(); + temp->SetFillColor(kGreen+2); + temp->SetLineColor(kGreen+2); + temp->SetFillStyle(3004); + h_pData_EB[i][k][j] = temp; + // (tempVect.at(k)).push_back(temp); + + // histoName=Form("EB_Phi_%d_%d_%d", i,k,j); + // temp = new TH1F(histoName, histoName, 360, 0., 360.); + // (h_Phi_EB.at(i)).push_back(temp); + } + + // std::cout<<"qui?"< > h_template_EB(nPhiBinsTempEB); + TH1F* h_template_EB[nPhiBinsTempEB][nEtaBinsTempEB][nRegionsEB]; + + std::cout << ">>> Initialize EB template" << std::endl; + for(int mod = 0; mod < nPhiBinsTempEB; ++mod) + { + for(int k = 0; k < nEtaBinsEB; ++k) + { + for(int j = 0; j < nRegionsEB; ++j) + { + TString histoName; + histoName=Form("EB_template_%d_%d_%d",mod,k,j); + TH1F* temp; + temp = new TH1F(histoName,"",50,0.,maximum); + h_template_EB[mod][k][j] = temp; + // std::cout<<"mah: "< refIdEB; + refIdEB.assign(nPhiBinsEB,0); + + for(int iphi = 0; iphi < nPhiBinsEB; ++iphi) + { + float phi = hPhiBinEB->GetBinCenter(iphi+1); + + phi = 2.*TMath::Pi() + phi + TMath::Pi()*10./180.; + phi -= int(phi/2./TMath::Pi()) * 2.*TMath::Pi(); + + int modPhi = int(phi/(2.*TMath::Pi()/nPhiBinsTempEB)); + if( modPhi == nPhiBinsTempEB ) modPhi = 0; + refIdEB.at(iphi) = modPhi; + // std::cout<GetEntries(); ++entry) + if (nEntriesMC<0) nEntriesMC = mc->GetEntries(); + for(int entry = 0; entry < nEntriesMC; ++entry) + { + if( entry%10000 == 0 ) + std::cout << "reading saved entry " << entry << "\r" << std::flush; + + mc->GetEntry(entry); + // std::cout< etaMax ) continue; + if( fabs(etaEle[iEle]) < etaMin) continue; + if( fabs(chargeEle[iEle]) !=chargeType) continue; + if( R9Ele[iEle] < R9cutEB) continue; + + float ww = 1.; + int index=0; + + // std::cout<etaMin && fabs(etaEle[iEle])FindBin(fabs(etaEle[iEle])) - 1; + if( EtabinEB == nEtaBinsEB ) EtabinEB = 0; + + // int regionId = templIndexEB(typeEB,etaEle[iEle]1,charge2,R92); + // if(regionId == -1) continue; + + if (targetTypeEB==1) + targetVariable=pAtVtxGsfEle[iEle]; + else if (targetTypeEB==2) + targetVariable=energySCEle[iEle]; + else + targetVariable=energySCEle[iEle]/(pAtVtxGsfEle[iEle]); + + // if (modPhi>=180) h_pData_EB[modPhi-180][EtabinEB][0] -> Fill((targetVariable),ww); // if you want to sum the two dees + h_template_EB[modPhi][EtabinEB][index] -> Fill((targetVariable),ww); + + // fill MC histos in eta bins + int PhibinEB = hPhiBinEB->FindBin(phiEle[iEle]) - 1; + if(PhibinEB==nPhiBinsEB) PhibinEB = 0; + + // std::cout<<"MC: fill with "< Fill(pAtVtxGsfEle[iEle],ww); // This is MC + h_phi_mc_EB[index]->Fill(phiEle[iEle],ww); + } + } + + } + + + + + //**************************** loop on DATA + + std::cout << "Loop in Data events " << endl; + + /* for (int i=0; i Fill(0); // This is DATA + } + } + } + */ + // for(int entry = 0; entry < data->GetEntries(); ++entry) + if (nEntriesData<0) nEntriesData = data->GetEntries(); + for(int entry = 0; entry < nEntriesData; ++entry) + { + if( entry%10000 == 0 ) + std::cout << "reading saved entry " << entry << "\r" << std::flush; + + data->GetEntry(entry); + + for (int iEle=0; iEle<2; iEle++) { + // if( isW == 1 ) continue; + if( fabs(etaEle[iEle]) > etaMax ) continue; + if( fabs(etaEle[iEle]) < etaMin) continue; + if( fabs(chargeEle[iEle]) != chargeType) continue; + if( R9Ele[iEle] < R9cutEB) continue; + + float ww = 1.; + int index=0; + + // int iz=0; + // DATA - ENDCAP - ele1 + if (fabs(etaEle[iEle])>etaMin && fabs(etaEle[iEle])FindBin(phiEle[iEle]) - 1; + if( PhibinEB == nPhiBinsEB ) PhibinEB = 0; + + int EtabinEB = hEtaBinEB->FindBin(fabs(etaEle[iEle])) - 1; + if( EtabinEB == nEtaBinsEB ) EtabinEB = 0; + + // int regionId = templIndexEB(typeEB,etaEle[iEle],charge,R9); + // if( regionId == -1 ) continue; + if (targetTypeEB==1) + targetVariable=pAtVtxGsfEle[iEle]; + else if (targetTypeEB==2) + targetVariable=energySCEle[iEle]; + else + targetVariable=energySCEle[iEle]/(pAtVtxGsfEle[iEle]); + + // if (PhibinEB>=180) h_pData_EB[PhibinEB-180][EtabinEB][0] -> Fill((targetVariable),ww); // if you want to sum the two dees + h_pData_EB[PhibinEB][EtabinEB][index] -> Fill((targetVariable),ww); // This is DATA + // (h_Phi_EB.at(PhibinEB)).at(index) -> Fill(phiEle[iEle]); + + h_phi_data_EB[index] -> Fill(phiEle[iEle]); + h_eta_data_EB[index] -> Fill(fabs(etaEle[iEle])); + + } + } + } + + std::cout << "End loop: Analyze events " << endl; + + + + + + + //---------------- + // Initializations + + // initialize TGraphs + TFile* o = new TFile((outputFile+"_"+typeEB+".root").c_str(),"RECREATE"); + + TGraphErrors* g_pData_EB[nEtaBinsEB][nRegionsEB];// = new TGraphErrors**[nEtaBinsEB][nRegionsEB]; + TGraphErrors* g_pAbs_EB[nEtaBinsEB][nRegionsEB];// = new TGraphErrors**[nEtaBinsEB][nRegionsEB]; + + for (int a=0; a > templateHistoFuncEB(nPhiBinsTempEB); + histoFunc* templateHistoFuncEB[nPhiBinsTempEB][nEtaBinsEB][nRegionsEB]; + + for(int mod = 0; mod < nPhiBinsTempEB; ++mod) + { + for(int k = 0; k < nEtaBinsEB; ++k) + { + for(int j = 0; j < nRegionsEB; ++j) + { + // h_template_EB[mod][k][j] -> Rebin(rebinEB); + templateHistoFuncEB[mod][k][j] = new histoFunc(h_template_EB[mod][k][j]); + } + } + } + + //------------------- + // Template Fit in EB + + if( typeEB != "none" ) + { + float pVector[nPhiBinsEB][nEtaBinsEB][2]; + float pVectorErr[nPhiBinsEB][nEtaBinsEB][2]; + + for(int i = 0; i < nPhiBinsEB; ++i) + { + for(int k = 0; k < nEtaBinsEB; ++k) + { + for(int j = 0; j < nRegionsEB; ++j) + { + float flPhi = hPhiBinEB->GetXaxis()->GetBinCenter(i); + + // (h_pMC_EB.at(i)).at(j) -> Rebin(rebinEB); + // h_pData_EB[i][k][j] -> Rebin(rebinEB); + + + // define the fitting function + // N.B. [0] * ( [1] * f( [1]*(x-[2]) ) ) + + char funcName[50]; + + sprintf(funcName,"f_pData_%d_%d_%d_Ref_%d_%d_%d_EB",i,k,j,refIdEB.at(i),k,j); + TF1* temp; + temp = new TF1(funcName, templateHistoFuncEB[refIdEB.at(i)][k][j], 0., maximum, 3, "histoFunc"); + f_pData_EB[i][k][j] = temp; + + f_pData_EB[i][k][j] -> SetParName(0,"Norm"); + f_pData_EB[i][k][j] -> SetParName(1,"Scale factor"); + + f_pData_EB[i][k][j] -> SetLineWidth(1); + f_pData_EB[i][k][j] -> SetLineColor(kGreen+2); + f_pData_EB[i][k][j] -> SetNpx(10000); + + // f_pData_EB[i][k][j] -> SetParameter(0, xNorm); + f_pData_EB[i][k][j] -> SetParameter(0, 1.); + f_pData_EB[i][k][j] -> SetParameter(1, 1); + + float shift=0.5; + if (targetTypeEB!=3) + shift=3.; + f_pData_EB[i][k][j] -> SetParameter(2, shift); + + std::cout << "***** Fitting DATA EB " << flPhi << " (" << i << "," << j << "): "; + + TFitResultPtr rp; + int fStatus; + + for(int trial = 0; trial < 300; ++trial) + { + rp = h_pData_EB[i][k][j] -> Fit(funcName, "QR+"); + fStatus = rp; + + // if( fStatus !=4 && f_pData_EB[i][k][j]->GetParError(1) != 0. && f_pData_EB[i][k][j] -> GetMaximumX(0.,500.)>30. ) + if( fStatus !=4 && f_pData_EB[i][k][j]->GetParError(1) != 0. && f_pData_EB[i][k][j] -> GetMaximumX(0.,maximum)>0. ) + { + std::cout << "fit OK "; + + double coeff = f_pData_EB[i][k][j]->GetParameter(1); + // double eee = f_pData_EB[i][k][j]->GetParError(1); + pVector[i][k][j] = coeff; + + break; + } + else if( trial %5 == 0 ) + { + pVector[i][k][j]=-1; + // std::cout<<" BAD FIT. Make another attempt with different parameters.. "< SetParameter(2, shift); + if (shift==-25) shift+=50.; + if (shift==-0.6) shift+=1.07; + // trial = 0; + // getchar(); + } + } + + // std::cout<<"media del bin "< GetMaximumX(0.,maximum)<GetParameter(2)*(f_pData_EB.at(0)).at(0)->GetParameter(1)+(h_template_EB.at(0)).at(j)->GetMean()<GetParError(1) != 0. && f_pData_EB[i][k][j] -> GetMaximumX(0.,500.)>30. ) { + if( fStatus !=4 && f_pData_EB[i][k][j]->GetParError(1) != 0. && f_pData_EB[i][k][j] -> GetMaximumX(0.,maximum)>0. ) { + pVector[i][k][j] = f_pData_EB[i][k][j] -> GetMaximumX(0.,maximum); + pVectorErr[i][k][j] = (h_pData_EB[i][k][j] -> GetRMS())/sqrt(h_pData_EB[i][k][j] -> GetEntries()); + } + else { + std::cout<<"BAD FIT!!!"<GetXaxis()->GetBinCenter(c); + int xVar=c*(int(360/nPhiBinsEB)); + + if (pVector[c][a][jc]==-1) { + // pVector[c][a][jc]=pMean[a][jc]; //if fit has failed, fill with the mean + pVector[c][a][jc]=pVector[c+1][a][jc]; //if fit has failed, fill with the mean + std::cout<<"be careful!! ("<1.15) { + if ( (pVector[c-1][a][jc]/pMean[a][jc])>1.15 ) { + g_pData_EB[a][jc] -> SetPoint(c,flPhi,pVector[c+1][a][jc]/pMean[a][jc]); + std::cout<<"caso A -iphi: "< SetPoint(c,flPhi,pVector[c-1][a][jc]/pMean[a][jc]); + std::cout<<"caso B -iphi: "< SetPoint(c,flPhi,pVector[c+1][a][jc]/pMean[a][jc]); + std::cout<<"caso C-iphi: "< SetPoint(c,flPhi,pVector[c-1][a][jc]/pMean[a][jc]); + std::cout<<"caso D-iphi: "< SetPoint(c,flPhi,pVector[c][a][jc]/pMean[a][jc]); + std::cout<<"caso E-iphi: "<180) xVar-=180; + // if (xVar>=90) continue; + //if (xVar<0) xVar+=180; + + // g_pData_EB[a][jc] -> SetPoint(c,xVar,pVector[c][a][jc]/pMean[a][jc]); + // g_pData_EB[a][jc] -> SetPoint(c,flPhi,pVector[c][a][jc]/pMean[a][jc]); + g_pAbs_EB[a][jc] -> SetPoint(c,xVar,pVector[c][a][jc]); + //g_pAbs_EB[a][jc] -> SetPoint(c,c*(int(360/nPhiBinsEB)),pVector[c][a][jc]); + histoPull_EB[a][jc] -> Fill((pVector[c][a][jc]-pMean[a][jc])/pVectorErr[c][a][jc]); + + // float err=(pVectorErr[c][a][jc]/pMean[a][jc])*(pVectorErr[c][a][jc]/pMean[a][jc])+(pVector[c][a][jc]/(pMean[a][jc]*pMean[a][jc])*(pMeanErr2[a][jc]*pMeanErr2[a][jc]))*(pVector[c][a][jc]/(pMean[a][jc]*pMean[a][jc])*(pMeanErr2[a][jc]*pMeanErr2[a][jc])); + // float err=(pVectorErr[c][a][jc]/pMean[a][jc]); + // float err=0.; + + // g_pData_EB[a][jc] -> SetPointError(c,0,err); + g_pData_EB[a][jc] -> SetPointError(c,0,0); + g_pAbs_EB[a][jc] -> SetPointError(c,0,pVectorErr[c][a][jc]); + // g_pAbs_EB[a][jc] -> SetPointError(c,0,0.); + // std::cout<GetXaxis()->GetBinCenter(i+1); + g_pData_EB[a][j] -> SetPoint(i, flPhi, 1.); + } + } + } + } + + + + std::cout<<"output"< cd(); + + for (int a=0; aGetN()!=0) g_pMC_EB[j] -> Write(Name); + Name = Form("g_pData_EB_%d_%d",a,j); + if(g_pData_EB[a][j]->GetN()!=0) g_pData_EB[a][j] -> Write(Name); + Name = Form("g_pAbs_EB_%d_%d",a,j); + if(g_pAbs_EB[a][j]->GetN()!=0) g_pAbs_EB[a][j] -> Write(Name); + //Name = Form("g_Rat_EB_%d",j); + //if(g_Rat_EB[j]->GetN()!=0) g_Rat_EB[j] -> Write(Name); + } + } + + for(int j =0; j< nRegionsEB; ++j) + { + if( h_phi_data_EB[j] -> GetEntries() !=0 ) h_phi_data_EB[j] -> Write(); + } + + h_template_EB[0][0][0] -> Write(); + // h_template_EB[0][0][1] -> Write(); + // h_template_EB[0][1][0] -> Write(); + // h_template_EB[0][1][1] -> Write(); + // h_template_EB[0][2][0] -> Write(); + // h_template_EB[0][2][1] -> Write(); + // h_template_EB[0][4][0] -> Write(); + // h_template_EB[0][4][1] -> Write(); + + for (int k=0; k Write(); + } + } + } + + for (int k=0; kWrite(); + } + } + + o -> Close(); + + + + return 0; +} + + +//////////////////////////////////Momentum correction + if(vm.count("momentumCorrectionEE")) { +///////// produce P corrections + + std::string typeEE = "eta1"; + int nRegionsEE = 3; + int nPhiBinsEE = 360; + int nPhiBinsTempEE = 1; + int nEtaBinsEE = 1; + int nEtaBinsTempEE = 1; + int rebinEE = 20; + std::string outputFile = "momentumCalibration2015_EE.root"; + int nEntriesMC = -1; + int nEntriesData = -1; + + // int nRegionsEE = GetNRegionsEE(typeEE); + + std::cout<<"REGIONI: "<GetEntries() << " entries in Data sample" << std::endl; + + // Set branch addresses + float etaSCEle[3], phiSCEle[3], etaEle[3], phiEle[3], esEnergySCEle[3], pAtVtxGsfEle[3], energySCEle[3], R9Ele[3]; + int seedXSCEle[3], seedYSCEle[3], chargeEle[3];//, seedZside; + + int debug=0; + + std::cout<<"debug: "<SetBranchStatus("*",0); + data->SetBranchStatus("etaSCEle",1); + data->SetBranchStatus("phiSCEle",1); + data->SetBranchStatus("etaEle",1); + data->SetBranchStatus("phiEle",1); + data->SetBranchStatus("rawEnergySCEle",1); + data->SetBranchStatus("energySCEle",1); + data->SetBranchStatus("esEnergySCEle",1); + data->SetBranchStatus("pAtVtxGsfEle",1); + data->SetBranchStatus("seedXSCEle",1); + data->SetBranchStatus("seedYSCEle",1); + data->SetBranchStatus("chargeEle",1); + data->SetBranchStatus("R9Ele",1); + + data->SetBranchAddress("etaSCEle", &etaSCEle); + data->SetBranchAddress("phiSCEle", &phiSCEle); + data->SetBranchAddress("etaEle", &etaEle); + data->SetBranchAddress("phiEle", &phiEle); + if (energyTypeEE==0) + data->SetBranchAddress("rawEnergySCEle", &energySCEle); + else + data->SetBranchAddress("energySCEle", &energySCEle); + data->SetBranchAddress("esEnergySCEle", &esEnergySCEle); + data->SetBranchAddress("pAtVtxGsfEle", &pAtVtxGsfEle); + //data->SetBranchAddress("energySCEle", &pAtVtxGsfEle); + data->SetBranchAddress("seedXSCEle", &seedXSCEle); + data->SetBranchAddress("seedYSCEle", &seedYSCEle); + data->SetBranchAddress("chargeEle", &chargeEle); + data->SetBranchAddress("R9Ele", &R9Ele); + + std::cout<<"debug: "<SetBranchStatus("*",0); + mc->SetBranchStatus("etaSCEle",1); + mc->SetBranchStatus("phiSCEle",1); + mc->SetBranchStatus("etaEle",1); + mc->SetBranchStatus("phiEle",1); + mc->SetBranchStatus("rawEnergySCEle",1); + mc->SetBranchStatus("energySCEle",1); + mc->SetBranchStatus("esEnergySCEle",1); + mc->SetBranchStatus("pAtVtxGsfEle",1); + mc->SetBranchStatus("seedXSCEle",1); + mc->SetBranchStatus("seedYSCEle",1); + mc->SetBranchStatus("chargeEle",1); + mc->SetBranchStatus("R9Ele",1); + + mc->SetBranchAddress("etaSCEle", &etaSCEle); + mc->SetBranchAddress("phiSCEle", &phiSCEle); + mc->SetBranchAddress("etaEle", &etaEle); + mc->SetBranchAddress("phiEle", &phiEle); + if (energyTypeEE==0) + mc->SetBranchAddress("rawEnergySCEle", &energySCEle); + else + mc->SetBranchAddress("energySCEle", &energySCEle); + mc->SetBranchAddress("esEnergySCEle", &esEnergySCEle); + mc->SetBranchAddress("pAtVtxGsfEle", &pAtVtxGsfEle); + //mc->SetBranchAddress("energySCEle", &pAtVtxGsfEle); + mc->SetBranchAddress("seedXSCEle", &seedXSCEle); + mc->SetBranchAddress("seedYSCEle", &seedYSCEle); + mc->SetBranchAddress("chargeEle", &chargeEle); + mc->SetBranchAddress("R9Ele", &R9Ele); + + std::cout<<"debug: "< > h_Phi_EE(nPhiBinsEE); // used to map iEta (as defined for Barrel and Endcap geom) into eta + // std::vector > h_Eta_EE(nEtaBinsEE); // used to map iEta (as defined for Barrel and Endcap geom) into eta + TH1F* h_pData_EE[nPhiBinsEE][nEtaBinsEE][nRegionsEE]; + // std::vector > > h_pData_EE(nPhiBinsEE); + TF1* f_pData_EE[nPhiBinsEE][nEtaBinsEE][nRegionsEE]; + + TH1F* histoPull_EE[nEtaBinsEE][nRegionsEE]; + std::cout<<"debug: "< vect1(nEtaBinsEE); + + // Initializate histos in EE + std::cout << ">>> Initialize EE histos" << std::endl; + // std::vector >tempVect(nEtaBinsEE); + for (int k=0; kSumw2(); + temp->SetFillColor(kGreen+2); + temp->SetLineColor(kGreen+2); + temp->SetFillStyle(3004); + h_pData_EE[i][k][j] = temp; + // (tempVect.at(k)).push_back(temp); + + // histoName=Form("EE_Phi_%d_%d_%d", i,k,j); + // temp = new TH1F(histoName, histoName, 360, 0., 360.); + // (h_Phi_EE.at(i)).push_back(temp); + } + + // std::cout<<"qui?"< > h_template_EE(nPhiBinsTempEE); + TH1F* h_template_EE[nPhiBinsTempEE][nEtaBinsTempEE][nRegionsEE]; + + std::cout << ">>> Initialize EE template" << std::endl; + for(int mod = 0; mod < nPhiBinsTempEE; ++mod) + { + for(int k = 0; k < nEtaBinsEE; ++k) + { + for(int j = 0; j < nRegionsEE; ++j) + { + TString histoName; + histoName=Form("EE_template_%d_%d_%d",mod,k,j); + TH1F* temp; + temp = new TH1F(histoName,"",50,0.,maximum); + h_template_EE[mod][k][j] = temp; + // std::cout<<"mah: "<GetNbinsX(); ix++) + for(int iy =0; iyGetNbinsY(); iy++) + { + mapConversionEEp->SetBinContent(ix+1,iy+1,0); + mapConversionEEm->SetBinContent(ix+1,iy+1,0); + } + + + // fill MC templates + + std::vector refIdEE; + refIdEE.assign(nPhiBinsEE,0); + + for(int iphi = 0; iphi < nPhiBinsEE; ++iphi) + { + float phi = hPhiBinEE->GetBinCenter(iphi+1); + + phi = 2.*TMath::Pi() + phi + TMath::Pi()*10./180.; + phi -= int(phi/2./TMath::Pi()) * 2.*TMath::Pi(); + + int modPhi = int(phi/(2.*TMath::Pi()/nPhiBinsTempEE)); + if( modPhi == nPhiBinsTempEE ) modPhi = 0; + refIdEE.at(iphi) = modPhi; + // std::cout<GetEntries(); ++entry) + if (nEntriesMC<0) nEntriesMC = mc->GetEntries(); + for(int entry = 0; entry < nEntriesMC; ++entry) + { + if( entry%10000 == 0 ) + std::cout << "reading saved entry " << entry << "\r" << std::flush; + + mc->GetEntry(entry); + // std::cout< etaMax ) continue; + if( fabs(etaEle[iEle]) < etaMin) continue; + if( fabs(chargeEle[iEle]) !=chargeType) continue; + if( R9Ele[iEle] < R9cutEE) continue; + + float ww = 1.; + int index=0; + + int iz=0; + // std::cout<etaMin && fabs(etaEle[iEle])0 ) { mapConversionEEp -> SetBinContent(seedXSCEle[iEle],seedYSCEle[iEle],etaEle[iEle]); iz=1; index=0; } + if( etaEle[iEle]<0 ) {mapConversionEEm -> SetBinContent(seedXSCEle[iEle],seedYSCEle[iEle],etaEle[iEle]); iz=-1; index=1; } + + int iphi = eRings->GetEndcapIphi(seedXSCEle[iEle],seedYSCEle[iEle],iz); + + // fill MC templates + int modPhi = int (iphi/(360./nPhiBinsTempEE)); + if( modPhi == nPhiBinsTempEE ) modPhi = 0; + + int EtabinEE = hEtaBinEE->FindBin(fabs(etaEle[iEle])) - 1; + if( EtabinEE == nEtaBinsEE ) EtabinEE = 0; + + // int regionId = templIndexEE(typeEE,etaEle[iEle]1,charge2,R92); + // if(regionId == -1) continue; + + if (targetTypeEE==1) + targetVariable=pAtVtxGsfEle[iEle]; + else if (targetTypeEE==2) + targetVariable=energySCEle[iEle]; + else + targetVariable=energySCEle[iEle]/(pAtVtxGsfEle[iEle]-esEnergySCEle[iEle]); + + // if (index==1) h_template_EE[modPhi][EtabinEE][0] -> Fill((targetVariable),ww); //if you want to sum EE+ and EE- + // if (modPhi>=180) h_pData_EE[modPhi-180][EtabinEE][0] -> Fill((targetVariable),ww); // if you want to sum the two dees + h_template_EE[modPhi][EtabinEE][index] -> Fill((targetVariable),ww); + h_template_EE[modPhi][EtabinEE][2] -> Fill((targetVariable),ww); //this is the sum of EE+ and EE- + + // fill MC histos in eta bins + int PhibinEE = hPhiBinEE->FindBin(phiEle[iEle]) - 1; + if(PhibinEE==nPhiBinsEE) PhibinEE = 0; + + // std::cout<<"MC: fill with "< Fill(pAtVtxGsfEle[iEle],ww); // This is MC + h_phi_mc_EE[index]->Fill(phiEle[iEle],ww); + h_phi_mc_EE[2]->Fill(phiEle[iEle],ww); + } + } + + } + + + + + //**************************** loop on DATA + + std::cout << "Loop in Data events " << endl; + + /* for (int i=0; i Fill(0); // This is DATA + } + } + } + */ + // for(int entry = 0; entry < data->GetEntries(); ++entry) + if (nEntriesData<0) nEntriesData = data->GetEntries(); + for(int entry = 0; entry < nEntriesData; ++entry) + { + if( entry%10000 == 0 ) + std::cout << "reading saved entry " << entry << "\r" << std::flush; + + data->GetEntry(entry); + + for (int iEle=0; iEle<2; iEle++) { + // if( isW == 1 ) continue; + if( fabs(etaEle[iEle]) > etaMax ) continue; + if( fabs(etaEle[iEle]) < etaMin) continue; + if( fabs(chargeEle[iEle]) != chargeType) continue; + if( R9Ele[iEle] < R9cutEE) continue; + + float ww = 1.; + int index=0; + + // int iz=0; + // DATA - ENDCAP - ele1 + if (fabs(etaEle[iEle])>etaMin && fabs(etaEle[iEle])0 ) { mapConversionEEp -> SetBinContent(seedXSCEle[iEle],seedYSCEle[iEle],etaEle[iEle]); index=0; } + if( etaEle[iEle]<0 ) { mapConversionEEm -> SetBinContent(seedXSCEle[iEle],seedYSCEle[iEle],etaEle[iEle]); index=1; } + + int PhibinEE = hPhiBinEE->FindBin(phiEle[iEle]) - 1; + if( PhibinEE == nPhiBinsEE ) PhibinEE = 0; + + int EtabinEE = hEtaBinEE->FindBin(fabs(etaEle[iEle])) - 1; + if( EtabinEE == nEtaBinsEE ) EtabinEE = 0; + + // int regionId = templIndexEE(typeEE,etaEle[iEle],charge,R9); + // if( regionId == -1 ) continue; + if (targetTypeEE==1) + targetVariable=pAtVtxGsfEle[iEle]; + else if (targetTypeEE==2) + targetVariable=energySCEle[iEle]; + else + targetVariable=energySCEle[iEle]/(pAtVtxGsfEle[iEle]-esEnergySCEle[iEle]); + + // if (PhibinEE>=180) h_pData_EE[PhibinEE-180][EtabinEE][0] -> Fill((targetVariable),ww); // if you want to sum the two dees + h_pData_EE[PhibinEE][EtabinEE][index] -> Fill((targetVariable),ww); // This is DATA + // (h_Phi_EE.at(PhibinEE)).at(index) -> Fill(phiEle[iEle]); + h_pData_EE[PhibinEE][EtabinEE][2] -> Fill((targetVariable),ww); // if you want to sum EE+ and EE- + + h_phi_data_EE[index] -> Fill(phiEle[iEle]); + h_eta_data_EE[index] -> Fill(fabs(etaEle[iEle])); + h_phi_data_EE[2] -> Fill(phiEle[iEle]); + h_eta_data_EE[2] -> Fill(fabs(etaEle[iEle])); + + } + } + } + + std::cout << "End loop: Analyze events " << endl; + + + + + + + //---------------- + // Initializations + + // initialize TGraphs + TFile* o = new TFile((outputFile+"_"+typeEE+".root").c_str(),"RECREATE"); + + TGraphErrors* g_pData_EE[nEtaBinsEE][nRegionsEE];// = new TGraphErrors**[nEtaBinsEE][nRegionsEE]; + TGraphErrors* g_pAbs_EE[nEtaBinsEE][nRegionsEE];// = new TGraphErrors**[nEtaBinsEE][nRegionsEE]; + + for (int a=0; a > templateHistoFuncEE(nPhiBinsTempEE); + histoFunc* templateHistoFuncEE[nPhiBinsTempEE][nEtaBinsEE][nRegionsEE]; + + for(int mod = 0; mod < nPhiBinsTempEE; ++mod) + { + for(int k = 0; k < nEtaBinsEE; ++k) + { + for(int j = 0; j < nRegionsEE; ++j) + { + // h_template_EE[mod][k][j] -> Rebin(rebinEE); + templateHistoFuncEE[mod][k][j] = new histoFunc(h_template_EE[mod][k][j]); + } + } + } + + //------------------- + // Template Fit in EE + + if( typeEE != "none" ) + { + float pVector[nPhiBinsEE][nEtaBinsEE][nRegionsEE]; + float pVectorErr[nPhiBinsEE][nEtaBinsEE][nRegionsEE]; + + for(int i = 0; i < nPhiBinsEE; ++i) + { + for(int k = 0; k < nEtaBinsEE; ++k) + { + for(int j = 0; j < nRegionsEE; ++j) + { + float flPhi = hPhiBinEE->GetXaxis()->GetBinCenter(i); + + // (h_pMC_EE.at(i)).at(j) -> Rebin(rebinEE); + // h_pData_EE[i][k][j] -> Rebin(rebinEE); + + + // define the fitting function + // N.B. [0] * ( [1] * f( [1]*(x-[2]) ) ) + + char funcName[50]; + + sprintf(funcName,"f_pData_%d_%d_%d_Ref_%d_%d_%d_EE",i,k,j,refIdEE.at(i),k,j); + TF1* temp; + temp = new TF1(funcName, templateHistoFuncEE[refIdEE.at(i)][k][j], 0., maximum, 3, "histoFunc"); + f_pData_EE[i][k][j] = temp; + + f_pData_EE[i][k][j] -> SetParName(0,"Norm"); + f_pData_EE[i][k][j] -> SetParName(1,"Scale factor"); + + f_pData_EE[i][k][j] -> SetLineWidth(1); + f_pData_EE[i][k][j] -> SetLineColor(kGreen+2); + f_pData_EE[i][k][j] -> SetNpx(10000); + + // f_pData_EE[i][k][j] -> SetParameter(0, xNorm); + f_pData_EE[i][k][j] -> SetParameter(0, 1.); + f_pData_EE[i][k][j] -> SetParameter(1, 1); + + float shift=0.5; + if (targetTypeEE!=3) + shift=3.; + f_pData_EE[i][k][j] -> SetParameter(2, shift); + + std::cout << "***** Fitting DATA EE " << flPhi << " (" << i << "," << j << "): "; + + TFitResultPtr rp; + int fStatus; + + for(int trial = 0; trial < 300; ++trial) + { + rp = h_pData_EE[i][k][j] -> Fit(funcName, "QR+"); + fStatus = rp; + + // if( fStatus !=4 && f_pData_EE[i][k][j]->GetParError(1) != 0. && f_pData_EE[i][k][j] -> GetMaximumX(0.,500.)>30. ) + if( fStatus !=4 && f_pData_EE[i][k][j]->GetParError(1) != 0. && f_pData_EE[i][k][j] -> GetMaximumX(0.,maximum)>0. ) + { + std::cout << "fit OK "; + + double coeff = f_pData_EE[i][k][j]->GetParameter(1); + // double eee = f_pData_EE[i][k][j]->GetParError(1); + pVector[i][k][j] = coeff; + + break; + } + else if( trial %5 == 0 ) + { + pVector[i][k][j]=-1; + // std::cout<<" BAD FIT. Make another attempt with different parameters.. "< SetParameter(2, shift); + if (shift==-25) shift+=50.; + if (shift==-0.6) shift+=1.07; + // trial = 0; + // getchar(); + } + } + + // std::cout<<"media del bin "< GetMaximumX(0.,maximum)<GetParameter(2)*(f_pData_EE.at(0)).at(0)->GetParameter(1)+(h_template_EE.at(0)).at(j)->GetMean()<GetParError(1) != 0. && f_pData_EE[i][k][j] -> GetMaximumX(0.,500.)>30. ) { + if( fStatus !=4 && f_pData_EE[i][k][j]->GetParError(1) != 0. && f_pData_EE[i][k][j] -> GetMaximumX(0.,maximum)>0. ) { + pVector[i][k][j] = f_pData_EE[i][k][j] -> GetMaximumX(0.,maximum); + pVectorErr[i][k][j] = (h_pData_EE[i][k][j] -> GetRMS())/sqrt(h_pData_EE[i][k][j] -> GetEntries()); + } + else { + std::cout<<"BAD FIT!!!"<GetXaxis()->GetBinCenter(c); + int xVar=c*(int(360/nPhiBinsEE)); + + if (pVector[c][a][jc]==-1) { + // pVector[c][a][jc]=pMean[a][jc]; //if fit has failed, fill with the mean + pVector[c][a][jc]=pVector[c+1][a][jc]; //if fit has failed, fill with the mean + std::cout<<"be careful!! ("<1.15) { + if ( (pVector[c-1][a][jc]/pMean[a][jc])>1.15 ) { + g_pData_EE[a][jc] -> SetPoint(c,flPhi,pVector[c+1][a][jc]/pMean[a][jc]); + std::cout<<"caso A -iphi: "< SetPoint(c,flPhi,pVector[c-1][a][jc]/pMean[a][jc]); + std::cout<<"caso B -iphi: "< SetPoint(c,flPhi,pVector[c+1][a][jc]/pMean[a][jc]); + std::cout<<"caso C-iphi: "< SetPoint(c,flPhi,pVector[c-1][a][jc]/pMean[a][jc]); + std::cout<<"caso D-iphi: "< SetPoint(c,flPhi,pVector[c][a][jc]/pMean[a][jc]); + std::cout<<"caso E-iphi: "<180) xVar-=180; + // if (xVar>=90) continue; + //if (xVar<0) xVar+=180; + + // g_pData_EE[a][jc] -> SetPoint(c,xVar,pVector[c][a][jc]/pMean[a][jc]); + // g_pData_EE[a][jc] -> SetPoint(c,flPhi,pVector[c][a][jc]/pMean[a][jc]); + g_pAbs_EE[a][jc] -> SetPoint(c,xVar,pVector[c][a][jc]); + //g_pAbs_EE[a][jc] -> SetPoint(c,c*(int(360/nPhiBinsEE)),pVector[c][a][jc]); + histoPull_EE[a][jc] -> Fill((pVector[c][a][jc]-pMean[a][jc])/pVectorErr[c][a][jc]); + + // float err=(pVectorErr[c][a][jc]/pMean[a][jc])*(pVectorErr[c][a][jc]/pMean[a][jc])+(pVector[c][a][jc]/(pMean[a][jc]*pMean[a][jc])*(pMeanErr2[a][jc]*pMeanErr2[a][jc]))*(pVector[c][a][jc]/(pMean[a][jc]*pMean[a][jc])*(pMeanErr2[a][jc]*pMeanErr2[a][jc])); + // float err=(pVectorErr[c][a][jc]/pMean[a][jc]); + // float err=0.; + + // g_pData_EE[a][jc] -> SetPointError(c,0,err); + g_pData_EE[a][jc] -> SetPointError(c,0,0); + g_pAbs_EE[a][jc] -> SetPointError(c,0,pVectorErr[c][a][jc]); + // g_pAbs_EE[a][jc] -> SetPointError(c,0,0.); + // std::cout<GetXaxis()->GetBinCenter(i+1); + g_pData_EE[a][j] -> SetPoint(i, flPhi, 1.); + } + } + } + } + + + + + + + //------- + // Output + + o -> cd(); + + for (int a=0; aGetN()!=0) g_pMC_EE[j] -> Write(Name); + Name = Form("g_pData_EE_%d_%d",a,j); + if(g_pData_EE[a][j]->GetN()!=0) g_pData_EE[a][j] -> Write(Name); + Name = Form("g_pAbs_EE_%d_%d",a,j); + if(g_pAbs_EE[a][j]->GetN()!=0) g_pAbs_EE[a][j] -> Write(Name); + //Name = Form("g_Rat_EE_%d",j); + //if(g_Rat_EE[j]->GetN()!=0) g_Rat_EE[j] -> Write(Name); + } + } + + for(int j =0; j< nRegionsEE; ++j) + { + if( h_phi_data_EE[j] -> GetEntries() !=0 ) h_phi_data_EE[j] -> Write(); + } + + mapConversionEEp -> Write(); + mapConversionEEm -> Write(); + + h_template_EE[0][0][0] -> Write(); + h_template_EE[0][0][1] -> Write(); + h_template_EE[0][0][2] -> Write(); + // h_template_EE[0][1][0] -> Write(); + // h_template_EE[0][1][1] -> Write(); + // h_template_EE[0][2][0] -> Write(); + // h_template_EE[0][2][1] -> Write(); + // h_template_EE[0][4][0] -> Write(); + // h_template_EE[0][4][1] -> Write(); + + for (int k=0; k Write(); + } + } + } + + for (int k=0; kWrite(); + } + } + + o -> Close(); + + + + return 0; +} + +///////////////////////LUCA + + if(vm.count("EOverPCalib") && vm.count("doEB")) { + + std::cout<<"---- START E/P CALIBRATION: BARREL ----"< > > jsonMap; + jsonMap = readJSONFile(jsonFileName); + // std::cout<<"JSON file: "< g_EoC_EB; + + // for(int i = 0; i < nRegionsEB; ++i){ + // TString Name = Form("g_pData_EB_0_%d",i); + TString Name = Form("g_EoC_EB_0"); + g_EoC_EB.push_back( (TGraphErrors*)(momentumscale->Get(Name)) ); + // } + + std::cout<<"momentum calibration file correctly opened"< g_EoE_EB; + + for(int i = 0; i < nRegionsEB; ++i){ + TString Name = Form("g_pData_EB_0_%d",i); + g_EoE_EB.push_back( (TGraphErrors*)(energyscale->Get(Name)) ); + } + + std::cout<<"energy calibration file correctly opened"<GetEntries(); + + std::cout<<"number of events: "< exit "< exit "< > > jsonMap; + jsonMap = readJSONFile(jsonFileName); + std::cout<<"JSON file: "< g_EoC_EE; + + // for(int i = 0; i < nRegionsEE; ++i){ + // TString Name = Form("g_pData_EE_0_%d",i); + TString Name = Form("g_EoC_EE_0"); + g_EoC_EE.push_back( (TGraphErrors*)(f4->Get(Name)) ); + // } + + /// open calibration energy graph + TFile* f5 = new TFile((inputEnergyScale.c_str()));//+"_"+typeEB+"_"+typeEE+".root").c_str()); + std::vector g_EoE_EE; + + for(int i = 0; i < nRegionsEE; ++i){ + TString Name = Form("g_pData_EE_0_%d",i); + g_EoE_EE.push_back( (TGraphErrors*)(f5->Get(Name)) ); + } + + ///Use the whole sample statistics if numberOfEvents < 0 + if ( numberOfEvents < 0 ) numberOfEvents = data->GetEntries(); + + + /// run in normal mode: full statistics + if ( splitStat == 0 ) { + + TString name ; + TString name_tmp; + + if(isMiscalib == true && useZ == 1 && isR9selection ==true && isEPselection == false && isfbrem == false && isPtCut ==false ) + name_tmp = Form ("%s_WZ_R9_miscalib_EE",outputFile.c_str()); + else if(isMiscalib == true && useZ == 1 && isR9selection ==false && isEPselection == false && isfbrem == true && isPtCut ==false ) + name_tmp = Form ("%s_WZ_Fbrem_miscalib_EE",outputFile.c_str()); + else if(isMiscalib == true && useZ == 1 && isR9selection ==true && isEPselection == false && isfbrem == false && isPtCut ==true ) + name_tmp = Form ("%s_WZ_PT_miscalib_EE",outputFile.c_str()); + else if(isMiscalib == true && useZ == 1 && isR9selection ==true && isEPselection == true && isfbrem == false && isPtCut ==false ) + name_tmp = Form ("%s_WZ_EP_miscalib_EE",outputFile.c_str()); + else if(isMiscalib == true && useZ == 1 && isEPselection ==false && isR9selection==false && isPtCut ==false && isfbrem ==false ) + name_tmp =Form ("%s_WZ_noEP_miscalib_EE",outputFile.c_str()); + + else if(isMiscalib == false && useZ == 1 && isR9selection ==true && isEPselection == false && isfbrem == false && isPtCut ==false ) + name_tmp = Form ("%s_WZ_R9_EE",outputFile.c_str()); + else if(isMiscalib == false && useZ == 1 && isR9selection ==false && isEPselection == false && isfbrem == true && isPtCut ==false ) + name_tmp = Form ("%s_WZ_Fbrem_EE",outputFile.c_str()); + else if(isMiscalib == false && useZ == 1 && isR9selection ==true && isEPselection == false && isfbrem == false && isPtCut ==true ) + name_tmp = Form ("%s_WZ_PT_EE",outputFile.c_str()); + else if(isMiscalib == false && useZ == 1 && isR9selection ==true && isEPselection == true && isfbrem == false && isPtCut ==false ) + name_tmp = Form ("%s_WZ_EP_EE",outputFile.c_str()); + else if(isMiscalib == false && useZ == 1 && isEPselection ==false && isR9selection==false && isPtCut ==false && isfbrem ==false ) + name_tmp =Form ("%s_WZ_noEP_EE",outputFile.c_str()); + + + + else if(isMiscalib == true && useZ == 0 && isR9selection ==true && isEPselection == false && isfbrem == false && isPtCut ==false ) + name_tmp = Form ("%s_W_R9_miscalib_EE",outputFile.c_str()); + else if(isMiscalib == true && useZ == 0 && isR9selection ==false && isEPselection == false && isfbrem == true && isPtCut ==false ) + name_tmp = Form ("%s_W_Fbrem_miscalib_EE",outputFile.c_str()); + else if(isMiscalib == true && useZ == 0 && isR9selection ==true && isEPselection == false && isfbrem == false && isPtCut ==true ) + name_tmp = Form ("%s_W_PT_miscalib_EE",outputFile.c_str()); + else if(isMiscalib == true && useZ == 0 && isR9selection ==true && isEPselection == true && isfbrem == false && isPtCut ==false ) + name_tmp = Form ("%s_W_EP_miscalib_EE",outputFile.c_str()); + else if(isMiscalib == true && useZ == 0 && isEPselection ==false && isR9selection==false && isPtCut ==false && isfbrem ==false ) + name_tmp =Form ("%s_W_noEP_miscalib_EE",outputFile.c_str()); + + else if(isMiscalib == false && useZ == 0 && isR9selection ==true && isEPselection == false && isfbrem == false && isPtCut ==false ) + name_tmp = Form ("%s_WZ_R9_EE",outputFile.c_str()); + else if(isMiscalib == false && useZ == 0 && isR9selection ==false && isEPselection == false && isfbrem == true && isPtCut ==false ) + name_tmp = Form ("%s_W_Fbrem_EE",outputFile.c_str()); + else if(isMiscalib == false && useZ == 0 && isR9selection ==true && isEPselection == false && isfbrem == false && isPtCut ==true ) + name_tmp = Form ("%s_W_PT_EE",outputFile.c_str()); + else if(isMiscalib == false && useZ == 0 && isR9selection ==true && isEPselection == true && isfbrem == false && isPtCut ==false ) + name_tmp = Form ("%s_W_EP_EE",outputFile.c_str()); + else if(isMiscalib == false && useZ == 0 && isEPselection ==false && isR9selection==false && isPtCut ==false && isfbrem ==false ) + name_tmp =Form ("%s_W_noEP_EE",outputFile.c_str()); + else { std::cout<<" Option not considered --> exit "< exit "<::const_iterator category_itr=categories.begin(); + category_itr != categories.end(); + category_itr++){ + myClock.Start(); +#ifdef DEBUG + std::cout << "[DEBUG] category: " << *category_itr << std::endl; +#endif + if (vm.count("runToy")) { + cout << "number of toys: "<floatParsFinal()); + sh.SetMinuit(m); + //ph.SetVariables(); + //ph.SetCovMatrix(fitres->covarianceMatrix()); + //ph.SetUpdateProposalParameters(kTRUE); // auto-create mean vars and add mappings + //ph.SetCacheSize(100); + //ProposalFunction* pf = ph.GetProposalFunction(); + + if(minimType=="migrad"){ + + //fitres = + m.fit(""); + //m.migrad(); + //m.hesse(); + } else if(minimType=="profile"){ + MinimizationProfile(smearer, args, nIter); + args.writeToStream(std::cout, kFALSE); + } else if(minimType=="MCMC"){ + MinimizationProfile(smearer, args, nIter, true); + args.writeToStream(std::cout, kFALSE); + } else if(minimType=="sampling"){ + RooArgList argList_(args); + TIterator *it_ = argList_.createIterator(); + for(RooRealVar *var = (RooRealVar*)it_->Next(); var != NULL; var = (RooRealVar*)it_->Next()){ + if (var->isConstant() || !var->isLValue()) continue; + TString name(var->GetName()); + if(name.Contains("scale")) var->setConstant(); + } + + RooStats::ProposalHelper ph; + ph.SetVariables(args); + ph.SetCovMatrix(*(smearer._markov.GetAsDataSet()->covarianceMatrix(args))); + ph.SetUniformFraction(0.05); + ph.SetWidthRangeDivisor(2); + + RooStats::MetropolisHastings MCMC(smearer, args, *(ph.GetProposalFunction()), nIter); + MCMC.SetNumBurnInSteps(10); + MCMC.SetSign(RooStats::MetropolisHastings::kNegative); + MCMC.SetType(RooStats::MetropolisHastings::kLog); + //MCMC.SetProposalFunction(sh); + RooStats::MarkovChain *mcChain = (MCMC.ConstructChain()); + mcChain->SaveAs("tmp/newChain.root"); + delete mcChain; + + } + } + + std::cout << "[INFO] Minimization time: \t"; + myClock.Stop(); + myClock.Print(); + if(!vm.count("profileOnly") && !vm.count("plotOnly")){ + args.writeToFile(outDirFitResData+"/params-"+r+"-"+TString(commonCut.c_str())+".txt"); + smearer._markov.SaveAs((outDirFitResData+"/markov-"+r+"-"+TString(commonCut.c_str())+".root")); + } + + //RooDataSet *dSet = smearer.GetMarkovChainAsDataSet(); + //dSet->SaveAs("tmp/dataset.root"); + //save the smeared histograms + + for(std::vector::iterator itr= smearer.ZeeCategories.begin(); + itr != smearer.ZeeCategories.end(); + itr++){ + smearer.GetSmearedHisto(*itr, true, false); + smearer.GetSmearedHisto(*itr, true, true); + smearer.GetSmearedHisto(*itr, false, smearer._isDataSmeared); + } + + if(vm.count("plotOnly") || !vm.count("profileOnly")){ + TFile *f = new TFile(outDirFitResData+"/histos-"+r+"-"+TString(commonCut.c_str())+".root", "recreate"); + f->Print(); + f->cd(); + for(std::vector::iterator itr= smearer.ZeeCategories.begin(); + itr != smearer.ZeeCategories.end(); + itr++){ + //if(!itr->active) continue; + TH1F *MC = smearer.GetSmearedHisto(*itr, true, false); + TH1F *smearMC = smearer.GetSmearedHisto(*itr, true, true); + TH1F *data = smearer.GetSmearedHisto(*itr, false, smearer._isDataSmeared); + + MC->Write(); + smearMC->Write(); + data->Write(); + f->Write(); + } + f->Close(); + } + + if(vm.count("profileOnly") || !vm.count("plotOnly")){ + //if(vm.count("profileOnly") && !vm.count("runToy")) smearer.SetNSmear(10); + + std::cout <<"==================PROFILE=================="<isConstant()) + continue; + + TString name(var->GetName()); + //if(name.Contains("scale")) continue; + //if(name.Contains("absEta_1_1.4442-gold") && vm.count("alphaGoldFix")) continue; + // special part for alpha fitting + double min=0.; + TString alphaName=name; alphaName.ReplaceAll("constTerm","alpha"); + RooRealVar *var2= name.Contains("constTerm") ? (RooRealVar *)argList.find(alphaName): NULL; + if(var2!=NULL && name.Contains("constTerm") && var2->isConstant()==false){ + TString name2 = name; + + double rho=0, Emean=0; + smearer.SetDataSet(name,TString(var->GetName())+TString(var2->GetName())); + if(vm.count("constTermFix")) MinProfile2D(var, var2, smearer, -1, 0., min, rho, Emean, false); + smearer.dataset->Write(); + + // rho profile + name2.ReplaceAll("constTerm", "rho"); + smearer.SetDataSet(name2,"rho"); + Double_t v1=var->getVal(); + Double_t v2=var2->getVal(); + var2->setVal(0); + var->setVal(rho); + TGraph *profil = NULL; + profil = GetProfile(var, smearer,0); + var2->setVal(v2); + var->setVal(v1); + TString n="profileChi2_"+name2+"_"; n+=randomInt; + profil->SetName(n); + TCanvas c("c_"+name); + profil->Draw("AP*"); + fOutProfile->cd(); + profil->Write(); + delete profil; + smearer.dataset->Write(); + + + // phi profile + name2.ReplaceAll("rho", "phi"); + smearer.SetDataSet(name2,"phi"); + profil = GetProfile(var, var2, smearer, true, rho, Emean); + n="profileChi2_"+name2+"_"; n+=randomInt; + profil->SetName(n); + profil->Draw("AP*"); + fOutProfile->cd(); + profil->Write(); + delete profil; + smearer.dataset->Write(); + + // rho profile with fixed phi!=pi/2 + name2.ReplaceAll("phi", "rho_phi4"); + smearer.SetDataSet(name2,"rho_phi4"); + profil = GetProfile(var, var2, smearer, true, 0, Emean, 0.785); + n="profileChi2_"+name2+"_"; n+=randomInt; + profil->SetName(n); + profil->Draw("AP*"); + fOutProfile->cd(); + profil->Write(); + delete profil; + smearer.dataset->Write(); + +// // rho profile with fixed phi!=pi/2 +// name2.ReplaceAll("rho_phi4", "rho_phi6"); +// smearer.SetDataSet(name2,"rho_phi6"); +// profil = GetProfile(var, var2, smearer, true, 0, Emean, 0.524); +// n="profileChi2_"+name2+"_"; n+=randomInt; +// profil->SetName(n); +// profil->Draw("AP*"); +// fOutProfile->cd(); +// profil->Write(); +// delete profil; +// smearer.dataset->Write(); + +// // rho profile with fixed phi!=pi/2 +// name2.ReplaceAll("rho_phi6", "rho_phi3"); +// smearer.SetDataSet(name2,"rho_phi3"); +// profil = GetProfile(var, var2, smearer, true, 0, Emean, 1.05); +// n="profileChi2_"+name2+"_"; n+=randomInt; +// profil->SetName(n); +// profil->Draw("AP*"); +// fOutProfile->cd(); +// profil->Write(); +// delete profil; +// smearer.dataset->Write(); + + + } + + //if(!name.Contains("scale")) continue; + std::cout << "Doing " << name << "\t" << var->getVal() << std::endl; + smearer.SetDataSet(name,name); + // if(vm.count("runToy")){ + // MinProfile(var, smearer, -1, 0., min, false); + //} + TGraph *profil = GetProfile(var, smearer,0); + TString n="profileChi2_"+name+"_"; n+=randomInt; + profil->SetName(n); + TCanvas c("c_"+name); + profil->Draw("AP*"); + fOutProfile->cd(); + profil->Write(); + std::cout << "Saved profile for " << name << std::endl; + smearer.dataset->Write(); + delete profil; + } + std::cout << "Cloning args" << std::endl; + // RooArgSet *mu = (RooArgSet *)args.snapshot(); + //std::cout << "creating roomultivargaussian" << std::endl; + //RooMultiVarGaussian g("multi","",args, *mu, *(smearer.GetMarkovChainAsDataSet()->covarianceMatrix())); + //std::cout << "created" << std::endl; + + // RooDataSet *dataset = g.generate(args,10); + // for(Long64_t iGen=0; iGen<1; iGen++){ + // RooArgList argList_(* dataset->get(iGen)); + // TIterator *it_ = argList_.createIterator(); + // for(RooRealVar *var = (RooRealVar*)it_->Next(); var != NULL; var = (RooRealVar*)it_->Next()){ + // if (!var->isLValue()) continue; + // TString name(var->GetName()); + // //std::cout << name << var->getVal() << std::endl; + // var->Print(); + // //args.setRealValue(name,var->getVal()); +// } +// //smearer.evaluate(); +// } + fOutProfile->Close(); + + } + } + tmpFile->Close(); + globalClock.Stop(); + std::cout << "[INFO] Total elapsed time: "; globalClock.Print(); + return 0; +} + + +// LocalWords: etaSCEle diff --git a/ZFitter/bin/ZFitter_vsLC.cpp b/ZFitter/bin/ZFitter_vsLC.cpp new file mode 100644 index 00000000000..b3c6133ab5f --- /dev/null +++ b/ZFitter/bin/ZFitter_vsLC.cpp @@ -0,0 +1,6110 @@ +/// Zee Fit program + +/**\file +The aim of the program is to provide a common interface to all the Z +fitting algorithms reading and combining in the proper way the +configuration files. + +\todo + - remove commonCut from category name and add it in the ZFit_class in order to not repeate the cut + - make alpha fitting more generic (look for alphaName) + - Implement the iterative Et dependent scale corrections + +*/ + #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include "TROOT.h" +#include "TSystem.h" +#include "TStyle.h" +#include "TFile.h" +#include "TCanvas.h" +#include "TGraphErrors.h" +#include "TGraphAsymmErrors.h" +#include "TPaveStats.h" +#include "TLegend.h" +#include "TChain.h" +#include "TVirtualFitter.h" +#include "TLatex.h" + + +/// @cond SHOW +/// \code +#include "../interface/ZFit_class.hh" +#include "../interface/puWeights_class.hh" +#include "../interface/r9Weights_class.hh" +#include "../interface/ZPtWeights_class.hh" + +#include "../interface/runDivide_class.hh" +#include "../interface/EnergyScaleCorrection_class.hh" +#include "../interface/addBranch_class.hh" + +#include "../interface/RooSmearer.hh" + +#include "../interface/nllProfile.hh" + +#include "../../EOverPCalibration/interface/ntpleUtils.h" +#include "../../EOverPCalibration/interface/CalibrationUtils.h" +#include "../../EOverPCalibration/interface/FastCalibratorEB.h" +#include "../../EOverPCalibration/interface/FastCalibratorEE.h" + +#include "../../EOverPCalibration/interface/TEndcapRings.h" +#include "../../EOverPCalibration/CommonTools/histoFunc.h" +//#include "treeReader.h" +//#include "setTDRStyle.h" +#include "../../EOverPCalibration/interface/ntpleUtils2.h" +#include "../../EOverPCalibration/interface/ConvoluteTemplate.h" +#include "../../EOverPCalibration/interface/stabilityUtils.h" +#include "../../EOverPCalibration/interface/geometryUtils.h" + +/// \endcode +/// @endcond + +#include +//#include +//#include +//#include +#include +#include +#include "RooBinning.h" +//#include "../src/ShervinMinuit.cc" +//#include +#include + +#include "Math/Minimizer.h" + +#include +#include +#include + +#include + +#include +#include + +#define profile + +//#define DEBUG +#define smooth + +//#include "../macro/loop.C" // a way to use compiled macros with ZFitter + +//using namespace std; +using namespace RooStats; + +///\endcond + + +/// map that associates the name of the tree and the pointer to the chain +typedef std::map< TString, TChain* > chain_map_t; + +/** \brief map that associates the name of the tag to the chain_map_t + * + * the logic is better described in \ref validationConfig + */ +typedef std::map< TString, chain_map_t > tag_chain_map_t; + + +/** Function parsing the region files + * \retval vector of strings, each string is the name of one region + */ +std::vector ReadRegionsFromFile(TString fileName){ + ifstream file(fileName); + std::vector regions; + TString region; + + while(file.peek()!=EOF && file.good()){ + if(file.peek()==10){ // 10 = \n + file.get(); + continue; + } + + if(file.peek() == 35){ // 35 = # + file.ignore(1000,10); // ignore the rest of the line until \n + continue; + } + + file >> region; + file.ignore(1000,10); // ignore the rest of the line until \n +#ifdef DEBUG + std::cout << "[DEBUG] Reading region: " << region<< std::endl; +#endif + regions.push_back(region); + + } + return regions; +} + + +/** + * This function reassociates the chains as friends of the "selected" tree. + * + * This function should be run when new chains or files are added to the tagChainMap. + * + */ +void UpdateFriends(tag_chain_map_t& tagChainMap, TString regionsFileNameTag){ +//void UpdateFriends(tag_chain_map_t& tagChainMap){ + // loop over all the tags + for(tag_chain_map_t::const_iterator tag_chain_itr=tagChainMap.begin(); + tag_chain_itr!=tagChainMap.end(); + tag_chain_itr++){ + // take the selected tree of that tag + TChain *chain = (tag_chain_itr->second.find("selected"))->second; + + // loop over all the trees + for(chain_map_t::const_iterator chain_itr=tag_chain_itr->second.begin(); + chain_itr!=tag_chain_itr->second.end(); + chain_itr++){ + + if(chain_itr->first!="selected"){ //except the selected + if(chain->GetFriend(chain_itr->first)==NULL){ + std::cout << "[STATUS] Adding friend branch: " << chain_itr->first + << " to tag " << tag_chain_itr->first << std::endl; + chain->AddFriend(chain_itr->second); + } // already added + } + + if(chain->GetEntries()!= chain_itr->second->GetEntries()){ + std::cerr << "[ERROR] Not the same number of events: " << chain->GetEntries() << "\t" << chain_itr->second->GetEntries() << std::endl; + exit(1); + } + } + } + return; +} + +void Dump(tag_chain_map_t& tagChainMap, TString tag="s", Long64_t firstentry=0){ + (tagChainMap[tag])["selected"]->Scan("etaEle:R9Ele:energySCEle_regrCorrSemiParV5_pho/cosh(etaSCEle):smearerCat:catName","","col=5:4:5:3:50",5,firstentry); +} + +/** + * \param tagChainMap map of all the tags declared in the validation config file + * \param tag name of the new \b tag created by the function, all the existent tags with name starting with + b tag are merged in the new \b tag + * + * A new tagChain with name=tag is added to the tagChainMap. All the tagChains with tag starting with \b tag are merged + * After the merging the friend list is updated by \ref UpdateFriends + */ +void MergeSamples(tag_chain_map_t& tagChainMap, TString regionsFileNameTag, TString tag="s"){ + + std::pair pair_tmp_tag(tag,chain_map_t()); // make_pair not work with scram b + tagChainMap.insert(pair_tmp_tag); + + //loop over all the tags + for(tag_chain_map_t::const_iterator tag_chain_itr=tagChainMap.begin(); + tag_chain_itr!=tagChainMap.end(); + tag_chain_itr++){ + + // consider tags matching the tag input parameter + if(tag_chain_itr->first.CompareTo(tag)==0 || !tag_chain_itr->first.Contains(tag)) continue; //do it for each sample + + // loop over all the trees + for(chain_map_t::const_iterator chain_itr=tag_chain_itr->second.begin(); + chain_itr!=tag_chain_itr->second.end(); + chain_itr++){ + TString chainName = chain_itr->first; + if(tagChainMap.count(chainName)==0){ // create the new chain if does not exist for tag + std::pair pair_tmp(chainName, new TChain(chainName)); + (tagChainMap[tag]).insert(pair_tmp); + (tagChainMap[tag])[chainName]->SetTitle(tag); + } + (tagChainMap[tag])[chainName]->Add(chain_itr->second); + std::cout << tag << "\t" << tag_chain_itr->first << "\t" << chainName << "\t" << chain_itr->second << "\t" << chain_itr->second->GetTitle() << std::endl; + + } + } + UpdateFriends(tagChainMap, regionsFileNameTag); + return; +} + + +/** + * \brief Function returning the name of the energy branch given the name of the invariant mass + */ +std::string energyBranchNameFromInvMassName(std::string invMass_var){ + + std::string energyBranchName=""; + if(invMass_var=="invMass_SC_regrCorr_ele") energyBranchName = "energySCEle_regrCorr_ele"; + else if(invMass_var=="invMass_SC_regrCorr_pho") energyBranchName = "energySCEle_regrCorr_pho"; + else if(invMass_var=="invMass_regrCorr_fra") energyBranchName = "energyEle_regrCorr_fra"; + else if(invMass_var=="invMass_regrCorr_egamma") energyBranchName = "energyEle_regrCorr_egamma"; + else if(invMass_var=="invMass_SC") energyBranchName = "energySCEle"; + else if(invMass_var=="invMass_SC_must") energyBranchName = "energySCEle_must"; + else if(invMass_var=="invMass_SC_must_regrCorr_ele") energyBranchName = "energySCEle_must_regrCorr_ele"; + else if(invMass_var=="invMass_rawSC") energyBranchName = "rawEnergySCEle"; + else if(invMass_var=="invMass_rawSC_esSC") energyBranchName = "rawEnergySCEle+esEnergySCEle"; + else if(invMass_var=="invMass_SC_corr") energyBranchName = "energySCEle_corr"; + else if(invMass_var=="invMass_SC_regrCorrSemiParV4_ele") energyBranchName = "energySCEle_regrCorrSemiParV4_ele"; + else if(invMass_var=="invMass_SC_regrCorrSemiParV4_pho") energyBranchName = "energySCEle_regrCorrSemiParV4_pho"; + else if(invMass_var=="invMass_SC_regrCorrSemiParV5_ele") energyBranchName = "energySCEle_regrCorrSemiParV5_ele"; + else if(invMass_var=="invMass_SC_regrCorrSemiParV5_pho") energyBranchName = "energySCEle_regrCorrSemiParV5_pho"; + else if(invMass_var=="invMass_SC_regrCorrSemiParV6_ele") energyBranchName = "energySCEle_regrCorrSemiParV6_ele"; + else if(invMass_var=="invMass_SC_regrCorrSemiParV6_pho") energyBranchName = "energySCEle_regrCorrSemiParV6_pho"; + else if(invMass_var=="invMass_SC_regrCorrSemiParV7_ele") energyBranchName = "energySCEle_regrCorrSemiParV7_ele"; + else if(invMass_var=="invMass_SC_regrCorrSemiParV7_pho") energyBranchName = "energySCEle_regrCorrSemiParV7_pho"; + else if(invMass_var=="invMass_SC_regrCorrSemiParV8_ele") energyBranchName = "energySCEle_regrCorrSemiParV8_ele"; + else if(invMass_var=="invMass_SC_regrCorrSemiParV8_pho") energyBranchName = "energySCEle_regrCorrSemiParV8_pho"; + else if(invMass_var=="invMass_SC_regrCorrSemiPar7TeVtrainV6_ele") energyBranchName = "energySCEle_regrCorrSemiPar7TeVtrainV6_ele"; + else if(invMass_var=="invMass_SC_regrCorrSemiPar7TeVtrainV6_pho") energyBranchName = "energySCEle_regrCorrSemiPar7TeVtrainV6_pho"; + else if(invMass_var=="invMass_SC_regrCorrSemiPar7TeVtrainV7_ele") energyBranchName = "energySCEle_regrCorrSemiPar7TeVtrainV7_ele"; + else if(invMass_var=="invMass_SC_regrCorrSemiPar7TeVtrainV7_pho") energyBranchName = "energySCEle_regrCorrSemiPar7TeVtrainV7_pho"; + else if(invMass_var=="invMass_SC_regrCorrSemiPar7TeVtrainV8_ele") energyBranchName = "energySCEle_regrCorrSemiPar7TeVtrainV8_ele"; + else if(invMass_var=="invMass_SC_regrCorrSemiPar7TeVtrainV8_pho") energyBranchName = "energySCEle_regrCorrSemiPar7TeVtrainV8_pho"; + + else { + std::cerr << "Energy branch name not define for invariant mass branch: " << invMass_var << std::endl; + exit(1); + } + return energyBranchName; +} + + + +TString energyBranchNameFromInvMassName(TString invMass_var){ + return TString( (energyBranchNameFromInvMassName(std::string(invMass_var))).c_str()); +} + +int main(int argc, char **argv) { + TStopwatch myClock; + TStopwatch globalClock; + globalClock.Start(); + + puWeights_class puWeights; + std::cout << "============================== Z General Fitter" << std::endl; + + //------------------------------------------------------------ + // parsing input options to the program + using namespace boost; + namespace po = boost::program_options; + unsigned int nEvents_runDivide=100000; + std::string chainFileListName; + std::string regionsFileName; + std::string runRangesFileName; + std::string dataPUFileName, mcPUFileName; + std::vector dataPUFileNameVec, mcPUFileNameVec; + std::string r9WeightFile; + std::string ZPtWeightFile; + std::string initFileName; + // bool savePUweightTree; + std::string imgFormat="eps", outDirFitResMC="test/MC/fitres", outDirFitResData="test/dato/fitres", outDirImgMC="test/MC/img", outDirImgData="test/dato/img", outDirTable="test/dato/table", selection; + TString eleID=""; + //std::vector signalFiles, bkgFiles, dataFiles; + std::string commonCut; + std::string corrEleFile, corrEleType; + std::string smearEleFile, smearEleType; + double smearingCBAlpha=1, smearingCBPower=5; + std::string invMass_var; + float invMass_min=0, invMass_max=0, invMass_binWidth=0.250; + int fit_type_value=1; + int signal_type_value=0; + unsigned long long int nToys = 0; + float constTermToy=0; + unsigned long long int nEventsPerToy = 0; + unsigned int nIter =0; + unsigned int nEventsMinDiag=0; + unsigned int nEventsMinOffDiag=0; + unsigned int nSmearToy=1; + + int pdfSystWeightIndex=-1; + std::string minimType; + std::vector branchList; + + + + + +//options for E/p + std::string jsonFileName; + std::string miscalibMap; + bool isMiscalib; + bool applyPcorr; + bool applyEcorr; + bool isSaveEPDistribution; + bool isMCTruth; + bool isEPselection; + bool isPtCut; + float PtMin; + bool isfbrem; + float fbremMax; + bool isR9selection; + float R9Min; + float EPMin; + int smoothCut; + int miscalibMethod; + std::string inputMomentumScale; + std::string inputEnergyScale; + std::string typeEB; + std::string typeEE; + std::string outputPath; + std::string outputFile; + int numberOfEvents; + int useZ, useW; + int useRawEnergy; + // int isBarrel; + int splitStat; + int nLoops; + bool isDeadTriggerTower; + std::string inputFileDeadXtal; + std::string EBEE; + std::string EBEEpu; + int evtsPerPoint; + + int useRegression; + int targetTypeEB, targetTypeEE; + float R9cutEB, R9cutEE; + int energyTypeEB, energyTypeEE; + float yMIN; + float yMAX; + std::string dayMin; + std::string dayMax; + std::string dayZOOM; + std::string LUMI; + //------------------------------ setting option categories + po::options_description desc("Main options"); + po::options_description outputOption("Output options"); + po::options_description inputOption("Input options"); + po::options_description fitterOption("Z fitter options"); + po::options_description smearerOption("Z smearer options"); + po::options_description toyOption("toyMC options"); + po::options_description EoverPOption("EoverP options"); + po::options_description momentumCorrectionEB("run the momentum calibration for barrel"); + po::options_description momentumCorrectionEE("run the momentum calibration for endcap"); + po::options_description laserMonitoringEPOption("laser monitoring with E/p options"); + po::options_description laserMonitoringEPvsPUOption("laser monitoring with E/p versus Pile Up options"); + + + + //po::options_description cmd_line_options; + //cmd_line_options.add(desc).add(fitOption).add(smearOption); + + //------------------------------ adding options' description + desc.add_options() + ("help,h","Help message") + ("loop","") + + ("runDivide", "execute the run division") + ("nEvents_runDivide", po::value(&nEvents_runDivide)->default_value(100000), "Minimum number of events in a run range") + + // + ("dataPU", po::value< string >(&dataPUFileName), "") + ("mcPU", po::value(&mcPUFileName),"") + ("noPU", "") + ("savePUTreeWeight","") + // + ("corrEleFile", po::value(&corrEleFile),"File with energy scale corrections") + ("corrEleType", po::value(&corrEleType),"Correction type/step") + ("saveCorrEleTree", "") + + ("smearEleFile", po::value(&smearEleFile),"File with energy smearings") + ("smearEleType", po::value(&smearEleType),"Correction type/step") + ("smearingCBAlpha", po::value(&smearingCBAlpha),"Correction type/step") + ("smearingCBPower", po::value(&smearingCBPower),"Correction type/step") + // + ("r9WeightFile", po::value(&r9WeightFile),"File with r9 photon-electron weights") + ("useR9weight", "use r9 photon-electron weights") + ("saveR9TreeWeight", "") + ("ZPtWeightFile", po::value(&ZPtWeightFile),"File with ZPt weights") + ("useZPtweight", "use ZPt weights") + ("useFSRweight", "activate the FSR weight in MC") + ("useWEAKweight", "activate the WEAK interference weight in MC") + ("saveRootMacro","") + // + ("selection", po::value(&selection)->default_value("loose25nsRun2"),"") + ("commonCut", po::value(&commonCut)->default_value("Et_25"),"") + ("invMass_var", po::value(&invMass_var)->default_value("invMass_SC_must"),"") + ("invMass_min", po::value(&invMass_min)->default_value(65.),"") + ("invMass_max", po::value(&invMass_max)->default_value(115.),"") + ("invMass_binWidth", po::value(&invMass_binWidth)->default_value(0.25),"Smearing binning") + ("isOddMC", "Activate if use only odd events in MC") + ("isOddData", "Activate if use only odd events in data") + // + ("readDirect","") //read correction directly from config file instead of passing as a command line arg + //("addPtBranches", "") //add new pt branches ( 3 by default, fra, ele, pho) + ("addBranch", po::value< std::vector >(&branchList), "") + ("saveAddBranchTree","") + // ("signal,s", po::value< std::vector >(&signalFiles), "Signal file (can be called multiple times putting the files in a chain") + // ("bkg,b", po::value< std::vector >(&bkgFiles), "Bkg file (can be called multiple times putting the files in a chain") + // ("data,d", po::value< std::vector >(&dataFiles), "Data file (can be called multiple times putting the files in a chain") + //("_ZFit_class", "call the Z fitter") + //; + // + // po::options_description fitOption("Z Fit options"); + // po::options_description smearOption("Z smearing options"); + // smearOption.add_options() + ; + fitterOption.add_options() + ("fit_type_value", po::value(&fit_type_value)->default_value(1),"0=floating tails, 1=fixed tails") + ("signal_type_value", po::value(&signal_type_value)->default_value(0),"0=BW+CB, 1=Cruijff") + ("forceNewFit", "refit MC also if fit exists") + ("updateOnly", "do not fit data if fit exists") + ;; + smearerOption.add_options() + ("smearerFit", "call the smearing") + ("smearerType", po::value(&minimType)->default_value("profile"), "minimization algo") + ("onlyDiagonal","if want to use only diagonal categories") + ("autoBin", "") + ("autoNsmear", "") + ("smearscan", "") + ("isDataSmeared","") + ("plotOnly", "active if you don't want to do the smearing") + ("profileOnly", "") + ("numIter", po::value(&nIter)->default_value(300), "number of MCMC steps") + ("nEventsMinDiag", po::value(&nEventsMinDiag)->default_value(1000), "min num events in diagonal categories") + ("nEventsMinOffDiag", po::value(&nEventsMinOffDiag)->default_value(2000), "min num events in off-diagonal categories") + ("onlyScale", "fix the smearing to constant") + ("constTermFix", "constTerm not depending on Et") + ("alphaGoldFix", "alphaTerm for gold electrons fixed to the low eta region") + ("smearingEt", "alpha term depend on sqrt(Et) and not on sqrt(E)") + ("nSmearToy", po::value(&nSmearToy)->default_value(0), "") + ("pdfSystWeightIndex", po::value(&pdfSystWeightIndex)->default_value(-1), "Index of the weight to be used") + ; + inputOption.add_options() + ("chainFileList,f", po::value< string >(&chainFileListName), "Configuration file with input file list") + ("regionsFile", po::value< string >(®ionsFileName), "Configuration file with regions") + ("runRangesFile", po::value< string >(&runRangesFileName), "Configuration file with run ranges") + ("initFile", po::value< string >(&initFileName), "Configuration file with init values of fit model") + ; + outputOption.add_options() + ("imgFormat", po::value(&imgFormat)->default_value("eps"),"") + ("outDirFitResMC", po::value(&outDirFitResMC),"") + ("outDirFitResData", po::value(&outDirFitResData),"") + ("outDirImgMC", po::value(&outDirImgMC),"") + ("outDirImgData", po::value(&outDirImgData),"") + //("outDirTable", po::value(&outDirTable),"") + ; + toyOption.add_options() + ("runToy","") + ("nToys", po::value(&nToys)->default_value(1000),"") + ("constTermToy", po::value(&constTermToy)->default_value(0.01),"") + ("eventsPerToy", po::value(&nEventsPerToy)->default_value(0),"=0: all events") + ; + momentumCorrectionEE.add_options() + ("momentumCorrectionEE", "run the momentum calibration for endcap") + ("targetTypeEE", po::value(&targetTypeEE)->default_value(1),"compute corrections on: 1=pTk, 2=energy, 3=E/p") + ("R9cutEE", po::value(&R9cutEE)->default_value(0.),"apply R9 cut") + ("energyTypeEE", po::value(&energyTypeEE)->default_value(0),"0=rawEnergy, 1=scEnergy") + ; + momentumCorrectionEB.add_options() + ("momentumCorrectionEB", "run the momentum calibration for barrel") + ("targetTypeEB", po::value(&targetTypeEB)->default_value(1),"compute corrections on: 1=pTk, 2=energy, 3=E/p") + ("R9cutEB", po::value(&R9cutEB)->default_value(0.),"apply R9 cut") + ("energyTypeEB", po::value(&energyTypeEB)->default_value(0),"0=rawEnergy, 1=scEnergy") + ; + laserMonitoringEPOption.add_options() + ("laserMonitoringEP", "call the laser monitoring with E/p") + ("yMIN", po::value(&yMIN)->default_value(0.65),"y min") + ("yMAX", po::value(&yMAX)->default_value(1.05),"y max") + ("EBEE", po::value(&EBEE)->default_value("EB"),"barrel or endcap") + ("evtsPerPoint", po::value(&evtsPerPoint)->default_value(1000),"events per point") + ("useRegression", po::value(&useRegression)->default_value(0),"use regression") + ("dayMin", po::value(&dayMin)->default_value("1-7-2015"),"day min") + ("dayMax", po::value(&dayMax)->default_value("15-11-2015"),"day max") + ("dayZOOM", po::value(&dayZOOM)->default_value("10-8-2015"),"day ZOOM") + ("LUMI", po::value(&LUMI)->default_value("1.9"),"LUMI") + ; + laserMonitoringEPvsPUOption.add_options() + ("laserMonitoringEPvsPU", "call the laser monitoring with E/p") + // ("EBEEpu", po::value(&EBEEpu)->default_value("EB"),"barrel or endcap") + //("evtsPerPointpu", po::value(&evtsPerPoint)->default_value(1000),"events per point") + // ("useRegression", po::value(&useRegression)->default_value(0),"use regression") + // ("dayMin", po::value(&dayMin)->default_value("1-6-2015"),"day min") + // ("dayMax", po::value(&dayMax)->default_value("1-10-2015"),"day max") + // ("dayZOOM", po::value(&dayZOOM)->default_value("10-8-2015"),"day ZOOM") + ; + EoverPOption.add_options() + ("EOverPCalib", "call the E/p calibration") + // ("isBarrel", po::value(&isBarrel)->default_value(1),"1=barrel, 0=endcap") + ("doEB", "do EoP IC calibration for EB") + ("doEE", "do EoP IC calibration for EE") + ("jsonFileName", po::value(&jsonFileName)->default_value("/afs/cern.ch/cms/CAF/CMSCOMM/COMM_DQM/certification/Collisions15/13TeV/Cert_246908-258750_13TeV_PromptReco_Collisions15_25ns_JSON.txt"), "jsonFileName") + ("isMiscalib", po::value(&isMiscalib)->default_value(false),"apply the initial miscalibration") + ("miscalibMethod", po::value(&miscalibMethod)->default_value(1),"miscalibration method") + ("miscalibMap", po::value(&miscalibMap)->default_value("/gwteray/users/brianza/scalibMap2.txt"), "map for the miscalibration") + ("isSaveEPDistribution", po::value(&isSaveEPDistribution)->default_value(false),"save E/P distribution") + ("isMCTruth", po::value(&isMCTruth)->default_value(false),"option for MC") + ("isEPselection", po::value(&isEPselection)->default_value(false),"apply E/p selection") + ("isPtCut", po::value(&isPtCut)->default_value(false),"apply Pt cut") + ("PtMin", po::value(&PtMin)->default_value(0.),"treshold for the Pt cut") + ("isfbrem", po::value(&isfbrem)->default_value(false),"apply fbrem cut") + ("fbremMax", po::value(&fbremMax)->default_value(100.),"fbrem treshold") + ("isR9selection", po::value(&isR9selection)->default_value(false),"apply R9 selection") + ("R9Min", po::value(&R9Min)->default_value(-1.),"R9 treshold") + ("applyPcorr", po::value(&applyPcorr)->default_value(true),"apply momentum correction") + ("inputMomentumScale", po::value(&inputMomentumScale)->default_value("/afs/cern.ch/user/l/lbrianza/work/public/EoP_additionalFiles/MomentumCalibration2015_eta1_eta1.root"),"input momentum scale") + ("applyEcorr", po::value(&applyEcorr)->default_value(false),"apply energy correction") + ("inputEnergyScale", po::value(&inputEnergyScale)->default_value("/afs/cern.ch/user/l/lbrianza/work/public/EoP_additionalFiles/momentumCalibration2015_EB_scE.root"),"input energy scale") + ("typeEB", po::value(&typeEB)->default_value("eta1"),"") + ("typeEE", po::value(&typeEE)->default_value("eta1"),"") + ("outputPath", po::value(&outputPath)->default_value("output/output_runD/"),"output dir for E/P calibration") + ("outputFile", po::value(&outputFile)->default_value("FastCalibrator_Oct2015_runD"),"output file for E/P calibration") + ("numberOfEvents", po::value(&numberOfEvents)->default_value(-1),"number of events (-1=all)") + ("useRawEnergy", po::value(&useRawEnergy)->default_value(0),"use raw energy") + ("useZ", po::value(&useZ)->default_value(1),"use Z events") + ("useW", po::value(&useW)->default_value(1),"use W events") + ("splitStat", po::value(&splitStat)->default_value(1),"split statistic") + ("nLoops", po::value(&nLoops)->default_value(20),"number of iteration of the L3 algorithm") + ("isDeadTriggerTower", po::value(&isDeadTriggerTower)->default_value(false),"") + ("inputFileDeadXtal", po::value(&inputFileDeadXtal)->default_value("NULL"),"") + ("EPMin", po::value(&EPMin)->default_value(100.),"E/p window") + ("smoothCut", po::value(&smoothCut)->default_value(0),"apply smooth cut on the E/p window") + ; + + desc.add(inputOption); + desc.add(outputOption); + desc.add(fitterOption); + desc.add(smearerOption); + desc.add(toyOption); + desc.add(momentumCorrectionEE); + desc.add(momentumCorrectionEB); + desc.add(EoverPOption); + desc.add(laserMonitoringEPOption); + desc.add(laserMonitoringEPvsPUOption); + + po::variables_map vm; + // + // po::store(po::parse_command_line(argc, argv, smearOption), vm); + po::store(po::parse_command_line(argc, argv, desc), vm); + po::notify(vm); + + + //------------------------------ checking options + if(!vm.count("invMass_binWidth") && !vm.count("smearerFit")){ + std::cout << "[INFO] Bin Width=0.5" << std::endl; + invMass_binWidth=0.5; + } + + if (vm.count("help")) { + cout << desc << "\n"; + return 1; + } + + if(vm.count("useZPtweight") && !vm.count("pdfSystWeightIndex")){ + std::cerr << "[ERROR] Asked for ZPt weights but no pdfSystWeightIndex indicated" << std::endl; + exit(1); + } + + TString energyBranchName=energyBranchNameFromInvMassName(invMass_var).c_str(); + + if(!vm.count("chainFileList") && !vm.count("runToy")){ + std::cerr << "[ERROR] Missing mandatory option \"chainFile\"" << std::endl; + return 1; + } + + + if(!vm.count("regionsFile") && + !vm.count("runDivide") && !vm.count("savePUTreeWeight") && + !vm.count("saveR9TreeWeight") && !vm.count("saveCorrEleTree") && !vm.count("EOverPCalib") && !vm.count("momentumCorrectionEE") && !vm.count("momentumCorrectionEB") && !vm.count("laserMonitoringEP") && !vm.count("laserMonitoringEPvsPU") + //&& !vm.count("saveRootMacro") + ){ + std::cerr << "[ERROR] Missing mandatory option \"regionsFile\"" << std::endl; + return 1; + } + // if(!vm.count("runRangesFile")){ + // std::cerr << "[ERROR] Missing mandatory option \"runRangesFile\"" << std::endl; + // return 1; + // } + + if(vm.count("dataPU") != vm.count("mcPU")){ + std::cerr << "[ERROR] One PU distribution (data or mc) are not provided" << std::endl; + return 1; + } + + + //if((vm.count("corrEleType") != vm.count("corrEleFile"))&&(vm.count("corrEleType") != vm.count("readDirect")) ){ + //std::cout << "[ERROR] Either provide correction file name, or provide read direct option" << std::endl; + //return 1; + //} + + if( vm.count("corrEleType") && vm.count("corrEleFile") && vm.count("readDirect") ){ + std::cout << "[ERROR] Either provide correction file name, or provide read direct option - choose only one" << std::endl; + return 1; + } + + //============================== Check output folders + bool checkDirectories=true; + checkDirectories=checkDirectories && !system("[ -d "+TString(outDirFitResMC)+" ]"); + if(!checkDirectories && !vm.count("EOverPCalib") && !vm.count("momentumCorrectionEE") && !vm.count("momentumCorrectionEB")){ + std::cerr << "[ERROR] Directory " << outDirFitResMC << " not found" << std::endl; + } + checkDirectories=checkDirectories && !system("[ -d "+TString(outDirFitResData)+" ]"); + if(!checkDirectories && !vm.count("EOverPCalib") && !vm.count("momentumCorrectionEE") && !vm.count("momentumCorrectionEB")){ + std::cerr << "[ERROR] Directory " << outDirFitResData << " not found" << std::endl; + } + checkDirectories=checkDirectories && !system("[ -d "+TString(outDirImgMC)+" ]"); + if(!checkDirectories && !vm.count("EOverPCalib") && !vm.count("momentumCorrectionEE") && !vm.count("momentumCorrectionEB")){ + std::cerr << "[ERROR] Directory " << outDirImgMC << " not found" << std::endl; + } + checkDirectories=checkDirectories && !system("[ -d "+TString(outDirImgData)+" ]"); + if(!checkDirectories && !vm.count("EOverPCalib") && !vm.count("momentumCorrectionEE") && !vm.count("momentumCorrectionEB")){ + std::cerr << "[ERROR] Directory " << outDirImgData << " not found" << std::endl; + } + checkDirectories=checkDirectories && !system("[ -d "+TString(outDirFitResMC)+" ]"); + if(!checkDirectories && !vm.count("EOverPCalib") && !vm.count("laserMonitoringEP") && !vm.count("laserMonitoringEPvsPU")){ + std::cerr << "[ERROR] Directory " << outDirFitResMC << " not found" << std::endl; + } + checkDirectories=checkDirectories && !system("[ -d "+TString(outDirFitResData)+" ]"); + if(!checkDirectories && !vm.count("EOverPCalib") && !vm.count("laserMonitoringEP") && !vm.count("laserMonitoringEPvsPU")){ + std::cerr << "[ERROR] Directory " << outDirFitResData << " not found" << std::endl; + } + checkDirectories=checkDirectories && !system("[ -d "+TString(outDirImgMC)+" ]"); + if(!checkDirectories && !vm.count("EOverPCalib") && !vm.count("laserMonitoringEP") && !vm.count("laserMonitoringEPvsPU")){ + std::cerr << "[ERROR] Directory " << outDirImgMC << " not found" << std::endl; + } + checkDirectories=checkDirectories && !system("[ -d "+TString(outDirImgData)+" ]"); + if(!checkDirectories && !vm.count("EOverPCalib") && !vm.count("laserMonitoringEP") && !vm.count("laserMonitoringEPvsPU")){ + std::cerr << "[ERROR] Directory " << outDirImgData << " not found" << std::endl; + } + // checkDirectories=checkDirectories && !system("[ -d "+TString(outDirTable)+" ]"); + // if(!checkDirectories){ + // std::cerr << "[ERROR] Directory " << outDirTable << " not found" << std::endl; + // } + if(!checkDirectories + && !vm.count("runDivide") + && !vm.count("savePUTreeWeight") + && !vm.count("saveCorrEleTree") + && !vm.count("saveR9TreeWeight") + && !vm.count("saveRootMacro") + && !vm.count("EOverPCalib") + && !vm.count("momentumCorrectionEE") + && !vm.count("momentumCorrectionEB") + && !vm.count("laserMonitoringEP") + && !vm.count("laserMonitoringEPvsPU") + ) return 1; + + if(!dataPUFileName.empty()) dataPUFileNameVec.push_back(dataPUFileName.c_str()); + if(!mcPUFileName.empty()) mcPUFileNameVec.push_back(mcPUFileName.c_str()); + //============================== Reading the config file with the list of chains + tag_chain_map_t tagChainMap; + TString tag, chainName, fileName; + + TString chainFileListTag=chainFileListName; + chainFileListTag.Remove(0,chainFileListTag.Last('/')+1); + chainFileListTag.ReplaceAll(".dat",""); + + TString regionsFileNameTag=regionsFileName; + regionsFileNameTag.Remove(0,regionsFileNameTag.Last('/')+1); + regionsFileNameTag.ReplaceAll(".dat",""); + + std::ifstream chainFileList(chainFileListName.c_str()); + while(chainFileList >> tag, chainFileList.good()){ + if(tag.Contains('#')){ + chainFileList.ignore(1000,'\n'); + continue; + } + chainFileList >> chainName >> fileName; + if(chainName.Contains("Hist")){ + // use these value only if not provided by the command line + if(tag.Contains("d") && dataPUFileName.empty()) dataPUFileNameVec.push_back(fileName); + else if(tag.Contains("s") && mcPUFileName.empty()) mcPUFileNameVec.push_back(fileName); + else std::cerr << "[ERROR] in configuration file Hist not recognized" << std::endl; + continue; + } + + // discard file with energy corrections different from the specified type + if(chainName.Contains("scaleEle")){ + if(chainName!="scaleEle_"+corrEleType) continue; + } + + // discard file with energy smearings different from the specified type + if(chainName.Contains("smearEle")){ + if(chainName!="smearEle_"+smearEleType) continue; + } + + // discard file with categories for "smearingMethod" different from the region file name + if(chainName.Contains("smearerCat")){ + if(chainName!="smearerCat_"+regionsFileNameTag) continue; + } + + if(!tagChainMap.count(tag)){ +#ifdef DEBUG + std::cout << "[DEBUG] Create new tag map for tag: " << tag << std::endl; +#endif + std::pair pair_tmp(tag,chain_map_t()); // make_pair not work with scram b + tagChainMap.insert(pair_tmp); + } + + if(!tagChainMap[tag].count(chainName)){ + std::pair pair_tmp(chainName, new TChain(chainName)); + (tagChainMap[tag]).insert(pair_tmp); + (tagChainMap[tag])[chainName]->SetTitle(tag); + } + std::cout <<"Adding file: " << tag << "\t" << chainName << "\t" << fileName<< std::endl; + if((tagChainMap[tag])[chainName]->Add(fileName,-1)==0) exit(1); +#ifdef DEBUG + std::cout << "[DEBUG] " << tag << "\t" << chainName << "\t" << fileName << "\t" << (tagChainMap[tag])[chainName]->GetEntries() << std::endl; +#endif + + } + + + //init chains and print + for(tag_chain_map_t::const_iterator tag_chain_itr=tagChainMap.begin(); + tag_chain_itr!=tagChainMap.end(); + tag_chain_itr++){ +#ifdef DEBUG + std::cout << tag_chain_itr->first << std::endl; +#endif + for(chain_map_t::const_iterator chain_itr=tag_chain_itr->second.begin(); + chain_itr!=tag_chain_itr->second.end(); + chain_itr++){ + //#ifdef DEBUG + std::cout << " - " << chain_itr->first << "\t" << chain_itr->second->GetName() << "\t" << chain_itr->second->GetTitle() << "\t" << chain_itr->second->GetEntries() << std::endl; + //#endif + chain_itr->second->GetEntries(); + } + } + + + ///------------------------------ to obtain run ranges + if(vm.count("runDivide")){ + runDivide_class runDivider; + std::vector v=runDivider.Divide((tagChainMap["d"])["selected"], "data/runRanges/runRangeLimits.dat", nEvents_runDivide); + runDivider.PrintRunRangeEvents(); + std::vector runRanges; + if(runRangesFileName!="") runRanges = ReadRegionsFromFile(runRangesFileName); + for(std::vector::const_iterator itr = runRanges.begin(); + itr != runRanges.end(); + itr++){ + std::cout << *itr << "\t" << "-1" << "\t" << runDivider.GetRunRangeTime(*itr) << std::endl; + } + + return 0; + } + + + + TString r(regionsFileName.c_str()); + r.Remove(0,r.Last('/')+1); r.ReplaceAll(".dat",""); + + std::vector regions = ReadRegionsFromFile(regionsFileName); + std::vector runRanges = ReadRegionsFromFile(runRangesFileName); + std::vector categories; + for(std::vector::const_iterator region_itr = regions.begin(); + region_itr != regions.end(); + region_itr++){ + if(runRanges.size()>0){ + for(std::vector::const_iterator runRange_itr = runRanges.begin(); + runRange_itr!=runRanges.end(); + runRange_itr++){ + TString token1,token2; + //Ssiz_t ss=0; + //runRange_itr->Tokenize(token1,ss,"-"); + //ss=runRange_itr->First('-'); + //runRange_itr->Tokenize(token2,ss,"-"); + TObjArray *tx = runRange_itr->Tokenize("-"); + token1 = ((TObjString *)(tx->At(0)))->String(); + token2 = ((TObjString *)(tx->At(1)))->String(); + categories.push_back((*region_itr)+"-runNumber_"+token1+"_"+token2+"-"+commonCut.c_str()); + } + }else categories.push_back((*region_itr)+"-"+commonCut.c_str()); + } + + + + ///------------------------------ to obtain r9weights + if(vm.count("saveR9TreeWeight") && !vm.count("r9WeightFile")){ + std::cerr << "[ERROR] No r9WeightFile specified" << std::endl; + return 1; + } + if(vm.count("r9WeightFile")){ + std::cout << "------------------------------------------------------------" << std::endl; + std::cout << "[STATUS] Getting r9Weights from file: " << r9WeightFile << std::endl; + r9Weights_class r9Weights; + r9Weights.ReadFromFile(r9WeightFile); + + TString treeName="r9Weight"; + + // mc // save it in a file and reload it as a chain to be safe against the reference directory for the tree + for(tag_chain_map_t::const_iterator tag_chain_itr=tagChainMap.begin(); + tag_chain_itr!=tagChainMap.end(); + tag_chain_itr++){ + if(tag_chain_itr->first.CompareTo("d")==0 || tag_chain_itr->first.CompareTo("s")==0) continue; + if(tag_chain_itr->second.count(treeName)!=0) continue; //skip if already present + TChain *ch = (tag_chain_itr->second.find("selected"))->second; + + TString filename="tmp/r9Weight_"+tag_chain_itr->first+"-"+chainFileListTag+".root"; + std::cout << "[STATUS] Saving r9Weights tree to root file:" << filename << std::endl; + + TFile f(filename,"recreate"); + if(!f.IsOpen() || f.IsZombie()){ + std::cerr << "[ERROR] File for r9Weights: " << filename << " not opened" << std::endl; + exit(1); + } + TTree *corrTree = r9Weights.GetTreeWeight(ch); + f.cd(); + corrTree->Write(); + std::cout << "[INFO] Data entries: " << ch->GetEntries() << std::endl; + std::cout << " r9Weights entries: " << corrTree->GetEntries() << std::endl; + delete corrTree; + + f.Write(); + f.Close(); + std::pair pair_tmp(treeName, new TChain(treeName)); + chain_map_t::iterator chain_itr= ((tagChainMap[tag_chain_itr->first]).insert(pair_tmp)).first; + chain_itr->second->SetTitle(tag_chain_itr->first); + chain_itr->second->Add(filename); + + } // end of data samples loop + } // end of r9Weight + + + if(vm.count("saveR9TreeWeight")) return 0; + + ///------------------------------ to obtain ZPt weights + if(vm.count("ZPtWeightFile")){ + std::cout << "------------------------------------------------------------" << std::endl; + std::cout << "[STATUS] Getting ZPtWeights from file: " << ZPtWeightFile << std::endl; + UpdateFriends(tagChainMap, regionsFileNameTag); + ZPtWeights_class ZPtWeights; + ZPtWeights.ReadFromFile(ZPtWeightFile); + + TString treeName="ZPtWeight"; + + // mc // save it in a file and reload it as a chain to be safe against the reference directory for the tree + for(tag_chain_map_t::const_iterator tag_chain_itr=tagChainMap.begin(); + tag_chain_itr!=tagChainMap.end(); + tag_chain_itr++){ + if(tag_chain_itr->first.Contains("d")) continue; /// \todo ZPtWeight only on MC! because from PdfWeights, to make it more general + if(tag_chain_itr->first.CompareTo("d")==0 || tag_chain_itr->first.CompareTo("s")==0) continue; + if(tag_chain_itr->second.count(treeName)!=0) continue; //skip if already present + TChain *ch = (tag_chain_itr->second.find("selected"))->second; + + TString filename="tmp/ZPtWeight_"+tag_chain_itr->first+"-"+chainFileListTag+".root"; + std::cout << "[STATUS] Saving r9Weights tree to root file:" << filename << std::endl; + + TFile f(filename,"recreate"); + if(!f.IsOpen() || f.IsZombie()){ + std::cerr << "[ERROR] File for ZPtWeights: " << filename << " not opened" << std::endl; + exit(1); + } + TTree *corrTree = ZPtWeights.GetTreeWeight(ch, "ZPt_"+energyBranchName); + f.cd(); + corrTree->Write(); + std::cout << "[INFO] Data entries: " << ch->GetEntries() << std::endl; + std::cout << " ZPtWeights entries: " << corrTree->GetEntries() << std::endl; + delete corrTree; + + f.Write(); + f.Close(); + std::pair pair_tmp(treeName, new TChain(treeName)); + chain_map_t::iterator chain_itr= ((tagChainMap[tag_chain_itr->first]).insert(pair_tmp)).first; + chain_itr->second->SetTitle(tag_chain_itr->first); + chain_itr->second->Add(filename); + + } // end of data samples loop + } // end of r9Weight + + + //============================== + + // if(vm.count("dataPU")==0 && (tagChainMap["s"]).count("pileupHist")==0 && (tagChainMap["s"]).count("pileup")==0){ + + if(vm.count("noPU")==0 && !vm.count("runToy") && !vm.count("correctionMomentum") && !vm.count("laserMonitoringEP") && !vm.count("laserMonitoringEPvsPU") && + !vm.count("EOverPCalib")){ + if(dataPUFileNameVec.empty() && (tagChainMap.count("s")!=0) && (tagChainMap["s"]).count("pileup")==0){ + std::cerr << "[ERROR] Nor pileup mc tree configured in chain list file either dataPU histograms are not provided" << std::endl; + return 1; + }else if( !vm.count("runToy") && (vm.count("dataPU")!=0 || (!dataPUFileNameVec.empty() && ((tagChainMap.count("s")==0) || (tagChainMap["s"]).count("pileup")==0)))){ + std::cout << "[STATUS] Creating pileup weighting tree and saving it" << std::endl; + for(unsigned int i=0; i < mcPUFileNameVec.size(); i++){ + TString mcPUFileName_=mcPUFileNameVec[i]; + TString dataPUFileName_=dataPUFileNameVec[i]; + TString runMin_ = ""; + if(!mcPUFileName_.Contains("nPU")){ +// if(mcPUFileName_.Index(".runMin_")!=-1){ + runMin_=mcPUFileName_; + runMin_.Remove(0,runMin_.Last('/')+1); + runMin_.Remove(runMin_.First('-')); +// runMin_.Remove(runMin_.First('.')); +// runMin_.ReplaceAll("runMin_",""); + } + int runMin = runMin_.Sizeof()>1 ? runMin_.Atoi() : 1; + std::cout << "********* runMin = " << runMin << "\t" << runMin_ << std::endl; + puWeights.ReadFromFiles(mcPUFileName_.Data(),dataPUFileName_.Data(), runMin); + } + + // for each mc sample create a tree with the per-event-weight + // but exclude the chain "s" since it's supposed to be created mergin alle the s-type samples + for(tag_chain_map_t::const_iterator tag_chain_itr=tagChainMap.begin(); + tag_chain_itr!=tagChainMap.end(); + tag_chain_itr++){ + if(tag_chain_itr->first.CompareTo("s")==0 || !tag_chain_itr->first.Contains("s")) continue; + TChain *ch = (tag_chain_itr->second.find("selected"))->second; + if((tag_chain_itr->second.count("pileup"))) continue; + TString treeName="pileup"; + TString filename="tmp/mcPUtree"+tag_chain_itr->first+".root"; + TFile f(filename,"recreate"); + if(f.IsOpen()){ + f.cd(); + + TTree *puTree = puWeights.GetTreeWeight(ch,true); + puTree->SetName(treeName); + puTree->Write(); + delete puTree; + f.Write(); + f.Close(); + std::pair pair_tmp(treeName, new TChain(treeName)); + chain_map_t::iterator chain_itr= ((tagChainMap[tag_chain_itr->first]).insert(pair_tmp)).first; + chain_itr->second->SetTitle(tag_chain_itr->first); + chain_itr->second->Add(filename); + } + } + } + } + + //read corrections directly from file + if (vm.count("corrEleType") && corrEleFile!=""){ + std::cout << "------------------------------------------------------------" << std::endl; + std::cout << "[STATUS] Getting energy scale corrections from file: " << corrEleFile << std::endl; + TString treeName="scaleEle_"+corrEleType; + EnergyScaleCorrection_class eScaler(corrEleFile); + + for(tag_chain_map_t::const_iterator tag_chain_itr=tagChainMap.begin(); + tag_chain_itr!=tagChainMap.end(); + tag_chain_itr++){ + if(tag_chain_itr->first.CompareTo("d")==0 || !tag_chain_itr->first.Contains("d")) continue; //only data + if(tag_chain_itr->second.count(treeName)!=0) continue; //skip if already present + TChain *ch = (tag_chain_itr->second.find("selected"))->second; + + TString filename="tmp/scaleEle_"+corrEleType+"_"+tag_chain_itr->first+"-"+chainFileListTag+".root"; + std::cout << "[STATUS] Saving electron scale corrections to root file:" << filename << std::endl; + + TFile f(filename,"recreate"); + if(!f.IsOpen() || f.IsZombie()){ + std::cerr << "[ERROR] File for scale corrections: " << filename << " not opened" << std::endl; + exit(1); + } + TTree *corrTree = eScaler.GetCorrTree(ch, "runNumber", "R9Eleprime"); + corrTree->SetName(TString("scaleEle_")+corrEleType.c_str()); + corrTree->SetTitle(corrEleType.c_str()); + f.cd(); + corrTree->Write(); + std::cout << "[INFO] Data entries: " << ch->GetEntries() << std::endl; + std::cout << " corrEle entries: " << corrTree->GetEntries() << std::endl; + delete corrTree; + + f.Write(); + f.Close(); + std::pair pair_tmp(treeName, new TChain(treeName)); + chain_map_t::iterator chain_itr= ((tagChainMap[tag_chain_itr->first]).insert(pair_tmp)).first; + chain_itr->second->SetTitle(tag_chain_itr->first); + chain_itr->second->Add(filename); + + } // end of data samples loop + } // end of corrEle loop + + + //read corrections directly from file + if (vm.count("smearEleType")){ + std::cout << "------------------------------------------------------------" << std::endl; + std::cout << "[STATUS] Getting energy smearings from file: " << smearEleFile << std::endl; + TString treeName="smearEle_"+smearEleType; + EnergyScaleCorrection_class eScaler("", smearEleFile); + for(tag_chain_map_t::const_iterator tag_chain_itr=tagChainMap.begin(); + tag_chain_itr!=tagChainMap.end(); + tag_chain_itr++){ + if(tag_chain_itr->first.CompareTo("s")==0 || !tag_chain_itr->first.Contains("s")) continue; //only data + if(tag_chain_itr->second.count(treeName)!=0) continue; //skip if already present + TChain *ch = (tag_chain_itr->second.find("selected"))->second; + + TString filename="tmp/smearEle_"+smearEleType+"_"+tag_chain_itr->first+"-"+chainFileListTag+".root"; + std::cout << "[STATUS] Saving electron smearings to root file:" << filename << std::endl; + + TFile f(filename,"recreate"); + if(!f.IsOpen() || f.IsZombie()){ + std::cerr << "[ERROR] File for scale corrections: " << filename << " not opened" << std::endl; + exit(1); + } + if(TString(smearEleType).Contains("CB")){ + eScaler.SetSmearingType(1); + eScaler.SetSmearingCBAlpha(smearingCBAlpha); + } + + TTree *corrTree = eScaler.GetSmearTree(ch, true, energyBranchName ); + f.cd(); + corrTree->SetName(TString("smearEle_")+smearEleType.c_str()); + corrTree->SetTitle(smearEleType.c_str()); + corrTree->Write(); + std::cout << "[INFO] Data entries: " << ch->GetEntries() << std::endl; + std::cout << " smearEle entries: " << corrTree->GetEntries() << std::endl; + delete corrTree; + + f.Write(); + f.Close(); + std::pair pair_tmp(treeName, new TChain(treeName)); + chain_map_t::iterator chain_itr= ((tagChainMap[tag_chain_itr->first]).insert(pair_tmp)).first; + chain_itr->second->SetTitle(tag_chain_itr->first); + chain_itr->second->Add(filename); + } + // \todo need the data part in case of needs + } + + + addBranch_class newBrancher; + newBrancher._commonCut=commonCut.c_str(); + newBrancher._regionList=categories; + + for( std::vector::const_iterator branch_itr = branchList.begin(); + branch_itr != branchList.end(); + branch_itr++){ + UpdateFriends(tagChainMap, regionsFileNameTag); + + TString treeName=*branch_itr; + TString t; + if(treeName=="smearerCat_s"){ + treeName.ReplaceAll("_s",""); + t="s"; + } + if(treeName=="smearerCat_d"){ + treeName.ReplaceAll("_d",""); + t="d"; + } + TString branchName=treeName; + std::cout << "#### --> " << treeName << "\t" << t << "\t" << *branch_itr <first.CompareTo("s")==0 || tag_chain_itr->first.CompareTo("d")==0)) continue; //only data + if(tag_chain_itr->second.count(treeName)!=0) continue; //skip if already present + if(t!="" && !tag_chain_itr->first.Contains(t)) continue; + TChain *ch = (tag_chain_itr->second.find("selected"))->second; + + //data + std::cout <<"[STATUS] Adding branch " << branchName << " to " << tag_chain_itr->first <first+"-"+chainFileListTag+".root"; + + TTree *newTree = newBrancher.AddBranch(ch,treeName, branchName,true,tag_chain_itr->first.Contains("s")); + if(newTree==NULL){ + std::cerr << "[ERROR] New tree for branch " << treeName << " is NULL" << std::endl; + return 1; + } + + TFile f(filename,"recreate"); + if (!f.IsOpen()){ + std::cerr << "[ERROR] File for branch " << branchName << " not created" << std::endl; + return 1; + } + f.cd(); + newTree->SetTitle(tag_chain_itr->first); + newTree->Write(); + delete newTree; + //f.Write(); + f.Close(); + std::pair pair_tmp(treeName, new TChain(treeName)); + chain_map_t::iterator chain_itr= ((tagChainMap[tag_chain_itr->first]).insert(pair_tmp)).first; + chain_itr->second->SetTitle(tag_chain_itr->first); + chain_itr->second->Add(filename); + } //end of sample loop + } //end of branches loop + + + + //(tagChainMap["s"])["selected"]->GetEntries(); + UpdateFriends(tagChainMap, regionsFileNameTag); + + //create tag "s" if not present (due to multiple mc samples) + if(!tagChainMap.count("s")){ + //#ifdef DEBUG + std::cout << "==============================" << std::endl; + std::cout << "==============================" << std::endl; + MergeSamples(tagChainMap, regionsFileNameTag, "s"); + MergeSamples(tagChainMap, regionsFileNameTag, "d"); + } + +// Dump(tagChainMap, "s",0); +// Dump(tagChainMap, "s",(tagChainMap["s1"])["selected"]->GetEntries()); +// Dump(tagChainMap, "s",(tagChainMap["s2"])["selected"]->GetEntries()); +// exit(0); + if(vm.count("saveRootMacro")){ + for(tag_chain_map_t::const_iterator tag_chain_itr=tagChainMap.begin(); + tag_chain_itr!=tagChainMap.end(); + tag_chain_itr++){ + for(chain_map_t::const_iterator chain_itr=tag_chain_itr->second.begin(); + chain_itr!=tag_chain_itr->second.end(); + chain_itr++){ + chain_itr->second->SaveAs("tmp/"+tag_chain_itr->first+"_"+chain_itr->first+"_chain.root"); + //chain_itr->second->SavePrimitive(std::cout); // not implemented + } + } + } + + if( + vm.count("saveRootMacro") + || vm.count("saveCorrEleTree") + || vm.count("saveAddBranchTree") + || vm.count("savePUTreeWeight") + || vm.count("runDivide") + || vm.count("saveCorrEleTree") + || vm.count("saveR9TreeWeight") + ) return 0; + + eleID+=selection.c_str(); + eleID.ReplaceAll("_",""); + + //------------------------------ RooSmearer + RooArgSet args; + std::vector args_vec; + + for(std::vector::const_iterator region_itr = categories.begin(); + region_itr != categories.end(); + region_itr++){ + RooRealVar *scale_ = new RooRealVar("scale_"+*region_itr, "scale_"+*region_itr,1.0, 0.95,1.05,"GeV"); //0.9,1.1,"GeV") + scale_->setError(0.005); // 1% + // scale_->setConstant(); + // scale_->setBinning(RooBinning( + args.add(*scale_); + + TString varName=*region_itr; + TPRegexp reg("Et_[0-9]*_[0-9]*"); + reg.Substitute(varName,""); + TPRegexp reg2("energySC_[0-9]*_[0-9]*"); + reg2.Substitute(varName,""); + varName.ReplaceAll("--","-"); + if(varName.First("-")==0) varName.Remove(0,1); + + //RooRealVar *const_term_ = new RooRealVar("constTerm_"+*region_itr, "constTerm_"+*region_itr, 0.01, 0.0005, 0.05); + RooAbsReal *const_term_=NULL; + RooRealVar *const_term_v = args.getSize() ==0 ? NULL : (RooRealVar *) args.find("constTerm_"+varName); + if(const_term_v==NULL){ + if(vm.count("constTermFix")==0) const_term_v = new RooRealVar("constTerm_"+*region_itr, "constTerm_"+varName,0.00, 0.000,0.05); + else const_term_v = new RooRealVar("constTerm_"+varName, "constTerm_"+varName,0.00, 0.000,0.02); + const_term_v->setError(0.03); // 1% + //const_term_v->setConstant(true); + args.add(*const_term_v); + } + if((reg.MatchB(*region_itr) || reg2.MatchB(*region_itr) )&& vm.count("constTermFix")==1){ + const_term_ = new RooFormulaVar("constTerm_"+*region_itr, "constTerm_"+varName,"@0", *const_term_v); + const_term_v->setConstant(false); + } else const_term_ = const_term_v; + + + + RooAbsReal *alpha_=NULL; + RooRealVar *alpha_v = args.getSize() ==0 ? NULL : (RooRealVar *) args.find("alpha_"+varName); + if(alpha_v==NULL){ + alpha_v = new RooRealVar("alpha_"+varName, "alpha_"+varName,0.0, 0.,0.20); + alpha_v->setError(0.01); + alpha_v->setConstant(true); + //alpha_v->Print(); + if(!vm.count("alphaGoldFix") || !region_itr->Contains("absEta_1_1.4442-gold")){ + args.add(*alpha_v); + } + } + if(reg.MatchB(*region_itr) && vm.count("constTermFix")==1){ + if(vm.count("alphaGoldFix") && region_itr->Contains("absEta_1_1.4442-gold")){ + std::cout << "[STATUS] Fixing alpha term to low eta region " << *region_itr << std::endl; + std::cerr << "[STATUS] Fixing alpha term to low eta region " << *region_itr << std::endl; + TString lowRegionVarName=varName; lowRegionVarName.ReplaceAll("absEta_1_1.4442","absEta_0_1"); + alpha_v = (RooRealVar *)args.find("alpha_"+lowRegionVarName); + alpha_ = new RooFormulaVar("alpha_"+*region_itr, "alpha_"+lowRegionVarName,"@0", *alpha_v); + } else { + alpha_ = new RooFormulaVar("alpha_"+*region_itr, "alpha_"+varName,"@0", *alpha_v); + } + alpha_v->setConstant(false); + } else alpha_ = alpha_v; + + args_vec.push_back(RooArgSet(*scale_, *alpha_, *const_term_)); + } + + if(vm.count("onlyScale")){ + TIterator *it1=NULL; + it1 = args.createIterator(); + for(RooRealVar *var = (RooRealVar *) it1->Next(); var!=NULL; + var = (RooRealVar *) it1->Next()){ + TString name(var->GetName()); + if(name.Contains("scale")) continue; + var->setConstant(true); + } + } + + args.sort(kFALSE); + if(vm.count("smearerFit")){ + std::cout << "------------------------------ smearer parameters" << std::endl; + args.writeToStream(std::cout, kFALSE); + } + + TRandom3 g(0); + Long64_t randomInt=g.Integer(1000000); + TString filename="tmp/tmpFile-"; filename+=randomInt;filename+=".root"; + TFile *tmpFile = new TFile(filename,"recreate"); + tmpFile->cd(); + RooSmearer smearer("smearer",(tagChainMap["d"])["selected"], (tagChainMap["s"])["selected"], NULL, + categories, + args_vec, args, energyBranchName); + smearer._isDataSmeared=vm.count("isDataSmeared"); + if(vm.count("runToy")) smearer.SetPuWeight(false); + smearer.SetOnlyDiagonal(vm.count("onlyDiagonal")); + smearer._autoBin=vm.count("autoBin"); + smearer._autoNsmear=vm.count("autoNsmear"); + smearer.smearscan=vm.count("smearscan"); + //smearer.nEventsMinDiag = nEventsMinDiag; + smearer._deactive_minEventsOffDiag = nEventsMinOffDiag; + smearer.SetSmearingEt(vm.count("smearingEt")); + smearer.SetR9Weight(vm.count("useR9weight")); + smearer.SetPdfSystWeight(pdfSystWeightIndex); + smearer.SetZPtWeight(vm.count("useZPtweight")); + smearer.SetFsrWeight(vm.count("useFSRweight")); + smearer.SetWeakWeight(vm.count("useWEAKweight")); + + if(nSmearToy>0) smearer._nSmearToy = nSmearToy; + + + //------------------------------ Take the list of branches needed for the defined categories + ElectronCategory_class cutter; + cutter.energyBranchName=energyBranchName; + std::set activeBranchList; + for(std::vector::const_iterator region_itr = categories.begin(); + region_itr != categories.end(); + region_itr++){ + std::set tmpList = cutter.GetBranchNameNtuple(*region_itr); + activeBranchList.insert(tmpList.begin(),tmpList.end()); + // add also the friend branches! + } + + if(vm.count("loop")){ +// TFile *file = new TFile("evList.root","read"); + +// Loop((tagChainMap["s1"])["selected"],file); + return 0; + } + //------------------------------ ZFit_class declare and set the options + TChain *data = NULL; + TChain *mc = NULL; + if(!vm.count("smearerFit")){ + data= (tagChainMap["d"])["selected"]; + mc = (tagChainMap["s"])["selected"]; + } + + + +//------------------------------ LASER MONITORING WITH E/P ------------------------------------------------------ + + if(vm.count("laserMonitoringEP")) { + + float timeLapse = 10000000.; // in hours + // int t1 = 1267401600; // 1 Mar 2010 + //int t2 = 1325289600; // 31 Dec 2011 + //int t1 = 1400000000; + //int t2 = 1600000000; + + // float yMIN = 0.65; + //float yMAX = 1.10; + + + // Set style options + setTDRStyle(); + gStyle->SetPadTickX(1); + gStyle->SetPadTickY(1); + gStyle->SetOptTitle(0); + gStyle->SetOptStat(1110); + gStyle->SetOptFit(1); + + // Set fitting options + TVirtualFitter::SetDefaultFitter("Fumili2"); + + + + //----------------- + // Input parameters + + + std::cout << "\n***************************************************************************************************************************" << std::endl; + + // std::string dayMin = ""; + //std::string dayMax = ""; + std::string dayMinLabel = ""; + std::string dayMaxLabel = ""; + std::string dayZOOMLabel =""; + float absEtaMin = -1.; + float absEtaMax = -1.; + int IetaMin = -1; + int IetaMax = -1; + int IphiMin = -1; + int IphiMax = -1; + + + + + // int t1 = dateToInt(dayMin); + // int t2 = dateToInt(dayMax); + int t3 = dateToInt(dayZOOM); + + float t1=0.; + float t2=10.; + /* + if(argc >= 5) + { + dayMin = std::string(argv[4])+" "+std::string(argv[5])+" "+std::string(argv[6]); + dayMax = std::string(argv[7])+" "+std::string(argv[8])+" "+std::string(argv[9]); + dayMinLabel = std::string(argv[4])+"_"+std::string(argv[5])+"_"+std::string(argv[6]); + dayMaxLabel = std::string(argv[7])+"_"+std::string(argv[8])+"_"+std::string(argv[9]); + + } + if(argc >= 11) + { + yMIN = atof(argv[10]); + yMAX = atof(argv[11]); + } + if(argc >= 13) + { + absEtaMin = atof(argv[12]); + absEtaMax = atof(argv[13]); + } + if(argc >= 15) + { + IetaMin = atoi(argv[14]); + IetaMax = atoi(argv[15]); + IphiMin = atoi(argv[16]); + IphiMax = atoi(argv[17]); + } + */ + + std::cout << "EBEE: " << EBEE << std::endl; + std::cout << "evtsPerPoint: " << evtsPerPoint << std::endl; + std::cout << "useRegression: " << useRegression << std::endl; + std::cout << "dayMin: " << dayMin << std::endl; + std::cout << "dayZOOM: " << dayZOOM << std::endl; + std::cout << "dayMax: " << dayMax << std::endl; + std::cout << "yMin: " << yMIN << std::endl; + std::cout << "yMax: " << yMAX << std::endl; + std::cout << "absEtaMin: " << absEtaMin << std::endl; + std::cout << "absEtaMax: " << absEtaMax << std::endl; + std::cout << "IetaMin: " << IetaMin << std::endl; + std::cout << "IetaMax: " << IetaMax << std::endl; + std::cout << "IphiMin: " << IphiMin << std::endl; + std::cout << "IphiMax: " << IphiMax << std::endl; + std::cout << "t1: " << t1 << std::endl; + std::cout << "t2: " << t2 << std::endl; + std::cout << "t3" << t3 << std::endl; + + std::string dayZOOM = ""; + std::string dayMin = ""; + std::string dayMax = ""; + + + //------------------- + // Define in/outfiles + + std::string folderName = std::string(EBEE) + "_" + dayMinLabel + "_" + dayMaxLabel; + if( (absEtaMin != -1.) && (absEtaMax != -1.) ) + { + char absEtaBuffer[50]; + sprintf(absEtaBuffer,"_%.2f-%.2f",absEtaMin,absEtaMax); + folderName += std::string(absEtaBuffer); + } + + if( (IetaMin != -1.) && (IetaMax != -1.) && (IphiMin != -1.) && (IphiMax != -1.) ) + { + char absEtaBuffer[50]; + sprintf(absEtaBuffer,"_Ieta_%d-%d_Iphi_%d-%d",IetaMin,IetaMax,IphiMin,IphiMax); + folderName += std::string(absEtaBuffer); + } + + gSystem->mkdir(folderName.c_str()); + TFile* o = new TFile((folderName+"/"+folderName+"_histos.root").c_str(),"RECREATE"); + + + + // Get trees + std::cout << std::endl; + + /* + TChain* ntu_DA = new TChain("simpleNtupleEoverP/SimpleNtupleEoverP"); + FillChain(ntu_DA,"inputDATA.txt"); + std::cout << " DATA: " << std::setw(8) << ntu_DA->GetEntries() << " entries" << std::endl; + + TChain* ntu_MC = new TChain("simpleNtupleEoverP/SimpleNtupleEoverP"); + FillChain(ntu_MC,"inputMC.txt"); + std::cout << "REFERENCE: " << std::setw(8) << ntu_MC->GetEntries() << " entries" << std::endl; + */ + + if (data->GetEntries() == 0 || mc->GetEntries() == 0 ) + { + std::cout << "Error: At least one file is empty" << std::endl; + return -1; + } + + + + // Set branch addresses + int runNumber; + int runTime; + int nPU; + float avgLCSCEle[3], etaSCEle[3], phiSCEle[3], energySCEle[3], esEnergySCEle[3], pAtVtxGsfEle[3], energySCEle_corr[3]; + int seedXSCEle[3], seedYSCEle[3];//, seedZside; + // float seedLaserAlphaSCEle1; + + data->SetBranchStatus("*",0); + data->SetBranchStatus("runNumber",1); + data->SetBranchStatus("runTime",1); + data->SetBranchStatus("nPU",1); + data->SetBranchStatus("avgLCSCEle",1); + // data->SetBranchStatus("seedLaserAlphaSCEle1",1); + // data->SetBranchStatus("ele1_EOverP",1); + data->SetBranchStatus("etaSCEle",1); + data->SetBranchStatus("phiSCEle",1); + data->SetBranchStatus("energySCEle_must",1); + data->SetBranchStatus("energySCEle_corr",1); + data->SetBranchStatus("esEnergySCEle",1); + data->SetBranchStatus("pAtVtxGsfEle",1); + data->SetBranchStatus("seedXSCEle",1); + data->SetBranchStatus("seedYSCEle",1); + // data->SetBranchStatus("ele1_seedZside",1); + + data->SetBranchAddress("runNumber", &runNumber); + data->SetBranchAddress("runTime", &runTime); + data->SetBranchAddress("nPU", &nPU); + data->SetBranchAddress("avgLCSCEle", &avgLCSCEle[0]); + //data->SetBranchAddress("seedLaserAlphaSCEle1", &seedLaserAlphaSCEle1); + // data->SetBranchAddress("ele1_EOverP", &EoP); + data->SetBranchAddress("etaSCEle", &etaSCEle); + data->SetBranchAddress("phiSCEle", &phiSCEle); + if( useRegression < 1 ) + data->SetBranchAddress("energySCEle_must", &energySCEle); + else + data->SetBranchAddress("energySCEle_corr", &energySCEle_corr); + // data->SetBranchAddress("energySCEle_corr", &energySCEle); + data->SetBranchAddress("esEnergySCEle", &esEnergySCEle); + data->SetBranchAddress("pAtVtxGsfEle", &pAtVtxGsfEle); + data->SetBranchAddress("seedXSCEle", &seedXSCEle); + data->SetBranchAddress("seedYSCEle", &seedYSCEle); + // data->SetBranchAddress("ele1_seedZside", &seedZside); + + + mc->SetBranchStatus("*",0); + mc->SetBranchStatus("runNumber",1); + mc->SetBranchStatus("runTime",1); + mc->SetBranchStatus("nPU",1); + mc->SetBranchStatus("avgLCSCEle",1); + // mc->SetBranchStatus("seedLaserAlphaSCEle1",1); + // mc->SetBranchStatus("ele1_EOverP",1); + mc->SetBranchStatus("etaSCEle",1); + mc->SetBranchStatus("phiSCEle",1); + mc->SetBranchStatus("energySCEle_must",1); + mc->SetBranchStatus("energySCEle_corr",1); + mc->SetBranchStatus("esEnergySCEle",1); + mc->SetBranchStatus("pAtVtxGsfEle",1); + mc->SetBranchStatus("seedXSCEle",1); + mc->SetBranchStatus("seedYSCEle",1); + // mc->SetBranchStatus("ele1_seedZside",1); + + mc->SetBranchAddress("runNumber", &runNumber); + mc->SetBranchAddress("runTime", &runTime); + mc->SetBranchAddress("nPU", &nPU); + mc->SetBranchAddress("avgLCSCEle", &avgLCSCEle[0]); + //mc->SetBranchAddress("seedLaserAlphaSCEle1", &seedLaserAlphaSCEle1); + // mc->SetBranchAddress("ele1_EOverP", &EoP); + mc->SetBranchAddress("etaSCEle", &etaSCEle); + mc->SetBranchAddress("phiSCEle", &phiSCEle); + if( useRegression < 1 ) + mc->SetBranchAddress("energySCEle_must", &energySCEle); + else + mc->SetBranchAddress("energySCEle_corr", &energySCEle_corr); + // mc->SetBranchAddress("energySCEle_corr", &energySCEle); + mc->SetBranchAddress("esEnergySCEle", &esEnergySCEle); + mc->SetBranchAddress("pAtVtxGsfEle", &pAtVtxGsfEle); + mc->SetBranchAddress("seedXSCEle", &seedXSCEle); + mc->SetBranchAddress("seedYSCEle", &seedYSCEle); + // mc->SetBranchAddress("ele1_seedZside", &seedZside); + + + + + + + //-------------------------------------------------------- + // Define PU correction (to be used if useRegression == 0) + + // corr = p0 + p1 * nPU + float p0_EB; + float p1_EB; + float p0_EE; + float p1_EE; + + if( useRegression == 0 ) + { + //2012 EB + p0_EB = 0.9991; + p1_EB = 0.0001635; + //2012 EE + p0_EE = 0.9968; + p1_EE = 0.001046; + } + else + { + //2012 EB + p0_EB = 1.001; + p1_EB = -0.000143; + //2012 EE + p0_EE = 1.00327; + p1_EE = -0.000432; + } + + float p0 = -1.; + float p1 = -1.; + + if( strcmp(EBEE.c_str(),"EB") == 0 ) + { + p0 = p0_EB; + p1 = p1_EB; + } + else + { + p0 = p0_EE; + p1 = p1_EE; + } + + //2015 + p0=1.; + p1=0.; + + + + + //--------------------------------- + // Build the reference distribution + + std::cout << std::endl; + std::cout << "***** Build reference for " << EBEE << " *****" << std::endl; + + TH1F* h_template = new TH1F("template", "", 2000, 0., 5.); + + for(int ientry = 0; ientry < mc->GetEntries(); ++ientry) + { + if( (ientry%10000 == 0) ) std::cout << "reading MC entry " << ientry <<"/"<GetEntries()<< "\r" << std::endl;//std::flush; + mc->GetEntry(ientry); + + // selections + if( (strcmp(EBEE.c_str(),"EB") == 0) && (fabs(etaSCEle[0]) > 1.479) ) continue; // barrel + if( (strcmp(EBEE.c_str(),"EB_0_1") == 0) && (fabs(etaSCEle[0]) > 1.0)) continue; // inner barrel + if( (strcmp(EBEE.c_str(),"EB_1_1479") == 0) && (fabs(etaSCEle[0]) < 1.0 || fabs(etaSCEle[0]) > 1.479) ) continue; // barrel + if( (strcmp(EBEE.c_str(),"EE") == 0) && (fabs(etaSCEle[0]) < 1.479 || fabs(etaSCEle[0])>2.5) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EE_1479_2") == 0) && (fabs(etaSCEle[0]) < 1.479 || fabs(etaSCEle[0])>2.0) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EE_2_25") == 0) && (fabs(etaSCEle[0]) < 2.0 || fabs(etaSCEle[0])>2.5) ) continue; // endcap + + if( (strcmp(EBEE.c_str(),"EEp") == 0) && (etaSCEle[0] < 1.479 || etaSCEle[0]>2.5 ) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_1479_2") == 0) && (etaSCEle[0] < 1.479 || etaSCEle[0]>2.0) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_2_25") == 0) && (etaSCEle[0] < 2.0 || etaSCEle[0]>2.5) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_2_225") == 0) && (etaSCEle[0] < 2.0 || etaSCEle[0]>2.25) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_225_25") == 0) && (etaSCEle[0] < 2.25 || etaSCEle[0]>2.25) ) continue; // endcap + + if( (strcmp(EBEE.c_str(),"EEm") == 0) && (etaSCEle[0] > -1.479 || etaSCEle[0]<-2.5 ) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_1479_2") == 0) && (etaSCEle[0] > -1.479 || etaSCEle[0]<-2.0) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_2_25") == 0) && (etaSCEle[0] > -2.0 || etaSCEle[0]<-2.5) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_2_225") == 0) && (etaSCEle[0] > -2.0 || etaSCEle[0]<-2.25) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_225_25") == 0) && (etaSCEle[0] > -2.25 || etaSCEle[0]<-2.5) ) continue; // endcap + + if( (absEtaMin != -1.) && (absEtaMax != -1.) ) + { + if( (fabs(etaSCEle[0]) < absEtaMin) || (fabs(etaSCEle[0]) > absEtaMax) ) continue; + } + + if( (IetaMin != -1.) && (IetaMax != -1.) && (IphiMin != -1.) && (IphiMax != -1.) ) + { + if( (seedXSCEle[0] < IetaMin) || (seedXSCEle[0] > IetaMax) ) continue; + if( (seedYSCEle[0] < IphiMin) || (seedYSCEle[0] > IphiMax) ) continue; + } + + // PU correction + float PUCorr = (p0 + p1*nPU); + //std::cout << "p0: " << p0 << " p1: " << p1 << " nPU: " << nPU << std::endl; + + // fill the template histogram + h_template -> Fill( (energySCEle[0]-esEnergySCEle[0])/(pAtVtxGsfEle[0]-esEnergySCEle[0]) / PUCorr ); + } + + std::cout << "Reference built for " << EBEE << " - " << h_template->GetEntries() << " events" << std::endl; + + + + + + + //--------------------- + // Loop and sort events + + std::cout << std::endl; + std::cout << "***** Sort events and define bins *****" << std::endl; + + int nEntries = data -> GetEntriesFast(); + int nSavePts = 0; + std::vector isSavedEntries(nEntries); + std::vector sortedEntries; + std::vector timeStampFirst; + + for(int ientry = 0; ientry < nEntries; ++ientry) + { + data -> GetEntry(ientry); + isSavedEntries.at(ientry) = false; + + if( (ientry%10000 == 0) ) std::cout << "reading data entry " << ientry << "\r" << std::endl;//std::flush; + + // selections + if( (strcmp(EBEE.c_str(),"EB") == 0) && (fabs(etaSCEle[0]) > 1.479) ) continue; // barrel + if( (strcmp(EBEE.c_str(),"EB_0_1") == 0) && (fabs(etaSCEle[0]) > 1.0)) continue; // inner barrel + if( (strcmp(EBEE.c_str(),"EB_1_1479") == 0) && (fabs(etaSCEle[0]) < 1.0 || fabs(etaSCEle[0]) > 1.479) ) continue; // barrel + if( (strcmp(EBEE.c_str(),"EE") == 0) && (fabs(etaSCEle[0]) < 1.479 || fabs(etaSCEle[0])>2.5) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EE_1479_2") == 0) && (fabs(etaSCEle[0]) < 1.479 || fabs(etaSCEle[0])>2.0) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EE_2_25") == 0) && (fabs(etaSCEle[0]) < 2.0 || fabs(etaSCEle[0])>2.5) ) continue; // endcap + + if( (strcmp(EBEE.c_str(),"EEp") == 0) && (etaSCEle[0] < 1.479 || etaSCEle[0]>2.5 ) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_1479_2") == 0) && (etaSCEle[0] < 1.479 || etaSCEle[0]>2.0) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_2_25") == 0) && (etaSCEle[0] < 2.0 || etaSCEle[0]>2.5) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_2_225") == 0) && (etaSCEle[0] < 2.0 || etaSCEle[0]>2.25) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_225_25") == 0) && (etaSCEle[0] < 2.25 || etaSCEle[0]>2.25) ) continue; // endcap + + if( (strcmp(EBEE.c_str(),"EEm") == 0) && (etaSCEle[0] > -1.479 || etaSCEle[0]<-2.5 ) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_1479_2") == 0) && (etaSCEle[0] > -1.479 || etaSCEle[0]<-2.0) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_2_25") == 0) && (etaSCEle[0] > -2.0 || etaSCEle[0]<-2.5) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_2_225") == 0) && (etaSCEle[0] > -2.0 || etaSCEle[0]<-2.25) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_225_25") == 0) && (etaSCEle[0] > -2.25 || etaSCEle[0]<-2.5) ) continue; // endcap + + if( (absEtaMin != -1.) && (absEtaMax != -1.) ) + { + if( (fabs(etaSCEle[0]) < absEtaMin) || (fabs(etaSCEle[0]) > absEtaMax) ) continue; + } + + if( (IetaMin != -1.) && (IetaMax != -1.) && (IphiMin != -1.) && (IphiMax != -1.) ) + { + if( (seedXSCEle[0] < IetaMin) || (seedXSCEle[0] > IetaMax) ) continue; + if( (seedYSCEle[0] < IphiMin) || (seedYSCEle[0] > IphiMax) ) continue; + } + + if( avgLCSCEle[0] < t1 ) continue; + if( avgLCSCEle[0] > t2 ) continue; + + if( avgLCSCEle[0] <= 0. ) continue; + + isSavedEntries.at(ientry) = true; + + + // fill sorter + Sorter dummy; + dummy.time = avgLCSCEle[0]; + dummy.entry = ientry; + sortedEntries.push_back(dummy); + + ++nSavePts; + } + + // sort events + std::sort(sortedEntries.begin(),sortedEntries.end(),Sorter()); + std::cout << "Data sorted in " << EBEE << " - " << nSavePts << " events" << std::endl; + + std::map antiMap; + for(unsigned int iSaved = 0; iSaved < sortedEntries.size(); ++iSaved) + antiMap[sortedEntries.at(iSaved).entry] = iSaved; + + + //--------------------- + // Loop and define bins + + // "wide" bins - find events with time separation bigger than 1 day + int nWideBins = 1; + std::vector wideBinEntryMax; + int timeStampOld = -1; + + // TEventList* evlist=new TEventList("events"); + // data->Draw(">>events","","goff"); + // TEventList* evlist = (TEventList*) gDirectory->Get("events"); + + wideBinEntryMax.push_back(0); + + for(int iSaved = 0; iSaved < nSavePts; ++iSaved) + { + if( iSaved%10000 == 0 ) std::cout << "reading saved entry " << iSaved << "\r" << std::endl;//std::flush; + data->GetEntry(sortedEntries[iSaved].entry); + // data->GetEntry(evlist->GetEntry(sortedEntries[iSaved].entry)); + + if( iSaved == 0 ) + { + timeStampOld = avgLCSCEle[0]; + continue; + } + + if( (avgLCSCEle[0]-timeStampOld)/3600. > timeLapse ) + { + ++nWideBins; + wideBinEntryMax.push_back(iSaved-1); + } + + timeStampOld = avgLCSCEle[0]; + } + std::cout << std::endl; + wideBinEntryMax.push_back(nSavePts); + + + // bins with approximatively evtsPerPoint events per bin + int nBins = 0; + std::vector binEntryMax; + + binEntryMax.push_back(0); + for(int wideBin = 0; wideBin < nWideBins; ++wideBin) + { + int nTempBins = std::max(1,int( (wideBinEntryMax.at(wideBin+1)-wideBinEntryMax.at(wideBin))/evtsPerPoint )); + int nTempBinEntries = int( (wideBinEntryMax.at(wideBin+1)-wideBinEntryMax.at(wideBin))/nTempBins ); + + for(int tempBin = 0; tempBin < nTempBins; ++tempBin) + { + ++nBins; + if( tempBin < nTempBins - 1 ) + binEntryMax.push_back( wideBinEntryMax.at(wideBin) + (tempBin+1)*nTempBinEntries ); + else + binEntryMax.push_back( wideBinEntryMax.at(wideBin+1) ); + } + } + + std::cout << "nBins = " << nBins << std::endl; + //for(int bin = 0; bin < nBins; ++bin) + // std::cout << "bin: " << bin + // << " entry min: " << setw(6) << binEntryMax.at(bin) + // << " entry max: " << setw(6) << binEntryMax.at(bin+1) + // << " events: " << setw(6) << binEntryMax.at(bin+1)-binEntryMax.at(bin) + // << std::endl; + + + + + + + //--------------------- + // histogram definition + + TH1F* h_scOccupancy_eta = new TH1F("h_scOccupancy_eta","", 298, -2.6, 2.6); + TH1F* h_scOccupancy_phi = new TH1F("h_scOccupancy_phi","", 363, -3.1765, 3.159); + SetHistoStyle(h_scOccupancy_eta); + SetHistoStyle(h_scOccupancy_phi); + + TH2F* h_seedOccupancy_EB = new TH2F("h_seedOccupancy_EB","", 171, -86., 85., 361, 0.,361.); + TH2F* h_seedOccupancy_EEp = new TH2F("h_seedOccupancy_EEp","", 101, 0.,101., 100, 0.,101.); + TH2F* h_seedOccupancy_EEm = new TH2F("h_seedOccupancy_EEm","", 101, 0.,101., 100, 0.,101.); + SetHistoStyle(h_seedOccupancy_EB); + SetHistoStyle(h_seedOccupancy_EEp); + SetHistoStyle(h_seedOccupancy_EEm); + + TH1F* h_EoP_spread = new TH1F("h_EoP_spread","",100,yMIN,yMAX); + TH1F* h_EoC_spread = new TH1F("h_EoC_spread","",100,yMIN,yMAX); + TH1F* h_EoP_spread_run = new TH1F("h_EoP_spread_run","",100,yMIN,yMAX); + TH1F* h_EoC_spread_run = new TH1F("h_EoC_spread_run","",100,yMIN,yMAX); + SetHistoStyle(h_EoP_spread,"EoP"); + SetHistoStyle(h_EoC_spread,"EoC"); + SetHistoStyle(h_EoP_spread_run,"EoP"); + SetHistoStyle(h_EoC_spread_run,"EoC"); + + TH1F* h_EoP_chi2 = new TH1F("h_EoP_chi2","",50,0.,5.); + TH1F* h_EoC_chi2 = new TH1F("h_EoC_chi2","",50,0.,5.); + SetHistoStyle(h_EoP_chi2,"EoP"); + SetHistoStyle(h_EoC_chi2,"EoC"); + + TH1F** h_EoP = new TH1F*[nBins]; + TH1F** h_EoC = new TH1F*[nBins]; + TH1F** h_Las = new TH1F*[nBins]; + TH1F** h_Tsp = new TH1F*[nBins]; + TH1F** h_Cvl = new TH1F*[nBins]; + + for(int i = 0; i < nBins; ++i) + { + char histoName[80]; + + sprintf(histoName, "EoP_%d", i); + h_EoP[i] = new TH1F(histoName, histoName, 2000, 0., 5.); + SetHistoStyle(h_EoP[i],"EoP"); + + sprintf(histoName, "EoC_%d", i); + h_EoC[i] = new TH1F(histoName, histoName, 2000, 0., 5.); + SetHistoStyle(h_EoC[i],"EoC"); + + sprintf(histoName, "Las_%d", i); + h_Las[i] = new TH1F(histoName, histoName, 500, 0.5, 1.5); + + sprintf(histoName, "Tsp_%d", i); + h_Tsp[i] = new TH1F(histoName, histoName, 500, 0.5, 1.5); + + } + + + // function definition + TF1** f_EoP = new TF1*[nBins]; + TF1** f_EoC = new TF1*[nBins]; + + + // graphs definition + TGraphAsymmErrors* g_fit = new TGraphAsymmErrors(); + TGraphAsymmErrors* g_c_fit = new TGraphAsymmErrors(); + + TGraphAsymmErrors* g_fit_run = new TGraphAsymmErrors(); + TGraphAsymmErrors* g_c_fit_run = new TGraphAsymmErrors(); + + TGraph* g_las = new TGraph(); + + TGraphErrors* g_LT = new TGraphErrors(); + + g_fit->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00"); + g_fit->GetXaxis()->SetTimeDisplay(1); + g_c_fit->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00"); + g_c_fit->GetXaxis()->SetTimeDisplay(1); + g_las->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00"); + g_las->GetXaxis()->SetTimeDisplay(1); + g_LT->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00"); + g_LT->GetXaxis()->SetTimeDisplay(1); + + + + + + + //------------------------------------ + // loop on the saved and sorted events + + std::cout << std::endl; + std::cout << "***** Fill and fit histograms *****" << std::endl; + + std::vector Entries(nBins); + std::vector AveTime(nBins); + std::vector MinTime(nBins); + std::vector MaxTime(nBins); + std::vector AveRun(nBins); + std::vector MinRun(nBins); + std::vector MaxRun(nBins); + std::vector AveLT(nBins); + std::vector AveLT2(nBins); + + int iSaved = -1; + for(int ientry = 0; ientry < nEntries; ++ientry) + { + if( (ientry%100000 == 0) ) std::cout << "reading entry " << ientry << "\r" << std::endl;//std::flush; + + if( isSavedEntries.at(ientry) == false ) continue; + + ++iSaved; + + int iSaved = antiMap[ientry]; + int bin = -1; + for(bin = 0; bin < nBins; ++bin) + if( iSaved >= binEntryMax.at(bin) && iSaved < binEntryMax.at(bin+1) ) + break; + + //std::cout << "bin = " << bin << " iSaved = "<< iSaved << std::endl; + data->GetEntry(ientry); + + + + Entries[bin] += 1; + + if( iSaved == binEntryMax.at(bin)+1 ) MinTime[bin] = avgLCSCEle[0]; + if( iSaved == binEntryMax.at(bin+1)-1 ) MaxTime[bin] = avgLCSCEle[0]; + AveTime[bin] += avgLCSCEle[0]; + + if( iSaved == binEntryMax.at(bin)+1 ) MinRun[bin] = runNumber; + if( iSaved == binEntryMax.at(bin+1)-1 ) MaxRun[bin] = runNumber; + AveRun[bin] += runNumber; + + // float LT = (-1. / seedLaserAlphaSCEle1 * log(avgLCSCEle[0])); + float LT = 1.; + AveLT[bin] += LT; + AveLT2[bin] += LT*LT; + + // PU correction + float PUCorr = (p0 + p1*nPU); + + // fill the histograms + (h_EoP[bin]) -> Fill( (energySCEle[0]-esEnergySCEle[0])/(pAtVtxGsfEle[0]-esEnergySCEle[0]) / avgLCSCEle[0] / PUCorr); + (h_EoC[bin]) -> Fill( (energySCEle[0]-esEnergySCEle[0])/(pAtVtxGsfEle[0]-esEnergySCEle[0]) / PUCorr ); + + (h_Las[bin]) -> Fill(avgLCSCEle[0]); + (h_Tsp[bin]) -> Fill(1./avgLCSCEle[0]); + + h_scOccupancy_eta -> Fill(etaSCEle[0]); + h_scOccupancy_phi -> Fill(phiSCEle[0]); + if(fabs(etaSCEle[0])<1.449) + h_seedOccupancy_EB -> Fill(seedXSCEle[0],seedYSCEle[0]); + else if(etaSCEle[0]>1.449) + h_seedOccupancy_EEp -> Fill(seedXSCEle[0],seedYSCEle[0]); + else if(etaSCEle[0]<-1.449) + h_seedOccupancy_EEm -> Fill(seedXSCEle[0],seedYSCEle[0]); + } + + for(int bin = 0; bin < nBins; ++bin) + { + AveTime[bin] = 1. * AveTime[bin] / (binEntryMax.at(bin+1)-binEntryMax.at(bin)); + AveRun[bin] = 1. * AveRun[bin] / (binEntryMax.at(bin+1)-binEntryMax.at(bin)); + AveLT[bin] = 1. * AveLT[bin] / (binEntryMax.at(bin+1)-binEntryMax.at(bin)); + AveLT2[bin] = 1. * AveLT2[bin] / (binEntryMax.at(bin+1)-binEntryMax.at(bin)); + //std::cout << date << " " << AveTime[i] << " " << MinTime[i] << " " << MaxTime[i] << std::endl; + } + + + + + + + int rebin = 2; + if( strcmp(EBEE.c_str(),"EE") == 0 ) rebin *= 2; + + h_template -> Rebin(rebin); + + + + float EoP_scale = 0.; + float EoP_err = 0.; + int EoP_nActiveBins = 0; + + float EoC_scale = 0.; + float EoC_err = 0.; + int EoC_nActiveBins = 0; + + float LCInv_scale = 0; + + std::vector validBins; + for(int i = 0; i < nBins; ++i) + { + bool isValid = true; + + h_EoP[i] -> Rebin(rebin); + h_EoC[i] -> Rebin(rebin); + + + + //------------------------------------ + // Fill the graph for uncorrected data + + // define the fitting function + // N.B. [0] * ( [1] * f( [1]*(x-[2]) ) ) + + //o -> cd(); + char convolutionName[50]; + sprintf(convolutionName,"h_convolution_%d",i); + //h_Cvl[i] = ConvoluteTemplate(std::string(convolutionName),h_template,h_Las[i],32768,-5.,5.); + h_Cvl[i] = MellinConvolution(std::string(convolutionName),h_template,h_Tsp[i]); + + histoFunc* templateHistoFunc = new histoFunc(h_template); + histoFunc* templateConvolutedHistoFunc = new histoFunc(h_Cvl[i]); + char funcName[50]; + + sprintf(funcName,"f_EoP_%d",i); + + if( strcmp(EBEE.c_str(),"EB") == 0 ) + f_EoP[i] = new TF1(funcName, templateConvolutedHistoFunc, 0.8*(h_Tsp[i]->GetMean()), 1.4*(h_Tsp[i]->GetMean()), 3, "histoFunc"); + else + f_EoP[i] = new TF1(funcName, templateConvolutedHistoFunc, 0.75*(h_Tsp[i]->GetMean()), 1.5*(h_Tsp[i]->GetMean()), 3, "histoFunc"); + + f_EoP[i] -> SetParName(0,"Norm"); + f_EoP[i] -> SetParName(1,"Scale factor"); + f_EoP[i] -> SetLineWidth(1); + f_EoP[i] -> SetNpx(10000); + + double xNorm = h_EoP[i]->GetEntries()/h_template->GetEntries() * + h_EoP[i]->GetBinWidth(1)/h_template->GetBinWidth(1); + + f_EoP[i] -> FixParameter(0, xNorm); + f_EoP[i] -> SetParameter(1, 1.); + f_EoP[i] -> FixParameter(2, 0.); + f_EoP[i] -> SetLineColor(kRed+2); + + int fStatus = 0; + int nTrials = 0; + TFitResultPtr rp; + + rp = h_EoP[i] -> Fit(funcName, "ERLS+"); + while( (fStatus != 0) && (nTrials < 10) ) + { + rp = h_EoP[i] -> Fit(funcName, "ERLS+"); + fStatus = rp; + if(fStatus == 0) break; + ++nTrials; + } + + // fill the graph + double eee = f_EoP[i]->GetParError(1); + //float k = f_EoP[i]->GetParameter(1); + float k = f_EoP[i]->GetParameter(1) / h_Tsp[i]->GetMean(); //needed when using mellin's convolution + + /* + std::cout << i <<"--nocorr---- "<< 1./k << std::endl; + std::cout <<" condizione 1: " << h_EoP[i]->GetEntries() << " fStatus: " << fStatus << " eee: " << eee << "con eee che ci piace essere maggiore di : " << 0.05*h_template->GetRMS()/sqrt(evtsPerPoint) << std::endl ; + getchar(); + */ + + + // if( (h_EoP[i]->GetEntries() > 3) && (fStatus == 0) && (eee > 0.05*h_template->GetRMS()/sqrt(evtsPerPoint)) ) + if( (h_EoP[i]->GetEntries() > 500) && (fStatus == 0) ) + { + float date = (float)AveTime[i]; + // float dLow = (float)(AveTime[i]-MinTime[i]); + //float dHig = (float)(MaxTime[i]-AveTime[i]); + float run = (float)AveRun[i]; + float rLow = (float)(AveRun[i]-MinRun[i]); + float rHig = (float)(MaxRun[i]-AveRun[i]); + + g_fit -> SetPoint(i, date , 1./k); + // g_fit -> SetPointError(i, dLow , dHig, eee/k/k, eee/k/k); + g_fit -> SetPointError(i, 0. , 0., eee/k/k, eee/k/k); + + g_fit_run -> SetPoint(i, run , 1./k); + g_fit_run -> SetPointError(i, rLow , rHig, eee/k/k, eee/k/k); + + std::cout <<"************-------------------*****************" < Fill(f_EoP[i]->GetChisquare()/f_EoP[i]->GetNDF()); + + EoP_scale += 1./k; + EoP_err += eee/k/k; + ++EoP_nActiveBins; + } + else + { + std::cout << "Fitting uncorrected time bin: " << i << " Fail status: " << fStatus << " sigma: " << eee << std::endl; + isValid = false; + } + + //---------------------------------- + // Fill the graph for corrected data + + // define the fitting function + // N.B. [0] * ( [1] * f( [1]*(x-[2]) ) ) + + sprintf(funcName,"f_EoC_%d",i); + if( strcmp(EBEE.c_str(),"EB") == 0 ) + f_EoC[i] = new TF1(funcName, templateHistoFunc, 0.8, 1.4, 3, "histoFunc"); + else + f_EoC[i] = new TF1(funcName, templateHistoFunc, 0.75, 1.5, 3, "histoFunc"); + f_EoC[i] -> SetParName(0,"Norm"); + f_EoC[i] -> SetParName(1,"Scale factor"); + f_EoC[i] -> SetLineWidth(1); + f_EoC[i] -> SetNpx(10000); + + xNorm = h_EoC[i]->GetEntries()/h_template->GetEntries() * + h_EoC[i]->GetBinWidth(1)/h_template->GetBinWidth(1); + + f_EoC[i] -> FixParameter(0, xNorm); + f_EoC[i] -> SetParameter(1, 0.99); + f_EoC[i] -> FixParameter(2, 0.); + f_EoC[i] -> SetLineColor(kGreen+2); + + + rp = h_EoC[i] -> Fit(funcName, "ERLS+"); + fStatus = rp; + nTrials = 0; + while( (fStatus != 0) && (nTrials < 10) ) + { + rp = h_EoC[i] -> Fit(funcName, "ERLS+"); + fStatus = rp; + if(fStatus == 0) break; + ++nTrials; + } + + + // fill the graph + k = f_EoC[i]->GetParameter(1); + eee = f_EoC[i]->GetParError(1); + + /* std::cout << i <<"--corr---- "<< 1./k << std::endl; + std::cout <<" condizione 1: " << h_EoP[i]->GetEntries() << " fStatus: " << fStatus << " eee: " << eee << "con eee che ci piace essere maggiore di : " << 0.05*h_template->GetRMS()/sqrt(evtsPerPoint) << std::endl ; + getchar(); + */ + + + if( (h_EoC[i]->GetEntries() > 500) && (fStatus == 0) ) + // if( (h_EoC[i]->GetEntries() > 10) && (fStatus == 0) && (eee > 0.05*h_template->GetRMS()/sqrt(evtsPerPoint)) ) + { + float date = (float)AveTime[i]; + // float dLow = (float)(AveTime[i]-MinTime[i]); + //float dHig = (float)(MaxTime[i]-AveTime[i]); + float run = (float)AveRun[i]; + float rLow = (float)(AveRun[i]-MinRun[i]); + float rHig = (float)(MaxRun[i]-AveRun[i]); + + g_c_fit -> SetPoint(i, date , 1./k); + // g_c_fit -> SetPointError(i, dLow , dHig , eee/k/k, eee/k/k); + g_c_fit -> SetPointError(i, 0. , 0. , eee/k/k, eee/k/k); + + g_c_fit_run -> SetPoint(i, run , 1./k); + g_c_fit_run -> SetPointError(i, rLow , rHig, eee/k/k, eee/k/k); + std::cout <<"************-------------------*****************" < Fill(f_EoC[i]->GetChisquare()/f_EoP[i]->GetNDF()); + + EoC_scale += 1./k; + EoC_err += eee/k/k; + ++EoC_nActiveBins; + } + else + { + std::cout << "Fitting corrected time bin: " << i << " Fail status: " << fStatus << " sigma: " << eee << std::endl; + isValid = false; + } + + if( isValid == true ) validBins.push_back(i); + } + + EoP_scale /= EoP_nActiveBins; + EoP_err /= EoP_nActiveBins; + + EoC_scale /= EoC_nActiveBins; + EoC_err /= EoC_nActiveBins; + + + + + + + //---------------------------------------- + // Fill the graph for avg laser correction + + //fede + for(unsigned int itr = 0; itr < validBins.size(); ++itr) + { + int i = validBins.at(itr); + g_las -> SetPoint(itr, (float)AveTime[i], h_Tsp[i]->GetMean()); + g_LT -> SetPoint(itr, (float)AveTime[i], AveLT[i] ); + g_LT -> SetPointError(itr, 0., sqrt(AveLT2[i]-AveLT[i]*AveLT[i]) / sqrt(Entries[i]) ); + + LCInv_scale += h_Tsp[i]->GetMean(); + } + + LCInv_scale /= validBins.size(); + + + + + + + //--------------- + // Rescale graphs + + float yscale = 1.; + //float yscale = 1./EoC_scale; + + for(unsigned int itr = 0; itr < validBins.size(); ++itr) + { + double x,y; + g_fit -> GetPoint(itr,x,y); + g_fit -> SetPoint(itr,x,y*yscale); + if ( (x > t1) && (x < t2) ) h_EoP_spread -> Fill(y*yscale); + + g_c_fit -> GetPoint(itr,x,y); + g_c_fit -> SetPoint(itr,x,y*yscale); + if ( (x > t1) && (x < t2) ) h_EoC_spread -> Fill(y*yscale); + + g_fit_run -> GetPoint(itr,x,y); + g_fit_run -> SetPoint(itr,x,y*yscale); + if ( (x > t1) && (x < t2) ) h_EoP_spread_run -> Fill(y*yscale); + + g_c_fit_run -> GetPoint(itr,x,y); + g_c_fit_run -> SetPoint(itr,x,y*yscale); + if ( (x > t1) && (x < t2) ) h_EoC_spread_run -> Fill(y*yscale); + + g_las -> GetPoint(itr,x,y); + g_las -> SetPoint(itr,x,y*yscale*EoP_scale/LCInv_scale); + } + TF1 EoC_pol0("EoC_pol0","pol0",t1,t2); + EoC_pol0.SetLineColor(kGreen+2); + EoC_pol0.SetLineWidth(2); + EoC_pol0.SetLineStyle(2); + g_c_fit -> Fit("EoC_pol0","QNR"); + + + + + + + + + //---------------------------- + // Print out global quantities + + std::cout << std::endl; + std::cout << "***** Mean scales and errors *****" << std::endl; + std::cout << std::fixed; + std::cout << std::setprecision(4); + std::cout << "Mean EoP scale: " << std::setw(6) << EoP_scale << " mean EoP error: " << std::setw(8) << EoP_err << std::endl; + std::cout << "Mean EoC scale: " << std::setw(6) << EoC_scale << " mean EoC error: " << std::setw(8) << EoC_err << std::endl; + std::cout << "Mean 1/LC scale: " << std::setw(6) << LCInv_scale << std::endl; + + + + + + + //----------------- + // Occupancy plots + //----------------- + + TCanvas* c_scOccupancy = new TCanvas("c_scOccupancy","SC occupancy",0,0,1000,500); + c_scOccupancy -> Divide(2,1); + + c_scOccupancy -> cd(1); + h_scOccupancy_eta -> GetXaxis() -> SetTitle("sc #eta"); + h_scOccupancy_eta -> GetYaxis() -> SetTitle("events"); + h_scOccupancy_eta -> Draw(); + + c_scOccupancy -> cd(2); + h_scOccupancy_phi -> GetXaxis() -> SetTitle("sc #phi"); + h_scOccupancy_phi -> GetYaxis() -> SetTitle("events"); + h_scOccupancy_phi -> Draw(); + + TCanvas* c_seedOccupancy = new TCanvas("c_seedOccupancy","seed occupancy",0,0,1500,500); + c_seedOccupancy -> Divide(3,1); + + c_seedOccupancy -> cd(1); + h_seedOccupancy_EB -> GetXaxis() -> SetTitle("seed i#eta"); + h_seedOccupancy_EB -> GetYaxis() -> SetTitle("seed i#phi"); + h_seedOccupancy_EB -> Draw("COLZ"); + + c_seedOccupancy -> cd(2); + h_seedOccupancy_EEp -> GetXaxis() -> SetTitle("seed ix"); + h_seedOccupancy_EEp -> GetYaxis() -> SetTitle("seed iy"); + h_seedOccupancy_EEp -> Draw("COLZ"); + + c_seedOccupancy -> cd(3); + h_seedOccupancy_EEm -> GetXaxis() -> SetTitle("seed ix"); + h_seedOccupancy_EEm -> GetYaxis() -> SetTitle("seed iy"); + h_seedOccupancy_EEm -> Draw("COLZ"); + + + + //----------- + // Chi2 plots + //----------- + + TCanvas* c_chi2 = new TCanvas("c_chi2","fit chi2",0,0,500,500); + c_chi2 -> cd(); + + h_EoC_chi2 -> GetXaxis() -> SetTitle("#chi^{2}/N_{dof}"); + h_EoC_chi2 -> Draw(""); + gPad -> Update(); + + TPaveStats* s_EoC = new TPaveStats; + s_EoC = (TPaveStats*)(h_EoC_chi2->GetListOfFunctions()->FindObject("stats")); + s_EoC -> SetStatFormat("1.4g"); + s_EoC -> SetTextColor(kGreen+2); + s_EoC->SetY1NDC(0.59); + s_EoC->SetY2NDC(0.79); + s_EoC -> Draw("sames"); + gPad -> Update(); + + h_EoP_chi2 -> GetXaxis() -> SetTitle("#chi^{2}/N_{dof}"); + h_EoP_chi2 -> Draw("sames"); + gPad -> Update(); + + TPaveStats* s_EoP = new TPaveStats; + s_EoP = (TPaveStats*)(h_EoP_chi2->GetListOfFunctions()->FindObject("stats")); + s_EoP -> SetStatFormat("1.4g"); + s_EoP -> SetTextColor(kRed+2); + s_EoP->SetY1NDC(0.79); + s_EoP->SetY2NDC(0.99); + s_EoP -> Draw("sames"); + gPad -> Update(); + + //ciao + //------------------- + // RMS vs Num evts -BARREL + //------------------- + double x[13]={2.,4.,6.,8.,10.,12.,14.,16.,18.,20.,22.,24.,30.}; + double y[13]={0.001049,0.001114,0.0009367,0.0008480,0.0007669,0.0007892,0.0006699,0.0006473,0.0006235,0.0005903,0.0005815,0.0005459,0.0005506}; + + TCanvas* RMSeb = new TCanvas("plot", "plot",0,0,500,500); + TGraph* gRMSeb = new TGraph(13,x,y); + + gRMSeb->Draw("APC"); + gRMSeb -> SetMarkerColor(38); + gRMSeb -> SetLineColor(38); + gRMSeb->GetXaxis()->SetTitle("Number of Events - Barrel"); + gRMSeb->GetYaxis()->SetTitle("RMS"); + + RMSeb -> Print((folderName+"/"+folderName+"_RMSeb"+".png").c_str(),"png"); + RMSeb -> Print((folderName+"/"+folderName+"_RMSeb"+".pdf").c_str(),"pdf"); + + //------------------- + // RMS vs Num evts -ENDCAP + //------------------- + + double xx[11]={2.,4.,6.,8.,10.,12.,14.,16.,18.,20.,22.}; + double yy[11]={0.007234,0.005759,0.004174,0.004255,0.003833,0.004037,0.003912,0.004251,0.003598,0.004067,0.004138}; + + TCanvas* RMSee = new TCanvas("plot", "plot",0,0,500,500); + TGraph* gRMSee = new TGraph(11,xx,yy); + + gRMSee->Draw("APC"); + gRMSee -> SetMarkerColor(38); + gRMSee -> SetLineColor(38); + gRMSee->GetXaxis()->SetTitle("Number of Events - Endcap"); + gRMSee->GetYaxis()->SetTitle("RMS"); + + + RMSee -> Print((folderName+"/"+folderName+"_RMSee"+".png").c_str(),"png"); + RMSee -> Print((folderName+"/"+folderName+"_RMSee"+".pdf").c_str(),"pdf"); + + + //ciao + //------------------- + // histos + //------------------- + + + /* + for ( int i = 0; i < nBins; ++i) + { + + TCanvas* histoEoP = new TCanvas("histo","histo",0,0,500,500); + histoEoP -> cd(); + + h_EoP[i] -> Draw(); + f_EoP[i] -> SetLineWidth(2); + f_EoP[i] -> SetLineColor(4); + f_EoP[i] -> Draw("same"); + // histoEoP -> Update(); + + histoEoP -> Print((folderName+"/"+folderName+"_histoEoP"+std::to_string(i)+".png").c_str(),"png"); + histoEoP -> Print((folderName+"/"+folderName+"_histoEoP"+std::to_string(i)+".pdf").c_str(),"pdf"); + + + TCanvas* histoEoC = new TCanvas("histo","histo",0,0,500,500); + histoEoC -> cd(); + + h_EoC[i] -> Draw(); + f_EoC[i] -> SetLineWidth(2); + f_EoC[i] -> SetLineColor(4); + f_EoC[i] -> Draw("same"); + //histoEoC -> Update(); + + histoEoC -> Print((folderName+"/"+folderName+"_histoEoC"+to_string(i)+".png").c_str(),"png"); + histoEoC -> Print((folderName+"/"+folderName+"_histoEoC"+to_string(i)+".pdf").c_str(),"pdf"); + + } + */ + + //------------------- + // Final Plot vs date + //------------------- + + TCanvas* cplot = new TCanvas("cplot", "history plot vs date",100,100,1000,500); + cplot->cd(); + + TPad *cLeft = new TPad("pad_0","pad_0",0.00,0.00,0.75,1.00); + TPad *cRight = new TPad("pad_1","pad_1",0.75,0.00,1.00,1.00); + + cLeft->SetLeftMargin(0.15); + cLeft->SetRightMargin(0.025); + cRight->SetLeftMargin(0.025); + + cLeft->Draw(); + cRight->Draw(); + + float tYoffset = 1.0; + float labSize = 0.05; + float labSize2 = 0.06; + + cLeft->cd(); + + cLeft->SetGridx(); + cLeft->SetGridy(); + + TH1F *hPad = (TH1F*)gPad->DrawFrame(t1,0.9,t2,1.05); + + //hPad->GetXaxis()->SetLimits(t3,t2); + hPad->GetXaxis()->SetRangeUser(t1,t2); + hPad->GetXaxis()->SetTitle("LC value"); + // hPad->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00"); + //hPad->GetXaxis()->SetTimeDisplay(1); + //hPad->GetXaxis() -> SetRangeUser(MinTime[0]-43200,MaxTime[nBins-1]+43200); + //hPad->GetXaxis()->SetTitle("date (day/month)"); + //ciao + //hPad->GetXaxis()->SetLabelSize(0.025); + + if( strcmp(EBEE.c_str(),"EB") == 0 ) + hPad->GetYaxis()->SetTitle("Relative E/p scale"); + else + hPad->GetYaxis()->SetTitle("Relative E/p scale"); + hPad->GetYaxis()->SetTitleOffset(tYoffset); + hPad->GetXaxis()->SetTitleOffset(0.8); + hPad->GetXaxis()->SetLabelSize(0.03); + hPad->GetXaxis()->SetTitleSize(labSize2); + hPad->GetYaxis()->SetLabelSize(labSize); + hPad->GetYaxis()->SetTitleSize(labSize2); + hPad -> SetMinimum(yMIN); + hPad -> SetMaximum(yMAX); + + // draw history plot + g_fit -> SetMarkerStyle(24); + g_fit -> SetMarkerSize(0.7); + g_fit -> SetMarkerColor(kRed+2); + g_fit -> SetLineColor(kRed+2); + g_fit -> Draw("P"); + g_c_fit -> SetMarkerStyle(20); + g_c_fit -> SetMarkerColor(kGreen+2); + g_c_fit -> SetLineColor(kGreen+2); + g_c_fit -> SetMarkerSize(0.7); + g_c_fit -> Draw("EP,same"); + g_las -> SetLineColor(kAzure-2); + g_las -> SetLineWidth(2); + // g_las -> Draw("L,same"); + + TLegend* legend = new TLegend(0.60,0.78,0.90,0.94); + legend -> SetLineColor(kWhite); + legend -> SetLineWidth(0); + legend -> SetFillColor(kWhite); + legend -> SetFillStyle(0); + legend -> SetTextFont(42); + legend -> SetTextSize(0.04); + legend -> AddEntry(g_c_fit,"with LM correction","PL"); + legend -> AddEntry(g_fit, "without LM correction","PL"); + // legend -> AddEntry(g_las, "1 / LM correction","L"); + legend -> Draw("same"); + + char latexBuffer[250]; + + sprintf(latexBuffer,"CMS 2016 Preliminary"); + TLatex* latex = new TLatex(0.18,0.89,latexBuffer); + latex -> SetNDC(); + latex -> SetTextFont(62); + latex -> SetTextSize(0.05); + latex -> Draw("same"); + + //sprintf(latexBuffer,"#sqrt{s} = 8 TeV L = 3.95 fb^{-1}"); + sprintf(latexBuffer,"#sqrt{s} = 13 TeV, L =%s fb^{-1} ", LUMI.c_str()); + + // sprintf(latexBuffer, LUMI.c_str()); + TLatex* latex2 = new TLatex(0.18,0.84,latexBuffer); + latex2 -> SetNDC(); + latex2 -> SetTextFont(42); + latex2 -> SetTextSize(0.05); + latex2 -> Draw("same"); + + if( strcmp(EBEE.c_str(),"EB") == 0 || strcmp(EBEE.c_str(),"EB_0_1") == 0 || strcmp(EBEE.c_str(),"EB_1_1479") == 0) + sprintf(latexBuffer,"ECAL Barrel"); + else + sprintf(latexBuffer,"ECAL Endcap"); + TLatex* latex3 = new TLatex(0.18,0.19,latexBuffer); + latex3 -> SetNDC(); + latex3 -> SetTextFont(42); + latex3 -> SetTextSize(0.05); + latex3 -> Draw("same"); + + //sprintf(latexBuffer,"%.2E events",1.*nSavePts); + //TLatex* latex4 = new TLatex(0.18,0.24,latexBuffer); + //latex4 -> SetNDC(); + //latex4 -> SetTextFont(42); + //latex4 -> SetTextSize(0.04); + //latex4 -> Draw("same"); + // + //sprintf(latexBuffer,"%d events/bin - %d bins",evtsPerPoint,nBins); + //TLatex* latex5 = new TLatex(0.18,0.19,latexBuffer); + //latex5 -> SetNDC(); + //latex5 -> SetTextFont(42); + //latex5 -> SetTextSize(0.04); + //latex5 -> Draw("same"); + + + cRight -> cd(); + + TPaveStats* s_EoP_spread = new TPaveStats(); + TPaveStats* s_EoC_spread = new TPaveStats(); + + + h_EoC_spread -> SetFillStyle(3001); + h_EoC_spread -> SetFillColor(kGreen+2); + h_EoC_spread->GetYaxis()->SetLabelSize(0.09); + h_EoC_spread->GetYaxis()->SetLabelOffset(-0.03); + h_EoC_spread->GetYaxis()->SetTitleSize(0.08); + h_EoC_spread->GetYaxis()->SetNdivisions(505); + h_EoC_spread->GetXaxis()->SetLabelOffset(1000); + + h_EoC_spread -> Draw("hbar"); + gPad -> Update(); + + s_EoC_spread = (TPaveStats*)(h_EoC_spread->GetListOfFunctions()->FindObject("stats")); + s_EoC_spread -> SetStatFormat("1.4g"); + s_EoC_spread->SetX1NDC(0.06); //new x start position + s_EoC_spread->SetX2NDC(0.71); //new x end position + s_EoC_spread->SetY1NDC(0.43); //new x start position + s_EoC_spread->SetY2NDC(0.34); //new x end position + s_EoC_spread -> SetOptStat(1100); + s_EoC_spread ->SetTextColor(kGreen+2); + s_EoC_spread ->SetTextSize(0.08); + s_EoC_spread -> Draw("sames"); + + + h_EoP_spread -> SetFillStyle(3001); + h_EoP_spread -> SetFillColor(kRed+2); + h_EoP_spread -> Draw("hbarsames"); + gPad -> Update(); + s_EoP_spread = (TPaveStats*)(h_EoP_spread->GetListOfFunctions()->FindObject("stats")); + s_EoP_spread -> SetStatFormat("1.4g"); + s_EoP_spread->SetX1NDC(0.06); //new x start position + s_EoP_spread->SetX2NDC(0.71); //new x end position + s_EoP_spread->SetY1NDC(0.33); //new x start position + s_EoP_spread->SetY2NDC(0.24); //new x end position + s_EoP_spread ->SetOptStat(1100); + s_EoP_spread ->SetTextColor(kRed+2); + s_EoP_spread ->SetTextSize(0.08); + s_EoP_spread -> Draw("sames"); + + /* + h_EoP_spread -> SetFillStyle(3001); + h_EoP_spread -> SetFillColor(kRed+2); + h_EoP_spread -> Draw("hbarsame"); + gPad -> Update(); + */ + + + + //------------------ + // Final plot vs run + //------------------ + + TCanvas* cplot_run = new TCanvas("cplot_run", "history plot vs run",100,100,1000,500); + cplot_run->cd(); + + cLeft = new TPad("pad_0_run","pad_0_run",0.00,0.00,0.75,1.00); + cRight = new TPad("pad_1_run","pad_1_run",0.75,0.00,1.00,1.00); + + cLeft->SetLeftMargin(0.15); + cLeft->SetRightMargin(0.025); + cRight->SetLeftMargin(0.025); + + cLeft->Draw(); + cRight->Draw(); + + tYoffset = 1.5; + labSize = 0.04; + labSize2 = 0.07; + + cLeft->cd(); + + cLeft->SetGridx(); + cLeft->SetGridy(); + + hPad = (TH1F*)gPad->DrawFrame(MinRun[0]-1000,0.9,MaxRun[nBins-1]+1000,1.05); + hPad->GetXaxis()->SetTitle("run"); + if( strcmp(EBEE.c_str(),"EB") == 0 ) + hPad->GetYaxis()->SetTitle("Relative E/p scale"); + else + hPad->GetYaxis()->SetTitle("Relative E/p scale"); + hPad->GetYaxis()->SetTitleOffset(tYoffset); + hPad->GetYaxis()->SetTitleOffset(0.8); + hPad->GetXaxis()->SetLabelSize(labSize); + hPad->GetXaxis()->SetTitleSize(labSize); + hPad->GetYaxis()->SetLabelSize(labSize); + hPad->GetYaxis()->SetTitleSize(labSize); + hPad -> SetMinimum(yMIN); + hPad -> SetMaximum(yMAX); + + // draw history plot + g_fit_run -> SetMarkerStyle(20); + g_fit_run -> SetMarkerSize(0.7); + g_fit_run -> SetMarkerColor(kRed+2); + g_fit_run -> SetLineColor(kRed+2); + g_fit_run -> Draw("P"); + g_c_fit_run -> SetMarkerStyle(20); + g_c_fit_run -> SetMarkerColor(kGreen+2); + g_c_fit_run -> SetLineColor(kGreen+2); + g_c_fit_run -> SetMarkerSize(0.7); + g_c_fit_run -> Draw("P,same"); + + + cRight -> cd(); + + s_EoP_spread = new TPaveStats(); + s_EoC_spread = new TPaveStats(); + + + h_EoC_spread_run -> SetFillStyle(3001); + h_EoC_spread_run -> SetFillColor(kGreen+2); + h_EoC_spread_run->GetYaxis()->SetLabelSize(labSize2); + h_EoC_spread_run->GetYaxis()->SetTitleSize(labSize2); + h_EoC_spread_run->GetYaxis()->SetNdivisions(505); + h_EoC_spread_run->GetYaxis()->SetLabelOffset(-0.02); + h_EoC_spread_run->GetXaxis()->SetLabelOffset(1000); + + h_EoC_spread_run -> Draw("hbar"); + gPad -> Update(); + + s_EoC_spread = (TPaveStats*)(h_EoC_spread_run->GetListOfFunctions()->FindObject("stats")); + s_EoC_spread ->SetTextColor(kGreen+2); + s_EoC_spread ->SetTextSize(0.06); + s_EoC_spread->SetX1NDC(0.49); //new x start position + s_EoC_spread->SetX2NDC(0.99); //new x end position + s_EoC_spread->SetY1NDC(0.475); //new x start position + s_EoC_spread->SetY2NDC(0.590); //new x end position + s_EoC_spread -> SetOptStat(1100); + s_EoC_spread -> Draw("sames"); + + h_EoP_spread_run -> SetFillStyle(3001); + h_EoP_spread_run -> SetFillColor(kRed+2); + h_EoP_spread_run -> Draw("hbarsames"); + gPad -> Update(); + + s_EoP_spread = (TPaveStats*)(h_EoP_spread_run->GetListOfFunctions()->FindObject("stats")); + s_EoP_spread->SetX1NDC(0.49); //new x start position + s_EoP_spread->SetX2NDC(0.99); //new x end position + s_EoP_spread->SetY1NDC(0.350); //new x start position + s_EoP_spread->SetY2NDC(0.475); //new x end position + s_EoP_spread ->SetOptStat(1100); + s_EoP_spread ->SetTextColor(kRed+2); + s_EoP_spread ->SetTextSize(0.06); + s_EoP_spread -> Draw("sames"); + + + + + c_chi2 -> Print((folderName+"/"+folderName+"_fitChi2.png").c_str(),"png"); + c_scOccupancy -> Print((folderName+"/"+folderName+"_scOccupancy.png").c_str(),"png"); + c_seedOccupancy -> Print((folderName+"/"+folderName+"_seedOccupancy.png").c_str(),"png"); + cplot -> Print((folderName+"/"+folderName+"_history_vsTime.png").c_str(),"png"); + cplot_run -> Print((folderName+"/"+folderName+"_history_vsRun.png").c_str(),"png"); + + c_chi2 -> Print((folderName+"/"+folderName+"_fitChi2.pdf").c_str(),"pdf"); + c_scOccupancy -> Print((folderName+"/"+folderName+"_scOccupancy.pdf").c_str(),"pdf"); + c_seedOccupancy -> Print((folderName+"/"+folderName+"_seedOccupancy.pdf").c_str(),"pdf"); + cplot -> Print((folderName+"/"+folderName+"_history_vsTime.pdf").c_str(),"pdf"); + cplot_run -> Print((folderName+"/"+folderName+"_history_vsRun.pdf").c_str(),"pdf"); + + cplot -> SaveAs((folderName+"/"+folderName+"_history_vsTime.C").c_str()); + cplot_run -> SaveAs((folderName+"/"+folderName+"_history_vsRun.C").c_str()); + + cplot -> SaveAs((folderName+"/"+folderName+"_history_vsTime.root").c_str()); + cplot_run -> SaveAs((folderName+"/"+folderName+"_history_vsRun.root").c_str()); + + + + o -> cd(); + + h_template -> Write(); + + h_scOccupancy_eta -> Write(); + h_scOccupancy_phi -> Write(); + h_seedOccupancy_EB -> Write(); + h_seedOccupancy_EEp -> Write(); + h_seedOccupancy_EEm -> Write(); + + g_fit -> Write("g_fit"); + g_c_fit -> Write("g_c_fit"); + g_fit_run -> Write("g_fit_run"); + g_c_fit_run -> Write("g_c_fit_run"); + g_las -> Write("g_las"); + g_LT -> Write("g_LT"); + + h_EoP_chi2 -> Write(); + h_EoC_chi2 -> Write(); + + //ciao + + for(int i = 0; i < nBins; ++i) + { + gStyle->SetOptFit(1111); + + h_EoP[i] -> Write(); + h_EoC[i] -> Write(); + f_EoP[i] -> Write(); + f_EoC[i] -> Write(); + // h_Tsp[i] -> Write(); + // + // h_Cvl[i] -> Write(); + } + + o -> Close(); + + return 0; + } + //------------------------------ LASER MONITORING WITH E/P versus PILE UP ------------------------------------------------------ + + if(vm.count("laserMonitoringEPvsPU")) { + + + //float yMIN = 0.95; + //float yMAX = 1.05; + + + // Set style options + setTDRStyle(); + gStyle->SetPadTickX(1); + gStyle->SetPadTickY(1); + gStyle->SetOptTitle(0); + gStyle->SetOptStat(1110); + gStyle->SetOptFit(1); + + // Set fitting options + TVirtualFitter::SetDefaultFitter("Fumili2"); + + + + //----------------- + // Input parameters + + + std::cout << "\n***************************************************************************************************************************" << std::endl; + + std::string dayMinLabel = ""; + std::string dayMaxLabel = ""; + std::string dayZOOMLabel =""; + float absEtaMin = -1.; + float absEtaMax = -1.; + int IetaMin = -1; + int IetaMax = -1; + int IphiMin = -1; + int IphiMax = -1; + + + + + int t1 = 0; + int t2 = 60; + + std::cout << "EBEE: " << EBEE << std::endl; + std::cout << "evtsPerPoint: " << evtsPerPoint << std::endl; + std::cout << "useRegression: " << useRegression << std::endl; + std::cout << "dayMin: " << dayMin << std::endl; + std::cout << "dayZOOM: " << dayZOOM << std::endl; + std::cout << "dayMax: " << dayMax << std::endl; + std::cout << "yMin: " << yMIN << std::endl; + std::cout << "yMax: " << yMAX << std::endl; + std::cout << "absEtaMin: " << absEtaMin << std::endl; + std::cout << "absEtaMax: " << absEtaMax << std::endl; + std::cout << "IetaMin: " << IetaMin << std::endl; + std::cout << "IetaMax: " << IetaMax << std::endl; + std::cout << "IphiMin: " << IphiMin << std::endl; + std::cout << "IphiMax: " << IphiMax << std::endl; + std::cout << "t1: " << t1 << std::endl; + std::cout << "t2: " << t2 << std::endl; + + + std::string dayZOOM = ""; + std::string dayMin = ""; + std::string dayMax = ""; + + + //------------------- + // Define in/outfiles + + std::string folderName = std::string(EBEE) + "_" + dayMinLabel + "_" + dayMaxLabel; + if( (absEtaMin != -1.) && (absEtaMax != -1.) ) + { + char absEtaBuffer[50]; + sprintf(absEtaBuffer,"_%.2f-%.2f",absEtaMin,absEtaMax); + folderName += std::string(absEtaBuffer); + } + + if( (IetaMin != -1.) && (IetaMax != -1.) && (IphiMin != -1.) && (IphiMax != -1.) ) + { + char absEtaBuffer[50]; + sprintf(absEtaBuffer,"_Ieta_%d-%d_Iphi_%d-%d",IetaMin,IetaMax,IphiMin,IphiMax); + folderName += std::string(absEtaBuffer); + } + + gSystem->mkdir(folderName.c_str()); + TFile* o = new TFile((folderName+"/"+folderName+"_histos.root").c_str(),"RECREATE"); + + + + // Get trees + std::cout << std::endl; + + + if (data->GetEntries() == 0 || mc->GetEntries() == 0 ) + { + std::cout << "Error: At least one file is empty" << std::endl; + return -1; + } + + + + // Set branch addresses + int runNumber; + int nPV; + int nPU; + float avgLCSCEle[3], seedLaserAlphaSCEle1, etaSCEle[3], phiSCEle[3], energySCEle[3], esEnergySCEle[3], pAtVtxGsfEle[3], energySCEle_corr[3]; + int seedXSCEle[3], seedYSCEle[3];//, seedZside; + + data->SetBranchStatus("*",0); + data->SetBranchStatus("runNumber",1); + data->SetBranchStatus("nPV",1); + data->SetBranchStatus("nPU",1); + data->SetBranchStatus("avgLCSCEle",1); + data->SetBranchStatus("seedLaserAlphaSCEle1",1); + // data->SetBranchStatus("ele1_EOverP",1); + data->SetBranchStatus("etaSCEle",1); + data->SetBranchStatus("phiSCEle",1); + data->SetBranchStatus("energySCEle_must",1); + data->SetBranchStatus("energySCEle_corr",1); + data->SetBranchStatus("esEnergySCEle",1); + data->SetBranchStatus("pAtVtxGsfEle",1); + data->SetBranchStatus("seedXSCEle",1); + data->SetBranchStatus("seedYSCEle",1); + // data->SetBranchStatus("ele1_seedZside",1); + + data->SetBranchAddress("runNumber", &runNumber); + data->SetBranchAddress("nPV", &nPV); + data->SetBranchAddress("nPU", &nPU); + data->SetBranchAddress("avgLCSCEle", &avgLCSCEle[0]); + data->SetBranchAddress("seedLaserAlphaSCEle1", &seedLaserAlphaSCEle1); + // data->SetBranchAddress("ele1_EOverP", &EoP); + data->SetBranchAddress("etaSCEle", &etaSCEle); + data->SetBranchAddress("phiSCEle", &phiSCEle); + if( useRegression < 1 ) + data->SetBranchAddress("energySCEle_must", &energySCEle); + else + data->SetBranchAddress("energySCEle_corr", &energySCEle_corr); + // data->SetBranchAddress("energySCEle", &energySCEle); + data->SetBranchAddress("esEnergySCEle", &esEnergySCEle); + data->SetBranchAddress("pAtVtxGsfEle", &pAtVtxGsfEle); + data->SetBranchAddress("seedXSCEle", &seedXSCEle); + data->SetBranchAddress("seedYSCEle", &seedYSCEle); + // data->SetBranchAddress("ele1_seedZside", &seedZside); + + + mc->SetBranchStatus("*",0); + mc->SetBranchStatus("runNumber",1); + mc->SetBranchStatus("nPV",1); + mc->SetBranchStatus("nPU",1); + mc->SetBranchStatus("avgLCSCEle",1); + mc->SetBranchStatus("seedLaserAlphaSCEle1",1); + // mc->SetBranchStatus("ele1_EOverP",1); + mc->SetBranchStatus("etaSCEle",1); + mc->SetBranchStatus("phiSCEle",1); + mc->SetBranchStatus("energySCEle_must",1); + mc->SetBranchStatus("energySCEle_corr",1); + mc->SetBranchStatus("esEnergySCEle",1); + mc->SetBranchStatus("pAtVtxGsfEle",1); + mc->SetBranchStatus("seedXSCEle",1); + mc->SetBranchStatus("seedYSCEle",1); + // mc->SetBranchStatus("ele1_seedZside",1); + + mc->SetBranchAddress("runNumber", &runNumber); + mc->SetBranchAddress("nPV", &nPV); + mc->SetBranchAddress("nPU", &nPU); + mc->SetBranchAddress("avgLCSCEle", &avgLCSCEle[0]); + mc->SetBranchAddress("seedLaserAlphaSCEle1", &seedLaserAlphaSCEle1); + // mc->SetBranchAddress("ele1_EOverP", &EoP); + mc->SetBranchAddress("etaSCEle", &etaSCEle); + mc->SetBranchAddress("phiSCEle", &phiSCEle); + if( useRegression < 1 ) + mc->SetBranchAddress("energySCEle_must", &energySCEle); + else + mc->SetBranchAddress("energySCEle_corr", &energySCEle_corr); + // mc->SetBranchAddress("energySCEle", &energySCEle); + mc->SetBranchAddress("esEnergySCEle", &esEnergySCEle); + mc->SetBranchAddress("pAtVtxGsfEle", &pAtVtxGsfEle); + mc->SetBranchAddress("seedXSCEle", &seedXSCEle); + mc->SetBranchAddress("seedYSCEle", &seedYSCEle); + // mc->SetBranchAddress("ele1_seedZside", &seedZside); + + + + + + + //-------------------------------------------------------- + // Define PU correction (to be used if useRegression == 0) + + // corr = p0 + p1 * nPU + float p0_EB; + float p1_EB; + float p0_EE; + float p1_EE; + + if( useRegression == 0 ) + { + //2012 EB + p0_EB = 0.9991; + p1_EB = 0.0001635; + //2012 EE + p0_EE = 0.9968; + p1_EE = 0.001046; + } + else + { + //2012 EB + p0_EB = 1.001; + p1_EB = -0.000143; + //2012 EE + p0_EE = 1.00327; + p1_EE = -0.000432; + } + + float p0 = -1.; + float p1 = -1.; + + if( strcmp(EBEE.c_str(),"EB") == 0 ) + { + p0 = p0_EB; + p1 = p1_EB; + } + else + { + p0 = p0_EE; + p1 = p1_EE; + } + + //2015 + p0=1.; + p1=0.; + + + + + //--------------------------------- + // Build the reference distribution + + std::cout << std::endl; + std::cout << "***** Build reference for " << EBEE << " *****" << std::endl; + + TH1F* h_template = new TH1F("template", "", 2000, 0., 5.); + + for(int ientry = 0; ientry < mc->GetEntries(); ++ientry) + { + if( (ientry%100000 == 0) ) std::cout << "reading MC entry " << ientry << "\r" << std::endl;//std::flush; + mc->GetEntry(ientry); + + // selections + if( (strcmp(EBEE.c_str(),"EB") == 0) && (fabs(etaSCEle[0]) > 1.479) ) continue; // barrel + if( (strcmp(EBEE.c_str(),"EB_0_1") == 0) && (fabs(etaSCEle[0]) > 1.0)) continue; // inner barrel + if( (strcmp(EBEE.c_str(),"EB_1_1479") == 0) && (fabs(etaSCEle[0]) < 1.0 || fabs(etaSCEle[0]) > 1.479) ) continue; // barrel + if( (strcmp(EBEE.c_str(),"EE") == 0) && (fabs(etaSCEle[0]) < 1.479 || fabs(etaSCEle[0])>2.5) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EE_1479_2") == 0) && (fabs(etaSCEle[0]) < 1.479 || fabs(etaSCEle[0])>2.0) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EE_2_25") == 0) && (fabs(etaSCEle[0]) < 2.0 || fabs(etaSCEle[0])>2.5) ) continue; // endcap + + if( (strcmp(EBEE.c_str(),"EEp") == 0) && (etaSCEle[0] < 1.479 || etaSCEle[0]>2.5 ) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_1479_2") == 0) && (etaSCEle[0] < 1.479 || etaSCEle[0]>2.0) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_2_25") == 0) && (etaSCEle[0] < 2.0 || etaSCEle[0]>2.5) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_2_225") == 0) && (etaSCEle[0] < 2.0 || etaSCEle[0]>2.25) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_225_25") == 0) && (etaSCEle[0] < 2.25 || etaSCEle[0]>2.25) ) continue; // endcap + + if( (strcmp(EBEE.c_str(),"EEm") == 0) && (etaSCEle[0] > -1.479 || etaSCEle[0]<-2.5 ) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_1479_2") == 0) && (etaSCEle[0] > -1.479 || etaSCEle[0]<-2.0) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_2_25") == 0) && (etaSCEle[0] > -2.0 || etaSCEle[0]<-2.5) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_2_225") == 0) && (etaSCEle[0] > -2.0 || etaSCEle[0]<-2.25) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_225_25") == 0) && (etaSCEle[0] > -2.25 || etaSCEle[0]<-2.5) ) continue; // endcap + + if( (absEtaMin != -1.) && (absEtaMax != -1.) ) + { + if( (fabs(etaSCEle[0]) < absEtaMin) || (fabs(etaSCEle[0]) > absEtaMax) ) continue; + } + + if( (IetaMin != -1.) && (IetaMax != -1.) && (IphiMin != -1.) && (IphiMax != -1.) ) + { + if( (seedXSCEle[0] < IetaMin) || (seedXSCEle[0] > IetaMax) ) continue; + if( (seedYSCEle[0] < IphiMin) || (seedYSCEle[0] > IphiMax) ) continue; + } + + // PU correction + float PUCorr = (p0 + p1*nPU); + //std::cout << "p0: " << p0 << " p1: " << p1 << " nPU: " << nPU << std::endl; + + // fill the template histogram + h_template -> Fill( (energySCEle[0]-esEnergySCEle[0])/(pAtVtxGsfEle[0]-esEnergySCEle[0]) / PUCorr ); + } + + std::cout << "Reference built for " << EBEE << " - " << h_template->GetEntries() << " events" << std::endl; + + + + + + + //--------------------- + // Loop and sort events + + std::cout << std::endl; + std::cout << "***** Sort events and define bins *****" << std::endl; + + int nEntries = data -> GetEntriesFast(); + int nSavePts = 0; + std::vector isSavedEntries(nEntries); + std::vector sortedEntries; + std::vector timeStampFirst; + + for(int ientry = 0; ientry < nEntries; ++ientry) + { + data -> GetEntry(ientry); + isSavedEntries.at(ientry) = false; + + // selections + if( (strcmp(EBEE.c_str(),"EB") == 0) && (fabs(etaSCEle[0]) > 1.479) ) continue; // barrel + if( (strcmp(EBEE.c_str(),"EB_0_1") == 0) && (fabs(etaSCEle[0]) > 1.0)) continue; // inner barrel + if( (strcmp(EBEE.c_str(),"EB_1_1479") == 0) && (fabs(etaSCEle[0]) < 1.0 || fabs(etaSCEle[0]) > 1.479) ) continue; // barrel + if( (strcmp(EBEE.c_str(),"EE") == 0) && (fabs(etaSCEle[0]) < 1.479 || fabs(etaSCEle[0])>2.5) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EE_1479_2") == 0) && (fabs(etaSCEle[0]) < 1.479 || fabs(etaSCEle[0])>2.0) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EE_2_25") == 0) && (fabs(etaSCEle[0]) < 2.0 || fabs(etaSCEle[0])>2.5) ) continue; // endcap + + if( (strcmp(EBEE.c_str(),"EEp") == 0) && (etaSCEle[0] < 1.479 || etaSCEle[0]>2.5 ) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_1479_2") == 0) && (etaSCEle[0] < 1.479 || etaSCEle[0]>2.0) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_2_25") == 0) && (etaSCEle[0] < 2.0 || etaSCEle[0]>2.5) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_2_225") == 0) && (etaSCEle[0] < 2.0 || etaSCEle[0]>2.25) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEp_225_25") == 0) && (etaSCEle[0] < 2.25 || etaSCEle[0]>2.25) ) continue; // endcap + + if( (strcmp(EBEE.c_str(),"EEm") == 0) && (etaSCEle[0] > -1.479 || etaSCEle[0]<-2.5 ) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_1479_2") == 0) && (etaSCEle[0] > -1.479 || etaSCEle[0]<-2.0) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_2_25") == 0) && (etaSCEle[0] > -2.0 || etaSCEle[0]<-2.5) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_2_225") == 0) && (etaSCEle[0] > -2.0 || etaSCEle[0]<-2.25) ) continue; // endcap + if( (strcmp(EBEE.c_str(),"EEm_225_25") == 0) && (etaSCEle[0] > -2.25 || etaSCEle[0]<-2.5) ) continue; // endcap + + if( (absEtaMin != -1.) && (absEtaMax != -1.) ) + { + if( (fabs(etaSCEle[0]) < absEtaMin) || (fabs(etaSCEle[0]) > absEtaMax) ) continue; + } + + if( (IetaMin != -1.) && (IetaMax != -1.) && (IphiMin != -1.) && (IphiMax != -1.) ) + { + if( (seedXSCEle[0] < IetaMin) || (seedXSCEle[0] > IetaMax) ) continue; + if( (seedYSCEle[0] < IphiMin) || (seedYSCEle[0] > IphiMax) ) continue; + } + + if( nPV < t1 ) continue; + if( nPV > t2 ) continue; + + if( avgLCSCEle[0] <= 0. ) continue; + + isSavedEntries.at(ientry) = true; + + + // fill sorter + Sorter dummy; + dummy.time = nPV; + dummy.entry = ientry; + sortedEntries.push_back(dummy); + + ++nSavePts; + } + + // sort events + std::sort(sortedEntries.begin(),sortedEntries.end(),Sorter()); + std::cout << "Data sorted in " << EBEE << " - " << nSavePts << " events" << std::endl; + + std::map antiMap; + for(unsigned int iSaved = 0; iSaved < sortedEntries.size(); ++iSaved) + antiMap[sortedEntries.at(iSaved).entry] = iSaved; + + + //--------------------- + // Loop and define bins + + // "wide" bins - find events with time separation bigger than 1 day + int nWideBins = 1; + std::vector wideBinEntryMax; + //int timeStampOld = -1; + + wideBinEntryMax.push_back(0); + + for(int iSaved = 0; iSaved < nSavePts; ++iSaved) + { + /* if( iSaved%100000 == 0 ) std::cout << "reading saved entry " << iSaved << "\r" << std::flush; + data->GetEntry(sortedEntries[iSaved].entry); + + if( iSaved == 0 ) + { + timeStampOld = nPV; + continue; + } + + if( (nPV-timeStampOld)/3600. > timeLapse ) + { + ++nWideBins; + wideBinEntryMax.push_back(iSaved-1); + } + + + timeStampOld = nPV; + */ + } + + + std::cout << std::endl; + wideBinEntryMax.push_back(nSavePts); + + // bins with approximatively evtsPerPoint events per bin + int nBins = 0; + std::vector binEntryMax; + + binEntryMax.push_back(0); + for(int wideBin = 0; wideBin < nWideBins; ++wideBin) + { + int nTempBins = std::max(1,int( (wideBinEntryMax.at(wideBin+1)-wideBinEntryMax.at(wideBin))/evtsPerPoint )); + int nTempBinEntries = int( (wideBinEntryMax.at(wideBin+1)-wideBinEntryMax.at(wideBin))/nTempBins ); + + for(int tempBin = 0; tempBin < nTempBins; ++tempBin) + { + ++nBins; + if( tempBin < nTempBins - 1 ) + binEntryMax.push_back( wideBinEntryMax.at(wideBin) + (tempBin+1)*nTempBinEntries ); + else + binEntryMax.push_back( wideBinEntryMax.at(wideBin+1) ); + } + } + + // std::cout << "nBins = " << nBins << std::endl; + //for(int bin = 0; bin < nBins; ++bin) + // std::cout << "bin: " << bin + // << " entry min: " << setw(6) << binEntryMax.at(bin) + // << " entry max: " << setw(6) << binEntryMax.at(bin+1) + // << " events: " << setw(6) << binEntryMax.at(bin+1)-binEntryMax.at(bin) + // << std::endl; + + + + + + + //--------------------- + // histogram definition + + TH1F* h_scOccupancy_eta = new TH1F("h_scOccupancy_eta","", 298, -2.6, 2.6); + TH1F* h_scOccupancy_phi = new TH1F("h_scOccupancy_phi","", 363, -3.1765, 3.159); + SetHistoStyle(h_scOccupancy_eta); + SetHistoStyle(h_scOccupancy_phi); + + TH2F* h_seedOccupancy_EB = new TH2F("h_seedOccupancy_EB","", 171, -86., 85., 361, 0.,361.); + TH2F* h_seedOccupancy_EEp = new TH2F("h_seedOccupancy_EEp","", 101, 0.,101., 100, 0.,101.); + TH2F* h_seedOccupancy_EEm = new TH2F("h_seedOccupancy_EEm","", 101, 0.,101., 100, 0.,101.); + SetHistoStyle(h_seedOccupancy_EB); + SetHistoStyle(h_seedOccupancy_EEp); + SetHistoStyle(h_seedOccupancy_EEm); + + TH1F* h_EoP_spread = new TH1F("h_EoP_spread","",100,yMIN,yMAX); + TH1F* h_EoC_spread = new TH1F("h_EoC_spread","",100,yMIN,yMAX); + TH1F* h_EoP_spread_run = new TH1F("h_EoP_spread_run","",100,yMIN,yMAX); + TH1F* h_EoC_spread_run = new TH1F("h_EoC_spread_run","",100,yMIN,yMAX); + SetHistoStyle(h_EoP_spread,"EoP"); + SetHistoStyle(h_EoC_spread,"EoC"); + SetHistoStyle(h_EoP_spread_run,"EoP"); + SetHistoStyle(h_EoC_spread_run,"EoC"); + + TH1F* h_EoP_chi2 = new TH1F("h_EoP_chi2","",50,0.,5.); + TH1F* h_EoC_chi2 = new TH1F("h_EoC_chi2","",50,0.,5.); + SetHistoStyle(h_EoP_chi2,"EoP"); + SetHistoStyle(h_EoC_chi2,"EoC"); + + TH1F** h_EoP = new TH1F*[nBins]; + TH1F** h_EoC = new TH1F*[nBins]; + TH1F** h_Las = new TH1F*[nBins]; + TH1F** h_Tsp = new TH1F*[nBins]; + TH1F** h_Cvl = new TH1F*[nBins]; + + for(int i = 0; i < nBins; ++i) + { + char histoName[80]; + + sprintf(histoName, "EoP_%d", i); + h_EoP[i] = new TH1F(histoName, histoName, 2000, 0., 5.); + SetHistoStyle(h_EoP[i],"EoP"); + + sprintf(histoName, "EoC_%d", i); + h_EoC[i] = new TH1F(histoName, histoName, 2000, 0., 5.); + SetHistoStyle(h_EoC[i],"EoC"); + + sprintf(histoName, "Las_%d", i); + h_Las[i] = new TH1F(histoName, histoName, 500, 0.5, 1.5); + + sprintf(histoName, "Tsp_%d", i); + h_Tsp[i] = new TH1F(histoName, histoName, 500, 0.5, 1.5); + + } + + + // function definition + TF1** f_EoP = new TF1*[nBins]; + TF1** f_EoC = new TF1*[nBins]; + + + // graphs definition + TGraphAsymmErrors* g_fit = new TGraphAsymmErrors(); + TGraphAsymmErrors* g_c_fit = new TGraphAsymmErrors(); + + TGraphAsymmErrors* g_fit_run = new TGraphAsymmErrors(); + TGraphAsymmErrors* g_c_fit_run = new TGraphAsymmErrors(); + + TGraph* g_las = new TGraph(); + + TGraphErrors* g_LT = new TGraphErrors(); + + g_fit->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00"); + g_fit->GetXaxis()->SetTimeDisplay(1); + g_c_fit->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00"); + g_c_fit->GetXaxis()->SetTimeDisplay(1); + g_las->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00"); + g_las->GetXaxis()->SetTimeDisplay(1); + g_LT->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00"); + g_LT->GetXaxis()->SetTimeDisplay(1); + + + + + + + //------------------------------------ + // loop on the saved and sorted events + + std::cout << std::endl; + std::cout << "***** Fill and fit histograms *****" << std::endl; + + std::vector Entries(nBins); + std::vector AveTime(nBins); + std::vector MinTime(nBins); + std::vector MaxTime(nBins); + std::vector AveRun(nBins); + std::vector MinRun(nBins); + std::vector MaxRun(nBins); + std::vector AveLT(nBins); + std::vector AveLT2(nBins); + + int iSaved = -1; + for(int ientry = 0; ientry < nEntries; ++ientry) + { + if( (ientry%100000 == 0) ) std::cout << "reading entry " << ientry << "\r" << std::endl;//std::flush; + + if( isSavedEntries.at(ientry) == false ) continue; + + ++iSaved; + + int iSaved = antiMap[ientry]; + int bin = -1; + for(bin = 0; bin < nBins; ++bin) + if( iSaved >= binEntryMax.at(bin) && iSaved < binEntryMax.at(bin+1) ) + break; + + //std::cout << "bin = " << bin << " iSaved = "<< iSaved << std::endl; + data->GetEntry(ientry); + + + + Entries[bin] += 1; + + if( iSaved == binEntryMax.at(bin)+1 ) MinTime[bin] = nPV; + if( iSaved == binEntryMax.at(bin+1)-1 ) MaxTime[bin] = nPV; + AveTime[bin] += nPV; + + if( iSaved == binEntryMax.at(bin)+1 ) MinRun[bin] = runNumber; + if( iSaved == binEntryMax.at(bin+1)-1 ) MaxRun[bin] = runNumber; + AveRun[bin] += runNumber; + + float LT = (-1. / seedLaserAlphaSCEle1 * log(avgLCSCEle[0])); + AveLT[bin] += LT; + AveLT2[bin] += LT*LT; + + // PU correction + float PUCorr = (p0 + p1*nPU); + + // fill the histograms + (h_EoP[bin]) -> Fill( (energySCEle[0]-esEnergySCEle[0])/(pAtVtxGsfEle[0]-esEnergySCEle[0]) / avgLCSCEle[0] / PUCorr); + (h_EoC[bin]) -> Fill( (energySCEle[0]-esEnergySCEle[0])/(pAtVtxGsfEle[0]-esEnergySCEle[0]) / PUCorr ); + + (h_Las[bin]) -> Fill(avgLCSCEle[0]); + (h_Tsp[bin]) -> Fill(1./avgLCSCEle[0]); + + h_scOccupancy_eta -> Fill(etaSCEle[0]); + h_scOccupancy_phi -> Fill(phiSCEle[0]); + if(fabs(etaSCEle[0])<1.449) + h_seedOccupancy_EB -> Fill(seedXSCEle[0],seedYSCEle[0]); + else if(etaSCEle[0]>1.449) + h_seedOccupancy_EEp -> Fill(seedXSCEle[0],seedYSCEle[0]); + else if(etaSCEle[0]<-1.449) + h_seedOccupancy_EEm -> Fill(seedXSCEle[0],seedYSCEle[0]); + } + + for(int bin = 0; bin < nBins; ++bin) + { + AveTime[bin] = 1. * AveTime[bin] / (binEntryMax.at(bin+1)-binEntryMax.at(bin)); + AveRun[bin] = 1. * AveRun[bin] / (binEntryMax.at(bin+1)-binEntryMax.at(bin)); + AveLT[bin] = 1. * AveLT[bin] / (binEntryMax.at(bin+1)-binEntryMax.at(bin)); + AveLT2[bin] = 1. * AveLT2[bin] / (binEntryMax.at(bin+1)-binEntryMax.at(bin)); + //std::cout << date << " " << AveTime[i] << " " << MinTime[i] << " " << MaxTime[i] << std::endl; + } + + + + + + + int rebin = 2; + if( strcmp(EBEE.c_str(),"EE") == 0 ) rebin *= 2; + + h_template -> Rebin(rebin); + + + + float EoP_scale = 0.; + float EoP_err = 0.; + int EoP_nActiveBins = 0; + + float EoC_scale = 0.; + float EoC_err = 0.; + int EoC_nActiveBins = 0; + + float LCInv_scale = 0; + + std::vector validBins; + for(int i = 0; i < nBins; ++i) + { + bool isValid = true; + + h_EoP[i] -> Rebin(rebin); + h_EoC[i] -> Rebin(rebin); + + + + //------------------------------------ + // Fill the graph for uncorrected data + + // define the fitting function + // N.B. [0] * ( [1] * f( [1]*(x-[2]) ) ) + + //o -> cd(); + char convolutionName[50]; + sprintf(convolutionName,"h_convolution_%d",i); + //h_Cvl[i] = ConvoluteTemplate(std::string(convolutionName),h_template,h_Las[i],32768,-5.,5.); + h_Cvl[i] = MellinConvolution(std::string(convolutionName),h_template,h_Tsp[i]); + + histoFunc* templateHistoFunc = new histoFunc(h_template); + histoFunc* templateConvolutedHistoFunc = new histoFunc(h_Cvl[i]); + char funcName[50]; + + sprintf(funcName,"f_EoP_%d",i); + + if( strcmp(EBEE.c_str(),"EB") == 0 ) + f_EoP[i] = new TF1(funcName, templateConvolutedHistoFunc, 0.8*(h_Tsp[i]->GetMean()), 1.4*(h_Tsp[i]->GetMean()), 3, "histoFunc"); + else + f_EoP[i] = new TF1(funcName, templateConvolutedHistoFunc, 0.75*(h_Tsp[i]->GetMean()), 1.5*(h_Tsp[i]->GetMean()), 3, "histoFunc"); + + f_EoP[i] -> SetParName(0,"Norm"); + f_EoP[i] -> SetParName(1,"Scale factor"); + f_EoP[i] -> SetLineWidth(1); + f_EoP[i] -> SetNpx(10000); + + double xNorm = h_EoP[i]->GetEntries()/h_template->GetEntries() * + h_EoP[i]->GetBinWidth(1)/h_template->GetBinWidth(1); + + f_EoP[i] -> FixParameter(0, xNorm); + f_EoP[i] -> SetParameter(1, 1.); + f_EoP[i] -> FixParameter(2, 0.); + f_EoP[i] -> SetLineColor(kRed+2); + + int fStatus = 0; + int nTrials = 0; + TFitResultPtr rp; + + rp = h_EoP[i] -> Fit(funcName, "ERLS+"); + while( (fStatus != 0) && (nTrials < 10) ) + { + rp = h_EoP[i] -> Fit(funcName, "ERLS+"); + fStatus = rp; + if(fStatus == 0) break; + ++nTrials; + } + + // fill the graph + double eee = f_EoP[i]->GetParError(1); + //float k = f_EoP[i]->GetParameter(1); + float k = f_EoP[i]->GetParameter(1) / h_Tsp[i]->GetMean(); //needed when using mellin's convolution + // std::cout << "noCORR" << std::endl; + // std::cout << "eee: " << f_EoP[i]->GetParError(1) << "k: " << f_EoP[i]->GetParameter(1) / h_Tsp[i]->GetMean() << std::endl; + + /* + std::cout << i <<"--nocorr---- "<< 1./k << std::endl; + std::cout <<" condizione 1: " << h_EoP[i]->GetEntries() << " fStatus: " << fStatus << " eee: " << eee << "con eee che ci piace essere maggiore di : " << 0.05*h_template->GetRMS()/sqrt(evtsPerPoint) << std::endl ; + getchar(); + */ + // if( (h_EoP[i]->GetEntries() > 3) && (fStatus == 0) && (eee > 0.05*h_template->GetRMS()/sqrt(evtsPerPoint)) ) + + if( (h_EoP[i]->GetEntries() > 500) && (fStatus == 0) ) + { + float date = (float)AveTime[i]; + float dLow = (float)(AveTime[i]-MinTime[i]); + float dHig = (float)(MaxTime[i]-AveTime[i]); + float run = (float)AveRun[i]; + float rLow = (float)(AveRun[i]-MinRun[i]); + float rHig = (float)(MaxRun[i]-AveRun[i]); + g_fit -> SetPoint(i, date , 1./k); + g_fit -> SetPointError(i, dLow , dHig, eee/k/k, eee/k/k); + g_fit_run -> SetPoint(i, run , 1./k); + g_fit_run -> SetPointError(i, rLow , rHig, eee/k/k, eee/k/k); + + std::cout <<"************-------------------*****************" < Fill(f_EoP[i]->GetChisquare()/f_EoP[i]->GetNDF()); + + EoP_scale += 1./k; + EoP_err += eee/k/k; + ++EoP_nActiveBins; + } + else + { + std::cout << "Fitting uncorrected time bin: " << i << " Fail status: " << fStatus << " sigma: " << eee << std::endl; + isValid = false; + } + + //---------------------------------- + // Fill the graph for corrected data + + // define the fitting function + // N.B. [0] * ( [1] * f( [1]*(x-[2]) ) ) + + sprintf(funcName,"f_EoC_%d",i); + if( strcmp(EBEE.c_str(),"EB") == 0 ) + f_EoC[i] = new TF1(funcName, templateHistoFunc, 0.8, 1.4, 3, "histoFunc"); + else + f_EoC[i] = new TF1(funcName, templateHistoFunc, 0.75, 1.5, 3, "histoFunc"); + f_EoC[i] -> SetParName(0,"Norm"); + f_EoC[i] -> SetParName(1,"Scale factor"); + f_EoC[i] -> SetLineWidth(1); + f_EoC[i] -> SetNpx(10000); + + xNorm = h_EoC[i]->GetEntries()/h_template->GetEntries() * + h_EoC[i]->GetBinWidth(1)/h_template->GetBinWidth(1); + + f_EoC[i] -> FixParameter(0, xNorm); + f_EoC[i] -> SetParameter(1, 0.99); + f_EoC[i] -> FixParameter(2, 0.); + f_EoC[i] -> SetLineColor(kGreen+2); + + + rp = h_EoC[i] -> Fit(funcName, "ERLS+"); + fStatus = rp; + nTrials = 0; + while( (fStatus != 0) && (nTrials < 10) ) + { + rp = h_EoC[i] -> Fit(funcName, "ERLS+"); + fStatus = rp; + if(fStatus == 0) break; + ++nTrials; + } + + + // fill the graph + k = f_EoC[i]->GetParameter(1); + eee = f_EoC[i]->GetParError(1); + //std::cout << "CORR" << std::endl; + //std::cout << "eee: " << f_EoP[i]->GetParError(1) << "k: " << f_EoP[i]->GetParameter(1) / h_Tsp[i]->GetMean() << std::endl; + //getchar(); + /* std::cout << i <<"--corr---- "<< 1./k << std::endl; + std::cout <<" condizione 1: " << h_EoP[i]->GetEntries() << " fStatus: " << fStatus << " eee: " << eee << "con eee che ci piace essere maggiore di : " << 0.05*h_template->GetRMS()/sqrt(evtsPerPoint) << std::endl ; + getchar(); + */ + + + if( (h_EoC[i]->GetEntries() > 500) && (fStatus == 0) ) + // if( (h_EoC[i]->GetEntries() > 10) && (fStatus == 0) && (eee > 0.05*h_template->GetRMS()/sqrt(evtsPerPoint)) ) + { + float date = (float)AveTime[i]; + float dLow = (float)(AveTime[i]-MinTime[i]); + float dHig = (float)(MaxTime[i]-AveTime[i]); + float run = (float)AveRun[i]; + float rLow = (float)(AveRun[i]-MinRun[i]); + float rHig = (float)(MaxRun[i]-AveRun[i]); + + g_c_fit -> SetPoint(i, date , 1./k); + g_c_fit -> SetPointError(i, dLow , dHig , eee/k/k, eee/k/k); + + g_c_fit_run -> SetPoint(i, run , 1./k); + g_c_fit_run -> SetPointError(i, rLow , rHig, eee/k/k, eee/k/k); + std::cout <<"************-------------------*****************" < Fill(f_EoC[i]->GetChisquare()/f_EoP[i]->GetNDF()); + + EoC_scale += 1./k; + EoC_err += eee/k/k; + ++EoC_nActiveBins; + } + else + { + std::cout << "Fitting corrected time bin: " << i << " Fail status: " << fStatus << " sigma: " << eee << std::endl; + isValid = false; + } + + if( isValid == true ) validBins.push_back(i); + } + + EoP_scale /= EoP_nActiveBins; + EoP_err /= EoP_nActiveBins; + + EoC_scale /= EoC_nActiveBins; + EoC_err /= EoC_nActiveBins; + + + + + + + //---------------------------------------- + // Fill the graph for avg laser correction + + + for(unsigned int itr = 0; itr < validBins.size(); ++itr) + { + //float k0 = f_EoP[0]->GetParameter(1) / h_Tsp[0]->GetMean(); + int i = validBins.at(itr); + // g_las -> SetPoint(itr, (float)AveTime[i], (h_Tsp[i]->GetMean())+((1/k0)-(h_Tsp[0]->GetMean())) ); + g_las -> SetPoint(itr, (float)AveTime[i], h_Tsp[i]->GetMean() ); + + + //g_las -> SetPointffa(itr, (float)AveTime[i], h_Tsp[i]->GetMean()); + g_LT -> SetPoint(itr, (float)AveTime[i], AveLT[i] ); + g_LT -> SetPointError(itr, 0., sqrt(AveLT2[i]-AveLT[i]*AveLT[i]) / sqrt(Entries[i]) ); + + LCInv_scale += h_Tsp[i]->GetMean(); + } + + LCInv_scale /= validBins.size(); + + + + + + + //--------------- + // Rescale graphs + + float yscale = 1.; + //float yscale = 1./EoC_scale; + + for(unsigned int itr = 0; itr < validBins.size(); ++itr) + { + double x,y; + g_fit -> GetPoint(itr,x,y); + g_fit -> SetPoint(itr,x,y*yscale); + if ( (x > t1) && (x < t2) ) h_EoP_spread -> Fill(y*yscale); + + g_c_fit -> GetPoint(itr,x,y); + g_c_fit -> SetPoint(itr,x,y*yscale); + if ( (x > t1) && (x < t2) ) h_EoC_spread -> Fill(y*yscale); + + g_fit_run -> GetPoint(itr,x,y); + g_fit_run -> SetPoint(itr,x,y*yscale); + if ( (x > t1) && (x < t2) ) h_EoP_spread_run -> Fill(y*yscale); + + g_c_fit_run -> GetPoint(itr,x,y); + g_c_fit_run -> SetPoint(itr,x,y*yscale); + if ( (x > t1) && (x < t2) ) h_EoC_spread_run -> Fill(y*yscale); + + g_las -> GetPoint(itr,x,y); + g_las -> SetPoint(itr,x,y*yscale*EoP_scale/LCInv_scale); + } + //ciao + TF1 EoC_pol0("EoC_pol0","pol0",t1,t2); + EoC_pol0.SetLineColor(kGreen+2); + EoC_pol0.SetLineWidth(2); + EoC_pol0.SetLineStyle(2); + g_c_fit -> Fit("EoC_pol0","QNR"); + + + + + + + + + //---------------------------- + // Print out global quantities + + std::cout << std::endl; + std::cout << "***** Mean scales and errors *****" << std::endl; + std::cout << std::fixed; + std::cout << std::setprecision(4); + std::cout << "Mean EoP scale: " << std::setw(6) << EoP_scale << " mean EoP error: " << std::setw(8) << EoP_err << std::endl; + std::cout << "Mean EoC scale: " << std::setw(6) << EoC_scale << " mean EoC error: " << std::setw(8) << EoC_err << std::endl; + std::cout << "Mean 1/LC scale: " << std::setw(6) << LCInv_scale << std::endl; + + + + + + + //------------------- + // Final Plot vs Vertex + //------------------- + + TCanvas* cplot = new TCanvas("cplot", "history plot vs Vertex",100,100,1000,500); + cplot->cd(); + + TPad *cLeft = new TPad("pad_0","pad_0",0.00,0.00,0.75,1.00); + TPad *cRight = new TPad("pad_1","pad_1",0.75,0.00,1.00,1.00); + + cLeft->SetLeftMargin(0.15); + cLeft->SetRightMargin(0.025); + cRight->SetLeftMargin(0.025); + + cLeft->Draw(); + cRight->Draw(); + + float tYoffset = 1.0; + float labSize = 0.05; + float labSize2 = 0.06; + + cLeft->cd(); + + cLeft->SetGridx(); + cLeft->SetGridy(); + + TH1F *hPad = (TH1F*)gPad->DrawFrame(t1,0.9,t2,1.05); + + hPad->GetXaxis()->SetLimits(0,46); + //hPad->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00"); + //hPad->GetXaxis()->SetTimeDisplay(1); + //hPad->GetXaxis() -> SetRangeUser(MinTime[0]-43200,MaxTime[nBins-1]+43200); + hPad->GetXaxis()->SetTitle(" Number of Vertices"); + hPad->GetXaxis()->SetTitleOffset(0.8); + + //ciao + + + if( strcmp(EBEE.c_str(),"EB") == 0 ) + hPad->GetYaxis()->SetTitle("Relative E/p scale"); + else + hPad->GetYaxis()->SetTitle("Relative E/p scale"); + hPad->GetYaxis()->SetTitleOffset(tYoffset); + hPad->GetXaxis()->SetLabelSize(labSize); + hPad->GetXaxis()->SetTitleSize(labSize2); + hPad->GetYaxis()->SetLabelSize(labSize); + hPad->GetYaxis()->SetTitleSize(labSize2); + hPad -> SetMinimum(yMIN); + hPad -> SetMaximum(yMAX); + + // draw history plot + g_fit -> SetMarkerStyle(24); + g_fit -> SetMarkerSize(0.7); + g_fit -> SetMarkerColor(kRed+2); + g_fit -> SetLineColor(kRed+2); + //g_fit -> Draw("P"); + g_c_fit -> SetMarkerStyle(20); + g_c_fit -> SetMarkerColor(kGreen+2); + g_c_fit -> SetLineColor(kGreen+2); + g_c_fit -> SetMarkerSize(0.7); + g_c_fit -> Draw("EP"); + g_las -> SetLineColor(kAzure-2); + g_las -> SetLineWidth(2); + //g_las -> Draw("L,same"); + + TLegend* legend = new TLegend(0.60,0.78,0.90,0.94); + legend -> SetLineColor(kWhite); + legend -> SetLineWidth(0); + legend -> SetFillColor(kWhite); + legend -> SetFillStyle(0); + legend -> SetTextFont(42); + legend -> SetTextSize(0.04); + legend -> AddEntry(g_c_fit,"with LM correction","PL"); + //legend -> AddEntry(g_fit, "without LM correction","PL"); + //legend -> AddEntry(g_las, "1 / LM correction","L"); + legend -> Draw("same"); + + char latexBuffer[250]; + + sprintf(latexBuffer,"CMS 2015 Preliminary"); + TLatex* latex = new TLatex(0.18,0.89,latexBuffer); + latex -> SetNDC(); + latex -> SetTextFont(62); + latex -> SetTextSize(0.05); + latex -> Draw("same"); + + //sprintf(latexBuffer,"#sqrt{s} = 8 TeV L = 3.95 fb^{-1}"); + sprintf(latexBuffer,"#sqrt{s} = 13 TeV"); + TLatex* latex2 = new TLatex(0.18,0.84,latexBuffer); + latex2 -> SetNDC(); + latex2 -> SetTextFont(42); + latex2 -> SetTextSize(0.05); + latex2 -> Draw("same"); + + if( strcmp(EBEE.c_str(),"EB") == 0 || strcmp(EBEE.c_str(),"EB_0_1") == 0 || strcmp(EBEE.c_str(),"EB_1_1479") == 0) + sprintf(latexBuffer,"ECAL Barrel"); + else + sprintf(latexBuffer,"ECAL Endcap"); + TLatex* latex3 = new TLatex(0.18,0.19,latexBuffer); + latex3 -> SetNDC(); + latex3 -> SetTextFont(42); + latex3 -> SetTextSize(0.05); + latex3 -> Draw("same"); + + //sprintf(latexBuffer,"%.2E events",1.*nSavePts); + //TLatex* latex4 = new TLatex(0.18,0.24,latexBuffer); + //latex4 -> SetNDC(); + //latex4 -> SetTextFont(42); + //latex4 -> SetTextSize(0.04); + //latex4 -> Draw("same"); + // + //sprintf(latexBuffer,"%d events/bin - %d bins",evtsPerPoint,nBins); + //TLatex* latex5 = new TLatex(0.18,0.19,latexBuffer); + //latex5 -> SetNDC(); + //latex5 -> SetTextFont(42); + //latex5 -> SetTextSize(0.04); + //latex5 -> Draw("same"); + + + cRight -> cd(); + + TPaveStats* s_EoP_spread = new TPaveStats(); + TPaveStats* s_EoC_spread = new TPaveStats(); + + + h_EoC_spread -> SetFillStyle(3001); + h_EoC_spread -> SetFillColor(kGreen+2); + h_EoC_spread->GetYaxis()->SetLabelSize(0.09); + h_EoC_spread->GetYaxis()->SetLabelOffset(-0.03); + h_EoC_spread->GetYaxis()->SetTitleSize(0.08); + h_EoC_spread->GetYaxis()->SetNdivisions(505); + h_EoC_spread->GetXaxis()->SetLabelOffset(1000); + + h_EoC_spread -> Draw("hbar"); + gPad -> Update(); + + s_EoC_spread = (TPaveStats*)(h_EoC_spread->GetListOfFunctions()->FindObject("stats")); + s_EoC_spread -> SetStatFormat("1.4g"); + s_EoC_spread->SetX1NDC(0.06); //new x start position + s_EoC_spread->SetX2NDC(0.71); //new x end position + s_EoC_spread->SetY1NDC(0.43); //new x start position + s_EoC_spread->SetY2NDC(0.34); //new x end position + s_EoC_spread -> SetOptStat(1100); + s_EoC_spread ->SetTextColor(kGreen+2); + s_EoC_spread ->SetTextSize(0.08); + s_EoC_spread -> Draw("sames"); + + + h_EoP_spread -> SetFillStyle(3001); + h_EoP_spread -> SetFillColor(kRed+2); + h_EoP_spread -> Draw("hbarsames"); + gPad -> Update(); + s_EoP_spread = (TPaveStats*)(h_EoP_spread->GetListOfFunctions()->FindObject("stats")); + s_EoP_spread -> SetStatFormat("1.4g"); + s_EoP_spread->SetX1NDC(0.06); //new x start position + s_EoP_spread->SetX2NDC(0.71); //new x end position + s_EoP_spread->SetY1NDC(0.33); //new x start position + s_EoP_spread->SetY2NDC(0.24); //new x end position + s_EoP_spread ->SetOptStat(1100); + s_EoP_spread ->SetTextColor(kRed+2); + s_EoP_spread ->SetTextSize(0.08); + s_EoP_spread -> Draw("sames"); + + /* + h_EoP_spread -> SetFillStyle(3001); + h_EoP_spread -> SetFillColor(kRed+2); + h_EoP_spread -> Draw("hbarsame"); + gPad -> Update(); + */ + + + + + + cplot -> Print((folderName+"/"+folderName+"_history_vsVertex.png").c_str(),"png"); + + cplot -> Print((folderName+"/"+folderName+"_history_vsVertex.pdf").c_str(),"pdf"); + + cplot -> SaveAs((folderName+"/"+folderName+"_history_vsVertex.C").c_str()); + + + + o -> cd(); + + h_template -> Write(); + + h_scOccupancy_eta -> Write(); + h_scOccupancy_phi -> Write(); + h_seedOccupancy_EB -> Write(); + h_seedOccupancy_EEp -> Write(); + h_seedOccupancy_EEm -> Write(); + + g_fit -> Write("g_fit"); + g_c_fit -> Write("g_c_fit"); + g_fit_run -> Write("g_fit_run"); + g_c_fit_run -> Write("g_c_fit_run"); + g_las -> Write("g_las"); + g_LT -> Write("g_LT"); + + h_EoP_chi2 -> Write(); + h_EoC_chi2 -> Write(); + + //ciao + + for(int i = 0; i < nBins; ++i) + { + gStyle->SetOptFit(1111); + + h_EoP[i] -> Write(); + h_EoC[i] -> Write(); + f_EoP[i] -> Write(); + f_EoC[i] -> Write(); + // h_Tsp[i] -> Write(); + // + // h_Cvl[i] -> Write(); + } + + o -> Close(); + + return 0; + } + ///////////--------------------------- E/P calibration ---------------------------------------------------------------------- + + + /////////////////////////////Momentum correction BARREL + +//////////////////////////////////Momentum correction + if(vm.count("momentumCorrectionEB")) { +///////// produce P corrections + + std::string typeEB = "eta1"; + int nRegionsEB = 1; + int nPhiBinsEB = 360; + int nPhiBinsTempEB = 1; + int nEtaBinsEB = 1; + int nEtaBinsTempEB = 1; + int rebinEB = 20; + std::string outputFile = "momentumCalibration2015_EB.root"; + int nEntriesMC = -1; + int nEntriesData = -1; + + // int nRegionsEB = GetNRegionsEB(typeEB); + + std::cout<<"REGIONI: "<GetEntries() << " entries in Data sample" << std::endl; + + // Set branch addresses + float etaSCEle[3], phiSCEle[3], etaEle[3], phiEle[3], esEnergySCEle[3], pAtVtxGsfEle[3], energySCEle[3], R9Ele[3]; + int seedXSCEle[3], seedYSCEle[3], chargeEle[3];//, seedZside; + + int debug=0; + + std::cout<<"debug: "<SetBranchStatus("*",0); + data->SetBranchStatus("etaSCEle",1); + data->SetBranchStatus("phiSCEle",1); + data->SetBranchStatus("etaEle",1); + data->SetBranchStatus("phiEle",1); + data->SetBranchStatus("rawEnergySCEle",1); + data->SetBranchStatus("energySCEle",1); + data->SetBranchStatus("esEnergySCEle",1); + data->SetBranchStatus("pAtVtxGsfEle",1); + data->SetBranchStatus("seedXSCEle",1); + data->SetBranchStatus("seedYSCEle",1); + data->SetBranchStatus("chargeEle",1); + data->SetBranchStatus("R9Ele",1); + + data->SetBranchAddress("etaSCEle", &etaSCEle); + data->SetBranchAddress("phiSCEle", &phiSCEle); + data->SetBranchAddress("etaEle", &etaEle); + data->SetBranchAddress("phiEle", &phiEle); + if (energyTypeEB==0) + data->SetBranchAddress("rawEnergySCEle", &energySCEle); + else + data->SetBranchAddress("energySCEle", &energySCEle); + data->SetBranchAddress("esEnergySCEle", &esEnergySCEle); + data->SetBranchAddress("pAtVtxGsfEle", &pAtVtxGsfEle); + //data->SetBranchAddress("energySCEle", &pAtVtxGsfEle); + data->SetBranchAddress("seedXSCEle", &seedXSCEle); + data->SetBranchAddress("seedYSCEle", &seedYSCEle); + data->SetBranchAddress("chargeEle", &chargeEle); + data->SetBranchAddress("R9Ele", &R9Ele); + + std::cout<<"debug: "<SetBranchStatus("*",0); + mc->SetBranchStatus("etaSCEle",1); + mc->SetBranchStatus("phiSCEle",1); + mc->SetBranchStatus("etaEle",1); + mc->SetBranchStatus("phiEle",1); + mc->SetBranchStatus("rawEnergySCEle",1); + mc->SetBranchStatus("energySCEle",1); + mc->SetBranchStatus("esEnergySCEle",1); + mc->SetBranchStatus("pAtVtxGsfEle",1); + mc->SetBranchStatus("seedXSCEle",1); + mc->SetBranchStatus("seedYSCEle",1); + mc->SetBranchStatus("chargeEle",1); + mc->SetBranchStatus("R9Ele",1); + + mc->SetBranchAddress("etaSCEle", &etaSCEle); + mc->SetBranchAddress("phiSCEle", &phiSCEle); + mc->SetBranchAddress("etaEle", &etaEle); + mc->SetBranchAddress("phiEle", &phiEle); + if (energyTypeEB==0) + mc->SetBranchAddress("rawEnergySCEle", &energySCEle); + else + mc->SetBranchAddress("energySCEle", &energySCEle); + mc->SetBranchAddress("esEnergySCEle", &esEnergySCEle); + mc->SetBranchAddress("pAtVtxGsfEle", &pAtVtxGsfEle); + //mc->SetBranchAddress("energySCEle", &pAtVtxGsfEle); + mc->SetBranchAddress("seedXSCEle", &seedXSCEle); + mc->SetBranchAddress("seedYSCEle", &seedYSCEle); + mc->SetBranchAddress("chargeEle", &chargeEle); + mc->SetBranchAddress("R9Ele", &R9Ele); + + std::cout<<"debug: "< > h_Phi_EB(nPhiBinsEB); // used to map iEta (as defined for Barrel and Endcap geom) into eta + // std::vector > h_Eta_EB(nEtaBinsEB); // used to map iEta (as defined for Barrel and Endcap geom) into eta + TH1F* h_pData_EB[nPhiBinsEB][nEtaBinsEB][nRegionsEB]; + // std::vector > > h_pData_EB(nPhiBinsEB); + TF1* f_pData_EB[nPhiBinsEB][nEtaBinsEB][nRegionsEB]; + + TH1F* histoPull_EB[nEtaBinsEB][nRegionsEB]; + std::cout<<"debug: "< vect1(nEtaBinsEB); + + // Initializate histos in EB + std::cout << ">>> Initialize EB histos" << std::endl; + // std::vector >tempVect(nEtaBinsEB); + for (int k=0; kSumw2(); + temp->SetFillColor(kGreen+2); + temp->SetLineColor(kGreen+2); + temp->SetFillStyle(3004); + h_pData_EB[i][k][j] = temp; + // (tempVect.at(k)).push_back(temp); + + // histoName=Form("EB_Phi_%d_%d_%d", i,k,j); + // temp = new TH1F(histoName, histoName, 360, 0., 360.); + // (h_Phi_EB.at(i)).push_back(temp); + } + + // std::cout<<"qui?"< > h_template_EB(nPhiBinsTempEB); + TH1F* h_template_EB[nPhiBinsTempEB][nEtaBinsTempEB][nRegionsEB]; + + std::cout << ">>> Initialize EB template" << std::endl; + for(int mod = 0; mod < nPhiBinsTempEB; ++mod) + { + for(int k = 0; k < nEtaBinsEB; ++k) + { + for(int j = 0; j < nRegionsEB; ++j) + { + TString histoName; + histoName=Form("EB_template_%d_%d_%d",mod,k,j); + TH1F* temp; + temp = new TH1F(histoName,"",50,0.,maximum); + h_template_EB[mod][k][j] = temp; + // std::cout<<"mah: "< refIdEB; + refIdEB.assign(nPhiBinsEB,0); + + for(int iphi = 0; iphi < nPhiBinsEB; ++iphi) + { + float phi = hPhiBinEB->GetBinCenter(iphi+1); + + phi = 2.*TMath::Pi() + phi + TMath::Pi()*10./180.; + phi -= int(phi/2./TMath::Pi()) * 2.*TMath::Pi(); + + int modPhi = int(phi/(2.*TMath::Pi()/nPhiBinsTempEB)); + if( modPhi == nPhiBinsTempEB ) modPhi = 0; + refIdEB.at(iphi) = modPhi; + // std::cout<GetEntries(); ++entry) + if (nEntriesMC<0) nEntriesMC = mc->GetEntries(); + for(int entry = 0; entry < nEntriesMC; ++entry) + { + if( entry%10000 == 0 ) + std::cout << "reading saved entry " << entry << "\r" << std::flush; + + mc->GetEntry(entry); + // std::cout< etaMax ) continue; + if( fabs(etaEle[iEle]) < etaMin) continue; + if( fabs(chargeEle[iEle]) !=chargeType) continue; + if( R9Ele[iEle] < R9cutEB) continue; + + float ww = 1.; + int index=0; + + // std::cout<etaMin && fabs(etaEle[iEle])FindBin(fabs(etaEle[iEle])) - 1; + if( EtabinEB == nEtaBinsEB ) EtabinEB = 0; + + // int regionId = templIndexEB(typeEB,etaEle[iEle]1,charge2,R92); + // if(regionId == -1) continue; + + if (targetTypeEB==1) + targetVariable=pAtVtxGsfEle[iEle]; + else if (targetTypeEB==2) + targetVariable=energySCEle[iEle]; + else + targetVariable=energySCEle[iEle]/(pAtVtxGsfEle[iEle]); + + // if (modPhi>=180) h_pData_EB[modPhi-180][EtabinEB][0] -> Fill((targetVariable),ww); // if you want to sum the two dees + h_template_EB[modPhi][EtabinEB][index] -> Fill((targetVariable),ww); + + // fill MC histos in eta bins + int PhibinEB = hPhiBinEB->FindBin(phiEle[iEle]) - 1; + if(PhibinEB==nPhiBinsEB) PhibinEB = 0; + + // std::cout<<"MC: fill with "< Fill(pAtVtxGsfEle[iEle],ww); // This is MC + h_phi_mc_EB[index]->Fill(phiEle[iEle],ww); + } + } + + } + + + + + //**************************** loop on DATA + + std::cout << "Loop in Data events " << endl; + + /* for (int i=0; i Fill(0); // This is DATA + } + } + } + */ + // for(int entry = 0; entry < data->GetEntries(); ++entry) + if (nEntriesData<0) nEntriesData = data->GetEntries(); + for(int entry = 0; entry < nEntriesData; ++entry) + { + if( entry%10000 == 0 ) + std::cout << "reading saved entry " << entry << "\r" << std::flush; + + data->GetEntry(entry); + + for (int iEle=0; iEle<2; iEle++) { + // if( isW == 1 ) continue; + if( fabs(etaEle[iEle]) > etaMax ) continue; + if( fabs(etaEle[iEle]) < etaMin) continue; + if( fabs(chargeEle[iEle]) != chargeType) continue; + if( R9Ele[iEle] < R9cutEB) continue; + + float ww = 1.; + int index=0; + + // int iz=0; + // DATA - ENDCAP - ele1 + if (fabs(etaEle[iEle])>etaMin && fabs(etaEle[iEle])FindBin(phiEle[iEle]) - 1; + if( PhibinEB == nPhiBinsEB ) PhibinEB = 0; + + int EtabinEB = hEtaBinEB->FindBin(fabs(etaEle[iEle])) - 1; + if( EtabinEB == nEtaBinsEB ) EtabinEB = 0; + + // int regionId = templIndexEB(typeEB,etaEle[iEle],charge,R9); + // if( regionId == -1 ) continue; + if (targetTypeEB==1) + targetVariable=pAtVtxGsfEle[iEle]; + else if (targetTypeEB==2) + targetVariable=energySCEle[iEle]; + else + targetVariable=energySCEle[iEle]/(pAtVtxGsfEle[iEle]); + + // if (PhibinEB>=180) h_pData_EB[PhibinEB-180][EtabinEB][0] -> Fill((targetVariable),ww); // if you want to sum the two dees + h_pData_EB[PhibinEB][EtabinEB][index] -> Fill((targetVariable),ww); // This is DATA + // (h_Phi_EB.at(PhibinEB)).at(index) -> Fill(phiEle[iEle]); + + h_phi_data_EB[index] -> Fill(phiEle[iEle]); + h_eta_data_EB[index] -> Fill(fabs(etaEle[iEle])); + + } + } + } + + std::cout << "End loop: Analyze events " << endl; + + + + + + + //---------------- + // Initializations + + // initialize TGraphs + TFile* o = new TFile((outputFile+"_"+typeEB+".root").c_str(),"RECREATE"); + + TGraphErrors* g_pData_EB[nEtaBinsEB][nRegionsEB];// = new TGraphErrors**[nEtaBinsEB][nRegionsEB]; + TGraphErrors* g_pAbs_EB[nEtaBinsEB][nRegionsEB];// = new TGraphErrors**[nEtaBinsEB][nRegionsEB]; + + for (int a=0; a > templateHistoFuncEB(nPhiBinsTempEB); + histoFunc* templateHistoFuncEB[nPhiBinsTempEB][nEtaBinsEB][nRegionsEB]; + + for(int mod = 0; mod < nPhiBinsTempEB; ++mod) + { + for(int k = 0; k < nEtaBinsEB; ++k) + { + for(int j = 0; j < nRegionsEB; ++j) + { + // h_template_EB[mod][k][j] -> Rebin(rebinEB); + templateHistoFuncEB[mod][k][j] = new histoFunc(h_template_EB[mod][k][j]); + } + } + } + + //------------------- + // Template Fit in EB + + if( typeEB != "none" ) + { + float pVector[nPhiBinsEB][nEtaBinsEB][2]; + float pVectorErr[nPhiBinsEB][nEtaBinsEB][2]; + + for(int i = 0; i < nPhiBinsEB; ++i) + { + for(int k = 0; k < nEtaBinsEB; ++k) + { + for(int j = 0; j < nRegionsEB; ++j) + { + float flPhi = hPhiBinEB->GetXaxis()->GetBinCenter(i); + + // (h_pMC_EB.at(i)).at(j) -> Rebin(rebinEB); + // h_pData_EB[i][k][j] -> Rebin(rebinEB); + + + // define the fitting function + // N.B. [0] * ( [1] * f( [1]*(x-[2]) ) ) + + char funcName[50]; + + sprintf(funcName,"f_pData_%d_%d_%d_Ref_%d_%d_%d_EB",i,k,j,refIdEB.at(i),k,j); + TF1* temp; + temp = new TF1(funcName, templateHistoFuncEB[refIdEB.at(i)][k][j], 0., maximum, 3, "histoFunc"); + f_pData_EB[i][k][j] = temp; + + f_pData_EB[i][k][j] -> SetParName(0,"Norm"); + f_pData_EB[i][k][j] -> SetParName(1,"Scale factor"); + + f_pData_EB[i][k][j] -> SetLineWidth(1); + f_pData_EB[i][k][j] -> SetLineColor(kGreen+2); + f_pData_EB[i][k][j] -> SetNpx(10000); + + // f_pData_EB[i][k][j] -> SetParameter(0, xNorm); + f_pData_EB[i][k][j] -> SetParameter(0, 1.); + f_pData_EB[i][k][j] -> SetParameter(1, 1); + + float shift=0.5; + if (targetTypeEB!=3) + shift=3.; + f_pData_EB[i][k][j] -> SetParameter(2, shift); + + std::cout << "***** Fitting DATA EB " << flPhi << " (" << i << "," << j << "): "; + + TFitResultPtr rp; + int fStatus; + + for(int trial = 0; trial < 300; ++trial) + { + rp = h_pData_EB[i][k][j] -> Fit(funcName, "QR+"); + fStatus = rp; + + // if( fStatus !=4 && f_pData_EB[i][k][j]->GetParError(1) != 0. && f_pData_EB[i][k][j] -> GetMaximumX(0.,500.)>30. ) + if( fStatus !=4 && f_pData_EB[i][k][j]->GetParError(1) != 0. && f_pData_EB[i][k][j] -> GetMaximumX(0.,maximum)>0. ) + { + std::cout << "fit OK "; + + double coeff = f_pData_EB[i][k][j]->GetParameter(1); + // double eee = f_pData_EB[i][k][j]->GetParError(1); + pVector[i][k][j] = coeff; + + break; + } + else if( trial %5 == 0 ) + { + pVector[i][k][j]=-1; + // std::cout<<" BAD FIT. Make another attempt with different parameters.. "< SetParameter(2, shift); + if (shift==-25) shift+=50.; + if (shift==-0.6) shift+=1.07; + // trial = 0; + // getchar(); + } + } + + // std::cout<<"media del bin "< GetMaximumX(0.,maximum)<GetParameter(2)*(f_pData_EB.at(0)).at(0)->GetParameter(1)+(h_template_EB.at(0)).at(j)->GetMean()<GetParError(1) != 0. && f_pData_EB[i][k][j] -> GetMaximumX(0.,500.)>30. ) { + if( fStatus !=4 && f_pData_EB[i][k][j]->GetParError(1) != 0. && f_pData_EB[i][k][j] -> GetMaximumX(0.,maximum)>0. ) { + pVector[i][k][j] = f_pData_EB[i][k][j] -> GetMaximumX(0.,maximum); + pVectorErr[i][k][j] = (h_pData_EB[i][k][j] -> GetRMS())/sqrt(h_pData_EB[i][k][j] -> GetEntries()); + } + else { + std::cout<<"BAD FIT!!!"<GetXaxis()->GetBinCenter(c); + int xVar=c*(int(360/nPhiBinsEB)); + + if (pVector[c][a][jc]==-1) { + // pVector[c][a][jc]=pMean[a][jc]; //if fit has failed, fill with the mean + pVector[c][a][jc]=pVector[c+1][a][jc]; //if fit has failed, fill with the mean + std::cout<<"be careful!! ("<1.15) { + if ( (pVector[c-1][a][jc]/pMean[a][jc])>1.15 ) { + g_pData_EB[a][jc] -> SetPoint(c,flPhi,pVector[c+1][a][jc]/pMean[a][jc]); + std::cout<<"caso A -iphi: "< SetPoint(c,flPhi,pVector[c-1][a][jc]/pMean[a][jc]); + std::cout<<"caso B -iphi: "< SetPoint(c,flPhi,pVector[c+1][a][jc]/pMean[a][jc]); + std::cout<<"caso C-iphi: "< SetPoint(c,flPhi,pVector[c-1][a][jc]/pMean[a][jc]); + std::cout<<"caso D-iphi: "< SetPoint(c,flPhi,pVector[c][a][jc]/pMean[a][jc]); + std::cout<<"caso E-iphi: "<180) xVar-=180; + // if (xVar>=90) continue; + //if (xVar<0) xVar+=180; + + // g_pData_EB[a][jc] -> SetPoint(c,xVar,pVector[c][a][jc]/pMean[a][jc]); + // g_pData_EB[a][jc] -> SetPoint(c,flPhi,pVector[c][a][jc]/pMean[a][jc]); + g_pAbs_EB[a][jc] -> SetPoint(c,xVar,pVector[c][a][jc]); + //g_pAbs_EB[a][jc] -> SetPoint(c,c*(int(360/nPhiBinsEB)),pVector[c][a][jc]); + histoPull_EB[a][jc] -> Fill((pVector[c][a][jc]-pMean[a][jc])/pVectorErr[c][a][jc]); + + // float err=(pVectorErr[c][a][jc]/pMean[a][jc])*(pVectorErr[c][a][jc]/pMean[a][jc])+(pVector[c][a][jc]/(pMean[a][jc]*pMean[a][jc])*(pMeanErr2[a][jc]*pMeanErr2[a][jc]))*(pVector[c][a][jc]/(pMean[a][jc]*pMean[a][jc])*(pMeanErr2[a][jc]*pMeanErr2[a][jc])); + // float err=(pVectorErr[c][a][jc]/pMean[a][jc]); + // float err=0.; + + // g_pData_EB[a][jc] -> SetPointError(c,0,err); + g_pData_EB[a][jc] -> SetPointError(c,0,0); + g_pAbs_EB[a][jc] -> SetPointError(c,0,pVectorErr[c][a][jc]); + // g_pAbs_EB[a][jc] -> SetPointError(c,0,0.); + // std::cout<GetXaxis()->GetBinCenter(i+1); + g_pData_EB[a][j] -> SetPoint(i, flPhi, 1.); + } + } + } + } + + + + std::cout<<"output"< cd(); + + for (int a=0; aGetN()!=0) g_pMC_EB[j] -> Write(Name); + Name = Form("g_pData_EB_%d_%d",a,j); + if(g_pData_EB[a][j]->GetN()!=0) g_pData_EB[a][j] -> Write(Name); + Name = Form("g_pAbs_EB_%d_%d",a,j); + if(g_pAbs_EB[a][j]->GetN()!=0) g_pAbs_EB[a][j] -> Write(Name); + //Name = Form("g_Rat_EB_%d",j); + //if(g_Rat_EB[j]->GetN()!=0) g_Rat_EB[j] -> Write(Name); + } + } + + for(int j =0; j< nRegionsEB; ++j) + { + if( h_phi_data_EB[j] -> GetEntries() !=0 ) h_phi_data_EB[j] -> Write(); + } + + h_template_EB[0][0][0] -> Write(); + // h_template_EB[0][0][1] -> Write(); + // h_template_EB[0][1][0] -> Write(); + // h_template_EB[0][1][1] -> Write(); + // h_template_EB[0][2][0] -> Write(); + // h_template_EB[0][2][1] -> Write(); + // h_template_EB[0][4][0] -> Write(); + // h_template_EB[0][4][1] -> Write(); + + for (int k=0; k Write(); + } + } + } + + for (int k=0; kWrite(); + } + } + + o -> Close(); + + + + return 0; +} + + +//////////////////////////////////Momentum correction + if(vm.count("momentumCorrectionEE")) { +///////// produce P corrections + + std::string typeEE = "eta1"; + int nRegionsEE = 3; + int nPhiBinsEE = 360; + int nPhiBinsTempEE = 1; + int nEtaBinsEE = 1; + int nEtaBinsTempEE = 1; + int rebinEE = 20; + std::string outputFile = "momentumCalibration2015_EE.root"; + int nEntriesMC = -1; + int nEntriesData = -1; + + // int nRegionsEE = GetNRegionsEE(typeEE); + + std::cout<<"REGIONI: "<GetEntries() << " entries in Data sample" << std::endl; + + // Set branch addresses + float etaSCEle[3], phiSCEle[3], etaEle[3], phiEle[3], esEnergySCEle[3], pAtVtxGsfEle[3], energySCEle[3], R9Ele[3]; + int seedXSCEle[3], seedYSCEle[3], chargeEle[3];//, seedZside; + + int debug=0; + + std::cout<<"debug: "<SetBranchStatus("*",0); + data->SetBranchStatus("etaSCEle",1); + data->SetBranchStatus("phiSCEle",1); + data->SetBranchStatus("etaEle",1); + data->SetBranchStatus("phiEle",1); + data->SetBranchStatus("rawEnergySCEle",1); + data->SetBranchStatus("energySCEle",1); + data->SetBranchStatus("esEnergySCEle",1); + data->SetBranchStatus("pAtVtxGsfEle",1); + data->SetBranchStatus("seedXSCEle",1); + data->SetBranchStatus("seedYSCEle",1); + data->SetBranchStatus("chargeEle",1); + data->SetBranchStatus("R9Ele",1); + + data->SetBranchAddress("etaSCEle", &etaSCEle); + data->SetBranchAddress("phiSCEle", &phiSCEle); + data->SetBranchAddress("etaEle", &etaEle); + data->SetBranchAddress("phiEle", &phiEle); + if (energyTypeEE==0) + data->SetBranchAddress("rawEnergySCEle", &energySCEle); + else + data->SetBranchAddress("energySCEle", &energySCEle); + data->SetBranchAddress("esEnergySCEle", &esEnergySCEle); + data->SetBranchAddress("pAtVtxGsfEle", &pAtVtxGsfEle); + //data->SetBranchAddress("energySCEle", &pAtVtxGsfEle); + data->SetBranchAddress("seedXSCEle", &seedXSCEle); + data->SetBranchAddress("seedYSCEle", &seedYSCEle); + data->SetBranchAddress("chargeEle", &chargeEle); + data->SetBranchAddress("R9Ele", &R9Ele); + + std::cout<<"debug: "<SetBranchStatus("*",0); + mc->SetBranchStatus("etaSCEle",1); + mc->SetBranchStatus("phiSCEle",1); + mc->SetBranchStatus("etaEle",1); + mc->SetBranchStatus("phiEle",1); + mc->SetBranchStatus("rawEnergySCEle",1); + mc->SetBranchStatus("energySCEle",1); + mc->SetBranchStatus("esEnergySCEle",1); + mc->SetBranchStatus("pAtVtxGsfEle",1); + mc->SetBranchStatus("seedXSCEle",1); + mc->SetBranchStatus("seedYSCEle",1); + mc->SetBranchStatus("chargeEle",1); + mc->SetBranchStatus("R9Ele",1); + + mc->SetBranchAddress("etaSCEle", &etaSCEle); + mc->SetBranchAddress("phiSCEle", &phiSCEle); + mc->SetBranchAddress("etaEle", &etaEle); + mc->SetBranchAddress("phiEle", &phiEle); + if (energyTypeEE==0) + mc->SetBranchAddress("rawEnergySCEle", &energySCEle); + else + mc->SetBranchAddress("energySCEle", &energySCEle); + mc->SetBranchAddress("esEnergySCEle", &esEnergySCEle); + mc->SetBranchAddress("pAtVtxGsfEle", &pAtVtxGsfEle); + //mc->SetBranchAddress("energySCEle", &pAtVtxGsfEle); + mc->SetBranchAddress("seedXSCEle", &seedXSCEle); + mc->SetBranchAddress("seedYSCEle", &seedYSCEle); + mc->SetBranchAddress("chargeEle", &chargeEle); + mc->SetBranchAddress("R9Ele", &R9Ele); + + std::cout<<"debug: "< > h_Phi_EE(nPhiBinsEE); // used to map iEta (as defined for Barrel and Endcap geom) into eta + // std::vector > h_Eta_EE(nEtaBinsEE); // used to map iEta (as defined for Barrel and Endcap geom) into eta + TH1F* h_pData_EE[nPhiBinsEE][nEtaBinsEE][nRegionsEE]; + // std::vector > > h_pData_EE(nPhiBinsEE); + TF1* f_pData_EE[nPhiBinsEE][nEtaBinsEE][nRegionsEE]; + + TH1F* histoPull_EE[nEtaBinsEE][nRegionsEE]; + std::cout<<"debug: "< vect1(nEtaBinsEE); + + // Initializate histos in EE + std::cout << ">>> Initialize EE histos" << std::endl; + // std::vector >tempVect(nEtaBinsEE); + for (int k=0; kSumw2(); + temp->SetFillColor(kGreen+2); + temp->SetLineColor(kGreen+2); + temp->SetFillStyle(3004); + h_pData_EE[i][k][j] = temp; + // (tempVect.at(k)).push_back(temp); + + // histoName=Form("EE_Phi_%d_%d_%d", i,k,j); + // temp = new TH1F(histoName, histoName, 360, 0., 360.); + // (h_Phi_EE.at(i)).push_back(temp); + } + + // std::cout<<"qui?"< > h_template_EE(nPhiBinsTempEE); + TH1F* h_template_EE[nPhiBinsTempEE][nEtaBinsTempEE][nRegionsEE]; + + std::cout << ">>> Initialize EE template" << std::endl; + for(int mod = 0; mod < nPhiBinsTempEE; ++mod) + { + for(int k = 0; k < nEtaBinsEE; ++k) + { + for(int j = 0; j < nRegionsEE; ++j) + { + TString histoName; + histoName=Form("EE_template_%d_%d_%d",mod,k,j); + TH1F* temp; + temp = new TH1F(histoName,"",50,0.,maximum); + h_template_EE[mod][k][j] = temp; + // std::cout<<"mah: "<GetNbinsX(); ix++) + for(int iy =0; iyGetNbinsY(); iy++) + { + mapConversionEEp->SetBinContent(ix+1,iy+1,0); + mapConversionEEm->SetBinContent(ix+1,iy+1,0); + } + + + // fill MC templates + + std::vector refIdEE; + refIdEE.assign(nPhiBinsEE,0); + + for(int iphi = 0; iphi < nPhiBinsEE; ++iphi) + { + float phi = hPhiBinEE->GetBinCenter(iphi+1); + + phi = 2.*TMath::Pi() + phi + TMath::Pi()*10./180.; + phi -= int(phi/2./TMath::Pi()) * 2.*TMath::Pi(); + + int modPhi = int(phi/(2.*TMath::Pi()/nPhiBinsTempEE)); + if( modPhi == nPhiBinsTempEE ) modPhi = 0; + refIdEE.at(iphi) = modPhi; + // std::cout<GetEntries(); ++entry) + if (nEntriesMC<0) nEntriesMC = mc->GetEntries(); + for(int entry = 0; entry < nEntriesMC; ++entry) + { + if( entry%10000 == 0 ) + std::cout << "reading saved entry " << entry << "\r" << std::flush; + + mc->GetEntry(entry); + // std::cout< etaMax ) continue; + if( fabs(etaEle[iEle]) < etaMin) continue; + if( fabs(chargeEle[iEle]) !=chargeType) continue; + if( R9Ele[iEle] < R9cutEE) continue; + + float ww = 1.; + int index=0; + + int iz=0; + // std::cout<etaMin && fabs(etaEle[iEle])0 ) { mapConversionEEp -> SetBinContent(seedXSCEle[iEle],seedYSCEle[iEle],etaEle[iEle]); iz=1; index=0; } + if( etaEle[iEle]<0 ) {mapConversionEEm -> SetBinContent(seedXSCEle[iEle],seedYSCEle[iEle],etaEle[iEle]); iz=-1; index=1; } + + int iphi = eRings->GetEndcapIphi(seedXSCEle[iEle],seedYSCEle[iEle],iz); + + // fill MC templates + int modPhi = int (iphi/(360./nPhiBinsTempEE)); + if( modPhi == nPhiBinsTempEE ) modPhi = 0; + + int EtabinEE = hEtaBinEE->FindBin(fabs(etaEle[iEle])) - 1; + if( EtabinEE == nEtaBinsEE ) EtabinEE = 0; + + // int regionId = templIndexEE(typeEE,etaEle[iEle]1,charge2,R92); + // if(regionId == -1) continue; + + if (targetTypeEE==1) + targetVariable=pAtVtxGsfEle[iEle]; + else if (targetTypeEE==2) + targetVariable=energySCEle[iEle]; + else + targetVariable=energySCEle[iEle]/(pAtVtxGsfEle[iEle]-esEnergySCEle[iEle]); + + // if (index==1) h_template_EE[modPhi][EtabinEE][0] -> Fill((targetVariable),ww); //if you want to sum EE+ and EE- + // if (modPhi>=180) h_pData_EE[modPhi-180][EtabinEE][0] -> Fill((targetVariable),ww); // if you want to sum the two dees + h_template_EE[modPhi][EtabinEE][index] -> Fill((targetVariable),ww); + h_template_EE[modPhi][EtabinEE][2] -> Fill((targetVariable),ww); //this is the sum of EE+ and EE- + + // fill MC histos in eta bins + int PhibinEE = hPhiBinEE->FindBin(phiEle[iEle]) - 1; + if(PhibinEE==nPhiBinsEE) PhibinEE = 0; + + // std::cout<<"MC: fill with "< Fill(pAtVtxGsfEle[iEle],ww); // This is MC + h_phi_mc_EE[index]->Fill(phiEle[iEle],ww); + h_phi_mc_EE[2]->Fill(phiEle[iEle],ww); + } + } + + } + + + + + //**************************** loop on DATA + + std::cout << "Loop in Data events " << endl; + + /* for (int i=0; i Fill(0); // This is DATA + } + } + } + */ + // for(int entry = 0; entry < data->GetEntries(); ++entry) + if (nEntriesData<0) nEntriesData = data->GetEntries(); + for(int entry = 0; entry < nEntriesData; ++entry) + { + if( entry%10000 == 0 ) + std::cout << "reading saved entry " << entry << "\r" << std::flush; + + data->GetEntry(entry); + + for (int iEle=0; iEle<2; iEle++) { + // if( isW == 1 ) continue; + if( fabs(etaEle[iEle]) > etaMax ) continue; + if( fabs(etaEle[iEle]) < etaMin) continue; + if( fabs(chargeEle[iEle]) != chargeType) continue; + if( R9Ele[iEle] < R9cutEE) continue; + + float ww = 1.; + int index=0; + + // int iz=0; + // DATA - ENDCAP - ele1 + if (fabs(etaEle[iEle])>etaMin && fabs(etaEle[iEle])0 ) { mapConversionEEp -> SetBinContent(seedXSCEle[iEle],seedYSCEle[iEle],etaEle[iEle]); index=0; } + if( etaEle[iEle]<0 ) { mapConversionEEm -> SetBinContent(seedXSCEle[iEle],seedYSCEle[iEle],etaEle[iEle]); index=1; } + + int PhibinEE = hPhiBinEE->FindBin(phiEle[iEle]) - 1; + if( PhibinEE == nPhiBinsEE ) PhibinEE = 0; + + int EtabinEE = hEtaBinEE->FindBin(fabs(etaEle[iEle])) - 1; + if( EtabinEE == nEtaBinsEE ) EtabinEE = 0; + + // int regionId = templIndexEE(typeEE,etaEle[iEle],charge,R9); + // if( regionId == -1 ) continue; + if (targetTypeEE==1) + targetVariable=pAtVtxGsfEle[iEle]; + else if (targetTypeEE==2) + targetVariable=energySCEle[iEle]; + else + targetVariable=energySCEle[iEle]/(pAtVtxGsfEle[iEle]-esEnergySCEle[iEle]); + + // if (PhibinEE>=180) h_pData_EE[PhibinEE-180][EtabinEE][0] -> Fill((targetVariable),ww); // if you want to sum the two dees + h_pData_EE[PhibinEE][EtabinEE][index] -> Fill((targetVariable),ww); // This is DATA + // (h_Phi_EE.at(PhibinEE)).at(index) -> Fill(phiEle[iEle]); + h_pData_EE[PhibinEE][EtabinEE][2] -> Fill((targetVariable),ww); // if you want to sum EE+ and EE- + + h_phi_data_EE[index] -> Fill(phiEle[iEle]); + h_eta_data_EE[index] -> Fill(fabs(etaEle[iEle])); + h_phi_data_EE[2] -> Fill(phiEle[iEle]); + h_eta_data_EE[2] -> Fill(fabs(etaEle[iEle])); + + } + } + } + + std::cout << "End loop: Analyze events " << endl; + + + + + + + //---------------- + // Initializations + + // initialize TGraphs + TFile* o = new TFile((outputFile+"_"+typeEE+".root").c_str(),"RECREATE"); + + TGraphErrors* g_pData_EE[nEtaBinsEE][nRegionsEE];// = new TGraphErrors**[nEtaBinsEE][nRegionsEE]; + TGraphErrors* g_pAbs_EE[nEtaBinsEE][nRegionsEE];// = new TGraphErrors**[nEtaBinsEE][nRegionsEE]; + + for (int a=0; a > templateHistoFuncEE(nPhiBinsTempEE); + histoFunc* templateHistoFuncEE[nPhiBinsTempEE][nEtaBinsEE][nRegionsEE]; + + for(int mod = 0; mod < nPhiBinsTempEE; ++mod) + { + for(int k = 0; k < nEtaBinsEE; ++k) + { + for(int j = 0; j < nRegionsEE; ++j) + { + // h_template_EE[mod][k][j] -> Rebin(rebinEE); + templateHistoFuncEE[mod][k][j] = new histoFunc(h_template_EE[mod][k][j]); + } + } + } + + //------------------- + // Template Fit in EE + + if( typeEE != "none" ) + { + float pVector[nPhiBinsEE][nEtaBinsEE][nRegionsEE]; + float pVectorErr[nPhiBinsEE][nEtaBinsEE][nRegionsEE]; + + for(int i = 0; i < nPhiBinsEE; ++i) + { + for(int k = 0; k < nEtaBinsEE; ++k) + { + for(int j = 0; j < nRegionsEE; ++j) + { + float flPhi = hPhiBinEE->GetXaxis()->GetBinCenter(i); + + // (h_pMC_EE.at(i)).at(j) -> Rebin(rebinEE); + // h_pData_EE[i][k][j] -> Rebin(rebinEE); + + + // define the fitting function + // N.B. [0] * ( [1] * f( [1]*(x-[2]) ) ) + + char funcName[50]; + + sprintf(funcName,"f_pData_%d_%d_%d_Ref_%d_%d_%d_EE",i,k,j,refIdEE.at(i),k,j); + TF1* temp; + temp = new TF1(funcName, templateHistoFuncEE[refIdEE.at(i)][k][j], 0., maximum, 3, "histoFunc"); + f_pData_EE[i][k][j] = temp; + + f_pData_EE[i][k][j] -> SetParName(0,"Norm"); + f_pData_EE[i][k][j] -> SetParName(1,"Scale factor"); + + f_pData_EE[i][k][j] -> SetLineWidth(1); + f_pData_EE[i][k][j] -> SetLineColor(kGreen+2); + f_pData_EE[i][k][j] -> SetNpx(10000); + + // f_pData_EE[i][k][j] -> SetParameter(0, xNorm); + f_pData_EE[i][k][j] -> SetParameter(0, 1.); + f_pData_EE[i][k][j] -> SetParameter(1, 1); + + float shift=0.5; + if (targetTypeEE!=3) + shift=3.; + f_pData_EE[i][k][j] -> SetParameter(2, shift); + + std::cout << "***** Fitting DATA EE " << flPhi << " (" << i << "," << j << "): "; + + TFitResultPtr rp; + int fStatus; + + for(int trial = 0; trial < 300; ++trial) + { + rp = h_pData_EE[i][k][j] -> Fit(funcName, "QR+"); + fStatus = rp; + + // if( fStatus !=4 && f_pData_EE[i][k][j]->GetParError(1) != 0. && f_pData_EE[i][k][j] -> GetMaximumX(0.,500.)>30. ) + if( fStatus !=4 && f_pData_EE[i][k][j]->GetParError(1) != 0. && f_pData_EE[i][k][j] -> GetMaximumX(0.,maximum)>0. ) + { + std::cout << "fit OK "; + + double coeff = f_pData_EE[i][k][j]->GetParameter(1); + // double eee = f_pData_EE[i][k][j]->GetParError(1); + pVector[i][k][j] = coeff; + + break; + } + else if( trial %5 == 0 ) + { + pVector[i][k][j]=-1; + // std::cout<<" BAD FIT. Make another attempt with different parameters.. "< SetParameter(2, shift); + if (shift==-25) shift+=50.; + if (shift==-0.6) shift+=1.07; + // trial = 0; + // getchar(); + } + } + + // std::cout<<"media del bin "< GetMaximumX(0.,maximum)<GetParameter(2)*(f_pData_EE.at(0)).at(0)->GetParameter(1)+(h_template_EE.at(0)).at(j)->GetMean()<GetParError(1) != 0. && f_pData_EE[i][k][j] -> GetMaximumX(0.,500.)>30. ) { + if( fStatus !=4 && f_pData_EE[i][k][j]->GetParError(1) != 0. && f_pData_EE[i][k][j] -> GetMaximumX(0.,maximum)>0. ) { + pVector[i][k][j] = f_pData_EE[i][k][j] -> GetMaximumX(0.,maximum); + pVectorErr[i][k][j] = (h_pData_EE[i][k][j] -> GetRMS())/sqrt(h_pData_EE[i][k][j] -> GetEntries()); + } + else { + std::cout<<"BAD FIT!!!"<GetXaxis()->GetBinCenter(c); + int xVar=c*(int(360/nPhiBinsEE)); + + if (pVector[c][a][jc]==-1) { + // pVector[c][a][jc]=pMean[a][jc]; //if fit has failed, fill with the mean + pVector[c][a][jc]=pVector[c+1][a][jc]; //if fit has failed, fill with the mean + std::cout<<"be careful!! ("<1.15) { + if ( (pVector[c-1][a][jc]/pMean[a][jc])>1.15 ) { + g_pData_EE[a][jc] -> SetPoint(c,flPhi,pVector[c+1][a][jc]/pMean[a][jc]); + std::cout<<"caso A -iphi: "< SetPoint(c,flPhi,pVector[c-1][a][jc]/pMean[a][jc]); + std::cout<<"caso B -iphi: "< SetPoint(c,flPhi,pVector[c+1][a][jc]/pMean[a][jc]); + std::cout<<"caso C-iphi: "< SetPoint(c,flPhi,pVector[c-1][a][jc]/pMean[a][jc]); + std::cout<<"caso D-iphi: "< SetPoint(c,flPhi,pVector[c][a][jc]/pMean[a][jc]); + std::cout<<"caso E-iphi: "<180) xVar-=180; + // if (xVar>=90) continue; + //if (xVar<0) xVar+=180; + + // g_pData_EE[a][jc] -> SetPoint(c,xVar,pVector[c][a][jc]/pMean[a][jc]); + // g_pData_EE[a][jc] -> SetPoint(c,flPhi,pVector[c][a][jc]/pMean[a][jc]); + g_pAbs_EE[a][jc] -> SetPoint(c,xVar,pVector[c][a][jc]); + //g_pAbs_EE[a][jc] -> SetPoint(c,c*(int(360/nPhiBinsEE)),pVector[c][a][jc]); + histoPull_EE[a][jc] -> Fill((pVector[c][a][jc]-pMean[a][jc])/pVectorErr[c][a][jc]); + + // float err=(pVectorErr[c][a][jc]/pMean[a][jc])*(pVectorErr[c][a][jc]/pMean[a][jc])+(pVector[c][a][jc]/(pMean[a][jc]*pMean[a][jc])*(pMeanErr2[a][jc]*pMeanErr2[a][jc]))*(pVector[c][a][jc]/(pMean[a][jc]*pMean[a][jc])*(pMeanErr2[a][jc]*pMeanErr2[a][jc])); + // float err=(pVectorErr[c][a][jc]/pMean[a][jc]); + // float err=0.; + + // g_pData_EE[a][jc] -> SetPointError(c,0,err); + g_pData_EE[a][jc] -> SetPointError(c,0,0); + g_pAbs_EE[a][jc] -> SetPointError(c,0,pVectorErr[c][a][jc]); + // g_pAbs_EE[a][jc] -> SetPointError(c,0,0.); + // std::cout<GetXaxis()->GetBinCenter(i+1); + g_pData_EE[a][j] -> SetPoint(i, flPhi, 1.); + } + } + } + } + + + + + + + //------- + // Output + + o -> cd(); + + for (int a=0; aGetN()!=0) g_pMC_EE[j] -> Write(Name); + Name = Form("g_pData_EE_%d_%d",a,j); + if(g_pData_EE[a][j]->GetN()!=0) g_pData_EE[a][j] -> Write(Name); + Name = Form("g_pAbs_EE_%d_%d",a,j); + if(g_pAbs_EE[a][j]->GetN()!=0) g_pAbs_EE[a][j] -> Write(Name); + //Name = Form("g_Rat_EE_%d",j); + //if(g_Rat_EE[j]->GetN()!=0) g_Rat_EE[j] -> Write(Name); + } + } + + for(int j =0; j< nRegionsEE; ++j) + { + if( h_phi_data_EE[j] -> GetEntries() !=0 ) h_phi_data_EE[j] -> Write(); + } + + mapConversionEEp -> Write(); + mapConversionEEm -> Write(); + + h_template_EE[0][0][0] -> Write(); + h_template_EE[0][0][1] -> Write(); + h_template_EE[0][0][2] -> Write(); + // h_template_EE[0][1][0] -> Write(); + // h_template_EE[0][1][1] -> Write(); + // h_template_EE[0][2][0] -> Write(); + // h_template_EE[0][2][1] -> Write(); + // h_template_EE[0][4][0] -> Write(); + // h_template_EE[0][4][1] -> Write(); + + for (int k=0; k Write(); + } + } + } + + for (int k=0; kWrite(); + } + } + + o -> Close(); + + + + return 0; +} + +///////////////////////LUCA + + if(vm.count("EOverPCalib") && vm.count("doEB")) { + + std::cout<<"---- START E/P CALIBRATION: BARREL ----"< > > jsonMap; + jsonMap = readJSONFile(jsonFileName); + // std::cout<<"JSON file: "< g_EoC_EB; + + // for(int i = 0; i < nRegionsEB; ++i){ + // TString Name = Form("g_pData_EB_0_%d",i); + TString Name = Form("g_EoC_EB_0"); + g_EoC_EB.push_back( (TGraphErrors*)(momentumscale->Get(Name)) ); + // } + + std::cout<<"momentum calibration file correctly opened"< g_EoE_EB; + + for(int i = 0; i < nRegionsEB; ++i){ + TString Name = Form("g_pData_EB_0_%d",i); + g_EoE_EB.push_back( (TGraphErrors*)(energyscale->Get(Name)) ); + } + + std::cout<<"energy calibration file correctly opened"<GetEntries(); + + std::cout<<"number of events: "< exit "< exit "< > > jsonMap; + jsonMap = readJSONFile(jsonFileName); + std::cout<<"JSON file: "< g_EoC_EE; + + // for(int i = 0; i < nRegionsEE; ++i){ + // TString Name = Form("g_pData_EE_0_%d",i); + TString Name = Form("g_EoC_EE_0"); + g_EoC_EE.push_back( (TGraphErrors*)(f4->Get(Name)) ); + // } + + /// open calibration energy graph + TFile* f5 = new TFile((inputEnergyScale.c_str()));//+"_"+typeEB+"_"+typeEE+".root").c_str()); + std::vector g_EoE_EE; + + for(int i = 0; i < nRegionsEE; ++i){ + TString Name = Form("g_pData_EE_0_%d",i); + g_EoE_EE.push_back( (TGraphErrors*)(f5->Get(Name)) ); + } + + ///Use the whole sample statistics if numberOfEvents < 0 + if ( numberOfEvents < 0 ) numberOfEvents = data->GetEntries(); + + + /// run in normal mode: full statistics + if ( splitStat == 0 ) { + + TString name ; + TString name_tmp; + + if(isMiscalib == true && useZ == 1 && isR9selection ==true && isEPselection == false && isfbrem == false && isPtCut ==false ) + name_tmp = Form ("%s_WZ_R9_miscalib_EE",outputFile.c_str()); + else if(isMiscalib == true && useZ == 1 && isR9selection ==false && isEPselection == false && isfbrem == true && isPtCut ==false ) + name_tmp = Form ("%s_WZ_Fbrem_miscalib_EE",outputFile.c_str()); + else if(isMiscalib == true && useZ == 1 && isR9selection ==true && isEPselection == false && isfbrem == false && isPtCut ==true ) + name_tmp = Form ("%s_WZ_PT_miscalib_EE",outputFile.c_str()); + else if(isMiscalib == true && useZ == 1 && isR9selection ==true && isEPselection == true && isfbrem == false && isPtCut ==false ) + name_tmp = Form ("%s_WZ_EP_miscalib_EE",outputFile.c_str()); + else if(isMiscalib == true && useZ == 1 && isEPselection ==false && isR9selection==false && isPtCut ==false && isfbrem ==false ) + name_tmp =Form ("%s_WZ_noEP_miscalib_EE",outputFile.c_str()); + + else if(isMiscalib == false && useZ == 1 && isR9selection ==true && isEPselection == false && isfbrem == false && isPtCut ==false ) + name_tmp = Form ("%s_WZ_R9_EE",outputFile.c_str()); + else if(isMiscalib == false && useZ == 1 && isR9selection ==false && isEPselection == false && isfbrem == true && isPtCut ==false ) + name_tmp = Form ("%s_WZ_Fbrem_EE",outputFile.c_str()); + else if(isMiscalib == false && useZ == 1 && isR9selection ==true && isEPselection == false && isfbrem == false && isPtCut ==true ) + name_tmp = Form ("%s_WZ_PT_EE",outputFile.c_str()); + else if(isMiscalib == false && useZ == 1 && isR9selection ==true && isEPselection == true && isfbrem == false && isPtCut ==false ) + name_tmp = Form ("%s_WZ_EP_EE",outputFile.c_str()); + else if(isMiscalib == false && useZ == 1 && isEPselection ==false && isR9selection==false && isPtCut ==false && isfbrem ==false ) + name_tmp =Form ("%s_WZ_noEP_EE",outputFile.c_str()); + + + + else if(isMiscalib == true && useZ == 0 && isR9selection ==true && isEPselection == false && isfbrem == false && isPtCut ==false ) + name_tmp = Form ("%s_W_R9_miscalib_EE",outputFile.c_str()); + else if(isMiscalib == true && useZ == 0 && isR9selection ==false && isEPselection == false && isfbrem == true && isPtCut ==false ) + name_tmp = Form ("%s_W_Fbrem_miscalib_EE",outputFile.c_str()); + else if(isMiscalib == true && useZ == 0 && isR9selection ==true && isEPselection == false && isfbrem == false && isPtCut ==true ) + name_tmp = Form ("%s_W_PT_miscalib_EE",outputFile.c_str()); + else if(isMiscalib == true && useZ == 0 && isR9selection ==true && isEPselection == true && isfbrem == false && isPtCut ==false ) + name_tmp = Form ("%s_W_EP_miscalib_EE",outputFile.c_str()); + else if(isMiscalib == true && useZ == 0 && isEPselection ==false && isR9selection==false && isPtCut ==false && isfbrem ==false ) + name_tmp =Form ("%s_W_noEP_miscalib_EE",outputFile.c_str()); + + else if(isMiscalib == false && useZ == 0 && isR9selection ==true && isEPselection == false && isfbrem == false && isPtCut ==false ) + name_tmp = Form ("%s_WZ_R9_EE",outputFile.c_str()); + else if(isMiscalib == false && useZ == 0 && isR9selection ==false && isEPselection == false && isfbrem == true && isPtCut ==false ) + name_tmp = Form ("%s_W_Fbrem_EE",outputFile.c_str()); + else if(isMiscalib == false && useZ == 0 && isR9selection ==true && isEPselection == false && isfbrem == false && isPtCut ==true ) + name_tmp = Form ("%s_W_PT_EE",outputFile.c_str()); + else if(isMiscalib == false && useZ == 0 && isR9selection ==true && isEPselection == true && isfbrem == false && isPtCut ==false ) + name_tmp = Form ("%s_W_EP_EE",outputFile.c_str()); + else if(isMiscalib == false && useZ == 0 && isEPselection ==false && isR9selection==false && isPtCut ==false && isfbrem ==false ) + name_tmp =Form ("%s_W_noEP_EE",outputFile.c_str()); + else { std::cout<<" Option not considered --> exit "< exit "<::const_iterator category_itr=categories.begin(); + category_itr != categories.end(); + category_itr++){ + myClock.Start(); +#ifdef DEBUG + std::cout << "[DEBUG] category: " << *category_itr << std::endl; +#endif + if (vm.count("runToy")) { + cout << "number of toys: "<floatParsFinal()); + sh.SetMinuit(m); + //ph.SetVariables(); + //ph.SetCovMatrix(fitres->covarianceMatrix()); + //ph.SetUpdateProposalParameters(kTRUE); // auto-create mean vars and add mappings + //ph.SetCacheSize(100); + //ProposalFunction* pf = ph.GetProposalFunction(); + + if(minimType=="migrad"){ + + //fitres = + m.fit(""); + //m.migrad(); + //m.hesse(); + } else if(minimType=="profile"){ + MinimizationProfile(smearer, args, nIter); + args.writeToStream(std::cout, kFALSE); + } else if(minimType=="MCMC"){ + MinimizationProfile(smearer, args, nIter, true); + args.writeToStream(std::cout, kFALSE); + } else if(minimType=="sampling"){ + RooArgList argList_(args); + TIterator *it_ = argList_.createIterator(); + for(RooRealVar *var = (RooRealVar*)it_->Next(); var != NULL; var = (RooRealVar*)it_->Next()){ + if (var->isConstant() || !var->isLValue()) continue; + TString name(var->GetName()); + if(name.Contains("scale")) var->setConstant(); + } + + RooStats::ProposalHelper ph; + ph.SetVariables(args); + ph.SetCovMatrix(*(smearer._markov.GetAsDataSet()->covarianceMatrix(args))); + ph.SetUniformFraction(0.05); + ph.SetWidthRangeDivisor(2); + + RooStats::MetropolisHastings MCMC(smearer, args, *(ph.GetProposalFunction()), nIter); + MCMC.SetNumBurnInSteps(10); + MCMC.SetSign(RooStats::MetropolisHastings::kNegative); + MCMC.SetType(RooStats::MetropolisHastings::kLog); + //MCMC.SetProposalFunction(sh); + RooStats::MarkovChain *mcChain = (MCMC.ConstructChain()); + mcChain->SaveAs("tmp/newChain.root"); + delete mcChain; + + } + } + + std::cout << "[INFO] Minimization time: \t"; + myClock.Stop(); + myClock.Print(); + if(!vm.count("profileOnly") && !vm.count("plotOnly")){ + args.writeToFile(outDirFitResData+"/params-"+r+"-"+TString(commonCut.c_str())+".txt"); + smearer._markov.SaveAs((outDirFitResData+"/markov-"+r+"-"+TString(commonCut.c_str())+".root")); + } + + //RooDataSet *dSet = smearer.GetMarkovChainAsDataSet(); + //dSet->SaveAs("tmp/dataset.root"); + //save the smeared histograms + + for(std::vector::iterator itr= smearer.ZeeCategories.begin(); + itr != smearer.ZeeCategories.end(); + itr++){ + smearer.GetSmearedHisto(*itr, true, false); + smearer.GetSmearedHisto(*itr, true, true); + smearer.GetSmearedHisto(*itr, false, smearer._isDataSmeared); + } + + if(vm.count("plotOnly") || !vm.count("profileOnly")){ + TFile *f = new TFile(outDirFitResData+"/histos-"+r+"-"+TString(commonCut.c_str())+".root", "recreate"); + f->Print(); + f->cd(); + for(std::vector::iterator itr= smearer.ZeeCategories.begin(); + itr != smearer.ZeeCategories.end(); + itr++){ + //if(!itr->active) continue; + TH1F *MC = smearer.GetSmearedHisto(*itr, true, false); + TH1F *smearMC = smearer.GetSmearedHisto(*itr, true, true); + TH1F *data = smearer.GetSmearedHisto(*itr, false, smearer._isDataSmeared); + + MC->Write(); + smearMC->Write(); + data->Write(); + f->Write(); + } + f->Close(); + } + + if(vm.count("profileOnly") || !vm.count("plotOnly")){ + //if(vm.count("profileOnly") && !vm.count("runToy")) smearer.SetNSmear(10); + + std::cout <<"==================PROFILE=================="<isConstant()) + continue; + + TString name(var->GetName()); + //if(name.Contains("scale")) continue; + //if(name.Contains("absEta_1_1.4442-gold") && vm.count("alphaGoldFix")) continue; + // special part for alpha fitting + double min=0.; + TString alphaName=name; alphaName.ReplaceAll("constTerm","alpha"); + RooRealVar *var2= name.Contains("constTerm") ? (RooRealVar *)argList.find(alphaName): NULL; + if(var2!=NULL && name.Contains("constTerm") && var2->isConstant()==false){ + TString name2 = name; + + double rho=0, Emean=0; + smearer.SetDataSet(name,TString(var->GetName())+TString(var2->GetName())); + if(vm.count("constTermFix")) MinProfile2D(var, var2, smearer, -1, 0., min, rho, Emean, false); + smearer.dataset->Write(); + + // rho profile + name2.ReplaceAll("constTerm", "rho"); + smearer.SetDataSet(name2,"rho"); + Double_t v1=var->getVal(); + Double_t v2=var2->getVal(); + var2->setVal(0); + var->setVal(rho); + TGraph *profil = NULL; + profil = GetProfile(var, smearer,0); + var2->setVal(v2); + var->setVal(v1); + TString n="profileChi2_"+name2+"_"; n+=randomInt; + profil->SetName(n); + TCanvas c("c_"+name); + profil->Draw("AP*"); + fOutProfile->cd(); + profil->Write(); + delete profil; + smearer.dataset->Write(); + + + // phi profile + name2.ReplaceAll("rho", "phi"); + smearer.SetDataSet(name2,"phi"); + profil = GetProfile(var, var2, smearer, true, rho, Emean); + n="profileChi2_"+name2+"_"; n+=randomInt; + profil->SetName(n); + profil->Draw("AP*"); + fOutProfile->cd(); + profil->Write(); + delete profil; + smearer.dataset->Write(); + + // rho profile with fixed phi!=pi/2 + name2.ReplaceAll("phi", "rho_phi4"); + smearer.SetDataSet(name2,"rho_phi4"); + profil = GetProfile(var, var2, smearer, true, 0, Emean, 0.785); + n="profileChi2_"+name2+"_"; n+=randomInt; + profil->SetName(n); + profil->Draw("AP*"); + fOutProfile->cd(); + profil->Write(); + delete profil; + smearer.dataset->Write(); + +// // rho profile with fixed phi!=pi/2 +// name2.ReplaceAll("rho_phi4", "rho_phi6"); +// smearer.SetDataSet(name2,"rho_phi6"); +// profil = GetProfile(var, var2, smearer, true, 0, Emean, 0.524); +// n="profileChi2_"+name2+"_"; n+=randomInt; +// profil->SetName(n); +// profil->Draw("AP*"); +// fOutProfile->cd(); +// profil->Write(); +// delete profil; +// smearer.dataset->Write(); + +// // rho profile with fixed phi!=pi/2 +// name2.ReplaceAll("rho_phi6", "rho_phi3"); +// smearer.SetDataSet(name2,"rho_phi3"); +// profil = GetProfile(var, var2, smearer, true, 0, Emean, 1.05); +// n="profileChi2_"+name2+"_"; n+=randomInt; +// profil->SetName(n); +// profil->Draw("AP*"); +// fOutProfile->cd(); +// profil->Write(); +// delete profil; +// smearer.dataset->Write(); + + + } + + //if(!name.Contains("scale")) continue; + std::cout << "Doing " << name << "\t" << var->getVal() << std::endl; + smearer.SetDataSet(name,name); + // if(vm.count("runToy")){ + // MinProfile(var, smearer, -1, 0., min, false); + //} + TGraph *profil = GetProfile(var, smearer,0); + TString n="profileChi2_"+name+"_"; n+=randomInt; + profil->SetName(n); + TCanvas c("c_"+name); + profil->Draw("AP*"); + fOutProfile->cd(); + profil->Write(); + std::cout << "Saved profile for " << name << std::endl; + smearer.dataset->Write(); + delete profil; + } + std::cout << "Cloning args" << std::endl; + // RooArgSet *mu = (RooArgSet *)args.snapshot(); + //std::cout << "creating roomultivargaussian" << std::endl; + //RooMultiVarGaussian g("multi","",args, *mu, *(smearer.GetMarkovChainAsDataSet()->covarianceMatrix())); + //std::cout << "created" << std::endl; + + // RooDataSet *dataset = g.generate(args,10); + // for(Long64_t iGen=0; iGen<1; iGen++){ + // RooArgList argList_(* dataset->get(iGen)); + // TIterator *it_ = argList_.createIterator(); + // for(RooRealVar *var = (RooRealVar*)it_->Next(); var != NULL; var = (RooRealVar*)it_->Next()){ + // if (!var->isLValue()) continue; + // TString name(var->GetName()); + // //std::cout << name << var->getVal() << std::endl; + // var->Print(); + // //args.setRealValue(name,var->getVal()); +// } +// //smearer.evaluate(); +// } + fOutProfile->Close(); + + } + } + tmpFile->Close(); + globalClock.Stop(); + std::cout << "[INFO] Total elapsed time: "; globalClock.Print(); + return 0; +} + + +// LocalWords: etaSCEle diff --git a/ZFitter/data/validation/EoverPcalibration_test.dat b/ZFitter/data/validation/EoverPcalibration_test.dat new file mode 100644 index 00000000000..f061a15861d --- /dev/null +++ b/ZFitter/data/validation/EoverPcalibration_test.dat @@ -0,0 +1,36 @@ +#################input list for the E/p calibration ############################ +#d selected /afs/cern.ch/user/l/lbrianza/work/public/ntuple_numEvent100.root +#d extraCalibTree /afs/cern.ch/user/l/lbrianza/work/public/extraCalibTree.root +#d selected /afs/cern.ch/user/l/lbrianza/work/public/RUND_DoubleElectron.root + +#d selected root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalMIBI/lbrianza/DoubleElectron/ntuple_multifit50ns.root +#d extraCalibTree root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalMIBI/lbrianza/DoubleElectron/extraCalibTree_multifit50ns.root +#d selected root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalMIBI/lbrianza/DoubleElectron/ntuple_multifit25ns.root +#d extraCalibTree root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalMIBI/lbrianza/DoubleElectron/extraCalibTree_multifit25ns.root +#d selected root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalMIBI/lbrianza/DoubleElectron/ntuple_oldweight.root +#d extraCalibTree root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalMIBI/lbrianza/DoubleElectron/extraCalibTree_oldweight.root + + +d extraCalibTree root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Nov2015_PS_v3/DoubleEG-ZSkim-Run2015D-Prompt-v3-25nsReco/256584-257611/246908-260426-Prompt_25ns-v1-full5x5fix-golden_silver/eop/extraCalibTree-unmerged-allRange.root +d selected root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Nov2015_PS_v3/DoubleEG-ZSkim-Run2015D-Prompt-v3-25nsReco/256584-257611/246908-260426-Prompt_25ns-v1-full5x5fix-golden_silver/eop/unmerged-allRange.root +d extraCalibTree root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Nov2015_PS_v3/DoubleEG-ZSkim-Run2015D-Prompt-v3-25nsReco/257612-258158/246908-260426-Prompt_25ns-v1-full5x5fix-golden_silver/eop/extraCalibTree-unmerged-allRange.root +d selected root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Nov2015_PS_v3/DoubleEG-ZSkim-Run2015D-Prompt-v3-25nsReco/257612-258158/246908-260426-Prompt_25ns-v1-full5x5fix-golden_silver/eop/unmerged-allRange.root +d extraCalibTree root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Nov2015_PS_v3/DoubleEG-ZSkim-Run2015D-Prompt-v4-25nsReco/258159-260737/246908-260426-Prompt_25ns-v1-full5x5fix-golden_silver/eop/extraCalibTree-unmerged-allRange.root +d selected root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Nov2015_PS_v3/DoubleEG-ZSkim-Run2015D-Prompt-v4-25nsReco/258159-260737/246908-260426-Prompt_25ns-v1-full5x5fix-golden_silver/eop/unmerged-allRange.root + +d extraCalibTree root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Nov2015_PS_v3/SingleElectron-WSkim-Run2015D-Prompt-v3-25nsReco/257612-258158/246908-260426-Prompt_25ns-v1-full5x5fix-golden_silver/eop/extraCalibTree-unmerged-allRange.root +d selected root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Nov2015_PS_v3/SingleElectron-WSkim-Run2015D-Prompt-v3-25nsReco/257612-258158/246908-260426-Prompt_25ns-v1-full5x5fix-golden_silver/eop/unmerged-allRange.root + + + + +s extraCalibTree root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Nov2015_PS_v3/DoubleEG-ZSkim-Run2015D-Prompt-v3-25nsReco/256584-257611/246908-260426-Prompt_25ns-v1-full5x5fix-golden_silver/eop/extraCalibTree-unmerged-allRange.root +s selected root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Nov2015_PS_v3/DoubleEG-ZSkim-Run2015D-Prompt-v3-25nsReco/256584-257611/246908-260426-Prompt_25ns-v1-full5x5fix-golden_silver/eop/unmerged-allRange.root +s extraCalibTree root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Nov2015_PS_v3/DoubleEG-ZSkim-Run2015D-Prompt-v3-25nsReco/257612-258158/246908-260426-Prompt_25ns-v1-full5x5fix-golden_silver/eop/extraCalibTree-unmerged-allRange.root +s selected root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Nov2015_PS_v3/DoubleEG-ZSkim-Run2015D-Prompt-v3-25nsReco/257612-258158/246908-260426-Prompt_25ns-v1-full5x5fix-golden_silver/eop/unmerged-allRange.root +s extraCalibTree root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Nov2015_PS_v3/DoubleEG-ZSkim-Run2015D-Prompt-v4-25nsReco/258159-260737/246908-260426-Prompt_25ns-v1-full5x5fix-golden_silver/eop/extraCalibTree-unmerged-allRange.root +s selected root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Nov2015_PS_v3/DoubleEG-ZSkim-Run2015D-Prompt-v4-25nsReco/258159-260737/246908-260426-Prompt_25ns-v1-full5x5fix-golden_silver/eop/unmerged-allRange.root + +s extraCalibTree root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Nov2015_PS_v3/SingleElectron-WSkim-Run2015D-Prompt-v3-25nsReco/257612-258158/246908-260426-Prompt_25ns-v1-full5x5fix-golden_silver/eop/extraCalibTree-unmerged-allRange.root +s selected root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Nov2015_PS_v3/SingleElectron-WSkim-Run2015D-Prompt-v3-25nsReco/257612-258158/246908-260426-Prompt_25ns-v1-full5x5fix-golden_silver/eop/unmerged-allRange.root + diff --git a/ZFitter/data/validation/EoverPcalibration.dat b/ZFitter/data/validation/MC_EoverPcalibration.dat similarity index 63% rename from ZFitter/data/validation/EoverPcalibration.dat rename to ZFitter/data/validation/MC_EoverPcalibration.dat index e309dd86910..eee6da9d17f 100644 --- a/ZFitter/data/validation/EoverPcalibration.dat +++ b/ZFitter/data/validation/MC_EoverPcalibration.dat @@ -7,5 +7,10 @@ #d extraCalibTree root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalMIBI/lbrianza/DoubleElectron/extraCalibTree_multifit50ns.root #d selected root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalMIBI/lbrianza/DoubleElectron/ntuple_multifit25ns.root #d extraCalibTree root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalMIBI/lbrianza/DoubleElectron/extraCalibTree_multifit25ns.root -d selected root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalMIBI/lbrianza/DoubleElectron/ntuple_oldweight.root -d extraCalibTree root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalMIBI/lbrianza/DoubleElectron/extraCalibTree_oldweight.root +#d selected root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalMIBI/lbrianza/DoubleElectron/ntuple_oldweight.root +#d extraCalibTree root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalMIBI/lbrianza/DoubleElectron/extraCalibTree_oldweight.root + +d selected /afs/cern.ch/user/l/lbrianza/work/public/ntupleEoP/DYJets_amctnlo-RunIISpring15DR74-Asym25ns-allRange.root + +s selected /afs/cern.ch/user/l/lbrianza/work/public/ntupleEoP/DYJets_amctnlo-RunIISpring15DR74-Asym25ns-allRange.root + diff --git a/ZFitter/data/validation/monitoring_2015.dat b/ZFitter/data/validation/monitoring_2015.dat new file mode 100644 index 00000000000..c7b3c671a82 --- /dev/null +++ b/ZFitter/data/validation/monitoring_2015.dat @@ -0,0 +1,33 @@ +# list of files to run on +# type treeName fileName +# files are added to the same chain if they have the same treeName and the same type +# chain with the same type are added as friends +# only three type are admitted: s (signal), b (bkg), d (data) +# all treeName are admitted, but some are mandatory: +# selected +# some are special: pileup, scaleEleHggRunEta, scaleEleHggRunEtaR9 +s1 selected root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARECOSIM/DYJetsToLL_M-50_13TeV-Asympt50ns-pythia8_16Jun15_v3/allRange/v3/DYJetsToLL_M-50_13TeV-Asympt50ns-pythia8_16Jun15_v3-allRange.root +s2 selected root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARECOSIM/DYJetsToLL_M-50_13TeV-StartupFlat10to50-pythia8_11Jun15_v1/allRange/v3/DYJetsToLL_M-50_13TeV-StartupFlat10to50-pythia8_11Jun15_v1-allRange.root +#s selected root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARECOSIM/DYJetsToLL_M-50_13TeV-StartupFlat10to50-pythia8_11Jun15_v1/allRange/DYJetsToLL_M-50_13TeV-StartupFlat10to50-pythia8_11Jun15_v1-allRange.root + +d pileupHist /afs/cern.ch/cms/CAF/CMSALCA/ALCA_ECALCALIB/ECALELF/puFiles/190456-208686-13Julv2_Prompt_Moriond2013.69400.observed.root +s pileupHist /afs/cern.ch/cms/CAF/CMSALCA/ALCA_ECALCALIB/ECALELF/puFiles/nPU-Summer12_DD3.observed.root +d selected root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/Run2015B_TEMP/ntuple_DoubleElectron-ZSkim-RUN2015D-13Jul15-v1.root + +### OLD (2012) +#s pileupTree /afs/cern.ch/cms/CAF/CMSALCA/ALCA_ECALCALIB/ECALELF/puFiles/tree-nPU-Summer12_DD3-190456-203002-13Jul_PromptTS.69400.observed.root +#d corr DoubleElectron-ZSkim-RUN2012C-v3-201230-201678-JSON_201230-201678-Prompt.root +#s pileup mcPUtree.root +#s selected root://eoscms//eos/cms/store/caf/user/shervin/calibration/8TeV/ZNtuples/ALCARECOSIM/DYJets-Summer12-START53-ZSkim/allRange/DYJets-Summer12-START53-ZSkim-allRange.root +#d pileupHist /afs/cern.ch/cms/CAF/CMSALCA/ALCA_ECALCALIB/ECALELF/puFiles/190456-204567-13Julv2_lastPrompt.69400.observed.root +#d selected root://eoscms//eos/cms/store/caf/user/shervin/calibration/8TeV/ZNtuples/alcareco/DoubleElectron-RUN2012A-v1-06Aug-recover/190782-190949/190782-190949-06Aug/DoubleElectron-RUN2012A-v1-06Aug-recover-190782-190949.root +#d selected root://eoscms//eos/cms/store/caf/user/shervin/calibration/8TeV/ZNtuples/alcareco/DoubleElectron-ZSkim-RUN2012A-13Jul-v1/190456-193621/190456-203002-13Jul_PromptTS/DoubleElectron-ZSkim-RUN2012A-13Jul-v1-190456-193621.root +#d selected root://eoscms//eos/cms/store/caf/user/shervin/calibration/8TeV/ZNtuples/alcareco/DoubleElectron-ZSkim-RUN2012B-13Jul-v1/193834-196531/190456-204567-13Julv2_Prompt/DoubleElectron-ZSkim-RUN2012B-13Jul-v1-193834-196531.root +#d selected root://eoscms//eos/cms/store/caf/user/shervin/calibration/8TeV/ZNtuples/alcareco/DoubleElectron-ZSkim-RUN2012C-v2/198111-198913/190456-204567-13Julv2_Prompt/DoubleElectron-ZSkim-RUN2012C-v2-198111-198913.root +#d selected root://eoscms//eos/cms/store/caf/user/shervin/calibration/8TeV/ZNtuples/alcareco/DoubleElectron-ZSkim-RUN2012C-24Aug-v1/198022-198523/198022-198523-24Aug/DoubleElectron-ZSkim-RUN2012C-24Aug-v1-198022-198523.root +#d selected root://eoscms//eos/cms/store/caf/user/shervin/calibration/8TeV/ZNtuples/alcareco/DoubleElectron-ZSkim-RUN2012C-v3/198934-201678/190456-203002-13Jul_PromptTS/DoubleElectron-ZSkim-RUN2012C-v3-198934-201678.root +#d selected root://eoscms//eos/cms/store/caf/user/shervin/calibration/8TeV/ZNtuples/alcareco/DoubleElectron-ZSkim-RUN2012C-v3/201679-202016/190456-203002-13Jul_PromptTS/DoubleElectron-ZSkim-RUN2012C-v3-201679-202016.root +#d selected root://eoscms//eos/cms/store/caf/user/shervin/calibration/8TeV/ZNtuples/alcareco/DoubleElectron-ZSkim-RUN2012C-v3/202017-202305/190456-203002-13Jul_PromptTS/DoubleElectron-ZSkim-RUN2012C-v3-202017-202305.root +#d selected root://eoscms//eos/cms/store/caf/user/shervin/calibration/8TeV/ZNtuples/alcareco/DoubleElectron-ZSkim-RUN2012C-v3/202306-203002/190456-203002-13Jul_PromptTS/DoubleElectron-ZSkim-RUN2012C-v3-202306-203002.root +#d selected root://eoscms//eos/cms/store/caf/user/shervin/calibration/8TeV/ZNtuples/alcareco/DoubleElectron-ZSkim-RUN2012C-v3/203003-203755/190456-203853_13Jul_Prompt/DoubleElectron-ZSkim-RUN2012C-v3-203003-203755.root +#d selected root://eoscms//eos/cms/store/caf/user/shervin/calibration/8TeV/ZNtuples/officialAlcareco/DoubleElectron-ZAlcaSkim-RUN2012D-v1/203773-208686/190456-208686-13Julv2_Prompt/DoubleElectron-ZAlcaSkim-RUN2012D-v1-203773-208686.root diff --git a/ZFitter/data/validation/monitoring_LC_with_EP_2015.dat b/ZFitter/data/validation/monitoring_LC_with_EP_2015.dat new file mode 100644 index 00000000000..64733ced4bc --- /dev/null +++ b/ZFitter/data/validation/monitoring_LC_with_EP_2015.dat @@ -0,0 +1,51 @@ +#s selected root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARECOSIM/DYJetsToLL_M-50_13TeV-Asympt50ns-pythia8_16Jun15_v3/allRange/v3/DYJetsToLL_M-50_13TeV-Asympt50ns-pythia8_16Jun15_v3-allRange.root +#d selected root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/Run2015B_TEMP/ntuple_DoubleElectron-ZSkim-RUN2015D-13Jul15-v1.root +#s selected root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/Run2015B_TEMP/ntuple_DoubleElectron-ZSkim-RUN2015D-13Jul15-v1.root + +#------------------------new ntuples DATA----------------------- + +#------ntuples runB-------- + +d extraCalibTree root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/test_7_10_50ns/SingleElectron-WSkim-RUN2015B-ALCARAW-21Jul15-v2/251022-251883/Cert_246908-255031_13TeV_PromptReco_Collisions15_50ns_JSON/SingleElectron-WSkim-RUN2015B-ALCARAW-21Jul15-v2-251022-251883_extraCalibTree.root +d selected root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/test_7_10_50ns/SingleElectron-WSkim-RUN2015B-ALCARAW-21Jul15-v2/251022-251883/Cert_246908-255031_13TeV_PromptReco_Collisions15_50ns_JSON/SingleElectron-WSkim-RUN2015B-ALCARAW-21Jul15-v2-251022-251883.root + + +#------ntuples runC-------- + +d extraCalibTree root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/phiSym_materialCorrection_ref/SingleElectron-WSkim-Run2015C-Prompt-v1-25nsReco/253620-254914/246908-258750-Prompt_25ns-v1/extraCalibTree-unmerged-allRange.root +d selected root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/phiSym_materialCorrection_ref/SingleElectron-WSkim-Run2015C-Prompt-v1-25nsReco/253620-254914/246908-258750-Prompt_25ns-v1/unmerged-allRange.root + +#-------ntuples runD--------- + +d extraCalibTree root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/phiSym_materialCorrection_ref/SingleElectron-WSkim-Run2015D-Prompt-v3-25nsReco/256584-257611/246908-258750-Prompt_25ns-v1/extraCalibTree-unmerged-allRange.root +d selected root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/phiSym_materialCorrection_ref/SingleElectron-WSkim-Run2015D-Prompt-v3-25nsReco/256584-257611/246908-258750-Prompt_25ns-v1/unmerged-allRange.root + +d extraCalibTree root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/phiSym_materialCorrection_ref/SingleElectron-WSkim-Run2015D-Prompt-v3-25nsReco/257612-258158/246908-258750-Prompt_25ns-v1/extraCalibTree-unmerged-allRange.root +d selected root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/phiSym_materialCorrection_ref/SingleElectron-WSkim-Run2015D-Prompt-v3-25nsReco/257612-258158/246908-258750-Prompt_25ns-v1/unmerged-allRange.root + +d extraCalibTree root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/phiSym_materialCorrection_ref/SingleElectron-WSkim-Run2015D-Prompt-v4-25nsReco/258159-258959/246908-258750-Prompt_25ns-v1/extraCalibTree-unmerged-allRange.root +d selected root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/phiSym_materialCorrection_ref/SingleElectron-WSkim-Run2015D-Prompt-v4-25nsReco/258159-258959/246908-258750-Prompt_25ns-v1/unmerged-allRange.root + + +#----------------------new ntuples TEMPLATE------------------------ + +#------ntuples runB-------- + +s extraCalibTree root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/test_7_10_50ns/SingleElectron-WSkim-RUN2015B-ALCARAW-21Jul15-v2/251022-251883/Cert_246908-255031_13TeV_PromptReco_Collisions15_50ns_JSON/SingleElectron-WSkim-RUN2015B-ALCARAW-21Jul15-v2-251022-251883_extraCalibTree.root +s selected root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/test_7_10_50ns/SingleElectron-WSkim-RUN2015B-ALCARAW-21Jul15-v2/251022-251883/Cert_246908-255031_13TeV_PromptReco_Collisions15_50ns_JSON/SingleElectron-WSkim-RUN2015B-ALCARAW-21Jul15-v2-251022-251883.root + +#------ntuples runC-------- + +s extraCalibTree root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/phiSym_materialCorrection_ref/SingleElectron-WSkim-Run2015C-Prompt-v1-25nsReco/253620-254914/246908-258750-Prompt_25ns-v1/extraCalibTree-unmerged-allRange.root +s selected root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/phiSym_materialCorrection_ref/SingleElectron-WSkim-Run2015C-Prompt-v1-25nsReco/253620-254914/246908-258750-Prompt_25ns-v1/unmerged-allRange.root + +#-------ntuples runD--------- + +s extraCalibTree root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/phiSym_materialCorrection_ref/SingleElectron-WSkim-Run2015D-Prompt-v3-25nsReco/256584-257611/246908-258750-Prompt_25ns-v1/extraCalibTree-unmerged-allRange.root +s selected root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/phiSym_materialCorrection_ref/SingleElectron-WSkim-Run2015D-Prompt-v3-25nsReco/256584-257611/246908-258750-Prompt_25ns-v1/unmerged-allRange.root + +s extraCalibTree root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/phiSym_materialCorrection_ref/SingleElectron-WSkim-Run2015D-Prompt-v3-25nsReco/257612-258158/246908-258750-Prompt_25ns-v1/extraCalibTree-unmerged-allRange.root +s selected root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/phiSym_materialCorrection_ref/SingleElectron-WSkim-Run2015D-Prompt-v3-25nsReco/257612-258158/246908-258750-Prompt_25ns-v1/unmerged-allRange.root + +s extraCalibTree root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/phiSym_materialCorrection_ref/SingleElectron-WSkim-Run2015D-Prompt-v4-25nsReco/258159-258959/246908-258750-Prompt_25ns-v1/extraCalibTree-unmerged-allRange.root +s selected root://eoscms//eos/cms/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/phiSym_materialCorrection_ref/SingleElectron-WSkim-Run2015D-Prompt-v4-25nsReco/258159-258959/246908-258750-Prompt_25ns-v1/unmerged-allRange.root \ No newline at end of file diff --git a/ZFitter/src/ZFit_class.cc b/ZFitter/src/ZFit_class.cc index 45ef8f0409d..a01c7068956 100644 --- a/ZFitter/src/ZFit_class.cc +++ b/ZFitter/src/ZFit_class.cc @@ -493,54 +493,53 @@ double ZFit_class::GetEffectiveSigma(RooAbsData *dataset, float quant=0.68){ // if(invMass_highBinning==NULL) invMass_highBinning = dataset->createHistogram(invMass.GetName(),invMass.getBins("plotRange")); if(invMass_highBinning==NULL) invMass_highBinning = dataset->createHistogram(invMass.GetName(),6000); - TH1* h = invMass_highBinning; + // TH1* h = dataset->createHistogram(invMass.GetName(),invMass.getBins("plotRange")*25); //200*25=5000 bins = 0.01 GeV/bin + TH1* h = dataset->createHistogram(invMass.GetName(),5000); //200*25=5000 bins = 0.01 GeV/bin double TotEvents = h->Integral(1, h->GetNbinsX()-1); double LocEvents = 0.; int binI = h->FindBin(h->GetMean()); int binF = h->GetNbinsX()-1; - // bool keepGoing = false; - #ifdef DEBUG - double frac = 0.; - #endif +#ifdef DEBUG + double frac = 0.; +#endif + //bool keepGoing = false; //debug for(int jBin=binI; jBin>0; --jBin){ LocEvents = 0.; - // keepGoing = false; - #ifdef DEBUG - std::cout<<"j: "<GetBinCenter(jBin)<<" I: "<GetBinCenter(binI)<<" F: "<GetBinCenter(binF)<<" frac: "<GetBinCenter(jBin)<<" I: "<GetBinCenter(binI)<<" F: "<GetBinCenter(binF)<<" frac: "<GetBinContent(iBin); if(LocEvents/TotEvents >= quant) { if(iBin-jBin < binF-binI) { binF = iBin; binI = jBin; - // keepGoing = true; + //keepGoing = true; +#ifdef DEBUG + frac = LocEvents/TotEvents; + std::cout<<"trovato nuovo intervallo piu piccolo di prima"<GetNbinsX()-1){ - //keepGoing = true; - #ifdef DEBUG - frac = LocEvents/TotEvents; - std::cout<<"trovato nuovo intervallo piu piccolo di prima"<GetNbinsX()-1) break; - if(iBin == binF-1 && binF != h->GetNbinsX()-1) { - #ifdef DEBUG - std::cout<<"qui: esci" <GetNbinsX()-1) { +#ifdef DEBUG + std::cout<<"qui: esci" <GetBinCenter(binF) - h->GetBinCenter(binI))/2.; - //std::cout << " >>> effective sigma: " << sigma << std::endl; - std::cout << ">>> - effective sigma: " << sigma << " interval start from: "<GetBinCenter(binI)<<" finish to: "<GetBinCenter(binF)<>> - effective sigma: " << sigma << " interval start from: "<GetBinCenter(binI)<<" finish to: "<GetBinCenter(binF)<sumEntries(); if(nEvents_region_data < 100){ data_red = ReduceDataset(data, region, false, true); - // nEvents_region_data=data_red->sumEntries(); + // nEvents_region_data=data_red->sumEntries(); } - // if(nEvents_region_data < 100) return NULL; + // if(nEvents_region_data < 100) return NULL; int numcpu=4; - if(_isDataUnbinned) numcpu=1;//this is because in previous versions of ROOT, the unbinned fit did not support nCPU>1 (to be checked in newer versions) + if(_isDataUnbinned) numcpu=1; //this is because in previous versions of ROOT, the unbinned fit did not support nCPU>1 (to be checked in newer versions) //EFFECTIVE SIGMA - sigmaeff_data = GetEffectiveSigma(data_red); - //overwriting values - sigmaeff_data_map[0.68]=GetEffectiveSigma(data_red); - sigmaeff_data_map[0.50]=GetEffectiveSigma(data_red, 0.50); - sigmaeff_data_map[0.30]=GetEffectiveSigma(data_red, 0.30); + if (_isDataUnbinned) + sigmaeff_data = GetEffectiveSigma(data_red); + else { //if data_red is binned, need to re-do it unbinned, in order to get an accurate effective sigma + RooAbsData *data_red_unbinned = ReduceDataset(data, region, false, true); + sigmaeff_data = GetEffectiveSigma(data_red_unbinned); + } SetFitPar(fitres_MC); RooFitResult *fitres_data = model_pdf->fitTo(*data_red,RooFit::Save(), //RooFit::Range(range.c_str()), diff --git a/ZFitter/submit_calibration_jobs.py b/ZFitter/submit_calibration_jobs.py new file mode 100644 index 00000000000..44139340e02 --- /dev/null +++ b/ZFitter/submit_calibration_jobs.py @@ -0,0 +1,222 @@ +#! /usr/bin/env python +import os +import glob +import math +from array import array +import sys +import time +import subprocess + +from optparse import OptionParser + +parser = OptionParser() + +parser.add_option('--generateOnly', action='store_true', dest='generateOnly', default=False, help='generate jobs only, without submitting them') + +(options, args) = parser.parse_args() + +currentDir = os.getcwd(); +CMSSWDir = currentDir+"/../"; + +applyPcorr = ["True"]; #decide if you want to apply momentum correction or not +applyEcorr = ["False"]; #decide if you want to apply energy correction or not +split = ["0","1"]; #0=full statistics, 1=even/odd +cut = ["0.15","0.20","0.30","100"];#size of the E/p cut window (default is 0.15) +smoothCut = ["1"]; #0=use step-function to reweight, 1=use the E/p distribution +energyType = ["0"]; #0=regression, 1=raw energy +nLoops = "10"; #number of iterations +ntupleName = "Run2016BCDEFG_WZSkim_12p9fb_multifit" +#ntupleName = "DYToEE_powheg_13TeV-RunIISpring15DR74-Asym25n-v1-allRange" #options: "data-Run2015D-25ns-multifit", "data-Run2015D-25ns-multifit" or "data-Run2015D-25ns-stream". +#For the MC use: "DYToEE_powheg_13TeV-RunIISpring15DR74-Asym25n-v1-allRange" +#ntuplelist = ["data-SingleElectron-Run2016BCD_WSkim_12p9fb_multifit","data-DoubleEG-Run2016BCD_ZSkim_12p9fb_multifit"] + +folder_dat = "/store/group/dpg_ecal/alca_ecalcalib/ecalMIBI/lbrianza/ntupleEoP/" #folder containing the .dat files (don't touch this) +folder = "/store/group/dpg_ecal/alca_ecalcalib/ecalMIBI/lbrianza/ntupleEoP/" #folder containing the .dat files (don't touch this) +#folder = "/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARECOSIM/DYToEE_powheg_13TeV-RunIISpring15DR74-Asym25n-v1/allRange/246908-258750-Prompt_25ns-v1-esPlanes/" #folder containing the MC ntuples + +ntuplelist = ["SingleElectron-Run2016B-WSkim-Prompt_v2-273150-275376","SingleElectron-Run2016C-WSkim-Prompt_v2-275420-276283","SingleElectron-Run2016D-WSkim-Prompt_v2-276315-276811","SingleElectron-Run2016E-WSkim-Prompt_v1-276830-277420","SingleElectron-Run2016F-WSkim-Prompt_v1-277820-278808","SingleElectron-Run2016G-WSkim-Prompt_v1-278817-279488"] + +#folderlist=["/store/group/dpg_ecal/alca_ecalcalib/ecalMIBI/lbrianza/ntupleEoP/"] +folderlist=[ +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/80X_dataRun2_Prompt_v10/SingleElectron-Run2016B-WSkim-Prompt_v2/273150-275376/271036_276811-ICHEP/withExtrasTest/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/80X_dataRun2_Prompt_v10/SingleElectron-Run2016C-WSkim-Prompt_v2/275420-276283/271036_276811-ICHEP/withExtrasTest/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/80X_dataRun2_Prompt_v10/SingleElectron-Run2016D-WSkim-Prompt_v2/276315-276811/271036_276811-ICHEP/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/80X_dataRun2_Prompt_v10/SingleElectron-Run2016E-WSkim-Prompt_v1/276830-277420/276830-277420/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/80X_dataRun2_Prompt_v10/SingleElectron-Run2016F-WSkim-Prompt_v1/277820-278808/271036-278808/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/80X_dataRun2_Prompt_v10/SingleElectron-Run2016G-WSkim-Prompt_v1/278817-279488/271036-279116/"] + + +TOP=currentDir +#cmscaf1nd + +#os.system("mkdir Job_"+ntupleName+""+nLoops+"loop_2016_newPcorr") +os.system("mkdir Job_"+ntupleName+""+nLoops+"2016_newPcorr") +os.system("mkdir cfg_"+ntupleName+"_"+nLoops+"2016_newPcorr") +os.system("mkdir ICset_"+ntupleName+"_"+nLoops+"2016_newPcorr") + +##RUN CALIBRATION ON BARREL +for b in range(len(split)): + for c in range(len(cut)): + for d in range(len(smoothCut)): + for e in range(len(applyPcorr)): + for f in range(len(applyEcorr)): + for g in range(len(energyType)): + fn = "Job_"+ntupleName+""+nLoops+"2016_newPcorr/Job_"+"EB"+"_"+split[b]+"_"+cut[c]+"_smoothCut"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g]; + outScript = open(fn+".sh","w"); + command = "ZFitter.exe -f EoverPcalibration_batch_"+ntupleName+".dat --EOverPCalib --outputPath output_"+ntupleName+"_"+nLoops+"2016_newPcorr_"+cut[c]+"_smooth"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g]+"/ --do"+"EB"+" --splitStat "+split[b]+" --nLoops "+nLoops+" --EPMin "+cut[c]+" --noPU --smoothCut "+smoothCut[d]+" --applyPcorr "+applyPcorr[e]+" --inputMomentumScale MomentumCalibration2016_eta1_eta1.root --applyEcorr "+applyEcorr[f]+" useRawEnergy "+energyType[g]+" --inputEnergyScale momentumCalibration2015_EB_scE.root" + print command; + outScript.write('#!/bin/bash'); + outScript.write("\n"+'cd '+CMSSWDir); + outScript.write("\n"+'eval `scram runtime -sh`'); + outScript.write("\n"+'cd -'); + outScript.write("\necho $PWD"); + outScript.write("\nls"); + + for j in range(len(ntuplelist)): + outScript.write("\necho \"copy main tree\" "); + outScript.write("\ncmsStage "+folderlist[j]+""+ntuplelist[j]+".root ./") + outScript.write("\necho \"copy extracalib tree\" "); + outScript.write("\ncmsStage "+folderlist[j]+"extraCalibTree-"+ntuplelist[j]+".root ./") + + outScript.write("\necho \"copiy additional files\" "); +# outScript.write("\ncp -v /afs/cern.ch/user/l/lbrianza/work/public/ntupleEoP/* .") + outScript.write("\ncmsStage "+folder_dat+"momentumCalibration2015_EB_pTk.root ./") + outScript.write("\ncmsStage "+folder_dat+"momentumCalibration2015_EB_scE.root ./") + outScript.write("\ncmsStage "+folder_dat+"EoverPcalibration_batch_"+ntupleName+".dat ./") + outScript.write("\ncmsStage "+folder_dat+"MomentumCalibration2016_eta1_eta1.root ./") + outScript.write("\necho \"end copy\" "); + + outScript.write("\nls") + outScript.write("\necho \"eseguo: "+command+"\" ") + outScript.write("\n"+command); + outScript.write("\nls") + outScript.write("\ncp -v -r output_"+ntupleName+"_"+nLoops+"2016_newPcorr_"+cut[c]+"_smooth"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g]+"/ "+currentDir) + outScript.close(); + os.system("chmod 777 "+currentDir+"/"+fn+".sh"); + command2 = "bsub -q cmscaf1nw -cwd "+currentDir+" "+currentDir+"/"+fn+".sh"; + if not options.generateOnly: + os.system(command2); + print command2 + + +##RUN CALIBRATION ON ENDCAP +for b in range(len(split)): + for c in range(len(cut)): + for d in range(len(smoothCut)): + for e in range(len(applyPcorr)): + for f in range(len(applyEcorr)): + for g in range(len(energyType)): + fn = "Job_"+ntupleName+""+nLoops+"2016_newPcorr/Job_"+"EE"+"_"+split[b]+"_"+cut[c]+"_smoothCut"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g]; + outScript = open(fn+".sh","w"); + command = "ZFitter.exe -f EoverPcalibration_batch_"+ntupleName+".dat --EOverPCalib --outputPath output_"+ntupleName+"_"+nLoops+"2016_newPcorr_"+cut[c]+"_smooth"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g]+"/ --do"+"EE"+" --splitStat "+split[b]+" --nLoops "+nLoops+" --EPMin "+cut[c]+" --noPU --smoothCut "+smoothCut[d]+" --applyPcorr "+applyPcorr[e]+" --inputMomentumScale MomentumCalibration2016_eta1_eta1.root --applyEcorr "+applyEcorr[f]+" useRawEnergy "+energyType[g]+" --inputEnergyScale momentumCalibration2015_EE_scE.root" + print command; + outScript.write('#!/bin/bash'); + outScript.write("\n"+'cd '+CMSSWDir); + outScript.write("\n"+'eval `scram runtime -sh`'); + outScript.write("\n"+'cd -'); + outScript.write("\necho $PWD"); + outScript.write("\nls"); + + for j in range(len(ntuplelist)): + outScript.write("\necho \"copy main tree\" "); + outScript.write("\ncmsStage "+folderlist[j]+""+ntuplelist[j]+".root ./") + outScript.write("\necho \"copy extracalib tree\" "); + outScript.write("\ncmsStage "+folderlist[j]+"extraCalibTree-"+ntuplelist[j]+".root ./") + + outScript.write("\necho \"copy additional files\" "); +# outScript.write("\ncp -v /afs/cern.ch/user/l/lbrianza/work/public/ntupleEoP/* .") + outScript.write("\ncmsStage "+folder_dat+"momentumCalibration2015_EE_pTk.root ./") + outScript.write("\ncmsStage "+folder_dat+"momentumCalibration2015_EE_scE.root ./") + outScript.write("\ncmsStage "+folder_dat+"EoverPcalibration_batch_"+ntupleName+".dat ./") + outScript.write("\ncmsStage "+folder_dat+"MomentumCalibration2016_eta1_eta1.root ./") + outScript.write("\necho \"end copy\" "); + outScript.write("\nls") + outScript.write("\necho \"eseguo: "+command+"\" ") + outScript.write("\n"+command); + outScript.write("\nls") + outScript.write("\ncp -v -r output_"+ntupleName+"_"+nLoops+"2016_newPcorr_"+cut[c]+"_smooth"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g]+"/ "+currentDir) + outScript.close(); + os.system("chmod 777 "+currentDir+"/"+fn+".sh"); + command2 = "bsub -q cmscaf1nw -cwd "+currentDir+" "+currentDir+"/"+fn+".sh"; + if not options.generateOnly: + os.system(command2); + print command2 + + +##CREATE CFG FILES TO PRODUCE CALIBRATION PLOTS LATER + +createAndPlotIC = "createAndPlotIC_"+ntupleName+"_"+nLoops+"2016_newPcorr.sh" +out2 = open(createAndPlotIC,"w") + +#for b in range(len(split)): +for c in range(len(cut)): + for d in range(len(smoothCut)): + for e in range(len(applyPcorr)): + for f in range(len(applyEcorr)): + for g in range(len(energyType)): + name = "EB"+"_"+cut[c]+"_smoothCut"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g] + fn = "cfg_"+ntupleName+"_"+nLoops+"2016_newPcorr/calibrationPlots_"+name+".py"; + folder = "output_"+ntupleName+"_"+nLoops+"2016_newPcorr_"+cut[c]+"_smooth"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g]+"/" + outScript = open(fn,"w"); + outScript.write("import FWCore.ParameterSet.Config as cms"); + outScript.write("\nprocess = cms.Process(\"calibrationPlotsEBparameters\")") + outScript.write("\nprocess.Options = cms.PSet(") + outScript.write("\n\tinFileName = cms.string(\""+TOP+"/"+folder+"FastCalibrator_Oct2015_runD_WZ_noEP_EB.root\"),") + outScript.write("\n\tinFileNameEven = cms.string(\""+TOP+"/"+folder+"FastCalibrator_Oct2015_runD_WZ_noEP_EB_even.root\"),") + outScript.write("\n\tinFileNameOdd = cms.string(\""+TOP+"/"+folder+"FastCalibrator_Oct2015_runD_WZ_noEP_EB_odd.root\"),") + outScript.write("\n\tnEtaBinsEB = cms.int32(1),") + outScript.write("\n\tnEtaBinsEE = cms.int32(1),") + outScript.write("\n\tis2012Calib = cms.bool(False),") + outScript.write("\n\tisEB = cms.bool(True),") + outScript.write("\n\tevalStat = cms.int32(1),") + outScript.write("\n\toutputFolder = cms.string(\""+folder+"\"),") + outScript.write("\n\toutFileName = cms.string(\""+name+".root\"),") + outScript.write("\n\toutputTxt = cms.string(\"IC_"+name+"\"),") + outScript.write("\n\tfileType = cms.string(\"cxx\")") + outScript.write("\n)") + out2.write("\nCalibrationPlots "+fn) + + +##CREATE CFG FILES TO PRODUCE CALIBRATION PLOTS LATER + +#for b in range(len(split)): +for c in range(len(cut)): + for d in range(len(smoothCut)): + for e in range(len(applyPcorr)): + for f in range(len(applyEcorr)): + for g in range(len(energyType)): + name = "EE"+"_"+cut[c]+"_smoothCut"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g] + fn = "cfg_"+ntupleName+"_"+nLoops+"2016_newPcorr/calibrationPlots_"+name+".py"; + folder = "output_"+ntupleName+"_"+nLoops+"2016_newPcorr_"+cut[c]+"_smooth"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g]+"/" + outScript = open(fn,"w"); + outScript.write("import FWCore.ParameterSet.Config as cms"); + outScript.write("\nprocess = cms.Process(\"calibrationPlotsEEparameters\")") + outScript.write("\nprocess.Options = cms.PSet(") + outScript.write("\n\tinFileName = cms.string(\""+TOP+"/"+folder+"FastCalibrator_Oct2015_runD_WZ_noEP_EE.root\"),") + outScript.write("\n\tinFileNameEven = cms.string(\""+TOP+"/"+folder+"FastCalibrator_Oct2015_runD_WZ_noEP_EE_even.root\"),") + outScript.write("\n\tinFileNameOdd = cms.string(\""+TOP+"/"+folder+"FastCalibrator_Oct2015_runD_WZ_noEP_EE_odd.root\"),") + outScript.write("\n\tnEtaBinsEB = cms.int32(1),") + outScript.write("\n\tnEtaBinsEE = cms.int32(1),") + outScript.write("\n\tis2012Calib = cms.bool(False),") + outScript.write("\n\tisEB = cms.bool(False),") + outScript.write("\n\tevalStat = cms.int32(1),") + outScript.write("\n\toutputFolder = cms.string(\""+folder+"\"),") + outScript.write("\n\toutFileName = cms.string(\""+name+".root\"),") + outScript.write("\n\toutputTxt = cms.string(\"IC_"+name+"\"),") + outScript.write("\n\tfileType = cms.string(\"cxx\")") + outScript.write("\n)") + out2.write("\nCalibrationPlots "+fn) + +##CREATE FOLDER CONTAINING THE FINAL SET OF IC (EB+EE) + +newFolder = "ICset_"+ntupleName+"_"+nLoops+"2016_newPcorr" + +for c in range(len(cut)): + for d in range(len(smoothCut)): + for e in range(len(applyPcorr)): + for f in range(len(applyEcorr)): + for g in range(len(energyType)): + name = "IC_"+cut[c]+"_smoothCut"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g] + folder = "output_"+ntupleName+"_"+nLoops+"2016_newPcorr_"+cut[c]+"_smooth"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g]+"/" + out2.write("\ncat "+folder+"IC_EB*txt "+folder+"IC_EE*txt > "+newFolder+"/"+name+".txt") + diff --git a/ZFitter/submit_calibration_jobs_multifit.py b/ZFitter/submit_calibration_jobs_multifit.py new file mode 100644 index 00000000000..21f8c3eadbb --- /dev/null +++ b/ZFitter/submit_calibration_jobs_multifit.py @@ -0,0 +1,247 @@ +1#! /usr/bin/env python +import os +import glob +import math +from array import array +import sys +import time +import subprocess + +from optparse import OptionParser + +parser = OptionParser() + +parser.add_option('--generateOnly', action='store_true', dest='generateOnly', default=False, help='generate jobs only, without submitting them') + +(options, args) = parser.parse_args() + +currentDir = os.getcwd(); +CMSSWDir = currentDir+"/../"; + +applyPcorr = ["True"]; #decide if you want to apply momentum correction or not +applyEcorr = ["False"]; #decide if you want to apply energy correction or not +split = ["0","1"]; #0=full statistics, 1=even/odd +cut = ["0.15","0.20","0.30","100"];#size of the E/p cut window (default is 0.15) +#cut = ["0.15"] +smoothCut = ["1"]; #0=use step-function to reweight, 1=use the E/p distribution +energyType = ["0"]; #0=regression, 1=raw energy +nLoops = "20"; #number of iterations +ntupleName = "Run2016BCDEFG_WZSkim_Cal_Sep2016_final_v3_multifit" +#ntupleName = "DYToEE_powheg_13TeV-RunIISpring15DR74-Asym25n-v1-allRange" #options: "data-Run2015D-25ns-multifit", "data-Run2015D-25ns-multifit" or "data-Run2015D-25ns-stream". +#For the MC use: "DYToEE_powheg_13TeV-RunIISpring15DR74-Asym25n-v1-allRange" +#ntuplelist = ["data-SingleElectron-Run2016BCD_WSkim_12p9fb_multifit","data-DoubleEG-Run2016BCD_ZSkim_12p9fb_multifit"] + +folder_dat = "/store/group/dpg_ecal/alca_ecalcalib/ecalMIBI/lbrianza/ntupleEoP/" #folder containing the .dat files (don't touch this) +folder = "/store/group/dpg_ecal/alca_ecalcalib/ecalMIBI/lbrianza/ntupleEoP/" #folder containing the .dat files (don't touch this) +#folder = "/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARECOSIM/DYToEE_powheg_13TeV-RunIISpring15DR74-Asym25n-v1/allRange/246908-258750-Prompt_25ns-v1-esPlanes/" #folder containing the MC ntuples + +ntuplelist = [ +"DoubleEG-Run2016B-ZSkim-Prompt_v2-273150-275376", +"DoubleEG-Run2016C-ZSkim-Prompt_v2-275420-276283", +"DoubleEG-Run2016D-ZSkim-Prompt_v2-276315-276811", +"DoubleEG-Run2016E-ZSkim-Prompt-v2-276830-277420", +"DoubleEG-Run2016F-ZSkim-Prompt-v1-277820-278808", +"DoubleEG-Run2016G-ZSkim-Prompt-v1-278817-279588", +"DoubleEG-Run2016G-ZSkim-Prompt-v1-279589-279931", +"SingleElectron-Run2016B-WSkim-Prompt_v2-273150-275376", +"SingleElectron-Run2016C-WSkim-Prompt_v2-275420-276283", +"SingleElectron-Run2016D-WSkim-Prompt_v2-276315-276811", +"SingleElectron-Run2016E-WSkim-Prompt-v2-276830-277420", +"SingleElectron-Run2016F-WSkim-Prompt-v1-277820-278808", +"SingleElectron-Run2016G-WSkim-Prompt-v1-278817-279588", +"SingleElectron-Run2016G-WSkim-Prompt-v1-279589-279931" +] + +#folderlist=["/store/group/dpg_ecal/alca_ecalcalib/ecalMIBI/lbrianza/ntupleEoP/"] +folderlist=[ +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016B-ZSkim-Prompt_v2/273150-275376/271036_279931-Cal_Sep2016/withExtras2/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016C-ZSkim-Prompt_v2/275420-276283/271036_279931-Cal_Sep2016/withExtras2/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016D-ZSkim-Prompt_v2/276315-276811/271036_279931-Cal_Sep2016/withExtras2/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016E-ZSkim-Prompt-v2/276830-277420/271036_279931-Cal_Sep2016/withExtras2/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016F-ZSkim-Prompt-v1/277820-278808/271036_279931-Cal_Sep2016/withExtras2/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016G-ZSkim-Prompt-v1/278817-279588/271036_279931-Cal_Sep2016/withExtras2/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016G-ZSkim-Prompt-v1/279589-279931/271036_279931-Cal_Sep2016/withExtras2/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/SingleElectron-Run2016B-WSkim-Prompt_v2/273150-275376/271036_279931-Cal_Sep2016/withExtras/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/SingleElectron-Run2016C-WSkim-Prompt_v2/275420-276283/271036_279931-Cal_Sep2016/withExtras/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/SingleElectron-Run2016D-WSkim-Prompt_v2/276315-276811/271036_279931-Cal_Sep2016/withExtras/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/SingleElectron-Run2016E-WSkim-Prompt-v2/276830-277420/271036_279931-Cal_Sep2016/withExtras/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/SingleElectron-Run2016F-WSkim-Prompt-v1/277820-278808/271036_279931-Cal_Sep2016/withExtras/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/SingleElectron-Run2016G-WSkim-Prompt-v1/278817-279588/271036_279931-Cal_Sep2016/withExtras/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/SingleElectron-Run2016G-WSkim-Prompt-v1/279589-279931/271036_279931-Cal_Sep2016/withExtras/" +] + + +TOP=currentDir +#cmscaf1nd + +#os.system("mkdir Job_"+ntupleName+""+nLoops+"loop_2016_newPcorr") +os.system("mkdir Job_"+ntupleName+""+nLoops+"2016_newPcorr") +os.system("mkdir cfg_"+ntupleName+"_"+nLoops+"2016_newPcorr") +os.system("mkdir ICset_"+ntupleName+"_"+nLoops+"2016_newPcorr") + +##RUN CALIBRATION ON BARREL +for b in range(len(split)): + for c in range(len(cut)): + for d in range(len(smoothCut)): + for e in range(len(applyPcorr)): + for f in range(len(applyEcorr)): + for g in range(len(energyType)): + fn = "Job_"+ntupleName+""+nLoops+"2016_newPcorr/Job_"+"EB"+"_"+split[b]+"_"+cut[c]+"_smoothCut"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g]; + outScript = open(fn+".sh","w"); + command = "ZFitter.exe -f EoverPcalibration_batch_"+ntupleName+".dat --EOverPCalib --outputPath output_"+ntupleName+"_"+nLoops+"2016_newPcorr_"+cut[c]+"_smooth"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g]+"/ --do"+"EB"+" --splitStat "+split[b]+" --nLoops "+nLoops+" --EPMin "+cut[c]+" --noPU --smoothCut "+smoothCut[d]+" --applyPcorr "+applyPcorr[e]+" --inputMomentumScale MomentumCalibration2016_eta1_eta1.root --applyEcorr "+applyEcorr[f]+" useRawEnergy "+energyType[g]+" --inputEnergyScale momentumCalibration2015_EB_scE.root" + print command; + outScript.write('#!/bin/bash'); + outScript.write("\n"+'cd '+CMSSWDir); + outScript.write("\n"+'eval `scram runtime -sh`'); + outScript.write("\n"+'cd -'); + outScript.write("\necho $PWD"); + outScript.write("\nls"); + + for j in range(len(ntuplelist)): + outScript.write("\necho \"copy main tree\" "); + outScript.write("\ncmsStage "+folderlist[j]+""+ntuplelist[j]+".root ./") + outScript.write("\necho \"copy extracalib tree\" "); + outScript.write("\ncmsStage "+folderlist[j]+"extraCalibTree-"+ntuplelist[j]+".root ./") + + outScript.write("\necho \"copiy additional files\" "); +# outScript.write("\ncp -v /afs/cern.ch/user/l/lbrianza/work/public/ntupleEoP/* .") + outScript.write("\ncmsStage "+folder_dat+"momentumCalibration2015_EB_pTk.root ./") + outScript.write("\ncmsStage "+folder_dat+"momentumCalibration2015_EB_scE.root ./") + outScript.write("\ncmsStage "+folder_dat+"EoverPcalibration_batch_"+ntupleName+".dat ./") + outScript.write("\ncmsStage "+folder_dat+"MomentumCalibration2016_eta1_eta1.root ./") + outScript.write("\necho \"end copy\" "); + + outScript.write("\nls") + outScript.write("\necho \"eseguo: "+command+"\" ") + outScript.write("\n"+command); + outScript.write("\nls") + outScript.write("\ncp -v -r output_"+ntupleName+"_"+nLoops+"2016_newPcorr_"+cut[c]+"_smooth"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g]+"/ "+currentDir) + outScript.close(); + os.system("chmod 777 "+currentDir+"/"+fn+".sh"); + command2 = "bsub -q cmscaf1nw -cwd "+currentDir+" "+currentDir+"/"+fn+".sh"; + if not options.generateOnly: + os.system(command2); + print command2 + + +##RUN CALIBRATION ON ENDCAP +for b in range(len(split)): + for c in range(len(cut)): + for d in range(len(smoothCut)): + for e in range(len(applyPcorr)): + for f in range(len(applyEcorr)): + for g in range(len(energyType)): + fn = "Job_"+ntupleName+""+nLoops+"2016_newPcorr/Job_"+"EE"+"_"+split[b]+"_"+cut[c]+"_smoothCut"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g]; + outScript = open(fn+".sh","w"); + command = "ZFitter.exe -f EoverPcalibration_batch_"+ntupleName+".dat --EOverPCalib --outputPath output_"+ntupleName+"_"+nLoops+"2016_newPcorr_"+cut[c]+"_smooth"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g]+"/ --do"+"EE"+" --splitStat "+split[b]+" --nLoops "+nLoops+" --EPMin "+cut[c]+" --noPU --smoothCut "+smoothCut[d]+" --applyPcorr "+applyPcorr[e]+" --inputMomentumScale MomentumCalibration2016_eta1_eta1.root --applyEcorr "+applyEcorr[f]+" useRawEnergy "+energyType[g]+" --inputEnergyScale momentumCalibration2015_EE_scE.root" + print command; + outScript.write('#!/bin/bash'); + outScript.write("\n"+'cd '+CMSSWDir); + outScript.write("\n"+'eval `scram runtime -sh`'); + outScript.write("\n"+'cd -'); + outScript.write("\necho $PWD"); + outScript.write("\nls"); + + for j in range(len(ntuplelist)): + outScript.write("\necho \"copy main tree\" "); + outScript.write("\ncmsStage "+folderlist[j]+""+ntuplelist[j]+".root ./") + outScript.write("\necho \"copy extracalib tree\" "); + outScript.write("\ncmsStage "+folderlist[j]+"extraCalibTree-"+ntuplelist[j]+".root ./") + + outScript.write("\necho \"copy additional files\" "); +# outScript.write("\ncp -v /afs/cern.ch/user/l/lbrianza/work/public/ntupleEoP/* .") + outScript.write("\ncmsStage "+folder_dat+"momentumCalibration2015_EE_pTk.root ./") + outScript.write("\ncmsStage "+folder_dat+"momentumCalibration2015_EE_scE.root ./") + outScript.write("\ncmsStage "+folder_dat+"EoverPcalibration_batch_"+ntupleName+".dat ./") + outScript.write("\ncmsStage "+folder_dat+"MomentumCalibration2016_eta1_eta1.root ./") + outScript.write("\necho \"end copy\" "); + outScript.write("\nls") + outScript.write("\necho \"eseguo: "+command+"\" ") + outScript.write("\n"+command); + outScript.write("\nls") + outScript.write("\ncp -v -r output_"+ntupleName+"_"+nLoops+"2016_newPcorr_"+cut[c]+"_smooth"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g]+"/ "+currentDir) + outScript.close(); + os.system("chmod 777 "+currentDir+"/"+fn+".sh"); + command2 = "bsub -q cmscaf1nw -cwd "+currentDir+" "+currentDir+"/"+fn+".sh"; + if not options.generateOnly: + os.system(command2); + print command2 + + +##CREATE CFG FILES TO PRODUCE CALIBRATION PLOTS LATER + +createAndPlotIC = "createAndPlotIC_"+ntupleName+"_"+nLoops+"2016_newPcorr.sh" +out2 = open(createAndPlotIC,"w") + +#for b in range(len(split)): +for c in range(len(cut)): + for d in range(len(smoothCut)): + for e in range(len(applyPcorr)): + for f in range(len(applyEcorr)): + for g in range(len(energyType)): + name = "EB"+"_"+cut[c]+"_smoothCut"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g] + fn = "cfg_"+ntupleName+"_"+nLoops+"2016_newPcorr/calibrationPlots_"+name+".py"; + folder = "output_"+ntupleName+"_"+nLoops+"2016_newPcorr_"+cut[c]+"_smooth"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g]+"/" + outScript = open(fn,"w"); + outScript.write("import FWCore.ParameterSet.Config as cms"); + outScript.write("\nprocess = cms.Process(\"calibrationPlotsEBparameters\")") + outScript.write("\nprocess.Options = cms.PSet(") + outScript.write("\n\tinFileName = cms.string(\""+TOP+"/"+folder+"FastCalibrator_Oct2015_runD_WZ_noEP_EB.root\"),") + outScript.write("\n\tinFileNameEven = cms.string(\""+TOP+"/"+folder+"FastCalibrator_Oct2015_runD_WZ_noEP_EB_even.root\"),") + outScript.write("\n\tinFileNameOdd = cms.string(\""+TOP+"/"+folder+"FastCalibrator_Oct2015_runD_WZ_noEP_EB_odd.root\"),") + outScript.write("\n\tnEtaBinsEB = cms.int32(1),") + outScript.write("\n\tnEtaBinsEE = cms.int32(1),") + outScript.write("\n\tis2012Calib = cms.bool(False),") + outScript.write("\n\tisEB = cms.bool(True),") + outScript.write("\n\tevalStat = cms.int32(1),") + outScript.write("\n\toutputFolder = cms.string(\""+folder+"\"),") + outScript.write("\n\toutFileName = cms.string(\""+name+".root\"),") + outScript.write("\n\toutputTxt = cms.string(\"IC_"+name+"\"),") + outScript.write("\n\tfileType = cms.string(\"cxx\")") + outScript.write("\n)") + out2.write("\nCalibrationPlots "+fn) + + +##CREATE CFG FILES TO PRODUCE CALIBRATION PLOTS LATER + +#for b in range(len(split)): +for c in range(len(cut)): + for d in range(len(smoothCut)): + for e in range(len(applyPcorr)): + for f in range(len(applyEcorr)): + for g in range(len(energyType)): + name = "EE"+"_"+cut[c]+"_smoothCut"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g] + fn = "cfg_"+ntupleName+"_"+nLoops+"2016_newPcorr/calibrationPlots_"+name+".py"; + folder = "output_"+ntupleName+"_"+nLoops+"2016_newPcorr_"+cut[c]+"_smooth"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g]+"/" + outScript = open(fn,"w"); + outScript.write("import FWCore.ParameterSet.Config as cms"); + outScript.write("\nprocess = cms.Process(\"calibrationPlotsEEparameters\")") + outScript.write("\nprocess.Options = cms.PSet(") + outScript.write("\n\tinFileName = cms.string(\""+TOP+"/"+folder+"FastCalibrator_Oct2015_runD_WZ_noEP_EE.root\"),") + outScript.write("\n\tinFileNameEven = cms.string(\""+TOP+"/"+folder+"FastCalibrator_Oct2015_runD_WZ_noEP_EE_even.root\"),") + outScript.write("\n\tinFileNameOdd = cms.string(\""+TOP+"/"+folder+"FastCalibrator_Oct2015_runD_WZ_noEP_EE_odd.root\"),") + outScript.write("\n\tnEtaBinsEB = cms.int32(1),") + outScript.write("\n\tnEtaBinsEE = cms.int32(1),") + outScript.write("\n\tis2012Calib = cms.bool(False),") + outScript.write("\n\tisEB = cms.bool(False),") + outScript.write("\n\tevalStat = cms.int32(1),") + outScript.write("\n\toutputFolder = cms.string(\""+folder+"\"),") + outScript.write("\n\toutFileName = cms.string(\""+name+".root\"),") + outScript.write("\n\toutputTxt = cms.string(\"IC_"+name+"\"),") + outScript.write("\n\tfileType = cms.string(\"cxx\")") + outScript.write("\n)") + out2.write("\nCalibrationPlots "+fn) + +##CREATE FOLDER CONTAINING THE FINAL SET OF IC (EB+EE) + +newFolder = "ICset_"+ntupleName+"_"+nLoops+"2016_newPcorr" + +for c in range(len(cut)): + for d in range(len(smoothCut)): + for e in range(len(applyPcorr)): + for f in range(len(applyEcorr)): + for g in range(len(energyType)): + name = "IC_"+cut[c]+"_smoothCut"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g] + folder = "output_"+ntupleName+"_"+nLoops+"2016_newPcorr_"+cut[c]+"_smooth"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g]+"/" + out2.write("\ncat "+folder+"IC_EB*txt "+folder+"IC_EE*txt > "+newFolder+"/"+name+".txt") + diff --git a/ZFitter/submit_calibration_jobs_weights.py b/ZFitter/submit_calibration_jobs_weights.py new file mode 100644 index 00000000000..6b017ab793f --- /dev/null +++ b/ZFitter/submit_calibration_jobs_weights.py @@ -0,0 +1,247 @@ +1#! /usr/bin/env python +import os +import glob +import math +from array import array +import sys +import time +import subprocess + +from optparse import OptionParser + +parser = OptionParser() + +parser.add_option('--generateOnly', action='store_true', dest='generateOnly', default=False, help='generate jobs only, without submitting them') + +(options, args) = parser.parse_args() + +currentDir = os.getcwd(); +CMSSWDir = currentDir+"/../"; + +applyPcorr = ["True"]; #decide if you want to apply momentum correction or not +applyEcorr = ["False"]; #decide if you want to apply energy correction or not +split = ["0","1"]; #0=full statistics, 1=even/odd +cut = ["0.15","0.20","0.30","100"];#size of the E/p cut window (default is 0.15) +#cut = ["0.10"] +smoothCut = ["1"]; #0=use step-function to reweight, 1=use the E/p distribution +energyType = ["0"]; #0=regression, 1=raw energy +nLoops = "15"; #number of iterations +ntupleName = "Run2016BCDEFG_WZSkim_Cal_Sep2016_final_v3_weights" +#ntupleName = "DYToEE_powheg_13TeV-RunIISpring15DR74-Asym25n-v1-allRange" #options: "data-Run2015D-25ns-multifit", "data-Run2015D-25ns-multifit" or "data-Run2015D-25ns-stream". +#For the MC use: "DYToEE_powheg_13TeV-RunIISpring15DR74-Asym25n-v1-allRange" +#ntuplelist = ["data-SingleElectron-Run2016BCD_WSkim_12p9fb_multifit","data-DoubleEG-Run2016BCD_ZSkim_12p9fb_multifit"] + +folder_dat = "/store/group/dpg_ecal/alca_ecalcalib/ecalMIBI/lbrianza/ntupleEoP/" #folder containing the .dat files (don't touch this) +folder = "/store/group/dpg_ecal/alca_ecalcalib/ecalMIBI/lbrianza/ntupleEoP/" #folder containing the .dat files (don't touch this) +#folder = "/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARECOSIM/DYToEE_powheg_13TeV-RunIISpring15DR74-Asym25n-v1/allRange/246908-258750-Prompt_25ns-v1-esPlanes/" #folder containing the MC ntuples + +ntuplelist = [ +"DoubleEG-Run2016B-ZSkim-Prompt_v2-weightsReco-273150-275376", +"DoubleEG-Run2016C-ZSkim-Prompt_v2-weightsReco-275420-276283", +"DoubleEG-Run2016D-ZSkim-Prompt_v2-weightsReco-276315-276811", +"DoubleEG-Run2016E-ZSkim-Prompt-v2-weightsReco-276830-277420", +"DoubleEG-Run2016F-ZSkim-Prompt-v1-weightsReco-277820-278808", +"DoubleEG-Run2016G-ZSkim-Prompt-v1-weightsReco-278817-279588", +"DoubleEG-Run2016G-ZSkim-Prompt-v1-weightsReco-279589-279931", +"SingleElectron-Run2016B-WSkim-Prompt_v2-weightsReco-273150-275376", +"SingleElectron-Run2016C-WSkim-Prompt_v2-weightsReco-275420-276283", +"SingleElectron-Run2016D-WSkim-Prompt_v2-weightsReco-276315-276811", +"SingleElectron-Run2016E-WSkim-Prompt-v2-weightsReco-276830-277420", +"SingleElectron-Run2016F-WSkim-Prompt-v1-weightsReco-277820-278808", +"SingleElectron-Run2016G-WSkim-Prompt-v1-weightsReco-278817-279588", +"SingleElectron-Run2016G-WSkim-Prompt-v1-weightsReco-279589-279931" +] + +#folderlist=["/store/group/dpg_ecal/alca_ecalcalib/ecalMIBI/lbrianza/ntupleEoP/"] +folderlist=[ +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016B-ZSkim-Prompt_v2-weightsReco/273150-275376/271036_279931-Cal_Sep2016/withExtras/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016C-ZSkim-Prompt_v2-weightsReco/275420-276283/271036_279931-Cal_Sep2016/withExtras/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016D-ZSkim-Prompt_v2-weightsReco/276315-276811/271036_279931-Cal_Sep2016/withExtras/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016E-ZSkim-Prompt-v2-weightsReco/276830-277420/271036_279931-Cal_Sep2016/withExtras/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016F-ZSkim-Prompt-v1-weightsReco/277820-278808/271036_279931-Cal_Sep2016/withExtras/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016G-ZSkim-Prompt-v1-weightsReco/278817-279588/271036_279931-Cal_Sep2016/withExtras/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016G-ZSkim-Prompt-v1-weightsReco/279589-279931/271036_279931-Cal_Sep2016/withExtras/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/SingleElectron-Run2016B-WSkim-Prompt_v2-weightsReco/273150-275376/271036_279931-Cal_Sep2016/withExtras/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/SingleElectron-Run2016C-WSkim-Prompt_v2-weightsReco/275420-276283/271036_279931-Cal_Sep2016/withExtras/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/SingleElectron-Run2016D-WSkim-Prompt_v2-weightsReco/276315-276811/271036_279931-Cal_Sep2016/withExtras/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/SingleElectron-Run2016E-WSkim-Prompt-v2-weightsReco/276830-277420/271036_279931-Cal_Sep2016/withExtras/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/SingleElectron-Run2016F-WSkim-Prompt-v1-weightsReco/277820-278808/271036_279931-Cal_Sep2016/withExtras/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/SingleElectron-Run2016G-WSkim-Prompt-v1-weightsReco/278817-279588/271036_279931-Cal_Sep2016/withExtras/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/SingleElectron-Run2016G-WSkim-Prompt-v1-weightsReco/279589-279931/271036_279931-Cal_Sep2016/withExtras/", +] + + +TOP=currentDir +#cmscaf1nd + +#os.system("mkdir Job_"+ntupleName+""+nLoops+"loop_2016_newPcorr") +os.system("mkdir Job_"+ntupleName+""+nLoops+"2016_newPcorr") +os.system("mkdir cfg_"+ntupleName+"_"+nLoops+"2016_newPcorr") +os.system("mkdir ICset_"+ntupleName+"_"+nLoops+"2016_newPcorr") + +##RUN CALIBRATION ON BARREL +for b in range(len(split)): + for c in range(len(cut)): + for d in range(len(smoothCut)): + for e in range(len(applyPcorr)): + for f in range(len(applyEcorr)): + for g in range(len(energyType)): + fn = "Job_"+ntupleName+""+nLoops+"2016_newPcorr/Job_"+"EB"+"_"+split[b]+"_"+cut[c]+"_smoothCut"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g]; + outScript = open(fn+".sh","w"); + command = "ZFitter.exe -f EoverPcalibration_batch_"+ntupleName+".dat --EOverPCalib --outputPath output_"+ntupleName+"_"+nLoops+"2016_newPcorr_"+cut[c]+"_smooth"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g]+"/ --do"+"EB"+" --splitStat "+split[b]+" --nLoops "+nLoops+" --EPMin "+cut[c]+" --noPU --smoothCut "+smoothCut[d]+" --applyPcorr "+applyPcorr[e]+" --inputMomentumScale MomentumCalibration2016_eta1_eta1.root --applyEcorr "+applyEcorr[f]+" useRawEnergy "+energyType[g]+" --inputEnergyScale momentumCalibration2015_EB_scE.root" + print command; + outScript.write('#!/bin/bash'); + outScript.write("\n"+'cd '+CMSSWDir); + outScript.write("\n"+'eval `scram runtime -sh`'); + outScript.write("\n"+'cd -'); + outScript.write("\necho $PWD"); + outScript.write("\nls"); + + for j in range(len(ntuplelist)): + outScript.write("\necho \"copy main tree\" "); + outScript.write("\ncmsStage "+folderlist[j]+""+ntuplelist[j]+".root ./") + outScript.write("\necho \"copy extracalib tree\" "); + outScript.write("\ncmsStage "+folderlist[j]+"extraCalibTree-"+ntuplelist[j]+".root ./") + + outScript.write("\necho \"copiy additional files\" "); +# outScript.write("\ncp -v /afs/cern.ch/user/l/lbrianza/work/public/ntupleEoP/* .") + outScript.write("\ncmsStage "+folder_dat+"momentumCalibration2015_EB_pTk.root ./") + outScript.write("\ncmsStage "+folder_dat+"momentumCalibration2015_EB_scE.root ./") + outScript.write("\ncmsStage "+folder_dat+"EoverPcalibration_batch_"+ntupleName+".dat ./") + outScript.write("\ncmsStage "+folder_dat+"MomentumCalibration2016_eta1_eta1.root ./") + outScript.write("\necho \"end copy\" "); + + outScript.write("\nls") + outScript.write("\necho \"eseguo: "+command+"\" ") + outScript.write("\n"+command); + outScript.write("\nls") + outScript.write("\ncp -v -r output_"+ntupleName+"_"+nLoops+"2016_newPcorr_"+cut[c]+"_smooth"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g]+"/ "+currentDir) + outScript.close(); + os.system("chmod 777 "+currentDir+"/"+fn+".sh"); + command2 = "bsub -q cmscaf1nw -cwd "+currentDir+" "+currentDir+"/"+fn+".sh"; + if not options.generateOnly: + os.system(command2); + print command2 + + +##RUN CALIBRATION ON ENDCAP +for b in range(len(split)): + for c in range(len(cut)): + for d in range(len(smoothCut)): + for e in range(len(applyPcorr)): + for f in range(len(applyEcorr)): + for g in range(len(energyType)): + fn = "Job_"+ntupleName+""+nLoops+"2016_newPcorr/Job_"+"EE"+"_"+split[b]+"_"+cut[c]+"_smoothCut"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g]; + outScript = open(fn+".sh","w"); + command = "ZFitter.exe -f EoverPcalibration_batch_"+ntupleName+".dat --EOverPCalib --outputPath output_"+ntupleName+"_"+nLoops+"2016_newPcorr_"+cut[c]+"_smooth"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g]+"/ --do"+"EE"+" --splitStat "+split[b]+" --nLoops "+nLoops+" --EPMin "+cut[c]+" --noPU --smoothCut "+smoothCut[d]+" --applyPcorr "+applyPcorr[e]+" --inputMomentumScale MomentumCalibration2016_eta1_eta1.root --applyEcorr "+applyEcorr[f]+" useRawEnergy "+energyType[g]+" --inputEnergyScale momentumCalibration2015_EE_scE.root" + print command; + outScript.write('#!/bin/bash'); + outScript.write("\n"+'cd '+CMSSWDir); + outScript.write("\n"+'eval `scram runtime -sh`'); + outScript.write("\n"+'cd -'); + outScript.write("\necho $PWD"); + outScript.write("\nls"); + + for j in range(len(ntuplelist)): + outScript.write("\necho \"copy main tree\" "); + outScript.write("\ncmsStage "+folderlist[j]+""+ntuplelist[j]+".root ./") + outScript.write("\necho \"copy extracalib tree\" "); + outScript.write("\ncmsStage "+folderlist[j]+"extraCalibTree-"+ntuplelist[j]+".root ./") + + outScript.write("\necho \"copy additional files\" "); +# outScript.write("\ncp -v /afs/cern.ch/user/l/lbrianza/work/public/ntupleEoP/* .") + outScript.write("\ncmsStage "+folder_dat+"momentumCalibration2015_EE_pTk.root ./") + outScript.write("\ncmsStage "+folder_dat+"momentumCalibration2015_EE_scE.root ./") + outScript.write("\ncmsStage "+folder_dat+"EoverPcalibration_batch_"+ntupleName+".dat ./") + outScript.write("\ncmsStage "+folder_dat+"MomentumCalibration2016_eta1_eta1.root ./") + outScript.write("\necho \"end copy\" "); + outScript.write("\nls") + outScript.write("\necho \"eseguo: "+command+"\" ") + outScript.write("\n"+command); + outScript.write("\nls") + outScript.write("\ncp -v -r output_"+ntupleName+"_"+nLoops+"2016_newPcorr_"+cut[c]+"_smooth"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g]+"/ "+currentDir) + outScript.close(); + os.system("chmod 777 "+currentDir+"/"+fn+".sh"); + command2 = "bsub -q cmscaf1nw -cwd "+currentDir+" "+currentDir+"/"+fn+".sh"; + if not options.generateOnly: + os.system(command2); + print command2 + + +##CREATE CFG FILES TO PRODUCE CALIBRATION PLOTS LATER + +createAndPlotIC = "createAndPlotIC_"+ntupleName+"_"+nLoops+"2016_newPcorr.sh" +out2 = open(createAndPlotIC,"w") + +#for b in range(len(split)): +for c in range(len(cut)): + for d in range(len(smoothCut)): + for e in range(len(applyPcorr)): + for f in range(len(applyEcorr)): + for g in range(len(energyType)): + name = "EB"+"_"+cut[c]+"_smoothCut"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g] + fn = "cfg_"+ntupleName+"_"+nLoops+"2016_newPcorr/calibrationPlots_"+name+".py"; + folder = "output_"+ntupleName+"_"+nLoops+"2016_newPcorr_"+cut[c]+"_smooth"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g]+"/" + outScript = open(fn,"w"); + outScript.write("import FWCore.ParameterSet.Config as cms"); + outScript.write("\nprocess = cms.Process(\"calibrationPlotsEBparameters\")") + outScript.write("\nprocess.Options = cms.PSet(") + outScript.write("\n\tinFileName = cms.string(\""+TOP+"/"+folder+"FastCalibrator_Oct2015_runD_WZ_noEP_EB.root\"),") + outScript.write("\n\tinFileNameEven = cms.string(\""+TOP+"/"+folder+"FastCalibrator_Oct2015_runD_WZ_noEP_EB_even.root\"),") + outScript.write("\n\tinFileNameOdd = cms.string(\""+TOP+"/"+folder+"FastCalibrator_Oct2015_runD_WZ_noEP_EB_odd.root\"),") + outScript.write("\n\tnEtaBinsEB = cms.int32(1),") + outScript.write("\n\tnEtaBinsEE = cms.int32(1),") + outScript.write("\n\tis2012Calib = cms.bool(False),") + outScript.write("\n\tisEB = cms.bool(True),") + outScript.write("\n\tevalStat = cms.int32(1),") + outScript.write("\n\toutputFolder = cms.string(\""+folder+"\"),") + outScript.write("\n\toutFileName = cms.string(\""+name+".root\"),") + outScript.write("\n\toutputTxt = cms.string(\"IC_"+name+"\"),") + outScript.write("\n\tfileType = cms.string(\"cxx\")") + outScript.write("\n)") + out2.write("\nCalibrationPlots "+fn) + + +##CREATE CFG FILES TO PRODUCE CALIBRATION PLOTS LATER + +#for b in range(len(split)): +for c in range(len(cut)): + for d in range(len(smoothCut)): + for e in range(len(applyPcorr)): + for f in range(len(applyEcorr)): + for g in range(len(energyType)): + name = "EE"+"_"+cut[c]+"_smoothCut"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g] + fn = "cfg_"+ntupleName+"_"+nLoops+"2016_newPcorr/calibrationPlots_"+name+".py"; + folder = "output_"+ntupleName+"_"+nLoops+"2016_newPcorr_"+cut[c]+"_smooth"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g]+"/" + outScript = open(fn,"w"); + outScript.write("import FWCore.ParameterSet.Config as cms"); + outScript.write("\nprocess = cms.Process(\"calibrationPlotsEEparameters\")") + outScript.write("\nprocess.Options = cms.PSet(") + outScript.write("\n\tinFileName = cms.string(\""+TOP+"/"+folder+"FastCalibrator_Oct2015_runD_WZ_noEP_EE.root\"),") + outScript.write("\n\tinFileNameEven = cms.string(\""+TOP+"/"+folder+"FastCalibrator_Oct2015_runD_WZ_noEP_EE_even.root\"),") + outScript.write("\n\tinFileNameOdd = cms.string(\""+TOP+"/"+folder+"FastCalibrator_Oct2015_runD_WZ_noEP_EE_odd.root\"),") + outScript.write("\n\tnEtaBinsEB = cms.int32(1),") + outScript.write("\n\tnEtaBinsEE = cms.int32(1),") + outScript.write("\n\tis2012Calib = cms.bool(False),") + outScript.write("\n\tisEB = cms.bool(False),") + outScript.write("\n\tevalStat = cms.int32(1),") + outScript.write("\n\toutputFolder = cms.string(\""+folder+"\"),") + outScript.write("\n\toutFileName = cms.string(\""+name+".root\"),") + outScript.write("\n\toutputTxt = cms.string(\"IC_"+name+"\"),") + outScript.write("\n\tfileType = cms.string(\"cxx\")") + outScript.write("\n)") + out2.write("\nCalibrationPlots "+fn) + +##CREATE FOLDER CONTAINING THE FINAL SET OF IC (EB+EE) + +newFolder = "ICset_"+ntupleName+"_"+nLoops+"2016_newPcorr" + +for c in range(len(cut)): + for d in range(len(smoothCut)): + for e in range(len(applyPcorr)): + for f in range(len(applyEcorr)): + for g in range(len(energyType)): + name = "IC_"+cut[c]+"_smoothCut"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g] + folder = "output_"+ntupleName+"_"+nLoops+"2016_newPcorr_"+cut[c]+"_smooth"+smoothCut[d]+"_pCorr_"+applyPcorr[e]+"_ECorr_"+applyEcorr[f]+"_useRaw"+energyType[g]+"/" + out2.write("\ncat "+folder+"IC_EB*txt "+folder+"IC_EE*txt > "+newFolder+"/"+name+".txt") + diff --git a/ZFitter/submit_monitoring_jobs.py b/ZFitter/submit_monitoring_jobs.py new file mode 100644 index 00000000000..edca062ba1a --- /dev/null +++ b/ZFitter/submit_monitoring_jobs.py @@ -0,0 +1,145 @@ +#! /usr/bin/env python +import os +import glob +import math +from array import array +import sys +import time +import subprocess + +from optparse import OptionParser + +parser = OptionParser() + +parser.add_option('--generateOnly', action='store_true', dest='generateOnly', default=False, help='generate jobs only, without submitting them') + +(options, args) = parser.parse_args() + +#ntupleName = "data-DoubleEG-Run2016BCD_ZSkim_12p9fb_multifit" +ntupleName = "Run2016BCDEFG_WZSkim_12p9fb_multifit" +#ntupleName = "data-SingleElectron-Run2016BCD_WSkim_12p9fb_weights" +#options: "data-Run2015D-25ns-multifit", "data-Run2015D-25ns-multifit" or "data-Run2015D-25ns-stream". +folder = "/store/group/dpg_ecal/alca_ecalcalib/ecalMIBI/lbrianza/ntupleEoP/" +categories = ["EB","EB_0_1","EB_1_1479","EE","EE_1479_2","EE_2_25","EEp","EEp_1479_2","EEp_2_25","EEm","EEm_1479_2","EEm_2_25","EEp_2_225","EEp_225_25","EEm_2_225","EEm_225_25"] +yMIN = ["0.85","0.85","0.85","0.65","0.65","0.40","0.65","0.65","0.40","0.65","0.65","0.40","0.40","0.40","0.40","0.40"] +events = ["20000","20000","20000","10000","10000","10000","10000","10000","10000","10000","10000","10000","10000","10000","10000","10000"] +#yMIN = ["0.95","0.95","0.95","0.95","0.95","0.95","0.95","0.95","0.95","0.95","0.95","0.95"] +#categories = ["EEp","EEp_1479_2","EEp_2_25","EEm","EEm_1479_2","EEm_2_25"] +#yMIN = ["0.65","0.65","0.40","0.65","0.65","0.40"] +#ntuplelist = ["data-SingleElectron-Run2016BCD_WSkim_12p9fb_weights"] +#ntuplelist = ["data-DoubleEG-Run2016BCD_ZSkim_12p9fb_multifit"] +#ntuplelist = ["data-SingleElectron-Run2016BCD_WSkim_12p9fb_multifit","data-DoubleEG-Run2016BCD_ZSkim_12p9fb_multifit"] +ntuplelist = ["SingleElectron-Run2016B-WSkim-Prompt_v2-273150-275376","SingleElectron-Run2016C-WSkim-Prompt_v2-275420-276283","SingleElectron-Run2016D-WSkim-Prompt_v2-276315-276811","SingleElectron-Run2016E-WSkim-Prompt_v1-276830-277420","SingleElectron-Run2016F-WSkim-Prompt_v1-277820-278808","SingleElectron-Run2016G-WSkim-Prompt_v1-278817-279488"] + +#folderlist=["/store/group/dpg_ecal/alca_ecalcalib/ecalMIBI/lbrianza/ntupleEoP/"] +folderlist=[ +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/80X_dataRun2_Prompt_v10/SingleElectron-Run2016B-WSkim-Prompt_v2/273150-275376/271036_276811-ICHEP/withExtrasTest/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/80X_dataRun2_Prompt_v10/SingleElectron-Run2016C-WSkim-Prompt_v2/275420-276283/271036_276811-ICHEP/withExtrasTest/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/80X_dataRun2_Prompt_v10/SingleElectron-Run2016D-WSkim-Prompt_v2/276315-276811/271036_276811-ICHEP/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/80X_dataRun2_Prompt_v10/SingleElectron-Run2016E-WSkim-Prompt_v1/276830-277420/276830-277420/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/80X_dataRun2_Prompt_v10/SingleElectron-Run2016F-WSkim-Prompt_v1/277820-278808/271036-278808/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/80X_dataRun2_Prompt_v10/SingleElectron-Run2016G-WSkim-Prompt_v1/278817-279488/271036-279116/"] + + +currentDir = os.getcwd(); +CMSSWDir = currentDir+"/../"; + +os.system("mkdir Job_monitoring_"+ntupleName) + +for i in range(len(categories)): + fn = "Job_monitoring_"+ntupleName+"/Job_"+categories[i]; + + outScript = open(fn+".sh","w"); +# command = "ZFitter.exe -f EoverPmonitoring_batch_"+ntupleName+".dat --evtsPerPoint 200000 --laserMonitoringEPvsPU --EBEE "+categories[i]+" --yMIN 0.95 --yMAX 1.05 --LUMI 12.9 --dayMin 15-03-2016 --dayMax 01-08-2016" #CAMBIA 1.15!!!! #use this if you want to run vs Nvtx +# command = "ZFitter.exe -f EoverPmonitoring_batch_"+ntupleName+".dat --evtsPerPoint 200000 --laserMonitoringEP --EBEE "+categories[i]+" --yMIN 0.8 --yMAX 1.20 --LUMI 12.9 --dayMin 15-03-2016 --dayMax 01-09-2016" #CAMBIA 1.15!!!! #use this if you want to run E/p vs LC + command = "ZFitter.exe -f EoverPmonitoring_batch_"+ntupleName+".dat --evtsPerPoint "+events[i]+" --laserMonitoringEP --EBEE "+categories[i]+" --yMIN "+yMIN[i]+" --yMAX 1.15 --LUMI 12.9 --dayMin 15-03-2016 --dayMax 01-09-2016" + print command; + outScript.write('#!/bin/bash'); + outScript.write("\n"+'cd '+CMSSWDir); + outScript.write("\n"+'eval `scram runtime -sh`'); + outScript.write("\n"+'cd -'); + outScript.write("\necho $PWD"); + outScript.write("mkdir "+categories[i]+"__"); + outScript.write("\nll"); + + for j in range(len(ntuplelist)): + outScript.write("\necho \"copy main tree\" "); + outScript.write("\ncmsStage "+folderlist[j]+""+ntuplelist[j]+".root ./") +# outScript.write("\necho \"copy extracalib tree\" "); +# outScript.write("\ncmsStage "+folderlist[j]+"extraCalibTree-"+ntuplelist[j]+".root ./") + + outScript.write("\necho \"copia13\" "); +# outScript.write("\ncp -v /afs/cern.ch/user/l/lbrianza/work/public/ntupleEoP/* .") + outScript.write("\ncmsStage "+folder+"momentumCalibration2015_EB_pTk.root ./") + outScript.write("\necho \"copia14\" "); + outScript.write("\ncmsStage "+folder+"momentumCalibration2015_EB_scE.root ./") + outScript.write("\necho \"copia15\" "); + outScript.write("\ncmsStage "+folder+"momentumCalibration2015_EE_pTk.root ./") + outScript.write("\necho \"copia14\" "); + outScript.write("\ncmsStage "+folder+"momentumCalibration2015_EE_scE.root ./") + outScript.write("\necho \"copia15\" "); + outScript.write("\ncmsStage "+folder+"EoverPmonitoring_batch_"+ntupleName+".dat ./") + outScript.write("\necho \"fine copia\" "); + + outScript.write("\nls") + outScript.write("\necho \"eseguo: "+command+"\" ") + outScript.write("\n"+command); + outScript.write("\nls") + outScript.write("\ncp -v -r "+categories[i]+"__/ "+currentDir+"/"+categories[i]+"_"+ntupleName+"/") + outScript.close(); + os.system("chmod 777 "+currentDir+"/"+fn+".sh"); + command2 = "bsub -q cmscaf1nd -cwd "+currentDir+" "+currentDir+"/"+fn+".sh"; + if not options.generateOnly: + os.system(command2); + print command2 + + + + + + +''' +fn = "Job_monitoring_"+ntupleName+"/Job_"+"EE"; +outScript = open(fn+".sh","w"); +command = "ZFitter.exe -f EoverPcalibration_batch_"+ntupleName+".dat --evtsPerPoint 50000 --laserMonitoringEPvsPU --EBEE EE --yMIN 0.6 --yMAX 1.15 --LUMI 12.9 --dayMin 15-03-2016 --dayMax 01-08-2016" +print command; +outScript.write('#!/bin/bash'); +outScript.write("\n"+'cd '+CMSSWDir); +outScript.write("\n"+'eval `scram runtime -sh`'); +outScript.write("\n"+'cd -'); +outScript.write("\necho $PWD"); +outScript.write("mkdir EE__"); +outScript.write("\nll"); + + +outScript.write("\necho \"copia1\" "); +outScript.write("\ncmsStage "+folder+ntupleName+".root ./") +outScript.write("\necho \"copia2\" "); +outScript.write("\ncmsStage "+folder+"extraCalibTree-"+ntupleName+".root ./") + +outScript.write("\necho \"copia13\" "); +# outScript.write("\ncp -v /afs/cern.ch/user/l/lbrianza/work/public/ntupleEoP/* .") +outScript.write("\ncmsStage "+folder+"momentumCalibration2015_EE_pTk.root ./") +outScript.write("\necho \"copia14\" "); +outScript.write("\ncmsStage "+folder+"momentumCalibration2015_EE_scE.root ./") +outScript.write("\necho \"copia15\" "); +outScript.write("\ncmsStage "+folder+"EoverPcalibration_batch_"+ntupleName+".dat ./") +outScript.write("\necho \"fine copia\" "); + +outScript.write("\nls") +outScript.write("\necho \"eseguo: "+command+"\" ") +outScript.write("\n"+command); +outScript.write("\nls") +outScript.write("\ncp -v -r EE__/ "+currentDir+"/EE_"+ntupleName+"/") +outScript.close(); +os.system("chmod 777 "+currentDir+"/"+fn+".sh"); +command2 = "bsub -q cmscaf1nd -cwd "+currentDir+" "+currentDir+"/"+fn+".sh"; +if not options.generateOnly: + os.system(command2); +print command2 +''' + + + + + diff --git a/ZFitter/submit_monitoring_jobs_multifit.py b/ZFitter/submit_monitoring_jobs_multifit.py new file mode 100644 index 00000000000..f0296235b7f --- /dev/null +++ b/ZFitter/submit_monitoring_jobs_multifit.py @@ -0,0 +1,179 @@ +#! /usr/bin/env python +import os +import glob +import math +from array import array +import sys +import time +import subprocess + +from optparse import OptionParser + +parser = OptionParser() + +parser.add_option('--generateOnly', action='store_true', dest='generateOnly', default=False, help='generate jobs only, without submitting them') + +(options, args) = parser.parse_args() + +#ntupleName = "data-DoubleEG-Run2016BCD_ZSkim_12p9fb_multifit" +ntupleName = "Run2016BCDEFG_WZSkim_Cal_Sep2016_final_v3_multifit" +#ntupleName = "data-SingleElectron-Run2016BCD_WSkim_12p9fb_weights" +#options: "data-Run2015D-25ns-multifit", "data-Run2015D-25ns-multifit" or "data-Run2015D-25ns-stream". +folder = "/store/group/dpg_ecal/alca_ecalcalib/ecalMIBI/lbrianza/ntupleEoP/" +categories = ["EB","EB_0_1","EB_1_1479","EE","EE_1479_2","EE_2_25","EEp","EEp_1479_2","EEp_2_25","EEm","EEm_1479_2","EEm_2_25","EEp_2_225","EEp_225_25","EEm_2_225","EEm_225_25"] +yMIN = ["0.85","0.85","0.85","0.65","0.65","0.40","0.65","0.65","0.40","0.65","0.65","0.40","0.40","0.40","0.40","0.40"] +events = ["20000","20000","20000","10000","10000","10000","10000","10000","10000","10000","10000","10000","10000","10000","10000","10000"] +#yMIN = ["0.95","0.95","0.95","0.95","0.95","0.95","0.95","0.95","0.95","0.95","0.95","0.95"] +#categories = ["EEp","EEp_1479_2","EEp_2_25","EEm","EEm_1479_2","EEm_2_25"] +#yMIN = ["0.65","0.65","0.40","0.65","0.65","0.40"] +#ntuplelist = ["data-SingleElectron-Run2016BCD_WSkim_12p9fb_weights"] +#ntuplelist = ["data-DoubleEG-Run2016BCD_ZSkim_12p9fb_multifit"] +#ntuplelist = ["data-SingleElectron-Run2016BCD_WSkim_12p9fb_multifit","data-DoubleEG-Run2016BCD_ZSkim_12p9fb_multifit"] +#ntuplelist = ["SingleElectron-Run2016B-WSkim-Prompt_v2-273150-275376","SingleElectron-Run2016C-WSkim-Prompt_v2-275420-276283","SingleElectron-Run2016D-WSkim-Prompt_v2-276315-276811","SingleElectron-Run2016E-WSkim-Prompt_v1-276830-277420","SingleElectron-Run2016F-WSkim-Prompt_v1-277820-278808","SingleElectron-Run2016G-WSkim-Prompt_v1-278817-279488"] +#ntuplelist=["DoubleEG-Run2016B-ZSkim-Prompt_v2-273150-275376.root","DoubleEG-Run2016C-ZSkim-Prompt_v2-275420-276283.root","DoubleEG-Run2016D-ZSkim-Prompt_v2-276315-276811.root", +#"DoubleEG-Run2016E-ZSkim-Prompt-v2-276830-277420.root","DoubleEG-Run2016F-ZSkim-Prompt-v1-277820-278808.root","DoubleEG-Run2016G-ZSkim-Prompt-v1-278817-279588.root","DoubleEG-Run2016G-ZSkim-Prompt-v1-279589-279931.root"] + +ntuplelist = [ +#"DoubleEG-Run2016B-ZSkim-Prompt_v2-273150-275376", +#"DoubleEG-Run2016C-ZSkim-Prompt_v2-275420-276283", +#"DoubleEG-Run2016D-ZSkim-Prompt_v2-276315-276811", +#"DoubleEG-Run2016E-ZSkim-Prompt-v2-276830-277420", +#"DoubleEG-Run2016F-ZSkim-Prompt-v1-277820-278808", +#"DoubleEG-Run2016G-ZSkim-Prompt-v1-278817-279588", +#"DoubleEG-Run2016G-ZSkim-Prompt-v1-279589-279931", +"SingleElectron-Run2016B-WSkim-Prompt_v2-273150-275376", +"SingleElectron-Run2016C-WSkim-Prompt_v2-275420-276283", +"SingleElectron-Run2016D-WSkim-Prompt_v2-276315-276811", +"SingleElectron-Run2016E-WSkim-Prompt-v2-276830-277420", +"SingleElectron-Run2016F-WSkim-Prompt-v1-277820-278808", +"SingleElectron-Run2016G-WSkim-Prompt-v1-278817-279588", +"SingleElectron-Run2016G-WSkim-Prompt-v1-279589-279931" +] + +folderlist=[ +#"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016B-ZSkim-Prompt_v2/273150-275376/271036_279931-Cal_Sep2016/withExtras2/", +#"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016C-ZSkim-Prompt_v2/275420-276283/271036_279931-Cal_Sep2016/withExtras2/", +#"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016D-ZSkim-Prompt_v2/276315-276811/271036_279931-Cal_Sep2016/withExtras2/", +#"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016E-ZSkim-Prompt-v2/276830-277420/271036_279931-Cal_Sep2016/withExtras2/", +#"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016F-ZSkim-Prompt-v1/277820-278808/271036_279931-Cal_Sep2016/withExtras2/", +#"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016G-ZSkim-Prompt-v1/278817-279588/271036_279931-Cal_Sep2016/withExtras2/", +#"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016G-ZSkim-Prompt-v1/279589-279931/271036_279931-Cal_Sep2016/withExtras2/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/SingleElectron-Run2016B-WSkim-Prompt_v2/273150-275376/271036_279931-Cal_Sep2016/withExtras/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/SingleElectron-Run2016C-WSkim-Prompt_v2/275420-276283/271036_279931-Cal_Sep2016/withExtras/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/SingleElectron-Run2016D-WSkim-Prompt_v2/276315-276811/271036_279931-Cal_Sep2016/withExtras/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/SingleElectron-Run2016E-WSkim-Prompt-v2/276830-277420/271036_279931-Cal_Sep2016/withExtras/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/SingleElectron-Run2016F-WSkim-Prompt-v1/277820-278808/271036_279931-Cal_Sep2016/withExtras/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/SingleElectron-Run2016G-WSkim-Prompt-v1/278817-279588/271036_279931-Cal_Sep2016/withExtras/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/SingleElectron-Run2016G-WSkim-Prompt-v1/279589-279931/271036_279931-Cal_Sep2016/withExtras/" +] + + +#folderlist=["/store/group/dpg_ecal/alca_ecalcalib/ecalMIBI/lbrianza/ntupleEoP/"] +#folderlist=["/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/80X_dataRun2_Prompt_v10/SingleElectron-Run2016B-WSkim-Prompt_v2/273150-275376/271036_276811-ICHEP/withExtrasTest/","/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/80X_dataRun2_Prompt_v10/SingleElectron-Run2016C-WSkim-Prompt_v2/275420-276283/271036_276811-ICHEP/withExtrasTest/","/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/80X_dataRun2_Prompt_v10/SingleElectron-Run2016D-WSkim-Prompt_v2/276315-276811/271036_276811-ICHEP/","/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/80X_dataRun2_Prompt_v10/SingleElectron-Run2016E-WSkim-Prompt_v1/276830-277420/276830-277420/","/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/80X_dataRun2_Prompt_v10/SingleElectron-Run2016F-WSkim-Prompt_v1/277820-278808/271036-278808/","/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/80X_dataRun2_Prompt_v10/SingleElectron-Run2016G-WSkim-Prompt_v1/278817-279488/271036-279116/"] + +#folderlist=["/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016B-ZSkim-Prompt_v2/273150-275376/271036_279931-Cal_Sep2016/withExtras2/","/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016C-ZSkim-Prompt_v2/275420-276283/271036_279931-Cal_Sep2016/withExtras2/","/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016D-ZSkim-Prompt_v2/276315-276811/271036_279931-Cal_Sep2016/withExtras2/","/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016E-ZSkim-Prompt-v2/276830-277420/271036_279931-Cal_Sep2016/withExtras2/","/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016F-ZSkim-Prompt-v1/277820-278808/271036_279931-Cal_Sep2016/withExtras2/","/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016G-ZSkim-Prompt-v1/278817-279588/271036_279931-Cal_Sep2016/withExtras2/","/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016G-ZSkim-Prompt-v1/279589-279931/271036_279931-Cal_Sep2016/withExtras2/"] + + +currentDir = os.getcwd(); +CMSSWDir = currentDir+"/../"; + +os.system("mkdir Job_monitoring_"+ntupleName) + +for i in range(len(categories)): + fn = "Job_monitoring_"+ntupleName+"/Job_"+categories[i]; + + outScript = open(fn+".sh","w"); + command = "ZFitter.exe -f EoverPmonitoring_batch_"+ntupleName+".dat --evtsPerPoint 200000 --laserMonitoringEP --EBEE "+categories[i]+" --yMIN 0.95 --yMAX 1.05 --LUMI 24.1 --dayMin 15-03-2016 --dayMax 15-09-2016 --EoPvsPU 1" #use this if you want to run vs Nvtx +# command = "ZFitter.exe -f EoverPmonitoring_batch_"+ntupleName+".dat --evtsPerPoint 200000 --laserMonitoringEP --EBEE "+categories[i]+" --yMIN 0.8 --yMAX 1.20 --LUMI 24.1 --dayMin 15-03-2016 --dayMax 15-09-2016" #use this if you want to run E/p vs LC +# command = "ZFitter.exe -f EoverPmonitoring_batch_"+ntupleName+".dat --evtsPerPoint "+events[i]+" --laserMonitoringEP --EBEE "+categories[i]+" --yMIN "+yMIN[i]+" --yMAX 1.15 --LUMI 24.1 --dayMin 15-03-2016 --dayMax 15-09-2016" #default, to be run for E/p vs time + print command; + outScript.write('#!/bin/bash'); + outScript.write("\n"+'cd '+CMSSWDir); + outScript.write("\n"+'eval `scram runtime -sh`'); + outScript.write("\n"+'cd -'); + outScript.write("\necho $PWD"); + outScript.write("mkdir "+categories[i]+"__"); + outScript.write("\nll"); + + for j in range(len(ntuplelist)): + outScript.write("\necho \"copy main tree\" "); + outScript.write("\ncmsStage "+folderlist[j]+""+ntuplelist[j]+".root ./") +# outScript.write("\ncmsStage "+folderlist[j]+""+ntuplelist[j]+" ./") +# outScript.write("\necho \"copy extracalib tree\" "); +# outScript.write("\ncmsStage "+folderlist[j]+"extraCalibTree-"+ntuplelist[j]+".root ./") + + outScript.write("\necho \"copia13\" "); +# outScript.write("\ncp -v /afs/cern.ch/user/l/lbrianza/work/public/ntupleEoP/* .") + outScript.write("\ncmsStage "+folder+"momentumCalibration2015_EB_pTk.root ./") + outScript.write("\necho \"copia14\" "); + outScript.write("\ncmsStage "+folder+"momentumCalibration2015_EB_scE.root ./") + outScript.write("\necho \"copia15\" "); + outScript.write("\ncmsStage "+folder+"momentumCalibration2015_EE_pTk.root ./") + outScript.write("\necho \"copia14\" "); + outScript.write("\ncmsStage "+folder+"momentumCalibration2015_EE_scE.root ./") + outScript.write("\necho \"copia15\" "); + outScript.write("\ncmsStage "+folder+"EoverPmonitoring_batch_"+ntupleName+".dat ./") + outScript.write("\necho \"fine copia\" "); + + outScript.write("\nls") + outScript.write("\necho \"eseguo: "+command+"\" ") + outScript.write("\n"+command); + outScript.write("\nls") + outScript.write("\ncp -v -r "+categories[i]+"__/ "+currentDir+"/"+categories[i]+"_"+ntupleName+"/") + outScript.close(); + os.system("chmod 777 "+currentDir+"/"+fn+".sh"); + command2 = "bsub -q cmscaf1nd -cwd "+currentDir+" "+currentDir+"/"+fn+".sh"; + if not options.generateOnly: + os.system(command2); + print command2 + + + + + + +''' +fn = "Job_monitoring_"+ntupleName+"/Job_"+"EE"; +outScript = open(fn+".sh","w"); +command = "ZFitter.exe -f EoverPcalibration_batch_"+ntupleName+".dat --evtsPerPoint 50000 --laserMonitoringEPvsPU --EBEE EE --yMIN 0.6 --yMAX 1.15 --LUMI 12.9 --dayMin 15-03-2016 --dayMax 01-08-2016" +print command; +outScript.write('#!/bin/bash'); +outScript.write("\n"+'cd '+CMSSWDir); +outScript.write("\n"+'eval `scram runtime -sh`'); +outScript.write("\n"+'cd -'); +outScript.write("\necho $PWD"); +outScript.write("mkdir EE__"); +outScript.write("\nll"); + + +outScript.write("\necho \"copia1\" "); +outScript.write("\ncmsStage "+folder+ntupleName+".root ./") +outScript.write("\necho \"copia2\" "); +outScript.write("\ncmsStage "+folder+"extraCalibTree-"+ntupleName+".root ./") + +outScript.write("\necho \"copia13\" "); +# outScript.write("\ncp -v /afs/cern.ch/user/l/lbrianza/work/public/ntupleEoP/* .") +outScript.write("\ncmsStage "+folder+"momentumCalibration2015_EE_pTk.root ./") +outScript.write("\necho \"copia14\" "); +outScript.write("\ncmsStage "+folder+"momentumCalibration2015_EE_scE.root ./") +outScript.write("\necho \"copia15\" "); +outScript.write("\ncmsStage "+folder+"EoverPcalibration_batch_"+ntupleName+".dat ./") +outScript.write("\necho \"fine copia\" "); + +outScript.write("\nls") +outScript.write("\necho \"eseguo: "+command+"\" ") +outScript.write("\n"+command); +outScript.write("\nls") +outScript.write("\ncp -v -r EE__/ "+currentDir+"/EE_"+ntupleName+"/") +outScript.close(); +os.system("chmod 777 "+currentDir+"/"+fn+".sh"); +command2 = "bsub -q cmscaf1nd -cwd "+currentDir+" "+currentDir+"/"+fn+".sh"; +if not options.generateOnly: + os.system(command2); +print command2 +''' + + + + + diff --git a/ZFitter/submit_monitoring_jobs_weights.py b/ZFitter/submit_monitoring_jobs_weights.py new file mode 100644 index 00000000000..bf184f524c4 --- /dev/null +++ b/ZFitter/submit_monitoring_jobs_weights.py @@ -0,0 +1,178 @@ +#! /usr/bin/env python +import os +import glob +import math +from array import array +import sys +import time +import subprocess + +from optparse import OptionParser + +parser = OptionParser() + +parser.add_option('--generateOnly', action='store_true', dest='generateOnly', default=False, help='generate jobs only, without submitting them') + +(options, args) = parser.parse_args() + +#ntupleName = "data-DoubleEG-Run2016BCD_ZSkim_12p9fb_multifit" +ntupleName = "Run2016BCDEFG_WZSkim_Cal_Sep2016_final_v3_weights" +#ntupleName = "data-SingleElectron-Run2016BCD_WSkim_12p9fb_weights" +#options: "data-Run2015D-25ns-multifit", "data-Run2015D-25ns-multifit" or "data-Run2015D-25ns-stream". +folder = "/store/group/dpg_ecal/alca_ecalcalib/ecalMIBI/lbrianza/ntupleEoP/" +categories = ["EB","EB_0_1","EB_1_1479","EE","EE_1479_2","EE_2_25","EEp","EEp_1479_2","EEp_2_25","EEm","EEm_1479_2","EEm_2_25","EEp_2_225","EEp_225_25","EEm_2_225","EEm_225_25"] +yMIN = ["0.85","0.85","0.85","0.65","0.65","0.40","0.65","0.65","0.40","0.65","0.65","0.40","0.40","0.40","0.40","0.40"] +events = ["20000","20000","20000","10000","10000","10000","10000","10000","10000","10000","10000","10000","10000","10000","10000","10000"] +#yMIN = ["0.95","0.95","0.95","0.95","0.95","0.95","0.95","0.95","0.95","0.95","0.95","0.95"] +#categories = ["EEp","EEp_1479_2","EEp_2_25","EEm","EEm_1479_2","EEm_2_25"] +#yMIN = ["0.65","0.65","0.40","0.65","0.65","0.40"] +#ntuplelist = ["data-SingleElectron-Run2016BCD_WSkim_12p9fb_weights"] +#ntuplelist = ["data-DoubleEG-Run2016BCD_ZSkim_12p9fb_multifit"] +#ntuplelist = ["data-SingleElectron-Run2016BCD_WSkim_12p9fb_multifit","data-DoubleEG-Run2016BCD_ZSkim_12p9fb_multifit"] +#ntuplelist = ["SingleElectron-Run2016B-WSkim-Prompt_v2-273150-275376","SingleElectron-Run2016C-WSkim-Prompt_v2-275420-276283","SingleElectron-Run2016D-WSkim-Prompt_v2-276315-276811","SingleElectron-Run2016E-WSkim-Prompt_v1-276830-277420","SingleElectron-Run2016F-WSkim-Prompt_v1-277820-278808","SingleElectron-Run2016G-WSkim-Prompt_v1-278817-279488"] +#ntuplelist=["DoubleEG-Run2016B-ZSkim-Prompt_v2-273150-275376.root","DoubleEG-Run2016C-ZSkim-Prompt_v2-275420-276283.root","DoubleEG-Run2016D-ZSkim-Prompt_v2-276315-276811.root", +#"DoubleEG-Run2016E-ZSkim-Prompt-v2-276830-277420.root","DoubleEG-Run2016F-ZSkim-Prompt-v1-277820-278808.root","DoubleEG-Run2016G-ZSkim-Prompt-v1-278817-279588.root","DoubleEG-Run2016G-ZSkim-Prompt-v1-279589-279931.root"] +ntuplelist = [ +#"DoubleEG-Run2016B-ZSkim-Prompt_v2-weightsReco-273150-275376", +#"DoubleEG-Run2016C-ZSkim-Prompt_v2-weightsReco-275420-276283", +#"DoubleEG-Run2016D-ZSkim-Prompt_v2-weightsReco-276315-276811", +#"DoubleEG-Run2016E-ZSkim-Prompt-v2-weightsReco-276830-277420", +#"DoubleEG-Run2016F-ZSkim-Prompt-v1-weightsReco-277820-278808", +#"DoubleEG-Run2016G-ZSkim-Prompt-v1-weightsReco-278817-279588", +#"DoubleEG-Run2016G-ZSkim-Prompt-v1-weightsReco-279589-279931", +"SingleElectron-Run2016B-WSkim-Prompt_v2-weightsReco-273150-275376", +"SingleElectron-Run2016C-WSkim-Prompt_v2-weightsReco-275420-276283", +"SingleElectron-Run2016D-WSkim-Prompt_v2-weightsReco-276315-276811", +"SingleElectron-Run2016E-WSkim-Prompt-v2-weightsReco-276830-277420", +"SingleElectron-Run2016F-WSkim-Prompt-v1-weightsReco-277820-278808", +"SingleElectron-Run2016G-WSkim-Prompt-v1-weightsReco-278817-279588", +"SingleElectron-Run2016G-WSkim-Prompt-v1-weightsReco-279589-279931" +] + +folderlist=[ +#"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016B-ZSkim-Prompt_v2-weightsReco/273150-275376/271036_279931-Cal_Sep2016/withExtras/", +#"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016C-ZSkim-Prompt_v2-weightsReco/275420-276283/271036_279931-Cal_Sep2016/withExtras/", +#"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016D-ZSkim-Prompt_v2-weightsReco/276315-276811/271036_279931-Cal_Sep2016/withExtras/", +#"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016E-ZSkim-Prompt-v2-weightsReco/276830-277420/271036_279931-Cal_Sep2016/withExtras/", +#"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016F-ZSkim-Prompt-v1-weightsReco/277820-278808/271036_279931-Cal_Sep2016/withExtras/", +#"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016G-ZSkim-Prompt-v1-weightsReco/278817-279588/271036_279931-Cal_Sep2016/withExtras/", +#"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016G-ZSkim-Prompt-v1-weightsReco/279589-279931/271036_279931-Cal_Sep2016/withExtras/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/SingleElectron-Run2016B-WSkim-Prompt_v2-weightsReco/273150-275376/271036_279931-Cal_Sep2016/withExtras/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/SingleElectron-Run2016C-WSkim-Prompt_v2-weightsReco/275420-276283/271036_279931-Cal_Sep2016/withExtras/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/SingleElectron-Run2016D-WSkim-Prompt_v2-weightsReco/276315-276811/271036_279931-Cal_Sep2016/withExtras/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/SingleElectron-Run2016E-WSkim-Prompt-v2-weightsReco/276830-277420/271036_279931-Cal_Sep2016/withExtras/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/SingleElectron-Run2016F-WSkim-Prompt-v1-weightsReco/277820-278808/271036_279931-Cal_Sep2016/withExtras/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/SingleElectron-Run2016G-WSkim-Prompt-v1-weightsReco/278817-279588/271036_279931-Cal_Sep2016/withExtras/", +"/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/SingleElectron-Run2016G-WSkim-Prompt-v1-weightsReco/279589-279931/271036_279931-Cal_Sep2016/withExtras/" +] + + +#folderlist=["/store/group/dpg_ecal/alca_ecalcalib/ecalMIBI/lbrianza/ntupleEoP/"] +#folderlist=["/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/80X_dataRun2_Prompt_v10/SingleElectron-Run2016B-WSkim-Prompt_v2/273150-275376/271036_276811-ICHEP/withExtrasTest/","/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/80X_dataRun2_Prompt_v10/SingleElectron-Run2016C-WSkim-Prompt_v2/275420-276283/271036_276811-ICHEP/withExtrasTest/","/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/80X_dataRun2_Prompt_v10/SingleElectron-Run2016D-WSkim-Prompt_v2/276315-276811/271036_276811-ICHEP/","/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/80X_dataRun2_Prompt_v10/SingleElectron-Run2016E-WSkim-Prompt_v1/276830-277420/276830-277420/","/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/80X_dataRun2_Prompt_v10/SingleElectron-Run2016F-WSkim-Prompt_v1/277820-278808/271036-278808/","/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/80X_dataRun2_Prompt_v10/SingleElectron-Run2016G-WSkim-Prompt_v1/278817-279488/271036-279116/"] + +#folderlist=["/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016B-ZSkim-Prompt_v2/273150-275376/271036_279931-Cal_Sep2016/withExtras2/","/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016C-ZSkim-Prompt_v2/275420-276283/271036_279931-Cal_Sep2016/withExtras2/","/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016D-ZSkim-Prompt_v2/276315-276811/271036_279931-Cal_Sep2016/withExtras2/","/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016E-ZSkim-Prompt-v2/276830-277420/271036_279931-Cal_Sep2016/withExtras2/","/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016F-ZSkim-Prompt-v1/277820-278808/271036_279931-Cal_Sep2016/withExtras2/","/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016G-ZSkim-Prompt-v1/278817-279588/271036_279931-Cal_Sep2016/withExtras2/","/store/group/dpg_ecal/alca_ecalcalib/ecalelf/ntuples/13TeV/ALCARERECO/Cal_Sep2016_final_v3/DoubleEG-Run2016G-ZSkim-Prompt-v1/279589-279931/271036_279931-Cal_Sep2016/withExtras2/"] + + +currentDir = os.getcwd(); +CMSSWDir = currentDir+"/../"; + +os.system("mkdir Job_monitoring_"+ntupleName) + +for i in range(len(categories)): + fn = "Job_monitoring_"+ntupleName+"/Job_"+categories[i]; + + outScript = open(fn+".sh","w"); + command = "ZFitter.exe -f EoverPmonitoring_batch_"+ntupleName+".dat --evtsPerPoint 200000 --laserMonitoringEP --EBEE "+categories[i]+" --yMIN 0.95 --yMAX 1.05 --LUMI 24.1 --dayMin 15-03-2016 --dayMax 15-09-2016 --EoPvsPU 1" #use this if you want to run vs Nvtx +# command = "ZFitter.exe -f EoverPmonitoring_batch_"+ntupleName+".dat --evtsPerPoint 200000 --laserMonitoringEP --EBEE "+categories[i]+" --yMIN 0.8 --yMAX 1.20 --LUMI 24.1 --dayMin 15-03-2016 --dayMax 01-09-2016" #use this if you want to run E/p vs LC +# command = "ZFitter.exe -f EoverPmonitoring_batch_"+ntupleName+".dat --evtsPerPoint "+events[i]+" --laserMonitoringEP --EBEE "+categories[i]+" --yMIN "+yMIN[i]+" --yMAX 1.15 --LUMI 24.1 --dayMin 15-03-2016 --dayMax 15-09-2016" #default, to be run for E/p vs time + print command; + outScript.write('#!/bin/bash'); + outScript.write("\n"+'cd '+CMSSWDir); + outScript.write("\n"+'eval `scram runtime -sh`'); + outScript.write("\n"+'cd -'); + outScript.write("\necho $PWD"); + outScript.write("mkdir "+categories[i]+"__"); + outScript.write("\nll"); + + for j in range(len(ntuplelist)): + outScript.write("\necho \"copy main tree\" "); + outScript.write("\ncmsStage "+folderlist[j]+""+ntuplelist[j]+".root ./") +# outScript.write("\ncmsStage "+folderlist[j]+""+ntuplelist[j]+" ./") +# outScript.write("\necho \"copy extracalib tree\" "); +# outScript.write("\ncmsStage "+folderlist[j]+"extraCalibTree-"+ntuplelist[j]+".root ./") + + outScript.write("\necho \"copia13\" "); +# outScript.write("\ncp -v /afs/cern.ch/user/l/lbrianza/work/public/ntupleEoP/* .") + outScript.write("\ncmsStage "+folder+"momentumCalibration2015_EB_pTk.root ./") + outScript.write("\necho \"copia14\" "); + outScript.write("\ncmsStage "+folder+"momentumCalibration2015_EB_scE.root ./") + outScript.write("\necho \"copia15\" "); + outScript.write("\ncmsStage "+folder+"momentumCalibration2015_EE_pTk.root ./") + outScript.write("\necho \"copia14\" "); + outScript.write("\ncmsStage "+folder+"momentumCalibration2015_EE_scE.root ./") + outScript.write("\necho \"copia15\" "); + outScript.write("\ncmsStage "+folder+"EoverPmonitoring_batch_"+ntupleName+".dat ./") + outScript.write("\necho \"fine copia\" "); + + outScript.write("\nls") + outScript.write("\necho \"eseguo: "+command+"\" ") + outScript.write("\n"+command); + outScript.write("\nls") + outScript.write("\ncp -v -r "+categories[i]+"__/ "+currentDir+"/"+categories[i]+"_"+ntupleName+"/") + outScript.close(); + os.system("chmod 777 "+currentDir+"/"+fn+".sh"); + command2 = "bsub -q cmscaf1nd -cwd "+currentDir+" "+currentDir+"/"+fn+".sh"; + if not options.generateOnly: + os.system(command2); + print command2 + + + + + + +''' +fn = "Job_monitoring_"+ntupleName+"/Job_"+"EE"; +outScript = open(fn+".sh","w"); +command = "ZFitter.exe -f EoverPcalibration_batch_"+ntupleName+".dat --evtsPerPoint 50000 --laserMonitoringEPvsPU --EBEE EE --yMIN 0.6 --yMAX 1.15 --LUMI 12.9 --dayMin 15-03-2016 --dayMax 01-08-2016" +print command; +outScript.write('#!/bin/bash'); +outScript.write("\n"+'cd '+CMSSWDir); +outScript.write("\n"+'eval `scram runtime -sh`'); +outScript.write("\n"+'cd -'); +outScript.write("\necho $PWD"); +outScript.write("mkdir EE__"); +outScript.write("\nll"); + + +outScript.write("\necho \"copia1\" "); +outScript.write("\ncmsStage "+folder+ntupleName+".root ./") +outScript.write("\necho \"copia2\" "); +outScript.write("\ncmsStage "+folder+"extraCalibTree-"+ntupleName+".root ./") + +outScript.write("\necho \"copia13\" "); +# outScript.write("\ncp -v /afs/cern.ch/user/l/lbrianza/work/public/ntupleEoP/* .") +outScript.write("\ncmsStage "+folder+"momentumCalibration2015_EE_pTk.root ./") +outScript.write("\necho \"copia14\" "); +outScript.write("\ncmsStage "+folder+"momentumCalibration2015_EE_scE.root ./") +outScript.write("\necho \"copia15\" "); +outScript.write("\ncmsStage "+folder+"EoverPcalibration_batch_"+ntupleName+".dat ./") +outScript.write("\necho \"fine copia\" "); + +outScript.write("\nls") +outScript.write("\necho \"eseguo: "+command+"\" ") +outScript.write("\n"+command); +outScript.write("\nls") +outScript.write("\ncp -v -r EE__/ "+currentDir+"/EE_"+ntupleName+"/") +outScript.close(); +os.system("chmod 777 "+currentDir+"/"+fn+".sh"); +command2 = "bsub -q cmscaf1nd -cwd "+currentDir+" "+currentDir+"/"+fn+".sh"; +if not options.generateOnly: + os.system(command2); +print command2 +''' + + + + + diff --git a/ZNtupleDumper/interface/SimpleCutBasedElectronIDSelectionFunctor.h b/ZNtupleDumper/interface/SimpleCutBasedElectronIDSelectionFunctor.h index 9c3d02a5718..057a99ead06 100644 --- a/ZNtupleDumper/interface/SimpleCutBasedElectronIDSelectionFunctor.h +++ b/ZNtupleDumper/interface/SimpleCutBasedElectronIDSelectionFunctor.h @@ -126,7 +126,7 @@ class SimpleCutBasedElectronIDSelectionFunctor : public Selector // // class declaration // @@ -110,7 +116,7 @@ class EleNewEnergiesProducer : public edm::EDProducer { edm::InputTag BeamSpotTAG; /// input tag for electrons - edm::InputTag electronsTAG; + // edm::InputTag electronsTAG; /// input rho edm::InputTag rhoTAG; @@ -122,7 +128,11 @@ class EleNewEnergiesProducer : public edm::EDProducer { private: // Handle to the electron collection - edm::Handle > electronsHandle; + + edm::EDGetTokenT< edm::View > electronsTAG; + edm::EDGetTokenT< edm::View > photonsTAG; + edm::Handle > electronsHandle; + edm::Handle > photonsHandle; edm::Handle > > recHitCollectionEBHandle; edm::Handle > > recHitCollectionEEHandle; edm::Handle bsHandle; @@ -133,8 +143,7 @@ class EleNewEnergiesProducer : public edm::EDProducer { edm::Handle conversionsHandle; //------------------------------ Josh's regression (Hgg) - - SCEnergyCorrectorSemiParm mustache_regr_; + SCEnergyCorrectorSemiParm mustache_regr_; }; // @@ -150,12 +159,16 @@ class EleNewEnergiesProducer : public edm::EDProducer { // constructors and destructor // EleNewEnergiesProducer::EleNewEnergiesProducer(const edm::ParameterSet& iConfig): - electronsTAG(iConfig.getParameter("electronCollection")) + electronsTAG ( consumes >(iConfig.getParameter( "electronCollection" ) ) ), + photonsTAG ( consumes >(iConfig.getParameter( "photonCollection" ) ) ) + // electronsTAG(iConfig.getParameter("electronCollection")) { - std::cout << electronsTAG << std::endl; + // std::cout << electronsTAG << std::endl; // this name are hard coded, should be put in the cfi produces< NewEnergyMap >("energySCEleMust"); produces< NewEnergyMap >("energySCEleMustVar"); + produces< NewEnergyMap >("energySCElePho"); + produces< NewEnergyMap >("energySCElePhoVar"); //now do what ever other initialization is needed edm::ConsumesCollector iC = consumesCollector(); @@ -182,52 +195,85 @@ void EleNewEnergiesProducer::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) { using namespace edm; - mustache_regr_.setEvent(iEvent); - std::vector energySC_must; - std::vector energySC_mustVar; std::auto_ptr energySC_mustMap(new NewEnergyMap()); std::auto_ptr energySC_mustVarMap(new NewEnergyMap()); + std::auto_ptr energySC_phoMap(new NewEnergyMap()); + std::auto_ptr energySC_phoVarMap(new NewEnergyMap()); - //------------------------------ ELECTRON - iEvent.getByLabel(electronsTAG, electronsHandle); + iEvent.getByToken(electronsTAG, electronsHandle); + iEvent.getByToken(photonsTAG, photonsHandle); + mustache_regr_.setEvent(iEvent); + + std::vector energySC_must(electronsHandle->size(),-999.); + std::vector energySC_mustVar(electronsHandle->size(),-999); + std::vector energySC_pho(electronsHandle->size(),-999.); + std::vector energySC_phoVar(electronsHandle->size(),-999); //iSetup.get().get(topologyHandle); - - - for(reco::GsfElectronCollection::const_iterator ele_itr = (electronsHandle)->begin(); - ele_itr != (electronsHandle)->end(); ele_itr++){ - - std::pair corEle = std::make_pair(-1,-1); - if(ele_itr->ecalDriven()){ - //assert(ele_itr->parentSuperCluster().isNonnull() && ele_itr->parentSuperCluster()->seed().isNonnull()); //failing for 1/14000 events in MC! - if(ele_itr->parentSuperCluster().isNonnull()) - corEle = mustache_regr_.GetCorrections(*(ele_itr->parentSuperCluster())); - else edm::LogWarning("energyProducer") << "EcalDriven electron withouth parentSC"; - } - - //fill the vector with the energies - energySC_must.push_back(corEle.first); - energySC_mustVar.push_back(corEle.second); - } + for(unsigned int iEle=0; iEle< electronsHandle->size(); ++iEle) + { + edm::Ptr ele_itr=electronsHandle->ptrAt(iEle); + + if(!ele_itr->ecalDriven()) + continue; + + reco::SuperCluster correctedSuperCluster; + + if (ele_itr->parentSuperCluster().isAvailable()) + correctedSuperCluster=*(ele_itr->parentSuperCluster()); + else + correctedSuperCluster=*(ele_itr->superCluster()); //just to make it run also on MINIAOD... + + if (ele_itr->pt()<5) //clusters not available in MINIAOD + continue; + + if (!correctedSuperCluster.clusters().isAvailable()) + continue; + + mustache_regr_.modifyObject(correctedSuperCluster); + //fill the vector with the energies + energySC_must[iEle]=correctedSuperCluster.correctedEnergy(); + energySC_mustVar[iEle]=correctedSuperCluster.correctedEnergyUncertainty(); + + //now associate electron to photon via SC + for (auto pho_itr=photonsHandle->begin();pho_itr != photonsHandle->end(); ++pho_itr) + { + float dR=deltaR(ele_itr->superCluster()->eta(),ele_itr->superCluster()->phi(),pho_itr->superCluster()->eta(),pho_itr->superCluster()->phi()); + if (dR<1E-2) + { + energySC_pho[iEle] = pho_itr->energy(); + energySC_phoVar[iEle] = pho_itr->getCorrectedEnergyError(pho_itr->getCandidateP4type()); + break; + } + } + } //prepare product // declare the filler of the ValueMap NewEnergyMap::Filler energySC_must_filler( *energySC_mustMap); NewEnergyMap::Filler energySC_mustVar_filler(*energySC_mustVarMap); + NewEnergyMap::Filler energySC_pho_filler( *energySC_phoMap); + NewEnergyMap::Filler energySC_phoVar_filler(*energySC_phoVarMap); //fill and insert valuemapv - energySC_must_filler.insert(electronsHandle,energySC_must.begin(),energySC_must.end()); - energySC_mustVar_filler.insert(electronsHandle,energySC_mustVar.begin(),energySC_mustVar.end());//fra + energySC_must_filler.insert( electronsHandle, energySC_must.begin(),energySC_must.end()); + energySC_mustVar_filler.insert( electronsHandle, energySC_mustVar.begin(),energySC_mustVar.end());//fra + energySC_pho_filler.insert( electronsHandle, energySC_pho.begin(), energySC_pho.end()); + energySC_phoVar_filler.insert( electronsHandle, energySC_phoVar.begin(),energySC_phoVar.end());//fra energySC_must_filler.fill(); - energySC_mustVar_filler.fill();//fra + energySC_mustVar_filler.fill(); + energySC_pho_filler.fill(); + energySC_phoVar_filler.fill(); //------------------------------ // put the ValueMap in the event iEvent.put(energySC_mustMap, "energySCEleMust"); iEvent.put(energySC_mustVarMap, "energySCEleMustVar"); + iEvent.put(energySC_phoMap, "energySCElePho"); + iEvent.put(energySC_phoVarMap, "energySCElePhoVar"); } diff --git a/ZNtupleDumper/plugins/EleSelectionProducers.cc b/ZNtupleDumper/plugins/EleSelectionProducers.cc index fdfdd40e8d1..bd0dbeb32e4 100644 --- a/ZNtupleDumper/plugins/EleSelectionProducers.cc +++ b/ZNtupleDumper/plugins/EleSelectionProducers.cc @@ -72,16 +72,17 @@ class EleSelectionProducers : public edm::EDProducer { /// input tag for electrons - edm::InputTag electronsTAG; + edm::EDGetTokenT > electronsToken_; // conversions - edm::InputTag conversionsProducerTAG; - edm::InputTag BeamSpotTAG; - edm::InputTag VertexTAG; + edm::EDGetTokenT conversionsProducerToken_; + edm::EDGetTokenT BeamSpotToken_; + edm::EDGetTokenT VertexToken_; // isolation - edm::InputTag chIsoValsTAG, emIsoValsTAG, nhIsoValsTAG; + edm::EDGetTokenT > chIsoValsToken_; + edm::EDGetTokenT > emIsoValsToken_; + edm::EDGetTokenT > nhIsoValsToken_; /// input rho - edm::InputTag rhoTAG; - + edm::EDGetTokenT rhoToken_; SimpleCutBasedElectronIDSelectionFunctor fiducial_selector; SimpleCutBasedElectronIDSelectionFunctor WP70_PU_selector; @@ -96,19 +97,20 @@ class EleSelectionProducers : public edm::EDProducer { SimpleCutBasedElectronIDSelectionFunctor loose50nsRun2_selector; SimpleCutBasedElectronIDSelectionFunctor medium50nsRun2_selector; SimpleCutBasedElectronIDSelectionFunctor tight50nsRun2_selector; + SimpleCutBasedElectronIDSelectionFunctor tightElectronStream_selector; }; EleSelectionProducers::EleSelectionProducers(const edm::ParameterSet& iConfig): - electronsTAG(iConfig.getParameter("electronCollection")), - conversionsProducerTAG(iConfig.getParameter("conversionCollection")), - BeamSpotTAG(iConfig.getParameter("BeamSpotCollection")), - VertexTAG(iConfig.getParameter("vertexCollection")), - chIsoValsTAG(iConfig.getParameter("chIsoVals")), - emIsoValsTAG(iConfig.getParameter("emIsoVals")), - nhIsoValsTAG(iConfig.getParameter("nhIsoVals")), - rhoTAG(iConfig.getParameter("rhoFastJet")), + electronsToken_(consumes >(iConfig.getParameter("electronCollection"))), + conversionsProducerToken_(consumes(iConfig.getParameter("conversionCollection"))), + BeamSpotToken_(consumes(iConfig.getParameter("BeamSpotCollection"))), + VertexToken_(consumes(iConfig.getParameter("vertexCollection"))), + chIsoValsToken_(consumes >(iConfig.getParameter("chIsoVals"))), + emIsoValsToken_(consumes >(iConfig.getParameter("emIsoVals"))), + nhIsoValsToken_(consumes >(iConfig.getParameter("nhIsoVals"))), + rhoToken_(consumes(iConfig.getParameter("rhoFastJet"))), fiducial_selector("fiducial", electronsHandle, conversionsHandle, bsHandle, vertexHandle, chIsoValsHandle, emIsoValsHandle, nhIsoValsHandle, rhoHandle), @@ -135,6 +137,8 @@ EleSelectionProducers::EleSelectionProducers(const edm::ParameterSet& iConfig): medium50nsRun2_selector("medium50nsRun2", electronsHandle, conversionsHandle, bsHandle, vertexHandle, chIsoValsHandle, emIsoValsHandle, nhIsoValsHandle, rhoHandle), tight50nsRun2_selector("tight50nsRun2", electronsHandle, conversionsHandle, bsHandle, vertexHandle, + chIsoValsHandle, emIsoValsHandle, nhIsoValsHandle, rhoHandle), + tightElectronStream_selector("tightElectronStream", electronsHandle, conversionsHandle, bsHandle, vertexHandle, chIsoValsHandle, emIsoValsHandle, nhIsoValsHandle, rhoHandle) { //register your products @@ -160,6 +164,7 @@ EleSelectionProducers::EleSelectionProducers(const edm::ParameterSet& iConfig): produces< SelectionMap >("loose50nsRun2"); produces< SelectionMap >("medium50nsRun2"); produces< SelectionMap >("tight50nsRun2"); + produces< SelectionMap >("tightElectronStream"); //now do what ever other initialization is needed @@ -210,36 +215,38 @@ void EleSelectionProducers::produce(edm::Event& iEvent, const edm::EventSetup& i std::auto_ptr looseMap50nsRun2(new SelectionMap()); std::auto_ptr mediumMap50nsRun2(new SelectionMap()); std::auto_ptr tightMap50nsRun2(new SelectionMap()); + std::vector tightElectronStream_vec; + std::auto_ptr tightElectronStreamMap(new SelectionMap()); //------------------------------ ELECTRON - iEvent.getByLabel(electronsTAG, electronsHandle); + iEvent.getByToken(electronsToken_, electronsHandle); //if(!electronsHandle.isValid()){ // std::cerr << "[ERROR] electron collection not found" << std::endl; // return; //} //------------------------------ CONVERSIONS - iEvent.getByLabel(conversionsProducerTAG, conversionsHandle); + iEvent.getByToken(conversionsProducerToken_, conversionsHandle); // std::cout << conversionsHandle.isValid() << std::endl; - iEvent.getByLabel(BeamSpotTAG, bsHandle); - iEvent.getByLabel(VertexTAG, vertexHandle); + iEvent.getByToken(BeamSpotToken_, bsHandle); + iEvent.getByToken(VertexToken_, vertexHandle); //------------------------------ RHO - iEvent.getByLabel(rhoTAG,rhoHandle); + iEvent.getByToken(rhoToken_,rhoHandle); //------------------------------ ISO DEPOSITS #ifdef CMSSW_7_2_X #else - iEvent.getByLabel(chIsoValsTAG, chIsoValsHandle); + iEvent.getByToken(chIsoValsToken_, chIsoValsHandle); if(!chIsoValsHandle.isValid()){ - chIsoValsTAG=edm::InputTag(chIsoValsTAG.label().substr(0,chIsoValsTAG.label().find("PFIso",chIsoValsTAG.label().size()-6))+"Gsf", chIsoValsTAG.instance(), chIsoValsTAG.process()); - emIsoValsTAG=edm::InputTag(emIsoValsTAG.label().substr(0,emIsoValsTAG.label().find("PFIso",emIsoValsTAG.label().size()-6))+"Gsf", emIsoValsTAG.instance(), emIsoValsTAG.process()); - nhIsoValsTAG=edm::InputTag(nhIsoValsTAG.label().substr(0,nhIsoValsTAG.label().find("PFIso",nhIsoValsTAG.label().size()-6))+"Gsf", nhIsoValsTAG.instance(), nhIsoValsTAG.process()); + chIsoValsToken_=edm::InputTag(chIsoValsToken_.label().substr(0,chIsoValsToken_.label().find("PFIso",chIsoValsToken_.label().size()-6))+"Gsf", chIsoValsToken_.instance(), chIsoValsToken_.process()); + emIsoValsToken_=edm::InputTag(emIsoValsToken_.label().substr(0,emIsoValsToken_.label().find("PFIso",emIsoValsToken_.label().size()-6))+"Gsf", emIsoValsToken_.instance(), emIsoValsToken_.process()); + nhIsoValsToken_=edm::InputTag(nhIsoValsToken_.label().substr(0,nhIsoValsToken_.label().find("PFIso",nhIsoValsToken_.label().size()-6))+"Gsf", nhIsoValsToken_.instance(), nhIsoValsToken_.process()); - iEvent.getByLabel(chIsoValsTAG, chIsoValsHandle); + iEvent.getByToken(chIsoValsToken_, chIsoValsHandle); } - iEvent.getByLabel(emIsoValsTAG, emIsoValsHandle); - iEvent.getByLabel(nhIsoValsTAG, nhIsoValsHandle); + iEvent.getByToken(emIsoValsToken_, emIsoValsHandle); + iEvent.getByToken(nhIsoValsToken_, nhIsoValsHandle); #endif #ifdef DEBUG @@ -263,6 +270,7 @@ void EleSelectionProducers::produce(edm::Event& iEvent, const edm::EventSetup& i pat::strbitset loose50nsRun2_ret; pat::strbitset medium50nsRun2_ret; pat::strbitset tight50nsRun2_ret; + pat::strbitset tightElectronStream_ret; fiducial_selector(eleRef, fiducial_ret); @@ -301,6 +309,9 @@ void EleSelectionProducers::produce(edm::Event& iEvent, const edm::EventSetup& i tight50nsRun2_selector(eleRef, tight50nsRun2_ret); tight50nsRun2_vec.push_back(tight50nsRun2_selector.result()); + tightElectronStream_selector(eleRef, tightElectronStream_ret); + tightElectronStream_vec.push_back(tightElectronStream_selector.result()); + if(((bool)tight_selector.result())){ if(!(bool) medium_selector.result() || !(bool) loose_selector.result()){ edm::LogError("Incoherent selection") << "passing tight but not medium or loose"; @@ -328,7 +339,7 @@ void EleSelectionProducers::produce(edm::Event& iEvent, const edm::EventSetup& i exit (1); } } - + /* if(((bool)tight50nsRun2_selector.result())){ if(!(bool) medium50nsRun2_selector.result() || !(bool) loose50nsRun2_selector.result()){ edm::LogError("Incoherent selection") << "passing tight but not medium or loose for run2: 50ns"; @@ -342,7 +353,7 @@ void EleSelectionProducers::produce(edm::Event& iEvent, const edm::EventSetup& i exit (1); } } - + */ // WP80_PU_vec.push_back((SelectionValue_t)WP80_PU_selector.bitMask()); // WP90_PU_vec.push_back((SelectionValue_t)WP90_PU_selector.bitMask()); #ifdef DEBUG @@ -369,6 +380,7 @@ void EleSelectionProducers::produce(edm::Event& iEvent, const edm::EventSetup& i SelectionMap::Filler loose50nsRun2_filler(*looseMap50nsRun2); SelectionMap::Filler medium50nsRun2_filler(*mediumMap50nsRun2); SelectionMap::Filler tight50nsRun2_filler(*tightMap50nsRun2); + SelectionMap::Filler tightElectronStream_filler(*tightElectronStreamMap); //fill and insert valuemap fiducial_filler.insert(electronsHandle,fiducial_vec.begin(),fiducial_vec.end()); @@ -384,6 +396,7 @@ void EleSelectionProducers::produce(edm::Event& iEvent, const edm::EventSetup& i loose50nsRun2_filler.insert(electronsHandle,loose50nsRun2_vec.begin(),loose50nsRun2_vec.end()); medium50nsRun2_filler.insert(electronsHandle,medium50nsRun2_vec.begin(),medium50nsRun2_vec.end()); tight50nsRun2_filler.insert(electronsHandle,tight50nsRun2_vec.begin(),tight50nsRun2_vec.end()); + tightElectronStream_filler.insert(electronsHandle,tightElectronStream_vec.begin(),tightElectronStream_vec.end()); fiducial_filler.fill(); @@ -399,6 +412,7 @@ void EleSelectionProducers::produce(edm::Event& iEvent, const edm::EventSetup& i loose50nsRun2_filler.fill(); medium50nsRun2_filler.fill(); tight50nsRun2_filler.fill(); + tightElectronStream_filler.fill(); //------------------------------ @@ -416,6 +430,7 @@ void EleSelectionProducers::produce(edm::Event& iEvent, const edm::EventSetup& i iEvent.put(looseMap50nsRun2, "loose50nsRun2"); iEvent.put(mediumMap50nsRun2, "medium50nsRun2"); iEvent.put(tightMap50nsRun2, "tight50nsRun2"); + iEvent.put(tightElectronStreamMap, "tightElectronStream"); } diff --git a/ZNtupleDumper/plugins/ZNtupleDumper.cc b/ZNtupleDumper/plugins/ZNtupleDumper.cc index 7f810d83073..2f27e836bfd 100644 --- a/ZNtupleDumper/plugins/ZNtupleDumper.cc +++ b/ZNtupleDumper/plugins/ZNtupleDumper.cc @@ -120,7 +120,9 @@ #include "DataFormats/METReco/interface/PFMET.h" #include "DataFormats/METReco/interface/PFMETFwd.h" - +#include "DataFormats/METReco/interface/CaloMET.h" +#include "DataFormats/METReco/interface/CaloMETFwd.h" +#include "DataFormats/METReco/interface/CaloMETCollection.h" // HLT trigger #include "FWCore/Framework/interface/TriggerNamesService.h" #include @@ -148,7 +150,6 @@ class ZNtupleDumper : public edm::EDAnalyzer static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); - private: virtual void beginJob() ; virtual void analyze(const edm::Event&, const edm::EventSetup&); @@ -183,42 +184,44 @@ class ZNtupleDumper : public edm::EDAnalyzer edm::Handle< GenEventInfoProduct > GenEventInfoHandle; edm::Handle conversionsHandle; edm::Handle< reco::PFMETCollection > metHandle; + edm::Handle< reco::CaloMETCollection > caloMetHandle; edm::Handle triggerResultsHandle; edm::Handle WZSkimResultsHandle; edm::Handle ESRechitsHandle; //------------------------------ Input Tags // input tag for primary vertex - edm::InputTag vtxCollectionTAG; - edm::InputTag BeamSpotTAG; - // input tag for electrons - edm::InputTag electronsTAG; - edm::InputTag muonsTAG; - edm::InputTag photonsTAG; - -#ifdef CMSSW_7_2_X - edm::EDGetTokenT recHitCollectionEBTAG; - edm::EDGetTokenT recHitCollectionEETAG; -#else - edm::InputTag recHitCollectionEBTAG; - edm::InputTag recHitCollectionEETAG; -#endif - - edm::InputTag recHitCollectionESTAG; - edm::InputTag EESuperClustersTAG; + edm::EDGetTokenT generatorInfoToken_; + edm::EDGetTokenT vtxCollectionToken_; + //edm::InputTag vtxCollectionTAG; + edm::EDGetTokenT beamSpotToken_; + //edm::InputTag BeamSpotTAG; + edm::EDGetTokenT electronsToken_; + edm::EDGetTokenT muonsToken_; + edm::EDGetTokenT photonsToken_; + + edm::EDGetTokenT recHitCollectionEBToken_; + edm::EDGetTokenT recHitCollectionEEToken_; + edm::EDGetTokenT recHitCollectionESToken_; + + edm::EDGetTokenT > EESuperClustersToken_; // input rho - edm::InputTag rhoTAG, pileupInfoTAG; - edm::InputTag conversionsProducerTAG; - edm::InputTag metTAG; - edm::InputTag triggerResultsTAG; - edm::InputTag WZSkimResultsTAG; + edm::EDGetTokenT rhoToken_; + edm::EDGetTokenT > pileupInfoToken_; + edm::EDGetTokenT conversionsProducerToken_; + edm::EDGetTokenT metToken_; + edm::EDGetTokenT caloMetToken_; + edm::EDGetTokenT triggerResultsToken_; + edm::EDGetTokenT WZSkimResultsToken_; + edm::InputTag triggerResultsTAG, WZSkimResultsTAG; std::vector< std::string> hltPaths, SelectEvents; + private: std::string foutName; bool doExtraCalibTree; bool doEleIDTree; - + bool electronStream; edm::Service fs; //< output file for extra ntuples TTree *tree; //< output file for standard ntuple @@ -275,6 +278,9 @@ class ZNtupleDumper : public edm::EDAnalyzer Float_t energySCEle_must_regrCorr_ele[3]; ///< mustache SC energy derived with regression (offline tool) Float_t energySigmaSCEle_must_regrCorr_ele[3]; ///< mustache SC energy resolution derived with regression (offline tool) + Float_t energySCEle_pho_regrCorr[3]; ///< mustache SC energy derived with regression (offline tool) + Float_t energySigmaSCEle_pho_regrCorr[3]; ///< mustache SC energy resolution derived with regression (offline tool) + Float_t esEnergySCEle[3]; ///< pre-shower energy associated to the electron Float_t esEnergyPlane1SCEle[3]; ///< energy associate to the electron in the first plane of ES Float_t esEnergyPlane2SCEle[3]; ///< energy associate to the electron in the second plane of ES @@ -296,6 +302,8 @@ class ZNtupleDumper : public edm::EDAnalyzer Float_t invMass_SC; ///< invariant mass using SC energy with PF. NB: in the rereco case, this is mustache too! Float_t invMass_SC_must; ///< invariant mass using SC energy with mustache Float_t invMass_SC_must_regrCorr_ele; ///< invariant mass using SC energy with mustache corrected with regression + Float_t invMass_SC_pho_regrCorr; ///< invariant mass using SC energy from associated photon + // Float_t invMass_e3x3; Float_t invMass_e5x5; Float_t invMass_rawSC; @@ -333,7 +341,7 @@ class ZNtupleDumper : public edm::EDAnalyzer std::vector energyRecHitSCEle[3]; std::vector LCRecHitSCEle[3]; std::vector ICRecHitSCEle[3]; - std::vector AlphaRecHitSCEle[3]; + float seedLaserAlphaSCEle[3]; //============================== //============================== check ele-id and iso @@ -421,6 +429,7 @@ class ZNtupleDumper : public edm::EDAnalyzer EcalClusterLazyTools *clustertools; // EcalClusterLocal _ecalLocal; + const EcalLaserAlphaMap* theEcalLaserAlphaMap; std::set alcaSkimPathIndexes; edm::ParameterSetID alcaSkimPathID; @@ -436,6 +445,8 @@ class ZNtupleDumper : public edm::EDAnalyzer ZSC, ZMMG, PARTGUN, + WSTREAM, + ZSTREAM, UNKNOWN, SINGLEELE, //no skim, no preselection and no selection are applied DEBUG_T @@ -455,25 +466,22 @@ ZNtupleDumper::ZNtupleDumper(const edm::ParameterSet& iConfig): // isMC(iConfig.getParameter("isMC")), isPartGun(iConfig.getParameter("isPartGun")), doHighEta_LowerEtaCut(iConfig.getParameter("doHighEta_LowerEtaCut")), - vtxCollectionTAG(iConfig.getParameter("vertexCollection")), - BeamSpotTAG(iConfig.getParameter("BeamSpotCollection")), - electronsTAG(iConfig.getParameter("electronCollection")), - muonsTAG(iConfig.getParameter("muonCollection")), - photonsTAG(iConfig.getParameter("photonCollection")), -#ifdef CMSSW_7_2_X - recHitCollectionEBTAG(consumes(iConfig.getParameter( "recHitCollectionEB" ))), - recHitCollectionEETAG(consumes(iConfig.getParameter( "recHitCollectionEE" ))), -#else - recHitCollectionEBTAG(iConfig.getParameter("recHitCollectionEB")), - recHitCollectionEETAG(iConfig.getParameter("recHitCollectionEE")), -#endif - - recHitCollectionESTAG(iConfig.getParameter("recHitCollectionES")), - EESuperClustersTAG(iConfig.getParameter("EESuperClusterCollection")), - rhoTAG(iConfig.getParameter("rhoFastJet")), - pileupInfoTAG(iConfig.getParameter("pileupInfo")), - conversionsProducerTAG(iConfig.getParameter("conversionCollection")), - metTAG(iConfig.getParameter("metCollection")), + vtxCollectionToken_(consumes(iConfig.getParameter("vertexCollection"))), + beamSpotToken_(consumes(iConfig.getParameter("BeamSpotCollection"))), + electronsToken_(consumes(iConfig.getParameter("electronCollection"))), + muonsToken_(consumes(iConfig.getParameter("muonCollection"))), + photonsToken_(consumes(iConfig.getParameter("photonCollection"))), + recHitCollectionEBToken_(consumes(iConfig.getParameter( "recHitCollectionEB" ))), + recHitCollectionEEToken_(consumes(iConfig.getParameter( "recHitCollectionEE" ))), + recHitCollectionESToken_(consumes(iConfig.getParameter("recHitCollectionES"))), + EESuperClustersToken_(consumes(iConfig.getParameter< edm::InputTag>("EESuperClusterCollection"))), + rhoToken_(consumes(iConfig.getParameter("rhoFastJet"))), + pileupInfoToken_(consumes>(iConfig.getParameter("pileupInfo"))), + conversionsProducerToken_(consumes(iConfig.getParameter("conversionCollection"))), + metToken_(consumes(iConfig.getParameter("metCollection"))), + caloMetToken_(consumes(iConfig.getParameter("caloMetCollection"))), //for the stream + triggerResultsToken_(consumes(iConfig.getParameter("triggerResultsCollection"))), + WZSkimResultsToken_(consumes(iConfig.getParameter("WZSkimResultsCollection"))), triggerResultsTAG(iConfig.getParameter("triggerResultsCollection")), WZSkimResultsTAG(iConfig.getParameter("WZSkimResultsCollection")), hltPaths(iConfig.getParameter< std::vector >("hltPaths")), @@ -481,6 +489,7 @@ ZNtupleDumper::ZNtupleDumper(const edm::ParameterSet& iConfig): foutName(iConfig.getParameter("foutName")), doExtraCalibTree(iConfig.getParameter("doExtraCalibTree")), doEleIDTree(iConfig.getParameter("doEleIDTree")), + electronStream(iConfig.getParameter("electronStream")), doPdfSystTree(false), pdfWeightTAGS(iConfig.getParameter< std::vector >("pdfWeightCollections")), fsrWeightTAG(iConfig.getParameter< edm::InputTag>("fsrWeightCollection")), @@ -550,16 +559,16 @@ void ZNtupleDumper::analyze(const edm::Event& iEvent, const edm::EventSetup& iSe // filling infos runNumber, eventNumber, lumi if( !iEvent.isRealData() ) { - iEvent.getByLabel(pileupInfoTAG, PupInfo); - iEvent.getByLabel(edm::InputTag("generator"), GenEventInfoHandle); + iEvent.getByToken(pileupInfoToken_, PupInfo); + iEvent.getByToken(generatorInfoToken_, GenEventInfoHandle); isMC = true; } else isMC = false; //------------------------------ HLT /// \todo check why - if(triggerResultsTAG.label() != "") iEvent.getByLabel(triggerResultsTAG, triggerResultsHandle); + if(triggerResultsTAG.label() != "") iEvent.getByToken(triggerResultsToken_, triggerResultsHandle); if(WZSkimResultsTAG.label() != "") { - iEvent.getByLabel(WZSkimResultsTAG, WZSkimResultsHandle); //else it is not produced with ALCARECO selection + iEvent.getByToken(WZSkimResultsToken_, WZSkimResultsHandle); //else it is not produced with ALCARECO selection //then the type of event has to be defined //Check if it is Wenu, Z or ZSC event according to triggerResults @@ -627,38 +636,49 @@ void ZNtupleDumper::analyze(const edm::Event& iEvent, const edm::EventSetup& iSe if(skipEvent) return; // event not coming from any skim or paths } } + if (electronStream) + eventType=WSTREAM; //------------------------------ CONVERSIONS - iEvent.getByLabel(conversionsProducerTAG, conversionsHandle); + iEvent.getByToken(conversionsProducerToken_, conversionsHandle); //------------------------------ - clustertools = new EcalClusterLazyTools (iEvent, iSetup, recHitCollectionEBTAG, - recHitCollectionEETAG); + clustertools = new EcalClusterLazyTools (iEvent, iSetup, recHitCollectionEBToken_, + recHitCollectionEEToken_); + + edm::ESHandle theEcalLaserAlphas; + iSetup.get().get(theEcalLaserAlphas); + theEcalLaserAlphaMap = theEcalLaserAlphas.product(); //------------------------------ electrons if (eventType == ZMMG) { //------------------------------ muons - iEvent.getByLabel(muonsTAG, muonsHandle); + iEvent.getByToken(muonsToken_, muonsHandle); //------------------------------ photons - iEvent.getByLabel(photonsTAG, photonsHandle); + iEvent.getByToken(photonsToken_, photonsHandle); } else { - iEvent.getByLabel(electronsTAG, electronsHandle); + iEvent.getByToken(electronsToken_, electronsHandle); } //------------------------------ SuperClusters (for high Eta studies) - iEvent.getByLabel(EESuperClustersTAG, EESuperClustersHandle); + iEvent.getByToken(EESuperClustersToken_, EESuperClustersHandle); // for conversions with full vertex fit //------------------------------ VERTEX - iEvent.getByLabel(vtxCollectionTAG, primaryVertexHandle); - iEvent.getByLabel(BeamSpotTAG, bsHandle); - iEvent.getByLabel(rhoTAG, rhoHandle); + iEvent.getByToken(vtxCollectionToken_, primaryVertexHandle); + iEvent.getByToken(beamSpotToken_, bsHandle); + iEvent.getByToken(rhoToken_, rhoHandle); - iEvent.getByLabel(metTAG, metHandle); - iEvent.getByLabel(recHitCollectionESTAG, ESRechitsHandle); + iEvent.getByToken(metToken_, metHandle); + iEvent.getByToken(recHitCollectionESToken_, ESRechitsHandle); //if(metHandle.isValid()==false) iEvent.getByType(metHandle); reco::PFMET met = metHandle.isValid() ? ((*metHandle))[0] : reco::PFMET(); /// \todo use corrected phi distribution + reco::CaloMET caloMet; + if (caloMetHandle.isValid()==true) { + iEvent.getByToken(caloMetToken_, caloMetHandle); + caloMet = ((*caloMetHandle))[0]; //get hlt met + } //Here the HLTBits are filled. TriggerResults TreeSetEventSummaryVar(iEvent); @@ -703,6 +723,7 @@ void ZNtupleDumper::analyze(const edm::Event& iEvent, const edm::EventSetup& iSe int nTight = 0; //number of electrons passing only the tight ID for preselection int nMedium = 0; //number of electrons passing only the medium ID for preselection int nLoose = 0; //number of electrons passing only the loose ID for preselection + int nEle = 0; //number of electrons saved in the electron stream //if (eventType!=ZMMG) { // count the number of electrons passing the different IDs for preselection and event type determination if (eventType != UNKNOWN) { // count the number of electrons passing the different IDs for preselection and event type determination @@ -712,6 +733,7 @@ void ZNtupleDumper::analyze(const edm::Event& iEvent, const edm::EventSetup& iSe if( eleIter1->electronID(eleID_tight) ) ++nTight; else if( eleIter1->electronID(eleID_medium) ) ++nMedium; else if( eleIter1->electronID(eleID_loose) ) ++nLoose; + nEle++; } } @@ -749,7 +771,7 @@ void ZNtupleDumper::analyze(const edm::Event& iEvent, const edm::EventSetup& iSe if(doEleIDTree) { TreeSetEleIDVar(*eleIter1, *eleIter2); } - } else if(eventType == ZEE || eventType == WENU || eventType == UNKNOWN) { + } else if(eventType==ZEE || eventType==WENU || eventType==UNKNOWN || eventType==WSTREAM || eventType==ZSTREAM){ #ifdef DEBUG std::cout << "[DEBUG] Electrons in the event: " << electronsHandle->size() << std::endl; #endif @@ -782,6 +804,31 @@ void ZNtupleDumper::analyze(const edm::Event& iEvent, const edm::EventSetup& iSe TreeSetEleIDVar(*eleIter1, 0); TreeSetEleIDVar(*eleIter1, -1); } + } else if(eventType==WSTREAM) { + if(! eleIter1->electronID("tightElectronStream") ) continue; + if (nEle!=1) continue; + //if( nWP70 != 1 || nWP90 > 0 ) continue; //to be a Wenu event request only 1 ele WP70 in the event + + iEvent.getByToken(caloMetToken_, caloMetHandle); + if (caloMetHandle.isValid()==false) continue; + + // MET/MT selection + if( caloMetHandle->at(0).pt() < 25. ) continue; + if( sqrt( 2.*eleIter1->et()*caloMetHandle->at(0).pt()*(1 -cos(eleIter1->phi()-caloMetHandle->at(0).phi()))) < 50. ) continue; + if( eleIter1->et()<30) continue; + doFill = true; + if(eventType == UNKNOWN) eventType = WENU; + TreeSetSingleElectronVar(*eleIter1, 0); //fill first electron + TreeSetSingleElectronVar(*eleIter1, -1); // fill fake second electron + + if(doExtraCalibTree) { + TreeSetExtraCalibVar(*eleIter1, 0); + TreeSetExtraCalibVar(*eleIter1, -1); + } + if(doEleIDTree) { + TreeSetEleIDVar(*eleIter1, 0); + TreeSetEleIDVar(*eleIter1, -1); + } } else { //ZEE or UNKNOWN // take only the fist di-electron pair (highest pt) for(pat::ElectronCollection::const_iterator eleIter2 = eleIter1 + 1; @@ -1179,7 +1226,10 @@ void ZNtupleDumper::InitNewTree() tree->Branch("rawEnergySCEle_must", rawEnergySCEle_must, "rawEnergySCEle_must[3]/F"); tree->Branch("energySCEle_must_regrCorr_ele", energySCEle_must_regrCorr_ele, "energySCEle_must_regrCorr_ele[3]/F"); - tree->Branch("energySCEle_must_regrCorr_ele", energySigmaSCEle_must_regrCorr_ele, "energySigmaSCEle_must_regrCorr_ele[3]/F"); + tree->Branch("energySigmaSCEle_must_regrCorr_ele", energySigmaSCEle_must_regrCorr_ele, "energySigmaSCEle_must_regrCorr_ele[3]/F"); + + tree->Branch("energySCEle_pho_regrCorr", energySCEle_pho_regrCorr, "energySCEle_pho_regrCorr[3]/F"); + tree->Branch("energySigmaSCEle_pho_regrCorr", energySigmaSCEle_pho_regrCorr, "energySigmaSCEle_pho_regrCorr[3]/F"); tree->Branch("esEnergySCEle", esEnergySCEle, "esEnergySCEle[3]/F"); tree->Branch("esEnergyPlane2SCEle", esEnergyPlane2SCEle, "esEnergyPlane2SCEle[3]/F"); @@ -1204,6 +1254,7 @@ void ZNtupleDumper::InitNewTree() tree->Branch("invMass_SC", &invMass_SC, "invMass_SC/F"); tree->Branch("invMass_SC_must", &invMass_SC_must, "invMass_SC_must/F"); tree->Branch("invMass_SC_must_regrCorr_ele", &invMass_SC_must_regrCorr_ele, "invMass_SC_must_regrCorr_ele/F"); + tree->Branch("invMass_SC_pho_regrCorr", &invMass_SC_pho_regrCorr, "invMass_SC_pho_regrCorr/F"); // tree->Branch("invMass_e3x3", &invMass_e3x3, "invMass_e3x3/F"); tree->Branch("invMass_e5x5", &invMass_e5x5, "invMass_e5x5/F"); tree->Branch("invMass_rawSC", &invMass_rawSC, "invMass_rawSC/F"); @@ -1396,8 +1447,13 @@ void ZNtupleDumper::TreeSetSingleElectronVar(const pat::Electron& electron1, int rawEnergySCEle_must[index] = -99; } - energySCEle_must_regrCorr_ele[index] = electron1.userFloat("eleNewEnergiesProducer:energySCEleMust"); - energySigmaSCEle_must_regrCorr_ele[index] = electron1.userFloat("eleNewEnergiesProducer:energySCEleMustVar"); + //I temporarly removed the following isntructions, since they don't work (and I don't know if they are needed) + + // energySCEle_must_regrCorr_ele[index] = electron1.userFloat("energySCEleMust"); + //energySigmaSCEle_must_regrCorr_ele[index] = electron1.userFloat("energySCEleMustVar"); + + //energySCEle_pho_regrCorr[index] = electron1.userFloat("energySCElePho"); + //energySigmaSCEle_pho_regrCorr[index] = electron1.userFloat("energySCElePhoVar"); rawESEnergyPlane1SCEle[index] = GetESPlaneRawEnergy(sc, 1); @@ -1846,6 +1902,8 @@ void ZNtupleDumper:: TreeSetDiElectronVar(const pat::Electron& electron1, const invMass_SC_must_regrCorr_ele = sqrt(2 * energySCEle_must_regrCorr_ele[0] * energySCEle_must_regrCorr_ele[1] * angle); + invMass_SC_pho_regrCorr = sqrt(2 * energySCEle_pho_regrCorr[0] * energySCEle_pho_regrCorr[1] * + angle); invMass_rawSC = sqrt(2 * rawEnergySCEle[0] * rawEnergySCEle[1] * angle); @@ -1901,6 +1959,7 @@ void ZNtupleDumper::TreeSetDiElectronVar(const pat::Electron& electron1, const r invMass_SC_must = sqrt(2 * energySCEle_must[0] * energySCEle_must[1] * angle); invMass_SC_must_regrCorr_ele = sqrt(2 * energySCEle_must_regrCorr_ele[0] * energySCEle_must_regrCorr_ele[1] * angle); + invMass_SC_pho_regrCorr = sqrt(2 * energySCEle_pho_regrCorr[0] * energySCEle_pho_regrCorr[1] * angle); invMass_rawSC = sqrt(2 * rawEnergySCEle[0] * rawEnergySCEle[1] * angle); @@ -1994,29 +2053,33 @@ void ZNtupleDumper:: TreeSetMuMuGammaVar(const pat::Photon& photon, const pat::M ///\todo highly inefficient: instead of the loop over the recHits should use a ->find() method, it should return both energies of both planes float ZNtupleDumper::GetESPlaneRawEnergy(const reco::SuperClusterRef& sc, unsigned int planeIndex) { - float RawenergyPlane = 0; float pfRawenergyPlane = 0; - if(ESRechitsHandle.isValid()) { - for(auto iES = sc->preshowerClustersBegin(); iES != sc->preshowerClustersEnd(); ++iES) { - const std::vector< std::pair > hits = (*iES)->hitsAndFractions(); - for(std::vector >::const_iterator rh = hits.begin(); rh != hits.end(); ++rh) { - // std::cout << "print = " << (*iES)->printHitAndFraction(iCount); - // ++iCount; - for(ESRecHitCollection::const_iterator esItr = ESRechitsHandle->begin(); esItr != ESRechitsHandle->end(); ++esItr) { - ESDetId rhid = ESDetId(esItr->id()); - if(rhid == (*rh).first) { - // std::cout << " ES energy = " << esItr->energy() << " pf energy = " << (*rh).second << std::endl; - if((int) rhid.plane() == (int) planeIndex) { - RawenergyPlane += esItr->energy(); - pfRawenergyPlane += rh->second; - } - break; - } - } - } + + if(!ESRechitsHandle.isValid()) + return RawenergyPlane; + if (!sc->preshowerClusters().isAvailable()) //protection for miniAOD + return RawenergyPlane; + + for(auto iES = sc->preshowerClustersBegin(); iES != sc->preshowerClustersEnd(); ++iES) { + const std::vector< std::pair > hits = (*iES)->hitsAndFractions(); + for(std::vector >::const_iterator rh = hits.begin(); rh != hits.end(); ++rh) { + // std::cout << "print = " << (*iES)->printHitAndFraction(iCount); + // ++iCount; + for(ESRecHitCollection::const_iterator esItr = ESRechitsHandle->begin(); esItr != ESRechitsHandle->end(); ++esItr) { + ESDetId rhid = ESDetId(esItr->id()); + if(rhid == (*rh).first) { + // std::cout << " ES energy = " << esItr->energy() << " pf energy = " << (*rh).second << std::endl; + if((int) rhid.plane() == (int) planeIndex) { + RawenergyPlane += esItr->energy(); + pfRawenergyPlane += rh->second; } + break; + } + } + } } + if (pfRawenergyPlane) ; // avoid compilation error for unused var if (RawenergyPlane); //std::cout << "LC DEBUG RawenergyPlane "<< RawenergyPlane << ", pfRawenergyPlane " << pfRawenergyPlane << std::endl; @@ -2057,8 +2120,8 @@ void ZNtupleDumper::InitExtraCalibTree() extraCalibTree->Branch("LCRecHitSCEle2", &(LCRecHitSCEle[1])); extraCalibTree->Branch("ICRecHitSCEle1", &(ICRecHitSCEle[0])); extraCalibTree->Branch("ICRecHitSCEle2", &(ICRecHitSCEle[1])); - extraCalibTree->Branch("AlphaRecHitSCEle1", &(AlphaRecHitSCEle[0])); - extraCalibTree->Branch("AlphaRecHitSCEle2", &(AlphaRecHitSCEle[1])); + extraCalibTree->Branch("seedLaserAlphaSCEle1", &(seedLaserAlphaSCEle[0])); + extraCalibTree->Branch("seedLaserAlphaSCEle2", &(seedLaserAlphaSCEle[1])); return; } @@ -2091,7 +2154,7 @@ void ZNtupleDumper::TreeSetExtraCalibVar(const pat::Electron& electron1, int ind energyRecHitSCEle[-index].clear(); LCRecHitSCEle[-index].clear(); ICRecHitSCEle[-index].clear(); - AlphaRecHitSCEle[-index].clear(); + seedLaserAlphaSCEle[-index] = -99.; return; } @@ -2103,7 +2166,7 @@ void ZNtupleDumper::TreeSetExtraCalibVar(const pat::Electron& electron1, int ind energyRecHitSCEle[index].clear(); LCRecHitSCEle[index].clear(); ICRecHitSCEle[index].clear(); - AlphaRecHitSCEle[index].clear(); + seedLaserAlphaSCEle[index] = -99.; // EcalIntercalibConstantMap icMap = icHandle->get() std::vector< std::pair > hitsAndFractions_ele1 = electron1.superCluster()->hitsAndFractions(); @@ -2157,6 +2220,15 @@ void ZNtupleDumper::TreeSetExtraCalibVar(const pat::Electron& electron1, int ind ICRecHitSCEle[index].push_back(icalconst); } + DetId seedDetId = electron1.seed()->seed(); + if(seedDetId.null()){ + seedDetId = findSCseed(*(electron1.superCluster())); + } + + EcalLaserAlphaMap::const_iterator italpha = theEcalLaserAlphaMap->find(seedDetId); + if( italpha != theEcalLaserAlphaMap->end() ) + seedLaserAlphaSCEle[index] = (*italpha); + return; } @@ -2172,7 +2244,7 @@ void ZNtupleDumper::TreeSetExtraCalibVar(const reco::SuperCluster& electron1, in energyRecHitSCEle[-index].clear(); LCRecHitSCEle[-index].clear(); ICRecHitSCEle[-index].clear(); - AlphaRecHitSCEle[-index].clear(); + seedLaserAlphaSCEle[-index] = -99.; return; } @@ -2184,7 +2256,7 @@ void ZNtupleDumper::TreeSetExtraCalibVar(const reco::SuperCluster& electron1, in energyRecHitSCEle[index].clear(); LCRecHitSCEle[index].clear(); ICRecHitSCEle[index].clear(); - AlphaRecHitSCEle[index].clear(); + seedLaserAlphaSCEle[index] = -99.; std::vector< std::pair > hitsAndFractions_ele1 = electron1.hitsAndFractions(); nHitsSCEle[index] = hitsAndFractions_ele1.size(); @@ -2259,6 +2331,15 @@ void ZNtupleDumper::TreeSetExtraCalibVar(const reco::SuperCluster& electron1, in } + DetId seedDetId = electron1.seed()->seed(); + if(seedDetId.null()){ + seedDetId = findSCseed(electron1); + } + + EcalLaserAlphaMap::const_iterator italpha = theEcalLaserAlphaMap->find(seedDetId); + if( italpha != theEcalLaserAlphaMap->end() ) + seedLaserAlphaSCEle[index] = (*italpha); + return; } @@ -2285,7 +2366,7 @@ void ZNtupleDumper::TreeSetExtraCalibVar(const pat::Photon& photon, int index) energyRecHitSCEle[-index].clear(); LCRecHitSCEle[-index].clear(); ICRecHitSCEle[-index].clear(); - AlphaRecHitSCEle[-index].clear(); + seedLaserAlphaSCEle[-index] = -99.; return; } @@ -2297,7 +2378,7 @@ void ZNtupleDumper::TreeSetExtraCalibVar(const pat::Photon& photon, int index) energyRecHitSCEle[index].clear(); LCRecHitSCEle[index].clear(); ICRecHitSCEle[index].clear(); - AlphaRecHitSCEle[index].clear(); + seedLaserAlphaSCEle[index] = -99.; // EcalIntercalibConstantMap icMap = icHandle->get() std::vector< std::pair > hitsAndFractions_ele1 = photon.superCluster()->hitsAndFractions(); @@ -2351,6 +2432,15 @@ void ZNtupleDumper::TreeSetExtraCalibVar(const pat::Photon& photon, int index) ICRecHitSCEle[index].push_back(icalconst); } + DetId seedDetId = photon.seed()->seed(); + if(seedDetId.null()){ + seedDetId = findSCseed(*(photon.superCluster())); + } + + EcalLaserAlphaMap::const_iterator italpha = theEcalLaserAlphaMap->find(seedDetId); + if( italpha != theEcalLaserAlphaMap->end() ) + seedLaserAlphaSCEle[index] = (*italpha); + return; } @@ -2366,7 +2456,7 @@ void ZNtupleDumper::TreeSetExtraCalibVar(const pat::Muon& muon1, int index) energyRecHitSCEle[-index].clear(); LCRecHitSCEle[-index].clear(); ICRecHitSCEle[-index].clear(); - AlphaRecHitSCEle[-index].clear(); + seedLaserAlphaSCEle[-index] = -99.; return; } @@ -2378,7 +2468,7 @@ void ZNtupleDumper::TreeSetExtraCalibVar(const pat::Muon& muon1, int index) energyRecHitSCEle[index].clear(); LCRecHitSCEle[index].clear(); ICRecHitSCEle[index].clear(); - AlphaRecHitSCEle[index].clear(); + seedLaserAlphaSCEle[index] = -99.; return; } @@ -2524,7 +2614,8 @@ void ZNtupleDumper::InitPdfSystTree(void) // pdfSystTree->Branch("lumiBlock", &lumiBlock, "lumiBlock/I"); // pdfSystTree->Branch("runTime", &runTime, "runTime/i"); - +#ifdef PDFWEIGHTS +// this part is deprecated for(std::vector< edm::InputTag >::const_iterator pdfWeightTAGS_itr = pdfWeightTAGS.begin(); pdfWeightTAGS_itr != pdfWeightTAGS.end(); pdfWeightTAGS_itr++) { @@ -2538,17 +2629,18 @@ void ZNtupleDumper::InitPdfSystTree(void) pdfSystTree->Branch("fsrWeight", &fsrWeight, "fsrWeight/F"); pdfSystTree->Branch("weakWeight", &weakWeight, "weakWeight/F"); +#endif return; } void ZNtupleDumper::TreeSetPdfSystVar(const edm::Event& iEvent) { - +#ifdef PDFWEIGHTS for(std::vector< edm::InputTag >::const_iterator pdfWeightTAGS_itr = pdfWeightTAGS.begin(); pdfWeightTAGS_itr != pdfWeightTAGS.end(); pdfWeightTAGS_itr++) { int i = pdfWeightTAGS_itr - pdfWeightTAGS.begin(); - iEvent.getByLabel(*pdfWeightTAGS_itr, pdfWeightHandle); + iEvent.getByToken(*pdfWeightTAGS_itr, pdfWeightHandle); //pdfSystWeight[i] = std::vector weights = std::vector(*pdfWeightHandle); @@ -2562,14 +2654,16 @@ void ZNtupleDumper::TreeSetPdfSystVar(const edm::Event& iEvent) // } } - iEvent.getByLabel(fsrWeightTAG, fsrWeightHandle); - iEvent.getByLabel(weakWeightTAG, weakWeightHandle); + iEvent.getByToken(fsrWeightTAG, fsrWeightHandle); + iEvent.getByToken(weakWeightTAG, weakWeightHandle); fsrWeight = (Float_t) * fsrWeightHandle; weakWeight = (Float_t) * weakWeightHandle; - +#endif return ; } //define this as a plug-in DEFINE_FWK_MODULE(ZNtupleDumper); + +// LocalWords: pileupInfoTAG conversionsProducerTAG triggerResultsTAG diff --git a/ZNtupleDumper/python/elenewenergiesproducer_cfi.py b/ZNtupleDumper/python/elenewenergiesproducer_cfi.py index 1bdfa7c4a8e..8cf753a616a 100644 --- a/ZNtupleDumper/python/elenewenergiesproducer_cfi.py +++ b/ZNtupleDumper/python/elenewenergiesproducer_cfi.py @@ -7,5 +7,6 @@ ecalRecHitsEE = cms.InputTag("alCaIsolatedElectrons", "alcaEndcapHits"), vertexCollection = cms.InputTag("offlinePrimaryVertices"), ), - electronCollection = cms.InputTag("gedGsfElectrons"), + electronCollection = cms.InputTag("patElectrons"), + photonCollection = cms.InputTag("photons"), ) diff --git a/ZNtupleDumper/python/patSequence_cff.py b/ZNtupleDumper/python/patSequence_cff.py index 9af21c6a888..baafd922a40 100644 --- a/ZNtupleDumper/python/patSequence_cff.py +++ b/ZNtupleDumper/python/patSequence_cff.py @@ -41,10 +41,10 @@ # electron.userFloat("eleNewEnergiesProducer:energySCEleJoshEle") # electron.userFloat("eleNewEnergiesProducer:energySCEleJoshEle:MVAntuplizer") -patElectrons.userData.userFloats.src = [ - cms.InputTag("eleNewEnergiesProducer", "energySCEleMust"), - cms.InputTag("eleNewEnergiesProducer", "energySCEleMustVar"), - ] +# patElectrons.userData.userFloats.src = [ +# cms.InputTag("eleNewEnergiesProducer", "energySCEleMust"), +# cms.InputTag("eleNewEnergiesProducer", "energySCEleMustVar"), +# ] #============================== Adding electron ID to patElectrons @@ -64,7 +64,8 @@ tight25nsRun2 = cms.InputTag("eleSelectionProducers", "tight25nsRun2"), loose50nsRun2 = cms.InputTag("eleSelectionProducers", "loose50nsRun2"), medium50nsRun2 = cms.InputTag("eleSelectionProducers", "medium50nsRun2"), - tight50nsRun2 = cms.InputTag("eleSelectionProducers", "tight50nsRun2") + tight50nsRun2 = cms.InputTag("eleSelectionProducers", "tight50nsRun2"), + tightElectronStream = cms.InputTag("eleSelectionProducers", "tightElectronStream") ) electronMatch.src=cms.InputTag('gedGsfElectrons') @@ -86,16 +87,37 @@ photonMatch.src=cms.InputTag('gedPhotons') muonMatch.src=cms.InputTag('muons') + +#============================== Slimming electron (not really slimming if alcareco +from PhysicsTools.PatAlgos.slimming.slimmedElectrons_cfi import * +slimmedElectrons.src = cms.InputTag('patElectrons') +slimmedElectrons.linkToPackedPFCandidates = cms.bool(False) +slimmedElectrons.modifierConfig = cms.PSet( + modifications = cms.VPSet( + cms.PSet( modifierName = cms.string('EGExtraInfoModifierFromFloatValueMaps'), + electron_config = cms.PSet( + electronSrc = cms.InputTag("slimmedElectrons","","@skipCurrentProcess"), + energySCEleMust = cms.InputTag("eleNewEnergiesProducer","energySCEleMust"), + energySCEleMustVar = cms.InputTag("eleNewEnergiesProducer","energySCEleMustVar"), + energySCElePho = cms.InputTag("eleNewEnergiesProducer","energySCElePho"), + energySCElePhoVar = cms.InputTag("eleNewEnergiesProducer","energySCElePhoVar") + ), + photon_config = cms.PSet( ) + ) +) +) + #process.trackerDrivenRemoverSeq: sequence to remove events with trackerDriven electrons #process.eleSelectionProducers: produces value maps of floats that says if the electron passes the given selection #process.eleNewEnergiesProducer: produces value maps of floats with the new calculated electron energy #process.electronMatch: assosiation map of gsfelectron and genparticle #process.patElectrons: producer of patElectron #process.zNtupleDumper: dumper of flat tree for MVA energy training (Francesco Micheli) -prePatSequence = cms.Sequence((eleSelectionProducers + eleNewEnergiesProducer)) +prePatSequence = cms.Sequence((eleSelectionProducers )) +postPatSequence = cms.Sequence() #eleNewEnergiesProducer) # * slimmedElectrons ) patTriggerMatchSeq = cms.Sequence( patTrigger * PatElectronTriggerMatchHLTEle_Ele20SC4Mass50v7 * PatElectronsTriggerMatch * patTriggerEvent ) -patSequence=cms.Sequence( prePatSequence * patElectrons ) -patSequenceMC=cms.Sequence( electronMatch * prePatSequence * patElectrons ) +patSequence=cms.Sequence( prePatSequence * patElectrons * postPatSequence) +patSequenceMC=cms.Sequence( electronMatch * prePatSequence * patElectrons * postPatSequence) eleNewEnergiesProducer.recHitCollectionEB = cms.InputTag("alCaIsolatedElectrons", "alCaRecHitsEB") diff --git a/ZNtupleDumper/python/zntupledumper_cfi.py b/ZNtupleDumper/python/zntupledumper_cfi.py index 20e2cecf7a9..e787d20c8eb 100644 --- a/ZNtupleDumper/python/zntupledumper_cfi.py +++ b/ZNtupleDumper/python/zntupledumper_cfi.py @@ -23,6 +23,8 @@ doStandardTree = cms.bool(True), doExtraCalibTree = cms.bool(False), doEleIDTree = cms.bool(False), + electronStream = cms.bool(False), + caloMetCollection = cms.InputTag('hltMet'), # pdfWeightCollections = cms.VInputTag(cms.InputTag('pdfWeights:cteq66'), cms.InputTag("pdfWeights:MRST2006nnlo"), cms.InputTag('pdfWeights:NNPDF10')), pdfWeightCollections = cms.VInputTag(), fsrWeightCollection = cms.InputTag("fsrWeight"),