Belle II Software development
CDCTriggerHoughETFModule.cc
1/**************************************************************************
2 * basf2 (Belle II Analysis Software Framework) *
3 * Author: The Belle II Collaboration *
4 * *
5 * See git log for contributors and copyright holders. *
6 * This file is licensed under LGPL-3.0, see LICENSE.md. *
7 **************************************************************************/
8
9#include <trg/cdc/modules/houghETF/CDCTriggerHoughETFModule.h>
10
11#include <cdc/geometry/CDCGeometryPar.h>
12#include <framework/logging/Logger.h>
13#include <framework/gearbox/Const.h>
14
15#include <cmath>
16#include <algorithm>
17#include <iterator>
18
19#include <root/TMatrix.h>
20
21/* defines */
22#define CDC_SUPER_LAYERS 9
23
24using namespace Belle2;
25using namespace Belle2::CDC;
26
27//-----------------------------------------------------------------
28// Register the Module
29//-----------------------------------------------------------------
30REG_MODULE(CDCTriggerHoughETF);
31
32//-----------------------------------------------------------------
33// Implementation
34//-----------------------------------------------------------------
35
37{
38 //Set module properties
39 setDescription("Hough tracking algorithm for CDC trigger.");
41
42 // Define module parameters
43 // 2D ETF specified parameters
44 // ----- PARAMETERS : GRL t0 finder with fastest priority timing (current at 2020.2.7)-----
45 // t0CalcMethod = 0
46 // usePriorityPosition = true
47 // arrivalOrder = 0
48 //
49 addParam("outputEventTimeName", m_EventTimeName,
50 "Name of the output StoreObjPtr.",
51 std::string(""));
52 addParam("storeTracks", m_storeTracks,
53 "store tracks",
54 false);
55 addParam("usePriorityTiming", m_usePriorityTiming,
56 "Use priority timing instead of fastest timing.",
57 true);
58 addParam("useHighPassTimingList", m_useHighPassTimingList,
59 "Use associated fastest timings track-by-track",
60 true);
61 addParam("t0CalcMethod", m_t0CalcMethod,
62 "0: Nth fastest fastest time."
63 "1: median of all timings."
64 "2: median of timings in timing window.",
65 (unsigned)(0));
66 addParam("arrivalOrder", m_arrivalOrder,
67 "When t0CalcMethod == 0: Nth fastest ft is used as T0. (i.e. 0 is fastest)",
68 (unsigned)(0));
69 addParam("timeWindowBegin", m_timeWindowBegin,
70 "When t0CalcMethod == 2: start time of time window relative to median. (in ns)",
71 (short)(40));
72 addParam("timeWindowEnd", m_timeWindowEnd,
73 "When t0CalcMethod == 2: end time of time window relative to median. (in ns)",
74 (short)(0));
75
76 //common as CDCTrigger2DFinderModule
77 addParam("hitCollectionName", m_hitCollectionName,
78 "Name of the input StoreArray of CDCTriggerSegmentHits.",
79 std::string(""));
80 addParam("outputCollectionName", m_outputCollectionName,
81 "Name of the StoreArray holding the tracks found in the Hough tracking.",
82 std::string("TRGCDCETFTracks"));
83 addParam("clusterCollectionName", m_clusterCollectionName,
84 "Name of the StoreArray holding the clusters formed in the Hough plane.",
85 std::string(""));
86 addParam("nCellsPhi", m_nCellsPhi,
87 "Number of Hough cells in phi (limits: [-180, 180]). Must be an even number.",
88 (unsigned)(160));
89 addParam("nCellsR", m_nCellsR,
90 "Number of Hough cells in 1/r. Must be an even number.",
91 (unsigned)(34));
92 addParam("minPt", m_minPt,
93 "Minimum Pt [GeV]. "
94 "Hough plane limits in 1/r are [-1/r(minPt), 1/r(minPt)]", (double)(0.3));
95 addParam("shiftPt", m_shiftPt,
96 "Shift the Hough plane by 1/4 cell size in 1/r to avoid "
97 "curvature 0 tracks (<0: shift in negative direction, "
98 "0: no shift, >0: shift in positive direction).", 0);
99
100 addParam("minHits", m_minHits,
101 "Minimum hits from different super layers required in a peak cell.",
102 (unsigned)(4));
103 addParam("minHitsShort", m_minHitsShort,
104 "Minimum hits required required in a peak cell for a short track"
105 " (must be in the first minHitsShort super layers).",
106 (unsigned)(4));
107 addParam("minCells", m_minCells,
108 "Peaks with less than mim_nCells connected cells are ignored.",
109 (unsigned)(2));
110 addParam("onlyLocalMax", m_onlyLocalMax,
111 "Switch to remove cells connected to a cell with higher super layer count.",
112 false);
113 addParam("connect", m_connect,
114 "Definition for connected cells. 4: direct (left/right/top/bottom), "
115 "6: direct + 2 diagonal (top right/bottom left), "
116 "8: direct + all diagonal (top right/top left/bottom right/bottom left)",
117 (unsigned)(6));
118 addParam("ignore2ndPriority", m_ignore2nd,
119 "Switch to skip second priority hits.", false);
120 addParam("usePriorityPosition", m_usePriority,
121 "If true, use wire position of priority cell in track segment, "
122 "otherwise use wire position of center cell.", true);
123 addParam("requireSL0", m_requireSL0,
124 "Switch to check separately for a hit in the innermost superlayer.", false);
125 addParam("storeHoughPlane", m_storePlane,
126 "Switch for saving Hough plane as TMatrix in DataStore. "
127 "0: don't store anything, 1: store only peaks, 2: store full plane "
128 "(will increase runtime).", (unsigned)(0));
129 addParam("clusterPattern", m_clusterPattern,
130 "use nested pattern algorithm to find clusters", true);
131 addParam("clusterSizeX", m_clusterSizeX,
132 "maximum number of 2 x 2 squares in cluster for pattern algorithm",
133 (unsigned)(3));
134 addParam("clusterSizeY", m_clusterSizeY,
135 "maximum number of 2 x 2 squares in cluster for pattern algorithm",
136 (unsigned)(3));
137 addParam("hitRelationsFromCorners", m_hitRelationsFromCorners,
138 "Switch for creating relations to hits in the pattern algorithm. "
139 "If true, create relations from cluster corners, otherwise "
140 "from estimated cluster center (might not have relations).", false);
141
142 addParam("testFilename", m_testFilename,
143 "If not empty, a file with input (hits) and output (tracks) "
144 "for each event is written (for firmware debugging).", std::string(""));
145
146 addParam("suppressClone", m_suppressClone,
147 "Switch to send only the first found track and suppress the "
148 "subsequent clones.", false);
149
150 addParam("offset", m_offset,
151 "Set certain time offset for ETFHough simulation"
152 "Default as -10", -10);
153}
154
155void
157{
158 // register DataStore elements
159 m_eventTime.registerInDataStore(m_EventTimeName);
161
162 if (m_storeTracks) {
163 m_tracks.registerInDataStore(m_outputCollectionName);
164 m_clusters.registerInDataStore(m_clusterCollectionName);
165
166 m_tracks.registerRelationTo(m_segmentHits);
167 m_tracks.registerRelationTo(m_clusters);
168 }
169
170 if (m_storePlane > 0) m_houghPlane.registerInDataStore("HoughPlane");
171
173 int layerId = 3;
174 int nTS = 0;
175 for (int iSL = 0; iSL < 9; ++iSL) {
176 m_TSoffset[iSL] = nTS;
177 nTS += cdc.nWiresInLayer(layerId);
178 m_TSoffset[iSL + 1] = nTS;
179 for (int priority = 0; priority < 2; ++ priority) {
180 m_radius[iSL][priority] = cdc.senseWireR(layerId + priority);
181 }
182 layerId += (iSL > 0 ? 6 : 7);
183 }
184
185 for (int sl = 1; sl < 9; sl++) {
186 m_NSecOffset[sl] = m_NSEC[sl - 1] + m_NSecOffset[sl - 1];
187 }
188
189 if (m_testFilename != "") {
191 }
192
193 if (m_suppressClone) {
194 B2INFO("2D finder will exit with the first track candidate in time.");
195 }
196
197 if (m_t0CalcMethod != 0 && m_t0CalcMethod != 1) B2WARNING("t0CalcMethod is invalid. calculate as default.");
198
199 /* Extent the Hough plane such that the cell number is a power of 2 (same for x and y).
200 * This is for the fast peak finder, which divides the Hough plane in half in each step.
201 * Peaks found outside of the actual limits are ignored. */
202 m_maxIterations = std::ceil(std::log2(std::max(m_nCellsPhi, m_nCellsR))) - 1;
203 m_nCells = std::pow(2, m_maxIterations + 1);
204 /* limits in phi: [-pi, pi] + extra cells */
205 m_rectX = M_PI * m_nCells / m_nCellsPhi;
206 /* limits in R: [-R(minPt), R(minPt)] + extra cells + shift */
207 m_maxR = 0.5 * Const::speedOfLight * 1.5e-4 / m_minPt;
209 m_shiftR = 0;
210 if (m_shiftPt < 0) {
211 m_shiftR = -m_maxR / 2. / m_nCellsR;
212 } else if (m_shiftPt > 0) {
213 m_shiftR = m_maxR / 2. / m_nCellsR;
214 }
215}
216
217void
219{
220 /* Clean hits */
221 m_hitMap.clear();
222 m_houghCand.clear();
224
225 if (!m_eventTime.isValid()) m_eventTime.create();
226 /* set default return value */
227 setReturnValue(true);
228
229 if (m_testFilename != "") {
231 << m_segmentHits.getEntries() << std::endl;
232 }
233
234 if (m_segmentHits.getEntries() == 0) {
235 //B2WARNING("CDCTracking: tsHitsCollection is empty!");
236 return;
237 }
238
239 /* get CDCHits coordinates in conformal space */
240 for (int iHit = 0; iHit < m_segmentHits.getEntries(); iHit++) {
241 unsigned short iSL = m_segmentHits[iHit]->getISuperLayer();
242 if (m_testFilename != "") {
243 m_testFile << iSL << " " << m_segmentHits[iHit]->getSegmentID() - m_TSoffset[iSL] << " "
244 << m_segmentHits[iHit]->getPriorityPosition() << std::endl;
245 }
246 if (iSL % 2) continue;
247 if (m_ignore2nd && m_segmentHits[iHit]->getPriorityPosition() < 3) continue;
248 double phi = m_segmentHits[iHit]->getSegmentID() - m_TSoffset[iSL];
249 if (m_usePriority) {
250 phi += 0.5 * (((m_segmentHits[iHit]->getPriorityPosition() >> 1) & 1)
251 - (m_segmentHits[iHit]->getPriorityPosition() & 1));
252 }
253 phi = phi * 2. * M_PI / (m_TSoffset[iSL + 1] - m_TSoffset[iSL]);
254 double r = m_radius[iSL][int(m_usePriority &&
255 m_segmentHits[iHit]->getPriorityPosition() < 3)];
256 ROOT::Math::XYVector pos(std::cos(phi) / r, std::sin(phi) / r);
257 m_hitMap.insert(std::make_pair(iHit, std::make_pair(iSL, pos)));
258 }
259
260 B2DEBUG(50, "extending Hough plane to " << m_maxIterations << " iterations, "
261 << m_nCells << " cells: phi in ["
262 << -m_rectX * 180. / M_PI << ", " << m_rectX * 180. / M_PI
263 << "] deg, 1/r in [" << -m_rectY + m_shiftR << ", " << m_rectY + m_shiftR << "] /cm");
264
265 /* prepare matrix for storing the Hough plane */
266 if (m_storePlane > 0) {
267 m_houghPlane.create();
269 }
270
271 // hit map containing only the early hits
272 CDCHitMap fastHitMap;
273 if (m_suppressClone && !m_hitMap.empty()) {
274 // find the first track candidates in Hough plane
275 // only for z0 resolution study with single-track events
276 // This will surely fail with multi-track ones,
277 // in which case we really need tick-by-tick simulation for all hits.
278
280 typedef std::pair<int, CDCPair> CDCHitPair;
281 // sequential hit map, ordered by TS found time
282 typedef std::vector<CDCHitPair> CDCSeqMap;
283 CDCSeqMap seqHitMap;
284 // copy hit map to sequential hit map and sort it by TS found time
285 seqHitMap.reserve(m_hitMap.size());
286 for (auto hit : m_hitMap) {
287 seqHitMap.push_back(hit);
288 }
289 sort(seqHitMap.begin(), seqHitMap.end(), [this](CDCHitPair i, CDCHitPair j) {
290 return m_segmentHits[i.first]->foundTime() < m_segmentHits[j.first]->foundTime();
291 });
292 auto seqHitItr = seqHitMap.begin();
293 /* layer filter */
294 std::vector<bool> layerHit(CDC_SUPER_LAYERS, false);
295 // data clock cycle in unit of 2ns
296 short period = 16;
297 short firstTick = m_segmentHits[(*seqHitMap.begin()).first]->foundTime() / period + 1;
298 short lastTick = m_segmentHits[(*(seqHitMap.end() - 1)).first]->foundTime() / period + 1;
299 // add TS hits in every clock cycle until a track candidate is found
300 for (auto tick = firstTick * period; tick < lastTick * period; tick += period) {
301 int nHitInCycle = 0;
302 for (auto itr = seqHitItr; itr < seqHitMap.end(); ++itr) {
303 CDCHitPair currentHit = *itr;
304 // start from the first hit over SL threshold
305 if (count(layerHit.begin(), layerHit.end(), true) >= m_minHits &&
306 m_segmentHits[currentHit.first]->foundTime() > tick) {
307 break;
308 }
309 nHitInCycle++;
310 layerHit[m_segmentHits[currentHit.first]->getISuperLayer()] = true;
311 }
312 copy_n(seqHitItr, nHitInCycle, inserter(fastHitMap, fastHitMap.end()));
313 fastInterceptFinder(fastHitMap, -m_rectX, m_rectX, -m_rectY + m_shiftR, m_rectY + m_shiftR, 0, 0, 0);
314 B2DEBUG(20, "at tick " << tick << ", number of candidates: " << m_houghCand.size());
315 if (!m_houghCand.empty()) {
316 B2DEBUG(10, "found a track at clock " << tick << " with "
317 << fastHitMap.size() << "hits");
318 break;
319 }
320 advance(seqHitItr, nHitInCycle);
321 }
322 } else {
323 /* find track candidates in Hough plane using all TS hits */
325 if (!m_houghCand.empty()) {
326 B2DEBUG(10, "found a track with " << m_hitMap.size() << "hits");
327 }
328 }
329
330 /* merge track candidates */
331 if (m_clusterPattern) {
332 if (patternClustering(fastHitMap))
333 m_eventTime->addBinnedEventT0(calcEventTiming() + m_offset, Const::CDC);
334 } else {
336 }
337
338 if (m_testFilename != "") {
339 m_testFile << m_tracks.getEntries() << std::endl;
340 for (int i = 0; i < m_tracks.getEntries(); ++i) {
341 float ix = (m_tracks[i]->getPhi0() - M_PI_4) * m_nCellsPhi / 2. / M_PI - 0.5;
342 float iy = (m_tracks[i]->getOmega() / 2. + m_maxR - m_shiftR) * m_nCellsR / 2. / m_maxR - 0.5;
343 m_testFile << round(2 * ix) / 2. << " " << round(2 * iy) / 2. << " "
344 << m_tracks[i]->getChargeSign() << std::endl;
347 m_testFile << hits.size() << std::endl;
348 for (unsigned ihit = 0; ihit < hits.size(); ++ihit) {
349 unsigned short iSL = hits[ihit]->getISuperLayer();
350 m_testFile << iSL << " " << hits[ihit]->getSegmentID() - m_TSoffset[iSL] << " "
351 << hits[ihit]->getPriorityPosition() << " "
352 << hits.weight(ihit) << std::endl;
353 }
354 }
355 }
356}
357
358void
std::string m_EventTimeName
Name of the StoreObject containing the trigger event time.
unsigned m_maxIterations
number of iterations for the fast peak finder, smallest n such that 2^(n+1) > max(nCellsPhi,...
std::string m_testFilename
filename for test output for firmware debugging
bool m_useHighPassTimingList
Use associated fastest timings track-by-track.
unsigned m_minCells
minimum number of cells in a cluster to form a track
bool patternClustering(const CDCHitMap &inputMap)
Combine Hough candidates to tracks by a fixed pattern algorithm.
unsigned m_minHitsShort
short tracks require hits in the first minHitsShort super layers to form a candidate
virtual void initialize() override
Initialize the module and check module parameters.
unsigned m_nCellsR
number of Hough cells in 1/r
int m_shiftPt
shift the Hough plane in 1/r to avoid curvature 0 tracks < 0: shift in negative direction (negative h...
double m_shiftR
Hough plane shift in 1/r [1/cm].
virtual void event() override
Run tracking.
StoreArray< CDCTriggerSegmentHit > m_segmentHits
list of track segment hits
std::string m_outputCollectionName
Name of the StoreArray containing the tracks found by the Hough tracking.
unsigned m_nCellsPhi
number of Hough cells in phi
bool m_usePriority
switch between priority position and center position of track segment
short m_timeWindowEnd
End time of time window relative to median.
bool m_clusterPattern
switch for clustering algorithm (if true use nested patterns)
virtual void terminate() override
Clean up.
bool m_hitRelationsFromCorners
switch for creating relations to hits in the pattern clustering algorithm.
StoreObjPtr< TMatrix > m_houghPlane
matrix containing the Hough plane
unsigned m_storePlane
switch to save the Hough plane in DataStore (0: don't save, 1: save only peaks, 2: save full plane)
bool m_ignore2nd
switch to skip second priority hits
std::vector< std::vector< CDCTriggerSegmentHit * > > m_associatedTSHitsList
list of fastest timing of TS associated with Track
unsigned m_connect
number of neighbors to check for connection (4: direct, 6: direct + upper right and lower left corner...
std::vector< CDCTriggerHoughCand > m_houghCand
Hough Candidates.
bool m_suppressClone
switch to send only the first found track and suppress the subsequent clones
std::ofstream m_testFile
filestream for test output for firmware debugging
unsigned m_t0CalcMethod
Switch method to determine the event timing.
unsigned m_nCells
number of cells for the fast peak finder: 2^(maxIterations + 1).
StoreArray< CDCTriggerTrack > m_tracks
list of found tracks
int m_offset
offset for ETF simulation
unsigned m_arrivalOrder
arrival order of fastest timing used as t0 (effective when t0CalcMEthod == 0)
unsigned m_clusterSizeX
maximum cluster size for pattern algorithm
double m_minPt
Hough plane limit in Pt [GeV].
int m_NSecOffset[9]
Number of sector offset of each super layer.
bool m_requireSL0
switch to check separately for a hit in the innermost super layer
short m_timeWindowBegin
Start time of time window relative to median.
unsigned m_TSoffset[10]
Number of track segments up to super layer.
unsigned m_minHits
minimum number of hits from different super layers in a Hough cell to form a candidate
StoreArray< CDCTriggerHoughCluster > m_clusters
list of clusters in the Hough map
int fastInterceptFinder(CDCHitMap &hits, double x1_s, double x2_s, double y1_s, double y2_s, unsigned iterations, unsigned ix_s, unsigned iy_s)
Fast intercept finder Divide Hough plane recursively to find cells with enough crossing lines.
double m_radius[9][2]
Radius of the CDC layers with priority wires (2 per super layer).
StoreObjPtr< BinnedEventT0 > m_eventTime
StoreObjPtr holding the event time.
double m_rectX
Store the rectangle size in x.
double m_maxR
Hough plane limit in 1/r [1/cm].
std::string m_clusterCollectionName
Name of the StoreArray containing the clusters formed in the Hough plane.
bool m_storeTracks
Switch to save the 2D Hough track reconstructed in this module.
std::string m_hitCollectionName
Name of the StoreArray containing the input track segment hits.
double m_rectY
Store the rectangle size in y.
bool m_onlyLocalMax
switch to ignore candidates connected to cells with higher super layer count
bool m_usePriorityTiming
Switch to use priority timing instead of fastest timing.
unsigned m_clusterSizeY
maximum cluster size for pattern algorithm
CDCHitMap m_hitMap
map of TS hits containing <iHit, <iSL, (x, y)>> with iHit: hit index in StoreArray iSL: super layer i...
const int m_NSEC[9]
Number of sector in each super layer.
void connectedRegions()
Combine Hough candidates to tracks by merging connected cells.
Combination of several CDCHits to a track segment hit for the trigger.
The Class for CDC Geometry Parameters.
static CDCGeometryPar & Instance(const CDCGeometry *=nullptr)
Static method to get a reference to the CDCGeometryPar instance.
static const double speedOfLight
[cm/ns]
Definition Const.h:696
void setDescription(const std::string &description)
Sets the description of the module.
Definition Module.cc:214
void setPropertyFlags(unsigned int propertyFlags)
Sets the flags for the module properties.
Definition Module.cc:208
Module()
Constructor.
Definition Module.cc:30
void setReturnValue(int value)
Sets the return value for this module as integer.
Definition Module.cc:220
@ c_ParallelProcessingCertified
This module can be run in parallel processing mode safely (All I/O must be done through the data stor...
Definition Module.h:80
Class for type safe access to objects that are referred to in relations.
size_t size() const
Get number of relations.
float weight(int index) const
Get weight with index.
void addParam(const std::string &name, T &paramVariable, const std::string &description, const T &defaultValue)
Adds a new parameter to the module.
Definition Module.h:560
#define REG_MODULE(moduleName)
Register the given module (without 'Module' suffix) with the framework.
Definition Module.h:650
std::unordered_map< int, CDCPair > CDCHitMap
Map of <counter, CDCPair>, for hits with indices.
Abstract base class for different kinds of events.