CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
MultiHitGeneratorFromChi2.cc
Go to the documentation of this file.
2 
7 
12 
15 
22 
28 
30 
32 
33 #include <algorithm>
34 #include <iostream>
35 #include <vector>
36 #include <cmath>
37 #include <map>
38 #include <limits>
39 
40 using namespace std;
41 
43 
44 namespace {
45  struct LayerRZPredictions {
47  };
48 }
49 
51  : thePairGenerator(0),
52  theLayerCache(0),
53  useFixedPreFiltering(cfg.getParameter<bool>("useFixedPreFiltering")),
54  extraHitRZtolerance(cfg.getParameter<double>("extraHitRZtolerance")),//extra window in ThirdHitRZPrediction range
55  extraHitRPhitolerance(cfg.getParameter<double>("extraHitRPhitolerance")),//extra window in ThirdHitPredictionFromCircle range (divide by R to get phi)
56  extraZKDBox(cfg.getParameter<double>("extraZKDBox")),//extra windown in Z when building the KDTree box (used in barrel)
57  extraRKDBox(cfg.getParameter<double>("extraRKDBox")),//extra windown in R when building the KDTree box (used in endcap)
58  extraPhiKDBox(cfg.getParameter<double>("extraPhiKDBox")),//extra windown in Phi when building the KDTree box
59  fnSigmaRZ(cfg.getParameter<double>("fnSigmaRZ")),//this multiplies the max hit error on the layer when building the KDTree box
60  chi2VsPtCut(cfg.getParameter<bool>("chi2VsPtCut")),
61  maxChi2(cfg.getParameter<double>("maxChi2")),
62  refitHits(cfg.getParameter<bool>("refitHits")),
63  debug(cfg.getParameter<bool>("debug")),
64  filterName_(cfg.getParameter<std::string>("ClusterShapeHitFilterName")),
65  builderName_(cfg.existsAs<std::string>("TTRHBuilder") ? cfg.getParameter<std::string>("TTRHBuilder") : std::string("WithTrackAngle")),
66  useSimpleMF_(false),
67  mfName_("")
68 {
69  theMaxElement=cfg.getParameter<unsigned int>("maxElement");
71  dphi = cfg.getParameter<double>("phiPreFiltering");
72  if (chi2VsPtCut) {
73  pt_interv = cfg.getParameter<std::vector<double> >("pt_interv");
74  chi2_cuts = cfg.getParameter<std::vector<double> >("chi2_cuts");
75  }
76  if (debug) {
77  detIdsToDebug = cfg.getParameter<std::vector<int> >("detIdsToDebug");
78  //if (detIdsToDebug.size()<3) //fixme
79  } else {
80  detIdsToDebug.push_back(0);
81  detIdsToDebug.push_back(0);
82  detIdsToDebug.push_back(0);
83  }
84  // 2014/02/11 mia:
85  // we should get rid of the boolean parameter useSimpleMF,
86  // and use only a string magneticField [instead of SimpleMagneticField]
87  // or better an edm::ESInputTag (at the moment HLT does not handle ESInputTag)
88  if (cfg.exists("SimpleMagneticField")) {
89  useSimpleMF_ = true;
90  mfName_ = cfg.getParameter<std::string>("SimpleMagneticField");
91  }
92  filter = 0;
93  bfield = 0;
94  nomField = -1.;
95 }
96 
98  LayerCacheType *layerCache)
99 {
100  thePairGenerator = pairs.clone();
101  theLayerCache = layerCache;
102 }
103 
105 {
106 
108  if (useSimpleMF_) es.get<IdealMagneticFieldRecord>().get(mfName_, bfield_h);
109  else es.get<IdealMagneticFieldRecord>().get(bfield_h);
110  bfield = bfield_h.product();
112 
114  es.get<CkfComponentsRecord>().get(filterName_, filterHandle_);
115  filter = filterHandle_.product();
116 
118  es.get<TransientRecHitRecord>().get(builderName_, builderH);
119  builder = (TkTransientTrackingRecHitBuilder const *)(builderH.product());
120  cloner = (*builder).cloner();
121 }
122 
124  std::vector<SeedingLayerSetsHits::SeedingLayer> thirdLayers) {
125  thePairGenerator->setSeedingLayers(pairLayers);
126  theLayers = thirdLayers;
127 }
128 
129 namespace {
130  inline
131  bool intersect(Range &range, const Range &second)
132  {
133  if (range.first > second.max() || range.second < second.min())
134  return false;
135  if (range.first < second.min())
136  range.first = second.min();
137  if (range.second > second.max())
138  range.second = second.max();
139  return range.first < range.second;
140  }
141 }
142 
145  const edm::Event & ev,
146  const edm::EventSetup& es)
147 {
148 
149  unsigned int debug_Id0 = detIdsToDebug[0];
150  unsigned int debug_Id1 = detIdsToDebug[1];
151  unsigned int debug_Id2 = detIdsToDebug[2];
152 
153  if (debug) cout << "pair: " << ((HitPairGeneratorFromLayerPair*) thePairGenerator)->innerLayer().name() << "+" << ((HitPairGeneratorFromLayerPair*) thePairGenerator)->outerLayer().name() << " 3rd lay size: " << theLayers.size() << endl;
154 
155  //gc: first get the pairs
157  pairs.reserve(30000);
158  thePairGenerator->hitPairs(region,pairs,ev,es);
159  if (debug) cout << endl;
160  if (pairs.empty()) {
161  //cout << "empy pairs" << endl;
162  return;
163  }
164 
165  //gc: these are all the layers compatible with the layer pairs (as defined in the config file)
166  int size = theLayers.size();
167 
168 
169  //gc: initialize a KDTree per each 3rd layer
170  std::vector<KDTreeNodeInfo<RecHitsSortedInPhi::HitIter> > layerTree; // re-used throughout
171  std::vector<RecHitsSortedInPhi::HitIter> foundNodes; // re-used thoughout
172  foundNodes.reserve(100);
174  float rzError[size]; //save maximum errors
175  double maxphi = Geom::twoPi(), minphi = -maxphi; //increase to cater for any range
176 
177  map<std::string, LayerRZPredictions> mapPred;//need to use the name as map key since we may have more than one SeedingLayer per DetLayer (e.g. TID and MTID)
178  const RecHitsSortedInPhi * thirdHitMap[size];//gc: this comes from theLayerCache
179 
180  //gc: loop over each layer
181  for(int il = 0; il < size; il++) {
182  thirdHitMap[il] = &(*theLayerCache)(theLayers[il], region, ev, es);
183  if (debug) cout << "considering third layer: " << theLayers[il].name() << " with hits: " << thirdHitMap[il]->all().second-thirdHitMap[il]->all().first << endl;
184  const DetLayer *layer = theLayers[il].detLayer();
185  LayerRZPredictions &predRZ = mapPred[theLayers[il].name()];
186  predRZ.line.initLayer(layer);
187  predRZ.line.initTolerance(extraHitRZtolerance);
188 
189  //gc: now we take all hits in the layer and fill the KDTree
190  RecHitsSortedInPhi::Range hitRange = thirdHitMap[il]->all(); // Get iterators
191  layerTree.clear();
192  double minz=999999.0, maxz= -999999.0; // Initialise to extreme values in case no hits
193  float maxErr=0.0f;
194  bool barrelLayer = (theLayers[il].detLayer()->location() == GeomDetEnumerators::barrel);
195  if (hitRange.first != hitRange.second)
196  { minz = barrelLayer? hitRange.first->hit()->globalPosition().z() : hitRange.first->hit()->globalPosition().perp();
197  maxz = minz; //In case there's only one hit on the layer
198  for (RecHitsSortedInPhi::HitIter hi=hitRange.first; hi != hitRange.second; ++hi)
199  { double angle = hi->phi();
200  double myz = barrelLayer? hi->hit()->globalPosition().z() : hi->hit()->globalPosition().perp();
201 
202  if (debug && hi->hit()->rawId()==debug_Id2) {
203  cout << "filling KDTree with hit in id=" << debug_Id2
204  << " with pos: " << hi->hit()->globalPosition()
205  << " phi=" << hi->hit()->globalPosition().phi()
206  << " z=" << hi->hit()->globalPosition().z()
207  << " r=" << hi->hit()->globalPosition().perp()
208  << endl;
209  }
210  //use (phi,r) for endcaps rather than (phi,z)
211  if (myz < minz) { minz = myz;} else { if (myz > maxz) {maxz = myz;}}
212  float myerr = barrelLayer? hi->hit()->errorGlobalZ(): hi->hit()->errorGlobalR();
213  if (myerr > maxErr) { maxErr = myerr;}
214  layerTree.push_back(KDTreeNodeInfo<RecHitsSortedInPhi::HitIter>(hi, angle, myz)); // save it
215  if (angle < 0) // wrap all points in phi
216  { layerTree.push_back(KDTreeNodeInfo<RecHitsSortedInPhi::HitIter>(hi, angle+Geom::twoPi(), myz));}
217  else
218  { layerTree.push_back(KDTreeNodeInfo<RecHitsSortedInPhi::HitIter>(hi, angle-Geom::twoPi(), myz));}
219  }
220  }
221  KDTreeBox phiZ(minphi, maxphi, minz-0.01, maxz+0.01); // declare our bounds
222  //add fudge factors in case only one hit and also for floating-point inaccuracy
223  hitTree[il].build(layerTree, phiZ); // make KDtree
224  rzError[il] = maxErr; //save error
225  }
226  //gc: now we have initialized the KDTrees and we are out of the layer loop
227 
228  //gc: this sets the minPt of the triplet
229  double curv = PixelRecoUtilities::curvature(1. / region.ptMin(), es);
230 
231  if (debug) std::cout << "pair size=" << pairs.size() << std::endl;
232 
233  //gc: now we loop over all pairs
234  for (OrderedHitPairs::const_iterator ip = pairs.begin(); ip != pairs.end(); ++ip) {
235 
236  int foundTripletsFromPair = 0;
237  bool usePair = false;
238  cacheHitPointer bestH2;
240 
241  SeedingHitSet::ConstRecHitPointer oriHit0 = ip->inner();
242  SeedingHitSet::ConstRecHitPointer oriHit1 = ip->outer();
243 
244  HitOwnPtr hit0(*oriHit0);
245  HitOwnPtr hit1(*oriHit1);
246  GlobalPoint gp0 = hit0->globalPosition();
247  GlobalPoint gp1 = hit1->globalPosition();
248 
249  bool debugPair = debug && ip->inner()->rawId()==debug_Id0 && ip->outer()->rawId()==debug_Id1;
250 
251  if (debugPair) {
252  cout << endl << endl
253  << "found new pair with ids "<<debug_Id0<<" "<<debug_Id1<<" with pos: " << gp0 << " " << gp1
254  << endl;
255  }
256 
257  if (refitHits) {
258 
259  TrajectoryStateOnSurface tsos0, tsos1;
260  assert(!hit0.isOwn()); assert(!hit1.isOwn());
261  refit2Hits(hit0,hit1,tsos0,tsos1,region,nomField,debugPair);
262  assert(hit0.isOwn()); assert(hit1.isOwn());
263 
264  //fixme add pixels
265  bool passFilterHit0 = true;
266  if (//hit0->geographicalId().subdetId() > 2
267  hit0->geographicalId().subdetId()==SiStripDetId::TIB
268  || hit0->geographicalId().subdetId()==SiStripDetId::TID
269  //|| hit0->geographicalId().subdetId()==SiStripDetId::TOB
270  //|| hit0->geographicalId().subdetId()==SiStripDetId::TEC
271  ) {
272  const std::type_info &tid = typeid(*hit0->hit());
273  if (tid == typeid(SiStripMatchedRecHit2D)) {
274  const SiStripMatchedRecHit2D* matchedHit = dynamic_cast<const SiStripMatchedRecHit2D *>(hit0->hit());
275  if (filter->isCompatible(DetId(matchedHit->monoId()), matchedHit->monoCluster(), tsos0.localMomentum())==0 ||
276  filter->isCompatible(DetId(matchedHit->stereoId()), matchedHit->stereoCluster(), tsos0.localMomentum())==0) passFilterHit0 = false;
277  } else if (tid == typeid(SiStripRecHit2D)) {
278  const SiStripRecHit2D* recHit = dynamic_cast<const SiStripRecHit2D *>(hit0->hit());
279  if (filter->isCompatible(*recHit, tsos0.localMomentum())==0) passFilterHit0 = false;
280  } else if (tid == typeid(ProjectedSiStripRecHit2D)) {
281  const ProjectedSiStripRecHit2D* precHit = dynamic_cast<const ProjectedSiStripRecHit2D *>(hit0->hit());
282  if (filter->isCompatible(precHit->originalHit(), tsos0.localMomentum())==0) passFilterHit0 = false; //FIXME
283  }
284  }
285  if (debugPair&&!passFilterHit0) cout << "hit0 did not pass cluster shape filter" << endl;
286  if (!passFilterHit0) continue;
287  bool passFilterHit1 = true;
288  if (//hit1->geographicalId().subdetId() > 2
289  hit1->geographicalId().subdetId()==SiStripDetId::TIB
290  || hit1->geographicalId().subdetId()==SiStripDetId::TID
291  //|| hit1->geographicalId().subdetId()==SiStripDetId::TOB
292  //|| hit1->geographicalId().subdetId()==SiStripDetId::TEC
293  ) {
294  const std::type_info &tid = typeid(*hit1->hit());
295  if (tid == typeid(SiStripMatchedRecHit2D)) {
296  const SiStripMatchedRecHit2D* matchedHit = dynamic_cast<const SiStripMatchedRecHit2D *>(hit1->hit());
297  if (filter->isCompatible(DetId(matchedHit->monoId()), matchedHit->monoCluster(), tsos1.localMomentum())==0 ||
298  filter->isCompatible(DetId(matchedHit->stereoId()), matchedHit->stereoCluster(), tsos1.localMomentum())==0) passFilterHit1 = false;
299  } else if (tid == typeid(SiStripRecHit2D)) {
300  const SiStripRecHit2D* recHit = dynamic_cast<const SiStripRecHit2D *>(hit1->hit());
301  if (filter->isCompatible(*recHit, tsos1.localMomentum())==0) passFilterHit1 = false;
302  } else if (tid == typeid(ProjectedSiStripRecHit2D)) {
303  const ProjectedSiStripRecHit2D* precHit = dynamic_cast<const ProjectedSiStripRecHit2D *>(hit1->hit());
304  if (filter->isCompatible(precHit->originalHit(), tsos1.localMomentum())==0) passFilterHit1 = false; //FIXME
305  }
306  }
307  if (debugPair&&!passFilterHit1) cout << "hit1 did not pass cluster shape filter" << endl;
308  if (!passFilterHit1) continue;
309 
310  } else {
311  // not refit clone anyhow
312  hit0.reset((BaseTrackerRecHit *)hit0->clone());
313  hit1.reset((BaseTrackerRecHit *)hit1->clone());
314  }
315 
316  //gc: create the RZ line for the pair
317  SimpleLineRZ line(PixelRecoPointRZ(gp0.perp(),gp0.z()), PixelRecoPointRZ(gp1.perp(),gp1.z()));
318  ThirdHitPredictionFromCircle predictionRPhi(gp0, gp1, extraHitRPhitolerance);
319 
320  //gc: this is the curvature of the two hits assuming the region
321  Range pairCurvature = predictionRPhi.curvature(region.originRBound());
322  //gc: intersect not only returns a bool but may change pairCurvature to intersection with curv
323  if (!intersect(pairCurvature, Range(-curv, curv))) {
324  if (debugPair) std::cout << "curvature cut: curv=" << curv
325  << " gc=(" << pairCurvature.first << ", " << pairCurvature.second << ")" << std::endl;
326  continue;
327  }
328 
329  //gc: loop over all third layers compatible with the pair
330  for(int il = 0; (il < size) & (!usePair); il++) {
331 
332  if (debugPair)
333  cout << "cosider layer: " << theLayers[il].name() << " for this pair. Location: " << theLayers[il].detLayer()->location() << endl;
334 
335  if (hitTree[il].empty()) {
336  if (debugPair) {
337  cout << "empty hitTree" << endl;
338  }
339  continue; // Don't bother if no hits
340  }
341 
342  cacheHitPointer bestL2;
343  float chi2FromThisLayer = std::numeric_limits<float>::max();
344 
345  const DetLayer *layer = theLayers[il].detLayer();
346  bool barrelLayer = layer->location() == GeomDetEnumerators::barrel;
347 
348  LayerRZPredictions &predRZ = mapPred.find(theLayers[il].name())->second;
349  predRZ.line.initPropagator(&line);
350 
351  //gc: this takes the z at R-thick/2 and R+thick/2 according to
352  // the line from the two points and the adds the extra tolerance
353  Range rzRange = predRZ.line();
354 
355  if (rzRange.first >= rzRange.second) {
356  if (debugPair) {
357  cout << "rzRange empty" << endl;
358  }
359  continue;
360  }
361  //gc: check that rzRange is compatible with detector bounds
362  // note that intersect may change rzRange to intersection with bounds
363  if (!intersect(rzRange, predRZ.line.detSize())) {// theDetSize = Range(-maxZ, maxZ);
364  if (debugPair) {
365  cout << "rzRange and detector do not intersect" << endl;
366  }
367  continue;
368  }
369  Range radius = barrelLayer ? predRZ.line.detRange() : rzRange;
370 
371  //gc: define the phi range of the hits
372  Range phiRange;
373  if (useFixedPreFiltering) {
374  //gc: in this case it takes as range the phi of the outer
375  // hit +/- the phiPreFiltering value from cfg
376  float phi0 = ip->outer()->globalPosition().phi();
377  phiRange = Range(phi0 - dphi, phi0 + dphi);
378  } else {
379  //gc: predictionRPhi uses the cosine rule to find the phi of the 3rd point at radius, assuming the pairCurvature range [-c,+c]
380  if (pairCurvature.first<0. && pairCurvature.second<0.) {
381  float phi12 = predictionRPhi.phi(pairCurvature.first,radius.second);
382  float phi21 = predictionRPhi.phi(pairCurvature.second,radius.first);
383  while(unlikely(phi12 < phi21)) phi12 += float(2. * M_PI);
384  phiRange = Range(phi21,phi12);
385  } else if (pairCurvature.first>=0. && pairCurvature.second>=0.) {
386  float phi11 = predictionRPhi.phi(pairCurvature.first,radius.first);
387  float phi22 = predictionRPhi.phi(pairCurvature.second,radius.second);
388  while(unlikely(phi11 < phi22)) phi11 += float(2. * M_PI);
389  phiRange = Range(phi22,phi11);
390  } else {
391  float phi12 = predictionRPhi.phi(pairCurvature.first,radius.second);
392  float phi22 = predictionRPhi.phi(pairCurvature.second,radius.second);
393  while(unlikely(phi12 < phi22)) phi12 += float(2. * M_PI);
394  phiRange = Range(phi22,phi12);
395  }
396  }
397 
398  //gc: this is the place where hits in the compatible region are put in the foundNodes
400  foundNodes.clear(); // Now recover hits in bounding box...
401  // This needs range -twoPi to +twoPi to work
402  float prmin=phiRange.min(), prmax=phiRange.max(); //get contiguous range
403  if ((prmax-prmin) > Geom::twoPi()) {
404  prmax=Geom::pi(); prmin = -Geom::pi();
405  } else {
406  while (prmax>maxphi) { prmin -= Geom::twoPi(); prmax -= Geom::twoPi();}
407  while (prmin<minphi) { prmin += Geom::twoPi(); prmax += Geom::twoPi();}
408  }
409 
410  if (debugPair) cout << "defining kd tree box" << endl;
411 
412  if (barrelLayer) {
413  KDTreeBox phiZ(prmin-extraPhiKDBox, prmax+extraPhiKDBox,
414  rzRange.min()-fnSigmaRZ*rzError[il]-extraZKDBox,
415  rzRange.max()+fnSigmaRZ*rzError[il]+extraZKDBox);
416  hitTree[il].search(phiZ, foundNodes);
417 
418  if (debugPair) cout << "kd tree box bounds, phi: " << prmin-extraPhiKDBox <<","<< prmax+extraPhiKDBox
419  << " z: "<< rzRange.min()-fnSigmaRZ*rzError[il]-extraZKDBox <<","<<rzRange.max()+fnSigmaRZ*rzError[il]+extraZKDBox
420  << " rzRange: " << rzRange.min() <<","<<rzRange.max()
421  << endl;
422 
423  } else {
424  KDTreeBox phiR(prmin-extraPhiKDBox, prmax+extraPhiKDBox,
425  rzRange.min()-fnSigmaRZ*rzError[il]-extraRKDBox,
426  rzRange.max()+fnSigmaRZ*rzError[il]+extraRKDBox);
427  hitTree[il].search(phiR, foundNodes);
428 
429  if (debugPair) cout << "kd tree box bounds, phi: " << prmin-extraPhiKDBox <<","<< prmax+extraPhiKDBox
430  << " r: "<< rzRange.min()-fnSigmaRZ*rzError[il]-extraRKDBox <<","<<rzRange.max()+fnSigmaRZ*rzError[il]+extraRKDBox
431  << " rzRange: " << rzRange.min() <<","<<rzRange.max()
432  << endl;
433  }
434 
435  if (debugPair) cout << "kd tree box size: " << foundNodes.size() << endl;
436 
437 
438  //gc: now we loop over the hits in the box for this layer
439  for (std::vector<RecHitsSortedInPhi::HitIter>::iterator ih = foundNodes.begin();
440  ih !=foundNodes.end() && !usePair; ++ih) {
441 
442  if (debugPair) std::cout << endl << "triplet candidate" << std::endl;
443 
444  const RecHitsSortedInPhi::HitIter KDdata = *ih;
445 
446  SeedingHitSet::ConstRecHitPointer oriHit2 = KDdata->hit();
447  cacheHitPointer hit2;
448 
449  if (refitHits) {//fixme
450 
451  //fitting all 3 hits takes too much time... do it quickly only for 3rd hit
452  GlobalVector initMomentum(oriHit2->globalPosition() - gp1);
453  initMomentum *= (1./initMomentum.perp()); //set pT=1
454  GlobalTrajectoryParameters kine = GlobalTrajectoryParameters(oriHit2->globalPosition(), initMomentum, 1, &*bfield);
455  TrajectoryStateOnSurface state(kine,*oriHit2->surface());
456  hit2.reset((SeedingHitSet::RecHitPointer)(cloner(*oriHit2,state)));
457 
458  //fixme add pixels
459  bool passFilterHit2 = true;
460  if (hit2->geographicalId().subdetId()==SiStripDetId::TIB
461  || hit2->geographicalId().subdetId()==SiStripDetId::TID
462  // || hit2->geographicalId().subdetId()==SiStripDetId::TOB
463  // || hit2->geographicalId().subdetId()==SiStripDetId::TEC
464  ) {
465  const std::type_info &tid = typeid(*hit2->hit());
466  if (tid == typeid(SiStripMatchedRecHit2D)) {
467  const SiStripMatchedRecHit2D* matchedHit = dynamic_cast<const SiStripMatchedRecHit2D *>(hit2->hit());
468  if (filter->isCompatible(DetId(matchedHit->monoId()), matchedHit->monoCluster(), initMomentum)==0 ||
469  filter->isCompatible(DetId(matchedHit->stereoId()), matchedHit->stereoCluster(), initMomentum)==0) passFilterHit2 = false;
470  } else if (tid == typeid(SiStripRecHit2D)) {
471  const SiStripRecHit2D* recHit = dynamic_cast<const SiStripRecHit2D *>(hit2->hit());
472  if (filter->isCompatible(*recHit, initMomentum)==0) passFilterHit2 = false;
473  } else if (tid == typeid(ProjectedSiStripRecHit2D)) {
474  const ProjectedSiStripRecHit2D* precHit = dynamic_cast<const ProjectedSiStripRecHit2D *>(hit2->hit());
475  if (filter->isCompatible(precHit->originalHit(), initMomentum)==0) passFilterHit2 = false;
476  }
477  }
478  if (debugPair&&!passFilterHit2) cout << "hit2 did not pass cluster shape filter" << endl;
479  if (!passFilterHit2) continue;
480 
481  // fitting all 3 hits takes too much time :-(
482  // TrajectoryStateOnSurface tsos0, tsos1, tsos2;
483  // refit3Hits(hit0,hit1,hit2,tsos0,tsos1,tsos2,nomField,debugPair);
484  // if (hit2->geographicalId().subdetId()==SiStripDetId::TIB
485  // // || hit2->geographicalId().subdetId()==SiStripDetId::TOB
486  // // || hit2->geographicalId().subdetId()==SiStripDetId::TID
487  // // || hit2->geographicalId().subdetId()==SiStripDetId::TEC
488  // ) {
489  // const std::type_info &tid = typeid(*hit2->hit());
490  // if (tid == typeid(SiStripMatchedRecHit2D)) {
491  // const SiStripMatchedRecHit2D* matchedHit = dynamic_cast<const SiStripMatchedRecHit2D *>(hit2->hit());
492  // if (filter->isCompatible(DetId(matchedHit->monoId()), matchedHit->monoCluster(), tsos2.localMomentum())==0 ||
493  // filter->isCompatible(DetId(matchedHit->stereoId()), matchedHit->stereoCluster(), tsos2.localMomentum())==0) continue;
494  // } else if (tid == typeid(SiStripRecHit2D)) {
495  // const SiStripRecHit2D* recHit = dynamic_cast<const SiStripRecHit2D *>(hit2->hit());
496  // if (filter->isCompatible(*recHit, tsos2.localMomentum())==0) continue;
497  // } else if (tid == typeid(ProjectedSiStripRecHit2D)) {
498  // const ProjectedSiStripRecHit2D* precHit = dynamic_cast<const ProjectedSiStripRecHit2D *>(hit2->hit());
499  // if (filter->isCompatible(precHit->originalHit(), tsos2.localMomentum())==0) continue;;
500  // }
501  // }
502 
503  } else {
504  // not refit clone anyhow
505  hit2.reset((BaseTrackerRecHit*)oriHit2->clone());
506  }
507 
508  //gc: add the chi2 cut
509  vector<GlobalPoint> gp(3);
510  vector<GlobalError> ge(3);
511  vector<bool> bl(3);
512  gp[0] = hit0->globalPosition();
513  ge[0] = hit0->globalPositionError();
514  int subid0 = hit0->geographicalId().subdetId();
515  bl[0] = (subid0 == StripSubdetector::TIB || subid0 == StripSubdetector::TOB || subid0 == (int) PixelSubdetector::PixelBarrel);
516  gp[1] = hit1->globalPosition();
517  ge[1] = hit1->globalPositionError();
518  int subid1 = hit1->geographicalId().subdetId();
519  bl[1] = (subid1 == StripSubdetector::TIB || subid1 == StripSubdetector::TOB || subid1 == (int) PixelSubdetector::PixelBarrel);
520  gp[2] = hit2->globalPosition();
521  ge[2] = hit2->globalPositionError();
522  int subid2 = hit2->geographicalId().subdetId();
523  bl[2] = (subid2 == StripSubdetector::TIB || subid2 == StripSubdetector::TOB || subid2 == (int) PixelSubdetector::PixelBarrel);
524  RZLine rzLine(gp,ge,bl);
525  float cottheta, intercept, covss, covii, covsi;
526  rzLine.fit(cottheta, intercept, covss, covii, covsi);
527  float chi2 = rzLine.chi2(cottheta, intercept);
528 
529  bool debugTriplet = debugPair && hit2->rawId()==debug_Id2;
530  if (debugTriplet) {
531  std::cout << endl << "triplet candidate in debug id" << std::endl;
532  cout << "hit in id="<<hit2->rawId()<<" (from KDTree) with pos: " << KDdata->hit()->globalPosition()
533  << " refitted: " << hit2->globalPosition()
534  << " chi2: " << chi2
535  << endl;
536  //cout << state << endl;
537  }
538  // should fix nan
539  if ( (chi2 > maxChi2) | edm::isNotFinite(chi2) ) continue;
540 
541  if (chi2VsPtCut) {
542 
543  FastCircle theCircle(hit2->globalPosition(),hit1->globalPosition(),hit0->globalPosition());
544  float tesla0 = 0.1*nomField;
545  float rho = theCircle.rho();
546  float cm2GeV = 0.01 * 0.3*tesla0;
547  float pt = cm2GeV * rho;
548  if (debugTriplet) {
549  std::cout << "triplet pT=" << pt << std::endl;
550  }
551  if (pt<region.ptMin()) continue;
552 
553  if (chi2_cuts.size()==4) {
554  if ( ( pt>pt_interv[0] && pt<=pt_interv[1] && chi2 > chi2_cuts[0] ) ||
555  ( pt>pt_interv[1] && pt<=pt_interv[2] && chi2 > chi2_cuts[1] ) ||
556  ( pt>pt_interv[2] && pt<=pt_interv[3] && chi2 > chi2_cuts[2] ) ||
557  ( pt>pt_interv[3] && chi2 > chi2_cuts[3] ) ) continue;
558  }
559 
560  // apparently this takes too much time...
561  // if (chi2_cuts.size()>1) {
562  // int ncuts = chi2_cuts.size();
563  // if ( pt<=pt_interv[0] && chi2 > chi2_cuts[0] ) continue;
564  // bool pass = true;
565  // for (int icut=1; icut<ncuts-1; icut++){
566  // if ( pt>pt_interv[icut-1] && pt<=pt_interv[icut] && chi2 > chi2_cuts[icut] ) pass=false;
567  // }
568  // if (!pass) continue;
569  // if ( pt>pt_interv[ncuts-2] && chi2 > chi2_cuts[ncuts-1] ) continue;
570  // if (debug && hit0->rawId()==debug_Id0 && hit1->rawId()==debug_Id1 && hit2->rawId()==debug_Id2) {
571  // std::cout << "triplet passed chi2 vs pt cut" << std::endl;
572  // }
573  // }
574 
575  }
576 
577  if (theMaxElement!=0 && result.size() >= theMaxElement) {
578  result.clear();
579  edm::LogError("TooManyTriplets")<<" number of triples exceed maximum. no triplets produced.";
580  return;
581  }
582  if (debugPair) std::cout << "triplet made" << std::endl;
583  //result.push_back(SeedingHitSet(hit0, hit1, hit2));
584  /* no refit so keep only hit2
585  assert(tripletFromThisLayer.empty());
586  assert(hit0.isOwn()); assert(hit1.isOwn());assert(hit2.isOwn());
587  tripletFromThisLayer.emplace_back(std::move(hit0));
588  tripletFromThisLayer.emplace_back(std::move(hit1));
589  tripletFromThisLayer.emplace_back(std::move(hit2));
590  assert(hit0.isEmpty()); assert(hit1.isEmpty());assert(hit2.isEmpty());
591  */
592  bestL2 = std::move(hit2);
593  chi2FromThisLayer = chi2;
594  foundTripletsFromPair++;
595  if (foundTripletsFromPair>=2) {
596  usePair=true;
597  if (debugPair)
598  std::cout << "using pair" << std::endl;
599  break;
600  }
601  }//loop over hits in KDTree
602 
603  if (usePair) break;
604  else {
605  //if there is one triplet in more than one layer, try picking the one with best chi2
606  if (chi2FromThisLayer<minChi2) {
607  bestH2 = std::move(bestL2);
608  minChi2 = chi2FromThisLayer;
609  }
610  /*
611  else {
612  if (!bestH2 && foundTripletsFromPair>0)
613  std::cout << "what?? " << minChi2 << ' ' << chi2FromThisLayer << std::endl;
614  }
615  */
616  }
617 
618  }//loop over layers
619 
620  if (foundTripletsFromPair==0) continue;
621 
622  //push back only (max) once per pair
623  if (debugPair) std::cout << "Done seed #" << result.size() << std::endl;
624  if (usePair) result.push_back(SeedingHitSet(ip->inner(), ip->outer()));
625  else {
626  assert(1==foundTripletsFromPair);
627  assert(bestH2);
628  result.emplace_back(&*hit0,&*hit1,&*bestH2);
629  assert(hit0.isOwn()); assert(hit1.isOwn());
630  cache.emplace_back(const_cast<BaseTrackerRecHit*>(hit0.release()));
631  cache.emplace_back(const_cast<BaseTrackerRecHit*>(hit1.release()));
632  cache.emplace_back(std::move(bestH2));
633  assert(hit0.empty()); assert(hit1.empty());assert(!bestH2);
634  }
635  // std::cout << (usePair ? "pair " : "triplet ") << minChi2 <<' ' << cache.size() << std::endl;
636 
637 
638  }//loop over pairs
639  if (debug) {
640  std::cout << "triplet size=" << result.size() << std::endl;
641  }
642 }
643 
644 bool MultiHitGeneratorFromChi2::checkPhiInRange(float phi, float phi1, float phi2) const
645 { while (phi > phi2) phi -= 2. * M_PI;
646  while (phi < phi1) phi += 2. * M_PI;
647  return phi <= phi2;
648 }
649 
650 std::pair<float, float>
651 MultiHitGeneratorFromChi2::mergePhiRanges(const std::pair<float, float> &r1,
652  const std::pair<float, float> &r2) const
653 { float r2Min = r2.first;
654  float r2Max = r2.second;
655  while (r1.first - r2Min > +M_PI) r2Min += 2. * M_PI, r2Max += 2. * M_PI;
656  while (r1.first - r2Min < -M_PI) r2Min -= 2. * M_PI, r2Max -= 2. * M_PI;
657  //std::cout << "mergePhiRanges " << fabs(r1.first-r2Min) << " " << fabs(r1.second-r2Max) << endl;
658  return std::make_pair(min(r1.first, r2Min), max(r1.second, r2Max));
659 }
660 
662  HitOwnPtr & hit2,
663  TrajectoryStateOnSurface& state1,
664  TrajectoryStateOnSurface& state2,
665  const TrackingRegion& region, float nomField, bool isDebug) {
666 
667  //these need to be sorted in R
668  GlobalPoint gp0 = region.origin();
669  GlobalPoint gp1 = hit1->globalPosition();
670  GlobalPoint gp2 = hit2->globalPosition();
671 
672  if (isDebug) {
673  cout << "positions before refitting: " << hit1->globalPosition() << " " << hit2->globalPosition() <<endl;
674  }
675 
676  FastCircle theCircle(gp2,gp1,gp0);
677  GlobalPoint cc(theCircle.x0(),theCircle.y0(),0);
678  float tesla0 = 0.1*nomField;
679  float rho = theCircle.rho();
680  float cm2GeV = 0.01 * 0.3*tesla0;
681  float pt = cm2GeV * rho;
682 
683  GlobalVector vec20 = gp2-gp0;
684  //if (isDebug) { cout << "vec20.eta=" << vec20.eta() << endl; }
685 
686  GlobalVector p0( gp0.y()-cc.y(), -gp0.x()+cc.x(), 0. );
687  p0 = p0*pt/p0.perp();
688  GlobalVector p1( gp1.y()-cc.y(), -gp1.x()+cc.x(), 0. );
689  p1 = p1*pt/p1.perp();
690  GlobalVector p2( gp2.y()-cc.y(), -gp2.x()+cc.x(), 0. );
691  p2 = p2*pt/p2.perp();
692 
693  //check sign according to scalar product
694  if ( (p0.x()*(gp1.x()-gp0.x())+p0.y()*(gp1.y()-gp0.y()) ) < 0 ) {
695  p0*=-1.;
696  p1*=-1.;
697  p2*=-1.;
698  }
699 
700  //now set z component
701  p0 = GlobalVector(p0.x(),p0.y(),p0.perp()/tan(vec20.theta()));
702  p1 = GlobalVector(p1.x(),p1.y(),p1.perp()/tan(vec20.theta()));
703  p2 = GlobalVector(p2.x(),p2.y(),p2.perp()/tan(vec20.theta()));
704 
705  //get charge from vectorial product
706  TrackCharge q = 1;
707  if ((gp1-cc).x()*p1.y() - (gp1-cc).y()*p1.x() > 0) q =-q;
708 
710  state1 = TrajectoryStateOnSurface(kine1,*hit1->surface());
711  hit1.reset((SeedingHitSet::RecHitPointer)(cloner(*hit1,state1)));
712 
714  state2 = TrajectoryStateOnSurface(kine2,*hit2->surface());
715  hit2.reset((SeedingHitSet::RecHitPointer)(cloner(*hit2,state2)));
716 
717  if (isDebug) {
718  cout << "charge=" << q << endl;
719  cout << "state1 pt=" << state1.globalMomentum().perp() << " eta=" << state1.globalMomentum().eta() << " phi=" << state1.globalMomentum().phi() << endl;
720  cout << "state2 pt=" << state2.globalMomentum().perp() << " eta=" << state2.globalMomentum().eta() << " phi=" << state2.globalMomentum().phi() << endl;
721  cout << "positions after refitting: " << hit1->globalPosition() << " " << hit2->globalPosition() <<endl;
722  }
723 
724 }
725 
726 /*
727 void MultiHitGeneratorFromChi2::refit3Hits(HitOwnPtr & hit0,
728  HitOwnPtr & hit1,
729  HitOwnPtr & hit2,
730  TrajectoryStateOnSurface& state0,
731  TrajectoryStateOnSurface& state1,
732  TrajectoryStateOnSurface& state2,
733  float nomField, bool isDebug) {
734 
735  //these need to be sorted in R
736  GlobalPoint gp0 = hit0->globalPosition();
737  GlobalPoint gp1 = hit1->globalPosition();
738  GlobalPoint gp2 = hit2->globalPosition();
739 
740  if (isDebug) {
741  cout << "positions before refitting: " << hit0->globalPosition() << " " << hit1->globalPosition() << " " << hit2->globalPosition() <<endl;
742  }
743 
744  FastCircle theCircle(gp2,gp1,gp0);
745  GlobalPoint cc(theCircle.x0(),theCircle.y0(),0);
746  float tesla0 = 0.1*nomField;
747  float rho = theCircle.rho();
748  float cm2GeV = 0.01 * 0.3*tesla0;
749  float pt = cm2GeV * rho;
750 
751  GlobalVector vec20 = gp2-gp0;
752  //if (isDebug) { cout << "vec20.eta=" << vec20.eta() << endl; }
753 
754  GlobalVector p0( gp0.y()-cc.y(), -gp0.x()+cc.x(), 0. );
755  p0 = p0*pt/p0.perp();
756  GlobalVector p1( gp1.y()-cc.y(), -gp1.x()+cc.x(), 0. );
757  p1 = p1*pt/p1.perp();
758  GlobalVector p2( gp2.y()-cc.y(), -gp2.x()+cc.x(), 0. );
759  p2 = p2*pt/p2.perp();
760 
761  //check sign according to scalar product
762  if ( (p0.x()*(gp1.x()-gp0.x())+p0.y()*(gp1.y()-gp0.y()) ) < 0 ) {
763  p0*=-1.;
764  p1*=-1.;
765  p2*=-1.;
766  }
767 
768  //now set z component
769  p0 = GlobalVector(p0.x(),p0.y(),p0.perp()/tan(vec20.theta()));
770  p1 = GlobalVector(p1.x(),p1.y(),p1.perp()/tan(vec20.theta()));
771  p2 = GlobalVector(p2.x(),p2.y(),p2.perp()/tan(vec20.theta()));
772 
773  //get charge from vectorial product
774  TrackCharge q = 1;
775  if ((gp1-cc).x()*p1.y() - (gp1-cc).y()*p1.x() > 0) q =-q;
776 
777  GlobalTrajectoryParameters kine0 = GlobalTrajectoryParameters(gp0, p0, q, &*bfield);
778  state0 = TrajectoryStateOnSurface(kine0,*hit0->surface());
779  hit0 = hit0->clone(state0);
780 
781  GlobalTrajectoryParameters kine1 = GlobalTrajectoryParameters(gp1, p1, q, &*bfield);
782  state1 = TrajectoryStateOnSurface(kine1,*hit1->surface());
783  hit1 = hit1->clone(state1);
784 
785  GlobalTrajectoryParameters kine2 = GlobalTrajectoryParameters(gp2, p2, q, &*bfield);
786  state2 = TrajectoryStateOnSurface(kine2,*hit2->surface());
787  hit2 = hit2->clone(state2);
788 
789  if (isDebug) {
790  cout << "charge=" << q << endl;
791  cout << "state0 pt=" << state0.globalMomentum().perp() << " eta=" << state0.globalMomentum().eta() << " phi=" << state0.globalMomentum().phi() << endl;
792  cout << "state1 pt=" << state1.globalMomentum().perp() << " eta=" << state1.globalMomentum().eta() << " phi=" << state1.globalMomentum().phi() << endl;
793  cout << "state2 pt=" << state2.globalMomentum().perp() << " eta=" << state2.globalMomentum().eta() << " phi=" << state2.globalMomentum().phi() << endl;
794  cout << "positions after refitting: " << hit0->globalPosition() << " " << hit1->globalPosition() << " " << hit2->globalPosition() <<endl;
795  }
796 
797 }
798 */
799 
float originRBound() const
bounds the particle vertex in the transverse plane
T getParameter(std::string const &) const
std::pair< float, float > mergePhiRanges(const std::pair< float, float > &r1, const std::pair< float, float > &r2) const
void reset()
Definition: ProxyBase11.h:64
virtual HitPairGenerator * clone() const =0
unsigned int stereoId() const
void build(std::vector< KDTreeNodeInfo > &eltList, const KDTreeBox &region)
bool empty() const
Definition: mayown_ptr.h:59
T perp() const
Definition: PV3DBase.h:72
GlobalPoint const & origin() const
virtual Location location() const =0
Which part of the detector (barrel, endcap)
int nominalValue() const
The nominal field value for this map in kGauss.
Definition: MagneticField.h:56
double x0() const
Definition: FastCircle.h:50
TkTransientTrackingRecHitBuilder const * builder
bool isOwn() const
Definition: mayown_ptr.h:26
SiStripCluster const & monoCluster() const
const ClusterShapeHitFilter * filter
Definition: DDAxes.h:10
Geom::Phi< T > phi() const
Definition: PV3DBase.h:69
T y() const
Definition: PV3DBase.h:63
bool exists(std::string const &parameterName) const
checks if a parameter exists
bool ev
virtual unsigned int size() const
void search(const KDTreeBox &searchBox, std::vector< KDTreeNodeInfo > &resRecHitList)
double rho() const
Definition: FastCircle.h:54
void reset()
Definition: mayown_ptr.h:56
T const * release()
Definition: mayown_ptr.h:55
Range curvature(double transverseIP) const
std::vector< SeedingLayerSetsHits::SeedingLayer > theLayers
Geom::Theta< T > theta() const
Definition: PV3DBase.h:75
static float fnSigmaRZ
LocalVector localMomentum() const
#define unlikely(x)
U second(std::pair< T, U > const &p)
virtual unsigned int size() const
void init(const HitPairGenerator &pairs, LayerCacheType *layerCache) override
std::pair< HitIter, HitIter > Range
int TrackCharge
Definition: TrackCharge.h:4
BaseTrackerRecHit const * ConstRecHitPointer
Definition: SeedingHitSet.h:11
bool isNotFinite(T x)
Definition: isFinite.h:10
T curvature(T InversePt, const edm::EventSetup &iSetup)
std::vector< HitWithPhi >::const_iterator HitIter
void setSeedingLayers(SeedingLayerSetsHits::SeedingLayerSet pairLayers, std::vector< SeedingLayerSetsHits::SeedingLayer > thirdLayers) override
T z() const
Definition: PV3DBase.h:64
tuple result
Definition: query.py:137
void initES(const edm::EventSetup &es) override
Tan< T >::type tan(const T &t)
Definition: Tan.h:22
MultiHitGeneratorFromChi2(const edm::ParameterSet &cfg)
T min(T a, T b)
Definition: MathUtil.h:58
double p2[4]
Definition: TauolaWrapper.h:90
#define M_PI
bool isCompatible(const SiPixelRecHit &recHit, const LocalVector &ldir, const SiPixelClusterShapeCache &clusterShapeCache, PixelData const *pd=0) const
SeedingHitSet::ConstRecHitPointer Hit
BaseTrackerRecHit const * Hit
Definition: RZLine.h:8
SiStripRecHit2D originalHit() const
Definition: DetId.h:18
PixelRecoRange< float > Range
#define debug
Definition: HDRShower.cc:19
const T & get() const
Definition: EventSetup.h:55
T const * product() const
Definition: ESHandle.h:62
float ptMin() const
minimal pt of interest
T eta() const
Definition: PV3DBase.h:76
double y0() const
Definition: FastCircle.h:52
SiStripCluster const & stereoCluster() const
double p1[4]
Definition: TauolaWrapper.h:89
GlobalVector globalMomentum() const
double pi()
Definition: Pi.h:31
double twoPi()
Definition: Pi.h:32
void fit(float &cotTheta, float &intercept, float &covss, float &covii, float &covsi) const
Definition: RZLine.cc:44
tuple cout
Definition: gather_cfg.py:121
float chi2(float cotTheta, float intercept) const
Definition: RZLine.cc:50
unsigned int monoId() const
volatile std::atomic< bool > shutdown_flag false
Definition: DDAxes.h:10
std::unique_ptr< BaseTrackerRecHit > cacheHitPointer
list pairs
sort tag files by run number
T x() const
Definition: PV3DBase.h:62
float phi(float curvature, float radius) const
tuple size
Write out results.
virtual void setSeedingLayers(SeedingLayerSetsHits::SeedingLayerSet layers)=0
bool checkPhiInRange(float phi, float phi1, float phi2) const
virtual void hitSets(const TrackingRegion &region, OrderedMultiHits &trs, const edm::Event &ev, const edm::EventSetup &es)
Global3DVector GlobalVector
Definition: GlobalVector.h:10
void refit2Hits(HitOwnPtr &hit0, HitOwnPtr &hit1, TrajectoryStateOnSurface &tsos0, TrajectoryStateOnSurface &tsos1, const TrackingRegion &region, float nomField, bool isDebug)
T angle(T x1, T y1, T z1, T x2, T y2, T z2)
Definition: angle.h:11
Definition: DDAxes.h:10