CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
KalmanAlignmentTrackRefitter.cc
Go to the documentation of this file.
1 
3 
5 
7 
10 
13 
15 
17 
18 #include "CLHEP/GenericFunctions/CumulativeChiSquare.hh"
19 
20 #include <iostream>
21 
22 using namespace std;
23 using namespace reco;
24 using namespace Genfun;
25 
26 
28  theRefitterAlgo( config ),
29  theNavigator( navigator ),
30  theDebugFlag( config.getUntrackedParameter<bool>( "debug", true ) )
31 {
34  config.getParameter< edm::InputTag >( "bsSrc" ) );
35 }
36 
37 
39 
40 
43  const AlignmentSetupCollection& algoSetups,
45  const reco::BeamSpot* beamSpot )
46 {
47  // Retrieve what we need from the EventSetup
49  edm::ESHandle< MagneticField > aMagneticField;
50  edm::ESHandle< TrajectoryFitter > aTrajectoryFitter;
51  edm::ESHandle< Propagator > aPropagator;
54 
55  getFromES( setup, aGeometry, aMagneticField, aTrajectoryFitter, aPropagator, theMeasTk, aRecHitBuilder );
56 
58  TrackCollection fullTracks;
59 
60  ConstTrajTrackPairCollection refittedFullTracks;
61  ConstTrajTrackPairCollection::const_iterator itTrack;
62 
63  for( itTrack = tracks.begin(); itTrack != tracks.end(); ++itTrack )
64  {
65  TransientTrack fullTrack( *(*itTrack).second, aMagneticField.product() );
66 
67  AlignmentSetupCollection::const_iterator itSetup;
68  for ( itSetup = algoSetups.begin(); itSetup != algoSetups.end(); ++itSetup )
69  {
70  RecHitContainer trackingRecHits;
71  RecHitContainer externalTrackingRecHits;
72 
74  RecHitContainer zPlusRecHits;
75  RecHitContainer zMinusRecHits;
76 
77  // Extract collection with TrackingRecHits
78  Trajectory::ConstRecHitContainer hits = (*itTrack).first->recHits();
79  Trajectory::ConstRecHitContainer::iterator itHits;
80 
81  for ( itHits = hits.begin(); itHits != hits.end(); ++itHits )
82  {
83  if ( !(*itHits)->isValid() ) continue;
84 
85  try
86  {
87  //if ( !theNavigator->alignableFromDetId( (*itHits)->geographicalId() )->alignmentParameters() ) continue;
88  theNavigator->alignableFromDetId( (*itHits)->geographicalId() );
89  } catch(...) { continue; }
90 
91  if ( (*itSetup)->useForTracking( *itHits ) )
92  {
93  trackingRecHits.push_back( (*itHits)->hit()->clone() );
94 
95  ( (*itHits)->det()->position().z() > 0. ) ?
96  zPlusRecHits.push_back( (*itHits)->hit()->clone() ) :
97  zMinusRecHits.push_back( (*itHits)->hit()->clone() );
98 
101  }
102  else if ( (*itSetup)->useForExternalTracking( *itHits ) )
103  {
104  externalTrackingRecHits.push_back( (*itHits)->hit()->clone() );
105  }
106  }
107 
108  //edm::LogInfo( "KalmanAlignmentTrackRefitter" ) << "Hits for tracking/external: " << trackingRecHits.size() << "/" << externalTrackingRecHits.size();
109 
110  //if ( !zPlusRecHits.size() || !zMinusRecHits.size() ) continue;
112 
113  if ( trackingRecHits.empty() ) continue;
114 
115  if ( externalTrackingRecHits.empty() )
116  {
117  if ( ( (*itSetup)->getExternalTrackingSubDetIds().size() == 0 ) && // O.K., no external hits expected,
118  ( trackingRecHits.size() >= (*itSetup)->minTrackingHits() ) )
119  {
120  TrajTrackPairCollection refitted = refitSingleTracklet( aGeometry.product(), aMagneticField.product(),
121  (*itSetup)->fitter(), (*itSetup)->propagator(),
122  aRecHitBuilder.product(), fullTrack,
123  trackingRecHits, beamSpot,
124  (*itSetup)->sortingDirection(), false, true );
125 
126  // The refitting did not work ... Try next!
127  if ( refitted.empty() ) continue;
128  if ( rejectTrack( refitted.front().second ) ) continue;
129 
130  if ( theDebugFlag )
131  {
132  debugTrackData( (*itSetup)->id(), refitted.front().first, refitted.front().second, beamSpot );
133  debugTrackData( "OrigFullTrack", (*itTrack).first, (*itTrack).second, beamSpot );
134  }
135 
136 
137  TrackletPtr trackletPtr( new KalmanAlignmentTracklet( refitted.front(), *itSetup ) );
138  result.push_back( trackletPtr );
139  }
140  else { continue; } // Expected external hits but found none or not enough hits.
141  }
142  else if ( ( trackingRecHits.size() >= (*itSetup)->minTrackingHits() ) &&
143  ( externalTrackingRecHits.size() >= (*itSetup)->minExternalHits() ) )
144  {
145  // Create an instance of KalmanAlignmentTracklet with an external prediction.
146 
147  TrajTrackPairCollection external = refitSingleTracklet( aGeometry.product(), aMagneticField.product(),
148  (*itSetup)->externalFitter(), (*itSetup)->externalPropagator(),
149  aRecHitBuilder.product(), fullTrack,
150  externalTrackingRecHits, beamSpot,
151  (*itSetup)->externalSortingDirection(),
152  false, true );
153  //if ( external.empty() || rejectTrack( external.front().second ) ) { continue; }
154  if ( external.empty() ) { continue; }
155 
156  TransientTrack externalTrack( *external.front().second, aMagneticField.product() );
157 
158  TrajTrackPairCollection refitted = refitSingleTracklet( aGeometry.product(), aMagneticField.product(),
159  (*itSetup)->fitter(), (*itSetup)->propagator(),
160  aRecHitBuilder.product(), externalTrack,
161  trackingRecHits, beamSpot,
162  (*itSetup)->sortingDirection(),
163  false, true, (*itSetup)->id() );
164 
165  if ( refitted.empty() ) { continue; }
166  if ( rejectTrack( refitted.front().second ) ) continue;
167 
168  //const Surface& surface = refitted.front().first->firstMeasurement().updatedState().surface();
169  const Surface& surface = refitted.front().first->lastMeasurement().updatedState().surface();
170  TrajectoryStateOnSurface externalTsos = externalTrack.impactPointState();
171  AnalyticalPropagator externalPredictionPropagator( aMagneticField.product(), anyDirection );
172  TrajectoryStateOnSurface externalPrediction = externalPredictionPropagator.propagate( externalTsos, surface );
173  if ( !externalPrediction.isValid() ) continue;
174 
175  if ( theDebugFlag )
176  {
177  debugTrackData( string("External") + (*itSetup)->id(), external.front().first, external.front().second, beamSpot );
178  debugTrackData( (*itSetup)->id(), refitted.front().first, refitted.front().second, beamSpot );
179  debugTrackData( "OrigFullTrack", (*itTrack).first, (*itTrack).second, beamSpot );
180  }
181 
182  TrackletPtr trackletPtr( new KalmanAlignmentTracklet( refitted.front(), externalPrediction, *itSetup ) );
183  result.push_back( trackletPtr );
184 
185  delete external.front().first;
186  delete external.front().second;
187  }
188  }
189  }
190 
191  return result;
192 }
193 
194 
197  const MagneticField* magneticField,
198  const TrajectoryFitter* fitter,
199  const Propagator* propagator,
200  const TransientTrackingRecHitBuilder* recHitBuilder,
201  const TransientTrack& fullTrack,
202  RecHitContainer& recHits,
203  const reco::BeamSpot* beamSpot,
204  const SortingDirection& sortingDir,
205  bool useExternalEstimate,
206  bool reuseMomentumEstimate,
207  const string identifier )
208 {
209 
211 
212  if ( recHits.size() < 2 ) return result;
213 
214  sortRecHits( recHits, recHitBuilder, sortingDir );
215 
217  RecHitContainer::iterator itRecHit;
218  for ( itRecHit = recHits.begin(); itRecHit != recHits.end(); ++itRecHit )
219  hits.push_back( recHitBuilder->build( &(*itRecHit) ) );
220 
221  TransientTrackingRecHit::ConstRecHitPointer firstHit = hits.front();
222 
223  AnalyticalPropagator firstStatePropagator( magneticField, anyDirection );
224  TrajectoryStateOnSurface firstState = firstStatePropagator.propagate( fullTrack.impactPointState(), firstHit->det()->surface() );
225 
226  KalmanAlignmentDataCollector::fillHistogram( identifier + string("_IPPt"),
227  1e-2*fullTrack.impactPointState().globalParameters().momentum().perp() );
228 
229  if ( !firstState.isValid() ) return result;
230 
231 // LocalTrajectoryError startError;
232 
233 // const double startErrorValue = 100;
234 // const unsigned int nTrajParam = 5;
235 
236 // if ( useExternalEstimate ) {
237 // startError = firstState.localError();
238 // } else {
239 // if ( reuseMomentumEstimate )
240 // {
241 // AlgebraicSymMatrix firstStateError( asHepMatrix( firstState.localError().matrix() ) );
242 // AlgebraicSymMatrix startErrorMatrix( nTrajParam, 0 );
243 // startErrorMatrix[0][0] = 1e-10;
244 // //startErrorMatrix[0][0] = firstStateError[0][0];
245 // startErrorMatrix[1][1] = startErrorValue;//firstStateError[1][1];
246 // startErrorMatrix[2][2] = startErrorValue;//firstStateError[2][2];
247 // startErrorMatrix[3][3] = startErrorValue;
248 // startErrorMatrix[4][4] = startErrorValue;
249 // startError = LocalTrajectoryError( startErrorMatrix );
250 // } else {
251 // AlgebraicSymMatrix startErrorMatrix( startErrorValue*AlgebraicSymMatrix( nTrajParam, 1 ) );
252 // startError = LocalTrajectoryError( startErrorMatrix );
253 // }
254 
255 // }
256 
257 // // MOMENTUM ESTIMATE FOR COSMICS. P = 1.5 GeV
258 // LocalTrajectoryParameters firstStateParameters = firstState.localParameters();
259 // AlgebraicVector firstStateParamVec = asHepVector( firstStateParameters.mixedFormatVector() );
260 // firstStateParamVec[0] = 1./1.5;
261 // LocalTrajectoryParameters cosmicsStateParameters( firstStateParamVec, firstStateParameters.pzSign(), true );
262 // TrajectoryStateOnSurface tsos( cosmicsStateParameters, startError, firstState.surface(), magneticField );
263 
264  KalmanAlignmentDataCollector::fillHistogram( identifier + string("_FSPt"),
265  1e-2*firstState.globalParameters().momentum().perp() );
266 
267  firstState.rescaleError( 100 );
268  TrajectoryStateOnSurface tsos( firstState.localParameters(), firstState.localError(),
269  firstState.surface(), magneticField );
270 
271  // Generate a trajectory seed.
272  TrajectorySeed seed( PTrajectoryStateOnDet(), recHits, propagator->propagationDirection() );
273 
274  // Generate track candidate.
275 
276  PTrajectoryStateOnDet state = trajectoryStateTransform::persistentState( tsos, firstHit->det()->geographicalId().rawId() );
277  TrackCandidate candidate( recHits, seed, state );
278 
279  AlgoProductCollection algoResult;
280 
281  int charge = static_cast<int>( tsos.charge() );
282  double momentum = firstState.localParameters().momentum().mag();
284  TRecHit1DMomConstraint::build( charge, momentum, 1e-10, &tsos.surface() );
285 
286  //no insert in OwnVector...
288  tmpHits.push_back(testhit);
289  for (TransientTrackingRecHit::RecHitContainer::const_iterator i=hits.begin(); i!=hits.end(); i++){
290  tmpHits.push_back(*i);
291  }
292  hits.swap(tmpHits);
293 
294  theRefitterAlgo.buildTrack( fitter, propagator, algoResult, hits, tsos, seed, 0, *beamSpot, candidate.seedRef());
295 
296  for ( AlgoProductCollection::iterator it = algoResult.begin(); it != algoResult.end(); ++it )
297  result.push_back( make_pair( (*it).first, (*it).second.first ) );
298 
299  return result;
300 }
301 
302 
304  const TransientTrackingRecHitBuilder* builder,
305  const SortingDirection& sortingDir ) const
306 {
307  // Don't start sorting if there is only 1 or even 0 elements.
308  if ( hits.size() < 2 ) return;
309 
310  TransientTrackingRecHit::RecHitPointer firstHit = builder->build( &hits.front() );
311  double firstRadius = firstHit->det()->surface().toGlobal( firstHit->localPosition() ).mag();
312  double firstY = firstHit->det()->surface().toGlobal( firstHit->localPosition() ).y();
313 
314  TransientTrackingRecHit::RecHitPointer lastHit = builder->build( &hits.back() );
315  double lastRadius = lastHit->det()->surface().toGlobal( lastHit->localPosition() ).mag();
316  double lastY = lastHit->det()->surface().toGlobal( lastHit->localPosition() ).y();
317 
318  bool insideOut = firstRadius < lastRadius;
319  bool upsideDown = lastY < firstY;
320 
321  if ( ( insideOut && ( sortingDir == KalmanAlignmentSetup::sortInsideOut ) ) ||
322  ( !insideOut && ( sortingDir == KalmanAlignmentSetup::sortOutsideIn ) ) ||
323  ( upsideDown && ( sortingDir == KalmanAlignmentSetup::sortUpsideDown ) ) ||
324  ( !upsideDown && ( sortingDir == KalmanAlignmentSetup::sortDownsideUp ) ) ) return;
325 
326  // Fill temporary container with reversed hits.
328  RecHitContainer::iterator itHit = hits.end();
329  do { --itHit; tmp.push_back( ( *itHit ).clone() ); } while ( itHit != hits.begin() );
330 
331  // Swap the content of the temporary and the input container.
332  hits.swap( tmp );
333 
334  return;
335 }
336 
337 
339 {
340  double trackChi2 = track->chi2();
341  unsigned int ndof = static_cast<unsigned int>( track->ndof() );
342  if ( trackChi2 <= 0. || ndof <= 0 ) return false;
343 
344  //FIXME: should be configurable (via KalmanAlignmentSetup)
345  double minChi2Prob = 0;//1e-6;
346  double maxChi2Prob = 1.0;
347 
348  GENFUNCTION cumulativeChi2 = Genfun::CumulativeChiSquare( ndof );
349  double chi2Prob = 1. - cumulativeChi2( trackChi2 );
350  return ( chi2Prob < minChi2Prob ) || ( chi2Prob > maxChi2Prob );
351 }
352 
353 
354 void KalmanAlignmentTrackRefitter::debugTrackData( const string identifier,
355  const Trajectory* traj,
356  const Track* track,
357  const reco::BeamSpot* bs )
358 {
359  unsigned int ndof = static_cast<unsigned int>( track->ndof() );
360  double trackChi2 = track->chi2();
361  if ( ( trackChi2 > 0. ) && ( ndof > 0 ) )
362  {
363  GENFUNCTION cumulativeChi2 = Genfun::CumulativeChiSquare( ndof );
364  KalmanAlignmentDataCollector::fillHistogram( identifier + string("_CumChi2"), 1. - cumulativeChi2( trackChi2 ) );
365  } else if ( ndof == 0 ) {
366  KalmanAlignmentDataCollector::fillHistogram( identifier + string("_CumChi2"), -1. );
367  } else {
368  KalmanAlignmentDataCollector::fillHistogram( identifier + string("_CumChi2"), -2. );
369  }
370 
371  KalmanAlignmentDataCollector::fillHistogram( identifier + string("_NHits"), traj->foundHits() );
372  KalmanAlignmentDataCollector::fillHistogram( identifier + string("_Pt"), 1e-2*track->pt() );
373  KalmanAlignmentDataCollector::fillHistogram( identifier + string("_Eta"), track->eta() );
374  KalmanAlignmentDataCollector::fillHistogram( identifier + string("_Phi"), track->phi() );
375  KalmanAlignmentDataCollector::fillHistogram( identifier + string("_NormChi2"), track->normalizedChi2() );
376  KalmanAlignmentDataCollector::fillHistogram( identifier + string("_DZ"), track->dz() );
377 
378  KalmanAlignmentDataCollector::fillHistogram( identifier + string("_DXY_BS"), fabs( track->dxy( bs->position() ) ) );
379  KalmanAlignmentDataCollector::fillHistogram( identifier + string("_DXY"), fabs( track->dxy() ) );
380  //KalmanAlignmentDataCollector::fillHistogram( identifier + string("_D0"), fabs( track->d0() ) );
381 }
T getParameter(std::string const &) const
int foundHits() const
Definition: Trajectory.h:224
int i
Definition: DBlmapReader.cc:9
TrackletCollection refitTracks(const edm::EventSetup &eventSetup, const AlignmentSetupCollection &algoSetups, const ConstTrajTrackPairCollection &tracks, const reco::BeamSpot *beamSpot)
reference back()
Definition: OwnVector.h:320
T perp() const
Definition: PV3DBase.h:71
static void fillHistogram(std::string histo_name, float data)
virtual PropagationDirection propagationDirection() const
Definition: Propagator.h:143
TrajectoryStateOnSurface propagate(const FreeTrajectoryState &fts, const Plane &plane) const
propagation to plane
bool rejectTrack(const reco::Track *track) const
const LocalTrajectoryParameters & localParameters() const
double normalizedChi2() const
chi-squared divided by n.d.o.f. (or chi-squared * 1e6 if n.d.o.f. is zero)
Definition: TrackBase.h:111
std::vector< reco::Track > TrackCollection
T mag() const
The vector magnitude. Equivalent to sqrt(vec.mag2())
size_type size() const
Definition: OwnVector.h:247
PTrajectoryStateOnDet persistentState(const TrajectoryStateOnSurface &ts, unsigned int detid)
double phi() const
azimuthal angle of momentum vector
Definition: TrackBase.h:139
void swap(OwnVector< T, P > &other) noexcept
Definition: OwnVector.h:400
double charge(const std::vector< uint8_t > &Ampls)
std::vector< ConstRecHitPointer > RecHitContainer
std::vector< KalmanAlignmentSetup * > AlignmentSetupCollection
bool buildTrack(const TrajectoryFitter *, const Propagator *, AlgoProductCollection &, TransientTrackingRecHit::RecHitContainer &, TrajectoryStateOnSurface &, const TrajectorySeed &, float, const reco::BeamSpot &, SeedRef seedRef=SeedRef(), int qualityMask=0, signed char nLoops=0)
Construct Tracks to be put in the event.
TransientTrackingRecHit::ConstRecHitContainer ConstRecHitContainer
Definition: Trajectory.h:43
iterator begin()
Definition: OwnVector.h:227
KalmanAlignmentTracklet::TrajTrackPairCollection TrajTrackPairCollection
void push_back(D *&d)
Definition: OwnVector.h:273
T mag() const
Definition: PV3DBase.h:66
double eta() const
pseudorapidity of momentum vector
Definition: TrackBase.h:141
double chi2() const
chi-squared of the fit
Definition: TrackBase.h:107
double ndof() const
number of degrees of freedom of the fit
Definition: TrackBase.h:109
virtual RecHitPointer build(const TrackingRecHit *p) const =0
build a tracking rechit from an existing rechit
bool empty() const
Definition: OwnVector.h:252
double pt() const
track transverse momentum
Definition: TrackBase.h:131
tuple result
Definition: query.py:137
void setConf(edm::ParameterSet conf)
Set parameter set.
LocalVector momentum() const
Momentum vector in the local frame.
const LocalTrajectoryError & localError() const
std::vector< AlgoProduct > AlgoProductCollection
void setSrc(edm::InputTag src, edm::InputTag bsSrc)
set label of source collection
void sortRecHits(RecHitContainer &hits, const TransientTrackingRecHitBuilder *builder, const SortingDirection &sortingDir) const
TrajTrackPairCollection refitSingleTracklet(const TrackingGeometry *geometry, const MagneticField *magneticField, const TrajectoryFitter *fitter, const Propagator *propagator, const TransientTrackingRecHitBuilder *recHitBuilder, const reco::TransientTrack &originalTrack, RecHitContainer &recHits, const reco::BeamSpot *beamSpot, const SortingDirection &sortingDir, bool useExternalEstimate, bool reuseMomentumEstimate, const std::string identifier=std::string("RefitSingle_"))
double dz() const
dz parameter (= dsz/cos(lambda)). This is the track z0 w.r.t (0,0,0) only if the refPoint is close to...
Definition: TrackBase.h:127
void debugTrackData(const std::string identifier, const Trajectory *traj, const reco::Track *track, const reco::BeamSpot *bs)
iterator end()
Definition: OwnVector.h:232
const GlobalTrajectoryParameters & globalParameters() const
tuple tracks
Definition: testEve_cfg.py:39
AlignmentAlgorithmBase::ConstTrajTrackPairCollection ConstTrajTrackPairCollection
T const * product() const
Definition: ESHandle.h:62
char state
Definition: procUtils.cc:75
std::vector< TrackletPtr > TrackletCollection
std::vector< std::vector< double > > tmp
Definition: MVATrainer.cc:100
ESHandle< TrackerGeometry > geometry
const Surface & surface() const
const Point & position() const
position
Definition: BeamSpot.h:63
TrajectoryStateOnSurface impactPointState() const
double dxy() const
dxy parameter. (This is the transverse impact parameter w.r.t. to (0,0,0) ONLY if refPoint is close t...
Definition: TrackBase.h:121
AlignableDetOrUnitPtr alignableFromDetId(const DetId &detid)
Returns AlignableDetOrUnitPtr corresponding to given DetId.
reference front()
Definition: OwnVector.h:348
void setup(std::vector< TH2F > &depth, std::string name, std::string units="")
KalmanAlignmentTrackRefitter(const edm::ParameterSet &config, AlignableNavigator *navigator)
Constructor.
TrackProducerAlgorithm< reco::Track > theRefitterAlgo
virtual void getFromES(const edm::EventSetup &, edm::ESHandle< TrackerGeometry > &, edm::ESHandle< MagneticField > &, edm::ESHandle< TrajectoryFitter > &, edm::ESHandle< Propagator > &, edm::ESHandle< MeasurementTracker > &, edm::ESHandle< TransientTrackingRecHitBuilder > &)
Get needed services from the Event Setup.