CMS 3D CMS Logo

/data/refman/pasoursint/CMSSW_4_1_8_patch9/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/KalmanUpdators/interface/Chi2MeasurementEstimator.h"
00015 #include "TrackingTools/GeomPropagators/interface/Propagator.h"
00016 #include "TrackingTools/GeomPropagators/interface/StateOnTrackerBound.h"
00017 
00018 #include "RecoTracker/Record/interface/TrackerRecoGeometryRecord.h"
00019 #include "RecoTracker/Record/interface/CkfComponentsRecord.h"
00020 #include "RecoTracker/MeasurementDet/interface/TkStripMeasurementDet.h"
00021 #include "RecoTracker/MeasurementDet/interface/MeasurementTracker.h"
00022 #include "RecoTracker/TkDetLayers/interface/GeometricSearchTracker.h"
00023 
00024 #include "RecoMuon/GlobalTrackingTools/interface/DirectTrackerNavigation.h"
00025 #include "TrackingTools/KalmanUpdators/interface/KFUpdator.h"
00026 
00027 #include "FWCore/MessageLogger/interface/MessageLogger.h"
00028 #include "FWCore/ServiceRegistry/interface/Service.h"
00029 #include "CommonTools/UtilAlgos/interface/TFileService.h"
00030 
00031 #include "SimDataFormats/Track/interface/SimTrackContainer.h"
00032 #include "DataFormats/TrackerRecHit2D/interface/SiTrackerGSRecHit2DCollection.h"
00033 #include "DataFormats/TrackerRecHit2D/interface/SiTrackerGSMatchedRecHit2DCollection.h"
00034 #include "FastSimulation/Tracking/interface/TrackerRecHit.h"
00035 #include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h"
00036 #include "Geometry/Records/interface/TrackerDigiGeometryRecord.h"
00037 #include "Geometry/CommonDetUnit/interface/GeomDetUnit.h"
00038 #include "FastSimulation/Tracking/plugins/TrajectorySeedProducer.h"
00039 #include "TrackingTools/TransientTrackingRecHit/interface/GenericTransientTrackingRecHit.h"
00040 #include "TrackingTools/Records/interface/TransientRecHitRecord.h"
00041 
00042 
00043 using namespace std;
00044 
00045 
00046 FastTSGFromPropagation::FastTSGFromPropagation(const edm::ParameterSet & iConfig) :theTkLayerMeasurements (0), theTracker(0), theNavigation(0), theService(0), theEstimator(0), theTSTransformer(0), theSigmaZ(0), theConfig (iConfig)
00047 {
00048   theCategory = "FastSimulation|Muons||FastTSGFromPropagation";
00049 
00050 }
00051 
00052 FastTSGFromPropagation::FastTSGFromPropagation(const edm::ParameterSet & iConfig, const MuonServiceProxy* service) : theTkLayerMeasurements (0), theTracker(0), theNavigation(0), theService(service),theUpdator(0), theEstimator(0), theTSTransformer(0), theSigmaZ(0), theConfig (iConfig)
00053 {
00054   theCategory = "FastSimulation|Muons|FastTSGFromPropagation";
00055 }
00056 
00057 FastTSGFromPropagation::~FastTSGFromPropagation()
00058 {
00059 
00060   LogTrace(theCategory) << " FastTSGFromPropagation dtor called ";
00061   if ( theNavigation ) delete theNavigation;
00062   if ( theUpdator ) delete theUpdator;
00063   if ( theEstimator ) delete theEstimator;
00064   if ( theTkLayerMeasurements ) delete theTkLayerMeasurements;
00065   if ( theTSTransformer ) delete  theTSTransformer;
00066   if ( theErrorMatrixAdjuster ) delete theErrorMatrixAdjuster;
00067 
00068 }
00069 
00070 void FastTSGFromPropagation::trackerSeeds(const TrackCand& staMuon, const TrackingRegion& region, std::vector<TrajectorySeed> & result) {
00071 
00072   if ( theResetMethod == "discrete" ) getRescalingFactor(staMuon);
00073 
00074   TrajectoryStateOnSurface staState = outerTkState(staMuon);
00075 
00076   if ( !staState.isValid() ) { 
00077     LogTrace(theCategory) << "Error: initial state from L2 muon is invalid.";
00078     return;
00079   }
00080 
00081   LogTrace(theCategory) << "begin of trackerSeed:\n staState pos: "<<staState.globalPosition()
00082                         << " mom: "<<staState.globalMomentum() 
00083                         <<"pos eta: "<<staState.globalPosition().eta()
00084                         <<"mom eta: "<<staState.globalMomentum().eta();
00085 
00086 
00087   std::vector<const DetLayer*> nls = theNavigation->compatibleLayers(*(staState.freeState()), oppositeToMomentum);
00088 
00089   LogTrace(theCategory) << " compatible layers: "<<nls.size();
00090 
00091   if ( nls.empty() ) return;
00092 
00093   int ndesLayer = 0;
00094 
00095   bool usePredictedState = false;
00096 
00097   if ( theUpdateStateFlag ) { //use updated states
00098      std::vector<TrajectoryMeasurement> alltm; 
00099 
00100      for (std::vector<const DetLayer*>::const_iterator inl = nls.begin();
00101          inl != nls.end(); inl++, ndesLayer++ ) {
00102          if ( (*inl == 0) ) break;
00103 //         if ( (inl != nls.end()-1 ) && ( (*inl)->subDetector() == GeomDetEnumerators::TEC ) && ( (*(inl+1))->subDetector() == GeomDetEnumerators::TOB ) ) continue; 
00104          alltm = findMeasurements_new(*inl, staState);
00105          if ( (!alltm.empty()) ) {
00106             LogTrace(theCategory) << "final compatible layer: "<<ndesLayer;
00107             break;
00108          }
00109      }
00110 
00111      if ( alltm.empty() ) {
00112         LogTrace(theCategory) << " NO Measurements Found: eta: "<<staState.globalPosition().eta() <<"pt "<<staState.globalMomentum().perp();
00113         usePredictedState = true;
00114      } else {
00115        LogTrace(theCategory) << " Measurements for seeds: "<<alltm.size();
00116        std::stable_sort(alltm.begin(),alltm.end(),increasingEstimate()); 
00117        if ( alltm.size() > 5 ) alltm.erase(alltm.begin() + 5, alltm.end());
00118 
00119        const edm::SimTrackContainer* simTracks = &(*theSimTracks);
00120        const std::vector<unsigned> theSimTrackIds = theGSRecHits->ids();
00121        TrackerRecHit theSeedHits;
00122        std::vector<TrackerRecHit> outerHits;
00123 
00124        //std::vector<TrajectorySeed>  tmpTS;
00125        bool isMatch = false;
00126        for (std::vector<TrajectoryMeasurement>::const_iterator itm = alltm.begin(); itm != alltm.end(); itm++) {
00127            const TrajectoryStateOnSurface seedState = itm->predictedState();
00128            double preY = seedState.globalPosition().y();
00129 
00130            // Check SimTrack
00131            TrackingRecHit* aTrackingRecHit;
00132            FreeTrajectoryState simtrack_trackerstate;
00133            for( unsigned tkId=0;  tkId != theSimTrackIds.size(); ++tkId ) {
00134                const SimTrack & simtrack = (*simTracks)[theSimTrackIds[tkId]];
00135                SiTrackerGSMatchedRecHit2DCollection::range theRecHitRange = theGSRecHits->get(theSimTrackIds[tkId]);
00136                SiTrackerGSMatchedRecHit2DCollection::const_iterator theRecHitRangeIteratorBegin = theRecHitRange.first;
00137                SiTrackerGSMatchedRecHit2DCollection::const_iterator theRecHitRangeIteratorEnd   = theRecHitRange.second;
00138                SiTrackerGSMatchedRecHit2DCollection::const_iterator iterRecHit;
00139 
00140                GlobalPoint position(simtrack.trackerSurfacePosition().x(),
00141                                     simtrack.trackerSurfacePosition().y(),
00142                                     simtrack.trackerSurfacePosition().z());
00143                GlobalVector momentum(simtrack.trackerSurfaceMomentum().x(),
00144                                      simtrack.trackerSurfaceMomentum().y(),
00145                                      simtrack.trackerSurfaceMomentum().z());
00146                int charge = (int)simtrack.charge();
00147                GlobalTrajectoryParameters glb_parameters(position, momentum, charge, &*theService->magneticField().product());
00148                simtrack_trackerstate = FreeTrajectoryState(glb_parameters);
00149 
00150                unsigned int outerId = 0;
00151                for( iterRecHit = theRecHitRangeIteratorBegin; iterRecHit != theRecHitRangeIteratorEnd; ++iterRecHit) {
00152                    theSeedHits = TrackerRecHit(&(*iterRecHit), theGeometry);
00153                    unsigned int id = theSeedHits.hit()->geographicalId().rawId();
00154                    if( preY < 0 ) {
00155                        if( id > outerId ) outerId = id;
00156                    }
00157                    else {
00158                        if( id > outerId ) outerId = id;
00159                    }
00160                }
00161                for( iterRecHit = theRecHitRangeIteratorBegin; iterRecHit != theRecHitRangeIteratorEnd; ++iterRecHit) {
00162                    theSeedHits = TrackerRecHit(&(*iterRecHit), theGeometry);
00163                    if( itm->recHit()->hit()->geographicalId().rawId() == theSeedHits.hit()->geographicalId().rawId() ) {
00164                        aTrackingRecHit = theSeedHits.hit()->clone();
00165                        TransientTrackingRecHit::ConstRecHitPointer recHit = theTTRHBuilder->build(aTrackingRecHit);
00166                        if( !recHit ) continue;
00167                        TrajectoryStateOnSurface updatedTSOS = updator()->update(seedState, *(recHit));
00168                        if( updatedTSOS.isValid() && passSelection(updatedTSOS) ) {
00169                            edm::OwnVector<TrackingRecHit> container;
00170                            container.push_back(recHit->hit()->clone());
00171                            TrajectorySeed ts = createSeed(updatedTSOS, container, recHit->geographicalId());
00172                            // check direction
00173                            const BasicTrajectorySeed* aSeed = &ts;
00174                            PTrajectoryStateOnDet PTSOD = aSeed->startingState();
00175                            TrajectoryStateTransform tsTransform;
00176                            const GeomDet *g = theGeometry->idToDet(PTSOD.detId());
00177                            TrajectoryStateOnSurface tsos = tsTransform.transientState(PTSOD, &(g->surface()),  &*theService->magneticField().product());
00178                            if( tsos.globalMomentum().basicVector()*seedState.globalMomentum().basicVector() < 0. ) continue;
00179                            result.push_back(ts);
00180                            isMatch = true;
00181                        }
00182                    }
00183                }
00184            }
00185        }
00186        if( !isMatch ) {
00187          // if there is no hits w.r.t. TM, find outermost hit
00188          for (std::vector<TrajectoryMeasurement>::const_iterator itm = alltm.begin(); itm != alltm.end(); itm++) {
00189            const TrajectoryStateOnSurface seedState = itm->predictedState();
00190            double preY = seedState.globalPosition().y();
00191 
00192            // Check SimTrack
00193            TrackingRecHit* aTrackingRecHit;
00194            FreeTrajectoryState simtrack_trackerstate;
00195            for( unsigned tkId=0;  tkId != theSimTrackIds.size(); ++tkId ) {
00196                const SimTrack & simtrack = (*simTracks)[theSimTrackIds[tkId]];
00197                SiTrackerGSMatchedRecHit2DCollection::range theRecHitRange = theGSRecHits->get(theSimTrackIds[tkId]);
00198                SiTrackerGSMatchedRecHit2DCollection::const_iterator theRecHitRangeIteratorBegin = theRecHitRange.first;
00199                SiTrackerGSMatchedRecHit2DCollection::const_iterator theRecHitRangeIteratorEnd   = theRecHitRange.second;
00200                SiTrackerGSMatchedRecHit2DCollection::const_iterator iterRecHit;
00201 
00202                GlobalPoint position(simtrack.trackerSurfacePosition().x(),
00203                                     simtrack.trackerSurfacePosition().y(),
00204                                     simtrack.trackerSurfacePosition().z());
00205                GlobalVector momentum(simtrack.trackerSurfaceMomentum().x(),
00206                                      simtrack.trackerSurfaceMomentum().y(),
00207                                      simtrack.trackerSurfaceMomentum().z());
00208                int charge = (int)simtrack.charge();
00209                GlobalTrajectoryParameters glb_parameters(position, momentum, charge, &*theService->magneticField().product());
00210                simtrack_trackerstate = FreeTrajectoryState(glb_parameters);
00211 
00212                unsigned int outerId = 0;
00213                for( iterRecHit = theRecHitRangeIteratorBegin; iterRecHit != theRecHitRangeIteratorEnd; ++iterRecHit) {
00214                    theSeedHits = TrackerRecHit(&(*iterRecHit), theGeometry);
00215                    unsigned int id = theSeedHits.hit()->geographicalId().rawId();
00216                    if( preY < 0 ) {
00217                        if( id > outerId ) outerId = id;
00218                    }
00219                    else {
00220                        if( id > outerId ) outerId = id;
00221                    }
00222                }
00223                for( iterRecHit = theRecHitRangeIteratorBegin; iterRecHit != theRecHitRangeIteratorEnd; ++iterRecHit) {
00224                    theSeedHits = TrackerRecHit(&(*iterRecHit), theGeometry);
00225                    if( outerId == theSeedHits.hit()->geographicalId().rawId() ) {
00226                        aTrackingRecHit = theSeedHits.hit()->clone();
00227                        TransientTrackingRecHit::ConstRecHitPointer recHit = theTTRHBuilder->build(aTrackingRecHit);
00228                        if( !recHit ) continue;
00229                        TrajectoryStateOnSurface updatedTSOS = updator()->update(seedState, *(recHit));
00230                        if( updatedTSOS.isValid() && passSelection(updatedTSOS) ) {
00231                            edm::OwnVector<TrackingRecHit> container;
00232                            container.push_back(recHit->hit()->clone());
00233                            TrajectorySeed ts = createSeed(updatedTSOS, container, recHit->geographicalId());
00234                            // check direction
00235                            const BasicTrajectorySeed* aSeed = &ts;
00236                            PTrajectoryStateOnDet PTSOD = aSeed->startingState();
00237                            TrajectoryStateTransform tsTransform;
00238                            const GeomDet *g = theGeometry->idToDet(PTSOD.detId());
00239                            TrajectoryStateOnSurface tsos = tsTransform.transientState(PTSOD, &(g->surface()),  &*theService->magneticField().product());
00240                            if( tsos.globalMomentum().basicVector()*seedState.globalMomentum().basicVector() < 0. ) continue;
00241                            result.push_back(ts);
00242                        }
00243                    }
00244                }
00245            }
00246          }
00247        }
00248 
00249        /*
00250        for( unsigned ir = 0; ir < tmpTS.size(); ir++ ) {
00251          const BasicTrajectorySeed* aSeed = &((tmpTS)[ir]);
00252          PTrajectoryStateOnDet PTSOD = aSeed->startingState();
00253          TrajectoryStateTransform tsTransform;
00254          DetId seedDetId(PTSOD.detId());
00255          const GeomDet * g = theGeometry->idToDet(seedDetId);
00256          TrajectoryStateOnSurface tsos = tsTransform.transientState(PTSOD, &(g->surface()),  &*theService->magneticField().product());
00257                  cout << "tsos3 = " << tsos.globalMomentum() << endl;
00258          if( _index == ir ) {
00259                  cout << "tsos4 = " << tsos.globalMomentum() << endl;
00260              result.push_back(tmpTS[ir]);
00261          }
00262        }
00263        */
00264        LogTrace(theCategory) << "result: "<<result.size();
00265        return;
00266      }
00267   }
00268   
00269   if ( !theUpdateStateFlag || usePredictedState ) { //use predicted states
00270      LogTrace(theCategory) << "use predicted state: ";
00271      for (std::vector<const DetLayer*>::const_iterator inl = nls.begin();
00272          inl != nls.end(); inl++ ) {
00273 
00274          if ( !result.empty() || *inl == 0 ) {
00275             break;
00276          }
00277          std::vector<DetLayer::DetWithState> compatDets = (*inl)->compatibleDets(staState, *propagator(), *estimator());
00278          LogTrace(theCategory) << " compatDets "<<compatDets.size();
00279          if ( compatDets.empty() ) continue;
00280          TrajectorySeed ts = createSeed(compatDets.front().second, compatDets.front().first->geographicalId());
00281          result.push_back(ts);
00282 
00283      }
00284      LogTrace(theCategory) << "result: "<<result.size();
00285      return;
00286   } 
00287   return;
00288 }
00289 
00290 void FastTSGFromPropagation::init(const MuonServiceProxy* service) {
00291 
00292   theMaxChi2 = theConfig.getParameter<double>("MaxChi2");
00293 
00294   theFixedErrorRescaling = theConfig.getParameter<double>("ErrorRescaling");
00295 
00296   theFlexErrorRescaling = 1.0;
00297 
00298   theResetMethod = theConfig.getParameter<std::string>("ResetMethod");
00299 
00300   if (theResetMethod != "discrete" && theResetMethod != "fixed" && theResetMethod != "matrix"  ) {
00301     edm::LogError("FastTSGFromPropagation") 
00302       <<"Wrong error rescaling method: "<<theResetMethod <<"\n"
00303       <<"Possible choices are: discrete, fixed, matrix.\n"
00304       <<"Use discrete method" <<std::endl;
00305     theResetMethod = "discrete"; 
00306   }
00307 
00308   theEstimator = new Chi2MeasurementEstimator(theMaxChi2);
00309 
00310   theCacheId_MT = 0;
00311 
00312   theCacheId_TG = 0;
00313 
00314   thePropagatorName = theConfig.getParameter<std::string>("Propagator");
00315 
00316   theService = service;
00317 
00318   theUseVertexStateFlag = theConfig.getParameter<bool>("UseVertexState");
00319 
00320   theUpdateStateFlag = theConfig.getParameter<bool>("UpdateState");
00321 
00322   theSelectStateFlag = theConfig.getParameter<bool>("SelectState");
00323 
00324   theSimTrackCollectionLabel = theConfig.getParameter<edm::InputTag>("SimTrackCollectionLabel");
00325   theHitProducer = theConfig.getParameter<edm::InputTag>("HitProducer");
00326 
00327   theUpdator = new KFUpdator();
00328 
00329   theTSTransformer = new TrajectoryStateTransform();
00330 
00331   theSigmaZ = theConfig.getParameter<double>("SigmaZ");
00332 
00333   edm::ParameterSet errorMatrixPset = theConfig.getParameter<edm::ParameterSet>("errorMatrixPset");
00334   if ( theResetMethod == "matrix" && !errorMatrixPset.empty()){
00335     theAdjustAtIp = errorMatrixPset.getParameter<bool>("atIP");
00336     theErrorMatrixAdjuster = new MuonErrorMatrix(errorMatrixPset);
00337   } else {
00338     theAdjustAtIp =false;
00339     theErrorMatrixAdjuster=0;
00340   }
00341 
00342   theService->eventSetup().get<TrackerRecoGeometryRecord>().get(theTracker); 
00343   theNavigation = new DirectTrackerNavigation(theTracker);
00344 
00345   edm::ESHandle<TrackerGeometry>        geometry;
00346   theService->eventSetup().get<TrackerDigiGeometryRecord>().get(geometry);
00347   theGeometry = &(*geometry);
00348 
00349   theService->eventSetup().get<TransientRecHitRecord>().get("WithTrackAngle", theTTRHBuilder);
00350 
00351 }
00352 
00353 void FastTSGFromPropagation::setEvent(const edm::Event& iEvent) {
00354 
00355   bool measTrackerChanged = false;
00356 
00357   iEvent.getByType(theBeamSpot);
00358   
00359   // retrieve the MC truth (SimTracks)
00360   iEvent.getByLabel(theSimTrackCollectionLabel, theSimTracks);
00361   iEvent.getByLabel(theHitProducer, theGSRecHits);
00362 
00363 
00364   unsigned long long newCacheId_MT = theService->eventSetup().get<CkfComponentsRecord>().cacheIdentifier();
00365 
00366   if ( theUpdateStateFlag && newCacheId_MT != theCacheId_MT ) {
00367     LogTrace(theCategory) << "Measurment Tracker Geometry changed!";
00368     theCacheId_MT = newCacheId_MT;
00369     theService->eventSetup().get<CkfComponentsRecord>().get(theMeasTracker);
00370     measTrackerChanged = true;
00371   }
00372 
00373   //if ( theUpdateStateFlag ) theMeasTracker->update(iEvent);
00374 
00375   if ( measTrackerChanged && (&*theMeasTracker) ) {
00376      if ( theTkLayerMeasurements ) delete theTkLayerMeasurements;
00377      theTkLayerMeasurements = new LayerMeasurements(&*theMeasTracker);
00378   }
00379 
00380   bool trackerGeomChanged = false;
00381 
00382   unsigned long long newCacheId_TG = theService->eventSetup().get<TrackerRecoGeometryRecord>().cacheIdentifier();
00383 
00384   if ( newCacheId_TG != theCacheId_TG ) {
00385     LogTrace(theCategory) << "Tracker Reco Geometry changed!";
00386     theCacheId_TG = newCacheId_TG;
00387     theService->eventSetup().get<TrackerRecoGeometryRecord>().get(theTracker);
00388     trackerGeomChanged = true;
00389   }
00390 
00391   if ( trackerGeomChanged && (&*theTracker) ) {
00392     if ( theNavigation ) delete theNavigation;
00393     theNavigation = new DirectTrackerNavigation(theTracker);
00394   }
00395 }
00396 
00397 TrajectoryStateOnSurface FastTSGFromPropagation::innerState(const TrackCand& staMuon) const {
00398 
00399   TrajectoryStateOnSurface innerTS;
00400 
00401   if ( staMuon.first && staMuon.first->isValid() ) {
00402     if (staMuon.first->direction() == alongMomentum) {
00403       innerTS = staMuon.first->firstMeasurement().updatedState();
00404     } 
00405     else if (staMuon.first->direction() == oppositeToMomentum) { 
00406       innerTS = staMuon.first->lastMeasurement().updatedState();
00407     }
00408   } else {
00409     innerTS = theTSTransformer->innerStateOnSurface(*(staMuon.second),*theService->trackingGeometry(), &*theService->magneticField());
00410   }
00411   //rescale the error
00412   adjust(innerTS);
00413 
00414   return  innerTS;
00415 
00416 //    return theTSTransformer->innerStateOnSurface(*(staMuon.second),*theService->trackingGeometry(), &*theService->magneticField());
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 = theTSTransformer->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 = theTSTransformer->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 }