CMS 3D CMS Logo

GsfTrackProducerBase.cc
Go to the documentation of this file.
2 // system include files
3 #include <memory>
4 // user include files
20 
22 
24 
26 
29 
31  const Propagator* prop,
32  const MeasurementTracker* measTk,
33  std::unique_ptr<TrackingRecHitCollection>& selHits,
34  std::unique_ptr<reco::GsfTrackCollection>& selTracks,
35  std::unique_ptr<reco::TrackExtraCollection>& selTrackExtras,
36  std::unique_ptr<reco::GsfTrackExtraCollection>& selGsfTrackExtras,
37  std::unique_ptr<std::vector<Trajectory> >& selTrajectories,
38  AlgoProductCollection& algoResults,
39  TransientTrackingRecHitBuilder const* hitBuilder,
40  const reco::BeamSpot& bs,
41  const TrackerTopology* ttopo) {
46 
50  edm::Ref<std::vector<Trajectory> >::key_type iTjRef = 0;
51  std::map<unsigned int, unsigned int> tjTkMap;
52 
53  TSCBLBuilderNoMaterial tscblBuilder;
54 
55  for (auto& i : algoResults) {
56  Trajectory* theTraj = i.trajectory;
57  if (trajectoryInEvent_) {
58  selTrajectories->push_back(*theTraj);
59  iTjRef++;
60  }
61 
62  reco::GsfTrack* theTrack = i.track;
63  PropagationDirection seedDir = i.pDir;
64 
65  LogDebug("TrackProducer") << "In GsfTrackProducerBase::putInEvt - seedDir=" << seedDir;
66 
67  reco::GsfTrack t = *theTrack;
68  selTracks->push_back(t);
69  iTkRef++;
70 
71  // Store indices in local map (starts at 0)
73  tjTkMap[iTjRef - 1] = iTkRef - 1;
74 
75  //sets the outermost and innermost TSOSs
76  TrajectoryStateOnSurface outertsos;
77  TrajectoryStateOnSurface innertsos;
78  unsigned int innerId, outerId;
79 
80  // --- NOTA BENE: the convention is to sort hits and measurements "along the momentum".
81  // This is consistent with innermost and outermost labels only for tracks from LHC collision
82  if (theTraj->direction() == alongMomentum) {
83  outertsos = theTraj->lastMeasurement().updatedState();
84  innertsos = theTraj->firstMeasurement().updatedState();
85  outerId = theTraj->lastMeasurement().recHit()->geographicalId().rawId();
86  innerId = theTraj->firstMeasurement().recHit()->geographicalId().rawId();
87  } else {
88  outertsos = theTraj->firstMeasurement().updatedState();
89  innertsos = theTraj->lastMeasurement().updatedState();
90  outerId = theTraj->firstMeasurement().recHit()->geographicalId().rawId();
91  innerId = theTraj->lastMeasurement().recHit()->geographicalId().rawId();
92  }
93  //build the TrackExtra
94  GlobalPoint v = outertsos.globalParameters().position();
95  GlobalVector p = outertsos.globalParameters().momentum();
96  math::XYZVector outmom(p.x(), p.y(), p.z());
97  math::XYZPoint outpos(v.x(), v.y(), v.z());
98  v = innertsos.globalParameters().position();
99  p = innertsos.globalParameters().momentum();
100  math::XYZVector inmom(p.x(), p.y(), p.z());
101  math::XYZPoint inpos(v.x(), v.y(), v.z());
102 
103  reco::TrackExtraRef teref = reco::TrackExtraRef(rTrackExtras, idx++);
104  reco::GsfTrack& track = selTracks->back();
105  track.setExtra(teref);
106 
107  //======= I want to set the second hitPattern here =============
108  if (theSchool.isValid()) {
110  evt.getByToken(mteSrc_, mte);
111  // NavigationSetter setter( *theSchool );
112  setSecondHitPattern(theTraj, track, prop, &*mte, ttopo);
113  }
114  //==============================================================
115 
116  selTrackExtras->push_back(reco::TrackExtra(outpos,
117  outmom,
118  true,
119  inpos,
120  inmom,
121  true,
122  outertsos.curvilinearError(),
123  outerId,
124  innertsos.curvilinearError(),
125  innerId,
126  seedDir,
127  theTraj->seedRef()));
128 
129  reco::TrackExtra& tx = selTrackExtras->back();
130 
131  // --- NOTA BENE: the convention is to sort hits and measurements "along the momentum".
132  // This is consistent with innermost and outermost labels only for tracks from LHC collisions
133  reco::TrackExtra::TrajParams trajParams;
135  Traj2TrackHits t2t;
136  auto ih = selHits->size();
137  t2t(*theTraj, *selHits, trajParams, chi2s);
138  auto ie = selHits->size();
139  tx.setHits(rHits, ih, ie - ih);
140  tx.setTrajParams(std::move(trajParams), std::move(chi2s));
141  for (; ih < ie; ++ih) {
142  auto const& hit = (*selHits)[ih];
143  track.appendHitPattern(hit, *ttopo);
144  }
145 
146  // ----
147 
148  std::vector<reco::GsfTangent> tangents;
149  const Trajectory::DataContainer& measurements = theTraj->measurements();
150  if (measurements.size() > 2) {
151  tangents.reserve(measurements.size() - 2);
152  Trajectory::DataContainer::const_iterator ibegin, iend;
153  int increment(0);
154  if (theTraj->direction() == alongMomentum) {
155  ibegin = measurements.begin() + 1;
156  iend = measurements.end() - 1;
157  increment = 1;
158  } else {
159  ibegin = measurements.end() - 2;
160  iend = measurements.begin();
161  increment = -1;
162  }
164  math::XYZVector momentum;
165  Measurement1D deltaP;
166  // only measurements on "mono" detectors
167  for (Trajectory::DataContainer::const_iterator i = ibegin; i != iend; i += increment) {
168  if (i->recHit().get()) {
169  DetId detId(i->recHit()->geographicalId());
170  if (detId.det() == DetId::Tracker) {
171  int subdetId = detId.subdetId();
172  if (subdetId == SiStripDetId::TIB || subdetId == SiStripDetId::TID || subdetId == SiStripDetId::TOB ||
173  subdetId == SiStripDetId::TEC) {
174  if (SiStripDetId(detId).stereo())
175  continue;
176  }
177  }
178  }
179  bool valid = computeModeAtTM(*i, position, momentum, deltaP);
180  if (valid) {
181  tangents.push_back(reco::GsfTangent(position, momentum, deltaP));
182  }
183  }
184  }
185 
186  //build the GsfTrackExtra
187  std::vector<reco::GsfComponent5D> outerStates;
188  fillStates(outertsos, outerStates);
189  std::vector<reco::GsfComponent5D> innerStates;
190  fillStates(innertsos, innerStates);
191 
192  reco::GsfTrackExtraRef terefGsf = reco::GsfTrackExtraRef(rGsfTrackExtras, idxGsf++);
193  track.setGsfExtra(terefGsf);
194  selGsfTrackExtras->push_back(reco::GsfTrackExtra(
195  outerStates, outertsos.localParameters().pzSign(), innerStates, innertsos.localParameters().pzSign(), tangents));
196 
197  if (innertsos.isValid()) {
199  TransverseImpactPointExtrapolator tipExtrapolator(gsfProp);
200  fillMode(track, innertsos, gsfProp, tipExtrapolator, tscblBuilder, bs);
201  }
202 
203  delete theTrack;
204  delete theTraj;
205  }
206 
207  LogTrace("TrackingRegressionTest") << "========== TrackProducer Info ===================";
208  LogTrace("TrackingRegressionTest") << "number of finalGsfTracks: " << selTracks->size();
209  for (reco::GsfTrackCollection::const_iterator it = selTracks->begin(); it != selTracks->end(); it++) {
210  LogTrace("TrackingRegressionTest") << "track's n valid and invalid hit, chi2, pt : " << it->found() << " , "
211  << it->lost() << " , " << it->normalizedChi2() << " , " << it->pt() << " , "
212  << it->eta();
213  }
214  LogTrace("TrackingRegressionTest") << "=================================================";
215 
216  rTracks_ = evt.put(std::move(selTracks));
217  evt.put(std::move(selTrackExtras));
218  evt.put(std::move(selGsfTrackExtras));
219  evt.put(std::move(selHits));
220 
221  if (trajectoryInEvent_) {
222  edm::OrphanHandle<std::vector<Trajectory> > rTrajs = evt.put(std::move(selTrajectories));
223 
224  // Now Create traj<->tracks association map
225  std::unique_ptr<TrajGsfTrackAssociationCollection> trajTrackMap(
227  for (std::map<unsigned int, unsigned int>::iterator i = tjTkMap.begin(); i != tjTkMap.end(); i++) {
228  edm::Ref<std::vector<Trajectory> > trajRef(rTrajs, (*i).first);
229  edm::Ref<reco::GsfTrackCollection> tkRef(rTracks_, (*i).second);
230  trajTrackMap->insert(edm::Ref<std::vector<Trajectory> >(rTrajs, (*i).first),
232  }
233  evt.put(std::move(trajTrackMap));
234  }
235 }
236 
237 void GsfTrackProducerBase::fillStates(TrajectoryStateOnSurface tsos, std::vector<reco::GsfComponent5D>& states) const {
240  GetComponents comps(tsos);
241  auto const& components = comps();
242  states.reserve(components.size());
243  for (auto const& st : components)
244  states.emplace_back(st.weight(), st.localParameters().vector(), st.localError().matrix());
245 }
246 
248  const TrajectoryStateOnSurface innertsos,
249  const Propagator& gsfProp,
250  const TransverseImpactPointExtrapolator& tipExtrapolator,
252  const reco::BeamSpot& bs) const {
253  // Get transverse impact parameter plane (from mean). This is a first approximation;
254  // the mode is then extrapolated to the
255  // final position closest to the beamline.
256  GlobalPoint bsPos(bs.position().x() + (track.vz() - bs.position().z()) * bs.dxdz(),
257  bs.position().y() + (track.vz() - bs.position().z()) * bs.dydz(),
258  track.vz());
259  TrajectoryStateOnSurface vtxTsos = tipExtrapolator.extrapolate(innertsos, bsPos);
260  if (!vtxTsos.isValid())
261  vtxTsos = innertsos;
262  // extrapolate mixture
263  vtxTsos = gsfProp.propagate(innertsos, vtxTsos.surface());
264  if (!vtxTsos.isValid())
265  return; // failed (GsfTrack keeps mode = mean)
266  // extract mode
267  // build perigee parameters (for covariance to be stored)
268  AlgebraicVector5 modeParameters;
269  AlgebraicSymMatrix55 modeCovariance;
270  // set parameters and variances for "mode" state (local parameters)
271  for (unsigned int iv = 0; iv < 5; ++iv) {
273  GaussianSumUtilities1D utils(state1D);
274  modeParameters(iv) = utils.mode().mean();
275  modeCovariance(iv, iv) = utils.mode().variance();
276  if (!utils.modeIsValid()) {
277  // if mode calculation fails: use mean
278  modeParameters(iv) = utils.mean();
279  modeCovariance(iv, iv) = utils.variance();
280  }
281  }
282  // complete covariance matrix
283  // approximation: use correlations from mean
284  const AlgebraicSymMatrix55& meanCovariance(vtxTsos.localError().matrix());
285  for (unsigned int iv1 = 0; iv1 < 5; ++iv1) {
286  for (unsigned int iv2 = 0; iv2 < iv1; ++iv2) {
287  double cov12 = meanCovariance(iv1, iv2) * sqrt(modeCovariance(iv1, iv1) / meanCovariance(iv1, iv1) *
288  modeCovariance(iv2, iv2) / meanCovariance(iv2, iv2));
289  modeCovariance(iv1, iv2) = modeCovariance(iv2, iv1) = cov12;
290  }
291  }
292  TrajectoryStateOnSurface modeTsos(LocalTrajectoryParameters(modeParameters, vtxTsos.localParameters().pzSign()),
293  LocalTrajectoryError(modeCovariance),
294  vtxTsos.surface(),
295  vtxTsos.magneticField(),
296  vtxTsos.surfaceSide());
297  TrajectoryStateClosestToBeamLine tscbl = tscblBuilder(*modeTsos.freeState(), bs);
298  if (!tscbl.isValid())
299  return; // failed (GsfTrack keeps mode = mean)
300  //
301  // extract state at PCA and create momentum vector and covariance matrix
302  //
303  const FreeTrajectoryState& fts = tscbl.trackStateAtPCA();
304  GlobalVector tscblMom = fts.momentum();
305  reco::GsfTrack::Vector mom(tscblMom.x(), tscblMom.y(), tscblMom.z());
307  const AlgebraicSymMatrix55& tscblCov = fts.curvilinearError().matrix();
308  for (unsigned int iv1 = 0; iv1 < reco::GsfTrack::dimensionMode; ++iv1) {
309  for (unsigned int iv2 = 0; iv2 < reco::GsfTrack::dimensionMode; ++iv2) {
310  cov(iv1, iv2) = tscblCov(iv1, iv2);
311  }
312  }
313  track.setMode(fts.charge(), mom, cov);
314 }
315 
318  AlgebraicSymMatrix55& covariance) const {
319  //
320  // parameters and errors from combined state
321  //
322  parameters = tsos.localParameters().vector();
323  covariance = tsos.localError().matrix();
324  //
325  // mode for parameter 0 (q/p)
326  //
328  GaussianSumUtilities1D qpGS(qpState);
329  if (!qpGS.modeIsValid())
330  return;
331  double qp = qpGS.mode().mean();
332  double varQp = qpGS.mode().variance();
333  //
334  // replace q/p value and variance, rescale correlation terms
335  // (heuristic procedure - alternative would be mode in 5D ...)
336  //
337  double VarQpRatio = sqrt(varQp / covariance(0, 0));
338  parameters(0) = qp;
339  covariance(0, 0) = varQp;
340  for (int i = 1; i < 5; ++i)
341  covariance(i, 0) *= VarQpRatio;
342 }
343 
346  reco::GsfTrackExtra::Vector& momentum,
347  Measurement1D& deltaP) const {
348  //
349  // states
350  //
351  TrajectoryStateOnSurface const& fwdState = tm.forwardPredictedState();
352  TrajectoryStateOnSurface const& bwdState = tm.backwardPredictedState();
353  TrajectoryStateOnSurface const& upState = tm.updatedState();
354 
355  if (!fwdState.isValid() || !bwdState.isValid() || !upState.isValid()) {
356  return false;
357  }
358  //
359  // position from mean, momentum from mode (in cartesian coordinates)
360  // following PF code
361  //
362  GlobalPoint pos = upState.globalPosition();
363  position = reco::GsfTrackExtra::Point(pos.x(), pos.y(), pos.z());
364  GlobalVector mom;
366  if (!result) {
367  // std::cout << "momentumFromModeCartesian failed" << std::endl;
368  return false;
369  }
370  momentum = reco::GsfTrackExtra::Vector(mom.x(), mom.y(), mom.z());
371  //
372  // calculation from deltaP from fit to forward & backward predictions
373  // (momentum from mode) and hit
374  //
375  // prepare input parameter vectors and covariance matrices
376  AlgebraicVector5 fwdPars = fwdState.localParameters().vector();
377  AlgebraicSymMatrix55 fwdCov = fwdState.localError().matrix();
378  localParametersFromQpMode(fwdState, fwdPars, fwdCov);
379  AlgebraicVector5 bwdPars = bwdState.localParameters().vector();
380  AlgebraicSymMatrix55 bwdCov = bwdState.localError().matrix();
381  localParametersFromQpMode(bwdState, bwdPars, bwdCov);
382  LocalPoint hitPos(0., 0., 0.);
383  LocalError hitErr(-1., -1., -1.);
384  if (tm.recHit()->isValid()) {
385  hitPos = tm.recHit()->localPosition();
386  hitErr = tm.recHit()->localPositionError();
387  }
388  CollinearFitAtTM2 collinearFit(fwdPars, fwdCov, bwdPars, bwdCov, hitPos, hitErr);
389  deltaP = collinearFit.deltaP();
390 
391  return true;
392 }
float pzSign() const
Sign of the z-component of the momentum in the local frame.
math::Error< dimension >::type CovarianceMatrix
std::remove_cv< typename std::remove_reference< argument_type >::type >::type key_type
Definition: Ref.h:164
OrphanHandle< PROD > put(std::unique_ptr< PROD > product)
Put a new product.
Definition: Event.h:133
math::Error< dimensionMode >::type CovarianceMatrixMode
3 parameter covariance matrix (momentum part) from mode
Definition: GsfTrack.h:21
const CurvilinearTrajectoryError & curvilinearError() const
int32_t *__restrict__ iv
const LocalTrajectoryError & localError() const
std::vector< unsigned char > Chi2sFive
void localParametersFromQpMode(const TrajectoryStateOnSurface tsos, AlgebraicVector5 &parameters, AlgebraicSymMatrix55 &covariance) const
local parameters rescaled with q/p from mode
T z() const
Definition: PV3DBase.h:61
static constexpr auto TID
Definition: SiStripDetId.h:38
void setHits(TrackingRecHitRefProd const &prod, unsigned firstH, unsigned int nH)
TrajectoryStateOnSurface extrapolate(const FreeTrajectoryState &fts, const GlobalPoint &vtx) const
extrapolation with default (=geometrical) propagator
TrajectoryStateOnSurface const & forwardPredictedState() const
Access to forward predicted state (from fitter or builder)
const GlobalTrajectoryParameters & globalParameters() const
void setSecondHitPattern(Trajectory *traj, reco::GsfTrack &track, const Propagator *prop, const MeasurementTrackerEvent *measTk, const TrackerTopology *ttopo)
std::vector< GsfTrackExtra > GsfTrackExtraCollection
collection of GsfTrackExtra objects
edm::RefToBase< TrajectorySeed > seedRef(void) const
Definition: Trajectory.h:303
edm::Ref< TrackExtraCollection > TrackExtraRef
persistent reference to a TrackExtra
Definition: TrackExtraFwd.h:16
const LocalTrajectoryParameters & localParameters() const
bool getByToken(EDGetToken token, Handle< PROD > &result) const
Definition: Event.h:539
PropagationDirection
const SurfaceType & surface() const
std::unique_ptr< T, impl::DeviceDeleter > unique_ptr
TrajectoryStateOnSurface propagate(STA const &state, SUR const &surface) const
Definition: Propagator.h:50
TrajectoryMeasurement const & lastMeasurement() const
Definition: Trajectory.h:150
#define LogTrace(id)
void fillMode(reco::GsfTrack &track, const TrajectoryStateOnSurface innertsos, const Propagator &gsfProp, const TransverseImpactPointExtrapolator &tipExtrapolator, TrajectoryStateClosestToBeamLineBuilder &tscblBuilder, const reco::BeamSpot &bs) const
DataContainer const & measurements() const
Definition: Trajectory.h:178
T x() const
Definition: PV3DBase.h:59
T y() const
Definition: PV3DBase.h:60
std::vector< LocalTrajectoryParameters > TrajParams
edm::AssociationMap< edm::OneToOne< std::vector< Trajectory >, reco::GsfTrackCollection, unsigned short > > TrajGsfTrackAssociationCollection
std::vector< TrajectoryMeasurement > DataContainer
Definition: Trajectory.h:40
GlobalPoint globalPosition() const
MultiGaussianState1D multiState1D(const std::vector< MultiGaussianState< N >::Vector > &, const std::vector< MultiGaussianState< N >::Matrix > &, const std::vector< double > &, unsigned int)
T sqrt(T t)
Definition: SSEVec.h:19
PropagationDirection const & direction() const
Definition: Trajectory.cc:133
TrackCharge charge() const
std::vector< GsfTrack > GsfTrackCollection
collection of GsfTracks
Definition: GsfTrackFwd.h:9
AlgebraicVector5 vector() const
GlobalVector momentum() const
TrajectoryStateOnSurface const & backwardPredictedState() const
Access to backward predicted state (from smoother)
ROOT::Math::SVector< double, 5 > AlgebraicVector5
bool modeIsValid() const
mode status
constexpr int subdetId() const
get the contents of the subdetector field (not cast into any detector&#39;s numbering enum) ...
Definition: DetId.h:48
virtual void putInEvt(edm::Event &, const Propagator *prop, const MeasurementTracker *measTk, std::unique_ptr< TrackingRecHitCollection > &, std::unique_ptr< reco::GsfTrackCollection > &, std::unique_ptr< reco::TrackExtraCollection > &, std::unique_ptr< reco::GsfTrackExtraCollection > &, std::unique_ptr< std::vector< Trajectory > > &, AlgoProductCollection &, TransientTrackingRecHitBuilder const *, const reco::BeamSpot &, const TrackerTopology *ttopo)
Put produced collections in the event.
static constexpr auto TOB
Definition: SiStripDetId.h:39
const SingleGaussianState1D & mode() const
double mean() const
parameter vector
RefProd< PROD > getRefBeforePut()
Definition: Event.h:158
bool isValid() const
Definition: ESHandle.h:44
edm::Ref< GsfTrackExtraCollection > GsfTrackExtraRef
persistent reference to a GsfTrackExtra
edm::EDGetTokenT< MeasurementTrackerEvent > mteSrc_
Detector identifier class for the strip tracker.
Definition: SiStripDetId.h:18
Definition: DetId.h:17
bool computeModeAtTM(const TrajectoryMeasurement &tm, reco::GsfTrackExtra::Point &position, reco::GsfTrackExtra::Vector &momentum, Measurement1D &deltaP) const
position, momentum and estimated deltaP at an intermediate measurement (true if successful) ...
std::vector< TrackExtra > TrackExtraCollection
collection of TrackExtra objects
Definition: TrackExtraFwd.h:10
const CurvilinearTrajectoryError & curvilinearError() const
XYZVectorD XYZVector
spatial vector with cartesian internal representation
Definition: Vector3D.h:31
std::vector< AlgoProduct > AlgoProductCollection
XYZPointD XYZPoint
point in space with cartesian internal representation
Definition: Point3D.h:12
math::XYZPoint Point
point in the space
Definition: GsfTrackExtra.h:25
const AlgebraicSymMatrix55 & matrix() const
ROOT::Math::SMatrix< double, 5, 5, ROOT::Math::MatRepSym< double, 5 > > AlgebraicSymMatrix55
Measurement1D deltaP() const
estimated deltaP (out-in) from fit parameters
void fillStates(TrajectoryStateOnSurface tsos, std::vector< reco::GsfComponent5D > &states) const
static constexpr auto TIB
Definition: SiStripDetId.h:37
TrajectoryStateOnSurface const & updatedState() const
Definition: utils.py:1
TrajectoryMeasurement const & firstMeasurement() const
Definition: Trajectory.h:166
static int position[264][3]
Definition: ReadPGInfo.cc:289
const AlgebraicSymMatrix55 & matrix() const
edm::ESHandle< NavigationSchool > theSchool
const MagneticField * magneticField() const
math::XYZVector Vector
spatial vector
Definition: GsfTrackExtra.h:27
double variance() const
variance
bool momentumFromModeCartesian(TrajectoryStateOnSurface const &tsos, GlobalVector &momentum)
edm::OrphanHandle< TrackCollection > rTracks_
math::XYZVector Vector
spatial vector
Definition: TrackBase.h:77
def move(src, dest)
Definition: eostools.py:511
void setTrajParams(TrajParams tmps, Chi2sFive chi2s)
static constexpr auto TEC
Definition: SiStripDetId.h:40
ConstRecHitPointer const & recHit() const
math::Vector< dimension >::type ParameterVector
#define LogDebug(id)