CMS 3D CMS Logo

/data/refman/pasoursint/CMSSW_5_3_0/src/RecoHI/HiMuonAlgos/src/HICTrajectoryBuilder.cc

Go to the documentation of this file.
00001 #include "RecoHI/HiMuonAlgos/interface/HICTrajectoryBuilder.h"
00002 #include "RecoHI/HiMuonAlgos/interface/HICTrajectoryCorrector.h"
00003 
00004 #include "FWCore/MessageLogger/interface/MessageLogger.h"
00005 
00006 #include "MagneticField/Records/interface/IdealMagneticFieldRecord.h"
00007 
00008 #include "TrackingTools/GeomPropagators/interface/Propagator.h"
00009 #include "TrackingTools/PatternTools/interface/TrajectoryStateUpdator.h"
00010 #include "TrackingTools/PatternTools/interface/MeasurementEstimator.h"
00011 
00012 #include "TrackingTools/PatternTools/interface/Trajectory.h"
00013 #include "TrackingTools/PatternTools/interface/TrajMeasLessEstim.h"
00014 #include "TrackingTools/TrajectoryState/interface/BasicSingleTrajectoryState.h"
00015 #include "TrackingTools/MeasurementDet/interface/LayerMeasurements.h"
00016 
00017 
00018 #include "RecoTracker/CkfPattern/src/RecHitIsInvalid.h"
00019 #include "RecoTracker/CkfPattern/interface/TrajCandLess.h"
00020 #include "TrackingTools/TrajectoryFiltering/interface/MinPtTrajectoryFilter.h"
00021 #include "TrackingTools/TrajectoryFiltering/interface/MaxHitsTrajectoryFilter.h"
00022 #include "RecoTracker/TkDetLayers/interface/GeometricSearchTracker.h"
00023 
00024 #include "RecoTracker/CkfPattern/interface/IntermediateTrajectoryCleaner.h"
00025 #include "RecoHI/HiMuonAlgos/interface/HICConst.h"
00026 #include "RecoHI/HiMuonAlgos/interface/DiMuonTrajectorySeed.h"
00027 #include "RecoHI/HiMuonAlgos/interface/HICMuonUpdator.h"
00028 #include "RecoHI/HiMuonAlgos/interface/HICMuonPropagator.h"
00029 
00030 
00031 #include "Geometry/CommonDetUnit/interface/GlobalTrackingGeometry.h"
00032 #include "Geometry/Records/interface/GlobalTrackingGeometryRecord.h"
00033 #include "DataFormats/BeamSpot/interface/BeamSpot.h"
00034 #include "DataFormats/TrackReco/interface/TrackBase.h"
00035 #include "TrackingTools/PatternTools/interface/TrajectorySmoother.h"
00036 #include "TrackingTools/Records/interface/TrackingComponentsRecord.h"
00037 #include "TrackingTools/PatternTools/interface/TSCBLBuilderNoMaterial.h"
00038 //#include "TrackingTools/PatternTools/interface/TrajectoryStateClosestToBeamLineBuilder.h"
00039 
00040 using namespace std;
00041 using namespace cms;
00042 
00043 //#define DEBUG
00044 
00045 HICTrajectoryBuilder::
00046   HICTrajectoryBuilder(const edm::ParameterSet&              conf, 
00047                        const edm::EventSetup&                es1,
00048                        const TrajectoryStateUpdator*         updator,
00049                        const Propagator*                     propagatorAlong,
00050                        const Propagator*                     propagatorOpposite,
00051                        const Chi2MeasurementEstimatorBase*   estimator,
00052                        const TransientTrackingRecHitBuilder* RecHitBuilder,
00053                        const MeasurementTracker*             measurementTracker,
00054                        const TrajectoryFilter*               filter):
00055 
00056     BaseCkfTrajectoryBuilder(conf,
00057                              updator, propagatorAlong,propagatorOpposite,
00058                              estimator, RecHitBuilder, measurementTracker,filter),
00059     theUpdator(updator),thePropagatorAlong(propagatorAlong),
00060     thePropagatorOpposite(propagatorOpposite),theEstimator(estimator),
00061         theTTRHBuilder(RecHitBuilder),theMeasurementTracker(measurementTracker),
00062         theLayerMeasurements(new LayerMeasurements(theMeasurementTracker)),
00063         theForwardPropagator(0), theBackwardPropagator(0)                                                        
00064 {
00065   theMaxCand              = 1;
00066   theMaxLostHit           = 0;
00067   theMaxConsecLostHit     = 0;
00068   theLostHitPenalty       = 0.;
00069   theIntermediateCleaning = false;
00070   theMinimumNumberOfHits  = 5;
00071   theAlwaysUseInvalidHits = false;
00072   es1.get<GlobalTrackingGeometryRecord>().get(globTkGeomHandle);
00073 //  es1.get<TrackingComponentsRecord>().get("KFFitterForRefitInsideOut",theFitterTrack);
00074 //  es1.get<TrackingComponentsRecord>().get("KFSmootherForRefitInsideOut",theSmootherTrack);
00075   es1.get<TrajectoryFitter::Record>().get("KFFitterForRefitInsideOut",theFitterTrack); 
00076   es1.get<TrajectoryFitter::Record>().get("KFSmootherForRefitInsideOut",theSmootherTrack);
00077   es1.get<TrackingComponentsRecord>().get("SmartPropagatorAny",thePropagatorTrack);
00078   
00079 #ifdef DEBUG  
00080   cout<<" HICTrajectoryBuilder::contructor "<<endl;
00081 #endif 
00082 }
00083 
00084 HICTrajectoryBuilder::~HICTrajectoryBuilder()
00085 {
00086   delete theLayerMeasurements;
00087 //  delete theMinPtCondition;
00088 //  delete theMaxHitsCondition;
00089 }
00090 
00091 void HICTrajectoryBuilder::setEvent(const edm::Event& event) const
00092 {
00093   theMeasurementTracker->update(event);
00094 }
00095 
00096 HICTrajectoryBuilder::TrajectoryContainer 
00097 HICTrajectoryBuilder::trajectories(const TrajectorySeed& seed) const
00098 { 
00099    theHICConst = dynamic_cast<HICMeasurementEstimator*>(const_cast<Chi2MeasurementEstimatorBase*>(theEstimator))->getHICConst(); 
00100 #ifdef DEBUG
00101    cout<<" HICTrajectoryBuilder::trajectories start with seed"<<endl;
00102 #endif   
00103   TrajectoryContainer result;
00104 
00105   TempTrajectory startingTraj = createStartingTrajectory( seed );
00106 #ifdef DEBUG  
00107   cout<<" HICTrajectoryBuilder::trajectories starting trajectories created "<<endl;
00108 #endif  
00109   if(startingTraj.empty()) {
00110 #ifdef DEBUG
00111         cout<<" Problem with starting trajectory "<<endl; 
00112 #endif
00113   return result;
00114   }
00115 
00118 
00119   limitedCandidates( startingTraj, result);
00120 #ifdef DEBUG  
00121    cout<<" HICTrajectoryBuilder::trajectories candidates found "<<result.size()<<endl;
00122 #endif
00123 
00124   return result;
00125 }
00126 
00127 TempTrajectory HICTrajectoryBuilder::
00128 createStartingTrajectory( const TrajectorySeed& seed) const
00129 {
00130 #ifdef DEBUG
00131   cout<<" HICTrajectoryBuilder::createStartingTrajectory "<<seed.direction()<<endl;
00132 #endif  
00133   TempTrajectory result( seed, oppositeToMomentum );
00134   theForwardPropagator = &(*thePropagatorOpposite);
00135   theBackwardPropagator = &(*thePropagatorAlong);
00136 
00137   std::vector<TM> seedMeas = seedMeasurements(seed);
00138 
00139 #ifdef DEBUG  
00140   std::cout<<" Size of seed "<<seedMeas.size()<<endl;
00141 #endif  
00142   if ( !seedMeas.empty()) {
00143 #ifdef DEBUG
00144   std::cout<<" TempTrajectory "<<std::endl;
00145 #endif
00146     for (std::vector<TM>::const_iterator i=seedMeas.begin(); i!=seedMeas.end(); i++){
00147     
00148        result.push(*i); 
00149       
00150                  
00151     }
00152   }
00153    
00154   return result;
00155   
00156 }
00157 
00158 void HICTrajectoryBuilder::
00159 limitedCandidates( TempTrajectory& startingTraj, 
00160                    TrajectoryContainer& result) const
00161 {
00162   TempTrajectoryContainer candidates; // = TrajectoryContainer();
00163   TempTrajectoryContainer newCand; // = TrajectoryContainer();
00164   candidates.push_back( startingTraj);
00165 // Add the additional stuff
00166 #ifdef DEBUG
00167   cout<<" HICTrajectoryBuilder::limitedCandidates "<<candidates.size()<<endl;
00168 #endif   
00169 
00170   int theIniSign = 1;
00171   dynamic_cast<HICMeasurementEstimator*>(const_cast<Chi2MeasurementEstimatorBase*>(theEstimator))->setSign(theIniSign);
00172 #ifdef DEBUG
00173   cout<<" Number of measurements "<<startingTraj.measurements().size()<<endl;
00174 #endif
00175 //
00176 // Calculate the number of final trajectories. Allow no more then 4.
00177 //
00178    
00179   int numtraj = 0; 
00180    
00181   while ( !candidates.empty()) {
00182 #ifdef DEBUG
00183   cout<<" HICTrajectoryBuilder::limitedCandidates::cycle "<<candidates.size()<<endl;
00184 #endif
00185     newCand.clear();
00186 
00187     for (TempTrajectoryContainer::iterator traj=candidates.begin();
00188          traj!=candidates.end(); traj++) {
00189 #ifdef DEBUG     
00190          cout<< " Before findCompatibleMeasurements "<<endl;
00191 #endif
00192       std::vector<TM> meas = findCompatibleMeasurements(*traj);
00193 #ifdef DEBUG
00194          cout<< " After findCompatibleMeasurements "<<meas.size()<<endl;
00195 #endif
00196 
00197       if ( meas.empty()) {
00198 #ifdef DEBUG
00199         cout<<": Measurements empty : "<<endl;
00200 #endif
00201         if ( qualityFilter( *traj)) {addToResult( *traj, result); numtraj++;}
00202       }
00203       else {
00204 #ifdef DEBUG
00205         cout<<" : Update trajectoris :   "<<endl;
00206 #endif
00207         for( std::vector<TM>::const_iterator itm = meas.begin(); 
00208                                              itm != meas.end(); itm++) {
00209           TempTrajectory newTraj = *traj;
00210           bool good = updateTrajectory( newTraj, *itm);
00211           if(good)
00212           {
00213             if ( toBeContinued(newTraj)) {
00214                         newCand.push_back(newTraj);
00215 #ifdef DEBUG
00216                cout<<": toBeContinued : increase "<<newCand.size()<<" maximal size "<<theMaxCand<<endl;
00217 #endif
00218              }
00219              else {
00220 #ifdef DEBUG
00221                cout<<": good TM : to be stored :"<<endl;
00222 #endif
00223                if ( qualityFilter(newTraj)) {addToResult( newTraj, result); numtraj++;}
00225                   }
00226           } // good
00227             else
00228             {
00229 #ifdef DEBUG
00230                   cout<<": bad TM : to be stored :"<<endl;
00231 #endif
00232                if ( qualityFilter( *traj)) {addToResult( *traj, result);numtraj++;}
00233             }
00234          } //meas 
00235       }
00236     
00237 //      if ((int)newCand.size() > theMaxCand) {
00238 //      sort( newCand.begin(), newCand.end(), TrajCandLess<TempTrajectory>(theLostHitPenalty));
00239 //      newCand.erase( newCand.begin()+theMaxCand, newCand.end());
00240 //      }
00241 
00242         if(numtraj > 4) break;
00243     } // trajectories
00244         if(numtraj > 4) break;
00245         candidates.swap(newCand);
00246   }
00247 
00248 #ifdef DEBUG 
00249   std::cout<<" qualityFilter::Number of trajectories "<<numtraj<<std::endl;
00250 #endif
00251   
00252 }
00253 
00254 
00255 
00256 #include "RecoTracker/TransientTrackingRecHit/interface/TkTransientTrackingRecHitBuilder.h"
00257 #include "TrackingTools/TrajectoryState/interface/TrajectoryStateTransform.h"
00258 #include "RecoHI/HiMuonAlgos/interface/DiMuonTrajectorySeed.h"
00259 
00260 std::vector<TrajectoryMeasurement> 
00261 HICTrajectoryBuilder::seedMeasurements(const TrajectorySeed& seed) const
00262 {
00263   std::vector<TrajectoryMeasurement> result;
00264 //  TrajectoryStateTransform tsTransform;
00265 
00266 #ifdef DEBUG 
00267   cout<<" HICTrajectoryBuilder::seedMeasurements number of TM "<<dynamic_cast<DiMuonTrajectorySeed*>(const_cast<TrajectorySeed*>(&seed))->measurements().size()<<endl;
00268 #endif  
00269 
00270    std::vector<TrajectoryMeasurement> start = dynamic_cast<DiMuonTrajectorySeed*>(const_cast<TrajectorySeed*>(&seed))->measurements();
00271    for(std::vector<TrajectoryMeasurement>::iterator imh = start.begin(); imh != start.end(); imh++)
00272    { 
00273 #ifdef DEBUG       
00274      cout<<" HICTrajectoryBuilder::seedMeasurements::RecHit "<<endl;
00275 #endif       
00276      result.push_back(*imh);
00277    }
00278 
00279   return result;
00280 }
00281 
00282  bool HICTrajectoryBuilder::qualityFilter( const TempTrajectory& traj) const
00283 {
00284 #ifdef DEBUG
00285     cout << "qualityFilter called for trajectory with " 
00286          << traj.foundHits() << " found hits and Chi2 = "
00287          << traj.chiSquared() << endl;
00288 #endif
00289   if ( traj.foundHits() < theMinimumNumberOfHits) {
00290     return false;
00291   }
00292 
00293   Trajectory traj0 = traj.toTrajectory();
00294 // Check the number of pixels
00295   const Trajectory::DataContainer tms = traj0.measurements();
00296   int ipix = 0; 
00297   for( Trajectory::DataContainer::const_iterator itm = tms.begin(); itm != tms.end(); itm++) {
00298      if((*itm).layer()->subDetector() == GeomDetEnumerators::PixelEndcap || (*itm).layer()->subDetector() == GeomDetEnumerators::PixelBarrel) ipix++;
00299   }
00300   
00301 #ifdef DEBUG
00302  cout<<" Number of pixels "<<ipix<<endl;
00303 #endif
00304 
00305  if(ipix < 1) return false;
00306  
00307 //
00308 // Refit the trajectory
00309 //
00310 
00311     reco::BeamSpot::CovarianceMatrix matrix;
00312     matrix(2,2) = 0.001;
00313     matrix(3,3) = 0.001;
00314 
00315     reco::BeamSpot bs( reco::BeamSpot::Point(0., 0., theHICConst->zvert),
00316                                                      0.1,
00317                                                      0.,
00318                                                      0.,
00319                                                      0.,
00320                                                     matrix
00321                      );
00322     
00323     enum RefitDirection{insideOut,outsideIn,undetermined};
00324     
00325     Trajectory::ConstRecHitContainer recHitsForReFit = traj0.recHits();
00326    
00327 #ifdef DEBUG
00328  cout<<" Take recHits for reFit "<<endl;
00329 #endif
00330 
00331  
00332     PTrajectoryStateOnDet garbage1;
00333     edm::OwnVector<TrackingRecHit> garbage2;
00334 //    TrajectoryStateOnSurface firstTSOS = traj0.firstMeasurement().updatedState(); 
00335 
00336     TrajectoryStateOnSurface firstTSOS = traj0.lastMeasurement().updatedState();
00337     Trajectory::ConstRecHitContainer newRecHitsForReFit;
00338     for(Trajectory::ConstRecHitContainer::const_iterator it=recHitsForReFit.end()-1; it!=recHitsForReFit.begin()-1; it--){
00339 //     cout<<" RecHIT is valid "<<(*it)->isValid()<<endl;
00340      if((*it)->isValid()) {
00341 //           cout<<(*it)->globalPosition()<<endl;
00342            newRecHitsForReFit.push_back(*it);
00343      } 
00344 //           else{cout<<" Invalid! "<<endl;
00345 //           }
00346     }
00347 
00348 
00349 
00350 
00351 #ifdef DEBUG
00352  cout<<" Take firstTSOS "<<firstTSOS.isValid()<<endl;
00353  if(firstTSOS.isValid()) cout<<firstTSOS.freeTrajectoryState()->charge()<<" "<<firstTSOS.freeTrajectoryState()->position()<<" "<<firstTSOS.freeTrajectoryState()->momentum()<<endl;
00354 #endif
00355 
00356 //    PropagationDirection propDir = oppositeToMomentum;
00357     PropagationDirection propDir = alongMomentum;
00358     TrajectorySeed seed(garbage1,garbage2,propDir);
00359     vector<Trajectory> trajectories = theFitterTrack->fit(seed,newRecHitsForReFit,firstTSOS);
00360 
00361  //   vector<Trajectory> trajectories = theFitterTrack->fit(seed,recHitsForReFit,firstTSOS);
00362  //   vector<Trajectory> trajectories = theFitterTrack->fit(seed,recHitsForReFit);
00363  //   vector<Trajectory> trajectories = theFitterTrack->fit(traj0);
00364 
00365 #ifdef DEBUG
00366  cout<<" fit Trajectory "<<endl;
00367 #endif
00368 
00369 
00370 
00371     TrajectoryStateOnSurface innertsos;
00372 
00373     if (traj0.direction() == alongMomentum) {
00374    //    cout<<" Direction is along momentum "<<endl;
00375       innertsos = traj0.firstMeasurement().updatedState();
00376     } else {
00377       innertsos = traj0.lastMeasurement().updatedState();
00378    //   cout<<" Direction is opposite to momentum "<<endl;
00379       
00380     }
00381 
00382 #ifdef DEBUG
00383  cout<<" take inertsos "<<endl;
00384 #endif
00385 
00386 
00387     TSCBLBuilderNoMaterial tscblBuilder;
00388 
00389     //TrajectoryStateClosestToBeamLineBuilder tscblBuilder;
00390     TrajectoryStateClosestToBeamLine tscbl = tscblBuilder(*(innertsos.freeState()),bs);
00391 
00392 #ifdef DEBUG
00393  cout<<" closest to Beam "<<endl;
00394 #endif
00395 
00396 
00397     if (tscbl.isValid()==false) {
00398     //cout<<" false track "<<endl; 
00399      return false;
00400     }
00401     
00402     GlobalPoint v = tscbl.trackStateAtPCA().position();
00403     math::XYZPoint  pos( v.x(), v.y(), v.z() );
00404    
00405 #ifdef DEBUG
00406  cout<<" check vertex constraints "<<endl;
00407 #endif
00408 
00409  
00410     if(v.perp() > 0.1 ) return false;
00411     if(fabs(v.z() - theHICConst->zvert ) > 0.4 ) return false;
00412 
00413  return true;
00414  
00415 }
00416 
00417 
00418 void HICTrajectoryBuilder::addToResult( TempTrajectory& tmptraj, 
00419                                         TrajectoryContainer& result) const
00420 {
00421   Trajectory traj = tmptraj.toTrajectory();
00422   result.push_back( traj);
00423 }
00424 
00425 bool HICTrajectoryBuilder::updateTrajectory( TempTrajectory& traj,
00426                                              const TM& tm) const
00427 {
00428   bool good=false; 
00429 #ifdef DEBUG
00430   std::cout<<"HICTrajectoryBuilder::updateTrajectory::start"<<std::endl;
00431 #endif
00432   TSOS predictedState = tm.predictedState();
00433   TM::ConstRecHitPointer hit = tm.recHit();
00434   Trajectory traj0 = traj.toTrajectory();
00435   
00436 // My update
00437    vector<double> theCut = dynamic_cast<HICMeasurementEstimator*>
00438                           (const_cast<Chi2MeasurementEstimatorBase*>(theEstimator))->setCuts(traj0,tm.layer());
00439    int icut = 3;
00440    dynamic_cast<HICMeasurementEstimator*>(const_cast<Chi2MeasurementEstimatorBase*>(theEstimator))->chooseCuts(icut);
00441    const MagneticField * mf = dynamic_cast<HICMeasurementEstimator*>(const_cast<Chi2MeasurementEstimatorBase*>(theEstimator))->getField();
00442    HICMuonUpdator hicup(theCut[2],theCut[3], mf,theHICConst);
00443    double chi2rz,chi2rf;
00444  
00445   if ( hit->isValid()) {
00446 // Check the charge
00447 // if() { 
00448 
00449    TrajectoryMeasurement tmlast = traj.lastMeasurement();
00450    TM::ConstRecHitPointer lasthit = tmlast.recHit();
00451    double dfi1 = predictedState.freeTrajectoryState()->position().phi() - lasthit->globalPosition().phi();
00452    double dfi2 = hit->globalPosition().phi() - lasthit->globalPosition().phi();
00453    
00454 
00455    if(dfi1*dfi2<0) {
00456 //    cout<<" Need to change charge "<<endl;
00457     TrackCharge aCharge = -1*predictedState.freeTrajectoryState()->charge();
00458     GlobalPoint xnew = predictedState.globalPosition();
00459     GlobalVector pnew = predictedState.globalMomentum();
00460     TrajectoryStateOnSurface tsos(
00461                             GlobalTrajectoryParameters(xnew, pnew, aCharge, predictedState.magneticField()),
00462                             predictedState.curvilinearError(), predictedState.surface());
00463     predictedState = tsos;
00464    }
00465    
00466 // Update trajectory
00467 //
00468   TrajectoryStateOnSurface newUpdateState=hicup.update(traj0, predictedState, tm, tm.layer(), chi2rz, chi2rf);
00469 
00470   bool accept=
00471               (dynamic_cast<HICMeasurementEstimator*>(const_cast<Chi2MeasurementEstimatorBase*>(theEstimator))->estimate(newUpdateState,*hit)).first;
00472   if(accept)
00473   {
00474 #ifdef DEBUG
00475   std::cout<<" updateTrajectory::UpdateState::New momentum "<<newUpdateState.freeTrajectoryState()->momentum().perp()<<" "<<newUpdateState.freeTrajectoryState()->momentum().z()<<std::endl;
00476 #endif
00477   TM tmp = TM(predictedState, newUpdateState, hit, tm.estimate(), tm.layer());
00478 
00479   traj.push(tmp );
00480   good=true;
00481   return good;
00482   }
00483     else
00484     {
00485 #ifdef DEBUG
00486        std::cout<<" updateTrajectory::failed after update "<<accept<<std::endl;
00487 #endif
00488        return good;
00489     }
00490   }
00491   else {
00492     return good;
00493   }
00494 }
00495 
00496 bool HICTrajectoryBuilder::toBeContinued (const TempTrajectory& traj) const
00497 {
00498   if ( traj.lostHits() > theMaxLostHit) return false;
00499 
00500   // check for conscutive lost hits only at the end 
00501   // (before the last valid hit),
00502   // since if there was an unacceptable gap before the last 
00503   // valid hit the trajectory would have been stopped already
00504 
00505   int consecLostHit = 0;
00506 
00507   const TempTrajectory::DataContainer & tms = traj.measurements();
00508   //for( TempTrajectory::DataContainer::const_iterator itm=tms.end()-1; itm>=tms.begin(); itm--) {
00509   for( TempTrajectory::DataContainer::const_iterator itm=tms.rbegin(), itb = tms.rend(); itm != itb; --itm) {
00510     if (itm->recHit()->isValid()) break;
00511     else if ( // FIXME: restore this:   !Trajectory::inactive(itm->recHit()->det()) &&
00512              Trajectory::lost(*itm->recHit())) consecLostHit++;
00513   }
00514   if (consecLostHit > theMaxConsecLostHit) return false; 
00515 
00516   // stopping condition from region has highest priority
00517   // if ( regionalCondition && !(*regionalCondition)(traj) )  return false;
00518   // next: pt-cut
00519   //if ( !(*theMinPtCondition)(traj) )  return false;
00520   //if ( !(*theMaxHitsCondition)(traj) )  return false;
00521   // finally: configurable condition
00522   // FIXME: restore this:  if ( !(*theConfigurableCondition)(traj) )  return false;
00523 
00524   return true;
00525 }
00526 
00527 std::vector<TrajectoryMeasurement> 
00528 HICTrajectoryBuilder::findCompatibleMeasurements( const TempTrajectory& traj) const
00529 {
00530   //cout<<" HICTrajectoryBuilder::FindCompatibleMeasurement start "<<traj.empty()<<endl; 
00531   vector<TM> result;
00532  // int invalidHits = 0;
00533   int theLowMult = 1; 
00534 
00535   TSOS currentState( traj.lastMeasurement().updatedState());
00536 
00537   vector<const DetLayer*> nl = 
00538                                traj.lastLayer()->nextLayers( *currentState.freeState(), traj.direction());
00539 #ifdef DEBUG
00540   std::cout<<" Number of layers "<<nl.size()<<std::endl;
00541 #endif
00542   
00543   if (nl.empty()) return result;
00544 
00545   int seedLayerCode = dynamic_cast<HICMeasurementEstimator*>(const_cast<Chi2MeasurementEstimatorBase*>(theEstimator))->
00546                                                               getDetectorCode(traj.measurements().front().layer());
00547 #ifdef DEBUG
00548   std::cout<<"findCompatibleMeasurements Point 0 "<<seedLayerCode<<std::endl;
00549 #endif
00550                                                               
00551   int currentLayerCode = dynamic_cast<HICMeasurementEstimator*>(const_cast<Chi2MeasurementEstimatorBase*>(theEstimator))->
00552                                                                getDetectorCode(traj.lastLayer()); 
00553 #ifdef DEBUG
00554   std::cout<<"findCompatibleMeasurements Point 1 "<<currentLayerCode<<std::endl;
00555 #endif
00556   for (vector<const DetLayer*>::iterator il = nl.begin(); 
00557                                          il != nl.end(); il++) {
00558 
00559    int nextLayerCode = dynamic_cast<HICMeasurementEstimator*>(const_cast<Chi2MeasurementEstimatorBase*>(theEstimator))->
00560                                                                getDetectorCode((*il)); 
00561 #ifdef DEBUG
00562   std::cout<<"findCompatibleMeasurements Point 2 "<<nextLayerCode<<std::endl;
00563 #endif
00564 
00565    if( traj.lastLayer()->location() == GeomDetEnumerators::endcap && (**il).location() == GeomDetEnumerators::barrel )
00566    {
00567    if( abs(seedLayerCode) > 100 && abs(seedLayerCode) < 108 )
00568    {
00569       if( (**il).subDetector() == GeomDetEnumerators::PixelEndcap ) continue;
00570    } // 100-108
00571    else
00572    {
00573     if(theLowMult == 0 )
00574     {      
00575       if( nextLayerCode == 0 ) continue;
00576     }         
00577       if( (**il).subDetector() == GeomDetEnumerators::TID || (**il).subDetector() == GeomDetEnumerators::TEC) continue;
00578    } // 100-108
00579    } // barrel and endcap
00580    
00581    if( currentLayerCode == 101 && nextLayerCode < 100 ) {
00582      continue; 
00583    }  // currentLayer-nextLayer
00584 #ifdef DEBUG   
00585   std::cout<<" findCompatibleMeasurements Point 3 "<<nextLayerCode<<std::endl;
00586 #endif   
00587                                                                        
00588   Trajectory traj0 = traj.toTrajectory();
00589   
00590   vector<double> theCut = dynamic_cast<HICMeasurementEstimator*>(const_cast<Chi2MeasurementEstimatorBase*>(theEstimator))->setCuts(traj0,(*il));
00591   
00592   // Choose Win
00593   int icut = 1;
00594   dynamic_cast<HICMeasurementEstimator*>(const_cast<Chi2MeasurementEstimatorBase*>(theEstimator))->chooseCuts(icut);
00595 #ifdef DEBUG
00596   std::cout<<" findCompatibleMeasurements::current state : "<<
00597              " charge "<< currentState.freeTrajectoryState()->parameters().charge()<<
00598              " pt "<<currentState.freeTrajectoryState()->parameters().momentum().perp()<<
00599              " pz "<<currentState.freeTrajectoryState()->parameters().momentum().z()<<
00600              " r  "<<currentState.freeTrajectoryState()->parameters().position().perp()<<
00601              " phi  "<<currentState.freeTrajectoryState()->parameters().position().phi()<<
00602              " z  "<<currentState.freeTrajectoryState()->parameters().position().z()<<
00603              endl; 
00604 #endif
00605   const MagneticField * mf = dynamic_cast<HICMeasurementEstimator*>(const_cast<Chi2MeasurementEstimatorBase*>(theEstimator))->getField();
00606   vector<TM> tmp0;
00607 
00608 //
00609 // We must check the charge of the high pt track after first step
00610 //
00611 
00612 /*
00613   if(abs(currentLayerCode) > 100&&traj0.measurements().size()>1) {
00614            HICMuonPropagator hmp(mf);
00615 #ifdef DEBUG
00616   std::cout<<" findCompatibleMeasurements::HICMuonPropagator::for forward::start "<<std::endl;
00617 #endif     
00618                tmp0 = 
00619                       theLayerMeasurements->measurements((**il), currentState, hmp, *theEstimator); 
00620       for( vector<TM>::iterator itm = tmp0.begin(); itm != tmp0.end(); itm++ )
00621      {
00622         TM tm = (*itm);
00623         TSOS predictedState = tm.predictedState();
00624         TM::ConstRecHitPointer  hit = tm.recHit();
00625         TSOS updateState = traj0.lastMeasurement().updatedState();
00626 #ifdef DEBUG
00627         std::cout<<" findCompatibleMeasurements::Size of trajectory "<<traj0.measurements().size()<<
00628                    " valid updated state "<< updateState.isValid()<<" Predicted state is valid "
00629                     <<predictedState.isValid()<<
00630                    " charge "<< predictedState.freeTrajectoryState()->parameters().charge()<<
00631                    " pt "<<predictedState.freeTrajectoryState()->parameters().momentum().perp()<<
00632                    " pz "<<predictedState.freeTrajectoryState()->parameters().momentum().z()<<
00633                    " r  "<<predictedState.freeTrajectoryState()->parameters().position().perp()<<
00634                    " phi  "<<predictedState.freeTrajectoryState()->parameters().position().phi()<<
00635                    " z  "<<predictedState.freeTrajectoryState()->parameters().position().z()<<
00636          std::endl;        
00637 #endif
00638      }
00639 #ifdef DEBUG
00640   std::cout<<" findCompatibleMeasurements::HICMuonPropagator::for forward::end "<<std::endl;
00641 #endif             
00642   }
00643 */
00644        tmp0 = theLayerMeasurements->measurements((**il), currentState, *theForwardPropagator, *theEstimator); 
00645                                       
00646 #ifdef DEBUG 
00647   std::cout<<" findCompatibleMeasurements Point 6 "<<theCut[0]<<" "<<theCut[1]<<std::endl;
00648   std::cout<<" findCompatibleMeasurements Point 7 "<<traj0.measurements().size()<<std::endl;
00649 #endif
00650 //   
00651 // ========================= Choose Cut and filter =================================
00652 //
00653      vector<TM> tmp;
00654      icut = 2;
00655      dynamic_cast<HICMeasurementEstimator*>(const_cast<Chi2MeasurementEstimatorBase*>(theEstimator))->chooseCuts(icut);
00656 #ifdef DEBUG
00657      std::cout<<" findCompatibleMeasurements Point 8 "<<theCut[0]<<" "<<theCut[1]<<" Size of candidates "<<tmp0.size()<<std::endl;
00658 #endif  
00659     int numtmp = 0; 
00660      for( vector<TM>::iterator itm = tmp0.begin(); itm != tmp0.end(); itm++ )
00661      {
00662         TM tm = (*itm);
00663         TSOS predictedState = tm.predictedState();
00664         TM::ConstRecHitPointer  hit = tm.recHit();
00665         TSOS updateState = traj0.lastMeasurement().updatedState();
00666 //
00667 // If track is not valid - stop with this hit
00668 //
00669         if(!(*hit).isValid()) {
00670 #ifdef DEBUG
00671          cout<<" findCompatibleMeasurements::hit is not valid "<<endl;
00672 #endif
00673          continue;
00674         } 
00675 
00676 #ifdef DEBUG
00677         std::cout<<" findCompatibleMeasurements::Size of trajectory "<<traj0.measurements().size()
00678                  <<" Number of TM "<< numtmp<<
00679                    " valid updated state "<< updateState.isValid()<<" Predicted state is valid "
00680                     <<predictedState.isValid()<<
00681                    " charge "<< predictedState.freeTrajectoryState()->parameters().charge()<<
00682                    " pt "<<predictedState.freeTrajectoryState()->parameters().momentum().perp()<<
00683                    " pz "<<predictedState.freeTrajectoryState()->parameters().momentum().z()<<
00684                    " r  "<<predictedState.freeTrajectoryState()->parameters().position().perp()<<
00685                    " phi  "<<predictedState.freeTrajectoryState()->parameters().position().phi()<<
00686                    " z  "<<predictedState.freeTrajectoryState()->parameters().position().z()<<
00687          std::endl;
00688 #endif
00689 
00690   if( traj0.measurements().size() == 1 )
00691   {
00692 #ifdef DEBUG
00693        std::cout<<" findCompatibleMeasurements::start corrector "<<std::endl;
00694 #endif
00695         HICTrajectoryCorrector theCorrector(mf,theHICConst);
00696 #ifdef DEBUG    
00697         std::cout<<" findCompatibleMeasurements::corrector::initialized "<<std::endl;
00698 #endif  
00699         TSOS predictedState0 = theCorrector.correct( (*traj0.lastMeasurement().updatedState().freeTrajectoryState()), 
00700                                                       (*(predictedState.freeTrajectoryState())), 
00701                                                       hit->det() );
00702 #ifdef DEBUG                                                  
00703      std::cout<<" findCompatibleMeasurements::end corrector "<<std::endl; 
00704 #endif
00705       if(predictedState0.isValid()) 
00706       {
00707 #ifdef DEBUG
00708               std::cout<<" Accept the corrected state "<<numtmp<<" Hit Valid "<<(*hit).isValid()<<std::endl; 
00709 #endif
00710               predictedState = predictedState0;
00711               
00712         if((*hit).isValid())
00713         {
00714 #ifdef DEBUG
00715                  std::cout<<" findCompatibleMeasurements::end corrector::hit valid "<<std::endl;
00716 #endif  
00717               bool accept= true;
00718               accept = (dynamic_cast<HICMeasurementEstimator*>(const_cast<Chi2MeasurementEstimatorBase*>(theEstimator))->estimate(predictedState,*hit)).first; 
00719               
00720               if(!accept) {
00721 #ifdef DEBUG
00722                   std::cout<<" findCompatibleMeasurements::failed after the first step "<<numtmp<<std::endl;
00723 #endif
00724                   numtmp++;
00725                   continue;
00726               } // accept
00727 #ifdef DEBUG
00728              std::cout<<" findCompatibleMeasurements::estimate at the first step is ok "<<numtmp<<std::endl;
00729 #endif
00730 // Add trajectory measurements
00731              tmp.push_back(TM(predictedState, updateState, hit, tm.estimate(), tm.layer())); 
00732 #ifdef DEBUG
00733              std::cout<<" findCompatibleMeasurements::fill estimate "<<numtmp<<std::endl;
00734 #endif
00735         } // Hit Valid
00736         
00737        } // predicted state is valid
00738    } // first step
00739       else
00740       { 
00741 //          tmp.push_back(TM(predictedState, updateState, hit, tm.estimate(), tm.layer()));
00742 #ifdef DEBUG
00743             std::cout<<" findCompatibleMeasurements::Add TM to collection::Predicted state is valid "<<predictedState.isValid()<<" Hit is valid "<<(*hit).isValid()<<std::endl;
00744 #endif      
00745             if( predictedState.isValid() && (*hit).isValid() ) tmp.push_back(*itm);
00746       } 
00747           numtmp++;
00748 
00749   }             // tm                      
00750 #ifdef DEBUG
00751         std::cout<<" findCompatibleMeasurements::point 9 "<<std::endl;
00752 #endif
00753     if ( !tmp.empty()) {
00754       if ( result.empty() ) result = tmp;
00755       else {
00756         // keep one dummy TM at the end, skip the others
00757         result.insert( result.end(), tmp.begin(), tmp.end());
00758       }
00759     }
00760    //  std::cout<<" Results size "<<result.size()<<std::endl;
00761   } // next layers
00762 
00763   // sort the final result, keep dummy measurements at the end
00764   if ( result.size() > 1) {
00765     sort( result.begin(), result.end(), TrajMeasLessEstim());
00766   }
00767 #ifdef DEBUG
00768        std::cout<<" findCompatibleMeasurements::point 10 "<<std::endl;
00769 #endif
00770   return result;
00771 }
00772