CMS 3D CMS Logo

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