CMS 3D CMS Logo

CandViewRefRandomSelector.cc
Go to the documentation of this file.
1 /*
2  * CandViewRefRandomSelector
3  *
4  * Author: Evan K. Friis (UC Davis)
5  *
6  * Takes a collection of objects inheriting from Candidates and returns up to
7  * N=<choose> candidates. The N output elements are selected randomly. If
8  * the collection contains N or fewer elements, the entire collection is
9  * returned.
10  *
11  */
12 
13 #include <vector>
14 
19 
22 
23 #include "TRandom3.h"
24 
26  public:
28  bool filter(edm::Event&, const edm::EventSetup&) override;
29  private:
31  unsigned int choose_;
32  unsigned int seed_;
33  bool filter_;
34  TRandom3 randy_;
35 };
36 
38  const edm::ParameterSet &pset) {
39  src_ = pset.getParameter<edm::InputTag>("src");
40  choose_ = pset.getParameter<unsigned int>("choose");
41  filter_ = pset.getParameter<bool>("filter");
42  seed_ = pset.exists("seed") ? pset.getParameter<unsigned int>("seed") : 123;
43  randy_ = TRandom3(seed_);
44  produces<reco::CandidateBaseRefVector>();
45 }
46 
48  const edm::EventSetup& es) {
50  evt.getByLabel(src_, cands);
51  auto output = std::make_unique<reco::CandidateBaseRefVector>(cands);
52  // If we don't have enough elements to select, just copy what we have
53  if (cands->size() <= choose_) {
54  for (size_t i = 0; i < cands->size(); ++i)
55  output->push_back(cands->refAt(i));
56  } else {
57  for (size_t i = 0; i < cands->size() && output->size() < choose_; ++i) {
58  // based on http://stackoverflow.com/questions/48087/
59  // select-a-random-n-elements-from-listt-in-c/48089#48089
60  double selectionProb =
61  (choose_ - output->size())*1.0/(cands->size() - i);
62  // throw a number to see if we select this element
63  if (randy_.Rndm() < selectionProb)
64  output->push_back(cands->refAt(i));
65  }
66  }
67  size_t outputSize = output->size();
68  evt.put(std::move(output));
69  return ( !filter_ || outputSize );
70 }
71 
T getParameter(std::string const &) const
OrphanHandle< PROD > put(std::unique_ptr< PROD > product)
Put a new product.
Definition: Event.h:127
#define DEFINE_FWK_MODULE(type)
Definition: MakerMacros.h:17
bool exists(std::string const &parameterName) const
checks if a parameter exists
bool getByLabel(InputTag const &tag, Handle< PROD > &result) const
Definition: Event.h:464
CandViewRefRandomSelector(const edm::ParameterSet &pset)
def move(src, dest)
Definition: eostools.py:510
bool filter(edm::Event &, const edm::EventSetup &) override