CMS 3D CMS Logo

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