CMS 3D CMS Logo

/data/refman/pasoursint/CMSSW_5_3_10_patch1/src/RecoEgamma/EgammaPhotonProducers/src/TrackProducerWithSCAssociation.cc

Go to the documentation of this file.
00001 #include "RecoEgamma/EgammaPhotonProducers/interface/TrackProducerWithSCAssociation.h"
00002 // system include files
00003 #include <memory>
00004 // user include files
00005 #include "FWCore/Framework/interface/Frameworkfwd.h"
00006 #include "FWCore/Framework/interface/MakerMacros.h"
00007 #include "FWCore/MessageLogger/interface/MessageLogger.h"
00008 #include "TrackingTools/GeomPropagators/interface/Propagator.h"
00009 #include "TrackingTools/PatternTools/interface/Trajectory.h"
00010 #include "TrackingTools/TrackFitters/interface/TrajectoryFitter.h"
00011 #include "TrackingTools/PatternTools/interface/TrajTrackAssociation.h"
00012 #include "TrackingTools/TrajectoryState/interface/TrajectoryStateTransform.h"
00013 #include "TrackingTools/TransientTrackingRecHit/interface/TransientTrackingRecHitBuilder.h"
00014 #include "RecoTracker/TrackProducer/interface/TrackProducerBase.h"
00015 #include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h"
00016 #include "DataFormats/EgammaTrackReco/interface/TrackCandidateCaloClusterAssociation.h"
00017 #include "DataFormats/EgammaTrackReco/interface/TrackCaloClusterAssociation.h"
00018 #include "DataFormats/CaloRecHit/interface/CaloCluster.h"
00019 
00020 TrackProducerWithSCAssociation::TrackProducerWithSCAssociation(const edm::ParameterSet& iConfig):
00021   TrackProducerBase<reco::Track>(iConfig.getParameter<bool>("TrajectoryInEvent")),
00022   theAlgo(iConfig)
00023 {
00024   setConf(iConfig);
00025   setSrc( iConfig.getParameter<edm::InputTag>( "src" ), 
00026   iConfig.getParameter<edm::InputTag>( "beamSpot" ));
00027   setAlias( iConfig.getParameter<std::string>( "@module_label" ) );
00028 
00029   if ( iConfig.exists("clusterRemovalInfo") ) {
00030     edm::InputTag tag = iConfig.getParameter<edm::InputTag>("clusterRemovalInfo");
00031     if (!(tag == edm::InputTag())) { setClusterRemovalInfo( tag ); }
00032   }
00033 
00034   
00035   myname_ = iConfig.getParameter<std::string>("ComponentName");
00036   conversionTrackCandidateProducer_ = iConfig.getParameter<std::string>("producer");
00037   trackCSuperClusterAssociationCollection_ = iConfig.getParameter<std::string>("trackCandidateSCAssociationCollection");
00038   trackSuperClusterAssociationCollection_ = iConfig.getParameter<std::string>("recoTrackSCAssociationCollection");
00039   myTrajectoryInEvent_ = iConfig.getParameter<bool>("TrajectoryInEvent");
00040 
00041  
00042   //register your products
00043   produces<reco::TrackCollection>().setBranchAlias( alias_ + "Tracks" );
00044   produces<reco::TrackExtraCollection>().setBranchAlias( alias_ + "TrackExtras" );
00045   produces<TrackingRecHitCollection>().setBranchAlias( alias_ + "RecHits" );
00046   produces<std::vector<Trajectory> >() ;
00047   produces<TrajTrackAssociationCollection>();
00048   //  produces< reco::TrackSuperClusterAssociationCollection > (trackSuperClusterAssociationCollection_ );
00049   produces< reco::TrackCaloClusterPtrAssociation > (trackSuperClusterAssociationCollection_ );
00050 
00051 }
00052 
00053 
00054 void TrackProducerWithSCAssociation::produce(edm::Event& theEvent, const edm::EventSetup& setup)
00055 {
00056   //edm::LogInfo("TrackProducerWithSCAssociation") << "Analyzing event number: " << theEvent.id() << "\n";
00057 
00058   //LogDebug("TrackProducerWithSCAssociation") << "Analyzing event number: " << theEvent.id() << "\n";
00059   //  std::cout << " TrackProducerWithSCAssociation Analyzing event number: " << theEvent.id() << "\n";
00060 
00061 
00062   //
00063   // create empty output collections
00064   //
00065   std::auto_ptr<TrackingRecHitCollection>    outputRHColl (new TrackingRecHitCollection);
00066   std::auto_ptr<reco::TrackCollection>       outputTColl(new reco::TrackCollection);
00067   std::auto_ptr<reco::TrackExtraCollection>  outputTEColl(new reco::TrackExtraCollection);
00068   std::auto_ptr<std::vector<Trajectory> >    outputTrajectoryColl(new std::vector<Trajectory>);
00069   //   Reco Track - Super Cluster Association
00070   std::auto_ptr<reco::TrackCaloClusterPtrAssociation> scTrkAssoc_p(new reco::TrackCaloClusterPtrAssociation);
00071 
00072   //
00073   //declare and get stuff to be retrieved from ES
00074   //
00075   edm::ESHandle<TrackerGeometry> theG;
00076   edm::ESHandle<MagneticField> theMF;
00077   edm::ESHandle<TrajectoryFitter> theFitter;
00078   edm::ESHandle<Propagator> thePropagator;
00079   edm::ESHandle<TransientTrackingRecHitBuilder> theBuilder;
00080   edm::ESHandle<MeasurementTracker> theMeasTk;
00081   getFromES(setup,theG,theMF,theFitter,thePropagator,theMeasTk,theBuilder);
00082 
00083  
00084 
00085   //
00086   //declare and get TrackColection to be retrieved from the event
00087   edm::Handle<TrackCandidateCollection> theTCCollection;
00089   validTrackCandidateSCAssociationInput_=true;
00090   edm::Handle<reco::TrackCandidateCaloClusterPtrAssociation> trkCandidateSCAssocHandle;
00091   theEvent.getByLabel(conversionTrackCandidateProducer_, trackCSuperClusterAssociationCollection_ , trkCandidateSCAssocHandle);
00092   if ( !trkCandidateSCAssocHandle.isValid() ) {
00093     //    std::cout << "Error! Can't get the product  "<<trackCSuperClusterAssociationCollection_.c_str() << " but keep running. Empty collection will be produced " << "\n";
00094     edm::LogError("TrackProducerWithSCAssociation") << "Error! Can't get the product  "<<trackCSuperClusterAssociationCollection_.c_str() << " but keep running. Empty collection will be produced " << "\n";
00095     validTrackCandidateSCAssociationInput_=false;
00096   }
00097   reco::TrackCandidateCaloClusterPtrAssociation scTrkCandAssCollection = *(trkCandidateSCAssocHandle.product());
00098   if ( scTrkCandAssCollection.size() ==0 )  validTrackCandidateSCAssociationInput_=false;
00099 
00100 
00101   std::vector<int> tccLocations;
00102   AlgoProductCollection algoResults;
00103   reco::BeamSpot bs;
00104   
00105    
00106  getFromEvt(theEvent,theTCCollection,bs);  
00107   
00108   if (theTCCollection.failedToGet()){
00109     edm::LogError("TrackProducerWithSCAssociation")  <<"TrackProducerWithSCAssociation could not get the TrackCandidateCollection.";} 
00110   else{
00111     //
00112     //run the algorithm  
00113     //
00114     //  LogDebug("TrackProducerWithSCAssociation") << "TrackProducerWithSCAssociation run the algorithm" << "\n";
00115     //    theAlgo.runWithCandidate(theG.product(), theMF.product(), *theTCCollection, 
00116     //                       theFitter.product(), thePropagator.product(), theBuilder.product(), algoResults);
00117     // we have to copy this method from the algo in order to get the association track-seed
00118     // this is ugly temporary code that should be replaced!!!!!
00119     // start of copied code ======================================================
00120   
00121     //    std::cout << "TrackProducerWithSCAssociation  Number of TrackCandidates: " << theTCCollection->size() << "\n";
00122     try{  
00123       int cont = 0;
00124       int tcc=0;
00125    
00126       for (TrackCandidateCollection::const_iterator i=theTCCollection->begin(); i!=theTCCollection->end();i++)
00127         {
00128           
00129           const TrackCandidate * theTC = &(*i);
00130           PTrajectoryStateOnDet state = theTC->trajectoryStateOnDet();
00131           const TrackCandidate::range& recHitVec=theTC->recHits();
00132           const TrajectorySeed& seed = theTC->seed();
00133           
00134           //convert PTrajectoryStateOnDet to TrajectoryStateOnSurface
00135           
00136           
00137           DetId  detId(state.detId());
00138           TrajectoryStateOnSurface theTSOS = trajectoryStateTransform::transientState( state,
00139                                                                          &(theG.product()->idToDet(detId)->surface()), 
00140                                                                          theMF.product());
00141           
00142           //LogDebug("TrackProducerWithSCAssociation")  << "TrackProducerWithSCAssociation  Initial TSOS\n" << theTSOS << "\n";
00143           
00144           //convert the TrackingRecHit vector to a TransientTrackingRecHit vector
00145           //meanwhile computes the number of degrees of freedom
00146           TransientTrackingRecHit::RecHitContainer hits;
00147           
00148           float ndof=0;
00149           
00150           for (edm::OwnVector<TrackingRecHit>::const_iterator i=recHitVec.first;
00151                i!=recHitVec.second; i++){
00152             hits.push_back(theBuilder.product()->build(&(*i) ));
00153           }
00154 
00155           
00156           //build Track
00157           // LogDebug("TrackProducerWithSCAssociation") << "TrackProducerWithSCAssociation going to buildTrack"<< "\n";
00158           bool ok = theAlgo.buildTrack(theFitter.product(),thePropagator.product(),algoResults, hits, theTSOS, seed, ndof, bs, theTC->seedRef());
00159           // LogDebug("TrackProducerWithSCAssociation")  << "TrackProducerWithSCAssociation buildTrack result: " << ok << "\n";
00160           if(ok) {
00161             cont++;
00162             tccLocations.push_back(tcc);
00163           }
00164           tcc++;
00165         }
00166       edm::LogInfo("TrackProducerWithSCAssociation") << "Number of Tracks found: " << cont << "\n";
00167       //LogDebug("TrackProducerWithSCAssociation") << "TrackProducerWithSCAssociation Number of Tracks found: " << cont << "\n";
00168       // end of copied code ======================================================
00169       
00170     } catch (cms::Exception &e){ edm::LogInfo("TrackProducerWithSCAssociation") << "cms::Exception caught!!!" << "\n" << e << "\n";}
00171     //
00172     //put everything in the event
00173     // we copy putInEvt to get OrphanHandle filled...
00174     putInEvt(theEvent,thePropagator.product(),theMeasTk.product(), 
00175              outputRHColl, outputTColl, outputTEColl, outputTrajectoryColl, algoResults);
00176     
00177     // now construct associationmap and put it in the  event
00178     if (  validTrackCandidateSCAssociationInput_ ) {    
00179       int itrack=0;
00180       std::vector<edm::Ptr<reco::CaloCluster> > caloPtrVec;
00181       for(AlgoProductCollection::iterator i=algoResults.begin(); i!=algoResults.end();i++){
00182         edm::Ref<TrackCandidateCollection> trackCRef(theTCCollection,tccLocations[itrack]);
00183         const edm::Ptr<reco::CaloCluster>&  aClus = (*trkCandidateSCAssocHandle)[trackCRef];
00184         caloPtrVec.push_back( aClus );
00185         itrack++;
00186       }
00187       
00188       
00189       edm::ValueMap<reco::CaloClusterPtr>::Filler filler(*scTrkAssoc_p);
00190       filler.insert(rTracks_, caloPtrVec.begin(), caloPtrVec.end());
00191       filler.fill();
00192     }    
00193     
00194     theEvent.put(scTrkAssoc_p,trackSuperClusterAssociationCollection_ ); 
00195     
00196   }
00197 
00198 }  
00199   
00200 std::vector<reco::TransientTrack> TrackProducerWithSCAssociation::getTransient(edm::Event& theEvent, const edm::EventSetup& setup)
00201 {
00202   edm::LogInfo("TrackProducerWithSCAssociation") << "Analyzing event number: " << theEvent.id() << "\n";
00203   //
00204   // create empty output collections
00205   //
00206   std::vector<reco::TransientTrack> ttks;
00207 
00208   //
00209   //declare and get stuff to be retrieved from ES
00210   //
00211   edm::ESHandle<TrackerGeometry> theG;
00212   edm::ESHandle<MagneticField> theMF;
00213   edm::ESHandle<TrajectoryFitter> theFitter;
00214   edm::ESHandle<Propagator> thePropagator;
00215   edm::ESHandle<TransientTrackingRecHitBuilder> theBuilder;
00216   edm::ESHandle<MeasurementTracker> theMeasTk;
00217   getFromES(setup,theG,theMF,theFitter,thePropagator,theMeasTk,theBuilder);
00218 
00219   //
00220   //declare and get TrackColection to be retrieved from the event
00221   //
00222   AlgoProductCollection algoResults;
00223   reco::BeamSpot bs;
00224  
00225   try{  
00226     edm::Handle<TrackCandidateCollection> theTCCollection;
00227     getFromEvt(theEvent,theTCCollection,bs);
00228     
00229     //
00230     //run the algorithm  
00231     //
00232     //LogDebug("TrackProducerWithSCAssociation") << "TrackProducerWithSCAssociation run the algorithm" << "\n";
00233    theAlgo.runWithCandidate(theG.product(), theMF.product(), *theTCCollection, 
00234                                theFitter.product(), thePropagator.product(), theBuilder.product(), bs, algoResults);
00235 
00236   } catch (cms::Exception &e){ edm::LogInfo("TrackProducerWithSCAssociation") << "cms::Exception caught!!!" << "\n" << e << "\n";}
00237 
00238 
00239   for (AlgoProductCollection::iterator prod=algoResults.begin();prod!=algoResults.end(); prod++){
00240     ttks.push_back( reco::TransientTrack(*(((*prod).second).first),thePropagator.product()->magneticField() ));
00241   }
00242 
00243   //LogDebug("TrackProducerWithSCAssociation") << "TrackProducerWithSCAssociation end" << "\n";
00244 
00245   return ttks;
00246 }
00247 
00248 
00249 
00250 
00251  void TrackProducerWithSCAssociation::putInEvt(edm::Event& evt,
00252                                                const Propagator* thePropagator,
00253                                                const MeasurementTracker* theMeasTk,
00254                                                std::auto_ptr<TrackingRecHitCollection>& selHits,
00255                                                std::auto_ptr<reco::TrackCollection>& selTracks,
00256                                                std::auto_ptr<reco::TrackExtraCollection>& selTrackExtras,
00257                                                std::auto_ptr<std::vector<Trajectory> >&   selTrajectories,
00258                                                AlgoProductCollection& algoResults)
00259 {
00260 
00261 TrackingRecHitRefProd rHits = evt.getRefBeforePut<TrackingRecHitCollection>();
00262   reco::TrackExtraRefProd rTrackExtras = evt.getRefBeforePut<reco::TrackExtraCollection>();
00263 
00264   edm::Ref<reco::TrackExtraCollection>::key_type idx = 0;
00265   edm::Ref<reco::TrackExtraCollection>::key_type hidx = 0;
00266   edm::Ref<reco::TrackCollection>::key_type iTkRef = 0;
00267   edm::Ref< std::vector<Trajectory> >::key_type iTjRef = 0;
00268   std::map<unsigned int, unsigned int> tjTkMap;
00269 
00270   for(AlgoProductCollection::iterator i=algoResults.begin(); i!=algoResults.end();i++){
00271     Trajectory * theTraj = (*i).first;
00272     if(myTrajectoryInEvent_) {
00273       selTrajectories->push_back(*theTraj);
00274       iTjRef++;
00275     }
00276     const TrajectoryFitter::RecHitContainer& transHits = theTraj->recHits();
00277     
00278     reco::Track * theTrack = (*i).second.first;
00279     PropagationDirection seedDir = (*i).second.second;
00280     
00281     //LogDebug("TrackProducer") << "In KfTrackProducerBase::putInEvt - seedDir=" << seedDir;
00282     
00283     reco::Track t = * theTrack;
00284     selTracks->push_back( t );
00285     iTkRef++;
00286     
00287     // Store indices in local map (starts at 0)
00288     if(trajectoryInEvent_) tjTkMap[iTjRef-1] = iTkRef-1;
00289     
00290     //sets the outermost and innermost TSOSs
00291     
00292     TrajectoryStateOnSurface outertsos;
00293     TrajectoryStateOnSurface innertsos;
00294     unsigned int innerId, outerId;
00295 
00296     // ---  NOTA BENE: the convention is to sort hits and measurements "along the momentum".
00297     // This is consistent with innermost and outermost labels only for tracks from LHC collision
00298     if (theTraj->direction() == alongMomentum) {
00299       outertsos = theTraj->lastMeasurement().updatedState();
00300       innertsos = theTraj->firstMeasurement().updatedState();
00301       outerId = theTraj->lastMeasurement().recHit()->geographicalId().rawId();
00302       innerId = theTraj->firstMeasurement().recHit()->geographicalId().rawId();
00303     } else {
00304       outertsos = theTraj->firstMeasurement().updatedState();
00305       innertsos = theTraj->lastMeasurement().updatedState();
00306       outerId = theTraj->firstMeasurement().recHit()->geographicalId().rawId();
00307       innerId = theTraj->lastMeasurement().recHit()->geographicalId().rawId();
00308     }
00309     // ---
00310     //build the TrackExtra
00311     GlobalPoint v = outertsos.globalParameters().position();
00312     GlobalVector p = outertsos.globalParameters().momentum();
00313     math::XYZVector outmom( p.x(), p.y(), p.z() );
00314     math::XYZPoint  outpos( v.x(), v.y(), v.z() );
00315     v = innertsos.globalParameters().position();
00316     p = innertsos.globalParameters().momentum();
00317     math::XYZVector inmom( p.x(), p.y(), p.z() );
00318     math::XYZPoint  inpos( v.x(), v.y(), v.z() );
00319 
00320     reco::TrackExtraRef teref= reco::TrackExtraRef ( rTrackExtras, idx ++ );
00321     reco::Track & track = selTracks->back();
00322     track.setExtra( teref );
00323 
00324     //======= I want to set the second hitPattern here =============
00325     if (theSchool.isValid())
00326       {
00327         NavigationSetter setter( *theSchool );
00328         setSecondHitPattern(theTraj,track,thePropagator,theMeasTk);
00329       }
00330     //==============================================================
00331 
00332 
00333     selTrackExtras->push_back( reco::TrackExtra (outpos, outmom, true, inpos, inmom, true,
00334                                                  outertsos.curvilinearError(), outerId,
00335                                                  innertsos.curvilinearError(), innerId,
00336                                                  seedDir,theTraj->seedRef()));
00337 
00338 
00339     reco::TrackExtra & tx = selTrackExtras->back();
00340    // ---  NOTA BENE: the convention is to sort hits and measurements "along the momentum".
00341     // This is consistent with innermost and outermost labels only for tracks from LHC collisions
00342     size_t k = 0;
00343     if (theTraj->direction() == alongMomentum) {
00344       for( TrajectoryFitter::RecHitContainer::const_iterator j = transHits.begin();
00345            j != transHits.end(); j ++ ) {
00346         if ((**j).hit()!=0){
00347           TrackingRecHit * hit = (**j).hit()->clone();
00348           track.setHitPattern( * hit, k++ );
00349           selHits->push_back( hit );
00350           tx.add( TrackingRecHitRef( rHits, hidx ++ ) );
00351         }
00352       }
00353     }else{
00354       for( TrajectoryFitter::RecHitContainer::const_iterator j = transHits.end()-1;
00355            j != transHits.begin()-1; --j ) {
00356         if ((**j).hit()!=0){
00357           TrackingRecHit * hit = (**j).hit()->clone();
00358           track.setHitPattern( * hit, k++ );
00359           selHits->push_back( hit );
00360         tx.add( TrackingRecHitRef( rHits, hidx ++ ) );
00361         }
00362       }
00363     }
00364     // ----
00365 
00366     delete theTrack;
00367     delete theTraj;
00368   }
00369 
00370   //LogTrace("TrackingRegressionTest") << "========== TrackProducer Info ===================";
00371   //LogDebug("TrackProducerWithSCAssociation") << "number of finalTracks: " << selTracks->size() << std::endl;
00372   //for (reco::TrackCollection::const_iterator it = selTracks->begin(); it != selTracks->end(); it++) {
00373     //LogDebug("TrackProducerWithSCAssociation")  << "track's n valid and invalid hit, chi2, pt : "
00374     //                                  << it->found() << " , "
00375     //                                  << it->lost()  <<" , "
00376     //                                  << it->normalizedChi2() << " , "
00377     //         << it->pt() << std::endl;
00378   // }
00379   //LogTrace("TrackingRegressionTest") << "=================================================";
00380 
00381 
00382   rTracks_ = evt.put( selTracks );
00383 
00384 
00385   evt.put( selTrackExtras );
00386   evt.put( selHits );
00387   
00388   if(myTrajectoryInEvent_) {
00389     edm::OrphanHandle<std::vector<Trajectory> > rTrajs = evt.put(selTrajectories);
00390     
00391     // Now Create traj<->tracks association map
00392     std::auto_ptr<TrajTrackAssociationCollection> trajTrackMap( new TrajTrackAssociationCollection() );
00393     for ( std::map<unsigned int, unsigned int>::iterator i = tjTkMap.begin();
00394           i != tjTkMap.end(); i++ ) {
00395       edm::Ref<std::vector<Trajectory> > trajRef( rTrajs, (*i).first );
00396       edm::Ref<reco::TrackCollection>    tkRef( rTracks_, (*i).second );
00397       trajTrackMap->insert( edm::Ref<std::vector<Trajectory> >( rTrajs, (*i).first ),
00398                             edm::Ref<reco::TrackCollection>( rTracks_, (*i).second ) );
00399     }
00400     evt.put( trajTrackMap );
00401   }
00402 
00403 
00404 
00405 
00406 
00407 
00408 }