CMS 3D CMS Logo

ProducerKFout.cc
Go to the documentation of this file.
12 
16 
17 #include <string>
18 #include <numeric>
19 
20 using namespace std;
21 using namespace edm;
22 using namespace trackerTFP;
23 using namespace tt;
24 
25 namespace trklet {
26 
37  class ProducerKFout : public stream::EDProducer<> {
38  public:
39  explicit ProducerKFout(const ParameterSet&);
40  ~ProducerKFout() override {}
41 
42  private:
43  void beginRun(const Run&, const EventSetup&) override;
44  void produce(Event&, const EventSetup&) override;
45  void endJob() {}
46 
47  // ED input token of kf stubs
49  // ED input token of kf tracks
51  // ED output token for accepted kfout tracks
53  // ED output token for TTTracks
55  // ED output token for truncated kfout tracks
57  // Setup token
59  // DataFormats token
61  // configuration
63  // helper class to store configurations
64  const Setup* setup_;
65  // helper class to extract structured data from tt::Frames
67  // Bins for dPhi/dZ use to create weight LUT
68  vector<double> dPhiBins_;
69  vector<double> dZBins_;
70 
71  std::unique_ptr<L1TrackQuality> trackQualityModel_;
72  double tqTanlScale_;
73  double tqZ0Scale_;
74  static constexpr double ap_fixed_rescale = 32.0;
75 
76  // For convenience and keeping readable code, accessed many times
79 
80  // Helper function to convert floating value to bin
81  template <typename T>
82  unsigned int digitise(const T& bins, double value, double factor) {
83  unsigned int bin = 0;
84  for (unsigned int i = 0; i < bins.size() - 1; i++) {
85  if (value * factor > bins[i] && value * factor <= bins[i + 1])
86  break;
87  bin++;
88  }
89  return bin;
90  }
91  };
92 
93  ProducerKFout::ProducerKFout(const ParameterSet& iConfig) : iConfig_(iConfig) {
94  const string& labelKF = iConfig.getParameter<string>("LabelKF");
95  const string& branchStubs = iConfig.getParameter<string>("BranchAcceptedStubs");
96  const string& branchTracks = iConfig.getParameter<string>("BranchAcceptedTracks");
97  const string& branchTTTracks = iConfig.getParameter<string>("BranchAcceptedTTTracks");
98  const string& branchLost = iConfig.getParameter<string>("BranchLostTracks");
99  // book in- and output ED products
100  edGetTokenStubs_ = consumes<StreamsStub>(InputTag(labelKF, branchStubs));
101  edGetTokenTracks_ = consumes<StreamsTrack>(InputTag(labelKF, branchTracks));
102  edPutTokenAccepted_ = produces<StreamsTrack>(branchTracks);
103  edPutTokenTTTracks_ = produces<TTTracks>(branchTTTracks);
104  edPutTokenLost_ = produces<StreamsTrack>(branchLost);
105  // book ES products
106  esGetTokenSetup_ = esConsumes<Setup, SetupRcd, Transition::BeginRun>();
107  esGetTokenDataFormats_ = esConsumes<DataFormats, DataFormatsRcd, Transition::BeginRun>();
108  // initial ES products
109  setup_ = nullptr;
110  dataFormats_ = nullptr;
111 
112  trackQualityModel_ = std::make_unique<L1TrackQuality>(iConfig.getParameter<edm::ParameterSet>("TrackQualityPSet"));
113  edm::ParameterSet trackQualityPSset = iConfig.getParameter<edm::ParameterSet>("TrackQualityPSet");
114  tqTanlScale_ = trackQualityPSset.getParameter<double>("tqemu_TanlScale");
115  tqZ0Scale_ = trackQualityPSset.getParameter<double>("tqemu_Z0Scale");
116  }
117 
118  void ProducerKFout::beginRun(const Run& iRun, const EventSetup& iSetup) {
119  // helper class to store configurations
120  setup_ = &iSetup.getData(esGetTokenSetup_);
122  return;
123  // check process history if desired
124  if (iConfig_.getParameter<bool>("CheckHistory"))
126  // helper class to extract structured data from tt::Frames
128 
129  // Calculate 1/dz**2 and 1/dphi**2 bins for v0 and v1 weightings
130  float temp_dphi = 0.0;
131  float temp_dz = 0.0;
132  for (int i = 0;
133  i < pow(2, dataFormats_->width(Variable::dPhi, Process::kfin)) / pow(2, setup_->weightBinFraction());
134  i++) {
135  temp_dphi =
136  pow(dataFormats_->base(Variable::dPhi, Process::kfin) * (i + 1) * pow(2, setup_->weightBinFraction()), -2);
137  temp_dphi = temp_dphi / setup_->dphiTruncation();
138  temp_dphi = std::floor(temp_dphi);
139  dPhiBins_.push_back(temp_dphi * setup_->dphiTruncation());
140  }
141  for (int i = 0; i < pow(2, dataFormats_->width(Variable::dZ, Process::kfin)) / pow(2, setup_->weightBinFraction());
142  i++) {
143  temp_dz =
144  pow(dataFormats_->base(Variable::dZ, Process::kfin) * (i + 1) * pow(2, setup_->weightBinFraction()), -2);
145  temp_dz = temp_dz * setup_->dzTruncation();
146  temp_dz = std::ceil(temp_dz);
147  dZBins_.push_back(temp_dz / setup_->dzTruncation());
148  }
151  }
152 
154  // empty KFout product
157  // read in KF Product and produce KFout product
159  Handle<StreamsStub> handleStubs;
160  iEvent.getByToken<StreamsStub>(edGetTokenStubs_, handleStubs);
161  const StreamsStub& streamsStubs = *handleStubs.product();
162  Handle<StreamsTrack> handleTracks;
163  iEvent.getByToken<StreamsTrack>(edGetTokenTracks_, handleTracks);
164  const StreamsTrack& streamsTracks = *handleTracks.product();
165 
166  // Setup KFout track collection
167  TrackKFOutSAPtrCollection KFoutTracks;
168 
169  // Setup containers for track quality
170  float tempTQMVAPreSig = 0.0;
171  // Due to ap_fixed implementation in CMSSW this 10,5 must be specified at compile time, TODO make this a changeable parameter
172  std::vector<ap_fixed<10, 5>> trackQuality_inputs = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
173 
174  // calculate track quality and fill TTTracks
175  TTTracks ttTracks;
176  int nTracks(0);
177  for (const StreamTrack& stream : streamsTracks)
178  nTracks += accumulate(stream.begin(), stream.end(), 0, [](int sum, const FrameTrack& frame) {
179  return sum + (frame.first.isNonnull() ? 1 : 0);
180  });
181  ttTracks.reserve(nTracks);
182  for (int iLink = 0; iLink < (int)streamsTracks.size(); iLink++) {
183  for (int iTrack = 0; iTrack < (int)streamsTracks[iLink].size(); iTrack++) {
184  const auto& track = streamsTracks[iLink].at(iTrack);
185  TrackKF inTrack(track, dataFormats_);
186 
187  double temp_z0 = inTrack.zT() - ((inTrack.cot() * setup_->chosenRofZ()));
188  // Correction to Phi calcuation depending if +ve/-ve phi sector
189  const double baseSectorCorr = inTrack.sectorPhi() ? -setup_->baseSector() : setup_->baseSector();
190  double temp_phi0 = inTrack.phiT() - ((inTrack.inv2R()) * setup_->hybridChosenRofPhi()) + baseSectorCorr;
191  double temp_tanL = inTrack.cotGlobal();
192 
194  double tempchi2rphi = 0;
195  double tempchi2rz = 0;
196  int temp_nstub = 0;
197  int temp_ninterior = 0;
198  bool counter = false;
199 
200  vector<StubKF> stubs;
201  stubs.reserve(setup_->numLayers());
202  for (int iStub = 0; iStub < setup_->numLayers(); iStub++) {
203  const auto& stub = streamsStubs[setup_->numLayers() * iLink + iStub].at(iTrack);
204  StubKF inStub(stub, dataFormats_, iStub);
205  if (stub.first.isNonnull())
206  stubs.emplace_back(stub, dataFormats_, iStub);
207 
208  if (!stub.first.isNonnull()) {
209  if (counter)
210  temp_ninterior += 1;
211  continue;
212  }
213 
214  counter = true;
215 
216  hitPattern.set(iStub);
217  temp_nstub += 1;
218  double phiSquared = pow(inStub.phi(), 2);
219  double zSquared = pow(inStub.z(), 2);
220 
221  double tempv0 = dPhiBins_[(inStub.dPhi() / (dataFormats_->base(Variable::dPhi, Process::kfin) *
222  pow(2, setup_->weightBinFraction())))];
223  double tempv1 = dZBins_[(
224  inStub.dZ() / (dataFormats_->base(Variable::dZ, Process::kfin) * pow(2, setup_->weightBinFraction())))];
225 
226  double tempRphi = phiSquared * tempv0;
227  double tempRz = zSquared * tempv1;
228 
229  tempchi2rphi += tempRphi;
230  tempchi2rz += tempRz;
231  } // Iterate over track stubs
232 
233  // Create bit vectors for each output, including digitisation of chi2
234  // TODO implement extraMVA, bendChi2, d0
236  TTBV extraMVA(0, TTTrack_TrackWord::TrackBitWidths::kMVAOtherSize, false);
237  TTBV bendChi2(0, TTTrack_TrackWord::TrackBitWidths::kBendChi2Size, false);
238  TTBV chi2rphi(digitise(TTTrack_TrackWord::chi2RPhiBins, tempchi2rphi, (double)setup_->kfoutchi2rphiConv()),
239  TTTrack_TrackWord::TrackBitWidths::kChi2RPhiSize,
240  false);
241  TTBV chi2rz(digitise(TTTrack_TrackWord::chi2RZBins, tempchi2rz, (double)setup_->kfoutchi2rzConv()),
242  TTTrack_TrackWord::TrackBitWidths::kChi2RZSize,
243  false);
244  TTBV d0(0, TTTrack_TrackWord::TrackBitWidths::kD0Size, false);
245  TTBV z0(
246  temp_z0, dataFormats_->base(Variable::zT, Process::kf), TTTrack_TrackWord::TrackBitWidths::kZ0Size, true);
247  TTBV tanL(temp_tanL,
248  dataFormats_->base(Variable::cot, Process::kf),
249  TTTrack_TrackWord::TrackBitWidths::kTanlSize,
250  true);
251  TTBV phi0(temp_phi0,
252  dataFormats_->base(Variable::phiT, Process::kf),
253  TTTrack_TrackWord::TrackBitWidths::kPhiSize,
254  true);
255  TTBV invR(-inTrack.inv2R(),
256  dataFormats_->base(Variable::inv2R, Process::kf),
257  TTTrack_TrackWord::TrackBitWidths::kRinvSize + 1,
258  true);
259  invR.resize(TTTrack_TrackWord::TrackBitWidths::kRinvSize);
260 
261  // conversion to tttrack to calculate bendchi2
262  // temporary fix for MVA1 while bendchi2 not implemented
263  TTTrack temp_tttrack = inTrack.ttTrack(stubs);
264  double tempbendchi2 = temp_tttrack.chi2BendRed();
265 
266  // Create input vector for BDT
267  trackQuality_inputs = {
268  (std::trunc(tanL.val() / tqTanlScale_)) / ap_fixed_rescale,
269  (std::trunc(z0.val() / tqZ0Scale_)) / ap_fixed_rescale,
270  digitise(TTTrack_TrackWord::bendChi2Bins, tempbendchi2, 1.),
271  temp_nstub,
272  temp_ninterior,
275 
276  // Run BDT emulation and package output into 3 bits
277  // output needs sigmoid transformation applied
278  tempTQMVAPreSig = trackQualityModel_->runEmulatedTQ(trackQuality_inputs);
279  TTBV tqMVA(digitise(L1TrackQuality::getTqMVAPreSigBins(), tempTQMVAPreSig, 1.0),
280  TTTrack_TrackWord::TrackBitWidths::kMVAQualitySize,
281  false);
282 
283  // Build 32 bit partial tracks for outputting in 64 bit packets
284  // 12 + 3 + 7 + 3 + 6
285  TTBV partialTrack3((d0 + bendChi2 + hitPattern + tqMVA + extraMVA), partialTrackWordBits_, false);
286  // 16 + 12 + 4
287  TTBV partialTrack2((tanL + z0 + chi2rz), partialTrackWordBits_, false);
288  // 1 + 15 + 12 + 4
289  TTBV partialTrack1((trackValid + invR + phi0 + chi2rphi), partialTrackWordBits_, false);
290 
291  int sortKey = (inTrack.sectorEta() < (int)(setup_->numSectorsEta() / 2)) ? 0 : 1;
292  int nonantId = iLink / setup_->kfNumWorker();
293  // Set correct bit to valid for track valid
294  TrackKFOut temp_track(partialTrack1.set((partialTrackWordBits_ - 1)),
295  partialTrack2,
296  partialTrack3,
297  sortKey,
298  nonantId,
299  track,
300  iTrack,
301  iLink,
302  true);
303  KFoutTracks.push_back(std::make_shared<TrackKFOut>(temp_track));
304 
305  // add MVA to tttrack and add tttrack to collection
306  temp_tttrack.settrkMVA1(1. / (1. + exp(tempTQMVAPreSig)));
307  temp_tttrack.setTrackWordBits();
308  ttTracks.emplace_back(temp_tttrack);
309  } // Iterate over Tracks
310  } // Iterate over Links
311  const OrphanHandle<tt::TTTracks> orphanHandleTTTracks = iEvent.emplace(edPutTokenTTTracks_, std::move(ttTracks));
312 
313  // sort partial KFout tracks into 18 separate links (nonant idx * eta idx) with tttrack ref info
314  // 0th index order: [nonant 0 + negative eta, nonant 0 + positive eta, nonant 1 + negative eta, ...]
315  struct kfoTrack_info {
316  TTBV partialBits;
317  TTTrackRef trackRef;
318  };
319  vector<vector<kfoTrack_info>> sortedPartialTracks(setup_->numRegions() * setup_->tfpNumChannel(),
320  vector<kfoTrack_info>(0));
321  for (int i = 0; i < (int)KFoutTracks.size(); i++) {
322  auto& kfoTrack = KFoutTracks.at(i);
323  if (kfoTrack->dataValid()) {
324  sortedPartialTracks[kfoTrack->nonantId() * setup_->tfpNumChannel() + kfoTrack->sortKey()].push_back(
325  {kfoTrack->PartialTrack1(), TTTrackRef(orphanHandleTTTracks, i)});
326  sortedPartialTracks[kfoTrack->nonantId() * setup_->tfpNumChannel() + kfoTrack->sortKey()].push_back(
327  {kfoTrack->PartialTrack2(), TTTrackRef(orphanHandleTTTracks, i)});
328  sortedPartialTracks[kfoTrack->nonantId() * setup_->tfpNumChannel() + kfoTrack->sortKey()].push_back(
329  {kfoTrack->PartialTrack3(), TTTrackRef(orphanHandleTTTracks, i)});
330  }
331  }
332  // fill remaining tracks allowed on each link (setup_->numFramesIO()) with null info
333  kfoTrack_info nullTrack_info;
334  for (int i = 0; i < (int)sortedPartialTracks.size(); i++) {
335  // will not fill if any additional tracks if already above limit
336  while ((int)sortedPartialTracks.at(i).size() < setup_->numFramesIO() * 2)
337  sortedPartialTracks.at(i).push_back(nullTrack_info);
338  }
339 
340  // combine sorted partial tracks into proper format:
341  // < TTTrackRef A, first 64 A bits >
342  // < TTTrackRef B, last 32 A bits + first 32 B bits >
343  // < TTTrackRef null, last 64 B bits >
344  // ... repeat for next tracks
345  const TTBV nullPartialBits(0, partialTrackWordBits_, false);
346  const TTTrackRef nullTrackRef;
347  int partialFactor = TTBV::S_ / partialTrackWordBits_; //how many partial track words to combine in an output
348  for (int iLink = 0; iLink < (int)sortedPartialTracks.size(); iLink++) {
349  for (int iTrack = 0; iTrack < (int)sortedPartialTracks[iLink].size(); iTrack += partialFactor) {
350  // if a partial track has no pair, pair it with null partial track
351  if (iTrack + 1 == (int)sortedPartialTracks[iLink].size())
352  sortedPartialTracks[iLink].push_back({nullPartialBits, nullTrackRef});
353  // keep TTTrackRef null every third (96 bits / 32 partial bits) output packet
354  TTTrackRef fillTrackRef;
355  if ((iTrack / partialFactor + 1) % (TTTrack_TrackWord::kTrackWordSize / partialTrackWordBits_) != 0)
356  fillTrackRef = sortedPartialTracks[iLink][iTrack + 1].trackRef;
357 
358  // if there are too many output packets, truncate and put remaining outputs in lost collection
359  if (iTrack / partialFactor < setup_->numFramesIO())
360  accepted[iLink].emplace_back(
361  std::make_pair(fillTrackRef,
362  (sortedPartialTracks[iLink][iTrack].partialBits.slice(partialTrackWordBits_) +
363  sortedPartialTracks[iLink][iTrack + 1].partialBits.slice(partialTrackWordBits_))
364  .bs()));
365  else
366  lost[iLink].emplace_back(
367  std::make_pair(fillTrackRef,
368  (sortedPartialTracks[iLink][iTrack].partialBits.slice(partialTrackWordBits_) +
369  sortedPartialTracks[iLink][iTrack + 1].partialBits.slice(partialTrackWordBits_))
370  .bs()));
371  }
372  }
373  } // Config Supported
374 
375  // store products
376  iEvent.emplace(edPutTokenAccepted_, std::move(accepted));
377  iEvent.emplace(edPutTokenLost_, std::move(lost));
378  }
379 } // namespace trklet
380 
double cot() const
Definition: DataFormats.h:968
EDPutTokenT< StreamsTrack > edPutTokenAccepted_
double zT() const
Definition: DataFormats.h:970
constexpr int32_t ceil(float num)
double base(Variable v, Process p) const
Definition: DataFormats.h:492
EDPutTokenT< TTTracks > edPutTokenTTTracks_
static constexpr std::array< double, 1<< TTTrack_TrackWord::TrackBitWidths::kMVAQualitySize > getTqMVAPreSigBins()
static constexpr std::array< double, 1<< TrackBitWidths::kChi2RPhiSize > chi2RPhiBins
double phiT() const
Definition: DataFormats.h:964
T getParameter(std::string const &) const
Definition: ParameterSet.h:307
TTTrack< Ref_Phase2TrackerDigi_ > ttTrack(const std::vector< StubKF > &stubs) const
Definition: DataFormats.cc:485
ESGetToken< Setup, SetupRcd > esGetTokenSetup_
double phi() const
Definition: DataFormats.h:830
std::vector< StreamTrack > StreamsTrack
Definition: TTTypes.h:67
T const & getData(const ESGetToken< T, R > &iToken) const noexcept(false)
Definition: EventSetup.h:119
int kfoutchi2rzConv() const
Definition: Setup.h:511
double chosenRofZ() const
Definition: Setup.h:417
Bit vector used by Track Trigger emulators. Mainly used to convert integers into arbitrary (within ma...
Definition: TTBV.h:20
vector< double > dPhiBins_
Class to process and provide run-time constants used by Track Trigger emulators.
Definition: Setup.h:44
std::vector< StreamStub > StreamsStub
Definition: TTTypes.h:66
int tfpNumChannel() const
Definition: Setup.h:408
T const * product() const
Definition: Handle.h:70
double dPhi() const
Definition: DataFormats.h:834
ESGetToken< DataFormats, DataFormatsRcd > esGetTokenDataFormats_
double cotGlobal() const
Definition: DataFormats.h:972
TTBV & resize(int size)
Definition: TTBV.h:237
double dZ() const
Definition: DataFormats.h:836
static constexpr std::array< double, 1<< TrackBitWidths::kBendChi2Size > bendChi2Bins
uint32_t T const *__restrict__ uint32_t const *__restrict__ int32_t int Histo::index_type cudaStream_t stream
std::vector< FrameTrack > StreamTrack
Definition: TTTypes.h:64
std::unique_ptr< L1TrackQuality > trackQualityModel_
int width(Variable v, Process p) const
Definition: DataFormats.h:490
std::pair< TTTrackRef, Frame > FrameTrack
Definition: TTTypes.h:62
int sectorPhi() const
Definition: DataFormats.h:960
int numSectorsEta() const
Definition: Setup.h:415
int iEvent
Definition: GenABIO.cc:224
Definition: TTTypes.h:54
void settrkMVA1(double atrkMVA1)
Definition: TTTrack.h:382
double z() const
Definition: DataFormats.h:832
static constexpr double ap_fixed_rescale
int kfoutchi2rphiConv() const
Definition: Setup.h:509
double inv2R() const
Definition: DataFormats.h:966
int kfNumWorker() const
Definition: Setup.h:491
EDGetTokenT< StreamsStub > edGetTokenStubs_
double baseSector() const
Definition: Setup.h:424
const unsigned int kValidSize
int sectorEta() const
Definition: DataFormats.h:962
EDPutTokenT< StreamsTrack > edPutTokenLost_
bool configurationSupported() const
Definition: Setup.h:60
#define DEFINE_FWK_MODULE(type)
Definition: MakerMacros.h:16
double chi2BendRed()
Definition: TTTrack.h:159
ProcessHistory const & processHistory() const
Definition: Run.cc:115
Definition: value.py:1
void beginRun(const Run &, const EventSetup &) override
TTBV & set()
Definition: TTBV.h:187
int weightBinFraction() const
Definition: Setup.h:513
int numLayers() const
Definition: Setup.h:215
double hybridChosenRofPhi() const
Definition: Setup.h:266
std::vector< TrackKFOutSAPtr > TrackKFOutSAPtrCollection
Definition: DataFormats.h:1033
void checkHistory(const edm::ProcessHistory &processHistory) const
Definition: Setup.cc:242
static constexpr float d0
void produce(Event &, const EventSetup &) override
Class to store the L1 Track Trigger tracks.
Definition: TTTrack.h:29
static constexpr int kTrackWordSize
deadvectors [0] push_back({0.0175431, 0.538005, 6.80997, 13.29})
int numRegions() const
Definition: Setup.h:349
int dzTruncation() const
Definition: Setup.h:515
HLT enums.
vector< double > dZBins_
static constexpr std::array< double, 1<< TrackBitWidths::kChi2RZSize > chi2RZBins
std::vector< TTTrack< Ref_Phase2TrackerDigi_ > > TTTracks
Definition: TTTypes.h:70
Class to calculate and provide dataformats used by Track Trigger emulator.
Definition: DataFormats.h:216
Converts KF output into tttrack collection and TFP output A bit accurate emulation of the track trans...
edm::Ref< std::vector< TTTrack< Ref_Phase2TrackerDigi_ > >, TTTrack< Ref_Phase2TrackerDigi_ > > TTTrackRef
Definition: TTTypes.h:51
static constexpr int S_
Definition: TTBV.h:22
const DataFormats * dataFormats_
long double T
EDGetTokenT< StreamsTrack > edGetTokenTracks_
void setTrackWordBits()
Set bits in 96-bit Track word.
Definition: TTTrack.h:440
int numFramesIO() const
Definition: Setup.h:157
Power< A, B >::type pow(const A &a, const B &b)
Definition: Power.h:29
def move(src, dest)
Definition: eostools.py:511
const Setup * setup_
Definition: Run.h:45
int dphiTruncation() const
Definition: Setup.h:517
unsigned int digitise(const T &bins, double value, double factor)