CMS 3D CMS Logo

/data/refman/pasoursint/CMSSW_5_3_6/src/RecoTracker/FinalTrackSelectors/src/CosmicTrackSplitter.cc

Go to the documentation of this file.
00001 #include "FWCore/Framework/interface/EDProducer.h"
00002 #include "FWCore/Framework/interface/Event.h"
00003 #include "FWCore/Framework/interface/EventSetup.h"
00004 #include "FWCore/Framework/interface/ESHandle.h"
00005 
00006 #include "FWCore/ParameterSet/interface/ParameterSet.h"
00007 #include "FWCore/Utilities/interface/InputTag.h"
00008 
00009 #include "DataFormats/Common/interface/View.h"
00010 #include "DataFormats/TrackReco/interface/TrackFwd.h"
00011 #include "DataFormats/TrackReco/interface/Track.h"
00012 #include "DataFormats/TrackCandidate/interface/TrackCandidateCollection.h"
00013 #include "DataFormats/TrackingRecHit/interface/InvalidTrackingRecHit.h"
00014 
00015 #include "Geometry/Records/interface/TrackerDigiGeometryRecord.h"
00016 #include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h"
00017 #include "MagneticField/Engine/interface/MagneticField.h"
00018 #include "MagneticField/Records/interface/IdealMagneticFieldRecord.h"
00019 #include "TrackingTools/TrajectoryState/interface/TrajectoryStateTransform.h"
00020 #include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h"
00021 
00022 #include "DataFormats/SiPixelDetId/interface/PXBDetId.h"
00023 #include "DataFormats/SiPixelDetId/interface/PXBDetId.h"
00024 #include "DataFormats/SiPixelDetId/interface/PXFDetId.h"
00025 #include "DataFormats/SiStripDetId/interface/TIBDetId.h"
00026 #include "DataFormats/SiStripDetId/interface/TIDDetId.h"
00027 #include "DataFormats/SiStripDetId/interface/TOBDetId.h"
00028 #include "DataFormats/SiStripDetId/interface/TECDetId.h"
00029 
00030 // added by me
00031 
00032 #include "Geometry/CommonDetUnit/interface/TrackingGeometry.h"
00033 #include "Geometry/CommonDetUnit/interface/GeomDetUnit.h"
00034 #include "DataFormats/GeometrySurface/interface/Surface.h"
00035 #include "DataFormats/GeometrySurface/interface/GloballyPositioned.h"
00036 #include "TrackingTools/TransientTrack/interface/TransientTrack.h"
00037 #include "TrackingTools/TrajectoryState/interface/FreeTrajectoryState.h"
00038 
00039 #include "TrackingTools/TrajectoryState/interface/FreeTrajectoryState.h" 
00040 #include "DataFormats/GeometrySurface/interface/Surface.h" 
00041 #include "DataFormats/Math/interface/Vector.h" 
00042 #include "DataFormats/Math/interface/Error.h" 
00043 #include "TrackingTools/TrajectoryState/interface/CopyUsingClone.h" 
00044 #include "RecoVertex/VertexTools/interface/PerigeeLinearizedTrackState.h" 
00045 
00046 #include "TrackingTools/TransientTrack/interface/TransientTrack.h"
00047 
00048 #include "DataFormats/GeometryCommonDetAlgo/interface/ErrorFrameTransformer.h"
00049 #include "DataFormats/TrackingRecHit/interface/AlignmentPositionError.h"
00050 
00051 #include "MagneticField/Records/interface/IdealMagneticFieldRecord.h" 
00052 
00053 #include "FWCore/Framework/interface/ESHandle.h"
00054 #include "FWCore/MessageLogger/interface/MessageLogger.h"
00055 
00056 
00057 #include "TrackingTools/PatternTools/interface/TrajTrackAssociation.h"
00058 #include "TrackingTools/PatternTools/interface/Trajectory.h"
00059 #include "TrackingTools/TrackFitters/interface/TrajectoryStateCombiner.h"
00060 
00061 
00062 #include <boost/regex.hpp>
00063 
00085 namespace reco { namespace modules {
00086         class CosmicTrackSplitter : public edm::EDProducer {
00087     public:
00088                 CosmicTrackSplitter(const edm::ParameterSet &iConfig) ; 
00089                 virtual void produce(edm::Event &iEvent, const edm::EventSetup &iSetup) ;
00090                 
00091     private:
00092                 edm::InputTag tracks_;
00093                 edm::InputTag tjTag_;
00094                 int totalTracks_;
00095                 size_t minimumHits_;
00096                 
00097                 bool replaceWithInactiveHits_;
00098                 bool stripFrontInvalidHits_;
00099                 bool stripBackInvalidHits_;
00100                 bool stripAllInvalidHits_;
00101                 bool excludePixelHits_;
00102                 
00103                 double dZcut_;
00104                 double dXYcut_;
00105                 
00106                 std::vector<uint32_t> detsToIgnore_;
00107                 
00108                 edm::ESHandle<TrackerGeometry> theGeometry;
00109                 edm::ESHandle<MagneticField>   theMagField;
00110                 
00111                 TrackCandidate makeCandidate(const reco::Track &tk, std::vector<TrackingRecHit *>::iterator hitsBegin, std::vector<TrackingRecHit *>::iterator hitsEnd) ;
00112                 
00113         }; // class
00114         
00115         
00116         CosmicTrackSplitter::CosmicTrackSplitter(const edm::ParameterSet &iConfig) :
00117     tracks_(iConfig.getParameter<edm::InputTag>("tracks")),
00118     tjTag_(iConfig.getParameter<edm::InputTag>("tjTkAssociationMapTag") ),
00119     minimumHits_(iConfig.getParameter<uint32_t>("minimumHits")),
00120     replaceWithInactiveHits_(iConfig.getParameter<bool>("replaceWithInactiveHits")),
00121     stripFrontInvalidHits_(iConfig.getParameter<bool>("stripFrontInvalidHits")),
00122     stripBackInvalidHits_( iConfig.getParameter<bool>("stripBackInvalidHits") ),
00123     stripAllInvalidHits_(  iConfig.getParameter<bool>("stripAllInvalidHits")  ),
00124         excludePixelHits_(  iConfig.getParameter<bool>("excludePixelHits")  ),
00125     dZcut_(iConfig.getParameter<double>("dzCut") ),
00126     dXYcut_(iConfig.getParameter<double>("dxyCut") ),
00127     detsToIgnore_( iConfig.getParameter<std::vector<uint32_t> >("detsToIgnore") )
00128         {
00129                 // sanity check 
00130                 if (stripAllInvalidHits_ && replaceWithInactiveHits_) {
00131                         throw cms::Exception("Configuration") << "Inconsistent Configuration: you can't set both 'stripAllInvalidHits' and 'replaceWithInactiveHits' to true\n";
00132                 }
00133                 
00134                 LogDebug("CosmicTrackSplitter") << "sanity check";
00135                 
00136                 // sort detids to ignore
00137                 std::sort(detsToIgnore_.begin(), detsToIgnore_.end());
00138                 
00139                 totalTracks_ = 0;
00140                 
00141                 // issue the produce<>
00142                 produces<TrackCandidateCollection>();
00143         }
00144         
00145         void 
00146         CosmicTrackSplitter::produce(edm::Event &iEvent, const edm::EventSetup &iSetup) 
00147         {
00148                 LogDebug("CosmicTrackSplitter") << "IN THE SPLITTER!!!!!";
00149                 
00150                 // read with View, so we can read also a TrackRefVector
00151                 edm::Handle<std::vector<reco::Track> > tracks;
00152                 iEvent.getByLabel(tracks_, tracks);
00153                 
00154                 // also need trajectories ...
00155                 // Retrieve trajectories and tracks from the event
00156                 // -> merely skip if collection is empty
00157                 edm::Handle<TrajTrackAssociationCollection> m_TrajTracksMap;
00158                 iEvent.getByLabel( tjTag_, m_TrajTracksMap ); 
00159                 
00160                 // read from EventSetup
00161                 iSetup.get<TrackerDigiGeometryRecord>().get(theGeometry);
00162                 iSetup.get<IdealMagneticFieldRecord>().get(theMagField);
00163                 
00164                 // prepare output collection
00165                 std::auto_ptr<TrackCandidateCollection> output(new TrackCandidateCollection());
00166                 output->reserve(tracks->size());
00167                 
00168                 // working area and tools
00169                 std::vector<TrackingRecHit *> hits;
00170                 
00171                 // Form pairs of trajectories and tracks
00172                 //ConstTrajTrackPairCollection trajTracks;
00173                 LogDebug("CosmicTrackSplitter") << "size of map: " << m_TrajTracksMap->size();
00174                 int HITTOSPLITFROM = 0;
00175                 for ( TrajTrackAssociationCollection::const_iterator iPair = m_TrajTracksMap->begin(); iPair != m_TrajTracksMap->end(); iPair++ ){
00176                         const Trajectory* trajFromMap = &(*(*iPair).key);
00177                         const reco::Track* trackFromMap = &(*(*iPair).val);
00178                         
00179                         // loop to find the hit to split from (by taking dot product of pT and transverse position
00180                         std::vector<TrajectoryMeasurement> measurements = trajFromMap->measurements();
00181                         int totalNumberOfHits = measurements.size();
00182                         int numberOfHits = 0;
00183                         double previousDotProduct = 0;
00184                         for (trackingRecHit_iterator ith = trackFromMap->recHitsBegin(), edh = trackFromMap->recHitsEnd(); ith != edh; ++ith) {
00185                                 
00186                                 GlobalVector stateMomentum = measurements[numberOfHits].forwardPredictedState().globalMomentum();
00187                                 GlobalPoint statePosition = measurements[numberOfHits].forwardPredictedState().globalPosition();
00188                                 double dotProduct = stateMomentum.x()*statePosition.x() + stateMomentum.y()*statePosition.y();
00189                                 if ( dotProduct*previousDotProduct < 0 ){
00190                                         //found hit to split from...
00191                                         HITTOSPLITFROM = numberOfHits;
00192                                 }
00193 
00194                                 previousDotProduct = dotProduct;
00195                                 numberOfHits++;
00196 
00197                         }
00198                         LogDebug("CosmicTrackSplitter") << "number of rechits: " << numberOfHits;
00199                         
00200                         // check if the trajectories and rechits are in reverse order...
00201                         trackingRecHit_iterator bIt = trackFromMap->recHitsBegin();
00202                         trackingRecHit_iterator fIt = trackFromMap->recHitsEnd() - 1;
00203                         const TrackingRecHit* bHit = bIt->get();
00204                         const TrackingRecHit* fHit = fIt->get();
00205                         // hit type valid = 0, missing = 1, inactive = 2, bad = 3
00206                         if( bHit->type() != 0 || bHit->isValid() != 1){
00207                                 //loop over hits forwards until first Valid hit is found
00208                                 trackingRecHit_iterator ihit;
00209                                 for( ihit =  trackFromMap->recHitsBegin(); 
00210                                         ihit != trackFromMap->recHitsEnd(); ++ihit){
00211                                         const TrackingRecHit* iHit = ihit->get();
00212                                         if( iHit->type() == 0 && iHit->isValid() == 1){
00213                                                 bHit = iHit;
00214                                                 break;
00215                                         }
00216                                 }
00217                         }
00218                         DetId bdetid = bHit->geographicalId();
00219                         GlobalPoint bPosHit = theGeometry->idToDetUnit( bdetid)->surface().
00220                         toGlobal(bHit->localPosition());
00221                         if( fHit->type() != 0 || fHit->isValid() != 1){
00222                                 //loop over hits backwards until first Valid hit is found
00223                                 trackingRecHit_iterator ihitf;
00224                                 for( ihitf =  trackFromMap->recHitsEnd()-1; 
00225                                         ihitf != trackFromMap->recHitsBegin(); --ihitf){
00226                                         const TrackingRecHit* iHit = ihitf->get();
00227                                         if( iHit->type() == 0 && iHit->isValid() == 1){
00228                                                 fHit = iHit;
00229                                                 break;
00230                                         }
00231                                 }
00232                         }
00233                         DetId fdetid = fHit->geographicalId();
00234                         GlobalPoint fPosHit =  theGeometry->
00235                         idToDetUnit( fdetid )->surface().toGlobal(fHit->localPosition());
00236                         GlobalPoint bPosState = measurements[0].updatedState().globalPosition();
00237                         GlobalPoint fPosState = measurements[measurements.size()-1].
00238                         updatedState().globalPosition();
00239                         bool trajReversedFlag = false;
00240                         /*
00241                         DetId bdetid = bHit->geographicalId();
00242                         DetId fdetid = fHit->geographicalId();
00243                         GlobalPoint bPosHit =  theGeometry->idToDetUnit( bdetid )->surface().toGlobal(bHit->localPosition());
00244                         GlobalPoint fPosHit =  theGeometry->idToDetUnit( fdetid )->surface().toGlobal(fHit->localPosition());
00245                         GlobalPoint bPosState = measurements[0].updatedState().globalPosition();
00246                         GlobalPoint fPosState = measurements[measurements.size() - 1].updatedState().globalPosition();
00247                         bool trajReversedFlag = false;
00248                         */
00249                         if (( (bPosHit - bPosState).mag() > (bPosHit - fPosState).mag() ) && ( (fPosHit - fPosState).mag() > (fPosHit - bPosState).mag() ) ){
00250                                 trajReversedFlag = true;
00251                         }
00252                         if (trajReversedFlag){ int temp = HITTOSPLITFROM; HITTOSPLITFROM = totalNumberOfHits - temp; }
00253                 }
00254 
00255                 totalTracks_ = totalTracks_ + tracks->size();
00256                 // loop on tracks
00257                 for (std::vector<reco::Track>::const_iterator itt = tracks->begin(), edt = tracks->end(); itt != edt; ++itt) {
00258                         hits.clear(); // extra safety
00259                         
00260                         LogDebug("CosmicTrackSplitter") << "ntracks: " << tracks->size();
00261                         
00262                         // try to find distance of closest approach
00263                         GlobalPoint v( itt->vx(), itt->vy(), itt->vz() );
00264                         
00265                         //checks on impact parameter
00266                         bool continueWithTrack = true;
00267                         if (fabs(v.z()) > dZcut_) continueWithTrack = false;
00268                         if (v.perp() > dXYcut_) continueWithTrack = false;
00269                         if (continueWithTrack == false) return;
00270                         
00271                         // LOOP TWICE, ONCE FOR TOP AND ONCE FOR BOTTOM
00272                         for (int i = 0; i < 2; ++i){
00273                                 hits.clear(); // extra safety
00274                                 LogDebug("CosmicTrackSplitter") << "   loop on hits of track #" << (itt - tracks->begin());
00275                                 int usedHitCtr = 0;
00276                                 int hitCtr = 0;
00277                                 for (trackingRecHit_iterator ith = itt->recHitsBegin(), edh = itt->recHitsEnd(); ith != edh; ++ith) {
00278                                         //hitCtr++;
00279                                         const TrackingRecHit * hit = ith->get(); // ith is an iterator on edm::Ref to rechit
00280                                         LogDebug("CosmicTrackSplitter") << "         hit number " << (ith - itt->recHitsBegin());
00281                                         // let's look at valid hits
00282                                         if (hit->isValid()) { 
00283                                                 LogDebug("CosmicTrackSplitter") << "            valid, detid = " << hit->geographicalId().rawId();
00284                                                 DetId detid = hit->geographicalId();
00285                                                 
00286                                                 if (detid.det() == DetId::Tracker) {  // check for tracker hits
00287                                                         LogDebug("CosmicTrackSplitter") << "            valid, tracker ";
00288                                                         bool  verdict = false;
00289                                                         
00290                                                         //trying to get the global position of the hit
00291                                                         //const GeomDetUnit* geomDetUnit =  theGeometry->idToDetUnit( detid ).;
00292                                                         
00293                                                         const GlobalPoint pos =  theGeometry->idToDetUnit( detid )->surface().toGlobal(hit->localPosition());
00294                                                         LogDebug("CosmicTrackSplitter") << "hit pos: " << pos << ", dca pos: " << v;
00295                                                         
00296                                                         // top half
00297                                                         if ((i == 0)&&(hitCtr < HITTOSPLITFROM)){
00298                                                                 verdict = true;
00299                                                                 LogDebug("CosmicTrackSplitter") << "tophalf";
00300                                                         }
00301                                                         // bottom half
00302                                                         if ((i == 1)&&(hitCtr >= HITTOSPLITFROM)){
00303                                                                 verdict = true;
00304                                                                 LogDebug("CosmicTrackSplitter") << "bottomhalf";
00305                                                         }
00306                                                         
00307                                                         // if the hit is good, check again at module level
00308                                                         if ( verdict  && std::binary_search(detsToIgnore_.begin(), detsToIgnore_.end(), detid.rawId())) {
00309                                                                 verdict = false;
00310                                                         }
00311                                                         
00312                                                         // if hit is good check to make sure that we are keeping pixel hits
00313                                                         if ( excludePixelHits_){
00314                                                                 if ((detid.det() == DetId::Tracker)&&((detid.subdetId() == 1)||(detid.subdetId() == 2))) {  // check for pixel hits
00315                                                                         verdict = false;
00316                                                                 }
00317                                                         }
00318                                                         
00319                                                         LogDebug("CosmicTrackSplitter") << "                   verdict after module list: " << (verdict ? "ok" : "no");
00320                                                         if (verdict == true) {
00321                                                                 // just copy the hit
00322                                                                 hits.push_back(hit->clone());
00323                                                                 usedHitCtr++;
00324                                                         } 
00325                                                         else {
00326                                                                 // still, if replaceWithInactiveHits is true we have to put a new hit
00327                                                                 if (replaceWithInactiveHits_) {
00328                                                                         hits.push_back(new InvalidTrackingRecHit(detid, TrackingRecHit::inactive));
00329                                                                 } 
00330                                                         }
00331                                                 } 
00332                                                 else { // just copy non tracker hits
00333                                                         hits.push_back(hit->clone());
00334                                                 }
00335                                         } 
00336                                         else {
00337                                                 if (!stripAllInvalidHits_) {
00338                                                         hits.push_back(hit->clone());
00339                                                 } 
00340                                         } // is valid hit
00341                                         LogDebug("CosmicTrackSplitter") << "         end of hit " << (ith - itt->recHitsBegin());
00342                                         hitCtr++;
00343                                 } // loop on hits
00344                                 LogDebug("CosmicTrackSplitter") << "   end of loop on hits of track #" << (itt - tracks->begin());
00345                                 
00346                                 std::vector<TrackingRecHit *>::iterator begin = hits.begin(), end = hits.end();
00347                                 
00348                                 LogDebug("CosmicTrackSplitter") << "   selected " << hits.size() << " hits ";
00349                                 
00350                                 // strip invalid hits at the beginning
00351                                 if (stripFrontInvalidHits_) {
00352                                         while ( (begin != end) && ( (*begin)->isValid() == false ) ) ++begin;
00353                                 }
00354                                 
00355                                 LogDebug("CosmicTrackSplitter") << "   after front stripping we have " << (end - begin) << " hits ";
00356                                 
00357                                 // strip invalid hits at the end
00358                                 if (stripBackInvalidHits_ && (begin != end)) {
00359                                         --end;
00360                                         while ( (begin != end) && ( (*end)->isValid() == false ) ) --end;
00361                                         ++end;
00362                                 }
00363                                 
00364                                 LogDebug("CosmicTrackSplitter") << "   after back stripping we have " << (end - begin) << " hits ";
00365                                 
00366                                 // if we still have some hits
00367                                 //if ((end - begin) >= int(minimumHits_)) {
00368                                 if ( usedHitCtr >= int(minimumHits_)) {
00369                                         output->push_back( makeCandidate ( *itt, begin, end ) );
00370                                         LogDebug("CosmicTrackSplitter") << "we made a candidate of " << hits.size() << " hits!";
00371                                 } 
00372                                 // now delete the hits not used by the candidate
00373                                 for (begin = hits.begin(), end = hits.end(); begin != end; ++begin) {
00374                                         if (*begin) delete *begin;
00375                                 } 
00376                                 LogDebug("CosmicTrackSplitter") << "loop: " << i << " has " << usedHitCtr << " active hits and " << hits.size() << " total hits...";
00377                                 hits.clear();
00378                         } // loop twice for top and bottom
00379                 } // loop on tracks
00380                 LogDebug("CosmicTrackSplitter") << "totalTracks_ = " << totalTracks_;
00381                 iEvent.put(output);
00382         }
00383         
00384         TrackCandidate
00385         CosmicTrackSplitter::makeCandidate(const reco::Track &tk, std::vector<TrackingRecHit *>::iterator hitsBegin, std::vector<TrackingRecHit *>::iterator hitsEnd) {
00386                 
00387                 LogDebug("CosmicTrackSplitter") << "Making a candidate!";
00388                 
00389                 
00390                 PropagationDirection   pdir = tk.seedDirection();
00391                 PTrajectoryStateOnDet state;
00392                 if ( pdir == anyDirection ) throw cms::Exception("UnimplementedFeature") << "Cannot work with tracks that have 'anyDirecton' \n";
00393                 //if ( (pdir == alongMomentum) == ( tk.p() >= tk.outerP() ) ) {
00394                 if ( (pdir == alongMomentum) == (  (tk.outerPosition()-tk.innerPosition()).Dot(tk.momentum()) >= 0    ) ) {
00395                         // use inner state
00396                         TrajectoryStateOnSurface originalTsosIn(trajectoryStateTransform::innerStateOnSurface(tk, *theGeometry, &*theMagField));
00397                         state = trajectoryStateTransform::persistentState( originalTsosIn, DetId(tk.innerDetId()) );
00398                 } else { 
00399                         // use outer state
00400                         TrajectoryStateOnSurface originalTsosOut(trajectoryStateTransform::outerStateOnSurface(tk, *theGeometry, &*theMagField));
00401                         state = trajectoryStateTransform::persistentState( originalTsosOut, DetId(tk.outerDetId()) );
00402                 }
00403                 
00404                 TrajectorySeed seed(state, TrackCandidate::RecHitContainer(), pdir);
00405                 
00406                 TrackCandidate::RecHitContainer ownHits;
00407                 ownHits.reserve(hitsEnd - hitsBegin);
00408                 for ( ; hitsBegin != hitsEnd; ++hitsBegin) { ownHits.push_back( *hitsBegin ); }
00409                 
00410                 TrackCandidate cand(ownHits, seed, state, tk.seedRef());
00411                 
00412                 
00413                 LogDebug("CosmicTrackSplitter") << "   dumping the hits now: ";
00414                 for (TrackCandidate::range hitR = cand.recHits(); hitR.first != hitR.second; ++hitR.first) {
00415                       LogTrace("CosmicTrackSplitter") << "     hit detid = " << hitR.first->geographicalId().rawId() <<
00416                         ", type  = " << typeid(*hitR.first).name();
00417                 }
00418                 
00419                 return cand;
00420         }
00421         
00422 }} //namespaces
00423 
00424 
00425 // ========= MODULE DEF ==============
00426 #include "FWCore/PluginManager/interface/ModuleDef.h"
00427 #include "FWCore/Framework/interface/MakerMacros.h"
00428 
00429 using reco::modules::CosmicTrackSplitter;
00430 DEFINE_FWK_MODULE(CosmicTrackSplitter);