CMS 3D CMS Logo

/data/refman/pasoursint/CMSSW_5_3_10_patch2/src/RecoEgamma/EgammaElectronAlgos/src/GsfElectronAlgo.cc

Go to the documentation of this file.
00001 
00002 #include "RecoEgamma/EgammaElectronAlgos/interface/GsfElectronAlgo.h"
00003 #include "RecoEgamma/EgammaElectronAlgos/interface/EgAmbiguityTools.h"
00004 #include "RecoEgamma/EgammaElectronAlgos/interface/ElectronClassification.h"
00005 #include "RecoEgamma/EgammaElectronAlgos/interface/ElectronMomentumCorrector.h"
00006 #include "RecoEgamma/EgammaElectronAlgos/interface/ElectronEnergyCorrector.h"
00007 #include "RecoEgamma/EgammaElectronAlgos/interface/ElectronUtilities.h"
00008 #include "RecoEgamma/EgammaTools/interface/ConversionFinder.h"
00009 
00010 #include "RecoEcal/EgammaCoreTools/interface/EcalClusterFunctionBaseClass.h"
00011 #include "RecoEcal/EgammaCoreTools/interface/EcalClusterTools.h"
00012 
00013 #include "DataFormats/ParticleFlowReco/interface/GsfPFRecTrackFwd.h"
00014 #include "DataFormats/ParticleFlowReco/interface/GsfPFRecTrack.h"
00015 #include "DataFormats/EgammaReco/interface/BasicCluster.h"
00016 #include "DataFormats/EgammaReco/interface/ElectronSeed.h"
00017 #include "DataFormats/Math/interface/LorentzVector.h"
00018 #include "DataFormats/TrackingRecHit/interface/TrackingRecHitFwd.h"
00019 #include "DataFormats/EcalDetId/interface/EcalSubdetector.h"
00020 #include "DataFormats/EcalDetId/interface/EBDetId.h"
00021 #include "DataFormats/EcalDetId/interface/EEDetId.h"
00022 #include "DataFormats/GeometryVector/interface/GlobalPoint.h"
00023 #include "DataFormats/GeometryVector/interface/GlobalVector.h"
00024 
00025 #include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h"
00026 #include "Geometry/Records/interface/CaloGeometryRecord.h"
00027 #include "Geometry/Records/interface/CaloTopologyRecord.h"
00028 
00029 #include "TrackingTools/GsfTools/interface/MultiTrajectoryStateTransform.h"
00030 #include "TrackingTools/GsfTools/interface/MultiTrajectoryStateMode.h"
00031 
00032 
00033 #include "CondFormats/DataRecord/interface/EcalChannelStatusRcd.h"
00034 
00035 #include "Geometry/CommonDetUnit/interface/TrackingGeometry.h"
00036 #include "Geometry/Records/interface/TrackerDigiGeometryRecord.h"
00037 
00038 
00039 #include "FWCore/MessageLogger/interface/MessageLogger.h"
00040 
00041 
00042 
00043 #include <Math/Point3D.h>
00044 #include <sstream>
00045 #include <algorithm>
00046 
00047 
00048 using namespace edm ;
00049 using namespace std ;
00050 using namespace reco ;
00051 
00052 
00053 //===================================================================
00054 // GsfElectronAlgo::GeneralData
00055 //===================================================================
00056 
00057 // general data and helpers
00058 struct GsfElectronAlgo::GeneralData
00059  {
00060   // constructors
00061   GeneralData
00062    ( const InputTagsConfiguration &,
00063      const StrategyConfiguration &,
00064      const CutsConfiguration & cutsCfg,
00065      const CutsConfiguration & cutsCfgPflow,
00066      const ElectronHcalHelper::Configuration & hcalCfg,
00067      const ElectronHcalHelper::Configuration & hcalCfgPflow,
00068      const IsolationConfiguration &,
00069      const EcalRecHitsConfiguration &,
00070      EcalClusterFunctionBaseClass * superClusterErrorFunction,
00071      EcalClusterFunctionBaseClass * crackCorrectionFunction ) ;
00072   ~GeneralData() ;
00073 
00074   // configurables
00075   const InputTagsConfiguration inputCfg ;
00076   const StrategyConfiguration strategyCfg ;
00077   const CutsConfiguration cutsCfg ;
00078   const CutsConfiguration cutsCfgPflow ;
00079   const IsolationConfiguration isoCfg ;
00080   const EcalRecHitsConfiguration recHitsCfg ;
00081 
00082   // additional configuration and helpers
00083   ElectronHcalHelper * hcalHelper, * hcalHelperPflow ;
00084   EcalClusterFunctionBaseClass * superClusterErrorFunction ;
00085   EcalClusterFunctionBaseClass * crackCorrectionFunction ;
00086  } ;
00087 
00088  GsfElectronAlgo::GeneralData::GeneralData
00089  ( const InputTagsConfiguration & inputConfig,
00090    const StrategyConfiguration & strategyConfig,
00091    const CutsConfiguration & cutsConfig,
00092    const CutsConfiguration & cutsConfigPflow,
00093    const ElectronHcalHelper::Configuration & hcalConfig,
00094    const ElectronHcalHelper::Configuration & hcalConfigPflow,
00095    const IsolationConfiguration & isoConfig,
00096    const EcalRecHitsConfiguration & recHitsConfig,
00097    EcalClusterFunctionBaseClass * superClusterErrorFunc,
00098    EcalClusterFunctionBaseClass * crackCorrectionFunc
00099  )
00100  : inputCfg(inputConfig),
00101    strategyCfg(strategyConfig),
00102    cutsCfg(cutsConfig),
00103    cutsCfgPflow(cutsConfigPflow),
00104    isoCfg(isoConfig),
00105    recHitsCfg(recHitsConfig),
00106    hcalHelper(new ElectronHcalHelper(hcalConfig)),
00107    hcalHelperPflow(new ElectronHcalHelper(hcalConfigPflow)),
00108    superClusterErrorFunction(superClusterErrorFunc),
00109    crackCorrectionFunction(crackCorrectionFunc)
00110  {}
00111 
00112 GsfElectronAlgo::GeneralData::~GeneralData()
00113  {
00114   delete hcalHelper ;
00115   delete hcalHelperPflow ;
00116  }
00117 
00118 //===================================================================
00119 // GsfElectronAlgo::EventSetupData
00120 //===================================================================
00121 
00122 struct GsfElectronAlgo::EventSetupData
00123  {
00124    EventSetupData() ;
00125    ~EventSetupData() ;
00126 
00127    unsigned long long cacheIDGeom ;
00128    unsigned long long cacheIDTopo ;
00129    unsigned long long cacheIDTDGeom ;
00130    unsigned long long cacheIDMagField ;
00131    //unsigned long long cacheChStatus ;
00132    unsigned long long cacheSevLevel ;
00133 
00134    edm::ESHandle<MagneticField> magField ;
00135    edm::ESHandle<CaloGeometry> caloGeom ;
00136    edm::ESHandle<CaloTopology> caloTopo ;
00137    edm::ESHandle<TrackerGeometry> trackerHandle ;
00138    //edm::ESHandle<EcalChannelStatus> chStatus ;
00139    edm::ESHandle<EcalSeverityLevelAlgo> sevLevel;
00140 
00141    const MultiTrajectoryStateTransform * mtsTransform ;
00142    GsfConstraintAtVertex * constraintAtVtx ;
00143    const MultiTrajectoryStateMode * mtsMode ;
00144 } ;
00145 
00146 GsfElectronAlgo::EventSetupData::EventSetupData()
00147  : cacheIDGeom(0), cacheIDTopo(0), cacheIDTDGeom(0), cacheIDMagField(0),/*cacheChStatus(0),*/
00148    cacheSevLevel(0), mtsTransform(0), constraintAtVtx(0), mtsMode(new MultiTrajectoryStateMode)
00149  {}
00150 
00151 GsfElectronAlgo::EventSetupData::~EventSetupData()
00152  {
00153   delete mtsMode ;
00154   delete constraintAtVtx ;
00155   delete mtsTransform ;
00156  }
00157 
00158 
00159 //===================================================================
00160 // GsfElectronAlgo::EventData
00161 //===================================================================
00162 
00163 struct GsfElectronAlgo::EventData
00164  {
00165   // general
00166   edm::Event * event ;
00167   const reco::BeamSpot * beamspot ;
00168   GsfElectronPtrCollection * electrons ;
00169 
00170   EventData() ;
00171   ~EventData() ;
00172 
00173   // utilities
00174   void retreiveOriginalTrackCollections
00175    ( const reco::TrackRef &, const reco::GsfTrackRef & ) ;
00176 
00177   // input collections
00178   edm::Handle<reco::GsfElectronCollection> previousElectrons ;
00179   edm::Handle<reco::GsfElectronCollection> pflowElectrons ;
00180   edm::Handle<reco::GsfElectronCoreCollection> coreElectrons ;
00181   edm::Handle<EcalRecHitCollection> barrelRecHits ;
00182   edm::Handle<EcalRecHitCollection> endcapRecHits ;
00183   edm::Handle<reco::TrackCollection> currentCtfTracks ;
00184   edm::Handle<CaloTowerCollection> towers ;
00185   edm::Handle<edm::ValueMap<float> > pfMva ;
00186   edm::Handle<reco::ElectronSeedCollection> seeds ;
00187   edm::Handle<reco::GsfPFRecTrackCollection> gsfPfRecTracks ;
00188   bool originalCtfTrackCollectionRetreived ;
00189   bool originalGsfTrackCollectionRetreived ;
00190   edm::Handle<reco::TrackCollection> originalCtfTracks ;
00191   edm::Handle<reco::GsfTrackCollection> originalGsfTracks ;
00192 
00193   // isolation helpers
00194   ElectronTkIsolation * tkIsolation03, * tkIsolation04 ;
00195   EgammaTowerIsolation * hadDepth1Isolation03, * hadDepth1Isolation04 ;
00196   EgammaTowerIsolation * hadDepth2Isolation03, * hadDepth2Isolation04 ;
00197   EgammaTowerIsolation * hadDepth1Isolation03Bc, * hadDepth1Isolation04Bc ;
00198   EgammaTowerIsolation * hadDepth2Isolation03Bc, * hadDepth2Isolation04Bc ;
00199   EcalRecHitMetaCollection * ecalBarrelHitsMeta ;
00200   EcalRecHitMetaCollection * ecalEndcapHitsMeta ;
00201   EgammaRecHitIsolation * ecalBarrelIsol03, * ecalBarrelIsol04 ;
00202   EgammaRecHitIsolation * ecalEndcapIsol03, * ecalEndcapIsol04 ;
00203  } ;
00204 
00205 GsfElectronAlgo::EventData::EventData()
00206  : event(0), beamspot(0),
00207    originalCtfTrackCollectionRetreived(false),
00208    originalGsfTrackCollectionRetreived(false),
00209    tkIsolation03(0), tkIsolation04(0),
00210    hadDepth1Isolation03(0), hadDepth1Isolation04(0),
00211    hadDepth2Isolation03(0), hadDepth2Isolation04(0),
00212    ecalBarrelHitsMeta(0), ecalEndcapHitsMeta(0),
00213    ecalBarrelIsol03(0), ecalBarrelIsol04(0),
00214    ecalEndcapIsol03(0), ecalEndcapIsol04(0)
00215  {
00216   electrons = new GsfElectronPtrCollection ;
00217  }
00218 
00219 GsfElectronAlgo::EventData::~EventData()
00220  {
00221   delete tkIsolation03 ;
00222   delete tkIsolation04 ;
00223   delete hadDepth1Isolation03 ;
00224   delete hadDepth1Isolation04 ;
00225   delete hadDepth2Isolation03 ;
00226   delete hadDepth2Isolation04 ;
00227   delete ecalBarrelHitsMeta ;
00228   delete ecalEndcapHitsMeta ;
00229   delete ecalBarrelIsol03 ;
00230   delete ecalBarrelIsol04 ;
00231   delete ecalEndcapIsol03 ;
00232   delete ecalEndcapIsol04 ;
00233 
00234   GsfElectronPtrCollection::const_iterator it ;
00235   for ( it = electrons->begin() ; it != electrons->end() ; it++ )
00236    { delete (*it) ; }
00237   delete electrons ;
00238  }
00239 
00240 void GsfElectronAlgo::EventData::retreiveOriginalTrackCollections
00241  ( const reco::TrackRef & ctfTrack, const reco::GsfTrackRef & gsfTrack )
00242  {
00243   if ((!originalCtfTrackCollectionRetreived)&&(ctfTrack.isNonnull()))
00244    {
00245     event->get(ctfTrack.id(),originalCtfTracks) ;
00246     originalCtfTrackCollectionRetreived = true ;
00247    }
00248   if ((!originalGsfTrackCollectionRetreived)&&(gsfTrack.isNonnull()))
00249    {
00250     event->get(gsfTrack.id(),originalGsfTracks) ;
00251     originalGsfTrackCollectionRetreived = true ;
00252    }
00253  }
00254 
00255 
00256 //===================================================================
00257 // GsfElectronAlgo::ElectronData
00258 //===================================================================
00259 
00260 struct GsfElectronAlgo::ElectronData
00261  {
00262   // Refs to subproducts
00263   const reco::GsfElectronCoreRef coreRef ;
00264   const reco::GsfTrackRef gsfTrackRef ;
00265   const reco::SuperClusterRef superClusterRef ;
00266   reco::TrackRef ctfTrackRef ;
00267   float shFracInnerHits ;
00268   const reco::BeamSpot beamSpot ;
00269 
00270   // constructors
00271   ElectronData
00272    ( const reco::GsfElectronCoreRef & core,
00273      const reco::BeamSpot & bs ) ;
00274   ~ElectronData() ;
00275 
00276   // utilities
00277   void checkCtfTrack( edm::Handle<reco::TrackCollection> currentCtfTracks ) ;
00278   void computeCharge( int & charge, reco::GsfElectron::ChargeInfo & info ) ;
00279   CaloClusterPtr getEleBasicCluster( const MultiTrajectoryStateTransform * ) ;
00280   bool calculateTSOS( const MultiTrajectoryStateTransform *, GsfConstraintAtVertex * ) ;
00281   void calculateMode( const MultiTrajectoryStateMode * mtsMode ) ;
00282   Candidate::LorentzVector calculateMomentum() ;
00283 
00284   // TSOS
00285   TrajectoryStateOnSurface innTSOS ;
00286   TrajectoryStateOnSurface outTSOS ;
00287   TrajectoryStateOnSurface vtxTSOS ;
00288   TrajectoryStateOnSurface sclTSOS ;
00289   TrajectoryStateOnSurface seedTSOS ;
00290   TrajectoryStateOnSurface eleTSOS ;
00291   TrajectoryStateOnSurface constrainedVtxTSOS ;
00292 
00293   // mode
00294   GlobalVector innMom, seedMom, eleMom, sclMom, vtxMom, outMom ;
00295   GlobalPoint innPos, seedPos, elePos, sclPos, vtxPos, outPos ;
00296   GlobalVector vtxMomWithConstraint ;
00297  } ;
00298 
00299 GsfElectronAlgo::ElectronData::ElectronData
00300  ( const reco::GsfElectronCoreRef & core,
00301    const reco::BeamSpot & bs )
00302  : coreRef(core),
00303    gsfTrackRef(coreRef->gsfTrack()),
00304    superClusterRef(coreRef->superCluster()),
00305    ctfTrackRef(coreRef->ctfTrack()), shFracInnerHits(coreRef->ctfGsfOverlap()),
00306    beamSpot(bs)
00307  {}
00308 
00309 GsfElectronAlgo::ElectronData::~ElectronData()
00310  {}
00311 
00312 void GsfElectronAlgo::ElectronData::checkCtfTrack( edm::Handle<reco::TrackCollection> currentCtfTracks )
00313  {
00314   if (!ctfTrackRef.isNull()) return ;
00315 
00316   // Code below from Puneeth Kalavase
00317 
00318   shFracInnerHits = 0 ;
00319   const TrackCollection * ctfTrackCollection = currentCtfTracks.product() ;
00320 
00321   // get the Hit Pattern for the gsfTrack
00322   const HitPattern & gsfHitPattern = gsfTrackRef->hitPattern() ;
00323 
00324   unsigned int counter ;
00325   TrackCollection::const_iterator ctfTkIter ;
00326   for ( ctfTkIter = ctfTrackCollection->begin() , counter = 0 ;
00327         ctfTkIter != ctfTrackCollection->end() ; ctfTkIter++, counter++ )
00328    {
00329 
00330     double dEta = gsfTrackRef->eta() - ctfTkIter->eta() ;
00331     double dPhi = gsfTrackRef->phi() - ctfTkIter->phi() ;
00332     double pi = acos(-1.);
00333     if(std::abs(dPhi) > pi) dPhi = 2*pi - std::abs(dPhi) ;
00334 
00335     // dont want to look at every single track in the event!
00336     if (sqrt(dEta*dEta + dPhi*dPhi) > 0.3) continue ;
00337 
00338     unsigned int shared = 0 ;
00339     int gsfHitCounter = 0 ;
00340     int numGsfInnerHits = 0 ;
00341     int numCtfInnerHits = 0 ;
00342 
00343     // get the CTF Track Hit Pattern
00344     const HitPattern & ctfHitPattern = ctfTkIter->hitPattern() ;
00345 
00346     trackingRecHit_iterator elHitsIt ;
00347     for ( elHitsIt = gsfTrackRef->recHitsBegin() ;
00348           elHitsIt != gsfTrackRef->recHitsEnd() ;
00349           elHitsIt++, gsfHitCounter++ )
00350      {
00351       if (!((**elHitsIt).isValid()))  //count only valid Hits
00352        { continue ; }
00353 
00354       // look only in the pixels/TIB/TID
00355       uint32_t gsfHit = gsfHitPattern.getHitPattern(gsfHitCounter) ;
00356       if (!(gsfHitPattern.pixelHitFilter(gsfHit) ||
00357           gsfHitPattern.stripTIBHitFilter(gsfHit) ||
00358           gsfHitPattern.stripTIDHitFilter(gsfHit) ) )
00359        { continue ; }
00360 
00361       numGsfInnerHits++ ;
00362 
00363       int ctfHitsCounter = 0 ;
00364       numCtfInnerHits = 0 ;
00365       trackingRecHit_iterator ctfHitsIt ;
00366       for ( ctfHitsIt = ctfTkIter->recHitsBegin() ;
00367             ctfHitsIt != ctfTkIter->recHitsEnd() ;
00368             ctfHitsIt++, ctfHitsCounter++ )
00369        {
00370         if(!((**ctfHitsIt).isValid())) //count only valid Hits!
00371          { continue ; }
00372 
00373         uint32_t ctfHit = ctfHitPattern.getHitPattern(ctfHitsCounter);
00374         if( !(ctfHitPattern.pixelHitFilter(ctfHit) ||
00375               ctfHitPattern.stripTIBHitFilter(ctfHit) ||
00376               ctfHitPattern.stripTIDHitFilter(ctfHit) ) )
00377          { continue ; }
00378 
00379         numCtfInnerHits++ ;
00380 
00381         if( (**elHitsIt).sharesInput(&(**ctfHitsIt),TrackingRecHit::all) )
00382          {
00383           shared++ ;
00384           break ;
00385          }
00386 
00387        } //ctfHits iterator
00388 
00389      } //gsfHits iterator
00390 
00391     if ((numGsfInnerHits==0)||(numCtfInnerHits==0))
00392      { continue ; }
00393 
00394     if ( static_cast<float>(shared)/min(numGsfInnerHits,numCtfInnerHits) > shFracInnerHits )
00395      {
00396       shFracInnerHits = static_cast<float>(shared)/min(numGsfInnerHits, numCtfInnerHits);
00397       ctfTrackRef = TrackRef(currentCtfTracks,counter);
00398      }
00399    } //ctfTrack iterator
00400  }
00401 
00402 void GsfElectronAlgo::ElectronData::computeCharge
00403  ( int & charge, GsfElectron::ChargeInfo & info )
00404  {
00405   // determine charge from SC
00406   GlobalPoint orig, scpos ;
00407   ele_convert(beamSpot.position(),orig) ;
00408   ele_convert(superClusterRef->position(),scpos) ;
00409   GlobalVector scvect(scpos-orig) ;
00410   GlobalPoint inntkpos = innTSOS.globalPosition() ;
00411   GlobalVector inntkvect = GlobalVector(inntkpos-orig) ;
00412   float dPhiInnEle=normalized_phi(scvect.phi()-inntkvect.phi()) ;
00413   if(dPhiInnEle>0) info.scPixCharge = -1 ;
00414   else info.scPixCharge = 1 ;
00415 
00416   // flags
00417   int chargeGsf = gsfTrackRef->charge() ;
00418   info.isGsfScPixConsistent = ((chargeGsf*info.scPixCharge)>0) ;
00419   info.isGsfCtfConsistent = (ctfTrackRef.isNonnull()&&((chargeGsf*ctfTrackRef->charge())>0)) ;
00420   info.isGsfCtfScPixConsistent = (info.isGsfScPixConsistent&&info.isGsfCtfConsistent) ;
00421 
00422   // default charge
00423   if (info.isGsfScPixConsistent||ctfTrackRef.isNull())
00424    { charge = info.scPixCharge ; }
00425   else
00426    { charge = ctfTrackRef->charge() ; }
00427  }
00428 
00429 CaloClusterPtr GsfElectronAlgo::ElectronData::getEleBasicCluster
00430  ( const MultiTrajectoryStateTransform * mtsTransform )
00431  {
00432   CaloClusterPtr eleRef ;
00433   TrajectoryStateOnSurface tempTSOS ;
00434   TrajectoryStateOnSurface outTSOS = mtsTransform->outerStateOnSurface(*gsfTrackRef) ;
00435   float dphimin = 1.e30 ;
00436   for (CaloCluster_iterator bc=superClusterRef->clustersBegin(); bc!=superClusterRef->clustersEnd(); bc++)
00437    {
00438     GlobalPoint posclu((*bc)->position().x(),(*bc)->position().y(),(*bc)->position().z()) ;
00439     tempTSOS = mtsTransform->extrapolatedState(outTSOS,posclu) ;
00440     if (!tempTSOS.isValid()) tempTSOS=outTSOS ;
00441     GlobalPoint extrap = tempTSOS.globalPosition() ;
00442     float dphi = EleRelPointPair(posclu,extrap,beamSpot.position()).dPhi() ;
00443     if (std::abs(dphi)<dphimin)
00444      {
00445       dphimin = std::abs(dphi) ;
00446       eleRef = (*bc);
00447       eleTSOS = tempTSOS ;
00448      }
00449    }
00450   return eleRef ;
00451  }
00452 
00453 bool GsfElectronAlgo::ElectronData::calculateTSOS
00454  ( const MultiTrajectoryStateTransform * mtsTransform, GsfConstraintAtVertex * constraintAtVtx )
00455  {
00456   //at innermost point
00457   innTSOS = mtsTransform->innerStateOnSurface(*gsfTrackRef);
00458   if (!innTSOS.isValid()) return false;
00459 
00460   //at vertex
00461   // innermost state propagation to the beam spot position
00462   GlobalPoint bsPos ;
00463   ele_convert(beamSpot.position(),bsPos) ;
00464   vtxTSOS = mtsTransform->extrapolatedState(innTSOS,bsPos) ;
00465   if (!vtxTSOS.isValid()) vtxTSOS=innTSOS;
00466 
00467   //at seed
00468   outTSOS = mtsTransform->outerStateOnSurface(*gsfTrackRef);
00469   if (!outTSOS.isValid()) return false;
00470 
00471   //    TrajectoryStateOnSurface seedTSOS
00472   seedTSOS = mtsTransform->extrapolatedState(outTSOS,
00473            GlobalPoint(superClusterRef->seed()->position().x(),
00474                superClusterRef->seed()->position().y(),
00475                  superClusterRef->seed()->position().z()));
00476   if (!seedTSOS.isValid()) seedTSOS=outTSOS;
00477 
00478   // at scl
00479   sclTSOS = mtsTransform->extrapolatedState(innTSOS,GlobalPoint(superClusterRef->x(),superClusterRef->y(),superClusterRef->z()));
00480   if (!sclTSOS.isValid()) sclTSOS=outTSOS;
00481 
00482   // constrained momentum
00483   constrainedVtxTSOS = constraintAtVtx->constrainAtBeamSpot(*gsfTrackRef,beamSpot);
00484 
00485   return true ;
00486  }
00487 
00488 void GsfElectronAlgo::ElectronData::calculateMode( const MultiTrajectoryStateMode * mtsMode )
00489  {
00490   mtsMode->momentumFromModeCartesian(innTSOS,innMom) ;
00491   mtsMode->positionFromModeCartesian(innTSOS,innPos) ;
00492   mtsMode->momentumFromModeCartesian(seedTSOS,seedMom) ;
00493   mtsMode->positionFromModeCartesian(seedTSOS,seedPos) ;
00494   mtsMode->momentumFromModeCartesian(eleTSOS,eleMom) ;
00495   mtsMode->positionFromModeCartesian(eleTSOS,elePos) ;
00496   mtsMode->momentumFromModeCartesian(sclTSOS,sclMom) ;
00497   mtsMode->positionFromModeCartesian(sclTSOS,sclPos) ;
00498   mtsMode->momentumFromModeCartesian(vtxTSOS,vtxMom) ;
00499   mtsMode->positionFromModeCartesian(vtxTSOS,vtxPos) ;
00500   mtsMode->momentumFromModeCartesian(outTSOS,outMom);
00501   mtsMode->positionFromModeCartesian(outTSOS,outPos) ;
00502   mtsMode->momentumFromModeCartesian(constrainedVtxTSOS,vtxMomWithConstraint);
00503  }
00504 
00505 Candidate::LorentzVector GsfElectronAlgo::ElectronData::calculateMomentum()
00506  {
00507   double scale = superClusterRef->energy()/vtxMom.mag() ;
00508   return Candidate::LorentzVector
00509    ( vtxMom.x()*scale,vtxMom.y()*scale,vtxMom.z()*scale,
00510      superClusterRef->energy() ) ;
00511  }
00512 
00513 void GsfElectronAlgo::calculateShowerShape( const reco::SuperClusterRef & theClus, bool pflow, reco::GsfElectron::ShowerShape & showerShape )
00514  {
00515   const reco::CaloCluster & seedCluster = *(theClus->seed()) ;
00516   // temporary, till CaloCluster->seed() is made available
00517   DetId seedXtalId = seedCluster.hitsAndFractions()[0].first ;
00518   int detector = seedXtalId.subdetId() ;
00519 
00520   const CaloTopology * topology = eventSetupData_->caloTopo.product() ;
00521   const CaloGeometry * geometry = eventSetupData_->caloGeom.product() ;
00522   const EcalRecHitCollection * recHits = 0 ;
00523   std::vector<int> recHitFlagsToBeExcluded ;
00524   std::vector<int> recHitSeverityToBeExcluded ;
00525   const EcalSeverityLevelAlgo * severityLevelAlgo = eventSetupData_->sevLevel.product() ;
00526   if (detector==EcalBarrel)
00527    {
00528     recHits = eventData_->barrelRecHits.product() ;
00529     recHitFlagsToBeExcluded = generalData_->recHitsCfg.recHitFlagsToBeExcludedBarrel ;
00530     recHitSeverityToBeExcluded = generalData_->recHitsCfg.recHitSeverityToBeExcludedBarrel ;
00531    }
00532   else
00533    {
00534     recHits = eventData_->endcapRecHits.product() ;
00535     recHitFlagsToBeExcluded = generalData_->recHitsCfg.recHitFlagsToBeExcludedEndcaps ;
00536     recHitSeverityToBeExcluded = generalData_->recHitsCfg.recHitSeverityToBeExcludedEndcaps ;
00537    }
00538 
00539   std::vector<float> covariances = EcalClusterTools::covariances(seedCluster,recHits,topology,geometry,recHitFlagsToBeExcluded,recHitSeverityToBeExcluded,severityLevelAlgo) ;
00540   std::vector<float> localCovariances = EcalClusterTools::localCovariances(seedCluster,recHits,topology,recHitFlagsToBeExcluded,recHitSeverityToBeExcluded,severityLevelAlgo) ;
00541   showerShape.sigmaEtaEta = sqrt(covariances[0]) ;
00542   showerShape.sigmaIetaIeta = sqrt(localCovariances[0]) ;
00543   if (!isnan(localCovariances[2])) showerShape.sigmaIphiIphi = sqrt(localCovariances[2]) ;
00544   showerShape.e1x5 = EcalClusterTools::e1x5(seedCluster,recHits,topology,recHitFlagsToBeExcluded,recHitSeverityToBeExcluded,severityLevelAlgo)  ;
00545   showerShape.e2x5Max = EcalClusterTools::e2x5Max(seedCluster,recHits,topology,recHitFlagsToBeExcluded,recHitSeverityToBeExcluded,severityLevelAlgo)  ;
00546   showerShape.e5x5 = EcalClusterTools::e5x5(seedCluster,recHits,topology,recHitFlagsToBeExcluded,recHitSeverityToBeExcluded,severityLevelAlgo) ;
00547   showerShape.r9 = EcalClusterTools::e3x3(seedCluster,recHits,topology,recHitFlagsToBeExcluded,recHitSeverityToBeExcluded,severityLevelAlgo)/theClus->rawEnergy() ;
00548 
00549   if (pflow)
00550    {
00551     showerShape.hcalDepth1OverEcal = generalData_->hcalHelperPflow->hcalESumDepth1(*theClus)/theClus->energy() ;
00552     showerShape.hcalDepth2OverEcal = generalData_->hcalHelperPflow->hcalESumDepth2(*theClus)/theClus->energy() ;
00553     showerShape.hcalTowersBehindClusters = generalData_->hcalHelperPflow->hcalTowersBehindClusters(*theClus) ;
00554     showerShape.hcalDepth1OverEcalBc = generalData_->hcalHelperPflow->hcalESumDepth1BehindClusters(showerShape.hcalTowersBehindClusters)/theClus->energy() ;
00555     showerShape.hcalDepth2OverEcalBc = generalData_->hcalHelperPflow->hcalESumDepth2BehindClusters(showerShape.hcalTowersBehindClusters)/theClus->energy() ;
00556    }
00557   else
00558    {
00559     showerShape.hcalDepth1OverEcal = generalData_->hcalHelper->hcalESumDepth1(*theClus)/theClus->energy() ;
00560     showerShape.hcalDepth2OverEcal = generalData_->hcalHelper->hcalESumDepth2(*theClus)/theClus->energy() ;
00561     showerShape.hcalTowersBehindClusters = generalData_->hcalHelper->hcalTowersBehindClusters(*theClus) ;
00562     showerShape.hcalDepth1OverEcalBc = generalData_->hcalHelper->hcalESumDepth1BehindClusters(showerShape.hcalTowersBehindClusters)/theClus->energy() ;
00563     showerShape.hcalDepth2OverEcalBc = generalData_->hcalHelper->hcalESumDepth2BehindClusters(showerShape.hcalTowersBehindClusters)/theClus->energy() ;
00564    }
00565  }
00566 
00567 
00568 //===================================================================
00569 // GsfElectronAlgo
00570 //===================================================================
00571 
00572 GsfElectronAlgo::GsfElectronAlgo
00573  ( const InputTagsConfiguration & inputCfg,
00574    const StrategyConfiguration & strategyCfg,
00575    const CutsConfiguration & cutsCfg,
00576    const CutsConfiguration & cutsCfgPflow,
00577    const ElectronHcalHelper::Configuration & hcalCfg,
00578    const ElectronHcalHelper::Configuration & hcalCfgPflow,
00579    const IsolationConfiguration & isoCfg,
00580    const EcalRecHitsConfiguration & recHitsCfg,
00581    EcalClusterFunctionBaseClass * superClusterErrorFunction,
00582    EcalClusterFunctionBaseClass * crackCorrectionFunction
00583  )
00584  : generalData_(new GeneralData(inputCfg,strategyCfg,cutsCfg,cutsCfgPflow,hcalCfg,hcalCfgPflow,isoCfg,recHitsCfg,superClusterErrorFunction,crackCorrectionFunction)),
00585    eventSetupData_(new EventSetupData),
00586    eventData_(0), electronData_(0)
00587  {}
00588 
00589 GsfElectronAlgo::~GsfElectronAlgo()
00590  {
00591   delete generalData_ ;
00592   delete eventSetupData_ ;
00593   delete eventData_ ;
00594   delete electronData_ ;
00595  }
00596 
00597 void GsfElectronAlgo::checkSetup( const edm::EventSetup & es )
00598  {
00599   // get EventSetupRecords if needed
00600   bool updateField(false);
00601   if (eventSetupData_->cacheIDMagField!=es.get<IdealMagneticFieldRecord>().cacheIdentifier()){
00602     updateField = true;
00603     eventSetupData_->cacheIDMagField=es.get<IdealMagneticFieldRecord>().cacheIdentifier();
00604     es.get<IdealMagneticFieldRecord>().get(eventSetupData_->magField);
00605   }
00606 
00607   bool updateGeometry(false);
00608   if (eventSetupData_->cacheIDTDGeom!=es.get<TrackerDigiGeometryRecord>().cacheIdentifier()){
00609     updateGeometry = true;
00610     eventSetupData_->cacheIDTDGeom=es.get<TrackerDigiGeometryRecord>().cacheIdentifier();
00611     es.get<TrackerDigiGeometryRecord>().get(eventSetupData_->trackerHandle);
00612   }
00613 
00614   if ( updateField || updateGeometry ) {
00615     delete eventSetupData_->mtsTransform ;
00616     eventSetupData_->mtsTransform = new MultiTrajectoryStateTransform(eventSetupData_->trackerHandle.product(),eventSetupData_->magField.product());
00617     delete eventSetupData_->constraintAtVtx ;
00618     eventSetupData_->constraintAtVtx = new GsfConstraintAtVertex(es) ;
00619   }
00620 
00621   if (eventSetupData_->cacheIDGeom!=es.get<CaloGeometryRecord>().cacheIdentifier()){
00622     eventSetupData_->cacheIDGeom=es.get<CaloGeometryRecord>().cacheIdentifier();
00623     es.get<CaloGeometryRecord>().get(eventSetupData_->caloGeom);
00624   }
00625 
00626   if (eventSetupData_->cacheIDTopo!=es.get<CaloTopologyRecord>().cacheIdentifier()){
00627     eventSetupData_->cacheIDTopo=es.get<CaloTopologyRecord>().cacheIdentifier();
00628     es.get<CaloTopologyRecord>().get(eventSetupData_->caloTopo);
00629   }
00630 
00631   generalData_->hcalHelper->checkSetup(es) ;
00632   generalData_->hcalHelperPflow->checkSetup(es) ;
00633 
00634   if (generalData_->superClusterErrorFunction)
00635    { generalData_->superClusterErrorFunction->init(es) ; }
00636   if (generalData_->crackCorrectionFunction)
00637    { generalData_->crackCorrectionFunction->init(es) ; }
00638 
00639   //if(eventSetupData_->cacheChStatus!=es.get<EcalChannelStatusRcd>().cacheIdentifier()){
00640   //  eventSetupData_->cacheChStatus=es.get<EcalChannelStatusRcd>().cacheIdentifier();
00641   //  es.get<EcalChannelStatusRcd>().get(eventSetupData_->chStatus);
00642   //}
00643 
00644   if(eventSetupData_->cacheSevLevel != es.get<EcalSeverityLevelAlgoRcd>().cacheIdentifier()){
00645     eventSetupData_->cacheSevLevel = es.get<EcalSeverityLevelAlgoRcd>().cacheIdentifier();
00646     es.get<EcalSeverityLevelAlgoRcd>().get(eventSetupData_->sevLevel);
00647   }
00648  }
00649 
00650 void GsfElectronAlgo::copyElectrons( GsfElectronCollection & outEle )
00651  {
00652   GsfElectronPtrCollection::const_iterator it ;
00653   for
00654    ( it = eventData_->electrons->begin() ;
00655      it != eventData_->electrons->end() ;
00656      it++ )
00657    { outEle.push_back(**it) ; }
00658  }
00659 
00660 void GsfElectronAlgo::beginEvent( edm::Event & event )
00661  {
00662   if (eventData_!=0)
00663    { throw cms::Exception("GsfElectronAlgo|InternalError")<<"unexpected event data" ; }
00664   eventData_ = new EventData ;
00665 
00666   // init the handles linked to the current event
00667   eventData_->event = &event ;
00668   event.getByLabel(generalData_->inputCfg.previousGsfElectrons,eventData_->previousElectrons) ;
00669   event.getByLabel(generalData_->inputCfg.pflowGsfElectronsTag,eventData_->pflowElectrons) ;
00670   event.getByLabel(generalData_->inputCfg.gsfElectronCores,eventData_->coreElectrons) ;
00671   event.getByLabel(generalData_->inputCfg.ctfTracks,eventData_->currentCtfTracks) ;
00672   event.getByLabel(generalData_->inputCfg.barrelRecHitCollection,eventData_->barrelRecHits) ;
00673   event.getByLabel(generalData_->inputCfg.endcapRecHitCollection,eventData_->endcapRecHits) ;
00674   event.getByLabel(generalData_->inputCfg.hcalTowersTag,eventData_->towers) ;
00675   event.getByLabel(generalData_->inputCfg.pfMVA,eventData_->pfMva) ;
00676   event.getByLabel(generalData_->inputCfg.seedsTag,eventData_->seeds) ;
00677   if (generalData_->strategyCfg.useGsfPfRecTracks)
00678    { event.getByLabel(generalData_->inputCfg.gsfPfRecTracksTag,eventData_->gsfPfRecTracks) ; }
00679 
00680   // get the beamspot from the Event:
00681   edm::Handle<reco::BeamSpot> recoBeamSpotHandle ;
00682   event.getByLabel(generalData_->inputCfg.beamSpotTag,recoBeamSpotHandle) ;
00683   eventData_->beamspot = recoBeamSpotHandle.product() ;
00684 
00685   // prepare access to hcal data
00686   generalData_->hcalHelper->readEvent(event) ;
00687   generalData_->hcalHelperPflow->readEvent(event) ;
00688 
00689   // Isolation algos
00690   float extRadiusSmall=0.3, extRadiusLarge=0.4 ;
00691   float intRadiusBarrel=generalData_->isoCfg.intRadiusBarrelTk, intRadiusEndcap=generalData_->isoCfg.intRadiusEndcapTk, stripBarrel=generalData_->isoCfg.stripBarrelTk, stripEndcap=generalData_->isoCfg.stripEndcapTk ;
00692   float ptMin=generalData_->isoCfg.ptMinTk, maxVtxDist=generalData_->isoCfg.maxVtxDistTk, drb=generalData_->isoCfg.maxDrbTk;
00693   eventData_->tkIsolation03 = new ElectronTkIsolation(extRadiusSmall,intRadiusBarrel,intRadiusEndcap,stripBarrel,stripEndcap,ptMin,maxVtxDist,drb,eventData_->currentCtfTracks.product(),eventData_->beamspot->position()) ;
00694   eventData_->tkIsolation04 = new ElectronTkIsolation(extRadiusLarge,intRadiusBarrel,intRadiusEndcap,stripBarrel,stripEndcap,ptMin,maxVtxDist,drb,eventData_->currentCtfTracks.product(),eventData_->beamspot->position()) ;
00695 
00696   float egHcalIsoConeSizeOutSmall=0.3, egHcalIsoConeSizeOutLarge=0.4;
00697   float egHcalIsoConeSizeIn=generalData_->isoCfg.intRadiusHcal,egHcalIsoPtMin=generalData_->isoCfg.etMinHcal;
00698   int egHcalDepth1=1, egHcalDepth2=2;
00699   eventData_->hadDepth1Isolation03 = new EgammaTowerIsolation(egHcalIsoConeSizeOutSmall,egHcalIsoConeSizeIn,egHcalIsoPtMin,egHcalDepth1,eventData_->towers.product()) ;
00700   eventData_->hadDepth2Isolation03 = new EgammaTowerIsolation(egHcalIsoConeSizeOutSmall,egHcalIsoConeSizeIn,egHcalIsoPtMin,egHcalDepth2,eventData_->towers.product()) ;
00701   eventData_->hadDepth1Isolation04 = new EgammaTowerIsolation(egHcalIsoConeSizeOutLarge,egHcalIsoConeSizeIn,egHcalIsoPtMin,egHcalDepth1,eventData_->towers.product()) ;
00702   eventData_->hadDepth2Isolation04 = new EgammaTowerIsolation(egHcalIsoConeSizeOutLarge,egHcalIsoConeSizeIn,egHcalIsoPtMin,egHcalDepth2,eventData_->towers.product()) ;
00703   eventData_->hadDepth1Isolation03Bc = new EgammaTowerIsolation(egHcalIsoConeSizeOutSmall,0.,egHcalIsoPtMin,egHcalDepth1,eventData_->towers.product()) ;
00704   eventData_->hadDepth2Isolation03Bc = new EgammaTowerIsolation(egHcalIsoConeSizeOutSmall,0.,egHcalIsoPtMin,egHcalDepth2,eventData_->towers.product()) ;
00705   eventData_->hadDepth1Isolation04Bc = new EgammaTowerIsolation(egHcalIsoConeSizeOutLarge,0.,egHcalIsoPtMin,egHcalDepth1,eventData_->towers.product()) ;
00706   eventData_->hadDepth2Isolation04Bc = new EgammaTowerIsolation(egHcalIsoConeSizeOutLarge,0.,egHcalIsoPtMin,egHcalDepth2,eventData_->towers.product()) ;
00707 
00708   float egIsoConeSizeOutSmall=0.3, egIsoConeSizeOutLarge=0.4, egIsoJurassicWidth=generalData_->isoCfg.jurassicWidth;
00709   float egIsoPtMinBarrel=generalData_->isoCfg.etMinBarrel,egIsoEMinBarrel=generalData_->isoCfg.eMinBarrel, egIsoConeSizeInBarrel=generalData_->isoCfg.intRadiusEcalBarrel;
00710   float egIsoPtMinEndcap=generalData_->isoCfg.etMinEndcaps,egIsoEMinEndcap=generalData_->isoCfg.eMinEndcaps, egIsoConeSizeInEndcap=generalData_->isoCfg.intRadiusEcalEndcaps;
00711   eventData_->ecalBarrelHitsMeta = new EcalRecHitMetaCollection(*eventData_->barrelRecHits) ;
00712   eventData_->ecalEndcapHitsMeta = new EcalRecHitMetaCollection(*eventData_->endcapRecHits) ;
00713   eventData_->ecalBarrelIsol03 = new EgammaRecHitIsolation(egIsoConeSizeOutSmall,egIsoConeSizeInBarrel,egIsoJurassicWidth,egIsoPtMinBarrel,egIsoEMinBarrel,eventSetupData_->caloGeom,eventData_->ecalBarrelHitsMeta,eventSetupData_->sevLevel.product(),DetId::Ecal);
00714   eventData_->ecalBarrelIsol04 = new EgammaRecHitIsolation(egIsoConeSizeOutLarge,egIsoConeSizeInBarrel,egIsoJurassicWidth,egIsoPtMinBarrel,egIsoEMinBarrel,eventSetupData_->caloGeom,eventData_->ecalBarrelHitsMeta,eventSetupData_->sevLevel.product(),DetId::Ecal);
00715   eventData_->ecalEndcapIsol03 = new EgammaRecHitIsolation(egIsoConeSizeOutSmall,egIsoConeSizeInEndcap,egIsoJurassicWidth,egIsoPtMinEndcap,egIsoEMinEndcap,eventSetupData_->caloGeom,eventData_->ecalEndcapHitsMeta,eventSetupData_->sevLevel.product(),DetId::Ecal);
00716   eventData_->ecalEndcapIsol04 = new EgammaRecHitIsolation(egIsoConeSizeOutLarge,egIsoConeSizeInEndcap,egIsoJurassicWidth,egIsoPtMinEndcap,egIsoEMinEndcap,eventSetupData_->caloGeom,eventData_->ecalEndcapHitsMeta,eventSetupData_->sevLevel.product(),DetId::Ecal);
00717   eventData_->ecalBarrelIsol03->setUseNumCrystals(generalData_->isoCfg.useNumCrystals);
00718   eventData_->ecalBarrelIsol03->setVetoClustered(generalData_->isoCfg.vetoClustered);
00719   eventData_->ecalBarrelIsol03->doSeverityChecks(eventData_->barrelRecHits.product(),generalData_->recHitsCfg.recHitSeverityToBeExcludedBarrel);
00720   eventData_->ecalBarrelIsol03->doFlagChecks(generalData_->recHitsCfg.recHitFlagsToBeExcludedBarrel);
00721   eventData_->ecalBarrelIsol04->setUseNumCrystals(generalData_->isoCfg.useNumCrystals);
00722   eventData_->ecalBarrelIsol04->setVetoClustered(generalData_->isoCfg.vetoClustered);
00723   eventData_->ecalBarrelIsol04->doSeverityChecks(eventData_->barrelRecHits.product(),generalData_->recHitsCfg.recHitSeverityToBeExcludedBarrel);
00724   eventData_->ecalBarrelIsol04->doFlagChecks(generalData_->recHitsCfg.recHitFlagsToBeExcludedBarrel);
00725   eventData_->ecalEndcapIsol03->setUseNumCrystals(generalData_->isoCfg.useNumCrystals);
00726   eventData_->ecalEndcapIsol03->setVetoClustered(generalData_->isoCfg.vetoClustered);
00727   eventData_->ecalEndcapIsol03->doSeverityChecks(eventData_->endcapRecHits.product(),generalData_->recHitsCfg.recHitSeverityToBeExcludedEndcaps);
00728   eventData_->ecalEndcapIsol03->doFlagChecks(generalData_->recHitsCfg.recHitFlagsToBeExcludedEndcaps);
00729   eventData_->ecalEndcapIsol04->setUseNumCrystals(generalData_->isoCfg.useNumCrystals);
00730   eventData_->ecalEndcapIsol04->setVetoClustered(generalData_->isoCfg.vetoClustered);
00731   eventData_->ecalEndcapIsol04->doSeverityChecks(eventData_->endcapRecHits.product(),generalData_->recHitsCfg.recHitSeverityToBeExcludedEndcaps);
00732   eventData_->ecalEndcapIsol04->doFlagChecks(generalData_->recHitsCfg.recHitFlagsToBeExcludedEndcaps);
00733  }
00734 
00735 void GsfElectronAlgo::endEvent()
00736  {
00737   if (eventData_==0)
00738    { throw cms::Exception("GsfElectronAlgo|InternalError")<<"lacking event data" ; }
00739   delete eventData_ ;
00740   eventData_ = 0 ;
00741  }
00742 
00743 void GsfElectronAlgo::displayInternalElectrons( const std::string & title ) const
00744  {
00745   LogTrace("GsfElectronAlgo") << "========== " << title << " ==========";
00746   LogTrace("GsfElectronAlgo") << "Event: " << eventData_->event->id();
00747   LogTrace("GsfElectronAlgo") << "Number of electrons: " << eventData_->electrons->size() ;
00748   GsfElectronPtrCollection::const_iterator it ;
00749   for ( it = eventData_->electrons->begin(); it != eventData_->electrons->end(); it++ )
00750    {
00751     LogTrace("GsfElectronAlgo") << "Electron with charge, pt, eta, phi: "  << (*it)->charge() << " , "
00752         << (*it)->pt() << " , " << (*it)->eta() << " , " << (*it)->phi();
00753    }
00754   LogTrace("GsfElectronAlgo") << "=================================================";
00755  }
00756 
00757 void GsfElectronAlgo::completeElectrons()
00758  {
00759   if (electronData_!=0)
00760    { throw cms::Exception("GsfElectronAlgo|InternalError")<<"unexpected electron data" ; }
00761 
00762   const GsfElectronCoreCollection * coreCollection = eventData_->coreElectrons.product() ;
00763   for ( unsigned int i=0 ; i<coreCollection->size() ; ++i )
00764    {
00765     // check there is no existing electron with this core
00766     const GsfElectronCoreRef coreRef = edm::Ref<GsfElectronCoreCollection>(eventData_->coreElectrons,i) ;
00767     bool coreFound = false ;
00768     GsfElectronPtrCollection::const_iterator itrEle ;
00769     for
00770      ( itrEle = eventData_->electrons->begin() ;
00771        itrEle != eventData_->electrons->end() ;
00772        itrEle++ )
00773      {
00774       if ((*itrEle)->core()==coreRef)
00775        {
00776         coreFound = true ;
00777         break ;
00778        }
00779      }
00780     if (coreFound) continue ;
00781 
00782     // check there is a super-cluster
00783     if (coreRef->superCluster().isNull()) continue ;
00784 
00785     // prepare internal structure for electron specific data
00786     delete electronData_ ;
00787     electronData_ = new ElectronData(coreRef,*eventData_->beamspot) ;
00788 
00789     // calculate and check Trajectory StatesOnSurface....
00790     if ( !electronData_->calculateTSOS( eventSetupData_->mtsTransform, eventSetupData_->constraintAtVtx ) ) continue ;
00791 
00792     createElectron() ;
00793 
00794    } // loop over tracks
00795 
00796   delete electronData_ ;
00797   electronData_ = 0 ;
00798  }
00799 
00800 void GsfElectronAlgo::clonePreviousElectrons()
00801  {
00802   const GsfElectronCollection * oldElectrons = eventData_->previousElectrons.product() ;
00803   const GsfElectronCoreCollection * newCores = eventData_->coreElectrons.product() ;
00804   GsfElectronCollection::const_iterator oldElectron ;
00805   for
00806    ( oldElectron = oldElectrons->begin() ;
00807      oldElectron != oldElectrons->end() ;
00808      ++oldElectron )
00809    {
00810     const GsfElectronCoreRef oldCoreRef = oldElectron->core() ;
00811     const GsfTrackRef oldElectronGsfTrackRef = oldCoreRef->gsfTrack() ;
00812     unsigned int icore ;
00813     for ( icore=0 ; icore<newCores->size() ; ++icore )
00814      {
00815       if (oldElectronGsfTrackRef==(*newCores)[icore].gsfTrack())
00816        {
00817         const GsfElectronCoreRef coreRef = edm::Ref<GsfElectronCoreCollection>(eventData_->coreElectrons,icore) ;
00818         eventData_->electrons->push_back(new GsfElectron(*oldElectron,coreRef)) ;
00819         break ;
00820        }
00821      }
00822    }
00823  }
00824 
00825 void GsfElectronAlgo::addPflowInfo()
00826  {
00827   bool found ;
00828   const GsfElectronCollection * pfElectrons = eventData_->pflowElectrons.product() ;
00829   GsfElectronCollection::const_iterator pfElectron ;
00830 
00831   GsfElectronPtrCollection::iterator el ;
00832   for
00833    ( el = eventData_->electrons->begin() ;
00834      el != eventData_->electrons->end() ;
00835      el++ )
00836    {
00837 //    // MVA
00838 //    // we check that the value is never inferior to the no-cut value
00839 //    // we generally use in the configuration file for minMVA.
00840 //    GsfTrackRef gsfTrackRef = (*el)->gsfTrack() ;
00841 //    float mva = (*eventData_->pfMva.product())[gsfTrackRef] ;
00842 //    if (mva<noCutMin) { throw cms::Exception("GsfElectronAlgo|UnexpectedMvaValue")<<"unexpected MVA value: "<<mva ; }
00843 //
00844 //    // Mva Output
00845 //    GsfElectron::MvaOutput mvaOutput ;
00846 //    mvaOutput.mva = mva ;
00847 //    (*el)->setMvaOutput(mvaOutput) ;
00848 
00849     // Retreive info from pflow electrons
00850     found = false ;
00851     for
00852      ( pfElectron = pfElectrons->begin() ; pfElectron != pfElectrons->end() ; pfElectron++ )
00853      {
00854       if (pfElectron->gsfTrack()==(*el)->gsfTrack())
00855        {
00856         if (found)
00857          {
00858           edm::LogWarning("GsfElectronProducer")<<"associated pfGsfElectron already found" ;
00859          }
00860         else
00861          {
00862           found = true ;
00863           (*el)->setPfIsolationVariables(pfElectron->pfIsolationVariables()) ;
00864           (*el)->setMvaInput(pfElectron->mvaInput()) ;
00865           (*el)->setMvaOutput(pfElectron->mvaOutput()) ;
00866           if ((*el)->ecalDrivenSeed())
00867            { (*el)->setP4(GsfElectron::P4_PFLOW_COMBINATION,pfElectron->p4(GsfElectron::P4_PFLOW_COMBINATION),pfElectron->p4Error(GsfElectron::P4_PFLOW_COMBINATION),false) ; }
00868           else
00869            { (*el)->setP4(GsfElectron::P4_PFLOW_COMBINATION,pfElectron->p4(GsfElectron::P4_PFLOW_COMBINATION),pfElectron->p4Error(GsfElectron::P4_PFLOW_COMBINATION),true) ; }
00870           double noCutMin = -999999999. ;
00871           if ((*el)->mva()<noCutMin) { throw cms::Exception("GsfElectronAlgo|UnexpectedMvaValue")<<"unexpected MVA value: "<<(*el)->mva() ; }
00872          }
00873        }
00874      }
00875 
00876     // Preselection
00877     setPflowPreselectionFlag(*el) ;
00878 
00879     // Shower Shape of pflow cluster
00880     if (!((*el)->pflowSuperCluster().isNull()))
00881      {
00882       reco::GsfElectron::ShowerShape pflowShowerShape ;
00883       calculateShowerShape((*el)->pflowSuperCluster(),true,pflowShowerShape) ;
00884       (*el)->setPfShowerShape(pflowShowerShape) ;
00885      }
00886     else if ((*el)->passingPflowPreselection())
00887      { edm::LogError("GsfElectronCoreProducer")<<"Preselected tracker driven GsfTrack with no associated pflow SuperCluster." ; }
00888 
00889     // PfBrem
00890     SuperClusterRef sc = (*el)->pflowSuperCluster() ;
00891     if (!(sc.isNull()))
00892      {
00893 
00894       if (sc->clustersSize()>1)
00895        {
00896         CaloCluster_iterator first = sc->clustersBegin() ;
00897         (*el)->setPfSuperClusterFbrem((sc->energy()-(*first)->energy())/sc->energy()) ;
00898        }
00899       else
00900        { (*el)->setPfSuperClusterFbrem(0.) ; }
00901       ElectronClassification theClassifier ;
00902       theClassifier.refineWithPflow(**el) ;
00903      }
00904    }
00905  }
00906 
00907 bool GsfElectronAlgo::isPreselected( GsfElectron * ele )
00908  { return (ele->passingCutBasedPreselection()||ele->passingPflowPreselection()) ; }
00909 
00910 void GsfElectronAlgo::removeNotPreselectedElectrons()
00911  {
00912   GsfElectronPtrCollection::size_type ei = 1, emax = eventData_->electrons->size() ;
00913   GsfElectronPtrCollection::iterator eitr = eventData_->electrons->begin() ;
00914   while (eitr!=eventData_->electrons->end())
00915    {
00916     LogTrace("GsfElectronAlgo")<<"========== removed not preselected "<<ei<<"/"<<emax<<"==========" ;
00917     if (isPreselected(*eitr))
00918      { ++eitr ; ++ei ; }
00919     else
00920      { delete (*eitr) ; eitr = eventData_->electrons->erase(eitr) ; ++ei ; }
00921    }
00922  }
00923 
00924 void GsfElectronAlgo::setCutBasedPreselectionFlag( GsfElectron * ele, const reco::BeamSpot & bs )
00925  {
00926   // default value
00927   ele->setPassCutBasedPreselection(false) ;
00928 
00929   // kind of seeding
00930   bool eg = ele->core()->ecalDrivenSeed() ;
00931   bool pf = ele->core()->trackerDrivenSeed() && !ele->core()->ecalDrivenSeed() ;
00932   if (eg&&pf) { throw cms::Exception("GsfElectronAlgo|BothEcalAndPureTrackerDriven")<<"An electron cannot be both egamma and purely pflow" ; }
00933   if ((!eg)&&(!pf)) { throw cms::Exception("GsfElectronAlgo|NeitherEcalNorPureTrackerDriven")<<"An electron cannot be neither egamma nor purely pflow" ; }
00934   const CutsConfiguration * cfg = (eg?&generalData_->cutsCfg:&generalData_->cutsCfgPflow) ;
00935 
00936   // Et cut
00937   double etaValue = EleRelPoint(ele->superCluster()->position(),bs.position()).eta() ;
00938   double etValue = ele->superCluster()->energy()/cosh(etaValue) ;
00939   LogTrace("GsfElectronAlgo") << "Et : " << etValue ;
00940   if (ele->isEB() && (etValue < cfg->minSCEtBarrel)) return ;
00941   if (ele->isEE() && (etValue < cfg->minSCEtEndcaps)) return ;
00942   LogTrace("GsfElectronAlgo") << "Et criteria are satisfied";
00943 
00944   // E/p cut
00945   double eopValue = ele->eSuperClusterOverP() ;
00946   LogTrace("GsfElectronAlgo") << "E/p : " << eopValue ;
00947   if (ele->isEB() && (eopValue > cfg->maxEOverPBarrel)) return ;
00948   if (ele->isEE() && (eopValue > cfg->maxEOverPEndcaps)) return ;
00949   if (ele->isEB() && (eopValue < cfg->minEOverPBarrel)) return ;
00950   if (ele->isEE() && (eopValue < cfg->minEOverPEndcaps)) return ;
00951   LogTrace("GsfElectronAlgo") << "E/p criteria are satisfied";
00952 
00953   // HoE cuts
00954   LogTrace("GsfElectronAlgo") << "HoE1 : " << ele->hcalDepth1OverEcal() << ", HoE2 : " << ele->hcalDepth2OverEcal();
00955   double had = ele->hcalOverEcal()*ele->superCluster()->energy() ;
00956   const reco::CaloCluster & seedCluster = *(ele->superCluster()->seed()) ;
00957   int detector = seedCluster.hitsAndFractions()[0].first.subdetId() ;
00958   bool HoEveto = false ;
00959   if (detector==EcalBarrel && (had<cfg->maxHBarrel || (had/ele->superCluster()->energy())<cfg->maxHOverEBarrel)) HoEveto=true;
00960   else if (detector==EcalEndcap && (had<cfg->maxHEndcaps || (had/ele->superCluster()->energy())<cfg->maxHOverEEndcaps)) HoEveto=true;
00961   if ( !HoEveto ) return ;
00962   LogTrace("GsfElectronAlgo") << "H/E criteria are satisfied";
00963 
00964   // delta eta criteria
00965   double deta = ele->deltaEtaSuperClusterTrackAtVtx() ;
00966   LogTrace("GsfElectronAlgo") << "delta eta : " << deta ;
00967   if (ele->isEB() && (std::abs(deta) > cfg->maxDeltaEtaBarrel)) return ;
00968   if (ele->isEE() && (std::abs(deta) > cfg->maxDeltaEtaEndcaps)) return ;
00969   LogTrace("GsfElectronAlgo") << "Delta eta criteria are satisfied";
00970 
00971   // delta phi criteria
00972   double dphi = ele->deltaPhiSuperClusterTrackAtVtx();
00973   LogTrace("GsfElectronAlgo") << "delta phi : " << dphi;
00974   if (ele->isEB() && (std::abs(dphi) > cfg->maxDeltaPhiBarrel)) return ;
00975   if (ele->isEE() && (std::abs(dphi) > cfg->maxDeltaPhiEndcaps)) return ;
00976   LogTrace("GsfElectronAlgo") << "Delta phi criteria are satisfied";
00977 
00978   // sigma ieta ieta
00979   LogTrace("GsfElectronAlgo") << "sigma ieta ieta : " << ele->sigmaIetaIeta();
00980   if (ele->isEB() && (ele->sigmaIetaIeta() > cfg->maxSigmaIetaIetaBarrel)) return ;
00981   if (ele->isEE() && (ele->sigmaIetaIeta() > cfg->maxSigmaIetaIetaEndcaps)) return ;
00982   LogTrace("GsfElectronAlgo") << "Sigma ieta ieta criteria are satisfied";
00983 
00984   // fiducial
00985   if (!ele->isEB() && cfg->isBarrel) return ;
00986   if (!ele->isEE() && cfg->isEndcaps) return ;
00987   if (cfg->isFiducial && (ele->isEBEEGap()||ele->isEBEtaGap()||ele->isEBPhiGap()||ele->isEERingGap()||ele->isEEDeeGap())) return ;
00988   LogTrace("GsfElectronAlgo") << "Fiducial flags criteria are satisfied";
00989 
00990   // seed in TEC
00991   edm::RefToBase<TrajectorySeed> seed = ele->gsfTrack()->extra()->seedRef() ;
00992   ElectronSeedRef elseed = seed.castTo<ElectronSeedRef>() ;
00993   if (eg && !generalData_->cutsCfg.seedFromTEC)
00994    {
00995     if (elseed.isNull())
00996      { throw cms::Exception("GsfElectronAlgo|NotElectronSeed")<<"The GsfTrack seed is not an ElectronSeed ?!" ; }
00997     else
00998      { if (elseed->subDet2()==6) return ; }
00999    }
01000 
01001   // transverse impact parameter
01002   if (std::abs(ele->gsfTrack()->dxy(bs.position()))>cfg->maxTIP) return ;
01003   LogTrace("GsfElectronAlgo") << "TIP criterion is satisfied" ;
01004 
01005   LogTrace("GsfElectronAlgo") << "All cut based criteria are satisfied" ;
01006   ele->setPassCutBasedPreselection(true) ;
01007  }
01008 
01009 void GsfElectronAlgo::setPflowPreselectionFlag( GsfElectron * ele )
01010  {
01011   ele->setPassMvaPreselection(false) ;
01012 
01013   if (ele->core()->ecalDrivenSeed())
01014    { if (ele->mvaOutput().mva>=generalData_->cutsCfg.minMVA) ele->setPassMvaPreselection(true) ; }
01015   else
01016    { if (ele->mvaOutput().mva>=generalData_->cutsCfgPflow.minMVA) ele->setPassMvaPreselection(true) ; }
01017 
01018   if (ele->passingMvaPreselection())
01019    { LogTrace("GsfElectronAlgo") << "Main mva criterion is satisfied" ; }
01020 
01021   ele->setPassPflowPreselection(ele->passingMvaPreselection()) ;
01022 
01023 //  ele->setPassPflowPreselection(false) ;
01024 //  if (ele->core()->ecalDrivenSeed())
01025 //   {
01026 //    if ((ele->mvaOutput().mva>=generalData_->cutsCfg.minMVA) ||
01027 //        (ele->mvaOutput().mvaByPassForIsolated>=generalData_->cutsCfg.minMvaByPassForIsolated))
01028 //      ele->setPassPflowPreselection(true) ;
01029 //   }
01030 //  else
01031 //   {
01032 //    if ((ele->mvaOutput().mva>=generalData_->cutsCfgPflow.minMVA) ||
01033 //        (ele->mvaOutput().mvaByPassForIsolated>=generalData_->cutsCfgPflow.minMvaByPassForIsolated))
01034 //      ele->setPassPflowPreselection(true) ;
01035 //   }
01036 //  if (ele->passingPflowPreselection())
01037 //   { LogTrace("GsfElectronAlgo") << "Mva criteria are satisfied" ; }
01038  }
01039 
01040 void GsfElectronAlgo::createElectron()
01041  {
01042   // eventually check ctf track
01043   if (generalData_->strategyCfg.ctfTracksCheck)
01044    { electronData_->checkCtfTrack(eventData_->currentCtfTracks) ; }
01045 
01046   // charge ID
01047   int eleCharge ;
01048   GsfElectron::ChargeInfo eleChargeInfo ;
01049   electronData_->computeCharge(eleCharge,eleChargeInfo) ;
01050 
01051   // electron basic cluster
01052   CaloClusterPtr elbcRef = electronData_->getEleBasicCluster(eventSetupData_->mtsTransform) ;
01053 
01054   // Seed cluster
01055   const reco::CaloCluster & seedCluster = *(electronData_->superClusterRef->seed()) ;
01056 
01057   // seed Xtal
01058   // temporary, till CaloCluster->seed() is made available
01059   DetId seedXtalId = seedCluster.hitsAndFractions()[0].first ;
01060 
01061   electronData_->calculateMode(eventSetupData_->mtsMode) ;
01062 
01063 
01064   //====================================================
01065   // Candidate attributes
01066   //====================================================
01067 
01068   Candidate::LorentzVector momentum = electronData_->calculateMomentum() ;
01069 
01070 
01071   //====================================================
01072   // Track-Cluster Matching
01073   //====================================================
01074 
01075   reco::GsfElectron::TrackClusterMatching tcMatching ;
01076   tcMatching.electronCluster = elbcRef ;
01077   tcMatching.eSuperClusterOverP = (electronData_->vtxMom.mag()>0)?(electronData_->superClusterRef->energy()/electronData_->vtxMom.mag()):(-1.) ;
01078   tcMatching.eSeedClusterOverP = (electronData_->vtxMom.mag()>0.)?(seedCluster.energy()/electronData_->vtxMom.mag()):(-1) ;
01079   tcMatching.eSeedClusterOverPout = (electronData_->seedMom.mag()>0.)?(seedCluster.energy()/electronData_->seedMom.mag()):(-1.) ;
01080   tcMatching.eEleClusterOverPout = (electronData_->eleMom.mag()>0.)?(elbcRef->energy()/electronData_->eleMom.mag()):(-1.) ;
01081 
01082   EleRelPointPair scAtVtx(electronData_->superClusterRef->position(),electronData_->sclPos,eventData_->beamspot->position()) ;
01083   tcMatching.deltaEtaSuperClusterAtVtx = scAtVtx.dEta() ;
01084   tcMatching.deltaPhiSuperClusterAtVtx = scAtVtx.dPhi() ;
01085 
01086   EleRelPointPair seedAtCalo(seedCluster.position(),electronData_->seedPos,eventData_->beamspot->position()) ;
01087   tcMatching.deltaEtaSeedClusterAtCalo = seedAtCalo.dEta() ;
01088   tcMatching.deltaPhiSeedClusterAtCalo = seedAtCalo.dPhi() ;
01089 
01090   EleRelPointPair ecAtCalo(elbcRef->position(),electronData_->elePos,eventData_->beamspot->position()) ;
01091   tcMatching.deltaEtaEleClusterAtCalo = ecAtCalo.dEta() ;
01092   tcMatching.deltaPhiEleClusterAtCalo = ecAtCalo.dPhi() ;
01093 
01094 
01095   //=======================================================
01096   // Track extrapolations
01097   //=======================================================
01098 
01099   reco::GsfElectron::TrackExtrapolations tkExtra ;
01100   ele_convert(electronData_->vtxPos,tkExtra.positionAtVtx) ;
01101   ele_convert(electronData_->sclPos,tkExtra.positionAtCalo) ;
01102   ele_convert(electronData_->vtxMom,tkExtra.momentumAtVtx) ;
01103   ele_convert(electronData_->sclMom,tkExtra.momentumAtCalo) ;
01104   ele_convert(electronData_->seedMom,tkExtra.momentumOut) ;
01105   ele_convert(electronData_->eleMom,tkExtra.momentumAtEleClus) ;
01106   ele_convert(electronData_->vtxMomWithConstraint,tkExtra.momentumAtVtxWithConstraint) ;
01107 
01108 
01109   //=======================================================
01110   // Closest Ctf Track
01111   //=======================================================
01112 
01113   reco::GsfElectron::ClosestCtfTrack ctfInfo ;
01114   ctfInfo.ctfTrack = electronData_->ctfTrackRef  ;
01115   ctfInfo.shFracInnerHits = electronData_->shFracInnerHits ;
01116 
01117 
01118   //====================================================
01119   // FiducialFlags, using nextToBoundary definition of gaps
01120   //====================================================
01121 
01122   reco::GsfElectron::FiducialFlags fiducialFlags ;
01123   int detector = seedXtalId.subdetId() ;
01124   double feta=std::abs(electronData_->superClusterRef->position().eta()) ;
01125   if (detector==EcalBarrel)
01126    {
01127     fiducialFlags.isEB = true ;
01128     EBDetId ebdetid(seedXtalId);
01129     if (EBDetId::isNextToEtaBoundary(ebdetid))
01130      {
01131       if (ebdetid.ietaAbs()==85)
01132        { fiducialFlags.isEBEEGap = true ; }
01133       else
01134        { fiducialFlags.isEBEtaGap = true ; }
01135      }
01136     if (EBDetId::isNextToPhiBoundary(ebdetid))
01137      { fiducialFlags.isEBPhiGap = true ; }
01138    }
01139   else if (detector==EcalEndcap)
01140    {
01141     fiducialFlags.isEE = true ;
01142     EEDetId eedetid(seedXtalId);
01143     if (EEDetId::isNextToRingBoundary(eedetid))
01144      {
01145       if (std::abs(feta)<2.)
01146        { fiducialFlags.isEBEEGap = true ; }
01147       else
01148        { fiducialFlags.isEERingGap = true ; }
01149      }
01150     if (EEDetId::isNextToDBoundary(eedetid))
01151      { fiducialFlags.isEEDeeGap = true ; }
01152    }
01153   else
01154    { throw cms::Exception("GsfElectronAlgo|UnknownXtalRegion")<<"createElectron(): do not know if it is a barrel or endcap seed cluster !!!!" ; }
01155 
01156 
01157   //====================================================
01158   // ShowerShape
01159   //====================================================
01160 
01161   reco::GsfElectron::ShowerShape showerShape ;
01162   calculateShowerShape(electronData_->superClusterRef,!(electronData_->coreRef->ecalDrivenSeed()),showerShape) ;
01163 
01164 
01165   //====================================================
01166   // ConversionRejection
01167   //====================================================
01168 
01169   eventData_->retreiveOriginalTrackCollections(electronData_->ctfTrackRef,electronData_->coreRef->gsfTrack()) ;
01170 
01171   ConversionFinder conversionFinder ;
01172   double BInTesla = eventSetupData_->magField->inTesla(GlobalPoint(0.,0.,0.)).z() ;
01173   edm::Handle<reco::TrackCollection> ctfTracks = eventData_->originalCtfTracks ;
01174   if (!ctfTracks.isValid()) { ctfTracks = eventData_->currentCtfTracks ; }
01175 
01176   // values of conversionInfo.flag()
01177   // -9999 : Partner track was not found
01178   // 0     : Partner track found in the CTF collection using
01179   // 1     : Partner track found in the CTF collection using
01180   // 2     : Partner track found in the GSF collection using
01181   // 3     : Partner track found in the GSF collection using the electron's GSF track
01182   ConversionInfo conversionInfo = conversionFinder.getConversionInfo
01183    (*electronData_->coreRef,ctfTracks,eventData_->originalGsfTracks,BInTesla) ;
01184 
01185   reco::GsfElectron::ConversionRejection conversionVars ;
01186   conversionVars.flags = conversionInfo.flag()  ;
01187   conversionVars.dist = conversionInfo.dist()  ;
01188   conversionVars.dcot = conversionInfo.dcot()  ;
01189   conversionVars.radius = conversionInfo.radiusOfConversion()  ;
01190   if ((conversionVars.flags==0)or(conversionVars.flags==1))
01191     conversionVars.partner = TrackBaseRef(conversionInfo.conversionPartnerCtfTk())  ;
01192   else if ((conversionVars.flags==2)or(conversionVars.flags==3))
01193     conversionVars.partner = TrackBaseRef(conversionInfo.conversionPartnerGsfTk())  ;
01194 
01195 
01196   //====================================================
01197   // Go !
01198   //====================================================
01199 
01200   GsfElectron * ele = new
01201     GsfElectron
01202      ( eleCharge,eleChargeInfo,electronData_->coreRef,
01203        tcMatching, tkExtra, ctfInfo,
01204        fiducialFlags,showerShape,
01205        conversionVars ) ;
01206   ele->setCorrectedEcalEnergyError(generalData_->superClusterErrorFunction->getValue(*(ele->superCluster()),0)) ;
01207   ele->setP4(GsfElectron::P4_FROM_SUPER_CLUSTER,momentum,0,true) ;
01208 
01209 
01210   //====================================================
01211   // brems fractions
01212   //====================================================
01213 
01214   if (electronData_->innMom.mag()>0.)
01215    { ele->setTrackFbrem((electronData_->innMom.mag()-electronData_->outMom.mag())/electronData_->innMom.mag()) ; }
01216 
01217   SuperClusterRef sc = ele->superCluster() ;
01218   if (!(sc.isNull()))
01219    {
01220     CaloClusterPtr cl = ele->electronCluster() ;
01221     if (sc->clustersSize()>1)
01222      { ele->setSuperClusterFbrem( ( sc->energy() - cl->energy() ) / sc->energy() ) ; }
01223     else
01224      { ele->setSuperClusterFbrem(0) ; }
01225    }
01226 
01227 
01228   //====================================================
01229   // classification and corrections
01230   //====================================================
01231 
01232   // classification
01233   ElectronClassification theClassifier ;
01234   theClassifier.classify(*ele) ;
01235 
01236   // ecal energy
01237   ElectronEnergyCorrector theEnCorrector(generalData_->crackCorrectionFunction) ;
01238   if (ele->core()->ecalDrivenSeed())
01239    {
01240     if (generalData_->strategyCfg.ecalDrivenEcalEnergyFromClassBasedParameterization)
01241      { theEnCorrector.classBasedParameterizationEnergy(*ele,*eventData_->beamspot) ; }
01242     if (generalData_->strategyCfg.ecalDrivenEcalErrorFromClassBasedParameterization)
01243      { theEnCorrector.classBasedParameterizationUncertainty(*ele) ; }
01244    }
01245   else
01246    {
01247     if (generalData_->strategyCfg.pureTrackerDrivenEcalErrorFromSimpleParameterization)
01248      { theEnCorrector.simpleParameterizationUncertainty(*ele) ; }
01249    }
01250 
01251   // momentum
01252   if (ele->core()->ecalDrivenSeed())
01253    {
01254     ElectronMomentumCorrector theMomCorrector;
01255     theMomCorrector.correct(*ele,electronData_->vtxTSOS);
01256    }
01257 
01258 
01259   //====================================================
01260   // now isolation variables
01261   //====================================================
01262 
01263   reco::GsfElectron::IsolationVariables dr03, dr04 ;
01264   dr03.tkSumPt = eventData_->tkIsolation03->getPtTracks(ele);
01265   dr03.hcalDepth1TowerSumEt = eventData_->hadDepth1Isolation03->getTowerEtSum(ele) ;
01266   dr03.hcalDepth2TowerSumEt = eventData_->hadDepth2Isolation03->getTowerEtSum(ele) ;
01267   dr03.hcalDepth1TowerSumEtBc = eventData_->hadDepth1Isolation03Bc->getTowerEtSum(ele,&(showerShape.hcalTowersBehindClusters)) ;
01268   dr03.hcalDepth2TowerSumEtBc = eventData_->hadDepth2Isolation03Bc->getTowerEtSum(ele,&(showerShape.hcalTowersBehindClusters)) ;
01269   dr03.ecalRecHitSumEt = eventData_->ecalBarrelIsol03->getEtSum(ele)+eventData_->ecalEndcapIsol03->getEtSum(ele);
01270   dr04.tkSumPt = eventData_->tkIsolation04->getPtTracks(ele);
01271   dr04.hcalDepth1TowerSumEt = eventData_->hadDepth1Isolation04->getTowerEtSum(ele);
01272   dr04.hcalDepth2TowerSumEt = eventData_->hadDepth2Isolation04->getTowerEtSum(ele);
01273   dr04.hcalDepth1TowerSumEtBc = eventData_->hadDepth1Isolation04Bc->getTowerEtSum(ele,&(showerShape.hcalTowersBehindClusters)) ;
01274   dr04.hcalDepth2TowerSumEtBc = eventData_->hadDepth2Isolation04Bc->getTowerEtSum(ele,&(showerShape.hcalTowersBehindClusters)) ;
01275   dr04.ecalRecHitSumEt = eventData_->ecalBarrelIsol04->getEtSum(ele)+eventData_->ecalEndcapIsol04->getEtSum(ele);
01276   ele->setIsolation03(dr03);
01277   ele->setIsolation04(dr04);
01278 
01279 
01280   //====================================================
01281   // preselection flag
01282   //====================================================
01283 
01284   setCutBasedPreselectionFlag(ele,*eventData_->beamspot) ;
01285 
01286   LogTrace("GsfElectronAlgo")<<"Constructed new electron with energy  "<< ele->p4().e() ;
01287 
01288   eventData_->electrons->push_back(ele) ;
01289  }
01290 
01291 
01292 //=======================================================================================
01293 // Ambiguity solving
01294 //=======================================================================================
01295 
01296 //bool better_electron( const reco::GsfElectron * e1, const reco::GsfElectron * e2 )
01297 // { return (std::abs(e1->eSuperClusterOverP()-1)<std::abs(e2->eSuperClusterOverP()-1)) ; }
01298 
01299 void GsfElectronAlgo::setAmbiguityData( bool ignoreNotPreselected )
01300  {
01301   GsfElectronPtrCollection::iterator e1, e2 ;
01302   if (generalData_->strategyCfg.ambSortingStrategy==0)
01303    { eventData_->electrons->sort(EgAmbiguityTools::isBetter) ; }
01304   else if (generalData_->strategyCfg.ambSortingStrategy==1)
01305    { eventData_->electrons->sort(EgAmbiguityTools::isInnerMost(eventSetupData_->trackerHandle)) ; }
01306   else
01307    { throw cms::Exception("GsfElectronAlgo|UnknownAmbiguitySortingStrategy")<<"value of generalData_->strategyCfg.ambSortingStrategy is : "<<generalData_->strategyCfg.ambSortingStrategy ; }
01308 
01309   // init
01310   for
01311    ( e1 = eventData_->electrons->begin() ;
01312      e1 != eventData_->electrons->end() ;
01313      ++e1 )
01314    {
01315     (*e1)->clearAmbiguousGsfTracks() ;
01316     (*e1)->setAmbiguous(false) ;
01317    }
01318 
01319   // get ambiguous from GsfPfRecTracks
01320   if (generalData_->strategyCfg.useGsfPfRecTracks)
01321    {
01322     for
01323      ( e1 = eventData_->electrons->begin() ;
01324        e1 != eventData_->electrons->end() ;
01325        ++e1 )
01326      {
01327       bool found = false ;
01328       const GsfPFRecTrackCollection * gsfPfRecTrackCollection = eventData_->gsfPfRecTracks.product() ;
01329       GsfPFRecTrackCollection::const_iterator gsfPfRecTrack ;
01330       for ( gsfPfRecTrack=gsfPfRecTrackCollection->begin() ;
01331             gsfPfRecTrack!=gsfPfRecTrackCollection->end() ;
01332             ++gsfPfRecTrack )
01333        {
01334         if (gsfPfRecTrack->gsfTrackRef()==(*e1)->gsfTrack())
01335          {
01336           if (found)
01337            {
01338             edm::LogWarning("GsfElectronAlgo")<<"associated gsfPfRecTrack already found" ;
01339            }
01340           else
01341            {
01342             found = true ;
01343             const std::vector<reco::GsfPFRecTrackRef> & duplicates(gsfPfRecTrack->convBremGsfPFRecTrackRef()) ;
01344             std::vector<reco::GsfPFRecTrackRef>::const_iterator duplicate ;
01345             for ( duplicate = duplicates.begin() ; duplicate != duplicates.end() ; duplicate ++ )
01346              { (*e1)->addAmbiguousGsfTrack((*duplicate)->gsfTrackRef()) ; }
01347            }
01348          }
01349        }
01350      }
01351    }
01352   // or search overlapping clusters
01353   else
01354    {
01355     for
01356      ( e1 = eventData_->electrons->begin() ;
01357        e1 != eventData_->electrons->end() ;
01358        ++e1 )
01359      {
01360       if ((*e1)->ambiguous()) continue ;
01361       if ( ignoreNotPreselected && !isPreselected(*e1) ) continue ;
01362 
01363       SuperClusterRef scRef1 = (*e1)->superCluster();
01364       CaloClusterPtr eleClu1 = (*e1)->electronCluster();
01365       LogDebug("GsfElectronAlgo")
01366         << "Blessing electron with E/P " << (*e1)->eSuperClusterOverP()
01367         << ", cluster " << scRef1.get()
01368         << " & track " << (*e1)->gsfTrack().get() ;
01369 
01370       for
01371        ( e2 = e1, ++e2 ;
01372          e2 != eventData_->electrons->end() ;
01373          ++e2 )
01374        {
01375         if ((*e2)->ambiguous()) continue ;
01376         if ( ignoreNotPreselected && !isPreselected(*e2) ) continue ;
01377 
01378         SuperClusterRef scRef2 = (*e2)->superCluster();
01379         CaloClusterPtr eleClu2 = (*e2)->electronCluster();
01380 
01381         // search if same cluster
01382         bool sameCluster = false ;
01383         if (generalData_->strategyCfg.ambClustersOverlapStrategy==0)
01384          { sameCluster = (scRef1==scRef2) ; }
01385         else if (generalData_->strategyCfg.ambClustersOverlapStrategy==1)
01386          {
01387           float eMin = 1. ;
01388           float threshold = eMin*cosh(EleRelPoint(scRef1->position(),eventData_->beamspot->position()).eta()) ;
01389           sameCluster =
01390            ( (EgAmbiguityTools::sharedEnergy(&(*eleClu1),&(*eleClu2),eventData_->barrelRecHits,eventData_->endcapRecHits)>=threshold) ||
01391              (EgAmbiguityTools::sharedEnergy(&(*scRef1->seed()),&(*eleClu2),eventData_->barrelRecHits,eventData_->endcapRecHits)>=threshold) ||
01392              (EgAmbiguityTools::sharedEnergy(&(*eleClu1),&(*scRef2->seed()),eventData_->barrelRecHits,eventData_->endcapRecHits)>=threshold) ||
01393              (EgAmbiguityTools::sharedEnergy(&(*scRef1->seed()),&(*scRef2->seed()),eventData_->barrelRecHits,eventData_->endcapRecHits)>=threshold) ) ;
01394          }
01395         else
01396          { throw cms::Exception("GsfElectronAlgo|UnknownAmbiguityClustersOverlapStrategy")<<"value of generalData_->strategyCfg.ambClustersOverlapStrategy is : "<<generalData_->strategyCfg.ambClustersOverlapStrategy ; }
01397 
01398         // main instructions
01399         if (sameCluster)
01400          {
01401           LogDebug("GsfElectronAlgo")
01402             << "Discarding electron with E/P " << (*e2)->eSuperClusterOverP()
01403             << ", cluster " << scRef2.get()
01404             << " and track " << (*e2)->gsfTrack().get() ;
01405           (*e1)->addAmbiguousGsfTrack((*e2)->gsfTrack()) ;
01406           (*e2)->setAmbiguous(true) ;
01407          }
01408         else if ((*e1)->gsfTrack()==(*e2)->gsfTrack())
01409          {
01410           edm::LogWarning("GsfElectronAlgo")
01411             << "Forgetting electron with E/P " << (*e2)->eSuperClusterOverP()
01412             << ", cluster " << scRef2.get()
01413             << " and track " << (*e2)->gsfTrack().get() ;
01414           (*e2)->setAmbiguous(true) ;
01415          }
01416        }
01417      }
01418    }
01419  }
01420 
01421 void GsfElectronAlgo::removeAmbiguousElectrons()
01422  {
01423   GsfElectronPtrCollection::size_type ei = 1, emax = eventData_->electrons->size() ;
01424   GsfElectronPtrCollection::iterator eitr = eventData_->electrons->begin() ;
01425   while (eitr!=eventData_->electrons->end())
01426    {
01427     LogTrace("GsfElectronAlgo")<<"========== remove ambiguous "<<ei<<"/"<<emax<<"==========" ;
01428     if ((*eitr)->ambiguous())
01429      { delete (*eitr) ; eitr = eventData_->electrons->erase(eitr) ; ++ei ; }
01430     else
01431      { ++eitr ; ++ei ; }
01432    }
01433  }
01434 
01435