CMS 3D CMS Logo

/data/doxygen/doxygen-1.7.3/gen/CMSSW_4_2_8/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 
00043 
00044 using namespace std;
00045 
00046 
00047 FastTSGFromPropagation::FastTSGFromPropagation(const edm::ParameterSet & iConfig) :theTkLayerMeasurements (0), theTracker(0), theNavigation(0), theService(0), theEstimator(0), theTSTransformer(0), theSigmaZ(0), theConfig (iConfig)
00048 {
00049   theCategory = "FastSimulation|Muons||FastTSGFromPropagation";
00050 
00051 }
00052 
00053 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)
00054 {
00055   theCategory = "FastSimulation|Muons|FastTSGFromPropagation";
00056 }
00057 
00058 FastTSGFromPropagation::~FastTSGFromPropagation()
00059 {
00060 
00061   LogTrace(theCategory) << " FastTSGFromPropagation dtor called ";
00062   if ( theNavigation ) delete theNavigation;
00063   if ( theUpdator ) delete theUpdator;
00064   if ( theEstimator ) delete theEstimator;
00065   if ( theTkLayerMeasurements ) delete theTkLayerMeasurements;
00066   if ( theTSTransformer ) delete  theTSTransformer;
00067   if ( theErrorMatrixAdjuster ) delete theErrorMatrixAdjuster;
00068 
00069 }
00070 
00071 void FastTSGFromPropagation::trackerSeeds(const TrackCand& staMuon, const TrackingRegion& region, std::vector<TrajectorySeed> & result) {
00072 
00073   if ( theResetMethod == "discrete" ) getRescalingFactor(staMuon);
00074 
00075   TrajectoryStateOnSurface staState = outerTkState(staMuon);
00076 
00077   if ( !staState.isValid() ) { 
00078     LogTrace(theCategory) << "Error: initial state from L2 muon is invalid.";
00079     return;
00080   }
00081 
00082   LogTrace(theCategory) << "begin of trackerSeed:\n staState pos: "<<staState.globalPosition()
00083                         << " mom: "<<staState.globalMomentum() 
00084                         <<"pos eta: "<<staState.globalPosition().eta()
00085                         <<"mom eta: "<<staState.globalMomentum().eta();
00086 
00087 
00088   std::vector<const DetLayer*> nls = theNavigation->compatibleLayers(*(staState.freeState()), oppositeToMomentum);
00089 
00090   LogTrace(theCategory) << " compatible layers: "<<nls.size();
00091 
00092   if ( nls.empty() ) return;
00093 
00094   int ndesLayer = 0;
00095 
00096   bool usePredictedState = false;
00097 
00098   if ( theUpdateStateFlag ) { //use updated states
00099      std::vector<TrajectoryMeasurement> alltm; 
00100 
00101      for (std::vector<const DetLayer*>::const_iterator inl = nls.begin();
00102          inl != nls.end(); inl++, ndesLayer++ ) {
00103          if ( (*inl == 0) ) break;
00104 //         if ( (inl != nls.end()-1 ) && ( (*inl)->subDetector() == GeomDetEnumerators::TEC ) && ( (*(inl+1))->subDetector() == GeomDetEnumerators::TOB ) ) continue; 
00105          alltm = findMeasurements_new(*inl, staState);
00106          if ( (!alltm.empty()) ) {
00107             LogTrace(theCategory) << "final compatible layer: "<<ndesLayer;
00108             break;
00109          }
00110      }
00111 
00112      if ( alltm.empty() ) {
00113         LogTrace(theCategory) << " NO Measurements Found: eta: "<<staState.globalPosition().eta() <<"pt "<<staState.globalMomentum().perp();
00114         usePredictedState = true;
00115      } else {
00116        LogTrace(theCategory) << " Measurements for seeds: "<<alltm.size();
00117        std::stable_sort(alltm.begin(),alltm.end(),increasingEstimate()); 
00118        if ( alltm.size() > 5 ) alltm.erase(alltm.begin() + 5, alltm.end());
00119 
00120        const edm::SimTrackContainer* simTracks = &(*theSimTracks);
00121        const std::vector<unsigned> theSimTrackIds = theGSRecHits->ids();
00122        TrackerRecHit theSeedHits;
00123        std::vector<TrackerRecHit> outerHits;
00124 
00125        //std::vector<TrajectorySeed>  tmpTS;
00126        bool isMatch = false;
00127        for (std::vector<TrajectoryMeasurement>::const_iterator itm = alltm.begin(); itm != alltm.end(); itm++) {
00128            const TrajectoryStateOnSurface seedState = itm->predictedState();
00129            double preY = seedState.globalPosition().y();
00130 
00131            // Check SimTrack
00132            TrackingRecHit* aTrackingRecHit;
00133            FreeTrajectoryState simtrack_trackerstate;
00134            for( unsigned tkId=0;  tkId != theSimTrackIds.size(); ++tkId ) {
00135                const SimTrack & simtrack = (*simTracks)[theSimTrackIds[tkId]];
00136                SiTrackerGSMatchedRecHit2DCollection::range theRecHitRange = theGSRecHits->get(theSimTrackIds[tkId]);
00137                SiTrackerGSMatchedRecHit2DCollection::const_iterator theRecHitRangeIteratorBegin = theRecHitRange.first;
00138                SiTrackerGSMatchedRecHit2DCollection::const_iterator theRecHitRangeIteratorEnd   = theRecHitRange.second;
00139                SiTrackerGSMatchedRecHit2DCollection::const_iterator iterRecHit;
00140 
00141                GlobalPoint position(simtrack.trackerSurfacePosition().x(),
00142                                     simtrack.trackerSurfacePosition().y(),
00143                                     simtrack.trackerSurfacePosition().z());
00144                GlobalVector momentum(simtrack.trackerSurfaceMomentum().x(),
00145                                      simtrack.trackerSurfaceMomentum().y(),
00146                                      simtrack.trackerSurfaceMomentum().z());
00147                int charge = (int)simtrack.charge();
00148                GlobalTrajectoryParameters glb_parameters(position, momentum, charge, &*theService->magneticField().product());
00149                simtrack_trackerstate = FreeTrajectoryState(glb_parameters);
00150 
00151                unsigned int outerId = 0;
00152                for( iterRecHit = theRecHitRangeIteratorBegin; iterRecHit != theRecHitRangeIteratorEnd; ++iterRecHit) {
00153                    theSeedHits = TrackerRecHit(&(*iterRecHit), theGeometry);
00154                    unsigned int id = theSeedHits.hit()->geographicalId().rawId();
00155                    if( preY < 0 ) {
00156                        if( id > outerId ) outerId = id;
00157                    }
00158                    else {
00159                        if( id > outerId ) outerId = id;
00160                    }
00161                }
00162                for( iterRecHit = theRecHitRangeIteratorBegin; iterRecHit != theRecHitRangeIteratorEnd; ++iterRecHit) {
00163                    theSeedHits = TrackerRecHit(&(*iterRecHit), theGeometry);
00164                    if( itm->recHit()->hit()->geographicalId().rawId() == theSeedHits.hit()->geographicalId().rawId() ) {
00165                        aTrackingRecHit = theSeedHits.hit()->clone();
00166                        TransientTrackingRecHit::ConstRecHitPointer recHit = theTTRHBuilder->build(aTrackingRecHit);
00167                        if( !recHit ) continue;
00168                        TrajectoryStateOnSurface updatedTSOS = updator()->update(seedState, *(recHit));
00169                        if( updatedTSOS.isValid() && passSelection(updatedTSOS) ) {
00170                            edm::OwnVector<TrackingRecHit> container;
00171                            container.push_back(recHit->hit()->clone());
00172                            TrajectorySeed ts = createSeed(updatedTSOS, container, recHit->geographicalId());
00173                            // check direction
00174                            const BasicTrajectorySeed* aSeed = &ts;
00175                            PTrajectoryStateOnDet PTSOD = aSeed->startingState();
00176                            TrajectoryStateTransform tsTransform;
00177                            const GeomDet *g = theGeometry->idToDet(PTSOD.detId());
00178                            TrajectoryStateOnSurface tsos = tsTransform.transientState(PTSOD, &(g->surface()),  &*theService->magneticField().product());
00179                            if( tsos.globalMomentum().basicVector()*seedState.globalMomentum().basicVector() < 0. ) continue;
00180                            result.push_back(ts);
00181                            isMatch = true;
00182                        }
00183                    }
00184                }
00185            }
00186        }
00187        if( !isMatch ) {
00188          // if there is no hits w.r.t. TM, find outermost hit
00189          for (std::vector<TrajectoryMeasurement>::const_iterator itm = alltm.begin(); itm != alltm.end(); itm++) {
00190            const TrajectoryStateOnSurface seedState = itm->predictedState();
00191            double preY = seedState.globalPosition().y();
00192 
00193            // Check SimTrack
00194            TrackingRecHit* aTrackingRecHit;
00195            FreeTrajectoryState simtrack_trackerstate;
00196            for( unsigned tkId=0;  tkId != theSimTrackIds.size(); ++tkId ) {
00197                const SimTrack & simtrack = (*simTracks)[theSimTrackIds[tkId]];
00198                SiTrackerGSMatchedRecHit2DCollection::range theRecHitRange = theGSRecHits->get(theSimTrackIds[tkId]);
00199                SiTrackerGSMatchedRecHit2DCollection::const_iterator theRecHitRangeIteratorBegin = theRecHitRange.first;
00200                SiTrackerGSMatchedRecHit2DCollection::const_iterator theRecHitRangeIteratorEnd   = theRecHitRange.second;
00201                SiTrackerGSMatchedRecHit2DCollection::const_iterator iterRecHit;
00202 
00203                GlobalPoint position(simtrack.trackerSurfacePosition().x(),
00204                                     simtrack.trackerSurfacePosition().y(),
00205                                     simtrack.trackerSurfacePosition().z());
00206                GlobalVector momentum(simtrack.trackerSurfaceMomentum().x(),
00207                                      simtrack.trackerSurfaceMomentum().y(),
00208                                      simtrack.trackerSurfaceMomentum().z());
00209                int charge = (int)simtrack.charge();
00210                GlobalTrajectoryParameters glb_parameters(position, momentum, charge, &*theService->magneticField().product());
00211                simtrack_trackerstate = FreeTrajectoryState(glb_parameters);
00212 
00213                unsigned int outerId = 0;
00214                for( iterRecHit = theRecHitRangeIteratorBegin; iterRecHit != theRecHitRangeIteratorEnd; ++iterRecHit) {
00215                    theSeedHits = TrackerRecHit(&(*iterRecHit), theGeometry);
00216                    unsigned int id = theSeedHits.hit()->geographicalId().rawId();
00217                    if( preY < 0 ) {
00218                        if( id > outerId ) outerId = id;
00219                    }
00220                    else {
00221                        if( id > outerId ) outerId = id;
00222                    }
00223                }
00224                for( iterRecHit = theRecHitRangeIteratorBegin; iterRecHit != theRecHitRangeIteratorEnd; ++iterRecHit) {
00225                    theSeedHits = TrackerRecHit(&(*iterRecHit), theGeometry);
00226                    if( outerId == theSeedHits.hit()->geographicalId().rawId() ) {
00227                        aTrackingRecHit = theSeedHits.hit()->clone();
00228                        TransientTrackingRecHit::ConstRecHitPointer recHit = theTTRHBuilder->build(aTrackingRecHit);
00229                        if( !recHit ) continue;
00230                        TrajectoryStateOnSurface updatedTSOS = updator()->update(seedState, *(recHit));
00231                        if( updatedTSOS.isValid() && passSelection(updatedTSOS) ) {
00232                            edm::OwnVector<TrackingRecHit> container;
00233                            container.push_back(recHit->hit()->clone());
00234                            TrajectorySeed ts = createSeed(updatedTSOS, container, recHit->geographicalId());
00235                            // check direction
00236                            const BasicTrajectorySeed* aSeed = &ts;
00237                            PTrajectoryStateOnDet PTSOD = aSeed->startingState();
00238                            TrajectoryStateTransform tsTransform;
00239                            const GeomDet *g = theGeometry->idToDet(PTSOD.detId());
00240                            TrajectoryStateOnSurface tsos = tsTransform.transientState(PTSOD, &(g->surface()),  &*theService->magneticField().product());
00241                            if( tsos.globalMomentum().basicVector()*seedState.globalMomentum().basicVector() < 0. ) continue;
00242                            result.push_back(ts);
00243                        }
00244                    }
00245                }
00246            }
00247          }
00248        }
00249 
00250        /*
00251        for( unsigned ir = 0; ir < tmpTS.size(); ir++ ) {
00252          const BasicTrajectorySeed* aSeed = &((tmpTS)[ir]);
00253          PTrajectoryStateOnDet PTSOD = aSeed->startingState();
00254          TrajectoryStateTransform tsTransform;
00255          DetId seedDetId(PTSOD.detId());
00256          const GeomDet * g = theGeometry->idToDet(seedDetId);
00257          TrajectoryStateOnSurface tsos = tsTransform.transientState(PTSOD, &(g->surface()),  &*theService->magneticField().product());
00258                  cout << "tsos3 = " << tsos.globalMomentum() << endl;
00259          if( _index == ir ) {
00260                  cout << "tsos4 = " << tsos.globalMomentum() << endl;
00261              result.push_back(tmpTS[ir]);
00262          }
00263        }
00264        */
00265        LogTrace(theCategory) << "result: "<<result.size();
00266        return;
00267      }
00268   }
00269   
00270   if ( !theUpdateStateFlag || usePredictedState ) { //use predicted states
00271      LogTrace(theCategory) << "use predicted state: ";
00272      for (std::vector<const DetLayer*>::const_iterator inl = nls.begin();
00273          inl != nls.end(); inl++ ) {
00274 
00275          if ( !result.empty() || *inl == 0 ) {
00276             break;
00277          }
00278          std::vector<DetLayer::DetWithState> compatDets = (*inl)->compatibleDets(staState, *propagator(), *estimator());
00279          LogTrace(theCategory) << " compatDets "<<compatDets.size();
00280          if ( compatDets.empty() ) continue;
00281          TrajectorySeed ts = createSeed(compatDets.front().second, compatDets.front().first->geographicalId());
00282          result.push_back(ts);
00283 
00284      }
00285      LogTrace(theCategory) << "result: "<<result.size();
00286      return;
00287   } 
00288   return;
00289 }
00290 
00291 void FastTSGFromPropagation::init(const MuonServiceProxy* service) {
00292 
00293   theMaxChi2 = theConfig.getParameter<double>("MaxChi2");
00294 
00295   theFixedErrorRescaling = theConfig.getParameter<double>("ErrorRescaling");
00296 
00297   theFlexErrorRescaling = 1.0;
00298 
00299   theResetMethod = theConfig.getParameter<std::string>("ResetMethod");
00300 
00301   if (theResetMethod != "discrete" && theResetMethod != "fixed" && theResetMethod != "matrix"  ) {
00302     edm::LogError("FastTSGFromPropagation") 
00303       <<"Wrong error rescaling method: "<<theResetMethod <<"\n"
00304       <<"Possible choices are: discrete, fixed, matrix.\n"
00305       <<"Use discrete method" <<std::endl;
00306     theResetMethod = "discrete"; 
00307   }
00308 
00309   theEstimator = new Chi2MeasurementEstimator(theMaxChi2);
00310 
00311   theCacheId_MT = 0;
00312 
00313   theCacheId_TG = 0;
00314 
00315   thePropagatorName = theConfig.getParameter<std::string>("Propagator");
00316 
00317   theService = service;
00318 
00319   theUseVertexStateFlag = theConfig.getParameter<bool>("UseVertexState");
00320 
00321   theUpdateStateFlag = theConfig.getParameter<bool>("UpdateState");
00322 
00323   theSelectStateFlag = theConfig.getParameter<bool>("SelectState");
00324 
00325   theSimTrackCollectionLabel = theConfig.getParameter<edm::InputTag>("SimTrackCollectionLabel");
00326   theHitProducer = theConfig.getParameter<edm::InputTag>("HitProducer");
00327 
00328   theUpdator = new KFUpdator();
00329 
00330   theTSTransformer = new TrajectoryStateTransform();
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.getByType(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 = theTSTransformer->innerStateOnSurface(*(staMuon.second),*theService->trackingGeometry(), &*theService->magneticField());
00411   }
00412   //rescale the error
00413   adjust(innerTS);
00414 
00415   return  innerTS;
00416 
00417 //    return theTSTransformer->innerStateOnSurface(*(staMuon.second),*theService->trackingGeometry(), &*theService->magneticField());
00418 }
00419 
00420 TrajectoryStateOnSurface FastTSGFromPropagation::outerTkState(const TrackCand& staMuon) const {
00421 
00422   TrajectoryStateOnSurface result;
00423 
00424   if ( theUseVertexStateFlag && staMuon.second->pt() > 1.0 ) {
00425     FreeTrajectoryState iniState = theTSTransformer->initialFreeState(*(staMuon.second), &*theService->magneticField());
00426     //rescale the error at IP
00427     adjust(iniState); 
00428 
00429     StateOnTrackerBound fromInside(&*(theService->propagator("PropagatorWithMaterial")));
00430     result = fromInside(iniState);
00431   } else {
00432     StateOnTrackerBound fromOutside(&*propagator());
00433     result = fromOutside(innerState(staMuon));
00434   }
00435   return result;
00436 }
00437 
00438 TrajectorySeed FastTSGFromPropagation::createSeed(const TrajectoryStateOnSurface& tsos, const DetId& id) const {
00439 
00440   edm::OwnVector<TrackingRecHit> container;
00441   return createSeed(tsos, container, id);
00442 
00443 }
00444 
00445 TrajectorySeed FastTSGFromPropagation::createSeed(const TrajectoryStateOnSurface& tsos, const edm::OwnVector<TrackingRecHit>& container, const DetId& id) const {
00446 
00447   PTrajectoryStateOnDet* seedTSOS = theTSTransformer->persistentState(tsos,id.rawId());
00448   return TrajectorySeed(*seedTSOS,container,oppositeToMomentum);
00449 
00450 }
00451 
00452 
00453 void FastTSGFromPropagation::validMeasurements(std::vector<TrajectoryMeasurement>& tms) const {
00454 
00455   std::vector<TrajectoryMeasurement>::iterator tmsend = std::remove_if(tms.begin(), tms.end(), isInvalid());
00456   tms.erase(tmsend, tms.end());
00457   return;
00458 
00459 }
00460 
00461 std::vector<TrajectoryMeasurement> FastTSGFromPropagation::findMeasurements_new(const DetLayer* nl, const TrajectoryStateOnSurface& staState) const {
00462 
00463   std::vector<TrajectoryMeasurement> result;
00464 
00465   std::vector<DetLayer::DetWithState> compatDets = nl->compatibleDets(staState, *propagator(), *estimator());
00466   if ( compatDets.empty() )  return result;
00467 
00468   for (std::vector<DetLayer::DetWithState>::const_iterator idws = compatDets.begin(); idws != compatDets.end(); ++idws) {
00469      if ( idws->second.isValid() && (idws->first) )  {
00470          std::vector<TrajectoryMeasurement> tmptm = 
00471            theMeasTracker->idToDet(idws->first->geographicalId())->fastMeasurements(idws->second, idws->second, *propagator(), *estimator());
00472          //validMeasurements(tmptm);
00473 //         if ( tmptm.size() > 2 ) {
00474 //            std::stable_sort(tmptm.begin(),tmptm.end(),increasingEstimate());
00475 //            result.insert(result.end(),tmptm.begin(), tmptm.begin()+2);
00476 //         } else {
00477             result.insert(result.end(),tmptm.begin(), tmptm.end());
00478 //         }
00479      }
00480   }
00481   
00482   return result;
00483 
00484 }
00485 
00486 std::vector<TrajectoryMeasurement> FastTSGFromPropagation::findMeasurements(const DetLayer* nl, const TrajectoryStateOnSurface& staState) const {
00487 
00488   std::vector<TrajectoryMeasurement> result = tkLayerMeasurements()->measurements((*nl), staState, *propagator(), *estimator());
00489   validMeasurements(result);
00490   return result;
00491 }
00492 
00493 bool FastTSGFromPropagation::passSelection(const TrajectoryStateOnSurface& tsos) const {
00494   if ( !theSelectStateFlag ) return true;
00495   else {
00496      if ( theBeamSpot.isValid() ) {
00497        return ( ( fabs(zDis(tsos) - theBeamSpot->z0() ) < theSigmaZ) );
00498 
00499      } else {
00500        return ( ( fabs(zDis(tsos)) < theSigmaZ) ); 
00501 //      double theDxyCut = 100;
00502 //      return ( (zDis(tsos) < theSigmaZ) && (dxyDis(tsos) < theDxyCut) );
00503      }
00504   }
00505 
00506 }
00507 
00508 double FastTSGFromPropagation::dxyDis(const TrajectoryStateOnSurface& tsos) const {
00509   return fabs(( - tsos.globalPosition().x() * tsos.globalMomentum().y() + tsos.globalPosition().y() * tsos.globalMomentum().x() )/tsos.globalMomentum().perp());
00510 }
00511 
00512 double FastTSGFromPropagation::zDis(const TrajectoryStateOnSurface& tsos) const {
00513   return tsos.globalPosition().z() - tsos.globalPosition().perp() * tsos.globalMomentum().z()/tsos.globalMomentum().perp();
00514 }
00515 
00516 void FastTSGFromPropagation::getRescalingFactor(const TrackCand& staMuon) {
00517     float pt = (staMuon.second)->pt();
00518     if ( pt < 13.0 ) theFlexErrorRescaling = 3; 
00519     else if ( pt < 30.0 ) theFlexErrorRescaling = 5;
00520     else theFlexErrorRescaling = 10;
00521     return;
00522 }
00523 
00524 
00525 void FastTSGFromPropagation::adjust(FreeTrajectoryState & state) const {
00526 
00527   //rescale the error
00528   if ( theResetMethod == "discreate" ) {
00529      state.rescaleError(theFlexErrorRescaling);
00530      return;
00531   }
00532 
00533   //rescale the error
00534   if ( theResetMethod == "fixed" || !theErrorMatrixAdjuster) {
00535      state.rescaleError(theFixedErrorRescaling);
00536      return;
00537   }
00538 
00539   CurvilinearTrajectoryError oMat = state.curvilinearError();
00540   CurvilinearTrajectoryError sfMat = theErrorMatrixAdjuster->get(state.momentum());//FIXME with position
00541   MuonErrorMatrix::multiply(oMat, sfMat);
00542   
00543   state = FreeTrajectoryState(state.parameters(),
00544                               oMat);
00545 }
00546 
00547 void FastTSGFromPropagation::adjust(TrajectoryStateOnSurface & state) const {
00548 
00549   //rescale the error
00550   if ( theResetMethod == "discreate" ) {
00551      state.rescaleError(theFlexErrorRescaling);
00552      return;
00553   }
00554 
00555   if ( theResetMethod == "fixed" || !theErrorMatrixAdjuster) {
00556      state.rescaleError(theFixedErrorRescaling);
00557      return;
00558   }
00559 
00560   CurvilinearTrajectoryError oMat = state.curvilinearError();
00561   CurvilinearTrajectoryError sfMat = theErrorMatrixAdjuster->get(state.globalMomentum());//FIXME with position
00562   MuonErrorMatrix::multiply(oMat, sfMat);
00563   
00564   state = TrajectoryStateOnSurface(state.globalParameters(),
00565                                    oMat,
00566                                    state.surface(),
00567                                    state.surfaceSide(),
00568                                    state.weight());
00569 }
00570 
00571 void FastTSGFromPropagation::stateOnDet(const TrajectoryStateOnSurface& ts,
00572                                         unsigned int detid,
00573                                         PTrajectoryStateOnDet& pts) const
00574 {
00575     const AlgebraicSymMatrix55& m = ts.localError().matrix();
00576     int dim = 5; 
00577     float localErrors[15];
00578     int k = 0;
00579     for (int i=0; i<dim; ++i) {
00580         for (int j=0; j<=i; ++j) {
00581             localErrors[k++] = m(i,j);
00582         }
00583     }
00584     int surfaceSide = static_cast<int>(ts.surfaceSide());
00585     pts = PTrajectoryStateOnDet( ts.localParameters(),
00586                                 localErrors, detid,
00587                                 surfaceSide);
00588 }