Project
Loading...
Searching...
No Matches
BuildTopologyDictionary.cxx
Go to the documentation of this file.
1// Copyright 2019-2026 CERN and copyright holders of ALICE O2.
2// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders.
3// All rights not expressly granted are reserved.
4//
5// This software is distributed under the terms of the GNU General Public
6// License v3 (GPL Version 3), copied verbatim in the file "COPYING".
7//
8// In applying this license CERN does not waive the privileges and immunities
9// granted to it by virtue of its status as an Intergovernmental Organization
10// or submit itself to any jurisdiction.
11
13
17#include <TFile.h>
18#include <fairlogger/Logger.h>
19#include <fmt/format.h>
20#include <algorithm>
21#include <cmath>
22#include <limits>
23#include <span>
24#include <stdexcept>
25#include <thread>
26#include <tuple>
27
28namespace o2::trkft3
29{
30
31namespace
32{
33
35float medianOf(std::span<float> values)
36{
37 const auto middle = values.begin() + static_cast<std::ptrdiff_t>(values.size() / 2);
38 std::nth_element(values.begin(), middle, values.end());
39 if (values.size() % 2 == 1) {
40 return *middle;
41 }
42 return 0.5f * (*std::max_element(values.begin(), middle) + *middle);
43}
44
47std::pair<float, float> medianAndWidth(std::span<float> values, std::span<float> deviations)
48{
49 const float median = medianOf(values);
50 for (std::size_t i = 0; i < values.size(); ++i) {
51 deviations[i] = std::abs(values[i] - median);
52 }
53 return {median, 1.4826f * medianOf(deviations.first(values.size()))};
54}
55
56std::pair<float, float> medianAndWidth(std::vector<float>& values)
57{
58 std::vector<float> deviations(values.size());
59 return medianAndWidth(values, deviations);
60}
61
62} // namespace
63
64template <int DetID>
66{
67 mDictionary.mLayers.resize(nLayers);
68}
69
70template <int DetID>
71void BuildTopologyDictionary<DetID>::accountCluster(const ClusterType& cluster, const unsigned char* pattern, const math_utils::Point3D<float>& start,
72 const math_utils::Point3D<float>& end)
73{
74 const int layer = Dictionary::layerOf(cluster);
75 if (layer < 0 || layer >= static_cast<int>(mInput.size())) {
76 throw std::runtime_error(fmt::format("{}: on no layer of the dictionary's {}", cluster.asString(), mInput.size()));
77 }
78 auto& input = mInput[layer];
79 const auto nBytes = static_cast<std::size_t>(2 + ((pattern[0] * pattern[1] + 7) / 8));
80 std::string bytes(reinterpret_cast<const char*>(pattern), nBytes);
81 const auto [index, inserted] = input.patternIndex.try_emplace(bytes, static_cast<uint32_t>(input.patterns.size()));
82 if (inserted) {
83 input.patterns.push_back(std::move(bytes));
84 }
85 const auto cog = Dictionary::centreOfGravity(cluster, pattern);
86 const auto a = Dictionary::localToFlat(cluster, start);
87 const auto b = Dictionary::localToFlat(cluster, end);
88 input.crossings.push_back({.pattern = index->second,
89 .x0 = a.X() - cog.X(),
90 .y0 = a.Y(),
91 .z0 = a.Z() - cog.Z(),
92 .dx = b.X() - a.X(),
93 .dy = b.Y() - a.Y(),
94 .dz = b.Z() - a.Z()});
95}
96
97template <int DetID>
98float BuildTopologyDictionary<DetID>::measureDepth(int layer, const LayerInput& input) const
99{
100 const auto& crossings = input.crossings;
101 float low = std::numeric_limits<float>::max(), high = std::numeric_limits<float>::lowest();
102 for (const auto& crossing : crossings) {
103 low = std::min({low, crossing.y0, crossing.y0 + crossing.dy});
104 high = std::max({high, crossing.y0, crossing.y0 + crossing.dy});
105 }
106 const float step = mSettings.depthStep;
107 const int nSteps = static_cast<int>(std::floor((high - low) / step));
108 if (nSteps < 1) {
109 throw std::runtime_error(fmt::format("layer {}: its hits span {} um of silicon, less than the depth step", layer, 1e4 * (high - low)));
110 }
111 // The grid's points sit half a step inside the cells; the crossings that reach all of them are scanned.
112 const auto depthAt = [low, step](int k) { return low + ((static_cast<float>(k) + 0.5f) * step); };
113 const float first = depthAt(0), last = depthAt(nSteps - 1);
114 std::vector<uint32_t> scanned;
115 for (std::size_t i = 0; i < crossings.size(); ++i) {
116 const auto& crossing = crossings[i];
117 if (crossing.dy != 0.f && std::min(crossing.y0, crossing.y0 + crossing.dy) <= first && std::max(crossing.y0, crossing.y0 + crossing.dy) >= last) {
118 scanned.push_back(static_cast<uint32_t>(i));
119 }
120 }
121 if (scanned.size() < mSettings.minCount) {
122 throw std::runtime_error(fmt::format("layer {}: {} crossings through the silicon, fewer than {}", layer, scanned.size(), mSettings.minCount));
123 }
124
125 std::vector<float> objective(nSteps);
126 const auto scan = [&](int thread, int nThreads) {
127 std::vector<float> residualsX(scanned.size()), residualsZ(scanned.size()), deviations(scanned.size());
128 for (int k = thread; k < nSteps; k += nThreads) {
129 const float depth = depthAt(k);
130 for (std::size_t i = 0; i < scanned.size(); ++i) {
131 const auto& crossing = crossings[scanned[i]];
132 const float t = (depth - crossing.y0) / crossing.dy;
133 residualsX[i] = crossing.x0 + (t * crossing.dx);
134 residualsZ[i] = crossing.z0 + (t * crossing.dz);
135 }
136 objective[k] = std::hypot(medianAndWidth(residualsX, deviations).second, medianAndWidth(residualsZ, deviations).second);
137 }
138 };
139 const int nThreads = std::clamp(mSettings.nThreads, 1, nSteps);
140 std::vector<std::thread> threads;
141 for (int thread = 1; thread < nThreads; ++thread) {
142 threads.emplace_back(scan, thread, nThreads);
143 }
144 scan(0, nThreads);
145 for (auto& thread : threads) {
146 thread.join();
147 }
148 return depthAt(static_cast<int>(std::ranges::min_element(objective) - objective.begin()));
149}
150
151template <int DetID>
152void BuildTopologyDictionary<DetID>::makeEntries(int layer, const LayerInput& input, LayerDictionary& data) const
153{
154 constexpr int NSpanClasses = Dictionary::NSpanClasses;
155 const auto nPatterns = input.patterns.size();
156 const auto spansOf = [&input](uint32_t pattern) { return std::pair<int, int>{static_cast<unsigned char>(input.patterns[pattern][0]), static_cast<unsigned char>(input.patterns[pattern][1])}; };
157
158 // The residuals at the depth, by pattern.
159 std::vector<std::vector<float>> residualsX(nPatterns), residualsZ(nPatterns);
160 std::vector<float> layerX, layerZ;
161 for (const auto& crossing : input.crossings) {
162 const float t = crossing.dy != 0.f ? (data.depth - crossing.y0) / crossing.dy : -1.f;
163 if (!(t >= 0.f && t <= 1.f)) {
164 continue;
165 }
166 const float x = crossing.x0 + (t * crossing.dx), z = crossing.z0 + (t * crossing.dz);
167 residualsX[crossing.pattern].push_back(x);
168 residualsZ[crossing.pattern].push_back(z);
169 layerX.push_back(x);
170 layerZ.push_back(z);
171 }
172 if (layerX.size() < mSettings.minCount) {
173 throw std::runtime_error(fmt::format("layer {}: {} residuals at its depth, fewer than {}", layer, layerX.size(), mSettings.minCount));
174 }
175
176 // The common patterns, most frequent first (equal counts by their bytes).
177 std::vector<uint32_t> common;
178 for (uint32_t pattern = 0; pattern < nPatterns; ++pattern) {
179 if (residualsX[pattern].size() >= mSettings.minCount) {
180 common.push_back(pattern);
181 }
182 }
183 std::ranges::sort(common, [&](uint32_t a, uint32_t b) {
184 return residualsX[a].size() != residualsX[b].size() ? residualsX[a].size() > residualsX[b].size() : input.patterns[a] < input.patterns[b];
185 });
186 std::vector<bool> isCommon(nPatterns, false);
187 for (const auto pattern : common) {
188 isCommon[pattern] = true;
189 const auto* bytes = reinterpret_cast<const unsigned char*>(input.patterns[pattern].data());
190 const auto [rowSpan, colSpan] = spansOf(pattern);
191 DictionaryEntry entry;
192 entry.pattern.assign(bytes, bytes + input.patterns[pattern].size());
193 float cogRow = 0.f, cogCol = 0.f;
194 itsmft::ClusterPattern::getCOG(rowSpan, colSpan, bytes + 2, cogRow, cogCol);
195 entry.xCOG = -cogRow;
196 entry.zCOG = cogCol;
197 std::tie(entry.xOffset, entry.xWidth) = medianAndWidth(residualsX[pattern]);
198 std::tie(entry.zOffset, entry.zWidth) = medianAndWidth(residualsZ[pattern]);
199 data.hashMap.emplace(itsmft::ClusterTopology::getCompleteHash(rowSpan, colSpan, bytes + 2), static_cast<int>(data.entries.size()));
200 data.entries.push_back(std::move(entry));
201 }
202
203 // The rare patterns pooled by group and by span class on each axis.
204 std::vector<std::vector<float>> groupX(Dictionary::NGroups), groupZ(Dictionary::NGroups), classX(NSpanClasses), classZ(NSpanClasses);
205 for (uint32_t pattern = 0; pattern < nPatterns; ++pattern) {
206 if (isCommon[pattern]) {
207 continue;
208 }
209 const auto [rowSpan, colSpan] = spansOf(pattern);
210 const int group = Dictionary::groupOf(rowSpan, colSpan);
211 groupX[group].insert(groupX[group].end(), residualsX[pattern].begin(), residualsX[pattern].end());
212 groupZ[group].insert(groupZ[group].end(), residualsZ[pattern].begin(), residualsZ[pattern].end());
213 auto& cx = classX[Dictionary::spanClass(rowSpan)];
214 auto& cz = classZ[Dictionary::spanClass(colSpan)];
215 cx.insert(cx.end(), residualsX[pattern].begin(), residualsX[pattern].end());
216 cz.insert(cz.end(), residualsZ[pattern].begin(), residualsZ[pattern].end());
217 }
218 const auto wholeX = medianAndWidth(layerX), wholeZ = medianAndWidth(layerZ);
219 const auto pooled = [this](std::vector<float>& group, std::vector<float>& spanClass, const std::pair<float, float>& whole) {
220 if (group.size() >= mSettings.minCount) {
221 return medianAndWidth(group);
222 }
223 if (spanClass.size() >= mSettings.minCount) {
224 return medianAndWidth(spanClass);
225 }
226 return whole;
227 };
228 for (int group = 0; group < Dictionary::NGroups; ++group) {
229 DictionaryEntry entry;
230 entry.isGroup = true;
231 std::tie(entry.xOffset, entry.xWidth) = pooled(groupX[group], classX[group / NSpanClasses], wholeX);
232 std::tie(entry.zOffset, entry.zWidth) = pooled(groupZ[group], classZ[group % NSpanClasses], wholeZ);
233 data.entries.push_back(std::move(entry));
234 }
235
236 for (std::size_t id = 0; id < data.entries.size(); ++id) {
237 const auto& entry = data.entries[id];
238 if (!(entry.xWidth > 0.f && entry.zWidth > 0.f && std::isfinite(entry.xWidth) && std::isfinite(entry.zWidth))) {
239 throw std::runtime_error(fmt::format("layer {}: entry {} has widths {} and {} cm", layer, id, entry.xWidth, entry.zWidth));
240 }
241 }
242}
243
244template <int DetID>
246{
247 for (int layer = 0; layer < static_cast<int>(mInput.size()); ++layer) {
248 auto& input = mInput[layer];
249 if (input.crossings.empty()) {
250 throw std::runtime_error(fmt::format("layer {} has no clusters", layer));
251 }
252 auto& data = mDictionary.mLayers[layer];
254 data.depth = measureDepth(layer, input);
255 makeEntries(layer, input, data);
256 input = LayerInput{};
257 LOGP(info, "{} dictionary layer {}: depth {:.2f} um, {} common patterns", o2::detectors::DetID(DetID).getName(), layer, 1e4 * data.depth,
258 data.entries.size() - Dictionary::NGroups);
259 }
260}
261
262template <int DetID>
263void BuildTopologyDictionary<DetID>::saveDictionaryRoot(const std::string& fileName) const
264{
265 TFile output(fileName.c_str(), "recreate");
266 output.WriteObjectAny(&mDictionary, Dictionary::Class(), "ccdb_object");
267 output.Close();
268}
269
272
273} // namespace o2::trkft3
Definition of the ClusterTopology class.
std::string getName(const TDataMember *dm, int index, int size)
unsigned int uint32_t
int32_t i
configStandalone Reconstruction settings
void output(const std::map< std::string, ChannelStat > &channels)
Definition rawdump.cxx:197
Builds the TRK and FT3 topology dictionaries from MC clusters and their particles' crossings.
size_t bytes
Static class with identifiers, bitmasks and names for ALICE detectors.
Definition DetID.h:60
static int getCOG(int rowSpan, int colSpan, const unsigned char patt[MaxPatternBytes], float &xCOG, float &zCOG)
Static: Compute pattern's COG position. Returns the number of fired pixels.
static unsigned long getCompleteHash(int nRow, int nCol, const unsigned char patt[ClusterPattern::MaxPatternBytes])
Compute the complete hash as defined for mHash.
BuildTopologyDictionary(int nLayers, const Settings &settings)
void build()
Builds every layer; throws std::runtime_error for a layer with too few residuals.
typename Dictionary::ClusterType ClusterType
void accountCluster(const ClusterType &cluster, const unsigned char *pattern, const math_utils::Point3D< float > &start, const math_utils::Point3D< float > &end)
A cluster and its particle's crossing of the chip, in O2's local frame [cm].
void saveDictionaryRoot(const std::string &fileName) const
Writes the dictionary as "ccdb_object".
GLint GLenum GLint x
Definition glcorearb.h:403
GLuint entry
Definition glcorearb.h:5735
GLsizeiptr size
Definition glcorearb.h:659
GLuint GLuint end
Definition glcorearb.h:469
GLuint index
Definition glcorearb.h:781
GLint first
Definition glcorearb.h:399
GLboolean GLboolean GLboolean b
Definition glcorearb.h:1233
GLenum GLsizei GLsizei GLint * values
Definition glcorearb.h:1576
GLboolean GLuint group
Definition glcorearb.h:3991
GLint GLint GLsizei GLsizei GLsizei depth
Definition glcorearb.h:470
GLenum GLuint GLint GLint layer
Definition glcorearb.h:1310
GLboolean GLboolean GLboolean GLboolean a
Definition glcorearb.h:1233
GLuint id
Definition glcorearb.h:650
GLdouble GLdouble GLdouble z
Definition glcorearb.h:843
R median(std::vector< T > v)
Definition fit.h:520
Enum< T >::Iterator begin(Enum< T >)
Definition Defs.h:158
value_T step
Definition TrackUtils.h:42
std::array< uint16_t, 5 > pattern