CMS 3D CMS Logo

/afs/cern.ch/work/a/aaltunda/public/www/CMSSW_6_2_5/src/FastSimulation/Muons/plugins/FastTSGFromPropagation.cc

Go to the documentation of this file.
00001 #include "FastSimulation/Muons/plugins/FastTSGFromPropagation.h"
00002 
00010 #include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h"
00011 #include "TrackingTools/TrajectoryState/interface/TrajectoryStateTransform.h"
00012 #include "TrackingTools/PatternTools/interface/Trajectory.h"
00013 #include "TrackingTools/MeasurementDet/interface/LayerMeasurements.h"
00014 #include "TrackingTools/MeasurementDet/interface/MeasurementDet.h"
00015 #include "TrackingTools/KalmanUpdators/interface/Chi2MeasurementEstimator.h"
00016 #include "TrackingTools/GeomPropagators/interface/Propagator.h"
00017 #include "TrackingTools/GeomPropagators/interface/StateOnTrackerBound.h"
00018 
00019 #include "RecoTracker/Record/interface/TrackerRecoGeometryRecord.h"
00020 #include "RecoTracker/Record/interface/CkfComponentsRecord.h"
00021 // #include "RecoTracker/MeasurementDet/interface/TkStripMeasurementDet.h"
00022 #include "RecoTracker/MeasurementDet/interface/MeasurementTracker.h"
00023 #include "RecoTracker/TkDetLayers/interface/GeometricSearchTracker.h"
00024 
00025 #include "RecoMuon/GlobalTrackingTools/interface/DirectTrackerNavigation.h"
00026 #include "TrackingTools/KalmanUpdators/interface/KFUpdator.h"
00027 
00028 #include "FWCore/MessageLogger/interface/MessageLogger.h"
00029 #include "FWCore/ServiceRegistry/interface/Service.h"
00030 #include "CommonTools/UtilAlgos/interface/TFileService.h"
00031 
00032 #include "SimDataFormats/Track/interface/SimTrackContainer.h"
00033 #include "DataFormats/TrackerRecHit2D/interface/SiTrackerGSRecHit2DCollection.h"
00034 #include "DataFormats/TrackerRecHit2D/interface/SiTrackerGSMatchedRecHit2DCollection.h"
00035 #include "FastSimulation/Tracking/interface/TrackerRecHit.h"
00036 #include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h"
00037 #include "Geometry/Records/interface/TrackerDigiGeometryRecord.h"
00038 #include "Geometry/CommonDetUnit/interface/GeomDetUnit.h"
00039 #include "FastSimulation/Tracking/plugins/TrajectorySeedProducer.h"
00040 #include "TrackingTools/TransientTrackingRecHit/interface/GenericTransientTrackingRecHit.h"
00041 #include "TrackingTools/Records/interface/TransientRecHitRecord.h"
00042 #include "DataFormats/TrackerCommon/interface/TrackerTopology.h"
00043 
00044 using namespace std;
00045 
00046 
00047 FastTSGFromPropagation::FastTSGFromPropagation(const edm::ParameterSet & iConfig) :theTkLayerMeasurements (0), theTracker(0), theNavigation(0), theService(0), theEstimator(0),  theSigmaZ(0), theConfig (iConfig),
00048   beamSpot_(iConfig.getParameter<edm::InputTag>("beamSpot"))
00049 {
00050   theCategory = "FastSimulation|Muons||FastTSGFromPropagation";
00051 
00052 }
00053 
00054 FastTSGFromPropagation::FastTSGFromPropagation(const edm::ParameterSet & iConfig, const MuonServiceProxy* service) : theTkLayerMeasurements (0), theTracker(0), theNavigation(0), theService(service),theUpdator(0), theEstimator(0), theSigmaZ(0), theConfig (iConfig),
00055   beamSpot_(iConfig.getParameter<edm::InputTag>("beamSpot"))
00056 {
00057   theCategory = "FastSimulation|Muons|FastTSGFromPropagation";
00058 }
00059 
00060 FastTSGFromPropagation::~FastTSGFromPropagation()
00061 {
00062 
00063   LogTrace(theCategory) << " FastTSGFromPropagation dtor called ";
00064   if ( theNavigation ) delete theNavigation;
00065   if ( theUpdator ) delete theUpdator;
00066   if ( theEstimator ) delete theEstimator;
00067   if ( theTkLayerMeasurements ) delete theTkLayerMeasurements;
00068   if ( theErrorMatrixAdjuster ) delete theErrorMatrixAdjuster;
00069 
00070 }
00071 
00072 void FastTSGFromPropagation::trackerSeeds(const TrackCand& staMuon, const TrackingRegion& region, 
00073                                           const TrackerTopology *tTopo, std::vector<TrajectorySeed> & result) {
00074 
00075   if ( theResetMethod == "discrete" ) getRescalingFactor(staMuon);
00076 
00077   TrajectoryStateOnSurface staState = outerTkState(staMuon);
00078 
00079   if ( !staState.isValid() ) { 
00080     LogTrace(theCategory) << "Error: initial state from L2 muon is invalid.";
00081     return;
00082   }
00083 
00084   LogTrace(theCategory) << "begin of trackerSeed:\n staState pos: "<<staState.globalPosition()
00085                         << " mom: "<<staState.globalMomentum() 
00086                         <<"pos eta: "<<staState.globalPosition().eta()
00087                         <<"mom eta: "<<staState.globalMomentum().eta();
00088 
00089 
00090   std::vector<const DetLayer*> nls = theNavigation->compatibleLayers(*(staState.freeState()), oppositeToMomentum);
00091 
00092   LogTrace(theCategory) << " compatible layers: "<<nls.size();
00093 
00094   if ( nls.empty() ) return;
00095 
00096   int ndesLayer = 0;
00097 
00098   bool usePredictedState = false;
00099 
00100   if ( theUpdateStateFlag ) { //use updated states
00101      std::vector<TrajectoryMeasurement> alltm; 
00102 
00103      for (std::vector<const DetLayer*>::const_iterator inl = nls.begin();
00104          inl != nls.end(); inl++, ndesLayer++ ) {
00105          if ( (*inl == 0) ) break;
00106 //         if ( (inl != nls.end()-1 ) && ( (*inl)->subDetector() == GeomDetEnumerators::TEC ) && ( (*(inl+1))->subDetector() == GeomDetEnumerators::TOB ) ) continue; 
00107          alltm = findMeasurements_new(*inl, staState);
00108          if ( (!alltm.empty()) ) {
00109             LogTrace(theCategory) << "final compatible layer: "<<ndesLayer;
00110             break;
00111          }
00112      }
00113 
00114      if ( alltm.empty() ) {
00115         LogTrace(theCategory) << " NO Measurements Found: eta: "<<staState.globalPosition().eta() <<"pt "<<staState.globalMomentum().perp();
00116         usePredictedState = true;
00117      } else {
00118        LogTrace(theCategory) << " Measurements for seeds: "<<alltm.size();
00119        std::stable_sort(alltm.begin(),alltm.end(),increasingEstimate()); 
00120        if ( alltm.size() > 5 ) alltm.erase(alltm.begin() + 5, alltm.end());
00121 
00122        const edm::SimTrackContainer* simTracks = &(*theSimTracks);
00123        const std::vector<unsigned> theSimTrackIds = theGSRecHits->ids();
00124        TrackerRecHit theSeedHits;
00125        std::vector<TrackerRecHit> outerHits;
00126 
00127        //std::vector<TrajectorySeed>  tmpTS;
00128        bool isMatch = false;
00129        for (std::vector<TrajectoryMeasurement>::const_iterator itm = alltm.begin(); itm != alltm.end(); itm++) {
00130            const TrajectoryStateOnSurface seedState = itm->predictedState();
00131            double preY = seedState.globalPosition().y();
00132 
00133            // Check SimTrack
00134            TrackingRecHit* aTrackingRecHit;
00135            FreeTrajectoryState simtrack_trackerstate;
00136            for( unsigned tkId=0;  tkId != theSimTrackIds.size(); ++tkId ) {
00137                const SimTrack & simtrack = (*simTracks)[theSimTrackIds[tkId]];
00138                SiTrackerGSMatchedRecHit2DCollection::range theRecHitRange = theGSRecHits->get(theSimTrackIds[tkId]);
00139                SiTrackerGSMatchedRecHit2DCollection::const_iterator theRecHitRangeIteratorBegin = theRecHitRange.first;
00140                SiTrackerGSMatchedRecHit2DCollection::const_iterator theRecHitRangeIteratorEnd   = theRecHitRange.second;
00141                SiTrackerGSMatchedRecHit2DCollection::const_iterator iterRecHit;
00142 
00143                GlobalPoint position(simtrack.trackerSurfacePosition().x(),
00144                                     simtrack.trackerSurfacePosition().y(),
00145                                     simtrack.trackerSurfacePosition().z());
00146                GlobalVector momentum(simtrack.trackerSurfaceMomentum().x(),
00147                                      simtrack.trackerSurfaceMomentum().y(),
00148                                      simtrack.trackerSurfaceMomentum().z());
00149                int charge = (int)simtrack.charge();
00150                GlobalTrajectoryParameters glb_parameters(position, momentum, charge, &*theService->magneticField().product());
00151                simtrack_trackerstate = FreeTrajectoryState(glb_parameters);
00152 
00153                unsigned int outerId = 0;
00154                for( iterRecHit = theRecHitRangeIteratorBegin; iterRecHit != theRecHitRangeIteratorEnd; ++iterRecHit) {
00155                  theSeedHits = TrackerRecHit(&(*iterRecHit), theGeometry, tTopo);
00156                    unsigned int id = theSeedHits.hit()->geographicalId().rawId();
00157                    if( preY < 0 ) {
00158                        if( id > outerId ) outerId = id;
00159                    }
00160                    else {
00161                        if( id > outerId ) outerId = id;
00162                    }
00163                }
00164                for( iterRecHit = theRecHitRangeIteratorBegin; iterRecHit != theRecHitRangeIteratorEnd; ++iterRecHit) {
00165                  theSeedHits = TrackerRecHit(&(*iterRecHit), theGeometry, tTopo);
00166                    if( itm->recHit()->hit()->geographicalId().rawId() == theSeedHits.hit()->geographicalId().rawId() ) {
00167                        aTrackingRecHit = theSeedHits.hit()->clone();
00168                        TransientTrackingRecHit::ConstRecHitPointer recHit = theTTRHBuilder->build(aTrackingRecHit);
00169                        if( !recHit ) continue;
00170                        TrajectoryStateOnSurface updatedTSOS = updator()->update(seedState, *(recHit));
00171                        if( updatedTSOS.isValid() && passSelection(updatedTSOS) ) {
00172                            edm::OwnVector<TrackingRecHit> container;
00173                            container.push_back(recHit->hit()->clone());
00174                            TrajectorySeed ts = createSeed(updatedTSOS, container, recHit->geographicalId());
00175                            // check direction
00176                            const BasicTrajectorySeed* aSeed = &ts;
00177                            PTrajectoryStateOnDet PTSOD = aSeed->startingState();
00178                            
00179                            const GeomDet *g = theGeometry->idToDet(PTSOD.detId());
00180                            TrajectoryStateOnSurface tsos = trajectoryStateTransform::transientState(PTSOD, &(g->surface()),  &*theService->magneticField().product());
00181                            if( tsos.globalMomentum().basicVector()*seedState.globalMomentum().basicVector() < 0. ) continue;
00182                            result.push_back(ts);
00183                            isMatch = true;
00184                        }
00185                    }
00186                }
00187            }
00188        }
00189        if( !isMatch ) {
00190          // if there is no hits w.r.t. TM, find outermost hit
00191          for (std::vector<TrajectoryMeasurement>::const_iterator itm = alltm.begin(); itm != alltm.end(); itm++) {
00192            const TrajectoryStateOnSurface seedState = itm->predictedState();
00193            double preY = seedState.globalPosition().y();
00194 
00195            // Check SimTrack
00196            TrackingRecHit* aTrackingRecHit;
00197            FreeTrajectoryState simtrack_trackerstate;
00198            for( unsigned tkId=0;  tkId != theSimTrackIds.size(); ++tkId ) {
00199                const SimTrack & simtrack = (*simTracks)[theSimTrackIds[tkId]];
00200                SiTrackerGSMatchedRecHit2DCollection::range theRecHitRange = theGSRecHits->get(theSimTrackIds[tkId]);
00201                SiTrackerGSMatchedRecHit2DCollection::const_iterator theRecHitRangeIteratorBegin = theRecHitRange.first;
00202                SiTrackerGSMatchedRecHit2DCollection::const_iterator theRecHitRangeIteratorEnd   = theRecHitRange.second;
00203                SiTrackerGSMatchedRecHit2DCollection::const_iterator iterRecHit;
00204 
00205                GlobalPoint position(simtrack.trackerSurfacePosition().x(),
00206                                     simtrack.trackerSurfacePosition().y(),
00207                                     simtrack.trackerSurfacePosition().z());
00208                GlobalVector momentum(simtrack.trackerSurfaceMomentum().x(),
00209                                      simtrack.trackerSurfaceMomentum().y(),
00210                                      simtrack.trackerSurfaceMomentum().z());
00211                int charge = (int)simtrack.charge();
00212                GlobalTrajectoryParameters glb_parameters(position, momentum, charge, &*theService->magneticField().product());
00213                simtrack_trackerstate = FreeTrajectoryState(glb_parameters);
00214 
00215                unsigned int outerId = 0;
00216                for( iterRecHit = theRecHitRangeIteratorBegin; iterRecHit != theRecHitRangeIteratorEnd; ++iterRecHit) {
00217                  theSeedHits = TrackerRecHit(&(*iterRecHit), theGeometry, tTopo);
00218                    unsigned int id = theSeedHits.hit()->geographicalId().rawId();
00219                    if( preY < 0 ) {
00220                        if( id > outerId ) outerId = id;
00221                    }
00222                    else {
00223                        if( id > outerId ) outerId = id;
00224                    }
00225                }
00226                for( iterRecHit = theRecHitRangeIteratorBegin; iterRecHit != theRecHitRangeIteratorEnd; ++iterRecHit) {
00227                  theSeedHits = TrackerRecHit(&(*iterRecHit), theGeometry, tTopo);
00228                    if( outerId == theSeedHits.hit()->geographicalId().rawId() ) {
00229                        aTrackingRecHit = theSeedHits.hit()->clone();
00230                        TransientTrackingRecHit::ConstRecHitPointer recHit = theTTRHBuilder->build(aTrackingRecHit);
00231                        if( !recHit ) continue;
00232                        TrajectoryStateOnSurface updatedTSOS = updator()->update(seedState, *(recHit));
00233                        if( updatedTSOS.isValid() && passSelection(updatedTSOS) ) {
00234                            edm::OwnVector<TrackingRecHit> container;
00235                            container.push_back(recHit->hit()->clone());
00236                            TrajectorySeed ts = createSeed(updatedTSOS, container, recHit->geographicalId());
00237                            // check direction
00238                            const BasicTrajectorySeed* aSeed = &ts;
00239                            PTrajectoryStateOnDet PTSOD = aSeed->startingState();
00240                            
00241                            const GeomDet *g = theGeometry->idToDet(PTSOD.detId());
00242                            TrajectoryStateOnSurface tsos = trajectoryStateTransform::transientState(PTSOD, &(g->surface()),  &*theService->magneticField().product());
00243                            if( tsos.globalMomentum().basicVector()*seedState.globalMomentum().basicVector() < 0. ) continue;
00244                            result.push_back(ts);
00245                        }
00246                    }
00247                }
00248            }
00249          }
00250        }
00251 
00252        /*
00253        for( unsigned ir = 0; ir < tmpTS.size(); ir++ ) {
00254          const BasicTrajectorySeed* aSeed = &((tmpTS)[ir]);
00255          PTrajectoryStateOnDet PTSOD = aSeed->startingState();
00256          
00257          DetId seedDetId(PTSOD.detId());
00258          const GeomDet * g = theGeometry->idToDet(seedDetId);
00259          TrajectoryStateOnSurface tsos = trajectoryStateTransform::transientState(PTSOD, &(g->surface()),  &*theService->magneticField().product());
00260                  cout << "tsos3 = " << tsos.globalMomentum() << endl;
00261          if( _index == ir ) {
00262                  cout << "tsos4 = " << tsos.globalMomentum() << endl;
00263              result.push_back(tmpTS[ir]);
00264          }
00265        }
00266        */
00267        LogTrace(theCategory) << "result: "<<result.size();
00268        return;
00269      }
00270   }
00271   
00272   if ( !theUpdateStateFlag || usePredictedState ) { //use predicted states
00273      LogTrace(theCategory) << "use predicted state: ";
00274      for (std::vector<const DetLayer*>::const_iterator inl = nls.begin();
00275          inl != nls.end(); inl++ ) {
00276 
00277          if ( !result.empty() || *inl == 0 ) {
00278             break;
00279          }
00280          std::vector<DetLayer::DetWithState> compatDets = (*inl)->compatibleDets(staState, *propagator(), *estimator());
00281          LogTrace(theCategory) << " compatDets "<<compatDets.size();
00282          if ( compatDets.empty() ) continue;
00283          TrajectorySeed ts = createSeed(compatDets.front().second, compatDets.front().first->geographicalId());
00284          result.push_back(ts);
00285 
00286      }
00287      LogTrace(theCategory) << "result: "<<result.size();
00288      return;
00289   } 
00290   return;
00291 }
00292 
00293 void FastTSGFromPropagation::init(const MuonServiceProxy* service) {
00294 
00295   theMaxChi2 = theConfig.getParameter<double>("MaxChi2");
00296 
00297   theFixedErrorRescaling = theConfig.getParameter<double>("ErrorRescaling");
00298 
00299   theFlexErrorRescaling = 1.0;
00300 
00301   theResetMethod = theConfig.getParameter<std::string>("ResetMethod");
00302 
00303   if (theResetMethod != "discrete" && theResetMethod != "fixed" && theResetMethod != "matrix"  ) {
00304     edm::LogError("FastTSGFromPropagation") 
00305       <<"Wrong error rescaling method: "<<theResetMethod <<"\n"
00306       <<"Possible choices are: discrete, fixed, matrix.\n"
00307       <<"Use discrete method" <<std::endl;
00308     theResetMethod = "discrete"; 
00309   }
00310 
00311   theEstimator = new Chi2MeasurementEstimator(theMaxChi2);
00312 
00313   theCacheId_MT = 0;
00314 
00315   theCacheId_TG = 0;
00316 
00317   thePropagatorName = theConfig.getParameter<std::string>("Propagator");
00318 
00319   theService = service;
00320 
00321   theUseVertexStateFlag = theConfig.getParameter<bool>("UseVertexState");
00322 
00323   theUpdateStateFlag = theConfig.getParameter<bool>("UpdateState");
00324 
00325   theSelectStateFlag = theConfig.getParameter<bool>("SelectState");
00326 
00327   theSimTrackCollectionLabel = theConfig.getParameter<edm::InputTag>("SimTrackCollectionLabel");
00328   theHitProducer = theConfig.getParameter<edm::InputTag>("HitProducer");
00329 
00330   theUpdator = new KFUpdator();
00331 
00332   theSigmaZ = theConfig.getParameter<double>("SigmaZ");
00333 
00334   edm::ParameterSet errorMatrixPset = theConfig.getParameter<edm::ParameterSet>("errorMatrixPset");
00335   if ( theResetMethod == "matrix" && !errorMatrixPset.empty()){
00336     theAdjustAtIp = errorMatrixPset.getParameter<bool>("atIP");
00337     theErrorMatrixAdjuster = new MuonErrorMatrix(errorMatrixPset);
00338   } else {
00339     theAdjustAtIp =false;
00340     theErrorMatrixAdjuster=0;
00341   }
00342 
00343   theService->eventSetup().get<TrackerRecoGeometryRecord>().get(theTracker); 
00344   theNavigation = new DirectTrackerNavigation(theTracker);
00345 
00346   edm::ESHandle<TrackerGeometry>        geometry;
00347   theService->eventSetup().get<TrackerDigiGeometryRecord>().get(geometry);
00348   theGeometry = &(*geometry);
00349 
00350   theService->eventSetup().get<TransientRecHitRecord>().get("WithTrackAngle", theTTRHBuilder);
00351 
00352 }
00353 
00354 void FastTSGFromPropagation::setEvent(const edm::Event& iEvent) {
00355 
00356   bool measTrackerChanged = false;
00357 
00358   iEvent.getByLabel(beamSpot_, theBeamSpot);
00359   
00360   // retrieve the MC truth (SimTracks)
00361   iEvent.getByLabel(theSimTrackCollectionLabel, theSimTracks);
00362   iEvent.getByLabel(theHitProducer, theGSRecHits);
00363 
00364 
00365   unsigned long long newCacheId_MT = theService->eventSetup().get<CkfComponentsRecord>().cacheIdentifier();
00366 
00367   if ( theUpdateStateFlag && newCacheId_MT != theCacheId_MT ) {
00368     LogTrace(theCategory) << "Measurment Tracker Geometry changed!";
00369     theCacheId_MT = newCacheId_MT;
00370     theService->eventSetup().get<CkfComponentsRecord>().get(theMeasTracker);
00371     measTrackerChanged = true;
00372   }
00373 
00374   //if ( theUpdateStateFlag ) theMeasTracker->update(iEvent);
00375 
00376   if ( measTrackerChanged && (&*theMeasTracker) ) {
00377      if ( theTkLayerMeasurements ) delete theTkLayerMeasurements;
00378      theTkLayerMeasurements = new LayerMeasurements(&*theMeasTracker);
00379   }
00380 
00381   bool trackerGeomChanged = false;
00382 
00383   unsigned long long newCacheId_TG = theService->eventSetup().get<TrackerRecoGeometryRecord>().cacheIdentifier();
00384 
00385   if ( newCacheId_TG != theCacheId_TG ) {
00386     LogTrace(theCategory) << "Tracker Reco Geometry changed!";
00387     theCacheId_TG = newCacheId_TG;
00388     theService->eventSetup().get<TrackerRecoGeometryRecord>().get(theTracker);
00389     trackerGeomChanged = true;
00390   }
00391 
00392   if ( trackerGeomChanged && (&*theTracker) ) {
00393     if ( theNavigation ) delete theNavigation;
00394     theNavigation = new DirectTrackerNavigation(theTracker);
00395   }
00396 }
00397 
00398 TrajectoryStateOnSurface FastTSGFromPropagation::innerState(const TrackCand& staMuon) const {
00399 
00400   TrajectoryStateOnSurface innerTS;
00401 
00402   if ( staMuon.first && staMuon.first->isValid() ) {
00403     if (staMuon.first->direction() == alongMomentum) {
00404       innerTS = staMuon.first->firstMeasurement().updatedState();
00405     } 
00406     else if (staMuon.first->direction() == oppositeToMomentum) { 
00407       innerTS = staMuon.first->lastMeasurement().updatedState();
00408     }
00409   } else {
00410     innerTS = trajectoryStateTransform::innerStateOnSurface(*(staMuon.second),*theService->trackingGeometry(), &*theService->magneticField());
00411   }
00412   //rescale the error
00413   adjust(innerTS);
00414 
00415   return  innerTS;
00416 
00417 }
00418 
00419 TrajectoryStateOnSurface FastTSGFromPropagation::outerTkState(const TrackCand& staMuon) const {
00420 
00421   TrajectoryStateOnSurface result;
00422 
00423   if ( theUseVertexStateFlag && staMuon.second->pt() > 1.0 ) {
00424     FreeTrajectoryState iniState = trajectoryStateTransform::initialFreeState(*(staMuon.second), &*theService->magneticField());
00425     //rescale the error at IP
00426     adjust(iniState); 
00427 
00428     StateOnTrackerBound fromInside(&*(theService->propagator("PropagatorWithMaterial")));
00429     result = fromInside(iniState);
00430   } else {
00431     StateOnTrackerBound fromOutside(&*propagator());
00432     result = fromOutside(innerState(staMuon));
00433   }
00434   return result;
00435 }
00436 
00437 TrajectorySeed FastTSGFromPropagation::createSeed(const TrajectoryStateOnSurface& tsos, const DetId& id) const {
00438 
00439   edm::OwnVector<TrackingRecHit> container;
00440   return createSeed(tsos, container, id);
00441 
00442 }
00443 
00444 TrajectorySeed FastTSGFromPropagation::createSeed(const TrajectoryStateOnSurface& tsos, const edm::OwnVector<TrackingRecHit>& container, const DetId& id) const {
00445 
00446   PTrajectoryStateOnDet seedTSOS = trajectoryStateTransform::persistentState(tsos,id.rawId());
00447   return TrajectorySeed(seedTSOS,container,oppositeToMomentum);
00448 
00449 }
00450 
00451 
00452 void FastTSGFromPropagation::validMeasurements(std::vector<TrajectoryMeasurement>& tms) const {
00453 
00454   std::vector<TrajectoryMeasurement>::iterator tmsend = std::remove_if(tms.begin(), tms.end(), isInvalid());
00455   tms.erase(tmsend, tms.end());
00456   return;
00457 
00458 }
00459 
00460 std::vector<TrajectoryMeasurement> FastTSGFromPropagation::findMeasurements_new(const DetLayer* nl, const TrajectoryStateOnSurface& staState) const {
00461 
00462   std::vector<TrajectoryMeasurement> result;
00463 
00464   std::vector<DetLayer::DetWithState> compatDets = nl->compatibleDets(staState, *propagator(), *estimator());
00465   if ( compatDets.empty() )  return result;
00466 
00467   for (std::vector<DetLayer::DetWithState>::const_iterator idws = compatDets.begin(); idws != compatDets.end(); ++idws) {
00468      if ( idws->second.isValid() && (idws->first) )  {
00469          std::vector<TrajectoryMeasurement> tmptm = 
00470            theMeasTracker->idToDet(idws->first->geographicalId())->fastMeasurements(idws->second, idws->second, *propagator(), *estimator());
00471          //validMeasurements(tmptm);
00472 //         if ( tmptm.size() > 2 ) {
00473 //            std::stable_sort(tmptm.begin(),tmptm.end(),increasingEstimate());
00474 //            result.insert(result.end(),tmptm.begin(), tmptm.begin()+2);
00475 //         } else {
00476             result.insert(result.end(),tmptm.begin(), tmptm.end());
00477 //         }
00478      }
00479   }
00480   
00481   return result;
00482 
00483 }
00484 
00485 std::vector<TrajectoryMeasurement> FastTSGFromPropagation::findMeasurements(const DetLayer* nl, const TrajectoryStateOnSurface& staState) const {
00486 
00487   std::vector<TrajectoryMeasurement> result = tkLayerMeasurements()->measurements((*nl), staState, *propagator(), *estimator());
00488   validMeasurements(result);
00489   return result;
00490 }
00491 
00492 bool FastTSGFromPropagation::passSelection(const TrajectoryStateOnSurface& tsos) const {
00493   if ( !theSelectStateFlag ) return true;
00494   else {
00495      if ( theBeamSpot.isValid() ) {
00496        return ( ( fabs(zDis(tsos) - theBeamSpot->z0() ) < theSigmaZ) );
00497 
00498      } else {
00499        return ( ( fabs(zDis(tsos)) < theSigmaZ) ); 
00500 //      double theDxyCut = 100;
00501 //      return ( (zDis(tsos) < theSigmaZ) && (dxyDis(tsos) < theDxyCut) );
00502      }
00503   }
00504 
00505 }
00506 
00507 double FastTSGFromPropagation::dxyDis(const TrajectoryStateOnSurface& tsos) const {
00508   return fabs(( - tsos.globalPosition().x() * tsos.globalMomentum().y() + tsos.globalPosition().y() * tsos.globalMomentum().x() )/tsos.globalMomentum().perp());
00509 }
00510 
00511 double FastTSGFromPropagation::zDis(const TrajectoryStateOnSurface& tsos) const {
00512   return tsos.globalPosition().z() - tsos.globalPosition().perp() * tsos.globalMomentum().z()/tsos.globalMomentum().perp();
00513 }
00514 
00515 void FastTSGFromPropagation::getRescalingFactor(const TrackCand& staMuon) {
00516     float pt = (staMuon.second)->pt();
00517     if ( pt < 13.0 ) theFlexErrorRescaling = 3; 
00518     else if ( pt < 30.0 ) theFlexErrorRescaling = 5;
00519     else theFlexErrorRescaling = 10;
00520     return;
00521 }
00522 
00523 
00524 void FastTSGFromPropagation::adjust(FreeTrajectoryState & state) const {
00525 
00526   //rescale the error
00527   if ( theResetMethod == "discreate" ) {
00528      state.rescaleError(theFlexErrorRescaling);
00529      return;
00530   }
00531 
00532   //rescale the error
00533   if ( theResetMethod == "fixed" || !theErrorMatrixAdjuster) {
00534      state.rescaleError(theFixedErrorRescaling);
00535      return;
00536   }
00537 
00538   CurvilinearTrajectoryError oMat = state.curvilinearError();
00539   CurvilinearTrajectoryError sfMat = theErrorMatrixAdjuster->get(state.momentum());//FIXME with position
00540   MuonErrorMatrix::multiply(oMat, sfMat);
00541   
00542   state = FreeTrajectoryState(state.parameters(),
00543                               oMat);
00544 }
00545 
00546 void FastTSGFromPropagation::adjust(TrajectoryStateOnSurface & state) const {
00547 
00548   //rescale the error
00549   if ( theResetMethod == "discreate" ) {
00550      state.rescaleError(theFlexErrorRescaling);
00551      return;
00552   }
00553 
00554   if ( theResetMethod == "fixed" || !theErrorMatrixAdjuster) {
00555      state.rescaleError(theFixedErrorRescaling);
00556      return;
00557   }
00558 
00559   CurvilinearTrajectoryError oMat = state.curvilinearError();
00560   CurvilinearTrajectoryError sfMat = theErrorMatrixAdjuster->get(state.globalMomentum());//FIXME with position
00561   MuonErrorMatrix::multiply(oMat, sfMat);
00562   
00563   state = TrajectoryStateOnSurface(state.globalParameters(),
00564                                    oMat,
00565                                    state.surface(),
00566                                    state.surfaceSide(),
00567                                    state.weight());
00568 }
00569 
00570 void FastTSGFromPropagation::stateOnDet(const TrajectoryStateOnSurface& ts,
00571                                         unsigned int detid,
00572                                         PTrajectoryStateOnDet& pts) const
00573 {
00574     const AlgebraicSymMatrix55& m = ts.localError().matrix();
00575     int dim = 5; 
00576     float localErrors[15];
00577     int k = 0;
00578     for (int i=0; i<dim; ++i) {
00579         for (int j=0; j<=i; ++j) {
00580             localErrors[k++] = m(i,j);
00581         }
00582     }
00583     int surfaceSide = static_cast<int>(ts.surfaceSide());
00584     pts = PTrajectoryStateOnDet( ts.localParameters(),
00585                                 localErrors, detid,
00586                                 surfaceSide);
00587 }