CMS 3D CMS Logo

/data/refman/pasoursint/CMSSW_4_1_8_patch12/src/RecoTracker/CkfPattern/src/CkfTrackCandidateMakerBase.cc

Go to the documentation of this file.
00001 #include <memory>
00002 #include <string>
00003 
00004 #include "DataFormats/Common/interface/Handle.h"
00005 #include "FWCore/Framework/interface/ESHandle.h"
00006 #include "FWCore/Framework/interface/EventSetup.h"
00007 #include "FWCore/MessageLogger/interface/MessageLogger.h"
00008 
00009 #include "DataFormats/Common/interface/OwnVector.h"
00010 #include "DataFormats/TrackCandidate/interface/TrackCandidateCollection.h"
00011 #include "DataFormats/Common/interface/View.h"
00012 
00013 #include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h"
00014 
00015 #include "TrackingTools/PatternTools/interface/Trajectory.h"
00016 #include "TrackingTools/TrajectoryCleaning/interface/TrajectoryCleanerBySharedHits.h"
00017 #include "TrackingTools/Records/interface/TrackingComponentsRecord.h"
00018 #include "TrackingTools/TrajectoryState/interface/TrajectoryStateTransform.h"
00019 
00020 #include "RecoTracker/CkfPattern/interface/CkfTrackCandidateMakerBase.h"
00021 #include "RecoTracker/CkfPattern/interface/TransientInitialStateEstimator.h"
00022 #include "RecoTracker/Record/interface/TrackerRecoGeometryRecord.h"
00023 #include "RecoTracker/Record/interface/CkfComponentsRecord.h"
00024 
00025 
00026 #include "RecoTracker/CkfPattern/interface/SeedCleanerByHitPosition.h"
00027 #include "RecoTracker/CkfPattern/interface/CachingSeedCleanerByHitPosition.h"
00028 #include "RecoTracker/CkfPattern/interface/SeedCleanerBySharedInput.h"
00029 #include "RecoTracker/CkfPattern/interface/CachingSeedCleanerBySharedInput.h"
00030 
00031 #include "RecoTracker/Record/interface/NavigationSchoolRecord.h"
00032 #include "TrackingTools/DetLayers/interface/NavigationSchool.h"
00033 
00034 #include<algorithm>
00035 #include<functional>
00036 
00037 #include "RecoTracker/CkfPattern/interface/PrintoutHelper.h"
00038 
00039 using namespace edm;
00040 using namespace std;
00041 
00042 namespace cms{
00043   CkfTrackCandidateMakerBase::CkfTrackCandidateMakerBase(edm::ParameterSet const& conf) : 
00044 
00045     conf_(conf),
00046     theTrackCandidateOutput(true),
00047     theTrajectoryOutput(false),
00048     useSplitting(conf.getParameter<bool>("useHitsSplitting")),
00049     doSeedingRegionRebuilding(conf.getParameter<bool>("doSeedingRegionRebuilding")),
00050     cleanTrajectoryAfterInOut(conf.getParameter<bool>("cleanTrajectoryAfterInOut")),
00051     theMaxNSeeds(conf.getParameter<unsigned int>("maxNSeeds")),
00052     theTrajectoryBuilderName(conf.getParameter<std::string>("TrajectoryBuilder")), 
00053     theTrajectoryBuilder(0),
00054     theTrajectoryCleanerName(conf.getParameter<std::string>("TrajectoryCleaner")), 
00055     theTrajectoryCleaner(0),
00056     theInitialState(0),
00057     theNavigationSchoolName(conf.getParameter<std::string>("NavigationSchool")),
00058     theNavigationSchool(0),
00059     theSeedCleaner(0)
00060   {  
00061     //produces<TrackCandidateCollection>();  
00062     // old configuration totally descoped.
00063     //    if (!conf.exists("src"))
00064     //      theSeedLabel = InputTag(conf_.getParameter<std::string>("SeedProducer"),conf_.getParameter<std::string>("SeedLabel"));
00065     //    else
00066       theSeedLabel= conf.getParameter<edm::InputTag>("src");
00067   }
00068 
00069   
00070   // Virtual destructor needed.
00071   CkfTrackCandidateMakerBase::~CkfTrackCandidateMakerBase() {
00072     delete theInitialState;  
00073     if (theSeedCleaner) delete theSeedCleaner;
00074   }  
00075 
00076   void CkfTrackCandidateMakerBase::beginRunBase (edm::Run & r, EventSetup const & es)
00077   {
00078     std::string cleaner = conf_.getParameter<std::string>("RedundantSeedCleaner");
00079     if (cleaner == "SeedCleanerByHitPosition") {
00080         theSeedCleaner = new SeedCleanerByHitPosition();
00081     } else if (cleaner == "SeedCleanerBySharedInput") {
00082         theSeedCleaner = new SeedCleanerBySharedInput();
00083     } else if (cleaner == "CachingSeedCleanerByHitPosition") {
00084         theSeedCleaner = new CachingSeedCleanerByHitPosition();
00085     } else if (cleaner == "CachingSeedCleanerBySharedInput") {
00086         theSeedCleaner = new CachingSeedCleanerBySharedInput();
00087     } else if (cleaner == "none") {
00088         theSeedCleaner = 0;
00089     } else {
00090         throw cms::Exception("RedundantSeedCleaner not found", cleaner);
00091     }
00092   }
00093 
00094   void CkfTrackCandidateMakerBase::setEventSetup( const edm::EventSetup& es ) {
00095 
00096     //services
00097     es.get<TrackerRecoGeometryRecord>().get( theGeomSearchTracker );
00098     es.get<IdealMagneticFieldRecord>().get( theMagField );
00099 
00100     if (!theInitialState){
00101       // constructor uses the EventSetup, it must be in the setEventSetup were it has a proper value.
00102       // get nested parameter set for the TransientInitialStateEstimator
00103       ParameterSet tise_params = conf_.getParameter<ParameterSet>("TransientInitialStateEstimatorParameters") ;
00104       theInitialState          = new TransientInitialStateEstimator( es,tise_params);
00105     }
00106 
00107     theInitialState->setEventSetup( es );
00108 
00109     edm::ESHandle<TrajectoryCleaner> trajectoryCleanerH;
00110     es.get<TrajectoryCleaner::Record>().get(theTrajectoryCleanerName, trajectoryCleanerH);
00111     theTrajectoryCleaner= trajectoryCleanerH.product();
00112 
00113     edm::ESHandle<NavigationSchool> navigationSchoolH;
00114     es.get<NavigationSchoolRecord>().get(theNavigationSchoolName, navigationSchoolH);
00115     theNavigationSchool = navigationSchoolH.product();
00116 
00117     // set the TrajectoryBuilder
00118     edm::ESHandle<TrajectoryBuilder> theTrajectoryBuilderHandle;
00119     es.get<CkfComponentsRecord>().get(theTrajectoryBuilderName,theTrajectoryBuilderHandle);
00120     theTrajectoryBuilder = theTrajectoryBuilderHandle.product();    
00121        
00122   }
00123 
00124   // Functions that gets called by framework every event
00125   void CkfTrackCandidateMakerBase::produceBase(edm::Event& e, const edm::EventSetup& es)
00126   { 
00127     // getting objects from the EventSetup
00128     setEventSetup( es ); 
00129 
00130     // set the correct navigation
00131     NavigationSetter setter( *theNavigationSchool);
00132     
00133     // propagator
00134     edm::ESHandle<Propagator> thePropagator;
00135     es.get<TrackingComponentsRecord>().get("AnyDirectionAnalyticalPropagator",
00136                                            thePropagator);
00137 
00138     // method for Debugging
00139     printHitsDebugger(e);
00140 
00141     // Step A: set Event for the TrajectoryBuilder
00142     theTrajectoryBuilder->setEvent(e);        
00143     
00144     // Step B: Retrieve seeds
00145     
00146     edm::Handle<View<TrajectorySeed> > collseed;
00147     e.getByLabel(theSeedLabel, collseed);
00148     
00149     // Step C: Create empty output collection
00150     std::auto_ptr<TrackCandidateCollection> output(new TrackCandidateCollection);    
00151     std::auto_ptr<std::vector<Trajectory> > outputT (new std::vector<Trajectory>());
00152 
00153     if ( (*collseed).size()>theMaxNSeeds ) {
00154       LogError("TooManySeeds")<<"Exceeded maximum numeber of seeds! theMaxNSeeds="<<theMaxNSeeds<<" nSeed="<<(*collseed).size();
00155       if (theTrackCandidateOutput){ e.put(output);}
00156       if (theTrajectoryOutput){e.put(outputT);}
00157       return;
00158     }
00159     
00160     // Step D: Invoke the building algorithm
00161     if ((*collseed).size()>0){
00162 
00163        vector<Trajectory> rawResult;
00164        rawResult.reserve(collseed->size() * 4);
00165 
00166       if (theSeedCleaner) theSeedCleaner->init( &rawResult );
00167       
00168       // method for debugging
00169       countSeedsDebugger();
00170 
00171       vector<Trajectory> theTmpTrajectories;
00172 
00173       // Loop over seeds
00174       size_t collseed_size = collseed->size(); 
00175       for (size_t j = 0; j < collseed_size; j++){
00176        
00177         // Check if seed hits already used by another track
00178         if (theSeedCleaner && !theSeedCleaner->good( &((*collseed)[j])) ) {
00179           LogDebug("CkfTrackCandidateMakerBase")<<" Seed cleaning kills seed "<<j;
00180           continue; 
00181         }
00182 
00183         // Build trajectory from seed outwards
00184         theTmpTrajectories.clear();
00185         theTrajectoryBuilder->trajectories( (*collseed)[j], theTmpTrajectories );
00186         
00187        
00188         LogDebug("CkfPattern") << "======== In-out trajectory building found " << theTmpTrajectories.size()
00189                                     << " trajectories from seed " << j << " ========"<<endl
00190                                <<PrintoutHelper::dumpCandidates(theTmpTrajectories);
00191         
00192         if (cleanTrajectoryAfterInOut) {
00193 
00194           // Select the best trajectory from this seed (declare others invalid)
00195           theTrajectoryCleaner->clean(theTmpTrajectories);
00196 
00197           LogDebug("CkfPattern") << "======== In-out trajectory cleaning gave the following valid trajectories from seed " 
00198                                  << j << " ========"<<endl
00199                                  << PrintoutHelper::dumpCandidates(theTmpTrajectories);
00200         }
00201 
00202         // Optionally continue building trajectory back through 
00203         // seed and if possible further inwards.
00204         if (doSeedingRegionRebuilding) {
00205           theTrajectoryBuilder->rebuildSeedingRegion((*collseed)[j],theTmpTrajectories);      
00206 
00207           LogDebug("CkfPattern") << "======== Out-in trajectory building found " << theTmpTrajectories.size()
00208                                       << " valid/invalid trajectories from seed " << j << " ========"<<endl
00209                                  <<PrintoutHelper::dumpCandidates(theTmpTrajectories);
00210         }
00211 
00212         // Select the best trajectory from this seed (after seed region rebuilding, can be more than one)
00213         theTrajectoryCleaner->clean(theTmpTrajectories);
00214 
00215         LogDebug("CkfPattern") << "======== Trajectory cleaning gave the following valid trajectories from seed " 
00216                                << j << " ========"<<endl
00217                                <<PrintoutHelper::dumpCandidates(theTmpTrajectories);
00218 
00219         for(vector<Trajectory>::iterator it=theTmpTrajectories.begin();
00220             it!=theTmpTrajectories.end(); it++){
00221           if( it->isValid() ) {
00222             it->setSeedRef(collseed->refAt(j));
00223             // Store trajectory
00224             rawResult.push_back(*it);
00225             // Tell seed cleaner which hits this trajectory used.
00226             //TO BE FIXED: this cut should be configurable via cfi file
00227             if (theSeedCleaner && it->foundHits()>3) theSeedCleaner->add( & (*it) );
00228             //if (theSeedCleaner ) theSeedCleaner->add( & (*it) );
00229           }
00230         }
00231 
00232         theTmpTrajectories.clear();
00233         
00234         LogDebug("CkfPattern") << "rawResult trajectories found so far = " << rawResult.size();
00235       }
00236       // end of loop over seeds
00237       
00238       if (theSeedCleaner) theSeedCleaner->done();
00239       
00240       // Step E: Clean the results to avoid duplicate tracks
00241       // Rejected ones just flagged as invalid.
00242       theTrajectoryCleaner->clean(rawResult);
00243 
00244       LogDebug("CkfPattern") << "======== Final cleaning of entire event found " << rawResult.size() 
00245                              << " valid/invalid trajectories ======="<<endl
00246                              <<PrintoutHelper::dumpCandidates(rawResult);
00247 
00248       LogDebug("CkfPattern") << "removing invalid trajectories.";
00249 
00250       vector<Trajectory> & unsmoothedResult(rawResult);
00251       unsmoothedResult.erase(std::remove_if(unsmoothedResult.begin(),unsmoothedResult.end(),
00252                                             std::not1(std::mem_fun_ref(&Trajectory::isValid))),
00253                              unsmoothedResult.end());
00254       
00255 
00256       //      for (vector<Trajectory>::const_iterator itraw = rawResult.begin();
00257       //           itraw != rawResult.end(); itraw++) {
00258       //if((*itraw).isValid()) unsmoothedResult.push_back( *itraw);
00259       //}
00260 
00261       //analyseCleanedTrajectories(unsmoothedResult);
00262       
00263       if (theTrackCandidateOutput){
00264         // Step F: Convert to TrackCandidates
00265        output->reserve(unsmoothedResult.size());
00266        for (vector<Trajectory>::const_iterator it = unsmoothedResult.begin();
00267             it != unsmoothedResult.end(); it++) {
00268         
00269          Trajectory::RecHitContainer thits;
00270          //it->recHitsV(thits);
00271          LogDebug("CkfPattern") << "retrieving "<<(useSplitting?"splitted":"un-splitted")<<" hits from trajectory";
00272          it->recHitsV(thits,useSplitting);
00273          OwnVector<TrackingRecHit> recHits;
00274          recHits.reserve(thits.size());
00275          LogDebug("CkfPattern") << "cloning hits into new collection.";
00276          for (Trajectory::RecHitContainer::const_iterator hitIt = thits.begin();
00277               hitIt != thits.end(); hitIt++) {
00278            recHits.push_back( (**hitIt).hit()->clone());
00279          }
00280 
00281          LogDebug("CkfPattern") << "getting initial state.";
00282          const bool doBackFit = !doSeedingRegionRebuilding;
00283          std::pair<TrajectoryStateOnSurface, const GeomDet*> initState = 
00284            theInitialState->innerState( *it , doBackFit);
00285 
00286          // temporary protection againt invalid initial states
00287          if (! initState.first.isValid() || initState.second == 0) {
00288            //cout << "invalid innerState, will not make TrackCandidate" << endl;
00289            continue;
00290          }
00291          
00292          PTrajectoryStateOnDet* state =0 ;
00293          if(useSplitting && (initState.second != thits.front()->det()) && thits.front()->det() ){        
00294            LogDebug("CkfPattern") << "propagating to hit front in case of splitting.";
00295            TrajectoryStateOnSurface propagated = thePropagator->propagate(initState.first,thits.front()->det()->surface());
00296            if (!propagated.isValid()) continue;
00297            state = TrajectoryStateTransform().persistentState(propagated,
00298                                                               thits.front()->det()->geographicalId().rawId());
00299          }
00300          
00301          if(!state) state = TrajectoryStateTransform().persistentState( initState.first,
00302                                                                         initState.second->geographicalId().rawId());
00303          
00304          LogDebug("CkfPattern") << "pushing a TrackCandidate.";
00305          output->push_back(TrackCandidate(recHits,it->seed(),*state,it->seedRef() ) );
00306          
00307          delete state;
00308        }
00309       }//output trackcandidates
00310 
00311       edm::ESHandle<TrackerGeometry> tracker;
00312       es.get<TrackerDigiGeometryRecord>().get(tracker);            
00313       LogTrace("CkfPattern|TrackingRegressionTest") << "========== CkfTrackCandidateMaker Info =========="
00314                                                     << "number of Seed: " << collseed->size()<<endl
00315                                                     <<PrintoutHelper::regressionTest(*tracker,unsmoothedResult);
00316 
00317       
00318      
00319       if (theTrajectoryOutput){ outputT->swap(unsmoothedResult);}
00320 
00321     }// end of ((*collseed).size()>0)
00322     
00323     // method for debugging
00324     deleteAssocDebugger();
00325 
00326     // Step G: write output to file
00327     if (theTrackCandidateOutput){ e.put(output);}
00328     if (theTrajectoryOutput){e.put(outputT);}
00329   }
00330 }
00331