CMS 3D CMS Logo

PFlow2DClusterizerWithTime.cc
Go to the documentation of this file.
8 
9 #include "Math/GenVector/VectorUtil.h"
10 #include "TMath.h"
11 #include "vdt/vdtMath.h"
12 
13 #include <iterator>
14 #include <unordered_map>
15 
18 
19 public:
21 
22  ~PFlow2DClusterizerWithTime() override = default;
23  PFlow2DClusterizerWithTime(const B2DGPF&) = delete;
24  B2DGPF& operator=(const B2DGPF&) = delete;
25 
26  void update(const edm::EventSetup& es) override {
27  _positionCalc->update(es);
28  if (_allCellsPosCalc)
29  _allCellsPosCalc->update(es);
31  _convergencePosCalc->update(es);
32  }
33 
35  const std::vector<bool>&,
36  reco::PFClusterCollection& outclus) override;
37 
38 private:
39  const unsigned _maxIterations;
40  const double _stoppingTolerance;
41  const double _showerSigma2;
42  const double _timeSigma_eb;
43  const double _timeSigma_ee;
44  const bool _excludeOtherSeeds;
45  const double _minFracTot;
46  const double _maxNSigmaTime;
47  const double _minChi2Prob;
49 
50  const std::unordered_map<std::string, int> _layerMap;
51  std::unordered_map<int, double> _recHitEnergyNorms;
52  std::unique_ptr<PFCPositionCalculatorBase> _allCellsPosCalc;
53  std::unique_ptr<PFCPositionCalculatorBase> _convergencePosCalc;
54 
55  std::unique_ptr<CaloRecHitResolutionProvider> _timeResolutionCalcBarrel;
56  std::unique_ptr<CaloRecHitResolutionProvider> _timeResolutionCalcEndcap;
57 
58  void seedPFClustersFromTopo(const reco::PFCluster&, const std::vector<bool>&, reco::PFClusterCollection&) const;
59 
60  void growPFClusters(const reco::PFCluster&,
61  const std::vector<bool>&,
62  const unsigned toleranceScaling,
63  const unsigned iter,
64  double dist,
66  void clusterTimeResolution(reco::PFCluster& cluster, double& res) const;
67  void clusterTimeResolutionFromSeed(reco::PFCluster& cluster, double& res) const;
68  double dist2Time(const reco::PFCluster&, const reco::PFRecHitRef&, int cell_layer, double prev_timeres2) const;
69  bool passChi2Prob(size_t iCluster,
70  double dist2,
71  std::vector<double>& clus_chi2,
72  std::vector<size_t>& clus_chi2_nhits) const;
74 };
75 
77 
78 #ifdef PFLOW_DEBUG
79 #define LOGVERB(x) edm::LogVerbatim(x)
80 #define LOGWARN(x) edm::LogWarning(x)
81 #define LOGERR(x) edm::LogError(x)
82 #define LOGDRESSED(x) edm::LogInfo(x)
83 #else
84 #define LOGVERB(x) LogTrace(x)
85 #define LOGWARN(x) edm::LogWarning(x)
86 #define LOGERR(x) edm::LogError(x)
87 #define LOGDRESSED(x) LogDebug(x)
88 #endif
89 
91  : PFClusterBuilderBase(conf, cc),
92  _maxIterations(conf.getParameter<unsigned>("maxIterations")),
93  _stoppingTolerance(conf.getParameter<double>("stoppingTolerance")),
94  _showerSigma2(std::pow(conf.getParameter<double>("showerSigma"), 2.0)),
95  _timeSigma_eb(std::pow(conf.getParameter<double>("timeSigmaEB"), 2.0)),
96  _timeSigma_ee(std::pow(conf.getParameter<double>("timeSigmaEE"), 2.0)),
97  _excludeOtherSeeds(conf.getParameter<bool>("excludeOtherSeeds")),
98  _minFracTot(conf.getParameter<double>("minFracTot")),
99  _maxNSigmaTime(std::pow(conf.getParameter<double>("maxNSigmaTime"), 2.0)),
100  _minChi2Prob(conf.getParameter<double>("minChi2Prob")),
101  _clusterTimeResFromSeed(conf.getParameter<bool>("clusterTimeResFromSeed")),
102 
103  _layerMap({{"PS2", (int)PFLayer::PS2},
104  {"PS1", (int)PFLayer::PS1},
105  {"ECAL_ENDCAP", (int)PFLayer::ECAL_ENDCAP},
106  {"ECAL_BARREL", (int)PFLayer::ECAL_BARREL},
107  {"NONE", (int)PFLayer::NONE},
108  {"HCAL_BARREL1", (int)PFLayer::HCAL_BARREL1},
109  {"HCAL_BARREL2_RING0", (int)PFLayer::HCAL_BARREL2},
110  {"HCAL_BARREL2_RING1", 100 * (int)PFLayer::HCAL_BARREL2},
111  {"HCAL_ENDCAP", (int)PFLayer::HCAL_ENDCAP},
112  {"HF_EM", (int)PFLayer::HF_EM},
113  {"HF_HAD", (int)PFLayer::HF_HAD}}) {
114  const std::vector<edm::ParameterSet>& thresholds = conf.getParameterSetVector("recHitEnergyNorms");
115  for (const auto& pset : thresholds) {
116  const std::string& det = pset.getParameter<std::string>("detector");
117  const double& rhE_norm = pset.getParameter<double>("recHitEnergyNorm");
118  auto entry = _layerMap.find(det);
119  if (entry == _layerMap.end()) {
120  throw cms::Exception("InvalidDetectorLayer") << "Detector layer : " << det << " is not in the list of recognized"
121  << " detector layers!";
122  }
123  _recHitEnergyNorms.emplace(_layerMap.find(det)->second, rhE_norm);
124  }
125 
126  if (conf.exists("allCellsPositionCalc")) {
127  const edm::ParameterSet& acConf = conf.getParameterSet("allCellsPositionCalc");
128  const std::string& algoac = acConf.getParameter<std::string>("algoName");
129  _allCellsPosCalc = PFCPositionCalculatorFactory::get()->create(algoac, acConf, cc);
130  }
131  // if necessary a third pos calc for convergence testing
132  if (conf.exists("positionCalcForConvergence")) {
133  const edm::ParameterSet& convConf = conf.getParameterSet("positionCalcForConvergence");
134  const std::string& algoconv = convConf.getParameter<std::string>("algoName");
135  _convergencePosCalc = PFCPositionCalculatorFactory::get()->create(algoconv, convConf, cc);
136  }
137  if (conf.exists("timeResolutionCalcBarrel")) {
138  const edm::ParameterSet& timeResConf = conf.getParameterSet("timeResolutionCalcBarrel");
139  _timeResolutionCalcBarrel = std::make_unique<CaloRecHitResolutionProvider>(timeResConf);
140  }
141  if (conf.exists("timeResolutionCalcEndcap")) {
142  const edm::ParameterSet& timeResConf = conf.getParameterSet("timeResolutionCalcEndcap");
143  _timeResolutionCalcEndcap = std::make_unique<CaloRecHitResolutionProvider>(timeResConf);
144  }
145 }
146 
148  const std::vector<bool>& seedable,
150  reco::PFClusterCollection clustersInTopo;
151  for (const auto& topocluster : input) {
152  clustersInTopo.clear();
153  seedPFClustersFromTopo(topocluster, seedable, clustersInTopo);
154  const unsigned tolScal = std::pow(std::max(1.0, clustersInTopo.size() - 1.0), 2.0);
155  growPFClusters(topocluster, seedable, tolScal, 0, tolScal, clustersInTopo);
156  // step added by Josh Bendavid, removes low-fraction clusters
157  // did not impact position resolution with fraction cut of 1e-7
158  // decreases the size of each pf cluster considerably
159  prunePFClusters(clustersInTopo);
160  // recalculate the positions of the pruned clusters
161  if (_convergencePosCalc) {
162  // if defined, use the special position calculation for convergence tests
163  _convergencePosCalc->calculateAndSetPositions(clustersInTopo);
164  } else {
165  if (clustersInTopo.size() == 1 && _allCellsPosCalc) {
166  _allCellsPosCalc->calculateAndSetPosition(clustersInTopo.back());
167  } else {
168  _positionCalc->calculateAndSetPositions(clustersInTopo);
169  }
170  }
171  for (auto& clusterout : clustersInTopo) {
172  output.insert(output.end(), std::move(clusterout));
173  }
174  }
175 }
176 
178  const std::vector<bool>& seedable,
179  reco::PFClusterCollection& initialPFClusters) const {
180  const auto& recHitFractions = topo.recHitFractions();
181  for (const auto& rhf : recHitFractions) {
182  if (!seedable[rhf.recHitRef().key()])
183  continue;
184  initialPFClusters.push_back(reco::PFCluster());
185  reco::PFCluster& current = initialPFClusters.back();
186  current.addRecHitFraction(rhf);
187  current.setSeed(rhf.recHitRef()->detId());
188  if (_convergencePosCalc) {
189  _convergencePosCalc->calculateAndSetPosition(current);
190  } else {
191  _positionCalc->calculateAndSetPosition(current);
192  }
193  }
194 }
195 
197  const std::vector<bool>& seedable,
198  const unsigned toleranceScaling,
199  const unsigned iter,
200  double diff,
202  if (iter >= _maxIterations) {
203  LOGDRESSED("PFlow2DClusterizerWithTime:growAndStabilizePFClusters")
204  << "reached " << _maxIterations << " iterations, terminated position "
205  << "fit with diff = " << diff;
206  }
207  if (iter >= _maxIterations || diff <= _stoppingTolerance * toleranceScaling)
208  return;
209  // reset the rechits in this cluster, keeping the previous position
210  std::vector<reco::PFCluster::REPPoint> clus_prev_pos;
211  // also calculate and keep the previous time resolution
212  std::vector<double> clus_prev_timeres2;
213 
214  for (auto& cluster : clusters) {
215  const reco::PFCluster::REPPoint& repp = cluster.positionREP();
216  clus_prev_pos.emplace_back(repp.rho(), repp.eta(), repp.phi());
217  if (_convergencePosCalc) {
218  if (clusters.size() == 1 && _allCellsPosCalc) {
219  _allCellsPosCalc->calculateAndSetPosition(cluster);
220  } else {
221  _positionCalc->calculateAndSetPosition(cluster);
222  }
223  }
224  double resCluster2;
226  clusterTimeResolutionFromSeed(cluster, resCluster2);
227  else
228  clusterTimeResolution(cluster, resCluster2);
229  clus_prev_timeres2.push_back(resCluster2);
230  cluster.resetHitsAndFractions();
231  }
232  // loop over topo cluster and grow current PFCluster hypothesis
233  std::vector<double> dist2, frac;
234 
235  // Store chi2 values and nhits to calculate chi2 prob. inline
236  std::vector<double> clus_chi2;
237  std::vector<size_t> clus_chi2_nhits;
238 
239  double fractot = 0;
240  for (const reco::PFRecHitFraction& rhf : topo.recHitFractions()) {
241  const reco::PFRecHitRef& refhit = rhf.recHitRef();
242  int cell_layer = (int)refhit->layer();
243  if (cell_layer == PFLayer::HCAL_BARREL2 && std::abs(refhit->positionREP().eta()) > 0.34) {
244  cell_layer *= 100;
245  }
246  const double recHitEnergyNorm = _recHitEnergyNorms.find(cell_layer)->second;
247  math::XYZPoint topocellpos_xyz(refhit->position());
248  dist2.clear();
249  frac.clear();
250  fractot = 0;
251 
252  // add rechits to clusters, calculating fraction based on distance
253  // need position in vector to get cluster time resolution
254  for (size_t iCluster = 0; iCluster < clusters.size(); ++iCluster) {
255  reco::PFCluster& cluster = clusters[iCluster];
256  const math::XYZPoint& clusterpos_xyz = cluster.position();
257  const math::XYZVector deltav = clusterpos_xyz - topocellpos_xyz;
258  double d2 = deltav.Mag2() / _showerSigma2;
259 
260  double d2time = dist2Time(cluster, refhit, cell_layer, clus_prev_timeres2[iCluster]);
261  d2 += d2time;
262 
263  if (_minChi2Prob > 0. && !passChi2Prob(iCluster, d2time, clus_chi2, clus_chi2_nhits))
264  d2 = 999.;
265 
266  dist2.emplace_back(d2);
267 
268  if (d2 > 100) {
269  LOGDRESSED("PFlow2DClusterizerWithTime:growAndStabilizePFClusters")
270  << "Warning! :: pfcluster-topocell distance is too large! d= " << d2;
271  }
272  // fraction assignment logic
273  double fraction;
274  if (refhit->detId() == cluster.seed() && _excludeOtherSeeds) {
275  fraction = 1.0;
276  } else if (seedable[refhit.key()] && _excludeOtherSeeds) {
277  fraction = 0.0;
278  } else {
279  fraction = cluster.energy() / recHitEnergyNorm * vdt::fast_expf(-0.5 * d2);
280  }
281  fractot += fraction;
282  frac.emplace_back(fraction);
283  }
284  for (unsigned i = 0; i < clusters.size(); ++i) {
285  if (fractot > _minFracTot || (refhit->detId() == clusters[i].seed() && fractot > 0.0)) {
286  frac[i] /= fractot;
287  } else {
288  continue;
289  }
290  // if the fraction has been set to 0, the cell
291  // is now added to the cluster - careful ! (PJ, 19/07/08)
292  // BUT KEEP ONLY CLOSE CELLS OTHERWISE MEMORY JUST EXPLOSES
293  // (PJ, 15/09/08 <- similar to what existed before the
294  // previous bug fix, but keeps the close seeds inside,
295  // even if their fraction was set to zero.)
296  // Also add a protection to keep the seed in the cluster
297  // when the latter gets far from the former. These cases
298  // (about 1% of the clusters) need to be studied, as
299  // they create fake photons, in general.
300  // (PJ, 16/09/08)
301  if (dist2[i] < 100.0 || frac[i] > 0.9999) {
302  clusters[i].addRecHitFraction(reco::PFRecHitFraction(refhit, frac[i]));
303  }
304  }
305  }
306  // recalculate positions and calculate convergence parameter
307  double diff2 = 0.0;
308  for (unsigned i = 0; i < clusters.size(); ++i) {
309  if (_convergencePosCalc) {
310  _convergencePosCalc->calculateAndSetPosition(clusters[i]);
311  } else {
312  if (clusters.size() == 1 && _allCellsPosCalc) {
313  _allCellsPosCalc->calculateAndSetPosition(clusters[i]);
314  } else {
315  _positionCalc->calculateAndSetPosition(clusters[i]);
316  }
317  }
318  const double delta2 = reco::deltaR2(clusters[i].positionREP(), clus_prev_pos[i]);
319  if (delta2 > diff2)
320  diff2 = delta2;
321  }
322  diff = std::sqrt(diff2);
323  dist2.clear();
324  frac.clear();
325  clus_prev_pos.clear(); // avoid badness
326  clus_chi2.clear();
327  clus_chi2_nhits.clear();
328  clus_prev_timeres2.clear();
329  growPFClusters(topo, seedable, toleranceScaling, iter + 1, diff, clusters);
330 }
331 
333  for (auto& cluster : clusters) {
334  cluster.pruneUsing([&](const reco::PFRecHitFraction& rhf) { return rhf.fraction() > _minFractionToKeep; });
335  }
336 }
337 
339  clusterRes2 = 10000.;
340  for (auto& rhf : cluster.recHitFractions()) {
341  const reco::PFRecHit& rh = *(rhf.recHitRef());
342  if (rh.detId() == cluster.seed()) {
343  cluster.setTime(rh.time());
344  bool isBarrel = (rh.layer() == PFLayer::HCAL_BARREL1 || rh.layer() == PFLayer::HCAL_BARREL2 ||
345  rh.layer() == PFLayer::ECAL_BARREL);
346  if (isBarrel)
347  clusterRes2 = _timeResolutionCalcBarrel->timeResolution2(rh.energy());
348  else
349  clusterRes2 = _timeResolutionCalcEndcap->timeResolution2(rh.energy());
350  cluster.setTimeError(std::sqrt(float(clusterRes2)));
351  }
352  }
353 }
354 
355 void PFlow2DClusterizerWithTime::clusterTimeResolution(reco::PFCluster& cluster, double& clusterRes2) const {
356  double sumTimeSigma2 = 0.;
357  double sumSigma2 = 0.;
358 
359  for (auto& rhf : cluster.recHitFractions()) {
360  const reco::PFRecHit& rh = *(rhf.recHitRef());
361  const double rhf_f = rhf.fraction();
362 
363  if (rhf_f == 0.)
364  continue;
365 
366  bool isBarrel = (rh.layer() == PFLayer::HCAL_BARREL1 || rh.layer() == PFLayer::HCAL_BARREL2 ||
367  rh.layer() == PFLayer::ECAL_BARREL);
368  double res2 = 10000.;
369  if (isBarrel)
370  res2 = _timeResolutionCalcBarrel->timeResolution2(rh.energy());
371  else
372  res2 = _timeResolutionCalcEndcap->timeResolution2(rh.energy());
373 
374  sumTimeSigma2 += rhf_f * rh.time() / res2;
375  sumSigma2 += rhf_f / res2;
376  }
377  if (sumSigma2 > 0.) {
378  clusterRes2 = 1. / sumSigma2;
379  cluster.setTime(sumTimeSigma2 / sumSigma2);
380  cluster.setTimeError(std::sqrt(float(clusterRes2)));
381  } else {
382  clusterRes2 = 999999.;
383  }
384 }
385 
387  const reco::PFRecHitRef& refhit,
388  int cell_layer,
389  double prev_timeres2) const {
390  const double deltaT = cluster.time() - refhit->time();
391  const double t2 = deltaT * deltaT;
392  double res2 = 100.;
393 
394  if (cell_layer == PFLayer::HCAL_BARREL1 || cell_layer == PFLayer::HCAL_BARREL2 ||
395  cell_layer == PFLayer::ECAL_BARREL) {
397  const double resCluster2 = prev_timeres2;
398  res2 = resCluster2 + _timeResolutionCalcBarrel->timeResolution2(refhit->energy());
399  } else {
400  return t2 / _timeSigma_eb;
401  }
402  } else if (cell_layer == PFLayer::HCAL_ENDCAP || cell_layer == PFLayer::HF_EM || cell_layer == PFLayer::HF_HAD ||
403  cell_layer == PFLayer::ECAL_ENDCAP) {
405  const double resCluster2 = prev_timeres2;
406  res2 = resCluster2 + _timeResolutionCalcEndcap->timeResolution2(refhit->energy());
407  } else {
408  return t2 / _timeSigma_ee;
409  }
410  }
411 
412  double distTime2 = t2 / res2;
413  if (distTime2 > _maxNSigmaTime)
414  return 999.; // reject hit
415 
416  return distTime2;
417 }
418 
420  double dist2,
421  std::vector<double>& clus_chi2,
422  std::vector<size_t>& clus_chi2_nhits) const {
423  if (iCluster >= clus_chi2.size()) { // first hit
424  clus_chi2.push_back(dist2);
425  clus_chi2_nhits.push_back(1);
426  return true;
427  } else {
428  double chi2 = clus_chi2[iCluster];
429  size_t nhitsCluster = clus_chi2_nhits[iCluster];
430  chi2 += dist2;
431  if (TMath::Prob(chi2, nhitsCluster) >= _minChi2Prob) {
432  clus_chi2[iCluster] = chi2;
433  clus_chi2_nhits[iCluster] = nhitsCluster + 1;
434  return true;
435  }
436  }
437  return false;
438 }
const math::XYZPoint & position() const
cluster centroid position
Definition: CaloCluster.h:154
void update(const edm::EventSetup &es) override
T getParameter(std::string const &) const
Definition: ParameterSet.h:303
void growPFClusters(const reco::PFCluster &, const std::vector< bool > &, const unsigned toleranceScaling, const unsigned iter, double dist, reco::PFClusterCollection &) const
Particle flow cluster, see clustering algorithm in PFClusterAlgo.
Definition: PFCluster.h:42
std::unique_ptr< PFCPositionCalculatorBase > _allCellsPosCalc
void clusterTimeResolution(reco::PFCluster &cluster, double &res) const
std::unique_ptr< PosCalc > _positionCalc
DetId seed() const
return DetId of seed
Definition: CaloCluster.h:219
const std::unordered_map< std::string, int > _layerMap
ParameterSet const & getParameterSet(std::string const &) const
void setTime(float time, float timeError=0)
Definition: PFCluster.h:84
PFLayer::Layer layer() const
rechit layer
Definition: PFRecHit.h:96
Fraction of a PFRecHit (rechits can be shared between several PFCluster&#39;s)
const std::vector< reco::PFRecHitFraction > & recHitFractions() const
vector of rechit fractions
Definition: PFCluster.h:65
#define LOGDRESSED(x)
float time() const
timing for cleaned hits
Definition: PFRecHit.h:102
~PFlow2DClusterizerWithTime() override=default
key_type key() const
Accessor for product key.
Definition: Ref.h:250
Definition: Electron.h:6
static std::string const input
Definition: EdmProvDump.cc:47
void setSeed(const DetId &id)
Definition: CaloCluster.h:146
float time() const
Definition: PFCluster.h:77
unsigned detId() const
rechit detId
Definition: PFRecHit.h:93
Particle flow rechit (rechit + geometry and topology information). See clustering algorithm in PFClus...
Definition: PFRecHit.h:31
T sqrt(T t)
Definition: SSEVec.h:19
double energy() const
cluster energy
Definition: PFCluster.h:74
Abs< T >::type abs(const T &t)
Definition: Abs.h:22
void seedPFClustersFromTopo(const reco::PFCluster &, const std::vector< bool > &, reco::PFClusterCollection &) const
PFlow2DClusterizerWithTime B2DGPF
void setTimeError(float timeError)
Definition: PFCluster.h:88
constexpr auto deltaR2(const T1 &t1, const T2 &t2) -> decltype(t1.eta())
Definition: deltaR.h:16
B2DGPF & operator=(const B2DGPF &)=delete
std::unique_ptr< CaloRecHitResolutionProvider > _timeResolutionCalcBarrel
std::unique_ptr< CaloRecHitResolutionProvider > _timeResolutionCalcEndcap
PFlow2DClusterizerWithTime(const edm::ParameterSet &conf, edm::ConsumesCollector &cc)
XYZVectorD XYZVector
spatial vector with cartesian internal representation
Definition: Vector3D.h:31
XYZPointD XYZPoint
point in space with cartesian internal representation
Definition: Point3D.h:12
void addRecHitFraction(const reco::PFRecHitFraction &frac)
add a given fraction of the rechit
Definition: PFCluster.cc:33
float energy() const
rechit energy
Definition: PFRecHit.h:99
double dist2Time(const reco::PFCluster &, const reco::PFRecHitRef &, int cell_layer, double prev_timeres2) const
void clusterTimeResolutionFromSeed(reco::PFCluster &cluster, double &res) const
float fast_expf(float x)
ROOT::Math::PositionVector3D< ROOT::Math::CylindricalEta3D< double > > REPPoint
Definition: PFCluster.h:48
std::vector< PFCluster > PFClusterCollection
collection of PFCluster objects
Definition: PFClusterFwd.h:9
void prunePFClusters(reco::PFClusterCollection &) const
std::unique_ptr< PFCPositionCalculatorBase > _convergencePosCalc
#define DEFINE_EDM_PLUGIN(factory, type, name)
void buildClusters(const reco::PFClusterCollection &, const std::vector< bool > &, reco::PFClusterCollection &outclus) override
#define get
Power< A, B >::type pow(const A &a, const B &b)
Definition: Power.h:29
bool passChi2Prob(size_t iCluster, double dist2, std::vector< double > &clus_chi2, std::vector< size_t > &clus_chi2_nhits) const
def move(src, dest)
Definition: eostools.py:511
std::unordered_map< int, double > _recHitEnergyNorms