CMS 3D CMS Logo

TrackProducerWithSCAssociation.cc
Go to the documentation of this file.
1 
27 
29 public:
30  explicit TrackProducerWithSCAssociation(const edm::ParameterSet& iConfig);
31 
32  void produce(edm::Event&, const edm::EventSetup&) override;
33 
34  std::vector<reco::TransientTrack> getTransient(edm::Event&, const edm::EventSetup&);
35 
36 private:
48 
49  //Same recipe as Ursula's for electrons. Copy this from TrackProducerBase to get the OrphanHandle
50  //ugly temporary solution!! I agree !
51  void putInEvt(edm::Event& evt,
52  const Propagator* thePropagator,
53  const MeasurementTracker* theMeasTk,
54  std::unique_ptr<TrackingRecHitCollection> selHits,
55  std::unique_ptr<reco::TrackCollection> selTracks,
56  std::unique_ptr<reco::TrackExtraCollection> selTrackExtras,
57  std::unique_ptr<std::vector<Trajectory>> selTrajectories,
58  AlgoProductCollection& algoResults,
59  TransientTrackingRecHitBuilder const* hitBuilder,
60  const TrackerTopology* ttopo);
61 };
62 
65 
67  : TrackProducerBase<reco::Track>(iConfig.getParameter<bool>("TrajectoryInEvent")),
68  theAlgo(iConfig),
69  ttopoToken_(esConsumes()) {
71  iConfig, consumesCollector(), consumes<TrackCandidateCollection>(iConfig.getParameter<edm::InputTag>("src")));
72  setAlias(iConfig.getParameter<std::string>("@module_label"));
73 
74  myname_ = iConfig.getParameter<std::string>("ComponentName");
76  trackCSuperClusterAssociationCollection_ = iConfig.getParameter<std::string>("trackCandidateSCAssociationCollection");
77  trackSuperClusterAssociationCollection_ = iConfig.getParameter<std::string>("recoTrackSCAssociationCollection");
78  myTrajectoryInEvent_ = iConfig.getParameter<bool>("TrajectoryInEvent");
79 
80  assoc_token = consumes<reco::TrackCandidateCaloClusterPtrAssociation>(
82  measurementTrkToken_ = consumes<MeasurementTrackerEvent>(
83  edm::InputTag("MeasurementTrackerEvent")); //hardcoded because the original was and no time to fix (sigh)
84 
85  //register your products
86  produces<reco::TrackCollection>().setBranchAlias(alias_ + "Tracks");
87  produces<reco::TrackExtraCollection>().setBranchAlias(alias_ + "TrackExtras");
88  produces<TrackingRecHitCollection>().setBranchAlias(alias_ + "RecHits");
89  produces<std::vector<Trajectory>>();
90  produces<TrajTrackAssociationCollection>();
91  // produces< reco::TrackSuperClusterAssociationCollection > (trackSuperClusterAssociationCollection_ );
92  produces<reco::TrackCaloClusterPtrAssociation>(trackSuperClusterAssociationCollection_);
93 }
94 
96  //edm::LogInfo("TrackProducerWithSCAssociation") << "Analyzing event number: " << theEvent.id() << "\n";
97 
98  //LogDebug("TrackProducerWithSCAssociation") << "Analyzing event number: " << theEvent.id() << "\n";
99  // std::cout << " TrackProducerWithSCAssociation Analyzing event number: " << theEvent.id() << "\n";
100 
101  //
102  // create empty output collections
103  //
104  auto outputRHColl = std::make_unique<TrackingRecHitCollection>();
105  auto outputTColl = std::make_unique<reco::TrackCollection>();
106  auto outputTEColl = std::make_unique<reco::TrackExtraCollection>();
107  auto outputTrajectoryColl = std::make_unique<std::vector<Trajectory>>();
108  // Reco Track - Super Cluster Association
109  auto scTrkAssoc_p = std::make_unique<reco::TrackCaloClusterPtrAssociation>();
110 
111  //
112  //declare and get stuff to be retrieved from ES
113  //
117  edm::ESHandle<Propagator> thePropagator;
120  getFromES(setup, theG, theMF, theFitter, thePropagator, theMeasTk, theBuilder);
121 
122  const TrackerTopology* ttopo = &setup.getData(ttopoToken_);
123 
124  //
125  //declare and get TrackColection to be retrieved from the event
130  theEvent.getByToken(assoc_token, trkCandidateSCAssocHandle);
131  if (!trkCandidateSCAssocHandle.isValid()) {
132  // std::cout << "Error! Can't get the product "<<trackCSuperClusterAssociationCollection_.c_str() << " but keep running. Empty collection will be produced " << "\n";
133  edm::LogError("TrackProducerWithSCAssociation")
134  << "Error! Can't get the product " << trackCSuperClusterAssociationCollection_.c_str()
135  << " but keep running. Empty collection will be produced "
136  << "\n";
138  }
139  reco::TrackCandidateCaloClusterPtrAssociation scTrkCandAssCollection = *(trkCandidateSCAssocHandle.product());
140  if (scTrkCandAssCollection.empty())
142 
143  std::vector<int> tccLocations;
144  AlgoProductCollection algoResults;
146 
147  getFromEvt(theEvent, theTCCollection, bs);
148 
149  if (theTCCollection.failedToGet()) {
150  edm::LogError("TrackProducerWithSCAssociation")
151  << "TrackProducerWithSCAssociation could not get the TrackCandidateCollection.";
152  } else {
153  //
154  //run the algorithm
155  //
156  // LogDebug("TrackProducerWithSCAssociation") << "TrackProducerWithSCAssociation run the algorithm" << "\n";
157  // theAlgo.runWithCandidate(theG.product(), theMF.product(), *theTCCollection,
158  // theFitter.product(), thePropagator.product(), theBuilder.product(), algoResults);
159  // we have to copy this method from the algo in order to get the association track-seed
160  // this is ugly temporary code that should be replaced!!!!!
161  // start of copied code ======================================================
162 
163  // std::cout << "TrackProducerWithSCAssociation Number of TrackCandidates: " << theTCCollection->size() << "\n";
164  try {
165  int cont = 0;
166  int tcc = 0;
167 
168  for (TrackCandidateCollection::const_iterator i = theTCCollection->begin(); i != theTCCollection->end(); i++) {
169  const TrackCandidate* theTC = &(*i);
171  const TrajectorySeed& seed = theTC->seed();
172 
173  //convert PTrajectoryStateOnDet to TrajectoryStateOnSurface
174 
175  DetId detId(state.detId());
177  state, &(theG.product()->idToDet(detId)->surface()), theMF.product());
178 
179  //LogDebug("TrackProducerWithSCAssociation") << "TrackProducerWithSCAssociation Initial TSOS\n" << theTSOS << "\n";
180 
181  //convert the TrackingRecHit vector to a TransientTrackingRecHit vector
182  //meanwhile computes the number of degrees of freedom
184 
185  float ndof = 0;
186 
187  for (auto const& recHit : theTC->recHits()) {
188  hits.push_back(theBuilder.product()->build(&recHit));
189  }
190 
191  //build Track
192  // LogDebug("TrackProducerWithSCAssociation") << "TrackProducerWithSCAssociation going to buildTrack"<< "\n";
193  FitterCloner fc(theFitter.product(), theBuilder.product());
194  bool ok = theAlgo.buildTrack(
195  fc.fitter.get(), thePropagator.product(), algoResults, hits, theTSOS, seed, ndof, bs, theTC->seedRef());
196  // LogDebug("TrackProducerWithSCAssociation") << "TrackProducerWithSCAssociation buildTrack result: " << ok << "\n";
197  if (ok) {
198  cont++;
199  tccLocations.push_back(tcc);
200  }
201  tcc++;
202  }
203  edm::LogInfo("TrackProducerWithSCAssociation") << "Number of Tracks found: " << cont << "\n";
204  //LogDebug("TrackProducerWithSCAssociation") << "TrackProducerWithSCAssociation Number of Tracks found: " << cont << "\n";
205  // end of copied code ======================================================
206 
207  } catch (cms::Exception& e) {
208  edm::LogInfo("TrackProducerWithSCAssociation") << "cms::Exception caught!!!"
209  << "\n"
210  << e << "\n";
211  }
212  //
213  //put everything in the event
214  // we copy putInEvt to get OrphanHandle filled...
215  putInEvt(theEvent,
216  thePropagator.product(),
217  theMeasTk.product(),
218  std::move(outputRHColl),
219  std::move(outputTColl),
220  std::move(outputTEColl),
221  std::move(outputTrajectoryColl),
222  algoResults,
223  theBuilder.product(),
224  ttopo);
225 
226  // now construct associationmap and put it in the event
228  int itrack = 0;
229  std::vector<edm::Ptr<reco::CaloCluster>> caloPtrVec;
230  for (AlgoProductCollection::iterator i = algoResults.begin(); i != algoResults.end(); i++) {
231  edm::Ref<TrackCandidateCollection> trackCRef(theTCCollection, tccLocations[itrack]);
232  const edm::Ptr<reco::CaloCluster>& aClus = (*trkCandidateSCAssocHandle)[trackCRef];
233  caloPtrVec.push_back(aClus);
234  itrack++;
235  }
236 
238  filler.insert(rTracks_, caloPtrVec.begin(), caloPtrVec.end());
239  filler.fill();
240  }
241 
242  theEvent.put(std::move(scTrkAssoc_p), trackSuperClusterAssociationCollection_);
243  }
244 }
245 
246 std::vector<reco::TransientTrack> TrackProducerWithSCAssociation::getTransient(edm::Event& theEvent,
247  const edm::EventSetup& setup) {
248  edm::LogInfo("TrackProducerWithSCAssociation") << "Analyzing event number: " << theEvent.id() << "\n";
249  //
250  // create empty output collections
251  //
252  std::vector<reco::TransientTrack> ttks;
253 
254  //
255  //declare and get stuff to be retrieved from ES
256  //
260  edm::ESHandle<Propagator> thePropagator;
263  getFromES(setup, theG, theMF, theFitter, thePropagator, theMeasTk, theBuilder);
264 
265  //
266  //declare and get TrackColection to be retrieved from the event
267  //
268  AlgoProductCollection algoResults;
270 
271  try {
273  getFromEvt(theEvent, theTCCollection, bs);
274 
275  //
276  //run the algorithm
277  //
278  //LogDebug("TrackProducerWithSCAssociation") << "TrackProducerWithSCAssociation run the algorithm" << "\n";
280  theMF.product(),
281  *theTCCollection,
282  theFitter.product(),
283  thePropagator.product(),
284  theBuilder.product(),
285  bs,
286  algoResults);
287 
288  } catch (cms::Exception& e) {
289  edm::LogInfo("TrackProducerWithSCAssociation") << "cms::Exception caught!!!"
290  << "\n"
291  << e << "\n";
292  }
293 
294  for (auto& prod : algoResults) {
295  ttks.emplace_back(*prod.track, thePropagator.product()->magneticField());
296  }
297 
298  //LogDebug("TrackProducerWithSCAssociation") << "TrackProducerWithSCAssociation end" << "\n";
299 
300  return ttks;
301 }
302 
304 
306  const Propagator* thePropagator,
307  const MeasurementTracker* theMeasTk,
308  std::unique_ptr<TrackingRecHitCollection> selHits,
309  std::unique_ptr<reco::TrackCollection> selTracks,
310  std::unique_ptr<reco::TrackExtraCollection> selTrackExtras,
311  std::unique_ptr<std::vector<Trajectory>> selTrajectories,
312  AlgoProductCollection& algoResults,
313  TransientTrackingRecHitBuilder const* hitBuilder,
314  const TrackerTopology* ttopo) {
317 
320  edm::Ref<std::vector<Trajectory>>::key_type iTjRef = 0;
321  std::map<unsigned int, unsigned int> tjTkMap;
322 
323  for (auto& i : algoResults) {
324  Trajectory* theTraj = i.trajectory;
325  if (myTrajectoryInEvent_) {
326  selTrajectories->push_back(*theTraj);
327  iTjRef++;
328  }
329 
330  reco::Track* theTrack = i.track;
331  PropagationDirection seedDir = i.pDir;
332 
333  //LogDebug("TrackProducer") << "In KfTrackProducerBase::putInEvt - seedDir=" << seedDir;
334 
335  reco::Track t = *theTrack;
336  selTracks->push_back(t);
337  iTkRef++;
338 
339  // Store indices in local map (starts at 0)
340  if (trajectoryInEvent_)
341  tjTkMap[iTjRef - 1] = iTkRef - 1;
342 
343  //sets the outermost and innermost TSOSs
344 
345  TrajectoryStateOnSurface outertsos;
346  TrajectoryStateOnSurface innertsos;
347  unsigned int innerId, outerId;
348 
349  // --- NOTA BENE: the convention is to sort hits and measurements "along the momentum".
350  // This is consistent with innermost and outermost labels only for tracks from LHC collision
351  if (theTraj->direction() == alongMomentum) {
352  outertsos = theTraj->lastMeasurement().updatedState();
353  innertsos = theTraj->firstMeasurement().updatedState();
354  outerId = theTraj->lastMeasurement().recHit()->geographicalId().rawId();
355  innerId = theTraj->firstMeasurement().recHit()->geographicalId().rawId();
356  } else {
357  outertsos = theTraj->firstMeasurement().updatedState();
358  innertsos = theTraj->lastMeasurement().updatedState();
359  outerId = theTraj->firstMeasurement().recHit()->geographicalId().rawId();
360  innerId = theTraj->lastMeasurement().recHit()->geographicalId().rawId();
361  }
362  // ---
363  //build the TrackExtra
364  GlobalPoint v = outertsos.globalParameters().position();
365  GlobalVector p = outertsos.globalParameters().momentum();
366  math::XYZVector outmom(p.x(), p.y(), p.z());
367  math::XYZPoint outpos(v.x(), v.y(), v.z());
368  v = innertsos.globalParameters().position();
369  p = innertsos.globalParameters().momentum();
370  math::XYZVector inmom(p.x(), p.y(), p.z());
371  math::XYZPoint inpos(v.x(), v.y(), v.z());
372 
373  reco::TrackExtraRef teref = reco::TrackExtraRef(rTrackExtras, idx++);
374  reco::Track& track = selTracks->back();
375  track.setExtra(teref);
376 
377  //======= I want to set the second hitPattern here =============
378  if (theSchool.isValid()) {
381  setSecondHitPattern(theTraj, track, thePropagator, &*mte, ttopo);
382  }
383  //==============================================================
384 
385  selTrackExtras->push_back(reco::TrackExtra(outpos,
386  outmom,
387  true,
388  inpos,
389  inmom,
390  true,
391  outertsos.curvilinearError(),
392  outerId,
393  innertsos.curvilinearError(),
394  innerId,
395  seedDir,
396  theTraj->seedRef()));
397 
398  reco::TrackExtra& tx = selTrackExtras->back();
399  // --- NOTA BENE: the convention is to sort hits and measurements "along the momentum".
400  // This is consistent with innermost and outermost labels only for tracks from LHC collisions
401  reco::TrackExtra::TrajParams trajParams;
403  Traj2TrackHits t2t;
404  auto ih = selHits->size();
405  t2t(*theTraj, *selHits, trajParams, chi2s);
406  auto ie = selHits->size();
407  tx.setHits(rHits, ih, ie - ih);
408  tx.setTrajParams(std::move(trajParams), std::move(chi2s));
409  for (; ih < ie; ++ih) {
410  auto const& hit = (*selHits)[ih];
411  track.appendHitPattern(hit, *ttopo);
412  }
413  // ----
414 
415  delete theTrack;
416  delete theTraj;
417  }
418 
419  //LogTrace("TrackingRegressionTest") << "========== TrackProducer Info ===================";
420  //LogDebug("TrackProducerWithSCAssociation") << "number of finalTracks: " << selTracks->size() << std::endl;
421  //for (reco::TrackCollection::const_iterator it = selTracks->begin(); it != selTracks->end(); it++) {
422  //LogDebug("TrackProducerWithSCAssociation") << "track's n valid and invalid hit, chi2, pt : "
423  // << it->found() << " , "
424  // << it->lost() <<" , "
425  // << it->normalizedChi2() << " , "
426  // << it->pt() << std::endl;
427  // }
428  //LogTrace("TrackingRegressionTest") << "=================================================";
429 
430  rTracks_ = evt.put(std::move(selTracks));
431 
432  evt.put(std::move(selTrackExtras));
433  evt.put(std::move(selHits));
434 
435  if (myTrajectoryInEvent_) {
436  edm::OrphanHandle<std::vector<Trajectory>> rTrajs = evt.put(std::move(selTrajectories));
437 
438  // Now Create traj<->tracks association map
439  auto trajTrackMap = std::make_unique<TrajTrackAssociationCollection>(rTrajs, rTracks_);
440  for (std::map<unsigned int, unsigned int>::iterator i = tjTkMap.begin(); i != tjTkMap.end(); i++) {
441  edm::Ref<std::vector<Trajectory>> trajRef(rTrajs, (*i).first);
442  edm::Ref<reco::TrackCollection> tkRef(rTracks_, (*i).second);
443  trajTrackMap->insert(edm::Ref<std::vector<Trajectory>>(rTrajs, (*i).first),
445  }
446  evt.put(std::move(trajTrackMap));
447  }
448 }
ESGetTokenH3DDVariant esConsumes(std::string const &Record, edm::ConsumesCollector &)
Definition: DeDxTools.cc:283
T getParameter(std::string const &) const
Definition: ParameterSet.h:303
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
edm::EDGetTokenT< MeasurementTrackerEvent > measurementTrkToken_
virtual void getFromEvt(edm::Event &, edm::Handle< TrackCandidateCollection > &, reco::BeamSpot &)
Get TrackCandidateCollection from the Event (needed by TrackProducer)
std::vector< unsigned char > Chi2sFive
edm::OrphanHandle< reco::TrackCollection > rTracks_
std::vector< reco::TransientTrack > getTransient(edm::Event &, const edm::EventSetup &)
void setHits(TrackingRecHitRefProd const &prod, unsigned firstH, unsigned int nH)
T const * product() const
Definition: Handle.h:70
const GlobalTrajectoryParameters & globalParameters() const
void setSecondHitPattern(Trajectory *traj, reco::Track &track, const Propagator *prop, const MeasurementTrackerEvent *measTk, const TrackerTopology *ttopo)
void initTrackProducerBase(const edm::ParameterSet &conf, edm::ConsumesCollector cc, const edm::EDGetToken &src)
Call this method in inheriting class&#39; constructor.
std::vector< ConstRecHitPointer > RecHitContainer
edm::RefToBase< TrajectorySeed > seedRef(void) const
Definition: Trajectory.h:303
edm::EDGetTokenT< reco::TrackCandidateCaloClusterPtrAssociation > assoc_token
edm::Ref< TrackExtraCollection > TrackExtraRef
persistent reference to a TrackExtra
Definition: TrackExtraFwd.h:16
bool getByToken(EDGetToken token, Handle< PROD > &result) const
Definition: Event.h:540
PropagationDirection
Log< level::Error, false > LogError
void setAlias(std::string alias)
set the aliases of produced collections
std::unique_ptr< T, impl::DeviceDeleter > unique_ptr
TrajectoryMeasurement const & lastMeasurement() const
Definition: Trajectory.h:150
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.
bool failedToGet() const
Definition: HandleBase.h:72
std::vector< LocalTrajectoryParameters > TrajParams
T const * product() const
Definition: ESHandle.h:86
virtual RecHitPointer build(const TrackingRecHit *p) const =0
build a tracking rechit from an existing rechit
PropagationDirection const & direction() const
Definition: Trajectory.cc:133
PTrajectoryStateOnDet const & trajectoryStateOnDet() const
#define DEFINE_FWK_MODULE(type)
Definition: MakerMacros.h:16
edm::EventID id() const
Definition: EventBase.h:63
RefProd< PROD > getRefBeforePut()
Definition: Event.h:158
const edm::ESGetToken< TrackerTopology, TrackerTopologyRcd > ttopoToken_
bool isValid() const
Definition: ESHandle.h:44
TrackProducerAlgorithm< reco::Track > theAlgo
Log< level::Info, false > LogInfo
Definition: DetId.h:17
std::vector< TrackExtra > TrackExtraCollection
collection of TrackExtra objects
Definition: TrackExtraFwd.h:10
TrajectoryStateOnSurface transientState(const PTrajectoryStateOnDet &ts, const Surface *surface, const MagneticField *field)
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
bool isValid() const
Definition: HandleBase.h:70
TrajectoryStateOnSurface const & updatedState() const
TrackProducerWithSCAssociation(const edm::ParameterSet &iConfig)
virtual const MagneticField * magneticField() const =0
fixed size matrix
TrajectoryMeasurement const & firstMeasurement() const
Definition: Trajectory.h:166
edm::RefToBase< TrajectorySeed > seedRef() const
TrajectorySeed const & seed() const
edm::ESHandle< NavigationSchool > theSchool
void runWithCandidate(const TrackingGeometry *, const MagneticField *, const TrackCandidateCollection &, const TrajectoryFitter *, const Propagator *, const TransientTrackingRecHitBuilder *, const reco::BeamSpot &, AlgoProductCollection &)
Run the Final Fit taking TrackCandidates as input.
edm::Range< RecHitContainer::const_iterator > recHits() const
bool empty() const
Definition: ValueMap.h:158
void putInEvt(edm::Event &evt, const Propagator *thePropagator, const MeasurementTracker *theMeasTk, std::unique_ptr< TrackingRecHitCollection > selHits, std::unique_ptr< reco::TrackCollection > selTracks, std::unique_ptr< reco::TrackExtraCollection > selTrackExtras, std::unique_ptr< std::vector< Trajectory >> selTrajectories, AlgoProductCollection &algoResults, TransientTrackingRecHitBuilder const *hitBuilder, const TrackerTopology *ttopo)
def move(src, dest)
Definition: eostools.py:511
cont
load Luminosity info ##
Definition: generateEDF.py:628
void setTrajParams(TrajParams tmps, Chi2sFive chi2s)
void produce(edm::Event &, const edm::EventSetup &) override
Method where the procduction take place. To be implemented in concrete classes.
ConstRecHitPointer const & recHit() const
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.