FairShip
Loading...
Searching...
No Matches
StrawPatRec.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: LGPL-3.0-or-later
2// SPDX-FileCopyrightText: Copyright CERN for the benefit of the SHiP
3// Collaboration
4
5#include "StrawPatRec.hpp"
6
7#include <Eigen/Dense>
8#include <algorithm>
9#include <cmath>
10#include <limits>
11#include <map>
12#include <numeric>
13#include <set>
14#include <tuple>
15#include <utility>
16
17namespace SHiP {
18
19namespace {
20
22constexpr double kKick = 0.299792458;
23
25constexpr double kMaxMomentum = 1000.;
26
30constexpr int kXLinesPerYLine = 4;
33constexpr double kSameLineFraction = 0.75;
34
37Eigen::Vector3d signDirection(const LineSegment& line, const StrawWire& wire) {
38 const Eigen::Vector3d t = Eigen::Vector3d(line.tx, line.ty, 1.).normalized();
39 const Eigen::Vector3d d(wire.dx, wire.dy, wire.dz);
40 return d.cross(t).normalized();
41}
42
43bool isStereo(const StrawWire& wire) {
44 return wire.view == 1 || wire.view == 2;
45}
46
47bool isUpstream(const StrawWire& wire) { return wire.station <= 2; }
48
50using Layers = std::vector<std::vector<int>>;
51
52Layers groupLayers(const std::vector<PatRecHit>& hits,
53 const std::vector<int>& selected) {
54 std::map<std::tuple<int, int, int>, std::vector<int>> byLayer;
55 for (const int i : selected) {
56 const auto& w = *hits[i].wire;
57 byLayer[{w.station, w.view, w.layer}].push_back(i);
58 }
59 Layers layers;
60 for (auto& [key, members] : byLayer) {
61 layers.push_back(std::move(members));
62 }
63 std::sort(layers.begin(), layers.end(),
64 [&hits](const auto& a, const auto& b) {
65 return hits[a.front()].wire->z < hits[b.front()].wire->z;
66 });
67 return layers;
68}
69
70int sharedHits(const LineSegment& a, const LineSegment& b) {
71 int shared = 0;
72 for (const int h : a.hits) {
73 shared += std::count(b.hits.begin(), b.hits.end(), h);
74 }
75 return shared;
76}
77
79bool better(const LineSegment& a, const LineSegment& b) {
80 if (a.hits.size() != b.hits.size()) {
81 return a.hits.size() > b.hits.size();
82 }
83 return a.chi2 < b.chi2;
84}
85
89std::vector<LineSegment> removeDuplicates(std::vector<LineSegment> segments,
90 int maxShared,
91 double maxFraction = 1.) {
92 std::sort(segments.begin(), segments.end(), better);
93 std::vector<LineSegment> kept;
94 for (auto& segment : segments) {
95 const bool duplicate =
96 std::any_of(kept.begin(), kept.end(), [&](const auto& other) {
97 const int shared = sharedHits(segment, other);
98 const auto shorter = std::min(segment.hits.size(), other.hits.size());
99 return shared > maxShared || shared > maxFraction * shorter;
100 });
101 if (!duplicate) {
102 kept.push_back(std::move(segment));
103 }
104 }
105 return kept;
106}
107
114bool fitLine(LineSegment& line, const std::vector<PatRecHit>& hits, bool fitX,
115 double outlierCut) {
116 for (int iteration = 0; iteration < 10; ++iteration) {
117 const int n = static_cast<int>(line.hits.size());
118 const int nPar = fitX ? 4 : 2;
119 if (n < nPar + 1) {
120 return false;
121 }
122 double zSum = 0.;
123 for (const int h : line.hits) {
124 zSum += hits[h].wire->z;
125 }
126 const double z0 = zSum / n;
127 // Re-express the current line around the new reference z
128 line.x0 = line.x(z0);
129 line.y0 = line.y(z0);
130 line.z0 = z0;
131
132 // Signs from the current line
133 std::vector<int> signs(n);
134 bool changed = line.signs.size() != static_cast<std::size_t>(n);
135 for (int k = 0; k < n; ++k) {
136 const double predicted =
137 signedWireDistance(line, *hits[line.hits[k]].wire);
138 signs[k] = predicted >= 0. ? 1 : -1;
139 changed = changed || signs[k] != line.signs[k];
140 }
141 line.signs = signs;
142
143 Eigen::MatrixXd a(n, nPar);
144 Eigen::VectorXd b(n);
145 for (int k = 0; k < n; ++k) {
146 const auto& hit = hits[line.hits[k]];
147 const auto& w = *hit.wire;
148 const Eigen::Vector3d m = signDirection(line, w);
149 const double dz = w.z - z0;
150 const double weight = 1. / hit.sigma;
151 // m . (P - c), with P = (x0 + tx dz, y0 + ty dz, w.z)
152 double rhs = signs[k] * hit.drift + m.x() * w.x + m.y() * w.y;
153 if (fitX) {
154 a.row(k) << m.x(), m.x() * dz, m.y(), m.y() * dz;
155 } else {
156 a.row(k) << m.y(), m.y() * dz;
157 rhs -= m.x() * line.x(w.z);
158 }
159 a.row(k) *= weight;
160 b(k) = rhs * weight;
161 }
162 const Eigen::VectorXd p = a.colPivHouseholderQr().solve(b);
163 if (!p.allFinite()) {
164 return false;
165 }
166 if (fitX) {
167 line.x0 = p(0);
168 line.tx = p(1);
169 line.y0 = p(2);
170 line.ty = p(3);
171 } else {
172 line.y0 = p(0);
173 line.ty = p(1);
174 }
175
176 // Residuals, and the worst outlier
177 line.chi2 = 0.;
178 int worst = -1;
179 double worstResidual = outlierCut;
180 for (int k = 0; k < n; ++k) {
181 const auto& hit = hits[line.hits[k]];
182 const double residual =
183 signs[k] * hit.drift - signedWireDistance(line, *hit.wire);
184 line.chi2 += residual * residual / (hit.sigma * hit.sigma);
185 if (std::abs(residual) > worstResidual) {
186 worstResidual = std::abs(residual);
187 worst = k;
188 }
189 }
190 if (worst >= 0) {
191 line.hits.erase(line.hits.begin() + worst);
192 line.signs.erase(line.signs.begin() + worst);
193 continue;
194 }
195 if (!changed) {
196 return true;
197 }
198 }
199 return true;
200}
201
203int closestHit(const LineSegment& line, const std::vector<int>& layer,
204 const std::vector<PatRecHit>& hits, double tolerance) {
205 int best = -1;
206 double bestDistance = tolerance;
207 for (const int h : layer) {
208 const double distance = std::abs(
209 std::abs(signedWireDistance(line, *hits[h].wire)) - hits[h].drift);
210 if (distance < bestDistance) {
211 bestDistance = distance;
212 best = h;
213 }
214 }
215 return best;
216}
217
218int countHits(const LineSegment& line, const std::vector<PatRecHit>& hits,
219 bool (*select)(const StrawWire&)) {
220 return std::count_if(line.hits.begin(), line.hits.end(),
221 [&](int h) { return select(*hits[h].wire); });
222}
223
224bool isY(const StrawWire& wire) { return !isStereo(wire); }
225
229std::vector<std::pair<int, int>> seedLayerPairs(
230 const Layers& layers, const std::vector<PatRecHit>& hits) {
231 std::set<std::pair<int, int>> pairs;
232 const auto addPairs = [&](int first, int last) {
233 const int n = last - first;
234 if (n < 2) {
235 return;
236 }
237 const int edge = std::min(2, n / 2);
238 for (int la = first; la < first + edge; ++la) {
239 for (int lb = last - edge; lb < last; ++lb) {
240 pairs.emplace(la, lb);
241 }
242 }
243 };
244 const int nLayers = static_cast<int>(layers.size());
245 addPairs(0, nLayers);
246 int first = 0;
247 for (int l = 1; l <= nLayers; ++l) {
248 if (l == nLayers || hits[layers[l].front()].wire->station !=
249 hits[layers[first].front()].wire->station) {
250 addPairs(first, l);
251 first = l;
252 }
253 }
254 return {pairs.begin(), pairs.end()};
255}
256bool isU(const StrawWire& wire) { return wire.view == 1; }
257bool isV(const StrawWire& wire) { return wire.view == 2; }
258
259} // namespace
260
261double signedWireDistance(const LineSegment& line, const StrawWire& wire) {
262 const Eigen::Vector3d p(line.x(wire.z), line.y(wire.z), wire.z);
263 const Eigen::Vector3d c(wire.x, wire.y, wire.z);
264 return (p - c).dot(signDirection(line, wire));
265}
266
267StrawPatRec::StrawPatRec(const Config& config, double bendingZ,
268 double fieldIntegral)
269 : m_cfg(config), m_bendingZ(bendingZ), m_fieldIntegral(fieldIntegral) {}
270
271std::vector<LineSegment> StrawPatRec::findSegments(
272 const std::vector<PatRecHit>& hits, bool upstream, int maxSegments) const {
273 std::vector<int> yHits;
274 std::vector<int> stereoHits;
275 for (int i = 0; i < static_cast<int>(hits.size()); ++i) {
276 const auto& w = *hits[i].wire;
277 if (isUpstream(w) != upstream) {
278 continue;
279 }
280 (isStereo(w) ? stereoHits : yHits).push_back(i);
281 }
282 const Layers yLayers = groupLayers(hits, yHits);
283 const Layers stereoLayers = groupLayers(hits, stereoHits);
284 const int nY = static_cast<int>(yLayers.size());
285 const int nStereo = static_cast<int>(stereoLayers.size());
286 if (nY < m_cfg.minYHits || nStereo < m_cfg.minStereoHits) {
287 return {};
288 }
289 // Seeds pair a hit in one of the first two layers with one in the last two,
290 // of the pair of stations and of each station
291
292 // y lines from pairs of drift circles: the two candidate y positions of
293 // each hit give four lines per pair
294 std::vector<LineSegment> yLines;
295 for (const auto& [la, lb] : seedLayerPairs(yLayers, hits)) {
296 {
297 for (const int a : yLayers[la]) {
298 for (const int b : yLayers[lb]) {
299 const auto& wa = *hits[a].wire;
300 const auto& wb = *hits[b].wire;
301 for (const int sa : {-1, 1}) {
302 for (const int sb : {-1, 1}) {
303 LineSegment line;
304 line.z0 = wa.z;
305 line.y0 = wa.y + sa * hits[a].drift;
306 line.ty = (wb.y + sb * hits[b].drift - line.y0) / (wb.z - wa.z);
307 if (std::abs(line.ty) > m_cfg.maxSlope) {
308 continue;
309 }
310 line.hits = {a, b};
311 for (int l = 0; l < nY; ++l) {
312 if (l == la || l == lb) {
313 continue;
314 }
315 const int h =
316 closestHit(line, yLayers[l], hits, m_cfg.tolerance);
317 if (h >= 0) {
318 line.hits.push_back(h);
319 }
320 }
321 if (static_cast<int>(line.hits.size()) < m_cfg.minYHits) {
322 continue;
323 }
324 if (fitLine(line, hits, false, m_cfg.tolerance) &&
325 static_cast<int>(line.hits.size()) >= m_cfg.minYHits) {
326 yLines.push_back(std::move(line));
327 }
328 }
329 }
330 }
331 }
332 }
333 }
334 // The y lines are not deduplicated: tracks that overlap in y have similar
335 // y lines, and are told apart only in the stereo views, and the same hits
336 // can fit with the sides of some wires mirrored, which projects the stereo
337 // hits differently. Duplicate segments are removed after the stereo views.
338
339 // For each y line, find the x line in the stereo views. Each stereo hit
340 // gives two x positions, one for each side of the wire.
341 struct XPoint {
342 int hit;
343 double z;
344 double x;
345 };
346 std::vector<LineSegment> segments;
347 for (const auto& yLine : yLines) {
348 std::vector<std::vector<XPoint>> points(nStereo);
349 for (int l = 0; l < nStereo; ++l) {
350 for (const int h : stereoLayers[l]) {
351 const auto& w = *hits[h].wire;
352 const Eigen::Vector3d m = signDirection(yLine, w);
353 if (std::abs(m.x()) < 1e-3) {
354 continue;
355 }
356 for (const int s : {-1, 1}) {
357 const double x =
358 w.x + (s * hits[h].drift - m.y() * (yLine.y(w.z) - w.y)) / m.x();
359 // Only where the wire actually is
360 const double along = (x - w.x) * w.dx + (yLine.y(w.z) - w.y) * w.dy;
361 if (std::abs(along) <= w.halfLength) {
362 points[l].push_back({h, w.z, x});
363 }
364 }
365 }
366 }
367 // Several x lines per y line (see kXLinesPerYLine)
368 std::vector<LineSegment> xLines;
369 for (const auto& [la, lb] : seedLayerPairs(stereoLayers, hits)) {
370 {
371 for (const auto& pa : points[la]) {
372 for (const auto& pb : points[lb]) {
373 LineSegment line = yLine;
374 line.tx = (pb.x - pa.x) / (pb.z - pa.z);
375 if (std::abs(line.tx) > m_cfg.maxSlope) {
376 continue;
377 }
378 line.x0 = pa.x + line.tx * (line.z0 - pa.z);
379 line.signs.clear();
380 line.hits.push_back(pa.hit);
381 line.hits.push_back(pb.hit);
382 for (int l = 0; l < nStereo; ++l) {
383 if (l == la || l == lb) {
384 continue;
385 }
386 const int h =
387 closestHit(line, stereoLayers[l], hits, m_cfg.tolerance);
388 if (h >= 0) {
389 line.hits.push_back(h);
390 }
391 }
392 if (countHits(line, hits, isStereo) < m_cfg.minStereoHits) {
393 continue;
394 }
395 if (fitLine(line, hits, true, m_cfg.tolerance) &&
396 countHits(line, hits, isY) >= m_cfg.minYHits &&
397 countHits(line, hits, isStereo) >= m_cfg.minStereoHits &&
398 countHits(line, hits, isU) >= m_cfg.minHitsPerStereoView &&
399 countHits(line, hits, isV) >= m_cfg.minHitsPerStereoView) {
400 xLines.push_back(std::move(line));
401 }
402 }
403 }
404 }
405 }
406 xLines = removeDuplicates(
407 std::move(xLines), std::numeric_limits<int>::max(), kSameLineFraction);
408 if (static_cast<int>(xLines.size()) > kXLinesPerYLine) {
409 xLines.resize(kXLinesPerYLine);
410 }
411 for (auto& line : xLines) {
412 segments.push_back(std::move(line));
413 }
414 }
415 // Only near-duplicates are removed here. Neighbouring tracks share
416 // straws, and the choice between conflicting candidates is left to the
417 // fit of the whole track.
418 segments = removeDuplicates(std::move(segments), m_cfg.maxSharedHits);
419 if (maxSegments > 0 && static_cast<int>(segments.size()) > maxSegments) {
420 segments.resize(maxSegments);
421 }
422 return segments;
423}
424
425std::optional<TrackCandidate> StrawPatRec::match(
426 const LineSegment& upstream, const LineSegment& downstream) const {
427 TrackCandidate candidate{upstream, downstream};
428 // The field kicks the track in y by q * kKick * integral(Bx dz) / pz
429 const double kink = downstream.ty - upstream.ty;
430 const double kick = kKick * m_fieldIntegral;
431 if (kink == 0. || kick == 0.) {
432 return std::nullopt;
433 }
434 const double pz = std::min(std::abs(kick / kink), kMaxMomentum);
435 candidate.momentum = pz * std::sqrt(1. + upstream.tx * upstream.tx +
436 upstream.ty * upstream.ty);
437 candidate.charge = kink / kick > 0. ? 1 : -1;
438
439 const double z = m_bendingZ;
440 const double p = candidate.momentum;
441 const auto sigma = [p](double a, double b) { return std::hypot(a, b / p); };
442 const double dx = (upstream.x(z) - downstream.x(z)) /
443 sigma(m_cfg.matchSigmaX, m_cfg.matchSigmaXPerP);
444 const double dtx = (upstream.tx - downstream.tx) /
445 sigma(m_cfg.matchSigmaTx, m_cfg.matchSigmaTxPerP);
446 const double dy = (upstream.y(z) - downstream.y(z)) /
447 sigma(m_cfg.matchSigmaY, m_cfg.matchSigmaYPerP);
448 candidate.matchChi2 = dx * dx + dtx * dtx + dy * dy;
449 return candidate;
450}
451
452std::vector<TrackCandidate> StrawPatRec::matchSegments(
453 const std::vector<LineSegment>& upstream,
454 const std::vector<LineSegment>& downstream) const {
455 std::vector<TrackCandidate> pairs;
456 for (const auto& u : upstream) {
457 for (const auto& d : downstream) {
458 auto candidate = match(u, d);
459 if (candidate &&
460 (candidate->matchChi2 < m_cfg.maxMatchChi2 ||
461 (candidate->momentum < m_cfg.lowMomentum &&
462 candidate->matchChi2 < m_cfg.maxLowMomentumMatchChi2))) {
463 pairs.push_back(std::move(*candidate));
464 }
465 }
466 }
467 // Greedy one-to-one assignment, best match first
468 std::sort(pairs.begin(), pairs.end(), [](const auto& a, const auto& b) {
469 return a.matchChi2 < b.matchChi2;
470 });
471 std::vector<TrackCandidate> tracks;
472 std::set<std::vector<int>> usedUp;
473 std::set<std::vector<int>> usedDown;
474 for (auto& pair : pairs) {
475 if (usedUp.count(pair.upstream.hits) ||
476 usedDown.count(pair.downstream.hits)) {
477 continue;
478 }
479 usedUp.insert(pair.upstream.hits);
480 usedDown.insert(pair.downstream.hits);
481 tracks.push_back(std::move(pair));
482 }
483 return tracks;
484}
485
486std::vector<TrackCandidate> StrawPatRec::findTracks(
487 const std::vector<PatRecHit>& hits) const {
488 return matchSegments(findSegments(hits, true, 0),
489 findSegments(hits, false, 0));
490}
491
492std::optional<TrackCandidate> StrawPatRec::fitCandidate(
493 const std::vector<PatRecHit>& hits) const {
494 const auto upstream = findSegments(hits, true, 1);
495 const auto downstream = findSegments(hits, false, 1);
496 if (upstream.empty() || downstream.empty()) {
497 return std::nullopt;
498 }
499 return match(upstream.front(), downstream.front());
500}
501
502} // namespace SHiP
constexpr Double_t m
std::vector< TrackCandidate > findTracks(const std::vector< PatRecHit > &hits) const
Find tracks among all hits of the event.
std::vector< LineSegment > findSegments(const std::vector< PatRecHit > &hits, bool upstream, int maxSegments) const
std::optional< TrackCandidate > fitCandidate(const std::vector< PatRecHit > &hits) const
std::vector< TrackCandidate > matchSegments(const std::vector< LineSegment > &upstream, const std::vector< LineSegment > &downstream) const
std::optional< TrackCandidate > match(const LineSegment &upstream, const LineSegment &downstream) const
StrawPatRec(const Config &config, double bendingZ, double fieldIntegral)
double signedWireDistance(const LineSegment &line, const StrawWire &wire)
int i
Definition ShipAna.py:108
std::vector< int > signs
signed drift distance = sign * drift
std::vector< int > hits
positions in the hit list
double y(double z) const
double x(double z) const
A straw wire in the SHiP frame (cm), for pattern recognition.
double x
Wire centre.