CMS 3D CMS Logo

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