ATLAS Offline Software
Loading...
Searching...
No Matches
SegmentFittingAlg.cxx
Go to the documentation of this file.
1/*
2 Copyright (C) 2002-2026 CERN for the benefit of the ATLAS collaboration
3*/
4#include "SegmentFittingAlg.h"
5
8
13#include "ActsInterop/Logger.h"
14
16
17#include "Acts/Definitions/Units.hpp"
18
19#include <format>
20
21using namespace Acts;
22using namespace Acts::UnitLiterals;
23
24namespace MuonR4 {
25 using namespace SegmentFit;
26 using namespace MuonValR4;
27
29
32 ATH_CHECK(m_geoCtxKey.initialize());
33 ATH_CHECK(m_seedKey.initialize());
34 ATH_CHECK(m_outSegments.initialize());
35 ATH_CHECK(m_calibTool.retrieve());
36 ATH_CHECK(m_idHelperSvc.retrieve());
37 ATH_CHECK(m_visionTool.retrieve(EnableTool{!m_visionTool.empty()}));
39 m_ambiSolver = std::make_unique<SegmentAmbiSolver>(name(), std::move(cfg));
40
42 fitCfg.calibrator = m_calibTool.get();
43 fitCfg.visionTool = m_visionTool.get();
44 fitCfg.idHelperSvc = m_idHelperSvc.get();
45 fitCfg.fitT0 = m_doT0Fit;
46 fitCfg.recalibrate = m_recalibInFit;
47 fitCfg.useFastFitter = m_useFastFitter;
48 fitCfg.fastPreFitter = m_fastPreFitter;
49 fitCfg.ignoreFailedPreFit = m_ignoreFailedPreFit;
50 fitCfg.useHessian = m_hessianResidual;
51
55
57 for (const auto* prop :{&m_seedMaxBsR, &m_seedMaxBsL}) {
58 if (prop->value().size() != s_stIdxMax ||
59 std::ranges::min(prop->value()) < 0.) {
60 ATH_MSG_ERROR("Invalid configuratnon of "<<(prop));
61 return StatusCode::FAILURE;
62 }
63 ATH_MSG_DEBUG("Configured "<<(*prop));
64 }
65 }
69 fitCfg.maxIter = m_maxIter;
70 ATH_MSG_DEBUG("Fitter configuration: \n -- "<<m_doT0Fit<<"\n -- "<<m_recalibInFit<<"\n -- "<<m_useFastFitter
71 <<"\n -- "<<m_fastPreFitter<<"\n -- "<<m_ignoreFailedPreFit<<"\n -- "<<m_hessianResidual
72 <<"\n -- "<<m_doBeamspotConstraint<<"\n -- "<<m_beamSpotR<<"\n -- "<<m_beamSpotL<<"\n -- "<<m_outlierRemovalCut
73 <<"\n -- "<<m_recoveryPull<<"\n -- "<<m_precHitCut<<"\n -- "<<m_maxIter);
74
75 m_fitter = std::make_unique<SegmentFit::SegmentLineFitter>(name(), std::move(fitCfg));
76
77 MdtSegmentSeedGenerator::Config genCfg{};
78 genCfg.hitPullCut = m_seedHitChi2;
79 genCfg.busyLayerLimit = m_busyLayerLimit;
80 genCfg.startWithPattern = m_tryPatternPars;
81 ATH_MSG_DEBUG("Seeder configuration: \n - "<<m_tryPatternPars
82 <<"\n - "<<m_seedHitChi2
83 <<"\n - "<<m_busyLayerLimit);
84 m_seeder = std::make_unique<SegmentFit::MdtSegmentSeedGenerator>(genCfg, makeActsAthenaLogger(this, name()));
85 genCfg.busyLayerLimit += 2;
86 m_seederBEE = std::make_unique<SegmentFit::MdtSegmentSeedGenerator>(genCfg, makeActsAthenaLogger(this, name()));
87
88 return StatusCode::SUCCESS;
89 }
90 StatusCode SegmentFittingAlg::execute(const EventContext& ctx) const {
91 const ActsTrk::GeometryContext* gctx{nullptr};
92 ATH_CHECK(SG::get(gctx, m_geoCtxKey, ctx));
93 const SegmentSeedContainer* segmentSeeds=nullptr;
94 ATH_CHECK(SG::get(segmentSeeds, m_seedKey, ctx));
95
96 SG::WriteHandle writeSegments{m_outSegments, ctx};
97 ATH_CHECK(writeSegments.record(std::make_unique<SegmentContainer>()));
98 SegmentVec_t allSegments{};
99 ATH_MSG_VERBOSE("execute() - Start processing " << segmentSeeds->size() << " pattern seeds.");
100 for (const SegmentSeed* seed : *segmentSeeds) {
101 SegmentVec_t segments = fitSegmentSeed(ctx, *gctx, seed);
102 if (m_visionTool.isEnabled() && segments.size() > 1) {
103 auto drawFinalReco = [this, &segments, &gctx, &ctx,&seed](const std::string& nameTag) {
104 PrimitiveVec segmentLines{};
105 double yLegend{0.85};
106 segmentLines.push_back(drawLabel(std::format("# segments: {:d}", segments.size()), 0.2, yLegend, 14));
107 yLegend-=0.04;
108 for (const std::unique_ptr<Segment>& seg : segments) {
109 const Parameters pars = localSegmentPars(*gctx, *seg);
110 const auto [pos, dir] = makeLine(pars);
111 segmentLines.emplace_back(drawLine(pars, -Gaudi::Units::m, Gaudi::Units::m, kRed));
112 std::stringstream signStream{};
113 const auto& cov = seg->covariance();
114 signStream<<std::format("#chi^{{2}}/nDoF: {:.2f} ({:}), ", seg->chi2() / seg->nDoF(), seg->nDoF());
115 signStream<<std::format("y_{{0}}={:.2f}#pm{:.2f}",
116 pars[toUnderlying(ParamDefs::y0)],
117 Amg::error(cov, toUnderlying(ParamDefs::y0)))<<", ";
118 signStream<<std::format("#theta={:.2f}#pm{:.2f}^{{#circ}}",
119 pars[toUnderlying(ParamDefs::theta)]/ 1._degree,
120 Amg::error(cov, toUnderlying(ParamDefs::theta)) / 1._degree )<<", ";
121 for (const Segment::MeasType& m : seg->measurements()) {
123 m->fitState() == CalibratedSpacePoint::State::Valid) {
124 signStream<<(SeedingAux::strawSign(pos, dir, *m) == -1 ? "L" : "R");
125 }
126 }
127 segmentLines.push_back(drawLabel(signStream.str(), 0.2, yLegend, 13));
128 yLegend-=0.03;
129 }
130
131 m_visionTool->visualizeBucket(ctx, *seed->parentBucket(), nameTag, std::move(segmentLines));
132 };
133 drawFinalReco("all segments");
134 const unsigned int nBeforeAmbi = segments.size();
135 segments = m_ambiSolver->resolveAmbiguity(*gctx, std::move(segments));
136 if (nBeforeAmbi != segments.size()) {
137 drawFinalReco("post ambiguity");
138 }
139 } else if (m_visionTool.isEnabled() && segments.empty() &&
140 std::ranges::any_of(seed->getHitsInMax(),[this](const SpacePoint* hit){
141 return m_visionTool->isLabeled(*hit);
142 })) {
143 m_visionTool->visualizeSeed(ctx, *seed, "Failed fit");
144 }
145 allSegments.insert(allSegments.end(), std::make_move_iterator(segments.begin()),
146 std::make_move_iterator(segments.end()));
147 }
148 resolveAmbiguities(*gctx, allSegments);
149 writeSegments->insert(writeSegments->end(),
150 std::make_move_iterator(allSegments.begin()),
151 std::make_move_iterator(allSegments.end()));
152 ATH_MSG_VERBOSE("Found in total "<<writeSegments->size()<<" segments. ");
153 return StatusCode::SUCCESS;
154 }
155
157 SegmentFittingAlg::fitSegmentSeed(const EventContext& ctx,
158 const ActsTrk::GeometryContext& gctx,
159 const SegmentSeed* patternSeed) const {
160
161 const auto& locToGlob = patternSeed->msSector()->localToGlobalTransform(gctx);
162 std::vector<std::unique_ptr<Segment>> segments{};
163
164 const Acts::CalibrationContext cctx = ActsTrk::getCalibrationContext(ctx);
165
166 using namespace Muon::MuonStationIndex;
167 using State_t = MdtSegmentSeedGenerator::State_t;
168 // Make sure patternSeed->parameters() are in ACTS units!
169 State_t seedState{patternSeed->parameters(), patternSeed, m_calibTool.get(), m_recalibSeed,
170 [&](const Amg::Vector3D& tangentSeedPos, const Amg::Vector3D& tangentSeedDir){
172 return true;
173 }
174 const Amg::Vector3D globPos{locToGlob*tangentSeedPos};
175 const Amg::Vector3D globDir{locToGlob.linear()*tangentSeedDir};
176
179 const StIndex stIdx = toStationIndex(patternSeed->msSector()->chamberIndex());
180 switch (stIdx) {
181 using enum StIndex;
182 case EM: {
183 if (std::abs(globPos.eta()) > 2.35 &&
184 std::abs(globPos.theta() - globDir.theta()) < 5.8_degree) {
185 return true;
186 }
187 break;
188 }
189 case EO: {
190 if (std::abs(globPos.eta()) > 2.35 &&
191 std::abs(globPos.theta() - globDir.theta()) < 3._degree) {
192 return true;
193 }
194 break;
195 }
196 default:
197 break;
198 }
199 using namespace Acts::detail::LineHelper;
200 const Acts::Intersection3D bsExtp = lineIntersect<3>(Amg::Vector3D::Zero(),
201 Amg::Vector3D::UnitZ(),
202 globPos, globDir);
203 const Amg::Vector3D closePoint = bsExtp.position();
204 const auto rawStIdx = Acts::toUnderlying(stIdx);
205 //coverity[NEGATIVE_RETURNS]
206 if (closePoint.perp() > m_seedMaxBsR.value().at(rawStIdx) * m_beamSpotR ||
207 std::abs(closePoint.z()) > m_seedMaxBsL.value().at(rawStIdx) * m_beamSpotL){
208 ATH_MSG_DEBUG("fitSegmentSeed() - Reject parameters "<<Amg::toString(tangentSeedPos)
209 <<" + "<<Amg::toString(tangentSeedDir)
210 <<" as extrapolation to beamspot is too far "<<Amg::toString(closePoint)
211 <<", r: "<<closePoint.perp());
212 return false;
213 }
214 return true;
215 }};
216
217 const auto* seeder = patternSeed->msSector()->chamberIndex() == ChIndex::BEE ?
218 m_seederBEE.get() : m_seeder.get();
219
221 if (m_visionTool.isEnabled()) {
222 PrimitiveVec seedLines{};
223 State_t drawMe{seedState};
224 while(auto s = seeder->nextSeed(cctx, drawMe)) {
225 seedLines.push_back(drawLine(s->parameters, -Gaudi::Units::m, Gaudi::Units::m, kViolet));
226 }
227 seedLines.push_back(drawLabel(std::format("possible seeds: {:d}", drawMe.nGenSeeds()), 0.2, 0.85, 14));
228 m_visionTool->visualizeSeed(ctx, *patternSeed, std::format("pattern_{:}{:}{:}",
229 patternSeed->msSector()->chamberIndex(),
230 patternSeed->msSector()->side() ? 'A' : 'C' ,
231 patternSeed->msSector()->sector()), std::move(seedLines));
232 }
233
234 ATH_MSG_VERBOSE("fitSegmentHits() - Start segment seed search");
235 while (auto seed = seeder->nextSeed(cctx, seedState)) {
236 ATH_MSG_VERBOSE("fitSegmentHits() - Found a seed. Try to fit the segment...");
237 // Back convert the seed parameters to athena units
238 seed->parameters[toUnderlying(ParamDefs::t0)] = ActsTrk::timeToAthena(seed->parameters[toUnderlying(ParamDefs::t0)]);
239
240 auto segment = m_fitter->fitSegment(ctx, patternSeed, seed->parameters,
241 locToGlob, std::move(seed->hits));
242 if (segment) {
243 segments.push_back(std::move(segment));
244 }
245 }
246 ATH_MSG_VERBOSE("fitSegmentHits() - In total "<<segments.size()<<" segment were constructed ");
247 return segments;
248
249 }
250
252 SegmentVec_t& segmentCandidates) const {
253 if (segmentCandidates.empty()) {
254 return;
255 }
256 ATH_MSG_VERBOSE("resolveAmbiguities() - Resolve ambiguities amongst "
257 <<segmentCandidates.size()<<" segment candidates.");
260
261 for (std::unique_ptr<Segment>& sortMe : segmentCandidates) {
262 const MuonGMR4::SpectrometerSector* chamb = sortMe->msSector();
263 candidatesPerChamber[chamb].push_back(std::move(sortMe));
264 }
265 segmentCandidates.clear();
266 for (auto& [chamber, resolveMe] : candidatesPerChamber) {
267 const std::size_t nBefore = resolveMe.size();
268 SegmentVec_t resolvedSegments = m_ambiSolver->resolveAmbiguity(gctx, std::move(resolveMe));
269 ATH_MSG_DEBUG("resolveAmbiguities() - "<<resolvedSegments.size()<<"/"<<nBefore
270 <<" segments survived ambiguity solving in "<<chamber->identString()<<".");
271 segmentCandidates.insert(segmentCandidates.end(),
272 std::make_move_iterator(resolvedSegments.begin()),
273 std::make_move_iterator(resolvedSegments.end()));
274 }
275 ATH_MSG_VERBOSE("Ambiguity solving done "<<segmentCandidates.size()<<" survived.");
276 }
277}
#define ATH_CHECK
Evaluate an expression and check for errors.
#define ATH_MSG_DEBUG(x,...)
#define ATH_MSG_ERROR(x,...)
#define ATH_MSG_VERBOSE(x,...)
bool hit(const Container &ids, int pdgId)
std::unique_ptr< const Acts::Logger > makeActsAthenaLogger(IMessageSvc *svc, const std::string &name, int level, std::optional< std::string > parent_name)
Definition Logger.cxx:64
size_type size() const noexcept
Returns the number of elements in the collection.
A spectrometer sector forms the envelope of all chambers that are placed in the same MS sector & laye...
int8_t side() const
Returns the side of the MS-sector 1 -> A side ; -1 -> C side.
const Acts::Transform3 & localToGlobalTransform(const ActsTrk::GeometryContext &gctx) const
Returns the local -> global tarnsformation from the sector.
int sector() const
Returns the sector of the MS-sector.
Muon::MuonStationIndex::ChIndex chamberIndex() const
Returns the chamber index scheme.
SeedingState< HitVec_t, CalibCont_t, SeederStateBase > State_t
Define the state holder object.
std::unique_ptr< SegmentFit::SegmentAmbiSolver > m_ambiSolver
Pointer to the ambiguity reosolution.
Gaudi::Property< unsigned > m_precHitCut
Minimum number of precision hits to accept the segment.
Gaudi::Property< bool > m_hessianResidual
Use the expliciit Hessian in the residual calculation.
virtual StatusCode initialize() override
Gaudi::Property< bool > m_recalibSeed
Toggle seed recalibration.
Gaudi::Property< double > m_seedHitChi2
Two mdt seeds are the same if their defining parameters match wihin.
Gaudi::Property< bool > m_useFastFitter
Use the fast Mdt fitter where possible.
ToolHandle< MuonValR4::IPatternVisualizationTool > m_visionTool
Pattern visualization tool.
Gaudi::Property< double > m_beamSpotL
Longitudinal covariance on the beam spo measurement.
Gaudi::Property< bool > m_recalibInFit
SG::WriteHandleKey< SegmentContainer > m_outSegments
SegmentVec_t fitSegmentSeed(const EventContext &ctx, const ActsTrk::GeometryContext &gctx, const SegmentSeed *seed) const
Fit the hits from the pattern seed to segment candidates.
Gaudi::Property< bool > m_fastPreFitter
The fast fitter is treated as a pre fitter.
std::unique_ptr< SegmentFit::MdtSegmentSeedGenerator > m_seederBEE
Pointer to the L-R segment seeder used for the BEE chambers -> increased hit occupancy.
void resolveAmbiguities(const ActsTrk::GeometryContext &gctx, SegmentVec_t &segmentCandidates) const
Resolve the ambiguity amongst the segment candidates within a spectrometer sector.
std::unique_ptr< SegmentFit::MdtSegmentSeedGenerator > m_seeder
Pointer to the L-R segment seeder.
ServiceHandle< Muon::IMuonIdHelperSvc > m_idHelperSvc
IdHelperSvc.
Gaudi::Property< bool > m_doBeamspotConstraint
Add beamline constraint.
ToolHandle< ISpacePointCalibrator > m_calibTool
Handle to the space point calibrator.
std::unique_ptr< SegmentFit::SegmentLineFitter > m_fitter
Pointer to the actual segment fitter.
std::vector< std::unique_ptr< Segment > > SegmentVec_t
Gaudi::Property< std::vector< double > > m_seedMaxBsL
Gaudi::Property< bool > m_ignoreFailedPreFit
Switch to try the full fit when the fast pre-fitter fails.
SegmentFit::Parameters Parameters
Gaudi::Property< bool > m_doT0Fit
static constexpr auto s_stIdxMax
SG::ReadHandleKey< SegmentSeedContainer > m_seedKey
ReadHandle of the seeds.
Gaudi::Property< std::vector< double > > m_seedMaxBsR
Maximum allowed distance of the segment seed line to the beam spot measurement expressed in relative ...
Gaudi::Property< double > m_recoveryPull
Gaudi::Property< double > m_beamSpotR
Radial covariance on th beam spot measurment.
Gaudi::Property< unsigned > m_maxIter
Tune the number of iterations.
virtual StatusCode execute(const EventContext &ctx) const override
ActsTrk::GeoContextReadKey_t m_geoCtxKey
Gaudi::Property< unsigned > m_busyLayerLimit
Cut on the number of hits per layer to use the layer for seeding.
Gaudi::Property< double > m_outlierRemovalCut
Cut on the segment chi2 / nDoF to launch the outlier removal.
Gaudi::Property< bool > m_tryPatternPars
Try first to fit the pattern parameters. Then proceed with the straw line tangents.
Representation of a segment seed (a fully processed hough maximum) produced by the hough transform.
Definition SegmentSeed.h:14
const Parameters & parameters() const
Returns the parameter array.
const MuonGMR4::SpectrometerSector * msSector() const
Returns the associated chamber.
Acts::CloneablePtr< CalibratedSpacePoint > MeasType
Calibrated space point type.
The muon space point is the combination of two uncalibrated measurements one of them measures the eta...
StatusCode record(std::unique_ptr< T > data)
Record a const object to the store.
constexpr double timeToAthena(T actsT)
Converts a time unit from Acts to Athena units.
Acts::CalibrationContext getCalibrationContext(const EventContext &ctx)
The Acts::Calibration context is piped through the Acts fitters to (re)calibrate the Acts::SourceLink...
std::string toString(const Translation3D &translation, int precision=4)
GeoPrimitvesToStringConverter.
double error(const Amg::MatrixX &mat, int index)
return diagonal error of the matrix caller should ensure the matrix is symmetric and the index is in ...
Eigen::Matrix< double, 3, 1 > Vector3D
Parameters localSegmentPars(const xAOD::MuonSegment &seg)
Returns the localSegPars decoration from a xAODMuon::Segment.
std::pair< Amg::Vector3D, Amg::Vector3D > makeLine(const Parameters &pars)
Returns the parsed parameters into an Eigen line parametrization.
This header ties the generic definitions in this package.
MuonValR4::IPatternVisualizationTool::PrimitiveVec PrimitiveVec
DataVector< SegmentSeed > SegmentSeedContainer
std::unique_ptr< TLine > drawLine(const MuonR4::SegmentFit::Parameters &pars, const double lowEnd, const double highEnd, const int color=kRed+1, const int lineStyle=kDashed, const int view=objViewEta)
Draws a line from the segment fit parameters.
std::unique_ptr< TLatex > drawLabel(const std::string &text, const double xPos, const double yPos, const double textSize=18, const bool useNDC=true, const int color=kBlack)
Create a TLatex label,.
StIndex
enum to classify the different station layers in the muon spectrometer
StIndex toStationIndex(ChIndex index)
convert ChIndex into StIndex
const T * get(const ReadCondHandleKey< T > &key, const EventContext &ctx)
Convenience function to retrieve an object given a ReadCondHandleKey.
Configuration object to stree the ambiguties.
const ISpacePointCalibrator * calibrator
Pointer to the calibrator.
bool doBeamSpot
Switch to insert a beamspot constraint if possible.
const Muon::IMuonIdHelperSvc * idHelperSvc
Pointer to the idHelperSvc.
unsigned nPrecHitCut
Minimum number of precision hits.
double outlierRemovalCut
Cut on the segment chi2 / nDoF to launch the outlier removal.
const MuonValR4::IPatternVisualizationTool * visionTool
Pointer to the visualization tool.
double recoveryPull
Maximum pull on a measurement to add it back on the line.
double beamSpotRadius
Parameters of the beamspot measurement.