CMS 3D CMS Logo

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