CMS 3D CMS Logo

TracksterLinksProducer.cc
Go to the documentation of this file.
1 // Author: Felice Pantaleo, Wahid Redjeb (CERN) - felice.pantaleo@cern.ch, wahid.redjeb@cern.ch
2 // Date: 12/2023
3 #include <memory> // unique_ptr
16 
18 
23 
29 
33 
36 
39 
43 
46 
47 #include "TrackstersPCA.h"
48 
49 using namespace ticl;
51 
52 class TracksterLinksProducer : public edm::stream::EDProducer<edm::GlobalCache<ONNXRuntime>> {
53 public:
54  explicit TracksterLinksProducer(const edm::ParameterSet &ps, const ONNXRuntime *);
55  ~TracksterLinksProducer() override {};
56  void produce(edm::Event &, const edm::EventSetup &) override;
57  static void fillDescriptions(edm::ConfigurationDescriptions &descriptions);
58 
59  void beginRun(edm::Run const &iEvent, edm::EventSetup const &es) override;
60  static std::unique_ptr<ONNXRuntime> initializeGlobalCache(const edm::ParameterSet &iConfig);
61  static void globalEndJob(const ONNXRuntime *);
62 
63 private:
64  void printTrackstersDebug(const std::vector<Trackster> &, const char *label) const;
65  void dumpTrackster(const Trackster &) const;
66 
67  std::unique_ptr<TracksterLinkingAlgoBase> linkingAlgo_;
69 
70  std::vector<edm::EDGetTokenT<std::vector<Trackster>>> tracksters_tokens_;
73 
74  const bool regressionAndPid_;
75  std::unique_ptr<TracksterInferenceAlgoBase> inferenceAlgo_;
76 
77  std::vector<edm::EDGetTokenT<std::vector<float>>> original_masks_tokens_;
78 
82 
88 };
89 
91  : algoType_(ps.getParameter<edm::ParameterSet>("linkingPSet").getParameter<std::string>("type")),
92  clusters_token_(consumes<std::vector<reco::CaloCluster>>(ps.getParameter<edm::InputTag>("layer_clusters"))),
93  clustersTime_token_(
94  consumes<edm::ValueMap<std::pair<float, float>>>(ps.getParameter<edm::InputTag>("layer_clustersTime"))),
95  regressionAndPid_(ps.getParameter<bool>("regressionAndPid")),
96  geometry_token_(esConsumes<CaloGeometry, CaloGeometryRecord, edm::Transition::BeginRun>()),
97  detector_(ps.getParameter<std::string>("detector")),
98  propName_(ps.getParameter<std::string>("propagator")),
99  bfield_token_(esConsumes<MagneticField, IdealMagneticFieldRecord, edm::Transition::BeginRun>()),
100  propagator_token_(
101  esConsumes<Propagator, TrackingComponentsRecord, edm::Transition::BeginRun>(edm::ESInputTag("", propName_))) {
102  // Loop over the edm::VInputTag and append the token to tracksters_tokens_
103  for (auto const &tag : ps.getParameter<std::vector<edm::InputTag>>("tracksters_collections")) {
104  tracksters_tokens_.emplace_back(consumes<std::vector<Trackster>>(tag));
105  }
106  //Loop over the edm::VInputTag of masks and append the token to original_masks_tokens_
107  for (auto const &tag : ps.getParameter<std::vector<edm::InputTag>>("original_masks")) {
108  original_masks_tokens_.emplace_back(consumes<std::vector<float>>(tag));
109  }
110  // Initialize inference algorithm using the factory
111  std::string inferencePlugin = ps.getParameter<std::string>("inferenceAlgo");
112  edm::ParameterSet inferencePSet = ps.getParameter<edm::ParameterSet>("pluginInferenceAlgo" + inferencePlugin);
113  inferenceAlgo_ = std::unique_ptr<TracksterInferenceAlgoBase>(
114  TracksterInferenceAlgoFactory::get()->create(inferencePlugin, inferencePSet));
115 
116  // New trackster collection after linking
117  produces<std::vector<Trackster>>();
118 
119  // Links
120  produces<std::vector<std::vector<unsigned int>>>();
121  produces<std::vector<std::vector<unsigned int>>>("linkedTracksterIdToInputTracksterId");
122  // LayerClusters Mask
123  produces<std::vector<float>>();
124 
125  auto linkingPSet = ps.getParameter<edm::ParameterSet>("linkingPSet");
126 
127  if (algoType_ == "Skeletons") {
128  std::string detectorName_ = (detector_ == "HFNose") ? "HGCalHFNoseSensitive" : "HGCalEESensitive";
129  hdc_token_ = esConsumes<HGCalDDDConstants, IdealGeometryRecord, edm::Transition::BeginRun>(
130  edm::ESInputTag("", detectorName_));
131  }
132 
133  linkingAlgo_ = TracksterLinkingPluginFactory::get()->create(algoType_, linkingPSet, consumesCollector(), onnxRuntime);
134 }
135 
136 std::unique_ptr<ONNXRuntime> TracksterLinksProducer::initializeGlobalCache(const edm::ParameterSet &iConfig) {
137  auto const &pluginPset = iConfig.getParameter<edm::ParameterSet>("linkingPSet");
138  if (pluginPset.exists("onnxModelPath"))
139  return std::make_unique<ONNXRuntime>(pluginPset.getParameter<edm::FileInPath>("onnxModelPath").fullPath());
140  else
141  return std::unique_ptr<ONNXRuntime>(nullptr);
142 }
143 
145 
147  if (algoType_ == "Skeletons") {
149  hgcons_ = hdc.product();
150  }
151 
154 
157 
158  linkingAlgo_->initialize(hgcons_, rhtools_, bfield, propagator);
159 };
160 
162  auto e_over_h = (t.raw_em_pt() / ((t.raw_pt() - t.raw_em_pt()) != 0. ? (t.raw_pt() - t.raw_em_pt()) : 1.));
163  LogDebug("TracksterLinksProducer")
164  << "\nTrackster raw_pt: " << t.raw_pt() << " raw_em_pt: " << t.raw_em_pt() << " eoh: " << e_over_h
165  << " barycenter: " << t.barycenter() << " eta,phi (baricenter): " << t.barycenter().eta() << ", "
166  << t.barycenter().phi() << " eta,phi (eigen): " << t.eigenvectors(0).eta() << ", " << t.eigenvectors(0).phi()
167  << " pt(eigen): " << std::sqrt(t.eigenvectors(0).Unit().perp2()) * t.raw_energy() << " seedID: " << t.seedID()
168  << " seedIndex: " << t.seedIndex() << " size: " << t.vertices().size() << " average usage: "
169  << (std::accumulate(std::begin(t.vertex_multiplicity()), std::end(t.vertex_multiplicity()), 0.) /
170  (float)t.vertex_multiplicity().size())
171  << " raw_energy: " << t.raw_energy() << " regressed energy: " << t.regressed_energy()
172  << " probs(ga/e/mu/np/cp/nh/am/unk): ";
173  for (auto const &p : t.id_probabilities()) {
174  LogDebug("TracksterLinksProducer") << std::fixed << p << " ";
175  }
176  LogDebug("TracksterLinksProducer") << " sigmas: ";
177  for (auto const &s : t.sigmas()) {
178  LogDebug("TracksterLinksProducer") << s << " ";
179  }
180  LogDebug("TracksterLinksProducer") << std::endl;
181 }
182 
184  linkingAlgo_->setEvent(evt, es);
185 
186  auto resultTracksters = std::make_unique<std::vector<Trackster>>();
187 
188  auto linkedResultTracksters = std::make_unique<std::vector<std::vector<unsigned int>>>();
189 
190  const auto &layerClusters = evt.get(clusters_token_);
191  const auto &layerClustersTimes = evt.get(clustersTime_token_);
192 
193  // loop over the original_masks_tokens_ and get the original masks collections and multiply them
194  // to get the global mask
195  std::vector<float> original_global_mask(layerClusters.size(), 1.f);
196  for (unsigned int i = 0; i < original_masks_tokens_.size(); ++i) {
197  const auto &tmp_mask = evt.get(original_masks_tokens_[i]);
198  for (unsigned int j = 0; j < tmp_mask.size(); ++j) {
199  original_global_mask[j] *= tmp_mask[j];
200  }
201  }
202 
203  auto resultMask = std::make_unique<std::vector<float>>(original_global_mask);
204 
205  std::vector<edm::Handle<std::vector<Trackster>>> tracksters_h(tracksters_tokens_.size());
206  MultiVectorManager<Trackster> trackstersManager;
207  for (unsigned int i = 0; i < tracksters_tokens_.size(); ++i) {
208  evt.getByToken(tracksters_tokens_[i], tracksters_h[i]);
209  //Fill MultiVectorManager
210  trackstersManager.addVector(*tracksters_h[i]);
211  }
212 
213  // Linking
214  const typename TracksterLinkingAlgoBase::Inputs input(evt, es, layerClusters, layerClustersTimes, trackstersManager);
215  auto linkedTracksterIdToInputTracksterId = std::make_unique<std::vector<std::vector<unsigned int>>>();
216 
217  // LinkTracksters will produce a vector of vector of indices of tracksters that:
218  // 1) are linked together if more than one
219  // 2) are isolated if only one
220  // Result tracksters contains the final version of the trackster collection
221  // linkedTrackstersToInputTrackstersMap contains the mapping between the linked tracksters and the input tracksters
222  linkingAlgo_->linkTracksters(input, *resultTracksters, *linkedResultTracksters, *linkedTracksterIdToInputTracksterId);
223 
224  // Now we need to remove the tracksters that are not linked
225  // We need to emplace_back in the resultTracksters only the tracksters that are linked
226 
227  for (auto const &resultTrackster : *resultTracksters) {
228  for (auto const &clusterIndex : resultTrackster.vertices()) {
229  (*resultMask)[clusterIndex] = 0.f;
230  }
231  }
232 
233  if (regressionAndPid_) {
234  // Run inference algorithm
235  inferenceAlgo_->inputData(layerClusters, *resultTracksters);
236  inferenceAlgo_->runInference(
237  *resultTracksters); //option to use "Linking" instead of "CLU3D"/"energyAndPid" instead of "PID"
238  }
239 
240  assignPCAtoTracksters(*resultTracksters,
242  layerClustersTimes,
244  rhtools_,
245  true);
246 
247  evt.put(std::move(linkedResultTracksters));
248  evt.put(std::move(resultMask));
249  evt.put(std::move(resultTracksters));
250  evt.put(std::move(linkedTracksterIdToInputTracksterId), "linkedTracksterIdToInputTracksterId");
251 }
252 
253 void TracksterLinksProducer::printTrackstersDebug(const std::vector<Trackster> &tracksters, const char *label) const {
254  int counter = 0;
255  LogDebug("TracksterLinksProducer").log([&](auto &log) {
256  for (auto const &t : tracksters) {
257  log << counter++ << " TracksterLinksProducer (" << label << ") obj barycenter: " << t.barycenter()
258  << " eta,phi (baricenter): " << t.barycenter().eta() << ", " << t.barycenter().phi()
259  << " eta,phi (eigen): " << t.eigenvectors(0).eta() << ", " << t.eigenvectors(0).phi()
260  << " pt(eigen): " << std::sqrt(t.eigenvectors(0).Unit().perp2()) * t.raw_energy() << " seedID: " << t.seedID()
261  << " seedIndex: " << t.seedIndex() << " size: " << t.vertices().size() << " average usage: "
262  << (std::accumulate(std::begin(t.vertex_multiplicity()), std::end(t.vertex_multiplicity()), 0.) /
263  (float)t.vertex_multiplicity().size())
264  << " raw_energy: " << t.raw_energy() << " regressed energy: " << t.regressed_energy()
265  << " probs(ga/e/mu/np/cp/nh/am/unk): ";
266  for (auto const &p : t.id_probabilities()) {
267  log << std::fixed << p << " ";
268  }
269  log << " sigmas: ";
270  for (auto const &s : t.sigmas()) {
271  log << s << " ";
272  }
273  log << "\n";
274  }
275  });
276 }
277 
280  edm::ParameterSetDescription linkingDesc;
281  linkingDesc.addNode(edm::PluginDescription<TracksterLinkingPluginFactory>("type", "Skeletons", true));
282  // Inference Plugins
283  edm::ParameterSetDescription inferenceDesc;
284  inferenceDesc.addNode(edm::PluginDescription<TracksterInferenceAlgoFactory>("type", "TracksterInferenceByDNN", true));
285  desc.add<edm::ParameterSetDescription>("pluginInferenceAlgoTracksterInferenceByDNN", inferenceDesc);
286 
287  edm::ParameterSetDescription inferenceDescCNNv4;
288  inferenceDescCNNv4.addNode(
289  edm::PluginDescription<TracksterInferenceAlgoFactory>("type", "TracksterInferenceByCNNv4", true));
290  desc.add<edm::ParameterSetDescription>("pluginInferenceAlgoTracksterInferenceByCNNv4", inferenceDescCNNv4);
291 
292  desc.add<edm::ParameterSetDescription>("linkingPSet", linkingDesc);
293  desc.add<std::vector<edm::InputTag>>("tracksters_collections", {edm::InputTag("ticlTrackstersCLUE3DHigh")});
294  desc.add<std::vector<edm::InputTag>>("original_masks",
295  {edm::InputTag("hgcalMergeLayerClusters", "InitialLayerClustersMask")});
296  desc.add<edm::InputTag>("layer_clusters", edm::InputTag("hgcalMergeLayerClusters"));
297  desc.add<edm::InputTag>("layer_clustersTime", edm::InputTag("hgcalMergeLayerClusters", "timeLayerCluster"));
298  desc.add<bool>("regressionAndPid", false);
299  desc.add<std::string>("detector", "HGCAL");
300  desc.add<std::string>("propagator", "PropagatorWithMaterial");
301  desc.add<std::string>("inferenceAlgo", "TracksterInferenceByDNN");
302  descriptions.add("tracksterLinksProducer", desc);
303 }
304 
const HGCalDDDConstants * hgcons_
static void fillDescriptions(edm::ConfigurationDescriptions &descriptions)
ESGetTokenH3DDVariant esConsumes(std::string const &Record, edm::ConsumesCollector &)
Definition: DeDxTools.cc:283
T getParameter(std::string const &) const
Definition: ParameterSet.h:307
OrphanHandle< PROD > put(std::unique_ptr< PROD > product)
Put a new product.
Definition: Event.h:133
std::unique_ptr< TracksterInferenceAlgoBase > inferenceAlgo_
void produce(edm::Event &, const edm::EventSetup &) override
bool get(ProductID const &oid, Handle< PROD > &result) const
Definition: Event.h:344
std::string fullPath() const
Definition: FileInPath.cc:161
const edm::ESGetToken< MagneticField, IdealMagneticFieldRecord > bfield_token_
std::vector< edm::EDGetTokenT< std::vector< float > > > original_masks_tokens_
static void globalEndJob(const ONNXRuntime *)
TracksterLinksProducer(const edm::ParameterSet &ps, const ONNXRuntime *)
ParameterDescriptionNode * addNode(ParameterDescriptionNode const &node)
void assignPCAtoTracksters(std::vector< Trackster > &tracksters, const std::vector< reco::CaloCluster > &layerClusters, const edm::ValueMap< std::pair< float, float >> &layerClustersTime, double z_limit_em, hgcal::RecHitTools const &rhTools, bool computeLocalTime=false, bool energyWeight=true, bool clean=false, int minLayer=10, int maxLayer=10)
bool getByToken(EDGetToken token, Handle< PROD > &result) const
Definition: Event.h:526
std::unique_ptr< TracksterLinkingAlgoBase > linkingAlgo_
const edm::EDGetTokenT< std::vector< reco::CaloCluster > > clusters_token_
static std::string const input
Definition: EdmProvDump.cc:50
char const * label
int iEvent
Definition: GenABIO.cc:224
T const * product() const
Definition: ESHandle.h:86
T sqrt(T t)
Definition: SSEVec.h:23
const edm::ESGetToken< CaloGeometry, CaloGeometryRecord > geometry_token_
Transition
Definition: Transition.h:12
#define DEFINE_FWK_MODULE(type)
Definition: MakerMacros.h:16
static std::unique_ptr< ONNXRuntime > initializeGlobalCache(const edm::ParameterSet &iConfig)
ESHandle< T > getHandle(const ESGetToken< T, R > &iToken) const
Definition: EventSetup.h:130
void printTrackstersDebug(const std::vector< Trackster > &, const char *label) const
static void fillDescriptions(edm::ConfigurationDescriptions &descriptions)
std::vector< edm::EDGetTokenT< std::vector< Trackster > > > tracksters_tokens_
void add(std::string const &label, ParameterSetDescription const &psetDescription)
GlobalPoint getPositionLayer(int layer, bool nose=false) const
Definition: RecHitTools.cc:152
void dumpTrackster(const Trackster &) const
void setGeometry(CaloGeometry const &)
Definition: RecHitTools.cc:79
fixed size matrix
HLT enums.
Definition: Common.h:10
edm::ESGetToken< HGCalDDDConstants, IdealGeometryRecord > hdc_token_
#define get
const edm::ESGetToken< Propagator, TrackingComponentsRecord > propagator_token_
void beginRun(edm::Run const &iEvent, edm::EventSetup const &es) override
const edm::EDGetTokenT< edm::ValueMap< std::pair< float, float > > > clustersTime_token_
def move(src, dest)
Definition: eostools.py:511
unsigned int lastLayerEE(bool nose=false) const
Definition: RecHitTools.h:76
Definition: Run.h:45
#define LogDebug(id)