CMS 3D CMS Logo

PFBlockAlgo.cc
Go to the documentation of this file.
5 
6 #include <algorithm>
7 #include <iostream>
8 #include <array>
9 #include <iterator>
10 #include <sstream>
11 #include <type_traits>
12 #include <utility>
13 
14 using namespace std;
15 using namespace reco;
16 
17 #define INIT_ENTRY(name) \
18  { #name, name }
19 
20 namespace {
21  class QuickUnion {
22  std::vector<unsigned> id_;
23  std::vector<unsigned> size_;
24  int count_;
25 
26  public:
27  QuickUnion(const unsigned NBranches) {
28  count_ = NBranches;
29  id_.resize(NBranches);
30  size_.resize(NBranches);
31  for (unsigned i = 0; i < NBranches; ++i) {
32  id_[i] = i;
33  size_[i] = 1;
34  }
35  }
36 
37  int count() const { return count_; }
38 
39  unsigned find(unsigned p) {
40  while (p != id_[p]) {
41  id_[p] = id_[id_[p]];
42  p = id_[p];
43  }
44  return p;
45  }
46 
47  bool connected(unsigned p, unsigned q) { return find(p) == find(q); }
48 
49  void unite(unsigned p, unsigned q) {
50  unsigned rootP = find(p);
51  unsigned rootQ = find(q);
52  id_[p] = q;
53 
54  if (size_[rootP] < size_[rootQ]) {
55  id_[rootP] = rootQ;
56  size_[rootQ] += size_[rootP];
57  } else {
58  id_[rootQ] = rootP;
59  size_[rootP] += size_[rootQ];
60  }
61  --count_;
62  }
63  };
64 } // namespace
65 
66 //for debug only
67 //#define PFLOW_DEBUG
68 
70  : debug_(false),
71  elementTypes_({INIT_ENTRY(PFBlockElement::TRACK),
72  INIT_ENTRY(PFBlockElement::PS1),
73  INIT_ENTRY(PFBlockElement::PS2),
76  INIT_ENTRY(PFBlockElement::GSF),
77  INIT_ENTRY(PFBlockElement::BREM),
78  INIT_ENTRY(PFBlockElement::HFEM),
79  INIT_ENTRY(PFBlockElement::HFHAD),
80  INIT_ENTRY(PFBlockElement::SC),
82  INIT_ENTRY(PFBlockElement::HGCAL)}) {}
83 
84 void PFBlockAlgo::setLinkers(const std::vector<edm::ParameterSet>& confs) {
85  constexpr unsigned rowsize = reco::PFBlockElement::kNBETypes;
86  for (unsigned i = 0; i < rowsize; ++i) {
87  for (unsigned j = 0; j < rowsize; ++j) {
88  linkTestSquare_[i][j] = 0;
89  }
90  }
91  linkTests_.resize(rowsize * rowsize);
92  const std::string prefix("PFBlockElement::");
93  const std::string pfx_kdtree("KDTree");
94  for (const auto& conf : confs) {
95  const std::string& linkerName = conf.getParameter<std::string>("linkerName");
96  const std::string& linkTypeStr = conf.getParameter<std::string>("linkType");
97  size_t split = linkTypeStr.find(':');
98  if (split == std::string::npos) {
99  throw cms::Exception("MalformedLinkType") << "\"" << linkTypeStr << "\" is not a valid link type definition."
100  << " This string should have the form \"linkFrom:linkTo\"";
101  }
102  std::string link1(prefix + linkTypeStr.substr(0, split));
103  std::string link2(prefix + linkTypeStr.substr(split + 1, std::string::npos));
104  if (!(elementTypes_.count(link1) && elementTypes_.count(link2))) {
105  throw cms::Exception("InvalidBlockElementType")
106  << "One of \"" << link1 << "\" or \"" << link2 << "\" are invalid block element types!";
107  }
108  const PFBlockElement::Type type1 = elementTypes_.at(link1);
109  const PFBlockElement::Type type2 = elementTypes_.at(link2);
110  const unsigned index = rowsize * std::max(type1, type2) + std::min(type1, type2);
112  linkTestSquare_[type1][type2] = index;
113  linkTestSquare_[type2][type1] = index;
114  // setup KDtree if requested
115  const bool useKDTree = conf.getParameter<bool>("useKDTree");
116  if (useKDTree) {
117  kdtrees_.emplace_back(KDTreeLinkerFactory::get()->create(pfx_kdtree + linkerName, conf));
118  kdtrees_.back()->setTargetType(std::min(type1, type2));
119  kdtrees_.back()->setFieldType(std::max(type1, type2));
120  } // useKDTree
121  } // loop over confs
122 }
123 
124 void PFBlockAlgo::setImporters(const std::vector<edm::ParameterSet>& confs, edm::ConsumesCollector& sumes) {
125  importers_.reserve(confs.size());
126  for (const auto& conf : confs) {
127  const std::string& importerName = conf.getParameter<std::string>("importerName");
128  importers_.emplace_back(BlockElementImporterFactory::get()->create(importerName, conf, sumes));
129  }
130 }
131 
133 #ifdef PFLOW_DEBUG
134  if (debug_)
135  cout << "~PFBlockAlgo - number of remaining elements: " << elements_.size() << endl;
136 #endif
137 }
138 
140  // Glowinski & Gouzevitch
141  for (const auto& kdtree : kdtrees_) {
142  kdtree->process();
143  }
144  // !Glowinski & Gouzevitch
146  // the blocks have not been passed to the event, and need to be cleared
147  blocks.reserve(elements_.size());
148 
149  QuickUnion qu(elements_.size());
150  const auto elem_size = elements_.size();
151  for (unsigned i = 0; i < elem_size; ++i) {
152  for (unsigned j = i + 1; j < elem_size; ++j) {
153  if (qu.connected(i, j))
154  continue;
155  if (!linkTests_[linkTestSquare_[elements_[i]->type()][elements_[j]->type()]]) {
156  j = ranges_[elements_[j]->type()].second;
157  continue;
158  }
159  auto p1(elements_[i].get()), p2(elements_[j].get());
160  const PFBlockElement::Type type1 = p1->type();
161  const PFBlockElement::Type type2 = p2->type();
162  const unsigned index = linkTestSquare_[type1][type2];
163  if (linkTests_[index]->linkPrefilter(p1, p2)) {
164  const double dist = linkTests_[index]->testLink(p1, p2);
165  // compute linking info if it is possible
166  if (dist > -0.5) {
167  qu.unite(i, j);
168  }
169  }
170  }
171  }
172 
173  std::unordered_multimap<unsigned, unsigned> blocksmap(elements_.size());
174  std::vector<unsigned> keys;
175  keys.reserve(elements_.size());
176  for (unsigned i = 0; i < elements_.size(); ++i) {
177  unsigned key = i;
178  while (key != qu.find(key))
179  key = qu.find(key); // make sure we always find the root node...
180  auto pos = std::lower_bound(keys.begin(), keys.end(), key);
181  if (pos == keys.end() || *pos != key) {
182  keys.insert(pos, key);
183  }
184  blocksmap.emplace(key, i);
185  }
186 
187  for (auto key : keys) {
188  blocks.push_back(reco::PFBlock());
189  auto range = blocksmap.equal_range(key);
190  auto& the_block = blocks.back();
191  ElementList::value_type::pointer p1(elements_[range.first->second].get());
192  the_block.addElement(p1);
193  const unsigned block_size = blocksmap.count(key) + 1;
194  //reserve up to 1M or 8MB; pay rehash cost for more
195  std::unordered_map<std::pair<unsigned int, unsigned int>, double> links(min(1000000u, block_size * block_size));
196  auto itr = range.first;
197  ++itr;
198  for (; itr != range.second; ++itr) {
199  ElementList::value_type::pointer p2(elements_[itr->second].get());
200  const PFBlockElement::Type type1 = p1->type();
201  const PFBlockElement::Type type2 = p2->type();
202  the_block.addElement(p2);
203  const unsigned index = linkTestSquare_[type1][type2];
204  if (nullptr != linkTests_[index]) {
205  const double dist = linkTests_[index]->testLink(p1, p2);
206  links.emplace(std::make_pair(p1->index(), p2->index()), dist);
207  }
208  }
209  packLinks(the_block, links);
210  }
211 
212  elements_.clear();
213 
214  return blocks;
215 }
216 
218  const std::unordered_map<std::pair<unsigned int, unsigned int>, double>& links) const {
219  constexpr unsigned rowsize = reco::PFBlockElement::kNBETypes;
220 
221  const edm::OwnVector<reco::PFBlockElement>& els = block.elements();
222 
223  block.bookLinkData();
224  unsigned elsize = els.size();
225  //First Loop: update all link data
226  for (unsigned i1 = 0; i1 < elsize; ++i1) {
227  for (unsigned i2 = 0; i2 < i1; ++i2) {
228  // no reflexive link
229  //if( i1==i2 ) continue;
230 
231  double dist = -1;
232 
233  bool linked = false;
234 
235  // are these elements already linked ?
236  // this can be optimized
237  const auto link_itr = links.find(std::make_pair(i2, i1));
238  if (link_itr != links.end()) {
239  dist = link_itr->second;
240  linked = true;
241  }
242 
243  if (!linked) {
244  const PFBlockElement::Type type1 = els[i1].type();
245  const PFBlockElement::Type type2 = els[i2].type();
246  const auto minmax = std::minmax(type1, type2);
247  const unsigned index = rowsize * minmax.second + minmax.first;
248  bool bTestLink =
249  (nullptr == linkTests_[index] ? false : linkTests_[index]->linkPrefilter(&(els[i1]), &(els[i2])));
250  if (bTestLink)
251  link(&els[i1], &els[i2], dist);
252  }
253 
254  //loading link data according to link test used: RECHIT
255  //block.setLink( i1, i2, chi2, block.linkData() );
256  block.setLink(i1, i2, dist, block.linkData());
257  }
258  }
259 }
260 
261 inline void PFBlockAlgo::link(const reco::PFBlockElement* el1, const reco::PFBlockElement* el2, double& dist) const {
262  constexpr unsigned rowsize = reco::PFBlockElement::kNBETypes;
263  dist = -1.0;
264  const PFBlockElement::Type type1 = el1->type();
265  const PFBlockElement::Type type2 = el2->type();
266  const unsigned index = rowsize * std::max(type1, type2) + std::min(type1, type2);
267  if (debug_) {
268  std::cout << " PFBlockAlgo links type1 " << type1 << " type2 " << type2 << std::endl;
269  }
270 
271  // index is always checked in the preFilter above, no need to check here
272  dist = linkTests_[index]->testLink(el1, el2);
273 }
274 
276  for (auto& importer : importers_) {
277  importer->updateEventSetup(es);
278  }
279 }
280 
281 // see plugins/importers and plugins/kdtrees
282 // for the definitions of available block element importers
283 // and kdtree preprocessors
285  // import block elements as defined in python configuration
286  ranges_.fill(std::make_pair(0, 0));
287  elements_.clear();
288  for (const auto& importer : importers_) {
289  importer->importToBlock(evt, elements_);
290  }
291 
292  std::sort(elements_.begin(), elements_.end(), [](const auto& a, const auto& b) { return a->type() < b->type(); });
293 
294  // list is now partitioned, so mark the boundaries so we can efficiently skip chunks
295  unsigned current_type = (!elements_.empty() ? elements_[0]->type() : 0);
296  unsigned last_type = (!elements_.empty() ? elements_.back()->type() : 0);
297  ranges_[current_type].first = 0;
298  ranges_[last_type].second = elements_.size() - 1;
299  for (size_t i = 0; i < elements_.size(); ++i) {
300  const auto the_type = elements_[i]->type();
301  if (the_type != current_type) {
302  ranges_[the_type].first = i;
303  ranges_[current_type].second = i - 1;
304  current_type = the_type;
305  }
306  }
307  // -------------- Loop over block elements ---------------------
308 
309  // Here we provide to all KDTree linkers the collections to link.
310  // Glowinski & Gouzevitch
311 
312  for (ElementList::iterator it = elements_.begin(); it != elements_.end(); ++it) {
313  for (const auto& kdtree : kdtrees_) {
314  if ((*it)->type() == kdtree->targetType()) {
315  kdtree->insertTargetElt(it->get());
316  }
317  if ((*it)->type() == kdtree->fieldType()) {
318  kdtree->insertFieldClusterElt(it->get());
319  }
320  }
321  }
322  //std::cout << "(new) imported: " << elements_.size() << " elements!" << std::endl;
323 }
324 
325 std::ostream& operator<<(std::ostream& out, const PFBlockAlgo& a) {
326  if (!out)
327  return out;
328 
329  out << "====== Particle Flow Block Algorithm ======= ";
330  out << endl;
331  out << "number of unassociated elements : " << a.elements_.size() << endl;
332  out << endl;
333 
334  for (auto const& element : a.elements_) {
335  out << "\t" << *element << endl;
336  }
337 
338  return out;
339 }
340 
341 // a little history, ideas we may want to keep around for later
342 /*
343  // Links between the two preshower layers are not used for now - disable
344  case PFBlockLink::PS1andPS2:
345  {
346  PFClusterRef ps1ref = lowEl->clusterRef();
347  PFClusterRef ps2ref = highEl->clusterRef();
348  assert( !ps1ref.isNull() );
349  assert( !ps2ref.isNull() );
350  // PJ - 14-May-09 : A link by rechit is needed here !
351  // dist = testPS1AndPS2( *ps1ref, *ps2ref );
352  dist = -1.;
353  linktest = PFBlock::LINKTEST_RECHIT;
354  break;
355  }
356  case PFBlockLink::TRACKandPS1:
357  case PFBlockLink::TRACKandPS2:
358  {
359  //cout<<"TRACKandPS"<<endl;
360  PFRecTrackRef trackref = lowEl->trackRefPF();
361  PFClusterRef clusterref = highEl->clusterRef();
362  assert( !trackref.isNull() );
363  assert( !clusterref.isNull() );
364  // PJ - 14-May-09 : A link by rechit is needed here !
365  dist = testTrackAndPS( *trackref, *clusterref );
366  linktest = PFBlock::LINKTEST_RECHIT;
367  break;
368  }
369  // GSF Track/Brem Track and preshower cluster links are not used for now - disable
370  case PFBlockLink::PS1andGSF:
371  case PFBlockLink::PS2andGSF:
372  {
373  PFClusterRef psref = lowEl->clusterRef();
374  assert( !psref.isNull() );
375  const reco::PFBlockElementGsfTrack * GsfEl = dynamic_cast<const reco::PFBlockElementGsfTrack*>(highEl);
376  const PFRecTrack * myTrack = &(GsfEl->GsftrackPF());
377  // PJ - 14-May-09 : A link by rechit is needed here !
378  dist = testTrackAndPS( *myTrack, *psref );
379  linktest = PFBlock::LINKTEST_RECHIT;
380  break;
381  }
382  case PFBlockLink::PS1andBREM:
383  case PFBlockLink::PS2andBREM:
384  {
385  PFClusterRef psref = lowEl->clusterRef();
386  assert( !psref.isNull() );
387  const reco::PFBlockElementBrem * BremEl = dynamic_cast<const reco::PFBlockElementBrem*>(highEl);
388  const PFRecTrack * myTrack = &(BremEl->trackPF());
389  // PJ - 14-May-09 : A link by rechit is needed here !
390  dist = testTrackAndPS( *myTrack, *psref );
391  linktest = PFBlock::LINKTEST_RECHIT;
392  break;
393  }
394  */
FastTimerService_cff.range
range
Definition: FastTimerService_cff.py:34
PluginFactory.h
testProducerWithPsetDescEmpty_cfi.i2
i2
Definition: testProducerWithPsetDescEmpty_cfi.py:46
PFBlockAlgo::buildElements
void buildElements(const edm::Event &)
Definition: PFBlockAlgo.cc:284
mps_fire.i
i
Definition: mps_fire.py:428
PFBlockAlgo::debug_
bool debug_
if true, debug printouts activated
Definition: PFBlockAlgo.h:75
funct::false
false
Definition: Factorize.h:29
min
T min(T a, T b)
Definition: MathUtil.h:58
AlCaHLTBitMon_ParallelJobs.p
p
Definition: AlCaHLTBitMon_ParallelJobs.py:153
reco::PFBlock
Block of elements.
Definition: PFBlock.h:26
gather_cfg.cout
cout
Definition: gather_cfg.py:144
pos
Definition: PixelAliasList.h:18
testProducerWithPsetDescEmpty_cfi.i1
i1
Definition: testProducerWithPsetDescEmpty_cfi.py:45
relativeConstraints.keys
keys
Definition: relativeConstraints.py:89
reco
fixed size matrix
Definition: AlignmentAlgorithmBase.h:45
beamerCreator.create
def create(alignables, pedeDump, additionalData, outputFile, config)
Definition: beamerCreator.py:44
spr::find
void find(edm::Handle< EcalRecHitCollection > &hits, DetId thisDet, std::vector< EcalRecHitCollection::const_iterator > &hit, bool debug=false)
Definition: FindCaloHit.cc:19
HLT_FULL_cff.importerName
importerName
Definition: HLT_FULL_cff.py:13607
reco::PFBlockElement::Type
Type
Definition: PFBlockElement.h:30
ECAL
Definition: HCALResponse.h:21
submitPVValidationJobs.split
def split(sequence, size)
Definition: submitPVValidationJobs.py:352
p2
double p2[4]
Definition: TauolaWrapper.h:90
PFBlockAlgo::link
void link(const reco::PFBlockElement *el1, const reco::PFBlockElement *el2, double &dist) const
check whether 2 elements are linked. Returns distance
Definition: PFBlockAlgo.cc:261
submitPVResolutionJobs.count
count
Definition: submitPVResolutionJobs.py:352
PFBlockAlgo::elements_
ElementList elements_
Definition: PFBlockAlgo.h:71
PFBlockAlgo::~PFBlockAlgo
~PFBlockAlgo()
Definition: PFBlockAlgo.cc:132
HCAL
Definition: HCALResponse.h:21
DigiToRawDM_cff.HO
HO
Definition: DigiToRawDM_cff.py:23
b
double b
Definition: hdecay.h:118
PFBlockAlgo::kdtrees_
std::vector< std::unique_ptr< KDTreeLinkerBase > > kdtrees_
Definition: PFBlockAlgo.h:86
AlCaHLTBitMon_QueryRunRegistry.string
string
Definition: AlCaHLTBitMon_QueryRunRegistry.py:256
reco::PFBlockCollection
std::vector< PFBlock > PFBlockCollection
collection of PFBlock objects
Definition: PFBlockFwd.h:10
INIT_ENTRY
#define INIT_ENTRY(name)
Definition: PFBlockAlgo.cc:17
pfDeepBoostedJetPreprocessParams_cfi.lower_bound
lower_bound
Definition: pfDeepBoostedJetPreprocessParams_cfi.py:15
a
double a
Definition: hdecay.h:119
PFBlockAlgo::linkTests_
std::vector< std::unique_ptr< BlockElementLinkerBase > > linkTests_
Definition: PFBlockAlgo.h:83
SiStripPI::max
Definition: SiStripPayloadInspectorHelper.h:169
PFBlockAlgo::elementTypes_
const std::unordered_map< std::string, reco::PFBlockElement::Type > elementTypes_
Definition: PFBlockAlgo.h:82
jetUpdater_cfi.sort
sort
Definition: jetUpdater_cfi.py:29
PFBlockAlgo::linkTestSquare_
unsigned int linkTestSquare_[reco::PFBlockElement::kNBETypes][reco::PFBlockElement::kNBETypes]
Definition: PFBlockAlgo.h:84
gainCalibHelper::gainCalibPI::type
type
Definition: SiPixelGainCalibHelper.h:40
PFBlockAlgo::setImporters
void setImporters(const std::vector< edm::ParameterSet > &, edm::ConsumesCollector &)
Definition: PFBlockAlgo.cc:124
p1
double p1[4]
Definition: TauolaWrapper.h:89
PFBlockAlgo::ranges_
ElementRanges ranges_
Definition: PFBlockAlgo.h:72
submitPVResolutionJobs.q
q
Definition: submitPVResolutionJobs.py:84
groupFilesInBlocks.block
block
Definition: groupFilesInBlocks.py:150
edm::EventSetup
Definition: EventSetup.h:58
PFBlockAlgo.h
PFBlockAlgo
Particle Flow Algorithm.
Definition: PFBlockAlgo.h:34
get
#define get
PFBlockAlgo::findBlocks
reco::PFBlockCollection findBlocks()
build blocks
Definition: PFBlockAlgo.cc:139
PFBlockAlgo::updateEventSetup
void updateEventSetup(const edm::EventSetup &)
Definition: PFBlockAlgo.cc:275
reco::PFBlockElement
Abstract base class for a PFBlock element (track, cluster...)
Definition: PFBlockElement.h:26
PFBlockAlgo::packLinks
void packLinks(reco::PFBlock &block, const std::unordered_map< std::pair< unsigned int, unsigned int >, double > &links) const
Definition: PFBlockAlgo.cc:217
std
Definition: JetResolutionObject.h:76
reco::PFBlockElement::kNBETypes
Definition: PFBlockElement.h:44
Exception
Definition: hltDiff.cc:245
electronStore.links
links
Definition: electronStore.py:149
Exception.h
reco::PFBlockElement::type
Type type() const
Definition: PFBlockElement.h:69
PFBlockAlgo::importers_
std::vector< std::unique_ptr< BlockElementImporterBase > > importers_
Definition: PFBlockAlgo.h:80
AlignmentPI::index
index
Definition: AlignmentPayloadInspectorHelper.h:46
MillePedeFileConverter_cfg.out
out
Definition: MillePedeFileConverter_cfg.py:31
ParameterSet.h
operator<<
std::ostream & operator<<(std::ostream &out, const PFBlockAlgo &a)
Definition: PFBlockAlgo.cc:325
dqmiolumiharvest.j
j
Definition: dqmiolumiharvest.py:66
PFBlockAlgo::PFBlockAlgo
PFBlockAlgo()
Definition: PFBlockAlgo.cc:69
edm::Event
Definition: Event.h:73
crabWrapper.key
key
Definition: crabWrapper.py:19
HLT_FULL_cff.useKDTree
useKDTree
Definition: HLT_FULL_cff.py:13582
edm::OwnVector::size
size_type size() const
Definition: OwnVector.h:300
gather_cfg.blocks
blocks
Definition: gather_cfg.py:90
edm::ConsumesCollector
Definition: ConsumesCollector.h:45
hcallasereventfilter2012_cfi.prefix
prefix
Definition: hcallasereventfilter2012_cfi.py:10
HLT_FULL_cff.linkerName
linkerName
Definition: HLT_FULL_cff.py:13583
edm::OwnVector< reco::PFBlockElement >
PFBlockAlgo::setLinkers
void setLinkers(const std::vector< edm::ParameterSet > &)
Definition: PFBlockAlgo.cc:84