CMS 3D CMS Logo

/data/doxygen/doxygen-1.7.3/gen/CMSSW_4_2_8/src/Calibration/EcalCalibAlgos/src/ZeeCalibration.cc

Go to the documentation of this file.
00001 #include "FWCore/ParameterSet/interface/ParameterSet.h"
00002 
00003 #include "DataFormats/EcalRecHit/interface/EcalRecHitCollections.h"
00004 #include "DataFormats/EcalRecHit/interface/EcalRecHit.h"
00005 #include "DataFormats/EcalDetId/interface/EBDetId.h"
00006 #include "DataFormats/EcalDetId/interface/EEDetId.h"
00007 #include "DataFormats/DetId/interface/DetId.h"
00008 #include "CondFormats/EcalObjects/interface/EcalIntercalibConstants.h"
00009 #include "CondFormats/DataRecord/interface/EcalIntercalibConstantsRcd.h"
00010 #include "Calibration/Tools/interface/calibXMLwriter.h"
00011 
00012 #include "Calibration/Tools/interface/CalibrationCluster.h"
00013 #include "Calibration/Tools/interface/HouseholderDecomposition.h"
00014 #include "Calibration/Tools/interface/MinL3Algorithm.h"
00015 #include "Calibration/Tools/interface/EcalRingCalibrationTools.h"
00016 #include "Calibration/Tools/interface/EcalIndexingTools.h"
00017 
00018 #include "CLHEP/Vector/LorentzVector.h"
00019 
00020 #include "FWCore/Framework/interface/EventSetup.h"
00021 #include "FWCore/Framework/interface/ESHandle.h"
00022 #include "Geometry/CaloGeometry/interface/CaloSubdetectorGeometry.h"
00023 #include "Geometry/CaloGeometry/interface/CaloGeometry.h"
00024 #include "Geometry/Records/interface/CaloGeometryRecord.h"
00025 
00026 #include "SimDataFormats/GeneratorProducts/interface/HepMCProduct.h"
00027 
00028 #include "Calibration/EcalCalibAlgos/interface/ZeeCalibration.h"
00029 #include "Calibration/EcalCalibAlgos/interface/ZeeKinematicTools.h"
00030 
00031 #include "CalibCalorimetry/CaloMiscalibTools/interface/MiscalibReaderFromXMLEcalBarrel.h"
00032 #include "CalibCalorimetry/CaloMiscalibTools/interface/MiscalibReaderFromXMLEcalEndcap.h"
00033 #include "CalibCalorimetry/CaloMiscalibTools/interface/CaloMiscalibMapEcal.h"
00034 
00035 #include "DataFormats/EgammaCandidates/interface/Electron.h"
00036 #include "DataFormats/EgammaCandidates/interface/GsfElectron.h"
00037 #include "DataFormats/EgammaCandidates/interface/GsfElectronFwd.h"
00038 #include "DataFormats/EgammaReco/interface/SuperCluster.h"
00039 #include "DataFormats/TrackReco/interface/Track.h"
00040 #include "DataFormats/TrackReco/interface/TrackFwd.h"
00041 #include "DataFormats/TrackReco/interface/TrackExtraFwd.h"
00042 #include "DataFormats/EgammaReco/interface/BasicCluster.h"
00043 
00044 #include "DataFormats/CaloRecHit/interface/CaloRecHit.h"
00045 
00047 #include "HLTrigger/HLTanalyzers/interface/HLTrigReport.h"
00048 #include "DataFormats/Common/interface/Handle.h"
00049 #include "DataFormats/Common/interface/TriggerResults.h"
00050 #include "FWCore/MessageLogger/interface/MessageLogger.h"
00051 #include "FWCore/Framework/interface/CachedProducts.h"
00052 #include "FWCore/ServiceRegistry/interface/Service.h"
00053 #include "FWCore/Framework/interface/TriggerNamesService.h"
00054 #include <FWCore/Framework/interface/Selector.h>
00055 
00056 
00057 #include "TTree.h"
00058 #include "TBranch.h"
00059 #include "TCanvas.h"
00060 #include "TFile.h"
00061 #include "TProfile.h"
00062 #include "TH1.h"
00063 #include "TH2.h"
00064 #include "TF1.h"
00065 #include "TGraph.h"
00066 #include "TGraphErrors.h"
00067 #include "TRandom.h"
00068 
00069 #include <iostream>
00070 #include <string>
00071 #include <stdexcept>
00072 #include <vector>
00073 #include <utility>
00074 #include <map>
00075 #include <fstream>
00076 
00077 #define MZ 91.1876
00078 
00079 #define DEBUG 1
00080 
00081 ZeeCalibration::ZeeCalibration(const edm::ParameterSet& iConfig)
00082 {
00083 
00084 #ifdef DEBUG
00085   std::cout<<"[ZeeCalibration] Starting the ctor"<<std::endl;
00086 #endif
00087 
00088   theMaxLoops =  iConfig.getUntrackedParameter<unsigned int>("maxLoops",0);
00089 
00090   wantEtaCorrection_ = iConfig.getUntrackedParameter<bool>("wantEtaCorrection",true);   
00091 
00092   outputFileName_  = iConfig.getParameter<std::string>("outputFile");
00093 
00094   minInvMassCut_ = iConfig.getUntrackedParameter<double>("minInvMassCut", 70.);   
00095   maxInvMassCut_ = iConfig.getUntrackedParameter<double>("maxInvMassCut", 110.);   
00096 
00097   rechitProducer_ = iConfig.getParameter<std::string>("rechitProducer");
00098   rechitCollection_ = iConfig.getParameter<std::string>("rechitCollection");
00099 
00100   erechitProducer_ = iConfig.getParameter<std::string>("erechitProducer");
00101   erechitCollection_ = iConfig.getParameter<std::string>("erechitCollection");
00102 
00103   scProducer_ = iConfig.getParameter<std::string>("scProducer");
00104   scCollection_ = iConfig.getParameter<std::string>("scCollection");
00105 
00106   scIslandProducer_ = iConfig.getParameter<std::string>("scIslandProducer");
00107   scIslandCollection_ = iConfig.getParameter<std::string>("scIslandCollection");
00108 
00109   calibMode_ = iConfig.getUntrackedParameter<std::string>("ZCalib_CalibType");
00110 
00111   mcProducer_ = iConfig.getUntrackedParameter<std::string>("mcProducer","");
00112 
00113 
00114   electronProducer_ = iConfig.getParameter<std::string > ("electronProducer");
00115   electronCollection_ = iConfig.getParameter<std::string > ("electronCollection");
00116 
00117   outputFile_ = TFile::Open(outputFileName_.c_str(),"RECREATE"); // open output file to store histograms  
00118   
00119   myTree = new TTree("myTree","myTree");
00120   //  myTree->Branch("zMass","zMass", &mass);
00121   myTree->Branch("zMass",&mass4tree,"mass/F");
00122   myTree->Branch("zMassDiff",&massDiff4tree,"massDiff/F");
00123 
00124   barrelfile_=iConfig.getUntrackedParameter<std::string> ("initialMiscalibrationBarrel","");
00125   endcapfile_=iConfig.getUntrackedParameter<std::string> ("initialMiscalibrationEndcap","");
00126 
00127   electronSelection_=iConfig.getUntrackedParameter<unsigned int> ("electronSelection",0);//option for electron selection
00128 
00129   etaBins_ = iConfig.getUntrackedParameter<unsigned int>("etaBins", 10);   
00130   etBins_ = iConfig.getUntrackedParameter<unsigned int>("etBins", 10);   
00131 
00132   etaMin_ = iConfig.getUntrackedParameter<double>("etaMin", 0.);   
00133   etMin_ = iConfig.getUntrackedParameter<double>("etMin", 0.);   
00134   etaMax_ = iConfig.getUntrackedParameter<double>("etaMax", 3.);   
00135   etMax_ = iConfig.getUntrackedParameter<double>("etMax", 100.);   
00136 
00137  
00138   //  new ZeePlots("zeePlots.root");
00139   //  ZeePlots->bookHistos();
00140 
00141   //ZeeCalibrationPLots("zeeCalibPlots");
00142   //ZeecaPlots->bookHistos(maxsIter); 
00143   
00144   hlTriggerResults_ = iConfig.getParameter<edm::InputTag> ("HLTriggerResults");
00145 
00146   theParameterSet=iConfig;
00147   EcalIndexingTools* myIndexTool=0;
00148 
00149   
00150   myIndexTool = EcalIndexingTools::getInstance();
00151   
00152   myIndexTool->setBinRange( etaBins_, etaMin_, etaMax_, etBins_, etMin_, etMax_ );
00153   
00154   //creating the algorithm
00155   theAlgorithm_ = new ZIterativeAlgorithmWithFit(iConfig);
00156   
00157   // Tell the framework what data is being produced
00158   //setWhatProduced(this);
00159   setWhatProduced (this, &ZeeCalibration::produceEcalIntercalibConstants ) ;
00160   findingRecord<EcalIntercalibConstantsRcd> () ;
00161 
00162   for(int i = 0; i<50; i++){
00163 
00164     coefficientDistanceAtIteration[i] = -1.;
00165     loopArray[i] = -1.;
00166     sigmaArray[i] = -1.;
00167     sigmaErrorArray[i] = -1.;
00168 
00169   }
00170 
00171 #ifdef DEBUG
00172   std::cout<<"[ZeeCalibration] Done with the ctor"<<std::endl;
00173 #endif
00174 
00175 }
00176 
00177 
00178 ZeeCalibration::~ZeeCalibration()
00179 {
00180 //   if (theAlgorithm_)
00181 //     delete theAlgorithm_;
00182 }
00183 
00184 //_____________________________________________________________________________
00185 // Produce EcalIntercalibConstants
00186 boost::shared_ptr<EcalIntercalibConstants>
00187 ZeeCalibration::produceEcalIntercalibConstants( const EcalIntercalibConstantsRcd& iRecord )
00188 {
00189   std::cout << "@SUB=ZeeCalibration::produceEcalIntercalibConstants" << std::endl;
00190   return ical;
00191 }
00192 
00193 void ZeeCalibration::beginOfJob(){isfirstcall_=true;}
00194 
00195 
00196 
00197 
00198 //========================================================================
00199 void
00200 ZeeCalibration::endOfJob() {
00201 
00202 
00203   printStatistics();
00204 
00205   if(calibMode_ != "ETA_ET_MODE"){
00206 
00208 
00209   //Writing out calibration coefficients
00210   calibXMLwriter* barrelWriter = new calibXMLwriter(EcalBarrel);
00211   for(int ieta=-EBDetId::MAX_IETA; ieta<=EBDetId::MAX_IETA ;++ieta) {
00212     if(ieta==0) continue;
00213     for(int iphi=EBDetId::MIN_IPHI; iphi<=EBDetId::MAX_IPHI; ++iphi) {
00214       // make an EBDetId since we need EBDetId::rawId() to be used as the key for the pedestals
00215       if (EBDetId::validDetId(ieta,iphi))
00216         {
00217           EBDetId ebid(ieta,iphi);
00218           barrelWriter->writeLine(ebid,* (ical->getMap().find(ebid.rawId()) ));
00219         }
00220     }
00221   }
00222   
00223 
00224   
00225   calibXMLwriter* endcapWriter = new calibXMLwriter(EcalEndcap);
00226   for(int iX=EEDetId::IX_MIN; iX<=EEDetId::IX_MAX ;++iX) {
00227     for(int iY=EEDetId::IY_MIN; iY<=EEDetId::IY_MAX; ++iY) {
00228       // make an EEDetId since we need EEDetId::rawId() to be used as the key for the pedestals
00229       if (EEDetId::validDetId(iX,iY,1))
00230         {
00231           EEDetId eeid(iX,iY,1);
00232           endcapWriter->writeLine(eeid,*(ical->getMap().find(eeid.rawId())  ) );
00233         }
00234       if (EEDetId::validDetId(iX,iY,-1))
00235         {
00236           EEDetId eeid(iX,iY,-1);
00237           endcapWriter->writeLine(eeid, *(ical->getMap().find(eeid.rawId())) );
00238         }
00239       
00240     }
00241   }
00242   
00243 
00244   } 
00245 
00246   std::cout<<"Writing  histos..."<<std::endl;
00247   outputFile_->cd();
00248 
00249   //  zeeplts->Write();
00250 
00251   h1_eventsBeforeEWKSelection_ ->Write();
00252   h1_eventsAfterEWKSelection_ ->Write();
00253 
00254   h1_eventsBeforeBorderSelection_ ->Write();
00255   h1_eventsAfterBorderSelection_ ->Write();
00256 
00257   h1_borderElectronClassification_->Write();
00258  
00259   h2_xtalMiscalibCoeffBarrel_->Write();
00260   h2_xtalMiscalibCoeffEndcapMinus_->Write();
00261   h2_xtalMiscalibCoeffEndcapPlus_->Write();
00262 
00263   h1_electronCosTheta_SC_->Write();
00264   h1_electronCosTheta_TK_->Write();
00265   h1_electronCosTheta_SC_TK_->Write();
00266 
00267   h1_zMassResol_->Write();
00268   h1_zEtaResol_->Write();
00269   h1_zPhiResol_->Write();
00270   h1_eleEtaResol_->Write();
00271   h1_elePhiResol_->Write();
00272   h1_seedOverSC_ ->Write();
00273   h1_preshowerOverSC_ ->Write();
00274    
00275   for(unsigned int i =0; i<25; i++){
00276     if( i < theMaxLoops ){
00277       
00278       h_ESCEtrueVsEta_[i]->Write();
00279       h_ESCEtrue_[i]->Write();
00280       
00281       h_ESCcorrEtrueVsEta_[i]->Write();
00282       h_ESCcorrEtrue_[i]->Write();
00283       
00284       h2_chi2_[i]->Write();
00285       h2_iterations_[i]->Write();
00286       
00287       //      h_DiffZMassDistr_[i]->Write();
00288       
00289       //h_ZMassDistr_[i]->Write();
00290     }
00291   }
00292 
00293   h2_fEtaBarrelGood_->Write();
00294   h2_fEtaBarrelBad_->Write();
00295   h2_fEtaEndcapGood_->Write();
00296   h2_fEtaEndcapBad_->Write();
00297   h1_eleClasses_->Write();
00298 
00299   h_eleEffEta_[0]->Write();
00300   h_eleEffPhi_[0]->Write();
00301   h_eleEffPt_[0]->Write();
00302   
00303   h_eleEffEta_[1]->Write();
00304   h_eleEffPhi_[1]->Write();
00305   h_eleEffPt_[1]->Write();
00306 
00307   
00308   int j = 0;
00309 
00310   int flag=0;
00311   
00312   Double_t mean[25] = {0.};
00313   Double_t num[25] = {0.};
00314   Double_t meanErr[25] = {0.};
00315   Float_t rms[25] = {0.};
00316   Float_t tempRms[10][25];
00317   
00318   for(int ia = 0; ia<10; ia++){
00319     for(int ib = 0; ib<25; ib++){
00320   
00321       tempRms[ia][ib] = 0.;
00322 
00323     }
00324   }
00325     
00326   int aa = 0;
00327       
00328   for( int k = 0; k<theAlgorithm_->getNumberOfChannels(); k++ )
00329     {
00330  
00331 
00332       
00334       bool isNearCrack = false;
00335       
00336       if( calibMode_ == "RING"){
00337         
00338         isNearCrack = ( abs( ringNumberCorrector(k) ) == 1 || abs( ringNumberCorrector(k) ) == 25 ||
00339                         abs( ringNumberCorrector(k) ) == 26 || abs( ringNumberCorrector(k) ) == 45 ||
00340                         abs( ringNumberCorrector(k) ) == 46 || abs( ringNumberCorrector(k) ) == 65 ||
00341                         abs( ringNumberCorrector(k) ) == 66 || abs( ringNumberCorrector(k) ) == 85 ||
00342                         abs( ringNumberCorrector(k) ) == 86 || abs( ringNumberCorrector(k) ) == 124 );
00343       }
00344       
00345       if(k<85)
00346         {
00347           
00348           if((k+1)%5!=0)
00349             {
00350               
00351               if(!isNearCrack){
00352                 mean[j]+=calibCoeff[k];
00353                 mean[j]+=calibCoeff[169 - k];
00354                 
00355                 num[j] += 2.;
00356                 
00357                 //meanErr[j]+= calibCoeffError[k];
00358                 //meanErr[j]+= calibCoeffError[169 - k];
00359                 
00360                 meanErr[j]+= 1./ pow ( calibCoeffError[k], 2 );
00361                 meanErr[j]+= 1./ pow ( calibCoeffError[169 - k], 2);
00362 
00363 
00364               tempRms[aa][j]+=calibCoeff[k];
00365                 aa++;
00366                 tempRms[aa][j]+=calibCoeff[169 - k];
00367                 aa++;
00368               }
00369             }
00370           
00371           else  {
00372             if(!isNearCrack){
00373               mean[j]+=calibCoeff[k];
00374               mean[j]+=calibCoeff[169 - k];
00375               
00376               num[j] += 2.;
00377               
00378               //meanErr[j]+= calibCoeffError[k];
00379               //meanErr[j]+= calibCoeffError[169 - k];
00380               
00381               meanErr[j]+= 1./ pow ( calibCoeffError[k], 2 );
00382               meanErr[j]+= 1./ pow ( calibCoeffError[169 - k], 2);
00383 
00384               tempRms[aa][j]+=calibCoeff[k];
00385               aa++;
00386               tempRms[aa][j]+=calibCoeff[169 - k];
00387               aa++;
00388 
00389             }
00390             j++;
00391             aa = 0;
00392             
00393           }
00394           
00395         }
00396       //EE begin
00397       
00398       
00399       if(k>=170 && k<=204){
00400         
00401         if(flag<4){
00402           //make groups of 5 Xtals in #eta
00403           mean[j]+=calibCoeff[k]/10.;
00404           mean[j]+=calibCoeff[k+39]/10.;
00405         
00406           meanErr[j]+= calibCoeffError[k]/30.;
00407           meanErr[j]+= calibCoeffError[k + 39]/30.;
00408 
00409           
00410           tempRms[aa][j]+=calibCoeff[k];
00411           aa++;
00412           tempRms[aa][j]+=calibCoeff[k + 39];
00413           aa++;
00414           
00415           flag++;
00416         }
00417 
00418         else if(flag==4){
00419           //make groups of 5 Xtals in #eta
00420           mean[j]+=calibCoeff[k]/10.;
00421           mean[j]+=calibCoeff[k+39]/10.;
00422 
00423           meanErr[j]+= calibCoeffError[k]/30.;
00424           meanErr[j]+= calibCoeffError[k + 39]/30.;
00425           
00426           tempRms[aa][j]+=calibCoeff[k];
00427           aa++;
00428           tempRms[aa][j]+=calibCoeff[k + 39];
00429           aa++;
00430           
00431           flag=0;
00432           //      std::cout<<" index(>85) "<<k<<" j is "<<j<<" mean[j] is "<<mean[j]<<std::endl;
00433           j++;
00434           aa = 0;
00435 
00436         }
00437         
00438       }
00439       if(k>=205 && k<=208){
00440         mean[j]+=calibCoeff[k]/8.;
00441         mean[j]+=calibCoeff[k+39]/8.;
00442 
00443         meanErr[j]+= calibCoeffError[k]/30.;
00444         meanErr[j]+= calibCoeffError[k + 39]/30.;
00445         
00446         
00447         tempRms[aa][j]+=calibCoeff[k];
00448         aa++;
00449         tempRms[aa][j]+=calibCoeff[k + 39];
00450         aa++;
00451       }
00452       //EE end
00453 
00454       /*
00455       for(int jj =0; jj< 25; jj++){ 
00456       if(meanErr[jj] > 0.)
00457         std::cout<<" meanErr[jj] before sqrt: "<<meanErr[jj]<<std::endl;
00458 
00459         meanErr[jj] = 1./sqrt( meanErr[jj] );
00460 
00461         std::cout<<" meanErr[jj] after sqrt: "<<meanErr[jj]<<std::endl;
00462       }
00463       */
00464       
00465       
00466       
00467       if(!isNearCrack){
00468         h2_coeffVsEta_->Fill( ringNumberCorrector(k), calibCoeff[k] );
00469         h2_miscalRecal_->Fill( initCalibCoeff[k], 1./calibCoeff[k] );
00470         h1_mc_->Fill( initCalibCoeff[k]*calibCoeff[k] -1. );
00471         
00472         
00473         
00474         if(k<170){
00475           h2_miscalRecalEB_->Fill( initCalibCoeff[k], 1./calibCoeff[k] );
00476           h1_mcEB_->Fill( initCalibCoeff[k]*calibCoeff[k] -1. );
00477         }
00478         
00479         if(k>=170){
00480           h2_miscalRecalEE_->Fill( initCalibCoeff[k], 1./calibCoeff[k] );
00481           h1_mcEE_->Fill( initCalibCoeff[k]*calibCoeff[k] -1. );
00482         }    
00483         
00484       }
00485     }
00486   
00487   for(int ic = 0; ic< 17; ic++){
00488 
00489     mean[ic] = mean[ic] / num[ic]; //find mean of recalib coeff on group of rings
00490     //meanErr[ic] = meanErr[ic] / ( sqrt( num[ic] ) * num[ic] ); //find mean of recalib coeff on group of rings
00491     meanErr[ic] = 1. / sqrt(meanErr[ic]); //find mean of recalib coeff on group of rings
00492     
00493   }
00494 
00495 
00496   //build array of RMS
00497   for(int ic = 0; ic< 25; ic++){
00498     for(int id = 0; id< 10; id++){
00499 
00500       if(tempRms[id][ic] > 0.){
00501         
00502         rms[ic] += (tempRms[id][ic] - mean[j])*(tempRms[id][ic] - mean[j]);
00503         
00504       }
00505     }
00506     rms[ic]/= 10.;//this is approximate
00507     rms[ic] = sqrt(rms[ic]);
00508   }
00509   
00510   //build array of RMS
00511   
00512   
00513   
00514   Double_t xtalEta[25] = {1.4425, 1.3567,1.2711,1.1855,
00515                          1.10,1.01,0.92,0.83,
00516                          0.7468,0.6612,0.5756,0.4897,0.3985,0.3117,0.2250,0.1384,0.0487,
00517                          1.546, 1.651, 1.771, 1.908, 2.071, 2.267, 2.516, 2.8};
00518   
00519   Double_t zero[25] = {0.026};//interval/sqrt(12)
00520 
00521   for(int j = 0; j <25; j++)
00522     h2_coeffVsEtaGrouped_->Fill( xtalEta[j],mean[j]);
00523   
00524   //  for(int sho = 0; sho <25; sho++)
00525   //cout<<"xtalEta[j] "<< xtalEta[sho]<<" mean[j]  "<<mean[sho]<<"  err[j] "<<meanErr[sho]<<std::endl;
00526 
00527   TProfile *px = h2_coeffVsEta_->ProfileX("coeffVsEtaProfile");
00528   px->SetXTitle("Eta channel");
00529   px->SetYTitle("recalibCoeff");
00530   px->Write();
00531 
00532   h2_coeffVsEta_->Write();
00533   h2_coeffVsEtaGrouped_->Write();
00534   h2_zMassVsLoop_->Write();
00535   h2_zMassDiffVsLoop_->Write();
00536   h2_zWidthVsLoop_->Write();
00537   h2_coeffVsLoop_->Write();
00538   h2_miscalRecal_->Write();
00539   h1_mc_->Write();
00540   h2_miscalRecalEB_->Write();
00541   h1_mcEB_->Write();
00542   h2_miscalRecalEE_->Write();
00543   h1_mcEE_->Write();
00544 
00545   h2_residualSigma_->Write();
00546 
00547   const ZIterativeAlgorithmWithFit::ZIterativeAlgorithmWithFitPlots* algoHistos=theAlgorithm_->getHistos();
00548 
00549   double weightSumMeanBarrel = 0.;
00550   double weightSumMeanEndcap = 0.;
00551 
00552   for (int iIteration=0;iIteration<theAlgorithm_->getNumberOfIterations();iIteration++)
00553     for (int iChannel=0;iChannel<theAlgorithm_->getNumberOfChannels();iChannel++)
00554       {
00555 
00556         if( iIteration==(theAlgorithm_->getNumberOfIterations()-1) ){
00557           
00558           if(iChannel < 170)
00559             weightSumMeanBarrel += algoHistos->weightedRescaleFactor[iIteration][iChannel]->Integral()/170.; 
00560 
00561           if(iChannel >= 170)
00562             weightSumMeanEndcap += algoHistos->weightedRescaleFactor[iIteration][iChannel]->Integral()/78.; 
00563           
00564           h1_occupancyVsEta_->Fill((Double_t)ringNumberCorrector(iChannel), algoHistos->weightedRescaleFactor[iIteration][iChannel]->Integral() );
00565           
00566           
00567           h1_occupancy_->Fill( algoHistos->weightedRescaleFactor[iIteration][iChannel]->Integral() );
00568           
00569           if(iChannel < 170)
00570             h1_occupancyBarrel_->Fill( algoHistos->weightedRescaleFactor[iIteration][iChannel]->Integral() );
00571 
00572           if(iChannel >= 170)
00573             h1_occupancyEndcap_->Fill( algoHistos->weightedRescaleFactor[iIteration][iChannel]->Integral() );
00574 
00575 #ifdef DEBUG
00576           std::cout<<"Writing weighted integral for channel "<<ringNumberCorrector(iChannel)<<" ,value "<<algoHistos->weightedRescaleFactor[iIteration][iChannel]->Integral()<<std::endl;
00577 #endif
00578 
00579         }
00580         
00581       }
00582   
00583   //  std::cout<<"Done! Closing output file... "<<std::endl;
00584 
00585   h1_weightSumMeanBarrel_ ->Fill(weightSumMeanBarrel);
00586   h1_weightSumMeanEndcap_ ->Fill(weightSumMeanEndcap);
00587 
00588   std::cout<<"Weight sum mean on channels in Barrel is :"<<weightSumMeanBarrel<<std::endl;
00589   std::cout<<"Weight sum mean on channels in Endcap is :"<<weightSumMeanEndcap<<std::endl;
00590 
00591   h1_weightSumMeanBarrel_ ->Write();
00592   h1_weightSumMeanEndcap_ ->Write();
00593 
00594   h1_occupancyVsEta_->Write();
00595    h1_occupancy_->Write();
00596   h1_occupancyBarrel_->Write();
00597   h1_occupancyEndcap_->Write();
00598 
00599   myTree->Write();
00600 
00601   TGraphErrors* graph = new TGraphErrors(25,xtalEta,mean,zero,meanErr);
00602   graph->Draw("APL");
00603   graph->Write();
00604 
00605   double zero50[50] = { 0. };
00606 
00607   TGraphErrors* residualSigmaGraph = new TGraphErrors(50,loopArray,sigmaArray,zero50,sigmaErrorArray);
00608   residualSigmaGraph->SetName("residualSigmaGraph");
00609   residualSigmaGraph->Draw("APL");
00610   residualSigmaGraph->Write();
00611 
00612   TGraphErrors* coefficientDistanceAtIterationGraph = new TGraphErrors(50,loopArray,coefficientDistanceAtIteration,zero50,zero50);
00613   coefficientDistanceAtIterationGraph->SetName("coefficientDistanceAtIterationGraph");
00614   coefficientDistanceAtIterationGraph->Draw("APL");
00615   coefficientDistanceAtIterationGraph->Write();
00616 
00617   Float_t noError[250] = {0.};
00618 
00619   Float_t ringInd[250];
00620   for(int i =0; i<250; i++)
00621     ringInd[i]=ringNumberCorrector(i);
00622 
00623   TGraphErrors* graphCoeff = new TGraphErrors(theAlgorithm_->getNumberOfChannels(),ringInd,calibCoeff,noError,calibCoeffError);
00624   graphCoeff->SetName("graphCoeff");
00625   graphCoeff->Draw("APL");
00626   graphCoeff->Write();
00627   
00628   //   outputFile_->Write();//this automatically writes all histos on file
00629  
00630 
00631   h1_ZCandMult_->Write();
00632   h1_reco_ZMass_->Write();
00633   
00634   h1_reco_ZMassCorr_->Write();
00635   h1_reco_ZMassCorrBB_->Write();
00636   h1_reco_ZMassCorrEE_->Write();
00637 
00638   outputFile_->Close();
00639   
00640   myZeePlots_ ->writeEleHistograms();
00641   myZeePlots_ ->writeMCEleHistograms();
00642   myZeePlots_ ->writeZHistograms();
00643   myZeePlots_ ->writeMCZHistograms();
00644   
00645   // myZeeRescaleFactorPlots_ = new ZeeRescaleFactorPlots("zeeRescaleFactorPlots.root");
00646   //myZeeRescaleFactorPlots_->writeHistograms( theAlgorithm_ );
00647   
00648   //  delete myZeeRescaleFactorPlots_;
00649   
00650   
00651   
00652 }
00653 
00654 //_____________________________________________________________________________
00655 // Called at each event
00656 //________________________________________
00657 
00658 edm::EDLooper::Status
00659 ZeeCalibration::duringLoop( const edm::Event& iEvent, const edm::EventSetup& iSetup )
00660 {
00661   using namespace edm;
00662 
00663 #ifdef DEBUG
00664   std::cout<<"[ZeeCalibration] Entering duringLoop"<<std::endl;
00665 #endif
00666  
00667   
00668   // code that used to be in beginJob
00669   if (isfirstcall_){
00670 
00671     //inizializzare la geometria di ecal
00672     edm::ESHandle<CaloGeometry> pG;
00673     iSetup.get<CaloGeometryRecord>().get(pG);     
00674     EcalRingCalibrationTools::setCaloGeometry(&(*pG));  
00675      
00676     myZeePlots_ = new ZeePlots( "zeePlots.root" );
00677     //  myZeeRescaleFactorPlots_ = new ZeeRescaleFactorPlots("zeeRescaleFactorPlots.root");
00678 
00679     // go to *OUR* rootfile and book histograms                                                                                                                
00680     outputFile_->cd();
00681     bookHistograms();
00682 
00683     std::cout<<"[ZeeCalibration::beginOfJob] Histograms booked "<<std::endl;
00684 
00685     loopFlag_ = 0;
00686 
00687     //Read miscalibration map if requested
00688     CaloMiscalibMapEcal* miscalibMap=0;
00689     if (!barrelfile_.empty() || !barrelfile_.empty())
00690       {
00691         miscalibMap=new CaloMiscalibMapEcal();
00692         miscalibMap->prefillMap();
00693       }
00694 
00695 
00696     if(!barrelfile_.empty())
00697       {
00698         MiscalibReaderFromXMLEcalBarrel barrelreader_(*miscalibMap);
00699         barrelreader_.parseXMLMiscalibFile(barrelfile_);
00700 #ifdef DEBUG
00701         std::cout<<"[ZeeCalibration::beginOfJob] Parsed EB miscal file"<<std::endl;
00702 #endif
00703       }
00704 
00705     if(!endcapfile_.empty())
00706       {
00707         MiscalibReaderFromXMLEcalEndcap endcapreader_(*miscalibMap);
00708         endcapreader_.parseXMLMiscalibFile(endcapfile_);
00709 #ifdef DEBUG
00710         std::cout<<"[ZeeCalibration::beginOfJob] Parsed EE miscal file"<<std::endl;
00711 #endif
00712       }
00713 
00714     std::cout << "  theAlgorithm_->getNumberOfChannels() "
00715               << theAlgorithm_->getNumberOfChannels() << std::endl;
00716 
00717 
00719     for(int k = 0; k < theAlgorithm_->getNumberOfChannels(); k++)
00720       {
00721         calibCoeff[k]=1.;
00722         calibCoeffError[k]=0.;
00723      
00724         std::vector<DetId> ringIds;
00725 
00726         if(calibMode_ == "RING")
00727           ringIds = EcalRingCalibrationTools::getDetIdsInRing(k);
00728 
00729         if(calibMode_ == "MODULE")
00730           ringIds = EcalRingCalibrationTools::getDetIdsInModule(k);
00731 
00732         if(calibMode_ == "ABS_SCALE" || calibMode_ == "ETA_ET_MODE" )
00733           ringIds = EcalRingCalibrationTools::getDetIdsInECAL();
00734       
00735         if (miscalibMap)
00736           {
00737             initCalibCoeff[k]=0.;             
00738             for (unsigned int iid=0; iid<ringIds.size();++iid)
00739               {
00740                 float miscalib=* (miscalibMap->get().getMap().find(ringIds[iid])  );
00741                 //            float miscalib=miscalibMap->get().getMap().find(ringIds[iid])->second; ////////AP
00742                 initCalibCoeff[k]+=miscalib;
00743               }
00744             initCalibCoeff[k]/=(float)ringIds.size();
00745             std::cout << k << " " << initCalibCoeff[k] << " " << ringIds.size() << std::endl;
00746           }
00747         else
00748           {
00749             initCalibCoeff[k]=1.;
00750           }
00751       }
00752 
00753     ical = boost::shared_ptr<EcalIntercalibConstants>( new EcalIntercalibConstants() );
00754   
00755     for(int k = 0; k < theAlgorithm_->getNumberOfChannels(); k++)
00756       {
00757         //      std::vector<DetId> ringIds = EcalRingCalibrationTools::getDetIdsInRing(k);
00758 
00759         std::vector<DetId> ringIds;
00760 
00761         if(calibMode_ == "RING")
00762           ringIds = EcalRingCalibrationTools::getDetIdsInRing(k);
00763 
00764         if(calibMode_ == "MODULE")
00765           ringIds = EcalRingCalibrationTools::getDetIdsInModule(k);
00766 
00767         if(calibMode_ == "ABS_SCALE" || calibMode_ == "ETA_ET_MODE")
00768           ringIds = EcalRingCalibrationTools::getDetIdsInECAL();
00769       
00770       
00771         for (unsigned int iid=0; iid<ringIds.size();++iid){
00772           //    ical->setValue( ringIds[iid], 1. * initCalibCoeff[k] );
00773         
00774           if(ringIds[iid].subdetId() == EcalBarrel){
00775             EBDetId myEBDetId(ringIds[iid]);  
00776             h2_xtalMiscalibCoeffBarrel_->SetBinContent( myEBDetId.ieta() + 86, myEBDetId.iphi(), * (miscalibMap->get().getMap().find(ringIds[iid]) ) );//fill TH2 with miscalibCoeff
00777          
00778           }
00779 
00780           if(ringIds[iid].subdetId() == EcalEndcap){
00781             EEDetId myEEDetId(ringIds[iid]);
00782             if(myEEDetId.zside() < 0)
00783               h2_xtalMiscalibCoeffEndcapMinus_->SetBinContent( myEEDetId.ix(), myEEDetId.iy(), * ( miscalibMap->get().getMap().find(ringIds[iid]) ) );//fill TH2 with miscalibCoeff
00784 
00785             if(myEEDetId.zside() > 0)
00786               h2_xtalMiscalibCoeffEndcapPlus_->SetBinContent( myEEDetId.ix(), myEEDetId.iy(), * (miscalibMap->get().getMap().find(ringIds[iid]) ) );//fill TH2 with miscalibCoeff
00787           
00788           }
00789         
00790           ical->setValue( ringIds[iid], *(miscalibMap->get().getMap().find(ringIds[iid])  ) );
00791 
00792         }
00793 
00794   
00795         read_events = 0;
00796         init_ = false;
00797 
00798 
00799       }
00800     isfirstcall_=false;
00801   }// if isfirstcall
00802 
00803   
00804 
00805 
00806 
00807 
00808 
00809 
00810 
00812   
00813   for(unsigned int iHLT=0; iHLT<200; ++iHLT) {
00814     aHLTResults[iHLT] = false;
00815   }
00816 
00817 #ifdef DEBUG
00818   std::cout<<"[ZeeCalibration::duringLoop] Done with initializing aHLTresults[] "<<std::endl;
00819 #endif
00820 
00821   edm::Handle<edm::TriggerResults> hltTriggerResultHandle;
00822   iEvent.getByLabel(hlTriggerResults_, hltTriggerResultHandle);
00823   
00824   if(!hltTriggerResultHandle.isValid()) {
00825     //std::cout << "invalid handle for HLT TriggerResults" << std::endl;
00826   } else {
00827 
00828     hltCount = hltTriggerResultHandle->size();
00829 
00830     if (loopFlag_ == 0)
00831       myZeePlots_->fillHLTInfo(hltTriggerResultHandle);
00832     
00833 #ifdef DEBUG
00834   std::cout<<"[ZeeCalibration::duringLoop] Done with myZeePlots_->fillHLTInfo(hltTriggerResultHandle); "<<std::endl;
00835 #endif
00836 
00837     for(int i = 0 ; i < hltCount ; i++) {
00838       aHLTResults[i] = hltTriggerResultHandle->accept(i);
00839     
00840       //HLT bit 32 = HLT1Electron
00841     //HLT bit 34 = HLT2Electron
00842     //HLT bit 35 = HLT2ElectronRelaxed
00843 
00844      }
00845 
00846       if(!aHLTResults[32] && !aHLTResults[34] && !aHLTResults[35])
00847         return kContinue;
00848       
00849   }
00850   
00851 #ifdef DEBUG
00852   std::cout<<"[ZeeCalibration::duringLoop] End HLT section"<<std::endl;
00853 #endif
00854   
00856   
00857 
00858   std::vector<HepMC::GenParticle*> mcEle;
00859 
00860   float myGenZMass(-1);
00861       
00862   if (!mcProducer_.empty())
00863     {
00864 
00865       //DUMP GENERATED Z MASS - BEGIN
00866       Handle< HepMCProduct > hepProd ;
00867       //   iEvent.getByLabel( "source", hepProd ) ;
00868       iEvent.getByLabel( mcProducer_.c_str(), hepProd ) ;
00869                                                                                                                              
00870       const HepMC::GenEvent * myGenEvent = hepProd->GetEvent();
00871       
00872       if (loopFlag_ == 0)
00873         myZeePlots_->fillZMCInfo( & (*myGenEvent) );
00874       
00875 #ifdef DEBUG
00876   std::cout<<"[ZeeCalibration::duringLoop] Done with myZeePlots_->fillZMCInfo( & (*myGenEvent) ); "<<std::endl;
00877 #endif
00878   
00879       HepMC::GenParticle* genZ=0;
00880       
00881       
00882       for ( HepMC::GenEvent::particle_const_iterator p = myGenEvent->particles_begin();
00883             p != myGenEvent->particles_end(); ++p ) {
00884         //return a pointer to MC Z in the event
00885         if ( (*p)->pdg_id() == 23 && (*p)->status()==2){
00886 
00887           myGenZMass = (*p)->momentum().m();
00888                           genZ=(*p);
00889         }
00890       }
00891       //DUMP GENERATED Z MASS - END
00892      
00893 
00894       if (loopFlag_ == 0)
00895         myZeePlots_ ->fillEleMCInfo( & (*myGenEvent) );
00896       
00897             
00898       //loop over MC positrons and find the closest MC positron in (eta,phi) phace space - begin
00899       HepMC::GenParticle MCele;
00900       
00901       for ( HepMC::GenEvent::particle_const_iterator p = myGenEvent->particles_begin();
00902             p != myGenEvent->particles_end(); ++p ) {
00903         
00904         if (  abs( (*p)->pdg_id() ) == 11 )
00905           {
00906             mcEle.push_back( (*p) );
00907             MCele=*(*p);
00908             
00909           }
00910       }
00911       
00912       
00913       if(mcEle.size()==2 && fabs(mcEle[0]->momentum().eta())<2.4 &&  fabs(mcEle[1]->momentum().eta())<2.4 ){
00914         NEVT++;
00915         
00916         if( fabs(mcEle[0]->momentum().eta())<1.479 && fabs(mcEle[1]->momentum().eta())<1.479 )MCZBB++;
00917         
00918         if( (fabs(mcEle[0]->momentum().eta())>1.479 && fabs(mcEle[1]->momentum().eta())<1.479) || (fabs(mcEle[0]->momentum().eta())<1.479 && fabs(mcEle[1]->momentum().eta())>1.479) )MCZEB++;
00919         
00920         if( fabs(mcEle[0]->momentum().eta())>1.479 && fabs(mcEle[1]->momentum().eta())>1.479 )MCZEE++;
00921         
00922         
00923       }
00924       
00925     }    
00926   
00927   
00928   
00929   // Get EBRecHits
00930   Handle<EBRecHitCollection> phits;
00931   try {
00932     iEvent.getByLabel( rechitProducer_, rechitCollection_, phits);
00933   } catch (std::exception& ex) {
00934     std::cerr << "Error! can't get the product EBRecHitCollection " << std::endl;
00935   }
00936   const EBRecHitCollection* hits = phits.product(); // get a ptr to the product
00937 
00938   // Get EERecHits
00939   Handle<EERecHitCollection> ephits;
00940   try {
00941     iEvent.getByLabel( erechitProducer_, erechitCollection_, ephits);
00942   } catch (std::exception& ex) {
00943     std::cerr << "Error! can't get the product EERecHitCollection " << std::endl;
00944   }
00945   const EERecHitCollection* ehits = ephits.product(); // get a ptr to the product
00946 
00947   
00948   //Get Hybrid SuperClusters
00949   Handle<reco::SuperClusterCollection> pSuperClusters;
00950   try {
00951     iEvent.getByLabel(scProducer_, scCollection_, pSuperClusters);
00952   } catch (std::exception& ex ) {
00953     std::cerr << "Error! can't get the product SuperClusterCollection "<< std::endl;
00954   }
00955   const reco::SuperClusterCollection* scCollection = pSuperClusters.product();
00956 
00957 #ifdef DEBUG
00958   std::cout<<"scCollection->size()"<<scCollection->size()<<std::endl;
00959   for(reco::SuperClusterCollection::const_iterator scIt = scCollection->begin();   scIt != scCollection->end(); scIt++)
00960     {
00961       std::cout<<scIt->energy()<<std::endl;
00962     }
00963 #endif
00964   
00965   //Get Island SuperClusters
00966   Handle<reco::SuperClusterCollection> pIslandSuperClusters;
00967   try {
00968     iEvent.getByLabel(scIslandProducer_, scIslandCollection_, pIslandSuperClusters);
00969   } catch (std::exception& ex ) {
00970     std::cerr << "Error! can't get the product IslandSuperClusterCollection "<< std::endl;
00971   }
00972   const reco::SuperClusterCollection* scIslandCollection = pIslandSuperClusters.product();
00973 
00974 #ifdef DEBUG
00975   std::cout<<"scCollection->size()"<<scIslandCollection->size()<<std::endl;
00976 #endif
00977 
00978   if(  ( scCollection->size()+scIslandCollection->size() ) < 2) 
00979     return kContinue;
00980 
00981   // Get Electrons
00982   Handle<reco::GsfElectronCollection> pElectrons;
00983   try {
00984     iEvent.getByLabel(electronProducer_, electronCollection_, pElectrons);
00985   } catch (std::exception& ex ) {
00986     std::cerr << "Error! can't get the product ElectronCollection "<< std::endl;
00987   }
00988   const reco::GsfElectronCollection* electronCollection = pElectrons.product();
00989 
00990   /*
00991   //reco-mc association map
00992   std::map<HepMC::GenParticle*,const reco::PixelMatchGsfElectron*> myMCmap;
00993   
00994     fillMCmap(&(*electronCollection),mcEle,myMCmap);
00995     
00996     fillEleInfo(mcEle,myMCmap);
00997   */
00998   
00999   if(electronCollection->size() < 2) 
01000     return kContinue;
01001   
01002   if ( !hits && !ehits){
01003     std::cout << "!hits" << std::endl;   
01004     return kContinue;
01005   }
01006   
01007   if (hits->size() == 0 && ehits->size() == 0){
01008     std::cout << "hits->size() == 0" << std::endl;   
01009     return kContinue;
01010   }  
01011   
01012   if (!electronCollection){
01013     std::cout << "!electronCollection" << std::endl;
01014     return kContinue;
01015   }
01016   
01017   if (electronCollection->size() == 0){
01018     std::cout << "electronCollection->size() == 0" << std::endl;
01019     return kContinue;
01020   }
01021 
01022 
01023   
01027   
01028   read_events++;
01029   
01030   //  std::cout << "read_events = " << read_events << std::endl;
01031   
01033   
01034 #ifdef DEBUG
01035   std::cout <<" Starting with myZeePlots_->fillEleInfo(electronCollection); " << std::endl; 
01036 #endif
01037 
01038   if (loopFlag_ == 0)
01039     myZeePlots_->fillEleInfo(electronCollection);
01040   
01041 #ifdef DEBUG
01042   std::cout <<" Done with myZeePlots_->fillEleInfo(electronCollection); " << std::endl; 
01043 #endif
01044 
01045   //FILL an electron vector - end
01046   //###################################Electron-SC association: begin#####################################################
01047   //Filling new ElectronCollection with new SC ref and calibElectron container
01048   std::vector<calib::CalibElectron> calibElectrons;
01049   //std::map< const calib::CalibElectron* , const reco::SuperCluster* > eleScMap;
01050   
01051   
01052 
01053   //#####################################Electron-SC association map: end#####################################################  
01054   for(unsigned int e_it = 0 ; e_it != electronCollection->size() ; e_it++)
01055     {
01056       calibElectrons.push_back(calib::CalibElectron(&((*electronCollection)[e_it]),hits,ehits));
01057 #ifdef DEBUG
01058       std::cout << calibElectrons.back().getRecoElectron()->superCluster()->energy() << " " << calibElectrons.back().getRecoElectron()->energy() << std::endl;
01059 #endif
01060       //      h1_recoEleEnergy_->Fill(calibElectrons.back().getRecoElectron()->superCluster()->energy());
01061     }
01062   //  if (iLoop == 0)
01063   //fillCalibElectrons(calibElectrons);
01064 
01065 #ifdef DEBUG
01066   std::cout << "Filled histos" << std::endl;
01067 #endif  
01068   
01069   //COMBINATORY FOR Z MASS - begin                                                                                                                           
01070   std::vector<std::pair<calib::CalibElectron*,calib::CalibElectron*> > zeeCandidates;
01071   int  myBestZ=-1;
01072   
01073   mass = -1.;
01074   double DeltaMinvMin(5000.);
01075   
01076   if (calibElectrons.size() < 2)
01077     return kContinue;
01078 
01079   for(unsigned int e_it = 0 ; e_it != calibElectrons.size() - 1 ; e_it++){
01080     for(unsigned int p_it = e_it + 1 ; p_it != calibElectrons.size() ; p_it++)
01081       {
01082 #ifdef DEBUG
01083         std::cout << e_it << " " << calibElectrons[e_it].getRecoElectron()->charge() << " " << p_it << " " << calibElectrons[p_it].getRecoElectron()->charge() << std::endl;
01084 #endif          
01085         if (calibElectrons[e_it].getRecoElectron()->charge() * calibElectrons[p_it].getRecoElectron()->charge() != -1)
01086           continue;
01087         
01088         mass =  ZeeKinematicTools::calculateZMass_withTK(std::pair<calib::CalibElectron*,calib::CalibElectron*>(&(calibElectrons[e_it]),&(calibElectrons[p_it])));
01089         
01090         if (mass<0)
01091           continue;
01092         
01093 #ifdef DEBUG
01094         std::cout << "#######################mass "<<mass << std::endl;
01095 #endif
01096         
01097         zeeCandidates.push_back(std::pair<calib::CalibElectron*,calib::CalibElectron*>(&(calibElectrons[e_it]),&(calibElectrons[p_it])));
01098         double DeltaMinv = fabs(mass - MZ); 
01099         
01100         if( DeltaMinv < DeltaMinvMin)
01101           {
01102             DeltaMinvMin = DeltaMinv;
01103             myBestZ=zeeCandidates.size()-1;
01104           }
01105       }
01106   }      
01107   
01108   //  h_DeltaZMassDistr_[loopFlag_]->Fill( (mass-MZ) / MZ );
01109 
01110   //  zeeCa->Fill(zeeCandidates);
01111   //
01112   h1_ZCandMult_->Fill(zeeCandidates.size());
01113   
01114   if(zeeCandidates.size()==0 || myBestZ==-1 )
01115     return kContinue;
01116       
01117   if (loopFlag_ == 0)
01118     myZeePlots_->fillZInfo( zeeCandidates[myBestZ] );
01119   
01120 #ifdef DEBUG  
01121   std::cout << "Found ZCandidates " << myBestZ << std::endl;
01122 #endif  
01123 
01124   //  h1_zMassResol_ ->Fill(mass-myGenZMass);
01125 
01127   
01128   
01129   h1_eleClasses_->Fill(zeeCandidates[myBestZ].first->getRecoElectron()->classification());
01130   h1_eleClasses_->Fill(zeeCandidates[myBestZ].second->getRecoElectron()->classification());
01131   
01132   int class1 = zeeCandidates[myBestZ].first->getRecoElectron()->classification();
01133   int class2 = zeeCandidates[myBestZ].second->getRecoElectron()->classification();
01134 
01135   std::cout << "BEFORE "<<std::endl;
01136 
01137   //  myZeePlots_->fillEleClassesPlots( zeeCandidates[myBestZ].first );
01138   //myZeePlots_->fillEleClassesPlots( zeeCandidates[myBestZ].second );
01139   
01140   std::cout << "AFTER "<<std::endl;
01141 
01143 
01144   if(class1 < 100)
01145     //    h1_Elec_->Fill(1);
01146     TOTAL_ELECTRONS_IN_BARREL++;
01147   if(class1 >= 100)
01148     TOTAL_ELECTRONS_IN_ENDCAP++;
01149 
01150   if(class2 < 100)
01151     TOTAL_ELECTRONS_IN_BARREL++;
01152   if(class2 >= 100)
01153     TOTAL_ELECTRONS_IN_ENDCAP++;
01154 
01155 
01156   if( class1==0)
01157     GOLDEN_ELECTRONS_IN_BARREL++;
01158   if( class1==100)
01159     GOLDEN_ELECTRONS_IN_ENDCAP++;
01160   if( class1==10 || class1 ==20)
01161     SILVER_ELECTRONS_IN_BARREL++;
01162   if( class1==110 || class1 ==120)
01163     SILVER_ELECTRONS_IN_ENDCAP++;
01164   if( class1>=30 && class1 <=34)
01165     SHOWER_ELECTRONS_IN_BARREL++;
01166   if( class1>=130 && class1 <=134)
01167     SHOWER_ELECTRONS_IN_ENDCAP++;
01168   if( class1==40)
01169     CRACK_ELECTRONS_IN_BARREL++;
01170   if( class1==140)
01171     CRACK_ELECTRONS_IN_ENDCAP++;
01172 
01173   if( class2==0)
01174     GOLDEN_ELECTRONS_IN_BARREL++;
01175   if( class2==100)
01176     GOLDEN_ELECTRONS_IN_ENDCAP++;
01177   if( class2==10 || class2 ==20)
01178     SILVER_ELECTRONS_IN_BARREL++;
01179   if( class2==110 || class2 ==120)
01180     SILVER_ELECTRONS_IN_ENDCAP++;
01181   if( class2>=30 && class2 <=34)
01182     SHOWER_ELECTRONS_IN_BARREL++;
01183   if( class2>=130 && class2 <=134)
01184     SHOWER_ELECTRONS_IN_ENDCAP++;
01185   if( class2==40)
01186     CRACK_ELECTRONS_IN_BARREL++;
01187   if( class2==140)
01188     CRACK_ELECTRONS_IN_ENDCAP++;
01189   
01191 
01193 
01194   
01195   DetId firstElehottestDetId = getHottestDetId( zeeCandidates[myBestZ].first->getRecoElectron()->superCluster()->seed()->hitsAndFractions() , hits, ehits ).first;
01196   DetId secondElehottestDetId = getHottestDetId( zeeCandidates[myBestZ].second->getRecoElectron()->superCluster()->seed()->hitsAndFractions()  , hits, ehits ).first;
01197   
01198   bool firstElectronIsOnModuleBorder(false);
01199   bool secondElectronIsOnModuleBorder(false);
01200   
01201   h1_eventsBeforeBorderSelection_->Fill(1);
01202 
01203   if(class1<100){
01204 
01205     if( firstElehottestDetId.subdetId() == EcalBarrel)
01206       firstElectronIsOnModuleBorder = xtalIsOnModuleBorder( firstElehottestDetId  );
01207     
01208     BARREL_ELECTRONS_BEFORE_BORDER_CUT++;
01209     
01210     if( firstElehottestDetId.subdetId() == EcalBarrel &&  !firstElectronIsOnModuleBorder )
01211       BARREL_ELECTRONS_AFTER_BORDER_CUT++;
01212     
01213   }
01214   
01215   if(class2<100){
01216     
01217     if( secondElehottestDetId.subdetId() == EcalBarrel)
01218       secondElectronIsOnModuleBorder = xtalIsOnModuleBorder( secondElehottestDetId  );
01219     
01220     BARREL_ELECTRONS_BEFORE_BORDER_CUT++;
01221     
01222     if( secondElehottestDetId.subdetId() == EcalBarrel &&  !secondElectronIsOnModuleBorder )
01223       BARREL_ELECTRONS_AFTER_BORDER_CUT++;
01224     
01225   }
01226   
01227   
01228   if(class1<100){
01229     if ( firstElehottestDetId.subdetId() == EcalBarrel &&  firstElectronIsOnModuleBorder ){
01230       h1_borderElectronClassification_ -> Fill( zeeCandidates[myBestZ].first->getRecoElectron()->classification() );
01231       return kContinue;
01232     }  
01233   }
01234   
01235   if(class2<100){
01236     if ( secondElehottestDetId.subdetId() == EcalBarrel &&  secondElectronIsOnModuleBorder ){ 
01237       h1_borderElectronClassification_ -> Fill( zeeCandidates[myBestZ].second->getRecoElectron()->classification() );
01238       return kContinue;
01239     }
01240   }
01241   
01242   h1_eventsAfterBorderSelection_->Fill(1);
01244   
01245   
01246   if(class1<100 && class2<100){
01247     BBZN++;
01248     if(class1==0 && class2==0)BBZN_gg++;
01249     if(class1<21 && class2<21)BBZN_tt++;
01250     if(class1<21 || class2<21)BBZN_t0++;
01251     
01252   }
01253 
01254   if(class1>=100 && class2>=100){
01255     EEZN++;
01256     if(class1==100 && class2==100)EEZN_gg++;
01257     if(class1<121 && class2<121)EEZN_tt++;
01258     if(class1<121 || class2<121)EEZN_t0++;
01259 
01260   }
01261 
01262   if( (class1<100 && class2>=100) || (class2<100 && class1>=100)){
01263     EBZN++;
01264     if( (class1==0 && class2==100)||(class2==0 && class1==100) )EBZN_gg++;
01265     if( ( class1<21 && class2<121) ||(class2<21 && class1<121) )EBZN_tt++;
01266     if(   class2<21 || class1<21 ||  class2<121 || class1<121 )EBZN_t0++;
01267   }
01268 
01269 
01271   
01272   if(myBestZ == -1)
01273     return kContinue;
01274 
01275 
01276   bool invMassBool = ( (mass > minInvMassCut_) && (mass < maxInvMassCut_) );
01277 
01278   bool selectionBool=false;  
01279   //0 = all electrons (but no crack)
01280   
01282 
01283   float theta1 = 2. * atan( exp(- zeeCandidates[myBestZ].first->getRecoElectron()->superCluster()->eta()) );
01284   bool ET_1 = (  (zeeCandidates[myBestZ].first->getRecoElectron()->superCluster()->energy() * sin( theta1) ) > 20.);
01285 
01286   float theta2 = 2. * atan( exp(- zeeCandidates[myBestZ].second->getRecoElectron()->superCluster()->eta()) );
01287   bool ET_2 = (  (zeeCandidates[myBestZ].second->getRecoElectron()->superCluster()->energy() * sin( theta2) ) > 20.);
01288 
01289 
01290   bool HoE_1 = (zeeCandidates[myBestZ].first->getRecoElectron()->hadronicOverEm() < 0.115);
01291   bool HoE_2 = (zeeCandidates[myBestZ].second->getRecoElectron()->hadronicOverEm() < 0.115);
01292 
01293   bool DeltaPhiIn_1 = ( zeeCandidates[myBestZ].first->getRecoElectron()->deltaPhiSuperClusterTrackAtVtx() < 0.090);
01294   bool DeltaPhiIn_2 = ( zeeCandidates[myBestZ].second->getRecoElectron()->deltaPhiSuperClusterTrackAtVtx() < 0.090);
01295 
01296   bool DeltaEtaIn_1 = ( zeeCandidates[myBestZ].first->getRecoElectron()->deltaEtaSuperClusterTrackAtVtx() < 0.0090);
01297   bool DeltaEtaIn_2 = ( zeeCandidates[myBestZ].second->getRecoElectron()->deltaEtaSuperClusterTrackAtVtx() < 0.0090);
01298    
01299   h1_eventsBeforeEWKSelection_->Fill(1);
01300 
01301   if(! (invMassBool &&
01302         ET_1 && ET_2 &&
01303         HoE_1 && HoE_2 &&
01304         DeltaPhiIn_1 && DeltaPhiIn_2 &&
01305         DeltaEtaIn_1 && DeltaEtaIn_2
01306         ) )
01307     return kContinue;
01309 
01310   h1_eventsAfterEWKSelection_->Fill(1);
01311 
01313   
01314 
01315 
01316   if(electronSelection_==0)selectionBool=( myBestZ != -1 && 
01317                                            zeeCandidates[myBestZ].first->getRecoElectron()->classification()!= 40 && 
01318                                            zeeCandidates[myBestZ].first->getRecoElectron()->classification()!= 40 && 
01319                                            zeeCandidates[myBestZ].second->getRecoElectron()->classification()!= 40 && 
01320                                            zeeCandidates[myBestZ].second->getRecoElectron()->classification()!= 140);
01321   
01322   //1 = all electrons are Golden, BB or Narrow
01323   
01324   if(electronSelection_==1)selectionBool=( myBestZ != -1 &&
01325                                            (zeeCandidates[myBestZ].first->getRecoElectron()->classification() ==0 || 
01326                                             zeeCandidates[myBestZ].first->getRecoElectron()->classification() ==10 || 
01327                                             zeeCandidates[myBestZ].first->getRecoElectron()->classification() ==20 ||
01328                                             zeeCandidates[myBestZ].first->getRecoElectron()->classification() ==100 ||
01329                                             zeeCandidates[myBestZ].first->getRecoElectron()->classification() ==110 ||
01330                                             zeeCandidates[myBestZ].first->getRecoElectron()->classification() ==120
01331                                             ) &&
01332                                            (zeeCandidates[myBestZ].second->getRecoElectron()->classification() == 0 || 
01333                                             zeeCandidates[myBestZ].second->getRecoElectron()->classification() == 10 ||
01334                                             zeeCandidates[myBestZ].second->getRecoElectron()->classification() == 20 ||
01335                                             zeeCandidates[myBestZ].second->getRecoElectron()->classification() == 100 ||
01336                                             zeeCandidates[myBestZ].second->getRecoElectron()->classification() == 110 ||
01337                                             zeeCandidates[myBestZ].second->getRecoElectron()->classification() == 120
01338                                             )
01339                                            );
01340   
01341   //2 = all electrons are Golden
01342   if(electronSelection_==2)selectionBool=( myBestZ != -1 &&
01343                                            (zeeCandidates[myBestZ].first->getRecoElectron()->classification() == 0 ||
01344                                             zeeCandidates[myBestZ].first->getRecoElectron()->classification() == 100
01345                                             ) &&
01346                                            (zeeCandidates[myBestZ].second->getRecoElectron()->classification() == 0 ||
01347                                             zeeCandidates[myBestZ].second->getRecoElectron()->classification() == 100
01348                                             ) 
01349                                            );
01350   //3 = all electrons are showering
01351   if(electronSelection_==3)selectionBool=( myBestZ != -1 &&
01352                                           (
01353                                            (zeeCandidates[myBestZ].first->getRecoElectron()->classification() >=30  &&
01354                                            zeeCandidates[myBestZ].first->getRecoElectron()->classification() <=34)  
01355                                            ||
01356                                            ((zeeCandidates[myBestZ].first->getRecoElectron()->classification() >=130  &&
01357                                              zeeCandidates[myBestZ].first->getRecoElectron()->classification() <=134))
01358                                            )
01359                                            &&
01360                                            ( (zeeCandidates[myBestZ].second->getRecoElectron()->classification() >=30  &&
01361                                               zeeCandidates[myBestZ].second->getRecoElectron()->classification() <=34)
01362                                              ||
01363                                              ((zeeCandidates[myBestZ].second->getRecoElectron()->classification() >=130  &&
01364                                                zeeCandidates[myBestZ].second->getRecoElectron()->classification() <=134))
01365                                              )
01366                                            
01367                                            );
01368   
01369   //4 = all Barrel electrons are Golden, BB or Narrow; take all Endcap electrons
01370                                                                                                                              
01371   if(electronSelection_==4)selectionBool=( myBestZ != -1 && 
01372                                            (
01373 
01374                                            (
01375                                             (zeeCandidates[myBestZ].first->getRecoElectron()->classification() ==0 ||
01376                                               zeeCandidates[myBestZ].first->getRecoElectron()->classification() ==10 ||
01377                                               zeeCandidates[myBestZ].first->getRecoElectron()->classification() ==20 
01378                                               ) && zeeCandidates[myBestZ].second->getRecoElectron()->classification()>=100 
01379                                             && zeeCandidates[myBestZ].second->getRecoElectron()->classification()!=140
01380                                             )
01381 
01382                                            ||
01383                                            
01384                                            (
01385                                             (zeeCandidates[myBestZ].second->getRecoElectron()->classification() ==0 ||
01386                                              zeeCandidates[myBestZ].second->getRecoElectron()->classification() ==10 ||
01387                                              zeeCandidates[myBestZ].second->getRecoElectron()->classification() ==20
01388                                              ) && zeeCandidates[myBestZ].first->getRecoElectron()->classification()>=100
01389                                             && zeeCandidates[myBestZ].first->getRecoElectron()->classification()!=140
01390                                             )
01391 
01392 
01393                                            )
01394                                            ); 
01395   
01396   //5 = all Endcap electrons (but no crack)
01397   
01398   if(electronSelection_==5)selectionBool=( myBestZ != -1 && 
01399                                            zeeCandidates[myBestZ].first->getRecoElectron()->classification()>=100 && 
01400                                            zeeCandidates[myBestZ].second->getRecoElectron()->classification()>= 100 && 
01401                                            zeeCandidates[myBestZ].first->getRecoElectron()->classification()!= 140 &&
01402                                            zeeCandidates[myBestZ].second->getRecoElectron()->classification()!= 140);
01403 
01404   //6 = all Barrel electrons (but no crack)
01405   
01406   if(electronSelection_==6)selectionBool=( myBestZ != -1 && 
01407                                            zeeCandidates[myBestZ].first->getRecoElectron()->classification()<100 && 
01408                                            zeeCandidates[myBestZ].second->getRecoElectron()->classification()< 100 && 
01409                                            zeeCandidates[myBestZ].first->getRecoElectron()->classification()!= 40 &&
01410                                            zeeCandidates[myBestZ].second->getRecoElectron()->classification()!= 40);
01411 
01412   //7 = this eliminates the events which have 1 ele in the Barrel and 1 in the Endcap
01413   
01414   if(electronSelection_==7)selectionBool=( myBestZ != -1 && 
01415                                            !(zeeCandidates[myBestZ].first->getRecoElectron()->classification()<100 && 
01416                                            zeeCandidates[myBestZ].second->getRecoElectron()->classification()>=100) &&
01417                                            !(zeeCandidates[myBestZ].first->getRecoElectron()->classification()>=100 &&
01418                                              zeeCandidates[myBestZ].second->getRecoElectron()->classification()<100) );
01419 
01420 
01421       float ele1EnergyCorrection(1.);
01422       float ele2EnergyCorrection(1.);
01423 
01424         if(invMassBool && selectionBool && wantEtaCorrection_){
01425           
01426           ele1EnergyCorrection=getEtaCorrection(zeeCandidates[myBestZ].first->getRecoElectron());
01427           ele2EnergyCorrection=getEtaCorrection(zeeCandidates[myBestZ].second->getRecoElectron());
01428 
01429         }
01430 
01431   if (invMassBool && selectionBool)  
01432     {
01433 
01434       h1_electronCosTheta_SC_ -> Fill( ZeeKinematicTools::cosThetaElectrons_SC(zeeCandidates[myBestZ],ele1EnergyCorrection,ele2EnergyCorrection)  );
01435       h1_electronCosTheta_TK_ -> Fill( ZeeKinematicTools::cosThetaElectrons_TK(zeeCandidates[myBestZ],ele1EnergyCorrection,ele2EnergyCorrection)  );
01436       h1_electronCosTheta_SC_TK_ -> Fill( ZeeKinematicTools::cosThetaElectrons_SC(zeeCandidates[myBestZ],ele1EnergyCorrection,ele2EnergyCorrection)/ZeeKinematicTools::cosThetaElectrons_TK(zeeCandidates[myBestZ],ele1EnergyCorrection,ele2EnergyCorrection) - 1. );
01437 
01438         if (!mcProducer_.empty())
01439           {
01440             h1_zMassResol_ ->Fill(mass-myGenZMass);
01441             
01442             //reco-mc association map - begin
01443             
01444             std::map<HepMC::GenParticle*,const reco::GsfElectron*> myMCmap;
01445             
01446             std::vector<const reco::GsfElectron*> dauElectronCollection;
01447             
01448             dauElectronCollection.push_back(zeeCandidates[myBestZ].first->getRecoElectron()  );
01449             dauElectronCollection.push_back(zeeCandidates[myBestZ].second->getRecoElectron()  );
01450             
01451             fillMCmap(&dauElectronCollection,mcEle,myMCmap);
01452             fillEleInfo(mcEle,myMCmap);
01453             //h_DiffZMassDistr_[loopFlag_]->Fill( (mass-myGenZMass) );
01454           }
01455 
01456       //PUT f(eta) IN OUR Zee ALGORITHM
01457       theAlgorithm_->addEvent(zeeCandidates[myBestZ].first, zeeCandidates[myBestZ].second,MZ*sqrt(ele1EnergyCorrection*ele2EnergyCorrection) );
01458      
01459       h1_reco_ZMass_->Fill(ZeeKinematicTools::calculateZMass_withTK(zeeCandidates[myBestZ]));
01460 
01461       h1_reco_ZMassCorr_->Fill(ZeeKinematicTools::calculateZMassWithCorrectedElectrons_withTK(zeeCandidates[myBestZ],ele1EnergyCorrection,ele2EnergyCorrection));
01462 
01463       if(zeeCandidates[myBestZ].first->getRecoElectron()->classification()<100 && zeeCandidates[myBestZ].second->getRecoElectron()->classification()<100 )
01464         h1_reco_ZMassCorrBB_->Fill(ZeeKinematicTools::calculateZMassWithCorrectedElectrons_withTK(zeeCandidates[myBestZ],ele1EnergyCorrection,ele2EnergyCorrection));
01465 
01466 
01467       if(zeeCandidates[myBestZ].first->getRecoElectron()->classification()>=100 && zeeCandidates[myBestZ].second->getRecoElectron()->classification()>=100 )
01468         h1_reco_ZMassCorrEE_->Fill(ZeeKinematicTools::calculateZMassWithCorrectedElectrons_withTK(zeeCandidates[myBestZ],ele1EnergyCorrection,ele2EnergyCorrection));
01469 
01470 
01471       mass4tree = ZeeKinematicTools::calculateZMassWithCorrectedElectrons_withTK(zeeCandidates[myBestZ],ele1EnergyCorrection,ele2EnergyCorrection);
01472 
01473       massDiff4tree = ZeeKinematicTools::calculateZMassWithCorrectedElectrons_withTK(zeeCandidates[myBestZ],ele1EnergyCorrection,ele2EnergyCorrection) - myGenZMass;
01474 
01475       //      h_ZMassDistr_[loopFlag_]->Fill(ZeeKinematicTools::calculateZMassWithCorrectedElectrons_withTK(zeeCandidates[myBestZ],ele1EnergyCorrection,ele2EnergyCorrection));
01476 
01477       myTree->Fill();
01478     
01479     }
01480 
01481 
01482 
01483 #ifdef DEBUG
01484   std::cout << "Added event to algorithm" << std::endl;  
01485 #endif
01486 
01487   return kContinue;
01488     }
01489 //end of ZeeCalibration::duringLoop
01490 
01491 
01492 // Called at beginning of loop
01493 void ZeeCalibration::startingNewLoop ( unsigned int iLoop )
01494 {
01495 
01496 std::cout<< "[ZeeCalibration] Starting loop number " << iLoop<<std::endl;
01497  
01498  theAlgorithm_->resetIteration();
01499  
01500  resetVariables();
01501  
01502  resetHistograms();
01503 
01504 #ifdef DEBUG
01505  std::cout<< "[ZeeCalibration] exiting from startingNewLoop" << std::endl;
01506 #endif
01507 
01508 }
01509 
01510 
01511 
01512 // Called at end of loop
01513 edm::EDLooper::Status
01514 ZeeCalibration::endOfLoop(const edm::EventSetup& iSetup, unsigned int iLoop)
01515 {
01516 
01517 
01518 
01519   double par[3];
01520   double errpar[3];
01521   double zChi2;
01522   int zIters;
01523 
01524   ZIterativeAlgorithmWithFit::gausfit(h1_reco_ZMass_,par,errpar,2.,2., &zChi2, &zIters );
01525 
01526   h2_zMassVsLoop_ -> Fill(loopFlag_,  par[1] );
01527 
01528   h2_zMassDiffVsLoop_ -> Fill(loopFlag_,  (par[1]-MZ)/MZ );
01529 
01530   h2_zWidthVsLoop_ -> Fill(loopFlag_, par[2] );
01531  
01532 
01534 
01535   std::cout<< "[ZeeCalibration] Ending loop " << iLoop<<std::endl;
01536   //RUN the algorithm
01537   theAlgorithm_->iterate();
01538 
01539   const std::vector<float>& optimizedCoefficients = theAlgorithm_->getOptimizedCoefficients();
01540   const std::vector<float>& optimizedCoefficientsError = theAlgorithm_->getOptimizedCoefficientsError();
01541   //const std::vector<float>& weightSum = theAlgorithm_->getWeightSum();
01542   const std::vector<float>& optimizedChi2 = theAlgorithm_->getOptimizedChiSquare();
01543   const std::vector<int>& optimizedIterations = theAlgorithm_->getOptimizedIterations();
01544 
01545 
01546   //#ifdef DEBUG
01547   std::cout<< "Optimized coefficients " << optimizedCoefficients.size() <<std::endl;
01548   //#endif
01549 
01550   //  h2_coeffVsLoop_->Fill(loopFlag_, optimizedCoefficients[75]); //show the evolution of just 1 ring coefficient (well chosen...)
01551 
01553   for (unsigned int ieta=0;ieta<optimizedCoefficients.size();ieta++)
01554     {
01555       NewCalibCoeff[ieta] = calibCoeff[ieta] * optimizedCoefficients[ieta];
01556 
01557       h2_chi2_[loopFlag_]->Fill( ringNumberCorrector( ieta ), optimizedChi2[ieta] );
01558       h2_iterations_[loopFlag_]->Fill( ringNumberCorrector( ieta ), optimizedIterations[ieta] );
01559  
01560     }
01562   
01563   
01564   coefficientDistanceAtIteration[loopFlag_]= computeCoefficientDistanceAtIteration(calibCoeff, NewCalibCoeff, optimizedCoefficients.size() );
01565 
01566   std::cout<<"Iteration # : "<< loopFlag_ << " CoefficientDistanceAtIteration "<< coefficientDistanceAtIteration[loopFlag_] <<std::endl;
01567   std::cout<<"size "<<optimizedCoefficients.size()<<std::endl;
01568 
01569   for (unsigned int ieta=0;ieta<optimizedCoefficients.size();ieta++)
01570     {
01571       calibCoeff[ieta] *= optimizedCoefficients[ieta];
01572       calibCoeffError[ieta] = calibCoeff[ieta] * sqrt ( pow( optimizedCoefficientsError[ieta]/optimizedCoefficients[ieta], 2 ) + pow( calibCoeffError[ieta]/calibCoeff[ieta] , 2 )  );
01573       //calibCoeffError[ieta] = optimizedCoefficientsError[ieta];
01574 
01575 
01576 #ifdef DEBUG
01577       std::cout<< ieta << " " << optimizedCoefficients[ieta] <<std::endl;  
01578 #endif
01579 
01580       std::vector<DetId> ringIds;
01581 
01582       if(calibMode_ == "RING")
01583         ringIds = EcalRingCalibrationTools::getDetIdsInRing(ieta);
01584 
01585       if(calibMode_ == "MODULE")
01586         ringIds = EcalRingCalibrationTools::getDetIdsInModule(ieta);
01587 
01588       if(calibMode_ == "ABS_SCALE" || calibMode_ == "ETA_ET_MODE" )
01589         ringIds = EcalRingCalibrationTools::getDetIdsInECAL();
01590 
01591       
01592       for (unsigned int iid=0; iid<ringIds.size();++iid){
01593         
01594         if(ringIds[iid].subdetId() == EcalBarrel){
01595           EBDetId myEBDetId(ringIds[iid]);  
01596           h2_xtalRecalibCoeffBarrel_[loopFlag_]->SetBinContent( myEBDetId.ieta() + 86, myEBDetId.iphi(), 100 * (calibCoeff[ieta]*initCalibCoeff[ieta] - 1.) );//fill TH2 with recalibCoeff
01597 
01598         }
01599 
01600         if(ringIds[iid].subdetId() == EcalEndcap){
01601           EEDetId myEEDetId(ringIds[iid]);
01602           if(myEEDetId.zside() < 0)
01603             h2_xtalRecalibCoeffEndcapMinus_[loopFlag_]->SetBinContent( myEEDetId.ix(), myEEDetId.iy(), 100 * (calibCoeff[ieta]*initCalibCoeff[ieta] - 1.) );//fill TH2 with recalibCoeff
01604 
01605           if(myEEDetId.zside() > 0)
01606             h2_xtalRecalibCoeffEndcapPlus_[loopFlag_]->SetBinContent( myEEDetId.ix(), myEEDetId.iy(), 100 * (calibCoeff[ieta]*initCalibCoeff[ieta] - 1.) );//fill TH2 with recalibCoeff
01607           
01608         }
01609         
01610         
01611         ical->setValue( ringIds[iid], *(ical->getMap().find(ringIds[iid])  ) * optimizedCoefficients[ieta] );
01612       }    
01613 
01614     }
01615   
01616   
01618 
01619   for( int k = 0; k<theAlgorithm_->getNumberOfChannels(); k++ )
01620     {
01621       bool isNearCrack = ( abs( ringNumberCorrector(k) ) == 1 || abs( ringNumberCorrector(k) ) == 25 ||
01622                            abs( ringNumberCorrector(k) ) == 26 || abs( ringNumberCorrector(k) ) == 45 ||
01623                            abs( ringNumberCorrector(k) ) == 46 || abs( ringNumberCorrector(k) ) == 65 ||
01624                            abs( ringNumberCorrector(k) ) == 66 || abs( ringNumberCorrector(k) ) == 85 ||
01625                            abs( ringNumberCorrector(k) ) == 86 || abs( ringNumberCorrector(k) ) == 124 );
01626 
01627       if(!isNearCrack){
01628 
01629         //      h2_miscalRecalParz_[iLoop]->Fill( initCalibCoeff[k], 1./calibCoeff[k] );
01630         h1_mcParz_[iLoop]->Fill( initCalibCoeff[k]*calibCoeff[k] -1. );
01631         
01632         if(k<170){
01633           //h2_miscalRecalEBParz_[iLoop]->Fill( initCalibCoeff[k], 1./calibCoeff[k] );
01634           h1_mcEBParz_[iLoop]->Fill( initCalibCoeff[k]*calibCoeff[k] -1. );
01635           
01636         }
01637         
01638         if(k>=170){
01639           //h2_miscalRecalEEParz_[iLoop]->Fill( initCalibCoeff[k], 1./calibCoeff[k] );
01640           h1_mcEEParz_[iLoop]->Fill( initCalibCoeff[k]*calibCoeff[k] -1. );
01641         }
01642      
01643       }
01644     }
01645   
01646   
01648   double parResidual[3];
01649   double errparResidual[3];
01650   double zResChi2;
01651   int zResIters;
01652   
01653   ZIterativeAlgorithmWithFit::gausfit(h1_mcParz_[iLoop],parResidual,errparResidual,3.,3., &zResChi2, &zResIters);
01654   //h1_mcParz_[iLoop]->Fit("gaus");
01655   
01656   h2_residualSigma_ -> Fill(loopFlag_ + 1,  parResidual[2]);
01657   loopArray[loopFlag_] = loopFlag_ + 1;
01658   sigmaArray[loopFlag_] = parResidual[2];
01659   sigmaErrorArray[loopFlag_] = errparResidual[2];
01660 
01661   std::cout<<"Fit on residuals, sigma is "<<parResidual[2]<<" +/- "<<errparResidual[2]<<std::endl;
01662 
01664   outputFile_->cd();
01665 
01666 
01667   //  h2_miscalRecalParz_[iLoop]->Write();
01668   h1_mcParz_[iLoop]->Write();
01669 
01670   //h2_miscalRecalEBParz_[iLoop]->Write();
01671   h1_mcEBParz_[iLoop]->Write();
01672 
01673   //h2_miscalRecalEEParz_[iLoop]->Write();
01674   h1_mcEEParz_[iLoop]->Write();
01675   h2_xtalRecalibCoeffBarrel_[loopFlag_] -> Write();
01676   h2_xtalRecalibCoeffEndcapPlus_[loopFlag_] -> Write();
01677   h2_xtalRecalibCoeffEndcapMinus_[loopFlag_] -> Write();
01678 
01680   
01681   loopFlag_++;
01682   
01683 #ifdef DEBUG  
01684   std::cout<<" loopFlag_ is "<<loopFlag_<<std::endl;
01685 #endif  
01686   
01687   if ( iLoop == theMaxLoops-1 || iLoop >= theMaxLoops ) return kStop;
01688   else return kContinue;
01689 }
01690 
01691 void ZeeCalibration::bookHistograms()
01692 {
01693 
01694   h1_eventsBeforeEWKSelection_=  new TH1F("h1_eventsBeforeEWKSelection", "h1_eventsBeforeEWKSelection", 5,0,5); 
01695   h1_eventsAfterEWKSelection_ =  new TH1F("h1_eventsAfterEWKSelection", "h1_eventsAfterEWKSelection", 5,0,5);
01696 
01697   h1_eventsBeforeBorderSelection_=  new TH1F("h1_eventsBeforeBorderSelection", "h1_eventsBeforeBorderSelection", 5,0,5); 
01698   h1_eventsAfterBorderSelection_ =  new TH1F("h1_eventsAfterBorderSelection", "h1_eventsAfterBorderSelection", 5,0,5);
01699 
01700   h1_seedOverSC_= new TH1F("h1_seedOverSC", "h1_seedOverSC", 400, 0., 2.);
01701 
01702   myZeePlots_ -> bookHLTHistograms();
01703   
01704   h1_borderElectronClassification_ = new TH1F("h1_borderElectronClassification", "h1_borderElectronClassification", 55, -5 , 50);
01705   h1_preshowerOverSC_= new TH1F("h1_preshowerOverSC", "h1_preshowerOverSC", 400, 0., 1.);
01706   
01707   h2_fEtaBarrelGood_ = new TH2F("fEtaBarrelGood","fEtaBarrelGood",800,-4.,4.,800,0.8,1.2);
01708   h2_fEtaBarrelGood_->SetXTitle("Eta");
01709   h2_fEtaBarrelGood_->SetYTitle("1/fEtaBarrelGood");
01710   
01711   h2_fEtaBarrelBad_ = new TH2F("fEtaBarrelBad","fEtaBarrelBad",800,-4.,4.,800,0.8,1.2);
01712   h2_fEtaBarrelBad_->SetXTitle("Eta");
01713   h2_fEtaBarrelBad_->SetYTitle("1/fEtaBarrelBad");
01714   
01715   h2_fEtaEndcapGood_ = new TH2F("fEtaEndcapGood","fEtaEndcapGood",800,-4.,4.,800,0.8,1.2);
01716   h2_fEtaEndcapGood_->SetXTitle("Eta");
01717   h2_fEtaEndcapGood_->SetYTitle("1/fEtaEndcapGood");
01718   
01719   h2_fEtaEndcapBad_ = new TH2F("fEtaEndcapBad","fEtaEndcapBad",800,-4.,4.,800,0.8,1.2);
01720   h2_fEtaEndcapBad_->SetXTitle("Eta");
01721   h2_fEtaEndcapBad_->SetYTitle("1/fEtaEndcapBad");
01722   
01723   for (int i=0;i<2;i++)
01724     {
01725       char histoName[50];
01726 
01727       sprintf(histoName,"h_eleEffEta_%d",i);
01728       h_eleEffEta_[i] = new TH1F(histoName,histoName, 150, 0., 2.7);
01729       h_eleEffEta_[i]->SetXTitle("|#eta|");
01730 
01731       sprintf(histoName,"h_eleEffPhi_%d",i);
01732       h_eleEffPhi_[i] = new TH1F(histoName,histoName, 400, -4., 4.);
01733       h_eleEffPhi_[i]->SetXTitle("Phi");
01734 
01735       sprintf(histoName,"h_eleEffPt_%d",i);
01736       h_eleEffPt_[i] = new TH1F(histoName,histoName, 200, 0., 200.);
01737       h_eleEffPt_[i]->SetXTitle("p_{T}(GeV/c)");
01738    }
01739   
01740   h2_xtalMiscalibCoeffBarrel_ = new TH2F("h2_xtalMiscalibCoeffBarrel","h2_xtalMiscalibCoeffBarrel", 171, -85, 85, 360, 0, 360);
01741   h2_xtalMiscalibCoeffEndcapMinus_ = new TH2F("h2_xtalMiscalibCoeffEndcapMinus", "h2_xtalMiscalibCoeffEndcapMinus", 100, 0,100, 100, 0, 100);
01742   h2_xtalMiscalibCoeffEndcapPlus_ = new TH2F("h2_xtalMiscalibCoeffEndcapPlus", "h2_xtalMiscalibCoeffEndcapPlus", 100, 0,100, 100, 0, 100);
01743 
01744   h2_xtalMiscalibCoeffBarrel_ ->SetXTitle("ieta");
01745   h2_xtalMiscalibCoeffBarrel_ ->SetYTitle("iphi");
01746 
01747   h2_xtalMiscalibCoeffEndcapMinus_->SetXTitle("ix");
01748   h2_xtalMiscalibCoeffEndcapMinus_->SetYTitle("iy");
01749 
01750   for (int i=0;i<25;i++)
01751     {
01752       
01753       char histoName[50];
01754       sprintf(histoName,"h_ESCEtrueVsEta_%d",i);
01755       
01756       h_ESCEtrueVsEta_[i] = new TH2F(histoName,histoName, 150, 0., 2.7, 300,0.,1.5);
01757       h_ESCEtrueVsEta_[i]->SetXTitle("|#eta|");
01758       h_ESCEtrueVsEta_[i]->SetYTitle("E_{SC,raw}/E_{MC}");
01759       
01760       sprintf(histoName,"h_ESCEtrue_%d",i);
01761 
01762       h_ESCEtrue_[i] = new TH1F(histoName,histoName, 300,0.,1.5);
01763 
01764       sprintf(histoName,"h2_chi2_%d",i);
01765       h2_chi2_[i] = new TH2F(histoName,histoName, 1000,-150,150, 1000, -1, 5);
01766 
01767       sprintf(histoName,"h2_iterations_%d",i);
01768       h2_iterations_[i] = new TH2F(histoName,histoName, 1000,-150,150, 1000, -1, 15);
01769 
01770       sprintf(histoName,"h_ESCcorrEtrueVsEta_%d",i);
01771       
01772       h_ESCcorrEtrueVsEta_[i] = new TH2F(histoName,histoName, 150, 0., 2.7, 300,0.,1.5);
01773       h_ESCcorrEtrueVsEta_[i]->SetXTitle("|#eta|");
01774       h_ESCcorrEtrueVsEta_[i]->SetYTitle("E_{SC,#eta-corr}/E_{MC}");
01775       
01776       sprintf(histoName,"h_ESCcorrEtrue_%d",i);
01777 
01778       h_ESCcorrEtrue_[i] = new TH1F(histoName,histoName, 300,0.,1.5);
01779 
01780       sprintf(histoName,"h2_xtalRecalibCoeffBarrel_%d",i);
01781       h2_xtalRecalibCoeffBarrel_[i] = new TH2F(histoName,histoName, 171, -85, 85, 360, 0, 360);
01782       
01783       h2_xtalRecalibCoeffBarrel_[i]->SetXTitle("ieta");
01784       h2_xtalRecalibCoeffBarrel_[i]->SetYTitle("iphi");
01785 
01786       sprintf(histoName,"h2_xtalRecalibCoeffEndcapMinus_%d",i);
01787       h2_xtalRecalibCoeffEndcapMinus_[i] = new TH2F(histoName,histoName, 100, 0,100, 100, 0, 100);
01788       h2_xtalRecalibCoeffEndcapMinus_[i]->SetXTitle("ix");
01789       h2_xtalRecalibCoeffEndcapMinus_[i]->SetYTitle("iy");
01790 
01791       sprintf(histoName,"h2_xtalRecalibCoeffEndcapPlus_%d",i);
01792       h2_xtalRecalibCoeffEndcapPlus_[i] = new TH2F(histoName,histoName, 100, 0,100, 100, 0, 100);
01793       h2_xtalRecalibCoeffEndcapPlus_[i]->SetXTitle("ix");
01794       h2_xtalRecalibCoeffEndcapPlus_[i]->SetYTitle("iy");
01795       
01796     }                         
01797                                                                      
01798   /*
01799   for (int i=0;i<15;i++)
01800     {
01801                                                                                                                              
01802       char histoName[50];
01803 
01804       sprintf(histoName,"h_DiffZMassDistr_%d",i);
01805       h_DiffZMassDistr_[i] = new TH1F(histoName,histoName, 400, -20., 20.);
01806       h_DiffZMassDistr_[i]->SetXTitle("M_{Z, reco} - M_{Z, MC}");
01807       h_DiffZMassDistr_[i]->SetYTitle("events");
01808 
01809       sprintf(histoName,"h_ZMassDistr_%d",i);
01810       h_ZMassDistr_[i] = new TH1F(histoName,histoName, 200, 0., 150.);
01811       h_ZMassDistr_[i]->SetXTitle("RecoZmass (GeV)");
01812       h_ZMassDistr_[i]->SetYTitle("events");
01813 
01814     }
01815   */
01816   
01817   h1_zMassResol_ = new TH1F("zMassResol", "zMassResol", 200, -50., 50.);
01818   h1_zMassResol_->SetXTitle("M_{Z, reco} - M_{Z, MC}");
01819   h1_zMassResol_->SetYTitle("events");
01820 
01821   h1_eleEtaResol_ = new TH1F("eleEtaResol", "eleEtaResol", 100, -0.01, 0.01);
01822   h1_eleEtaResol_->SetXTitle("#eta_{reco} - #eta_{MC}");
01823   h1_eleEtaResol_->SetYTitle("events");
01824 
01825   h1_electronCosTheta_TK_ = new TH1F("electronCosTheta_TK", "electronCosTheta_TK", 100, -1, 1);
01826   h1_electronCosTheta_TK_->SetXTitle("cos #theta_{12}");
01827   h1_electronCosTheta_TK_->SetYTitle("events");
01828 
01829   h1_electronCosTheta_SC_ = new TH1F("electronCosTheta_SC", "electronCosTheta_SC", 100, -1, 1);
01830   h1_electronCosTheta_SC_->SetXTitle("cos #theta_{12}");
01831   h1_electronCosTheta_SC_->SetYTitle("events");
01832 
01833   h1_electronCosTheta_SC_TK_ = new TH1F("electronCosTheta_SC_TK", "electronCosTheta_SC_TK", 200, -0.1, 0.1);
01834   h1_electronCosTheta_SC_TK_->SetXTitle("cos #theta_{12}^{SC}/ cos #theta_{12}^{TK} - 1");
01835   h1_electronCosTheta_SC_TK_->SetYTitle("events");
01836 
01837   h1_elePhiResol_ = new TH1F("elePhiResol", "elePhiResol", 100, -0.01, 0.01);
01838   h1_elePhiResol_->SetXTitle("#phi_{reco} - #phi_{MC}");
01839   h1_elePhiResol_->SetYTitle("events");
01840 
01841 
01842   h1_zEtaResol_ = new TH1F("zEtaResol", "zEtaResol", 200, -1., 1.);
01843   h1_zEtaResol_->SetXTitle("#eta_{Z, reco} - #eta_{Z, MC}");
01844   h1_zEtaResol_->SetYTitle("events");
01845 
01846 
01847   h1_zPhiResol_ = new TH1F("zPhiResol", "zPhiResol", 200, -1., 1.);
01848   h1_zPhiResol_->SetXTitle("#phi_{Z, reco} - #phi_{Z, MC}");
01849   h1_zPhiResol_->SetYTitle("events");
01850 
01851   h1_nEleReco_ = new TH1F("nEleReco","Number of reco electrons",10,-0.5,10.5);
01852   h1_nEleReco_->SetXTitle("nEleReco");
01853   h1_nEleReco_->SetYTitle("events");
01854   
01855   //  h1_occupancyVsEta_ = new TH1F("occupancyVsEta","occupancyVsEta",EcalRingCalibrationTools::N_RING_TOTAL,0,(float)EcalRingCalibrationTools::N_RING_TOTAL);
01856 
01857   h1_occupancyVsEta_ = new TH1F("occupancyVsEta","occupancyVsEta",249, -124, 124);
01858   h1_occupancyVsEta_->SetYTitle("Weighted electron statistics");
01859   h1_occupancyVsEta_->SetXTitle("Eta channel");
01860 
01861   h1_weightSumMeanBarrel_= new TH1F("weightSumMeanBarrel","weightSumMeanBarrel",10000, 0, 10000);
01862   h1_weightSumMeanEndcap_= new TH1F("weightSumMeanEndcap","weightSumMeanEndcap",10000, 0, 10000);
01863   
01864   h1_occupancy_ = new TH1F("occupancy","occupancy",1000,0,10000);
01865   h1_occupancy_->SetXTitle("Weighted electron statistics");
01866 
01867   h1_occupancyBarrel_ = new TH1F("occupancyBarrel","occupancyBarrel",1000,0,10000);
01868   h1_occupancyBarrel_->SetXTitle("Weighted electron statistics");
01869 
01870   h1_occupancyEndcap_ = new TH1F("occupancyEndcap","occupancyEndcap",1000,0,10000);
01871   h1_occupancyEndcap_->SetXTitle("Weighted electron statistics");
01872  
01873 
01874   h1_eleClasses_= new TH1F("eleClasses","eleClasses",301,-1,300);
01875   h1_eleClasses_->SetXTitle("classCode");
01876   h1_eleClasses_->SetYTitle("#");
01877   
01878 
01879 
01880  myZeePlots_ ->bookZMCHistograms();
01881 
01882  myZeePlots_ ->bookZHistograms();
01883  
01884  myZeePlots_ ->bookEleMCHistograms();   
01885  
01886  myZeePlots_ ->bookEleHistograms();             
01887  
01888 
01889   h1_ZCandMult_ =new TH1F("ZCandMult","Multiplicity of Z candidates in one event",10,-0.5,10.5);
01890   h1_ZCandMult_ ->SetXTitle("ZCandMult");
01891   
01892   h1_reco_ZMass_ = new TH1F("reco_ZMass","Inv. mass of 2 reco Electrons",200,0.,150.);
01893   h1_reco_ZMass_->SetXTitle("reco_ZMass (GeV)");
01894   h1_reco_ZMass_->SetYTitle("events");
01895 
01896   h1_reco_ZMassCorr_ = new TH1F("reco_ZMassCorr","Inv. mass of 2 corrected reco Electrons",200,0.,150.);
01897   h1_reco_ZMassCorr_->SetXTitle("reco_ZMass (GeV)");
01898   h1_reco_ZMassCorr_->SetYTitle("events");
01899 
01900   h1_reco_ZMassCorrBB_ = new TH1F("reco_ZMassCorrBB","Inv. mass of 2 corrected reco Electrons",200,0.,150.);
01901   h1_reco_ZMassCorrBB_->SetXTitle("reco_ZMass (GeV)");
01902   h1_reco_ZMassCorrBB_->SetYTitle("events");
01903 
01904   h1_reco_ZMassCorrEE_ = new TH1F("reco_ZMassCorrEE","Inv. mass of 2 corrected reco Electrons",200,0.,150.);
01905   h1_reco_ZMassCorrEE_->SetXTitle("reco_ZMass (GeV)");
01906   h1_reco_ZMassCorrEE_->SetYTitle("events");
01907 
01908   //  h2_coeffVsEta_= new TH2F("h2_calibCoeffVsEta","h2_calibCoeffVsEta",EcalRingCalibrationTools::N_RING_TOTAL,0, (double)EcalRingCalibrationTools::N_RING_TOTAL, 200, 0., 2.);
01909 
01910   h2_coeffVsEta_= new TH2F("h2_calibCoeffVsEta","h2_calibCoeffVsEta",249,-124,125, 200, 0., 2.);
01911   h2_coeffVsEta_->SetXTitle("Eta channel");
01912   h2_coeffVsEta_->SetYTitle("recalibCoeff");
01913 
01914   h2_coeffVsEtaGrouped_= new TH2F("h2_calibCoeffVsEtaGrouped","h2_calibCoeffVsEtaGrouped", 200, 0., 3., 200, 0.6, 1.4);
01915   h2_coeffVsEtaGrouped_->SetXTitle("|#eta|");
01916   h2_coeffVsEtaGrouped_->SetYTitle("recalibCoeff");
01917 
01918   h2_zMassVsLoop_= new TH2F("h2_zMassVsLoop","h2_zMassVsLoop",1000,0,40, 90, 80.,95.);
01919 
01920   h2_zMassDiffVsLoop_= new TH2F("h2_zMassDiffVsLoop","h2_zMassDiffVsLoop",1000,0,40, 100, -1., 1.);
01921   h2_zMassDiffVsLoop_->SetXTitle("Iteration");
01922   h2_zMassDiffVsLoop_->SetYTitle("M_{Z, reco peak} - M_{Z, true}");
01923 
01924   h2_zWidthVsLoop_= new TH2F("h2_zWidthVsLoop","h2_zWidthVsLoop",1000,0,40, 100, 0.,10.);
01925 
01926   h2_coeffVsLoop_= new TH2F("h2_coeffVsLoop","h2_coeffVsLoop",1000,0,40, 100, 0., 2.);
01927 
01928   h2_residualSigma_= new TH2F("h2_residualSigma","h2_residualSigma",1000, 0, 40, 100, 0., .5);
01929 
01930   h2_miscalRecal_ = new TH2F("h2_miscalRecal","h2_miscalRecal", 500, 0., 2., 500, 0., 2.);
01931   h2_miscalRecal_->SetXTitle("initCalibCoeff");
01932   h2_miscalRecal_->SetYTitle("1/RecalibCoeff");
01933  
01934   h2_miscalRecalEB_ = new TH2F("h2_miscalRecalEB","h2_miscalRecalEB", 500, 0., 2., 500, 0., 2.);
01935   h2_miscalRecalEB_->SetXTitle("initCalibCoeff");
01936   h2_miscalRecalEB_->SetYTitle("1/RecalibCoeff");
01937 
01938   h2_miscalRecalEE_ = new TH2F("h2_miscalRecalEE","h2_miscalRecalEE", 500, 0., 2., 500, 0., 2.);
01939   h2_miscalRecalEE_->SetXTitle("initCalibCoeff");
01940   h2_miscalRecalEE_->SetYTitle("1/RecalibCoeff");
01941 
01942   h1_mc_ = new TH1F("h1_residualMiscalib","h1_residualMiscalib", 200, -0.2, 0.2);
01943   h1_mcEB_ = new TH1F("h1_residualMiscalibEB","h1_residualMiscalibEB", 200, -0.2, 0.2);
01944   h1_mcEE_ = new TH1F("h1_residualMiscalibEE","h1_residualMiscalibEE", 200, -0.2, 0.2);
01945  
01946   for (int i=0;i<25;i++)
01947     {
01948       char histoName[50];
01949       /*     
01950              sprintf(histoName,"h2_miscalRecalParz_%d",i);
01951              h2_miscalRecalParz_[i] = new TH2F(histoName,histoName,500, 0., 2., 500, 0., 2.);
01952              h2_miscalRecalParz_[i]->SetXTitle("initCalibCoeff");
01953              h2_miscalRecalParz_[i]->SetYTitle("1/recalibCoeff");
01954              
01955              sprintf(histoName,"h2_miscalRecalEBParz_%d",i);
01956              h2_miscalRecalEBParz_[i] = new TH2F(histoName,histoName,500, 0., 2., 500, 0., 2.);
01957              h2_miscalRecalEBParz_[i]->SetXTitle("initCalibCoeff");
01958              h2_miscalRecalEBParz_[i]->SetYTitle("1/recalibCoeff");
01959              
01960       sprintf(histoName,"h2_miscalRecalEEParz_%d",i);
01961       h2_miscalRecalEEParz_[i] = new TH2F(histoName,histoName,500, 0., 2., 500, 0., 2.);
01962       h2_miscalRecalEEParz_[i]->SetXTitle("initCalibCoeff");
01963       h2_miscalRecalEEParz_[i]->SetYTitle("1/recalibCoeff");
01964       */
01965       
01966       sprintf(histoName,"h1_residualMiscalibParz_%d",i);
01967       h1_mcParz_[i] = new TH1F(histoName,histoName, 200, -0.2, 0.2);
01968       sprintf(histoName,"h1_residualMiscalibEBParz_%d",i);
01969       h1_mcEBParz_[i] = new TH1F(histoName,histoName, 200, -0.2, 0.2);
01970       sprintf(histoName,"h1_residualMiscalibEEParz_%d",i);
01971       h1_mcEEParz_[i] = new TH1F(histoName,histoName, 200, -0.2, 0.2);
01972       
01973     }
01974  
01975 
01976 }
01977 
01978 
01979 double ZeeCalibration::fEtaBarrelBad(double scEta) const{
01980   
01981   float p0 = 1.00153e+00;
01982     float p1 = 3.29331e-02;
01983     float p2 = 1.21187e-03;
01984 
01985   double x  = (double) fabs(scEta);
01986 
01987   return 1. / ( p0 + p1*x*x + p2*x*x*x*x );  
01988 
01989 }
01990   
01991 double ZeeCalibration::fEtaEndcapGood(double scEta) const{
01992 
01993   // f(eta) for the first 3 classes (100, 110 and 120) 
01994   // Ivica's new corrections 01/06
01995   float p0 = 1.06819e+00;
01996     float p1 = -1.53189e-02;
01997     float p2 = 4.01707e-04 ;
01998 
01999   double x  = (double) fabs(scEta);
02000 
02001   return 1. / ( p0 + p1*x*x + p2*x*x*x*x );  
02002 
02003 }
02004 
02005 double ZeeCalibration::fEtaEndcapBad(double scEta) const{
02006   
02007   float p0 = 1.17382e+00;
02008   float p1 = -6.52319e-02; 
02009   float p2 = 6.26108e-03;
02010 
02011   double x  = (double) fabs(scEta);
02012 
02013  return 1. / ( p0 + p1*x*x + p2*x*x*x*x );  
02014 
02015 }
02016   
02017 double ZeeCalibration::fEtaBarrelGood(double scEta) const{
02018 
02019   float p0 = 9.99782e-01 ;
02020   float p1 = 1.26983e-02;
02021   float p2 = 2.16344e-03;
02022 
02023   double x  = (double) fabs(scEta);
02024 
02025  return 1. / ( p0 + p1*x*x + p2*x*x*x*x );  
02026 
02027 }
02028 
02029 
02031 
02032 void ZeeCalibration::fillMCmap(const std::vector<const reco::GsfElectron*>* electronCollection,const std::vector<HepMC::GenParticle*>& mcEle,std::map<HepMC::GenParticle*,const reco::GsfElectron*>& myMCmap)
02033 {
02034   for (unsigned int i=0;i<mcEle.size();i++)
02035     {
02036       float minDR=0.1;
02037       const reco::GsfElectron* myMatchEle=0;
02038       for (unsigned int j=0;j<electronCollection->size();j++)
02039         {
02040           float dr=EvalDR(mcEle[i]->momentum().pseudoRapidity(),(*(*electronCollection)[j]).eta(),mcEle[i]->momentum().phi(),(*(*electronCollection)[j]).phi());
02041           if (dr < minDR )
02042             {
02043               myMatchEle = (*electronCollection)[j];
02044               minDR = dr;
02045             }
02046         }
02047       myMCmap.insert(std::pair<HepMC::GenParticle*,const reco::GsfElectron*>(mcEle[i],myMatchEle));
02048       
02049     }
02050 }
02051                                                                                                                              
02052 float ZeeCalibration::EvalDR(float Eta,float Eta_ref,float Phi,float Phi_ref)
02053 {
02054   if (Phi<0) Phi = 2*TMath::Pi() + Phi;
02055   if (Phi_ref<0) Phi_ref = 2*TMath::Pi() + Phi_ref;
02056   float DPhi = Phi - Phi_ref ;
02057   if (fabs(DPhi)>TMath::Pi()) DPhi = 2*TMath::Pi() - fabs(DPhi);
02058                                                                                                                              
02059   float DEta = Eta - Eta_ref ;
02060                                                                                                                              
02061   float DR = sqrt( DEta*DEta + DPhi*DPhi );
02062   return DR;
02063 }
02064 
02065 float ZeeCalibration::EvalDPhi(float Phi,float Phi_ref)
02066 {
02067   if (Phi<0) Phi = 2*TMath::Pi() + Phi;
02068   if (Phi_ref<0) Phi_ref = 2*TMath::Pi() + Phi_ref;
02069   return (Phi - Phi_ref);
02070 }
02071 
02072 void ZeeCalibration::fillEleInfo( std::vector<HepMC::GenParticle*>& mcEle, std::map<HepMC::GenParticle*,const reco::GsfElectron*>& associationMap)
02073 {
02074 
02075   for (unsigned int i=0;i<mcEle.size();i++)
02076     {
02077 
02078       h_eleEffEta_[0]->Fill(fabs(mcEle[i]->momentum().pseudoRapidity()));
02079       h_eleEffPhi_[0]->Fill(mcEle[i]->momentum().phi());
02080       h_eleEffPt_[0]->Fill(mcEle[i]->momentum().perp());
02081 
02082       std::map<HepMC::GenParticle*,const reco::GsfElectron*>::const_iterator mIter = associationMap.find(mcEle[i]);
02083       if (mIter == associationMap.end() )
02084         continue;
02085     
02086       if((*mIter).second)
02087         {
02088           const reco::GsfElectron* myEle=(*mIter).second;
02089       
02090           h_eleEffEta_[1]->Fill(fabs(mcEle[i]->momentum().pseudoRapidity()));
02091           h_eleEffPhi_[1]->Fill(mcEle[i]->momentum().phi());
02092           h_eleEffPt_[1]->Fill(mcEle[i]->momentum().perp());
02093           h1_eleEtaResol_->Fill( myEle->eta() - mcEle[i]->momentum().eta() );
02094           h1_elePhiResol_->Fill( myEle->phi() - mcEle[i]->momentum().phi() );
02095 
02096           const reco::SuperCluster* mySC=&(*(myEle->superCluster()));
02097           if (/*fabs(mySC->position().eta()) < 2.4*/1)
02098             {
02099               //      if(myEle->classification()>=100)std::cout<<"mySC->preshowerEnergy()"<<mySC->preshowerEnergy()<<std::endl;
02100 
02101               h_ESCEtrue_[loopFlag_]->Fill(mySC->energy()/mcEle[i]->momentum().e());
02102               h_ESCEtrueVsEta_[loopFlag_]->Fill(fabs(mySC->position().eta()),mySC->energy()/mcEle[i]->momentum().e());
02103 
02104               double corrSCenergy = ( mySC->energy() )/getEtaCorrection(myEle);
02105               h_ESCcorrEtrue_[loopFlag_]->Fill(corrSCenergy/mcEle[i]->momentum().e());
02106               h_ESCcorrEtrueVsEta_[loopFlag_]->Fill(fabs(mySC->position().eta()),corrSCenergy/mcEle[i]->momentum().e());
02107 
02108 //            std::vector<DetId> mySCRecHits = mySC->seed()->getHitsByDetId();
02109 
02110               h1_seedOverSC_->Fill( mySC->seed()->energy() / mySC->energy() );
02111               h1_preshowerOverSC_->Fill( mySC->preshowerEnergy() / mySC->energy() );
02112               
02113             }
02114 
02115         }
02116     }
02117 }
02118 
02119 int ZeeCalibration::ringNumberCorrector(int k)
02120 {
02121 
02122   int index=-999;
02123 
02124   if( calibMode_ == "RING"){
02125     if(k>=0 && k<=84)index = k - 85;
02126     
02127     if(k>=85 && k<=169)index = k - 84;
02128     
02129     if(k>=170 && k<=208)index = - k + 84;
02130     
02131     if(k>=209 && k<=247)index = k - 123;
02132     
02133   }
02134   
02135   else if( calibMode_ == "MODULE"){
02136     
02137     if(k>=0 && k<=71)index = k - 72;
02138     
02139     if(k>=72 && k<=143)index = k - 71;
02140     
02141   }
02142   return index;
02143   
02144 }
02145 
02146 
02147 double ZeeCalibration::getEtaCorrection(const reco::GsfElectron* ele){
02148 
02149   double correction(1.);
02150 
02151   if(ele->classification() ==0 ||
02152      ele->classification() ==10 ||
02153      ele->classification() ==20)
02154     correction = fEtaBarrelGood(ele->superCluster()->eta());
02155                                                                                                                                                
02156   if(ele->classification() ==100 ||
02157      ele->classification() ==110 ||
02158      ele->classification() ==120)
02159     correction = fEtaEndcapGood(ele->superCluster()->eta());
02160                                                                                                                                                
02161   if(ele->classification() ==30 ||
02162      ele->classification() ==31 ||
02163      ele->classification() ==32 ||
02164      ele->classification() ==33 ||
02165      ele->classification() ==34)
02166     correction = fEtaBarrelBad(ele->superCluster()->eta());
02167 
02168 
02169   if(ele->classification() ==130 ||
02170      ele->classification() ==131 ||
02171      ele->classification() ==132 ||
02172      ele->classification() ==133 ||
02173      ele->classification() ==134)
02174     correction = fEtaEndcapBad(ele->superCluster()->eta());
02175  
02176   return correction;                                                                                                                                              
02177 }
02178 
02179 std::pair<DetId, double> ZeeCalibration::getHottestDetId(std::vector<std::pair< DetId,float > > mySCRecHits, const EBRecHitCollection* ebhits, const EERecHitCollection* eehits){
02180   
02181 
02182   double maxEnergy = -9999.;
02183   const EcalRecHit* hottestRecHit=0;
02184   
02185   std::pair<DetId, double> myPair (DetId(0), -9999.);
02186 
02187 
02188   for(   std::vector<std::pair<DetId,float> >::const_iterator idIt=mySCRecHits.begin(); idIt != mySCRecHits.end(); idIt++){
02189    
02190     if (idIt->first.subdetId() == EcalBarrel )
02191       {
02192         hottestRecHit  = & (* ( ebhits->find((*idIt).first) ) );
02193 
02194         if( hottestRecHit == & (*( ebhits->end())) )
02195           {
02196             std::cout<<"@@@@@@@@@@@@@@@@@@@@@@@@@@@ NO RECHIT FOUND SHOULD NEVER HAPPEN"<<std::endl;
02197             continue;
02198           }
02199       }
02200     else if (idIt->first.subdetId() == EcalEndcap )
02201       {
02202         hottestRecHit  = & (* ( eehits->find((*idIt).first) ) );
02203         if( hottestRecHit == & (*( eehits->end())) )
02204           {
02205             std::cout<<"@@@@@@@@@@@@@@@@@@@@@@@@@@@ NO RECHIT FOUND SHOULD NEVER HAPPEN"<<std::endl;
02206             continue;
02207           }
02208       }    
02209     
02210     //std::cout<<"[getHottestDetId] hottestRecHit->energy() "<<hottestRecHit->energy()<<std::endl;
02211    
02212     if(hottestRecHit && hottestRecHit->energy() > maxEnergy){
02213 
02214       maxEnergy = hottestRecHit->energy();
02215       
02216       myPair.first =   hottestRecHit ->id();
02217       myPair.second = maxEnergy;
02218       
02219     }
02220     
02221   }//end loop to find hottest RecHit    
02222   
02223   //std::cout<<"[ZeeCalibration::getHottestDetId] going to return..."<<std::endl;
02224 
02225   return myPair;
02226   
02227 }
02228 
02229 
02230 bool ZeeCalibration::xtalIsOnModuleBorder( EBDetId myEBDetId ){
02231   
02232   bool myBool(false); 
02233 
02234   short ieta = myEBDetId.ieta();
02235   short iphi = myEBDetId.iphi();
02236 
02237   //  std::cout<<"[xtalIsOnModuleBorder] ieta: "<<ieta<<" iphi "<<iphi<<std::endl;
02238  
02239   myBool = ( abs( ieta )  == 1 || abs( ieta ) == 25
02240              || abs( ieta )  ==26 || abs( ieta ) == 45
02241              || abs( ieta )  ==46 || abs( ieta ) == 65
02242              || abs( ieta )  ==66 || abs( ieta ) == 85 );
02243     
02244     for(int i = 0; i < 19; i++){
02245       
02246       if(iphi == ( 20*i + 1 ) || iphi == 20*i )
02247       myBool = true;
02248       
02249     }
02250   
02251   return myBool;
02252 }
02253 
02254 float ZeeCalibration::computeCoefficientDistanceAtIteration( float v1[250], float v2[250], int size ){
02255 
02256   float dist(0.);
02257  
02258   for(int i =0; i < size; i++){
02259     
02260     //    std::cout<< "[ZeeCalibration::computeCoefficientDistanceAtIteration] Adding term "<<pow( v1[i]-v2[i], 2 )<<" from v1 "<<v1[i]<<" and v2 "<<v2[i]<<std::endl;
02261     
02262     bool isNearCrack = false;
02263 
02264     if( calibMode_ == "RING"){//exclude non-calibrated rings from computation
02265 
02266       isNearCrack = ( abs( ringNumberCorrector(i) ) == 1 || abs( ringNumberCorrector(i) ) == 25 ||
02267                       abs( ringNumberCorrector(i) ) == 26 || abs( ringNumberCorrector(i) ) == 45 ||
02268                       abs( ringNumberCorrector(i) ) == 46 || abs( ringNumberCorrector(i) ) == 65 ||
02269                       abs( ringNumberCorrector(i) ) == 66 || abs( ringNumberCorrector(i) ) == 85 ||
02270                       abs( ringNumberCorrector(i) ) == 86 || abs( ringNumberCorrector(i) ) == 124 );
02271     }
02272     
02273     if(!isNearCrack)
02274       dist += pow( v1[i]-v2[i], 2 );
02275   }
02276   
02277   dist = sqrt(dist) / size;
02278   
02279   return dist;
02280   
02281 }
02282 
02283 
02284 void ZeeCalibration::resetVariables(){
02285 
02286  BBZN=0;
02287  EBZN=0;
02288  EEZN=0;
02289  BBZN_gg=0;
02290  EBZN_gg=0;
02291  EEZN_gg=0;
02292 
02293  BBZN_tt=0;
02294  EBZN_tt=0;
02295  EEZN_tt=0;
02296 
02297  BBZN_t0=0;
02298  EBZN_t0=0;
02299  EEZN_t0=0;
02300 
02301  TOTAL_ELECTRONS_IN_BARREL=0;
02302  TOTAL_ELECTRONS_IN_ENDCAP=0;
02303 
02304  GOLDEN_ELECTRONS_IN_BARREL=0;
02305  GOLDEN_ELECTRONS_IN_ENDCAP=0;
02306  SILVER_ELECTRONS_IN_BARREL=0;
02307  SILVER_ELECTRONS_IN_ENDCAP=0;
02308  SHOWER_ELECTRONS_IN_BARREL=0;
02309  SHOWER_ELECTRONS_IN_ENDCAP=0;
02310  CRACK_ELECTRONS_IN_BARREL=0;
02311  CRACK_ELECTRONS_IN_ENDCAP=0;
02312 
02313 
02314  BARREL_ELECTRONS_BEFORE_BORDER_CUT = 0;
02315  BARREL_ELECTRONS_AFTER_BORDER_CUT = 0;
02316 
02317  return;
02318 
02319 }
02320 
02321 
02322 void ZeeCalibration::resetHistograms(){
02323 
02324  h1_eventsBeforeEWKSelection_ ->Reset();
02325  h1_eventsAfterEWKSelection_ ->Reset();
02326 
02327  h1_eventsBeforeBorderSelection_ ->Reset();
02328  h1_eventsAfterBorderSelection_ ->Reset();
02329 
02330  for (int i=0;i<2;i++)
02331    {
02332      h_eleEffEta_[i] ->Reset();
02333      h_eleEffPhi_[i] ->Reset(); 
02334      h_eleEffPt_[i]  ->Reset();
02335    }
02336 
02337  h1_seedOverSC_ ->Reset();
02338  h1_preshowerOverSC_ ->Reset();
02339 
02340  h1_eleEtaResol_->Reset();
02341  h1_elePhiResol_->Reset();
02342 
02343  h1_zMassResol_->Reset(); 
02344  
02345  h1_electronCosTheta_TK_->Reset();
02346  h1_electronCosTheta_SC_->Reset();
02347  h1_electronCosTheta_SC_TK_->Reset();
02348 
02349  h2_fEtaBarrelGood_->Reset();
02350  h2_fEtaBarrelBad_->Reset();
02351  h2_fEtaEndcapGood_->Reset();
02352  h2_fEtaEndcapBad_->Reset();
02353  h1_eleClasses_->Reset();
02354 
02355  h1_ZCandMult_-> Reset();
02356  h1_reco_ZMass_-> Reset();
02357   h1_reco_ZMassCorr_-> Reset();
02358  h1_reco_ZMassCorrBB_-> Reset();
02359  h1_reco_ZMassCorrEE_-> Reset();
02360  h1_occupancyVsEta_-> Reset();
02361  h1_occupancy_-> Reset();
02362  h1_occupancyBarrel_-> Reset();
02363  h1_occupancyEndcap_-> Reset();
02364 
02365  return;
02366 
02367 }
02368 
02369 
02370 void ZeeCalibration::printStatistics(){
02371 
02372 
02373   std::cout<< "[ CHECK ON BARREL ELECTRON NUMBER ]"<<" first "<<BARREL_ELECTRONS_BEFORE_BORDER_CUT<<" second "<<TOTAL_ELECTRONS_IN_BARREL << std::endl;
02374   
02375   
02376   std::cout<< "[ EFFICIENCY OF THE BORDER SELECTION ]" << (float)BARREL_ELECTRONS_AFTER_BORDER_CUT / (float) BARREL_ELECTRONS_BEFORE_BORDER_CUT << std::endl;
02377   
02378   std::cout<< "[ EFFICIENCY OF THE GOLDEN SELECTION ] BARREL: " << (float)GOLDEN_ELECTRONS_IN_BARREL / (float) TOTAL_ELECTRONS_IN_BARREL << " ENDCAP: "<< (float)GOLDEN_ELECTRONS_IN_ENDCAP / (float) TOTAL_ELECTRONS_IN_ENDCAP << std::endl;
02379   
02380   std::cout<< "[ EFFICIENCY OF THE SILVER SELECTION ] BARREL: " << (float)SILVER_ELECTRONS_IN_BARREL / (float) TOTAL_ELECTRONS_IN_BARREL << " ENDCAP: "<< (float)SILVER_ELECTRONS_IN_ENDCAP / (float) TOTAL_ELECTRONS_IN_ENDCAP << std::endl;
02381   
02382   std::cout<< "[ EFFICIENCY OF THE SHOWER SELECTION ] BARREL: " << (float)SHOWER_ELECTRONS_IN_BARREL / (float) TOTAL_ELECTRONS_IN_BARREL << " ENDCAP: "<< (float)SHOWER_ELECTRONS_IN_ENDCAP / (float) TOTAL_ELECTRONS_IN_ENDCAP << std::endl;
02383   
02384   std::cout<< "[ EFFICIENCY OF THE CRACK SELECTION ] BARREL: " << (float)CRACK_ELECTRONS_IN_BARREL / (float) TOTAL_ELECTRONS_IN_BARREL << " ENDCAP: "<< (float)CRACK_ELECTRONS_IN_ENDCAP / (float) TOTAL_ELECTRONS_IN_ENDCAP << std::endl;
02385   
02386   
02387   
02388   ofstream fout("ZeeStatistics.txt");
02389   
02390   if(!fout) {
02391     std::cout << "Cannot open output file.\n";
02392     }
02393 
02394   fout<<"ZeeStatistics"<<std::endl;
02395 
02396   fout<<"##########################RECO#########################"<<std::endl;
02397   fout<<"##################Zee with Barrel-Barrel electrons: "<<BBZN<<std::endl;
02398 
02399   fout<<"Golden-Golden fraction: "<<(float)BBZN_gg/BBZN<<" 3-3 fraction is "<<(float)BBZN_tt/BBZN<<" 3-whatever fraction is "<<(float)BBZN_t0/BBZN<<std::endl; 
02400   fout<<"##################Zee with Barrel-Endcap electrons: "<<EBZN<<std::endl;
02401   fout<<"Golden-Golden fraction: "<<(float)EBZN_gg/EBZN<<" 3-3 fraction is "<<(float)EBZN_tt/EBZN<<" 3-whatever fraction is "<<(float)EBZN_t0/EBZN<<std::endl; 
02402   fout<<"##################Zee with Endcap-Endcap electrons: "<<EEZN<<std::endl;
02403   fout<<"Golden-Golden fraction: "<<(float)EEZN_gg/EEZN<<" 3-3 fraction is "<<(float)EEZN_tt/EEZN<<" 3-whatever fraction is "<<(float)EEZN_t0/EEZN<<std::endl; 
02404 
02405   fout<<"\n"<<std::endl;
02406 
02407   fout<<"##########################GEN#########################"<<std::endl;
02408   fout<<"##################Zee with Barrel-Barrel electrons: "<<(float)MCZBB/NEVT<<std::endl;
02409   fout<<"##################Zee with Barrel-Endcap electrons: "<<(float)MCZEB/NEVT<<std::endl;
02410   fout<<"##################Zee with Endcap-Endcap electrons: "<<(float)MCZEE/NEVT<<std::endl;
02411 
02412   fout.close();
02413 
02414 
02415 
02416 }