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
5#include "SegmentFittingAlg.h"
6
8
12#include <ActsInterop/Logger.h>
13
15
16#include <format>
17
18using namespace Acts;
19namespace MuonR4 {
20 using namespace SegmentFit;
21 using namespace MuonValR4;
22
24
27 ATH_CHECK(m_geoCtxKey.initialize());
28 ATH_CHECK(m_seedKey.initialize());
29 ATH_CHECK(m_outSegments.initialize());
30 ATH_CHECK(m_calibTool.retrieve());
31 ATH_CHECK(m_idHelperSvc.retrieve());
32 ATH_CHECK(m_visionTool.retrieve(EnableTool{!m_visionTool.empty()}));
34 m_ambiSolver = std::make_unique<SegmentAmbiSolver>(name(), std::move(cfg));
35
37 fitCfg.calibrator = m_calibTool.get();
38 fitCfg.visionTool = m_visionTool.get();
39 fitCfg.idHelperSvc = m_idHelperSvc.get();
40 fitCfg.fitT0 = m_doT0Fit;
41 fitCfg.recalibrate = m_recalibInFit;
42 fitCfg.useFastFitter = m_useFastFitter;
43 fitCfg.fastPreFitter = m_fastPreFitter;
44 //fitCfg.ignoreFailedPreFit = m_ignoreFailedPreFit;
45 fitCfg.useHessian = m_hessianResidual;
46
50
54 fitCfg.maxIter = m_maxIter;
55 ATH_MSG_DEBUG("Fitter configuration: \n - fitT0: "<<m_doT0Fit
56 <<"\n - recalibInFit: "<<m_recalibInFit
57 <<"\n - useFastFitter: "<<m_useFastFitter
58 <<"\n - fastPreFitter: "<<m_fastPreFitter
59 <<"\n - ignoreFailedPreFit: "<<m_ignoreFailedPreFit
60 <<"\n - hessianResidual: "<<m_hessianResidual
61 <<"\n - doBeamSpotConstraint: "<<m_doBeamspotConstraint
62 <<"\n - beamSpotR: "<<m_beamSpotR
63 <<"\n - beamSpotL: "<<m_beamSpotL
64 <<"\n - outlierRemovalCut: "<<m_outlierRemovalCut
65 <<"\n - recoveryPull: "<<m_recoveryPull
66 <<"\n - precHitCut: "<<m_precHitCut
67 <<"\n - maxIter: "<<m_maxIter);
68
69 m_fitter = std::make_unique<SegmentFit::SegmentLineFitter>(name(), std::move(fitCfg));
70
71 MdtSegmentSeedGenerator::Config genCfg{};
72 genCfg.hitPullCut = m_seedHitChi2;
73 genCfg.busyLayerLimit = m_busyLayerLimit;
74 genCfg.startWithPattern = m_tryPatternPars;
75 ATH_MSG_DEBUG("Seeder configuration: \n - "<<m_tryPatternPars
76 <<"\n - "<<m_seedHitChi2
77 <<"\n - "<<m_busyLayerLimit);
78 m_seeder = std::make_unique<SegmentFit::MdtSegmentSeedGenerator>(genCfg, makeActsAthenaLogger(this, name()));
79 genCfg.busyLayerLimit += 2;
80 m_seederBEE = std::make_unique<SegmentFit::MdtSegmentSeedGenerator>(genCfg, makeActsAthenaLogger(this, name()));
81
82 return StatusCode::SUCCESS;
83 }
84 StatusCode SegmentFittingAlg::execute(const EventContext& ctx) const {
85 const ActsTrk::GeometryContext* gctx{nullptr};
86 ATH_CHECK(SG::get(gctx, m_geoCtxKey, ctx));
87 const SegmentSeedContainer* segmentSeeds=nullptr;
88 ATH_CHECK(SG::get(segmentSeeds, m_seedKey, ctx));
89
90 SG::WriteHandle writeSegments{m_outSegments, ctx};
91 ATH_CHECK(writeSegments.record(std::make_unique<SegmentContainer>()));
92 SegmentVec_t allSegments{};
93 ATH_MSG_VERBOSE("execute() - Start processing " << segmentSeeds->size() << " pattern seeds.");
94 for (const SegmentSeed* seed : *segmentSeeds) {
95 SegmentVec_t segments = fitSegmentSeed(ctx, *gctx, seed);
96 if (m_visionTool.isEnabled() && segments.size() > 1) {
97 auto drawFinalReco = [this, &segments, &gctx, &ctx,&seed](const std::string& nameTag) {
98 PrimitiveVec segmentLines{};
99 double yLegend{0.85};
100 segmentLines.push_back(drawLabel(std::format("# segments: {:d}", segments.size()), 0.2, yLegend, 14));
101 yLegend-=0.04;
102 for (const std::unique_ptr<Segment>& seg : segments) {
103 const Parameters pars = localSegmentPars(*gctx, *seg);
104 const auto [pos, dir] = makeLine(pars);
105 segmentLines.emplace_back(drawLine(pars, -Gaudi::Units::m, Gaudi::Units::m, kRed));
106 std::stringstream signStream{};
107 signStream<<std::format("#chi^{{2}}/nDoF: {:.2f} ({:}), ", seg->chi2() / seg->nDoF(), seg->nDoF());
108 signStream<<std::format("y_{{0}}={:.2f}",pars[toUnderlying(ParamDefs::y0)])<<", ";
109 signStream<<std::format("#theta={:.2f}^{{#circ}}", pars[toUnderlying(ParamDefs::theta)]/ Gaudi::Units::deg )<<", ";
110 for (const Segment::MeasType& m : seg->measurements()) {
111 if (m->type() == xAOD::UncalibMeasType::MdtDriftCircleType && m->fitState() == CalibratedSpacePoint::State::Valid) {
112 signStream<<(SeedingAux::strawSign(pos, dir, *m) == -1 ? "L" : "R");
113 }
114 }
115 segmentLines.push_back(drawLabel(signStream.str(), 0.2, yLegend, 13));
116 yLegend-=0.03;
117 }
118
119 m_visionTool->visualizeBucket(ctx, *seed->parentBucket(), nameTag, std::move(segmentLines));
120 };
121 drawFinalReco("all segments");
122 const unsigned int nBeforeAmbi = segments.size();
123 segments = m_ambiSolver->resolveAmbiguity(*gctx, std::move(segments));
124 if (nBeforeAmbi != segments.size()) {
125 drawFinalReco("post ambiguity");
126 }
127 } else if (m_visionTool.isEnabled() && segments.empty() &&
128 std::ranges::count_if(seed->getHitsInMax(),[this](const SpacePoint* hit){
129 return m_visionTool->isLabeled(*hit);
130 })) {
131 m_visionTool->visualizeSeed(ctx, *seed, "Failed fit");
132 }
133 allSegments.insert(allSegments.end(), std::make_move_iterator(segments.begin()),
134 std::make_move_iterator(segments.end()));
135 }
136 resolveAmbiguities(*gctx, allSegments);
137 writeSegments->insert(writeSegments->end(),
138 std::make_move_iterator(allSegments.begin()),
139 std::make_move_iterator(allSegments.end()));
140 ATH_MSG_VERBOSE("Found in total "<<writeSegments->size()<<" segments. ");
141 return StatusCode::SUCCESS;
142 }
143
145 SegmentFittingAlg::fitSegmentSeed(const EventContext& ctx,
146 const ActsTrk::GeometryContext& gctx,
147 const SegmentSeed* patternSeed) const {
148
149 const Amg::Transform3D& locToGlob{patternSeed->msSector()->localToGlobalTransform(gctx)};
150 std::vector<std::unique_ptr<Segment>> segments{};
151
152 Acts::CalibrationContext cctx = ActsTrk::getCalibrationContext(ctx);
153
154 using State_t = MdtSegmentSeedGenerator::State_t;
155 // Make sure patternSeed->parameters() are in ACTS units!
156 State_t seedState{patternSeed->parameters(), patternSeed, m_calibTool.get(), m_recalibSeed};
157
158 const auto* seeder = patternSeed->parameters()[toUnderlying(ParamDefs::theta)] > 50 * Gaudi::Units::deg ?
159 m_seederBEE.get() : m_seeder.get();
160
162 if (m_visionTool.isEnabled()) {
163 PrimitiveVec seedLines{};
164 State_t drawMe{seedState};
165 while(auto s = seeder->nextSeed(cctx, drawMe)) {
166 seedLines.push_back(drawLine(s->parameters, -Gaudi::Units::m, Gaudi::Units::m, kViolet));
167 }
168 seedLines.push_back(drawLabel(std::format("possible seeds: {:d}", drawMe.nGenSeeds()), 0.2, 0.85, 14));
169 m_visionTool->visualizeSeed(ctx, *patternSeed, "pattern", std::move(seedLines));
170 }
171
172 ATH_MSG_VERBOSE("fitSegmentHits() - Start segment seed search");
173 while (auto seed = seeder->nextSeed(cctx, seedState)) {
174 ATH_MSG_VERBOSE("fitSegmentHits() - Found a seed. Try to fit the segment...");
175 // Back convert the seed parameters to athena units
176 seed->parameters[toUnderlying(ParamDefs::t0)] = ActsTrk::timeToAthena(seed->parameters[toUnderlying(ParamDefs::t0)]);
177 auto segment = m_fitter->fitSegment(ctx, patternSeed, seed->parameters,
178 locToGlob, std::move(seed->hits));
179 if (segment) {
180 segments.push_back(std::move(segment));
181 }
182 }
183 ATH_MSG_VERBOSE("fitSegmentHits() - In total "<<segments.size()<<" segment were constructed ");
184 return segments;
185
186 }
187
189 SegmentVec_t& segmentCandidates) const {
190 if (segmentCandidates.empty()) {
191 return;
192 }
193 ATH_MSG_VERBOSE("Resolve ambiguities amongst "<<segmentCandidates.size()<<" segment candidates. ");
194 std::unordered_map<const MuonGMR4::SpectrometerSector*, SegmentVec_t> candidatesPerChamber{};
195
196 for (std::unique_ptr<Segment>& sortMe : segmentCandidates) {
197 const MuonGMR4::SpectrometerSector* chamb = sortMe->msSector();
198 candidatesPerChamber[chamb].push_back(std::move(sortMe));
199 }
200 segmentCandidates.clear();
201 for (auto& [chamber, resolveMe] : candidatesPerChamber) {
202 SegmentVec_t resolvedSegments = m_ambiSolver->resolveAmbiguity(gctx, std::move(resolveMe));
203 segmentCandidates.insert(segmentCandidates.end(),
204 std::make_move_iterator(resolvedSegments.begin()),
205 std::make_move_iterator(resolvedSegments.end()));
206 }
207 }
208}
#define ATH_CHECK
Evaluate an expression and check for errors.
#define ATH_MSG_VERBOSE(x)
#define ATH_MSG_DEBUG(x)
std::unique_ptr< const Acts::Logger > makeActsAthenaLogger(IMessageSvc *svc, const std::string &name, int level, std::optional< std::string > parent_name)
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...
const Amg::Transform3D & localToGlobalTransform(const ActsTrk::GeometryContext &gctx) const
Returns the local -> global tarnsformation from the sector.
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
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< bool > m_ignoreFailedPreFit
Switch to try the full fit when the fast pre-fitter fails.
SegmentFit::Parameters Parameters
Gaudi::Property< bool > m_doT0Fit
SG::ReadHandleKey< SegmentSeedContainer > m_seedKey
ReadHandle of the seeds.
Gaudi::Property< double > m_recoveryPull
Gaudi::Property< double > m_beamSpotR
Gaudi::Property< unsigned > m_maxIter
Tune the number of iterations.
virtual StatusCode execute(const EventContext &ctx) const override
SG::ReadHandleKey< ActsTrk::GeometryContext > 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.
std::unique_ptr< 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(const double 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...
Eigen::Affine3d Transform3D
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,.
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.