CMS 3D CMS Logo

/data/refman/pasoursint/CMSSW_5_3_3/src/Calibration/EcalCalibAlgos/src/ZeeCalibration.cc

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