CMS 3D CMS Logo

CosmicMuonTrajectoryBuilder.cc
Go to the documentation of this file.
12 
13 /* Collaborating Class Header */
37 
38 #include <algorithm>
39 
40 using namespace edm;
41 using namespace std;
42 
46  : theService(service) {
47  thePropagatorName = par.getParameter<string>("Propagator");
48 
49  bool enableDTMeasurement = par.getParameter<bool>("EnableDTMeasurement");
50  bool enableCSCMeasurement = par.getParameter<bool>("EnableCSCMeasurement");
51  bool enableRPCMeasurement = par.getParameter<bool>("EnableRPCMeasurement");
52 
53  // if(enableDTMeasurement)
54  InputTag DTRecSegmentLabel = par.getParameter<InputTag>("DTRecSegmentLabel");
55 
56  // if(enableCSCMeasurement)
57  InputTag CSCRecSegmentLabel = par.getParameter<InputTag>("CSCRecSegmentLabel");
58 
59  // if(enableRPCMeasurement)
60  InputTag RPCRecSegmentLabel = par.getParameter<InputTag>("RPCRecSegmentLabel");
61 
62  // if(enableGEMMeasurement)
63  // InputTag GEMRecSegmentLabel = par.getParameter<InputTag>("GEMRecSegmentLabel");
64 
68  edm::InputTag(),
69  edm::InputTag(),
70  iC,
71  enableDTMeasurement,
72  enableCSCMeasurement,
73  enableRPCMeasurement,
74  false,
75  false);
76 
77  ParameterSet muonUpdatorPSet = par.getParameter<ParameterSet>("MuonTrajectoryUpdatorParameters");
78 
79  theNavigation = nullptr; // new DirectMuonNavigation(theService->detLayerGeometry());
80  theUpdator = new MuonTrajectoryUpdator(muonUpdatorPSet, insideOut);
81 
83 
84  ParameterSet muonBackwardUpdatorPSet = par.getParameter<ParameterSet>("BackwardMuonTrajectoryUpdatorParameters");
85 
86  theBKUpdator = new MuonTrajectoryUpdator(muonBackwardUpdatorPSet, outsideIn);
87 
88  theTraversingMuonFlag = par.getParameter<bool>("BuildTraversingMuon");
89 
90  theStrict1LegFlag = par.getParameter<bool>("Strict1Leg");
91 
92  ParameterSet smootherPSet = par.getParameter<ParameterSet>("MuonSmootherParameters");
93 
94  theNavigationPSet = par.getParameter<ParameterSet>("MuonNavigationParameters");
95 
96  theSmoother = new CosmicMuonSmoother(smootherPSet, theService);
97 
98  theNTraversing = 0;
99  theNSuccess = 0;
100  theCacheId_DG = 0;
101  category_ = "Muon|RecoMuon|CosmicMuon|CosmicMuonTrajectoryBuilder";
102 }
103 
105  LogTrace(category_) << "CosmicMuonTrajectoryBuilder dtor called";
106  if (theUpdator)
107  delete theUpdator;
108  if (theBKUpdator)
109  delete theBKUpdator;
111  delete theLayerMeasurements;
112  if (theSmoother)
113  delete theSmoother;
114  if (theNavigation)
115  delete theNavigation;
117 
118  LogTrace(category_) << "CosmicMuonTrajectoryBuilder Traversing: " << theNSuccess << "/" << theNTraversing;
119 }
120 
123 
124  // DetLayer Geometry
125  unsigned long long newCacheId_DG = theService->eventSetup().get<MuonRecoGeometryRecord>().cacheIdentifier();
126  if (newCacheId_DG != theCacheId_DG) {
127  LogTrace(category_) << "Muon Reco Geometry changed!";
128  theCacheId_DG = newCacheId_DG;
129  if (theNavigation)
130  delete theNavigation;
132  }
133 }
134 
136  TrajectoryContainer emptyContainer;
137 
139 
140  PTrajectoryStateOnDet ptsd1(seed.startingState());
141  DetId did(ptsd1.detId());
142  const BoundPlane& bp = theService->trackingGeometry()->idToDet(did)->surface();
143  TrajectoryStateOnSurface lastTsos =
144  trajectoryStateTransform::transientState(ptsd1, &bp, &*theService->magneticField());
145  LogTrace(category_) << "Seed: mom " << lastTsos.globalMomentum() << "pos: " << lastTsos.globalPosition();
146  LogTrace(category_) << "Seed: mom eta " << lastTsos.globalMomentum().eta()
147  << "pos eta: " << lastTsos.globalPosition().eta();
148 
149  bool beamhaloFlag = ((did.subdetId() == MuonSubdetId::CSC) && fabs(lastTsos.globalMomentum().eta()) > 4.0);
150 
151  vector<const DetLayer*> navLayers;
152 
153  if (did.subdetId() == MuonSubdetId::DT) {
154  //DT
155  navLayers = navigation()->compatibleLayers(*(lastTsos.freeState()), alongMomentum);
156  } else if (beamhaloFlag || (theTraversingMuonFlag && theStrict1LegFlag)) {
157  //CSC
158  navLayers = navigation()->compatibleEndcapLayers(*(lastTsos.freeState()), alongMomentum);
159  } else {
160  navLayers = navigation()->compatibleLayers(*(lastTsos.freeState()), alongMomentum);
161  }
162 
163  LogTrace(category_) << "found " << navLayers.size() << " compatible DetLayers for the Seed";
164 
165  if (navLayers.empty())
166  return emptyContainer;
167 
168  vector<DetWithState> detsWithStates;
169  LogTrace(category_) << "Compatible layers: ";
170  for (vector<const DetLayer*>::const_iterator layer = navLayers.begin(); layer != navLayers.end(); layer++) {
171  LogTrace(category_) << debug.dumpMuonId((*layer)->basicComponents().front()->geographicalId())
172  << debug.dumpLayer(*layer);
173  }
174 
175  detsWithStates = navLayers.front()->compatibleDets(lastTsos, *propagator(), *(updator()->estimator()));
176  LogTrace(category_) << "Number of compatible dets: " << detsWithStates.size() << endl;
177 
178  if (!detsWithStates.empty()) {
179  // get the updated TSOS
180  if (detsWithStates.front().second.isValid()) {
181  LogTrace(category_) << "New starting TSOS is on det: " << endl;
182  LogTrace(category_) << debug.dumpMuonId(detsWithStates.front().first->geographicalId())
183  << debug.dumpLayer(navLayers.front());
184  lastTsos = detsWithStates.front().second;
185  LogTrace(category_) << "Seed after extrapolation: mom " << lastTsos.globalMomentum()
186  << "pos: " << lastTsos.globalPosition();
187  }
188  }
189  detsWithStates.clear();
190  if (!lastTsos.isValid())
191  return emptyContainer;
192 
193  TrajectoryStateOnSurface secondLast = lastTsos;
194 
195  lastTsos.rescaleError(10.0);
196 
197  Trajectory theTraj(seed, alongMomentum);
198 
199  navLayers.clear();
200 
201  if (fabs(lastTsos.globalMomentum().eta()) < 1.0) {
202  //DT
203  navLayers = navigation()->compatibleLayers(*(lastTsos.freeState()), alongMomentum);
204  } else if (beamhaloFlag || (theTraversingMuonFlag && theStrict1LegFlag)) {
205  //CSC
206  navLayers = navigation()->compatibleEndcapLayers(*(lastTsos.freeState()), alongMomentum);
207  } else {
208  navLayers = navigation()->compatibleLayers(*(lastTsos.freeState()), alongMomentum);
209  }
210 
211  int DTChamberUsedBack = 0;
212  int CSCChamberUsedBack = 0;
213  int RPCChamberUsedBack = 0;
214  int TotalChamberUsedBack = 0;
216  vector<TrajectoryMeasurement> measL;
217 
218  LogTrace(category_) << "Begin forward fit " << navLayers.size();
219 
220  for (vector<const DetLayer*>::const_iterator rnxtlayer = navLayers.begin(); rnxtlayer != navLayers.end();
221  ++rnxtlayer) {
222  LogTrace(category_) << "new layer ";
223  measL.clear();
224  LogTrace(category_) << debug.dumpMuonId((*rnxtlayer)->basicComponents().front()->geographicalId())
225  << debug.dumpLayer(*rnxtlayer);
226  LogTrace(category_) << "from lastTsos " << lastTsos.globalMomentum() << " at " << lastTsos.globalPosition();
227 
228  measL = findBestMeasurements(*rnxtlayer, lastTsos, propagator(), (updator()->estimator()));
229 
230  if (measL.empty() && (fabs(theService->magneticField()->inTesla(GlobalPoint(0, 0, 0)).z()) < 0.01) &&
231  (theService->propagator("StraightLinePropagator").isValid())) {
232  LogTrace(category_) << "try straight line propagator ";
233  measL = findBestMeasurements(
234  *rnxtlayer, lastTsos, &*theService->propagator("StraightLinePropagator"), (updator()->estimator()));
235  }
236  if (measL.empty())
237  continue;
238 
239  for (vector<TrajectoryMeasurement>::const_iterator theMeas = measL.begin(); theMeas != measL.end(); ++theMeas) {
240  pair<bool, TrajectoryStateOnSurface> result = updator()->update((&*theMeas), theTraj, propagator());
241 
242  if (result.first) {
243  LogTrace(category_) << "update ok ";
245  (*rnxtlayer), DTChamberUsedBack, CSCChamberUsedBack, RPCChamberUsedBack, TotalChamberUsedBack);
246  secondLast = lastTsos;
247  if ((!theTraj.empty()) && result.second.isValid()) {
248  lastTsos = result.second;
249  LogTrace(category_) << "get new lastTsos here " << lastTsos.globalMomentum() << " at "
250  << lastTsos.globalPosition();
251  } else if ((theMeas)->predictedState().isValid())
252  lastTsos = (theMeas)->predictedState();
253  }
254  }
255  }
256  measL.clear();
257  while (!theTraj.empty()) {
258  theTraj.pop();
259  }
260 
261  if (!theTraj.isValid() || TotalChamberUsedBack < 2 || (DTChamberUsedBack + CSCChamberUsedBack) == 0 ||
262  !lastTsos.isValid()) {
263  return emptyContainer;
264  }
265 
266  // if got good trajectory, then do backward refitting
267  DTChamberUsedBack = 0;
268  CSCChamberUsedBack = 0;
269  RPCChamberUsedBack = 0;
270  TotalChamberUsedBack = 0;
271 
273 
274  // set starting navigation direction for MuonTrajectoryUpdator
275 
276  GlobalPoint lastPos = lastTsos.globalPosition();
277  GlobalPoint secondLastPos = secondLast.globalPosition();
278  GlobalVector momDir = secondLastPos - lastPos;
279 
280  if (lastPos.basicVector().dot(momDir.basicVector()) > 0) {
281  // LogTrace("CosmicMuonTrajectoryBuilder")<<"Fit direction changed to insideOut";
283  } else
285 
286  if (fabs(lastTsos.globalMomentum().eta()) < 1.0) {
287  //DT
288  navLayers = navigation()->compatibleLayers(*(lastTsos.freeState()), oppositeToMomentum);
289  } else if (beamhaloFlag || (theTraversingMuonFlag && theStrict1LegFlag)) {
290  //CSC
291  std::reverse(navLayers.begin(), navLayers.end());
292  } else {
293  navLayers = navigation()->compatibleLayers(*(lastTsos.freeState()), oppositeToMomentum);
294  }
295 
296  LogTrace(category_) << "Begin backward refitting, with " << navLayers.size() << " layers" << endl;
297 
298  for (vector<const DetLayer*>::const_iterator rnxtlayer = navLayers.begin(); rnxtlayer != navLayers.end();
299  ++rnxtlayer) {
300  measL.clear();
301 
302  measL = findBestMeasurements(*rnxtlayer, lastTsos, propagator(), (backwardUpdator()->estimator()));
303 
304  if (measL.empty()) {
306  for (MuonRecHitContainer::const_iterator ihit = tmpHits.begin(); ihit != tmpHits.end(); ++ihit) {
307  allUnusedHits.push_back(*ihit);
308  }
309  continue;
310  }
311 
312  for (vector<TrajectoryMeasurement>::const_iterator theMeas = measL.begin(); theMeas != measL.end(); ++theMeas) {
313  // if the part change, we need to reconsider the fit direction
314  if (rnxtlayer != navLayers.begin()) {
315  vector<const DetLayer*>::const_iterator lastlayer = rnxtlayer;
316  lastlayer--;
317 
318  if ((*rnxtlayer)->location() != (*lastlayer)->location()) {
319  lastPos = lastTsos.globalPosition();
320  GlobalPoint thisPos = (theMeas)->predictedState().globalPosition();
321  GlobalVector momDir = thisPos - lastPos;
322  // LogTrace("CosmicMuonTrajectoryBuilder")<<"momDir "<<momDir;
323 
324  if (momDir.mag() > 0.01) { //if lastTsos is on the surface, no need
325  if (thisPos.basicVector().dot(momDir.basicVector()) > 0) {
327  } else
329  }
330  }
331  if (((*lastlayer)->location() == GeomDetEnumerators::endcap) &&
332  ((*rnxtlayer)->location() == GeomDetEnumerators::endcap) &&
333  (lastTsos.globalPosition().z() * (theMeas)->predictedState().globalPosition().z() < 0)) {
335  }
336  }
337 
338  // if (theBKUpdator->fitDirection() == insideOut)
339  // LogTrace("CosmicMuonTrajectoryBuilder")<<"Fit direction insideOut";
340  // else LogTrace("CosmicMuonTrajectoryBuilder")<<"Fit direction outsideIn";
341  pair<bool, TrajectoryStateOnSurface> bkresult = backwardUpdator()->update((&*theMeas), myTraj, propagator());
342 
343  if (bkresult.first) {
345  (*rnxtlayer), DTChamberUsedBack, CSCChamberUsedBack, RPCChamberUsedBack, TotalChamberUsedBack);
346 
347  if (theTraversingMuonFlag) {
348  MuonRecHitContainer tmpUnusedHits = unusedHits(*rnxtlayer, *theMeas);
349  allUnusedHits.insert(allUnusedHits.end(), tmpUnusedHits.begin(), tmpUnusedHits.end());
350  }
351  if ((!myTraj.empty()) && bkresult.second.isValid())
352  lastTsos = bkresult.second;
353  else if ((theMeas)->predictedState().isValid())
354  lastTsos = (theMeas)->predictedState();
355  }
356  }
357  }
358 
359  if ((!myTraj.isValid()) || (myTraj.empty()) || ((selfDuplicate(myTraj))) || TotalChamberUsedBack < 2 ||
360  (DTChamberUsedBack + CSCChamberUsedBack) < 1) {
361  return emptyContainer;
362  }
363 
364  if (theTraversingMuonFlag && (allUnusedHits.size() >= 2)) {
365  // LogTrace(category_)<<utilities()->print(allUnusedHits);
366  LogTrace(category_) << "Building trajectory in second hemisphere...";
367  buildSecondHalf(myTraj);
368  // check if traversing trajectory has hits in both hemispheres
369 
370  if (theStrict1LegFlag && !utilities()->isTraversing(myTraj)) {
371  return emptyContainer;
372  }
374  return emptyContainer;
375  }
376 
377  LogTrace(category_) << " traj ok ";
378 
379  // getDirectionByTime(myTraj);
380  if (beamhaloFlag)
381  estimateDirection(myTraj);
382  if (myTraj.empty())
383  return emptyContainer;
384 
385  // try to smooth it
386  vector<Trajectory> smoothed = theSmoother->trajectories(myTraj);
387 
388  if (!smoothed.empty() && smoothed.front().foundHits() > 3) {
389  LogTrace(category_) << " Smoothed successfully.";
390  myTraj = smoothed.front();
391  } else {
392  LogTrace(category_) << " Smooth failed.";
393  }
394 
395  LogTrace(category_) << "first " << myTraj.firstMeasurement().updatedState() << "\n last "
396  << myTraj.lastMeasurement().updatedState();
397  if (myTraj.direction() == alongMomentum)
398  LogTrace(category_) << "alongMomentum";
399  else if (myTraj.direction() == oppositeToMomentum)
400  LogTrace(category_) << "oppositeMomentum";
401  else
402  LogTrace(category_) << "anyDirection";
403 
404  if (!beamhaloFlag) {
405  if (myTraj.lastMeasurement().updatedState().globalMomentum().y() > 0) {
406  LogTrace(category_) << "flip trajectory ";
407  flipTrajectory(myTraj);
408  }
409 
410  if ((myTraj.direction() == alongMomentum && (myTraj.firstMeasurement().updatedState().globalPosition().y() <
411  myTraj.lastMeasurement().updatedState().globalPosition().y())) ||
413  myTraj.lastMeasurement().updatedState().globalPosition().y()))) {
414  LogTrace(category_) << "reverse propagation direction";
416  }
417  }
418  // getDirectionByTime(myTraj);
419  if (!myTraj.isValid())
420  return emptyContainer;
421 
422  // check direction agree with position!
424  GlobalVector dirFromPos = myTraj.measurements().back().recHit()->globalPosition() -
425  myTraj.measurements().front().recHit()->globalPosition();
426 
427  if (theStrict1LegFlag && !utilities()->isTraversing(myTraj)) {
428  return emptyContainer;
429  }
430 
431  LogTrace(category_) << "last hit " << myTraj.measurements().back().recHit()->globalPosition() << endl;
432  LogTrace(category_) << "first hit " << myTraj.measurements().front().recHit()->globalPosition() << endl;
433 
434  LogTrace(category_) << "last tsos " << myTraj.measurements().back().updatedState().globalPosition() << " mom "
435  << myTraj.measurements().back().updatedState().globalMomentum() << endl;
436  LogTrace(category_) << "first tsos " << myTraj.measurements().front().updatedState().globalPosition() << " mom "
437  << myTraj.measurements().front().updatedState().globalMomentum() << endl;
438 
439  PropagationDirection propDir =
440  (dirFromPos.basicVector().dot(myTraj.firstMeasurement().updatedState().globalMomentum().basicVector()) > 0)
441  ? alongMomentum
443  LogTrace(category_) << " dir " << dir << " propDir " << propDir << endl;
444 
445  LogTrace(category_) << "chi2 " << myTraj.chiSquared() << endl;
446 
447  if (dir != propDir) {
448  LogTrace(category_) << "reverse propagation direction ";
450  }
451  if (myTraj.empty())
452  return emptyContainer;
453 
454  navLayers.clear();
456  ret.reserve(1);
457  ret.emplace_back(std::make_unique<Trajectory>(myTraj));
458  return ret;
459 }
460 
461 //
462 //
463 //
465  const DetLayer* layer, const TrajectoryMeasurement& meas) const {
468  for (MuonRecHitContainer::const_iterator ihit = tmpHits.begin(); ihit != tmpHits.end(); ++ihit) {
469  if ((*ihit)->geographicalId() != meas.recHit()->geographicalId()) {
470  result.push_back(*ihit);
471  LogTrace(category_) << "Unused hit: " << (*ihit)->globalPosition() << endl;
472  }
473  }
474 
475  return result;
476 }
477 
478 //
479 // continue to build a trajectory starting from given trajectory state
480 //
482  const NavigationDirection& startingDir,
483  Trajectory& traj) {
484  if (!ts.isValid())
485  return;
486 
487  const FreeTrajectoryState* fts = ts.freeState();
488  if (!fts)
489  return;
490 
491  vector<const DetLayer*> navLayers;
492 
493  if (fabs(fts->momentum().basicVector().eta()) < 1.0) {
494  //DT
495  if (fts->position().basicVector().dot(fts->momentum().basicVector()) > 0) {
496  navLayers = navigation()->compatibleLayers((*fts), alongMomentum);
497  } else {
498  navLayers = navigation()->compatibleLayers((*fts), oppositeToMomentum);
499  }
500 
502  //CSC
503  if (fts->position().basicVector().dot(fts->momentum().basicVector()) > 0) {
504  navLayers = navigation()->compatibleEndcapLayers((*fts), alongMomentum);
505  } else {
506  navLayers = navigation()->compatibleEndcapLayers((*fts), oppositeToMomentum);
507  }
508  } else {
509  if (fts->position().basicVector().dot(fts->momentum().basicVector()) > 0) {
510  navLayers = navigation()->compatibleLayers((*fts), alongMomentum);
511  } else {
512  navLayers = navigation()->compatibleLayers((*fts), oppositeToMomentum);
513  }
514  }
515 
516  if (navLayers.empty())
517  return;
518 
519  theBKUpdator->setFitDirection(startingDir);
520 
521  int DTChamberUsedBack = 0;
522  int CSCChamberUsedBack = 0;
523  int RPCChamberUsedBack = 0;
524  int TotalChamberUsedBack = 0;
525 
528  ? propagatorAlong()->propagate((*fts), navLayers.front()->surface())
529  : propagatorOpposite()->propagate((*fts), navLayers.front()->surface());
530 
531  if (!lastTsos.isValid()) {
532  LogTrace(category_) << "propagation failed from fts to inner cylinder";
533  return;
534  }
535  LogTrace(category_) << "tsos " << lastTsos.globalPosition();
536  lastTsos.rescaleError(10.);
537  vector<TrajectoryMeasurement> measL;
538  for (vector<const DetLayer*>::const_iterator rnxtlayer = navLayers.begin(); rnxtlayer != navLayers.end();
539  ++rnxtlayer) {
540  measL.clear();
541  measL = findBestMeasurements(*rnxtlayer, lastTsos, propagator(), (backwardUpdator()->estimator()));
542 
543  if (measL.empty())
544  continue;
545 
546  for (vector<TrajectoryMeasurement>::const_iterator theMeas = measL.begin(); theMeas != measL.end(); ++theMeas) {
547  pair<bool, TrajectoryStateOnSurface> bkresult = backwardUpdator()->update((&*theMeas), traj, propagator());
548  if (bkresult.first) {
549  LogTrace(category_) << "update ok : " << (theMeas)->recHit()->globalPosition();
550 
552  (*rnxtlayer), DTChamberUsedBack, CSCChamberUsedBack, RPCChamberUsedBack, TotalChamberUsedBack);
553 
554  if ((!traj.empty()) && bkresult.second.isValid())
555  lastTsos = bkresult.second;
556  else if ((theMeas)->predictedState().isValid())
557  lastTsos = (theMeas)->predictedState();
558  }
559  }
560  }
561  navLayers.clear();
562  updator()->makeFirstTime();
564 
565  measL.clear();
566 
567  return;
568 }
569 
570 //
571 // build trajectory in second hemisphere with pattern
572 // recognition starting from an intermediate state
573 //
575  if ((traj.firstMeasurement().recHit()->globalPosition().perp() <
576  traj.lastMeasurement().recHit()->globalPosition().perp())) {
577  LogTrace(category_) << "inside-out: reverseTrajectory";
578  reverseTrajectory(traj);
579  }
580  if (traj.empty())
581  return;
583  if (!tsos.isValid())
584  tsos = traj.lastMeasurement().predictedState();
585  LogTrace(category_) << "last tsos on traj: pos: " << tsos.globalPosition() << " mom: " << tsos.globalMomentum();
586  if (!tsos.isValid()) {
587  LogTrace(category_) << "last tsos on traj invalid";
588  return;
589  }
590 
591  build(intermediateState(tsos), insideOut, traj);
592 
593  return;
594 }
595 
596 //
597 //
598 //
600  PerpendicularBoundPlaneBuilder planeBuilder;
601  GlobalPoint pos(0.0, 0.0, 0.0);
602  BoundPlane* SteppingPlane = planeBuilder(pos, tsos.globalDirection());
603 
604  TrajectoryStateOnSurface predTsos = propagator()->propagate(tsos, *SteppingPlane);
605  if (predTsos.isValid())
606  LogTrace(category_) << "intermediateState: a intermediate state: pos: " << predTsos.globalPosition()
607  << "mom: " << predTsos.globalMomentum();
608 
609  return predTsos;
610 }
611 
612 //
613 //
614 //
616  if (hits.size() < 2)
617  return;
618 
620  vector<bool> keep(hits.size(), true);
621  int i(0);
622  int j(0);
623 
624  for (MuonRecHitContainer::const_iterator ihit = hits.begin(); ihit != hits.end(); ++ihit) {
625  if (!keep[i]) {
626  i++;
627  continue;
628  };
629  j = i + 1;
630  for (MuonRecHitContainer::const_iterator ihit2 = ihit + 1; ihit2 != hits.end(); ++ihit2) {
631  if (!keep[j]) {
632  j++;
633  continue;
634  }
635  if ((*ihit)->geographicalId() == (*ihit2)->geographicalId()) {
636  if ((*ihit)->dimension() > (*ihit2)->dimension()) {
637  keep[j] = false;
638  } else if ((*ihit)->dimension() < (*ihit2)->dimension()) {
639  keep[i] = false;
640  } else {
641  if ((*ihit)->transientHits().size() > (*ihit2)->transientHits().size()) {
642  keep[j] = false;
643  } else if ((*ihit)->transientHits().size() < (*ihit2)->transientHits().size()) {
644  keep[i] = false;
645  } else if ((*ihit)->degreesOfFreedom() != 0 && (*ihit2)->degreesOfFreedom() != 0) {
646  if (((*ihit)->chi2() / (*ihit)->degreesOfFreedom()) > ((*ihit2)->chi2() / (*ihit)->degreesOfFreedom()))
647  keep[i] = false;
648  else
649  keep[j] = false;
650  }
651  }
652  } // if same geomid
653  j++;
654  }
655  i++;
656  }
657 
658  i = 0;
659  for (MuonRecHitContainer::const_iterator ihit = hits.begin(); ihit != hits.end(); ++ihit) {
660  if (keep[i])
661  tmp.push_back(*ihit);
662  i++;
663  }
664 
665  hits.clear();
666  hits.swap(tmp);
667 
668  return;
669 }
670 
671 //
672 //
673 //
676 
677  if (traj.empty())
678  return true;
679 
680  bool result = false;
681  for (ConstRecHitContainer::const_iterator ir = hits.begin(); ir != hits.end(); ir++) {
682  if (!(*ir)->isValid())
683  continue;
684  for (ConstRecHitContainer::const_iterator ir2 = ir + 1; ir2 != hits.end(); ir2++) {
685  if (!(*ir2)->isValid())
686  continue;
687  if ((*ir) == (*ir2))
688  result = true;
689  }
690  }
691 
692  return result;
693 }
694 
695 //
696 // reverse a trajectory without refitting
697 // this can only be used for cosmic muons that come from above
698 //
700  PropagationDirection newDir =
701  (traj.firstMeasurement().recHit()->globalPosition().y() < traj.lastMeasurement().recHit()->globalPosition().y())
703  : alongMomentum;
704  Trajectory newTraj(traj.seed(), newDir);
705 
706  /* does not work in gcc4.8?)
707  std::vector<TrajectoryMeasurement> & meas = traj.measurements();
708  for (auto itm = meas.rbegin(); itm != meas.rend(); ++itm ) {
709  newTraj.push(std::move(*itm));
710  }
711  traj = std::move(newTraj);
712  */
713 
714  std::vector<TrajectoryMeasurement> const& meas = traj.measurements();
715  for (auto itm = meas.rbegin(); itm != meas.rend(); ++itm) {
716  newTraj.push(*itm);
717  }
718  traj = newTraj;
719 }
720 
721 //
722 // reverse a trajectory momentum direction and then refit
723 //
726  if (!lastTSOS.isValid()) {
727  LogTrace(category_) << "Error: last TrajectoryState invalid.";
728  }
730  std::reverse(hits.begin(), hits.end());
731 
732  LogTrace(category_) << "last tsos before flipping " << lastTSOS;
733  utilities()->reverseDirection(lastTSOS, &*theService->magneticField());
734  LogTrace(category_) << "last tsos after flipping " << lastTSOS;
735 
736  vector<Trajectory> refittedback = theSmoother->fit(traj.seed(), hits, lastTSOS);
737  if (refittedback.empty()) {
738  LogTrace(category_) << "flipTrajectory fail. " << endl;
739  return;
740  }
741  LogTrace(category_) << "flipTrajectory: first " << refittedback.front().firstMeasurement().updatedState()
742  << "\nflipTrajectory: last " << refittedback.front().lastMeasurement().updatedState();
743 
744  traj = refittedback.front();
745 
746  return;
747 }
748 
749 //
750 //
751 //
753  if (traj.direction() == anyDirection)
754  return;
756  Trajectory newTraj(traj.seed(), newDir);
757  const std::vector<TrajectoryMeasurement>& meas = traj.measurements();
758 
759  for (std::vector<TrajectoryMeasurement>::const_iterator itm = meas.begin(); itm != meas.end(); ++itm) {
760  newTraj.push(*itm);
761  }
762 
763  while (!traj.empty()) {
764  traj.pop();
765  }
766 
767  traj = newTraj;
768 }
769 
770 //
771 // guess the direction by normalized chi2
772 //
775 
777 
779 
780  if (!firstTSOS.isValid() || !lastTSOS.isValid())
781  return;
782 
783  LogTrace(category_) << "Two ends of the traj " << firstTSOS.globalPosition() << ", " << lastTSOS.globalPosition();
784 
785  LogTrace(category_) << "Their mom: " << firstTSOS.globalMomentum() << ", " << lastTSOS.globalMomentum();
786 
787  LogTrace(category_) << "Their mom eta: " << firstTSOS.globalMomentum().eta() << ", "
788  << lastTSOS.globalMomentum().eta();
789 
790  // momentum eta can be used to estimate direction
791  // the beam-halo muon seems enter with a larger |eta|
792 
793  if (fabs(firstTSOS.globalMomentum().eta()) > fabs(lastTSOS.globalMomentum().eta())) {
794  vector<Trajectory> refitted = theSmoother->trajectories(traj.seed(), hits, firstTSOS);
795  if (!refitted.empty())
796  traj = refitted.front();
797 
798  } else {
799  std::reverse(hits.begin(), hits.end());
800  utilities()->reverseDirection(lastTSOS, &*theService->magneticField());
801  vector<Trajectory> refittedback = theSmoother->trajectories(traj.seed(), hits, lastTSOS);
802  if (!refittedback.empty())
803  traj = refittedback.front();
804  }
805 
806  return;
807 }
808 
809 //
810 // get direction from timing information of rechits and segments
811 //
814  LogTrace(category_) << "getDirectionByTime" << endl;
815  for (TransientTrackingRecHit::ConstRecHitContainer::const_iterator ir = hits.begin(); ir != hits.end(); ir++) {
816  if (!(*ir)->isValid()) {
817  LogTrace(category_) << "invalid RecHit" << endl;
818  continue;
819  }
820 
821  const GlobalPoint& pos = (*ir)->globalPosition();
822  LogTrace(category_) << "pos" << pos << "radius " << pos.perp() << " dim " << (*ir)->dimension() << " det "
823  << (*ir)->det()->geographicalId().det() << " sub det " << (*ir)->det()->subDetector() << endl;
824 
825  if ((*ir)->det()->geographicalId().det() == 2 && (*ir)->det()->subDetector() == 6) {
826  // const CSCRecHit2D* iCSC = dynamic_cast<const CSCRecHit2D*>(&**ir);
827  // if (iCSC) LogTrace(category_)<<"csc from cast tpeak "<<iCSC->tpeak();
828  CSCRecHit2DCollection::range thisrange = cschits_->get(CSCDetId((*ir)->geographicalId()));
829  for (CSCRecHit2DCollection::const_iterator rechit = thisrange.first; rechit != thisrange.second; ++rechit) {
830  if ((*rechit).isValid())
831  LogTrace(category_) << "csc from collection tpeak " << (*rechit).tpeak();
832  }
833  }
834  if ((*ir)->det()->geographicalId().det() == 2 && (*ir)->det()->subDetector() == 7) {
835  // const DTRecHit1D* iDT = dynamic_cast<const DTRecHit1D*>(&**ir);
836  // if (iDT) LogTrace(category_)<<"dt digitime "<<iDT->digiTime();
837  DTRecHitCollection::range thisrange = dthits_->get(DTLayerId((*ir)->geographicalId()));
838  for (DTRecHitCollection::const_iterator rechit = thisrange.first; rechit != thisrange.second; ++rechit) {
839  if ((*rechit).isValid())
840  LogTrace(category_) << "dt from collection digitime " << (*rechit).digiTime();
841  }
842  }
843  }
844 
845  return;
846 }
847 
848 //
849 //
850 //
851 std::vector<TrajectoryMeasurement> CosmicMuonTrajectoryBuilder::findBestMeasurements(
852  const DetLayer* layer,
853  const TrajectoryStateOnSurface& tsos,
854  const Propagator* propagator,
856  std::vector<TrajectoryMeasurement> result;
857  std::vector<TrajectoryMeasurement> measurements;
858 
859  if (layer->hasGroups()) {
860  std::vector<TrajectoryMeasurementGroup> measurementGroups =
862 
863  for (std::vector<TrajectoryMeasurementGroup>::const_iterator tmGroupItr = measurementGroups.begin();
864  tmGroupItr != measurementGroups.end();
865  ++tmGroupItr) {
866  measurements = tmGroupItr->measurements();
867  const TrajectoryMeasurement* bestMeasurement =
869 
870  if (bestMeasurement)
871  result.push_back(*bestMeasurement);
872  }
873  } else {
874  measurements = theLayerMeasurements->measurements(layer, tsos, *propagator, *estimator);
875  const TrajectoryMeasurement* bestMeasurement =
877 
878  if (bestMeasurement)
879  result.push_back(*bestMeasurement);
880  }
881  measurements.clear();
882 
883  return result;
884 }
885 
886 //
887 //
888 //
890  const DetLayer* layer, int& dtChambers, int& cscChambers, int& rpcChambers, int& totalChambers) {
891  if (layer->subDetector() == GeomDetEnumerators::DT)
892  dtChambers++;
893  else if (layer->subDetector() == GeomDetEnumerators::CSC)
894  cscChambers++;
895  else if (layer->subDetector() == GeomDetEnumerators::RPCBarrel ||
896  layer->subDetector() == GeomDetEnumerators::RPCEndcap)
897  rpcChambers++;
898  totalChambers++;
899 }
900 
901 //
902 //
903 //
905  if ((dtseg == nullptr) || (!dtseg->hasPhi()))
906  return 0;
907  // timing information
908  double result = 0;
909  if (dtseg->phiSegment() == nullptr)
910  return 0;
911  int phiHits = dtseg->phiSegment()->specificRecHits().size();
912  LogTrace(category_) << "phiHits " << phiHits;
913  if (phiHits > 5) {
914  if (dtseg->phiSegment()->ist0Valid())
915  result = dtseg->phiSegment()->t0();
916  if (dtseg->phiSegment()->ist0Valid()) {
917  LogTrace(category_) << " Phi t0: " << dtseg->phiSegment()->t0() << " hits: " << phiHits;
918  } else {
919  LogTrace(category_) << " Phi t0 is invalid: " << dtseg->phiSegment()->t0() << " hits: " << phiHits;
920  }
921  }
922 
923  return result;
924 }
925 
926 //
927 //
928 //
930  const DTRecSegment4D* dtseg2) const {
931  LogTrace(category_) << "comparing dtseg: " << dtseg1 << " " << dtseg2 << endl;
932  if (dtseg1 == dtseg2 || t0(dtseg1) == t0(dtseg2))
933  return anyDirection;
934 
936 
937  return result;
938 }
void reverseDirection(TrajectoryStateOnSurface &, const MagneticField *) const
bool ist0Valid() const
T getParameter(std::string const &) const
Definition: ParameterSet.h:303
std::pair< const_iterator, const_iterator > range
iterator range
Definition: RangeMap.h:50
TrajectoryStateOnSurface const & predictedState() const
bool isValid() const
Definition: Trajectory.h:257
std::vector< const DetLayer * > compatibleEndcapLayers(const FreeTrajectoryState &fts, PropagationDirection timeDirection) const
std::vector< const DetLayer * > compatibleLayers(const FreeTrajectoryState &fts, PropagationDirection timeDirection) const
const bool isValid(const Frame &aFrame, const FrameQuality &aQuality, const uint16_t aExpectedPos)
bool hasPhi() const
Does it have the Phi projection?
double t0() const
Get the segment t0 (if recomputed, 0 is returned otherwise)
T z() const
Definition: PV3DBase.h:61
void makeFirstTime()
reset the theFirstTSOSFlag
edm::Handle< CSCRecHit2DCollection > cschits_
ret
prodAgent to be discontinued
MuonTransientTrackingRecHit::MuonRecHitContainer unusedHits(const DetLayer *, const TrajectoryMeasurement &) const
void reverseTrajectory(Trajectory &) const
reverse a trajectory without refit (out the measurements order changed)
T eta() const
Definition: PV3DBase.h:73
const Propagator * propagatorAlong() const
const Propagator * propagator() const
Global3DPoint GlobalPoint
Definition: GlobalPoint.h:10
float chiSquared() const
Definition: Trajectory.h:241
void reverseTrajectoryPropagationDirection(Trajectory &) const
reverse the propagation direction of a trajectory
bool selfDuplicate(const Trajectory &) const
check if the trajectory iterates the same hit more than once
MuonCandidate::TrajectoryContainer TrajectoryContainer
edm::Handle< DTRecHitCollection > dthits_
void setEvent(const edm::Event &) override
pass the Event to the algo at each event
void getDirectionByTime(Trajectory &) const
check the direction of trajectory by checking the timing
PropagationDirection
MuonDetLayerMeasurements * theLayerMeasurements
TrajectoryStateOnSurface propagate(STA const &state, SUR const &surface) const
Definition: Propagator.h:50
MuonTrajectoryUpdator * backwardUpdator() const
double t0(const DTRecSegment4D *deseg) const
std::vector< TrajectoryMeasurementGroup > groupedMeasurements(const DetLayer *layer, const TrajectoryStateOnSurface &startingState, const Propagator &prop, const MeasurementEstimator &est, const edm::Event &iEvent)
TrajectoryMeasurement const & lastMeasurement() const
Definition: Trajectory.h:150
void estimateDirection(Trajectory &) const
check the direction of trajectory by checking eta spread
TrajectoryContainer trajectories(const TrajectorySeed &) override
build trajectories from seed
#define LogTrace(id)
constexpr std::array< uint8_t, layerIndexSize > layer
DataContainer const & measurements() const
Definition: Trajectory.h:178
GlobalPoint position() const
C::const_iterator const_iterator
constant access iterator type
Definition: RangeMap.h:43
T y() const
Definition: PV3DBase.h:60
PropagationDirection checkDirectionByT0(const DTRecSegment4D *, const DTRecSegment4D *) const
GlobalPoint globalPosition() const
MuonRecHitContainer recHits(const DetLayer *layer, const edm::Event &iEvent)
returns the rechits which are on the layer
MuonBestMeasurementFinder * theBestMeasurementFinder
const CosmicMuonUtilities * utilities() const
void setFitDirection(NavigationDirection fitDirection)
set fit direction
PropagationDirection const & direction() const
Definition: Trajectory.cc:133
ConstRecHitContainer recHits() const
Definition: Trajectory.h:186
T mag() const
Definition: PV3DBase.h:64
GlobalVector momentum() const
void incrementChamberCounters(const DetLayer *layer, int &dtChambers, int &cscChambers, int &rpcChambers, int &totalChambers)
std::vector< Trajectory > fit(const Trajectory &) const
~CosmicMuonTrajectoryBuilder() override
Destructor.
MeasurementContainer measurements(const DetLayer *layer, const GeomDet *det, const TrajectoryStateOnSurface &stateOnDet, const MeasurementEstimator &est, const edm::Event &iEvent)
const BasicVectorType & basicVector() const
Definition: PV3DBase.h:53
void selectHits(MuonTransientTrackingRecHit::MuonRecHitContainer &) const
std::vector< ConstRecHitPointer > ConstRecHitContainer
Definition: DetId.h:17
#define debug
Definition: HDRShower.cc:19
TrajectoryStateOnSurface intermediateState(const TrajectoryStateOnSurface &) const
TrajectoryStateOnSurface transientState(const PTrajectoryStateOnDet &ts, const Surface *surface, const MagneticField *field)
const DTChamberRecSegment2D * phiSegment() const
The superPhi segment: 0 if no phi projection available.
TrajectorySeed const & seed() const
Access to the seed used to reconstruct the Trajectory.
Definition: Trajectory.h:263
std::vector< DTRecHit1D > specificRecHits() const
Access to specific components.
void pop()
Definition: Trajectory.cc:30
GlobalVector globalDirection() const
DirectMuonNavigation * navigation() const
bool empty() const
True if trajectory has no measurements.
Definition: Trajectory.h:233
MuonTrajectoryUpdator * updator() const
GlobalVector globalMomentum() const
TrajectoryStateOnSurface const & updatedState() const
void setEvent(const edm::Event &)
set event
HLT enums.
const MeasurementEstimator * estimator() const
accasso at the propagator
TrajectoryMeasurement const & firstMeasurement() const
Definition: Trajectory.h:166
void flipTrajectory(Trajectory &) const
flip a trajectory with refit (the momentum direction is opposite)
TrajectoryContainer trajectories(const Trajectory &traj) const override
CosmicMuonTrajectoryBuilder(const edm::ParameterSet &, const MuonServiceProxy *service, edm::ConsumesCollector &iC)
Constructor.
TrajectoryMeasurement * findBestMeasurement(std::vector< TrajectoryMeasurement > &measC, const Propagator *propagator)
return the Tm with the best chi2: no cut applied.
FreeTrajectoryState const * freeState(bool withErrors=true) const
MuonTransientTrackingRecHit::MuonRecHitContainer MuonRecHitContainer
std::vector< TrajectoryMeasurement > findBestMeasurements(const DetLayer *, const TrajectoryStateOnSurface &, const Propagator *, const MeasurementEstimator *)
virtual std::pair< bool, TrajectoryStateOnSurface > update(const TrajectoryMeasurement *measurement, Trajectory &trajectory, const Propagator *propagator)
update the Trajectory with the TrajectoryMeasurement
static constexpr int DT
Definition: MuonSubdetId.h:11
void build(const TrajectoryStateOnSurface &, const NavigationDirection &, Trajectory &)
tmp
align.sh
Definition: createJobs.py:716
T dot(const Basic3DVector &rh) const
Scalar product, or "dot" product, with a vector of same type.
static constexpr int CSC
Definition: MuonSubdetId.h:12
std::vector< MuonRecHitPointer > MuonRecHitContainer
Definition: event.py:1
ConstRecHitPointer const & recHit() const
const Propagator * propagatorOpposite() const