18#include "Acts/Definitions/Units.hpp"
23using namespace Acts::UnitLiterals;
27 using namespace MuonValR4;
38 double etaEdgeTolerance = 25. * Gaudi::Units::mm,
39 double phiEdgeTolerance = 0.){
43 const double yCross = seed.interceptY() + (
z * seed.tanBeta());
44 if (loc.
minY() - etaEdgeTolerance > yCross || yCross > loc.
maxY() + etaEdgeTolerance) {
49 if (!seed.hasPhiExtension()) {
54 const double xCross = seed.interceptX() + (
z * seed.tanAlpha());
57 const double halfWidthX = loc.
width(yCross);
59 return ((loc.
location().x() - halfWidthX) + phiEdgeTolerance) < xCross && xCross < ((loc.
location().
x() + halfWidthX) - phiEdgeTolerance);
74 m_ambiSolver = std::make_unique<SegmentAmbiSolver>(name(), std::move(cfg));
94 std::ranges::min(prop->value()) < 0.) {
96 return StatusCode::FAILURE;
110 m_fitter = std::make_unique<SegmentFit::SegmentLineFitter>(name(), std::move(fitCfg));
112 MdtSegmentSeedGenerator::Config genCfg{};
127 return StatusCode::SUCCESS;
139 ATH_MSG_VERBOSE(__func__<<
"() "<<__LINE__<<
" - execute() - Start processing " << segmentSeeds->
size() <<
" pattern seeds.");
143 auto drawFinalReco = [
this, &segments, &gctx, &ctx,&seed](
const std::string& nameTag) {
145 double yLegend{0.85};
146 segmentLines.push_back(
drawLabel(std::format(
"# segments: {:d}", segments.size()), 0.2, yLegend, 14));
148 for (
const std::unique_ptr<Segment>& seg : segments) {
150 const auto [pos, dir] =
makeLine(pars);
151 segmentLines.emplace_back(
drawLine(pars, -Gaudi::Units::m, Gaudi::Units::m, kRed));
152 std::stringstream signStream{};
153 const auto& cov = seg->covariance();
154 signStream<<std::format(
"#chi^{{2}}/nDoF: {:.2f} ({:}), ", seg->chi2() / seg->nDoF(), seg->nDoF());
155 signStream<<std::format(
"y_{{0}}={:.2f}#pm{:.2f}",
156 pars[toUnderlying(ParamDefs::y0)],
157 Amg::error(cov, toUnderlying(ParamDefs::y0)))<<
", ";
158 signStream<<std::format(
"#theta={:.2f}#pm{:.2f}^{{#circ}}",
159 pars[toUnderlying(ParamDefs::theta)]/ 1._degree,
160 Amg::error(cov, toUnderlying(ParamDefs::theta)) / 1._degree )<<
", ";
163 m->fitState() == CalibratedSpacePoint::State::Valid) {
164 signStream<<(SeedingAux::strawSign(pos, dir, *m) == -1 ?
"L" :
"R");
167 segmentLines.push_back(
drawLabel(signStream.str(), 0.2, yLegend, 13));
171 m_visionTool->visualizeBucket(ctx, *seed->parentBucket(), nameTag, std::move(segmentLines));
173 drawFinalReco(
"all segments");
174 const unsigned int nBeforeAmbi = segments.size();
175 segments =
m_ambiSolver->resolveAmbiguity(*gctx, std::move(segments));
176 if (nBeforeAmbi != segments.size()) {
177 drawFinalReco(
"post ambiguity");
179 }
else if (
m_visionTool.isEnabled() && segments.empty() &&
180 std::ranges::any_of(seed->getHitsInMax(),[
this](
const SpacePoint*
hit){
181 return m_visionTool->isLabeled(*hit);
185 allSegments.insert(allSegments.end(), std::make_move_iterator(segments.begin()),
186 std::make_move_iterator(segments.end()));
189 writeSegments->insert(writeSegments->end(),
190 std::make_move_iterator(allSegments.begin()),
191 std::make_move_iterator(allSegments.end()));
192 ATH_MSG_VERBOSE(__func__<<
"() "<<__LINE__<<
" - Found in total "<<writeSegments->size()<<
" segments. ");
193 return StatusCode::SUCCESS;
202 std::vector<std::unique_ptr<Segment>> segments{};
216 const Amg::Vector3D globDir{locToGlob.linear()*tangentSeedDir};
224 if (std::abs(globPos.eta()) > 2.35 &&
225 std::abs(globPos.theta() - globDir.theta()) < 5.8_degree) {
231 if (std::abs(globPos.eta()) > 2.35 &&
232 std::abs(globPos.theta() - globDir.theta()) < 3._degree) {
240 using namespace Acts::detail::LineHelper;
241 const Acts::Intersection3D bsExtp = lineIntersect<3>(Amg::Vector3D::Zero(),
242 Amg::Vector3D::UnitZ(),
245 const auto rawStIdx = Acts::toUnderlying(stIdx);
251 <<
" as extrapolation to beamspot is too far "<<
Amg::toString(closePoint)
252 <<
", r: "<<closePoint.perp());
261 auto visualizeSegmentSeeds = [&](State_t& state,
const std::string_view
label) {
264 State_t drawMe{state};
265 while(
auto s =
m_seeder->nextSeed(cctx, drawMe)) {
266 seedLines.push_back(
drawLine(s->parameters, -Gaudi::Units::m, Gaudi::Units::m, kViolet));
268 seedLines.push_back(
drawLabel(std::format(
"{} possible seeds: {:d}",
label, drawMe.nGenSeeds()), 0.2, 0.85, 14));
269 m_visionTool->visualizeSeed(ctx, *patternSeed, std::format(
"pattern_{:}{:}{:}",
276 auto runSeeder = [&](State_t&& state) {
277 while (
auto seed =
m_seeder->nextSeed(cctx, state)) {
278 seed->parameters[toUnderlying(ParamDefs::t0)] =
ActsTrk::timeToAthena( seed->parameters[toUnderlying(ParamDefs::t0)]);
279 auto segment =
m_fitter->fitSegment(ctx, patternSeed, seed->parameters, locToGlob, std::move(seed->hits));
281 segments.push_back(std::move(segment));
286 visualizeSegmentSeeds(seedState,
"Nominal Seeds");
287 ATH_MSG_VERBOSE(__func__<<
"() "<<__LINE__<<
" - fitSegmentHits() - Start segment seed search");
288 runSeeder(std::move(seedState));
297 ATH_MSG_VERBOSE(__func__<<
"() "<<__LINE__<<
" - fitSegmentSeed() - Standard MDT seeding failed. " "Trying ML fallback.");
300 std::optional<SpacePointPerLayerSplitter::HitVec> recoveryHits{};
306 ATH_MSG_VERBOSE(__func__<<
":" <<__LINE__<<
"- BIL recovery did not succeed. Try BIM/BIR.");
312 ATH_MSG_VERBOSE(__func__<<
"() "<<__LINE__<<
" - fitSegmentSeed() - ML seeding fallback has " << recoveryHits->size() <<
" hits.");
314 visualizeSegmentSeeds(fallbackState ,
"Fallback Seeds");
315 runSeeder(std::move(fallbackState));
318 ATH_MSG_VERBOSE(__func__<<
"() "<<__LINE__<<
" - fitSegmentHits() - In total "<<segments.size()<<
" segment were constructed ");
325 if (segmentCandidates.empty()) {
328 ATH_MSG_VERBOSE(__func__<<
"() "<<__LINE__<<
" - resolveAmbiguities() - Resolve ambiguities amongst "
329 <<segmentCandidates.size()<<
" segment candidates.");
333 for (std::unique_ptr<Segment>& sortMe : segmentCandidates) {
335 candidatesPerChamber[chamb].push_back(std::move(sortMe));
337 segmentCandidates.clear();
338 for (
auto& [chamber, resolveMe] : candidatesPerChamber) {
339 const std::size_t nBefore = resolveMe.size();
341 ATH_MSG_DEBUG(
"resolveAmbiguities() - "<<resolvedSegments.size()<<
"/"<<nBefore
342 <<
" segments survived ambiguity solving in "<<chamber->identString()<<
".");
343 segmentCandidates.insert(segmentCandidates.end(),
344 std::make_move_iterator(resolvedSegments.begin()),
345 std::make_move_iterator(resolvedSegments.end()));
347 ATH_MSG_VERBOSE(__func__<<
"() "<<__LINE__<<
" - Ambiguity solving done "<<segmentCandidates.size()<<
" survived.");
351std::optional<SpacePointPerLayerSplitter::HitVec>
359 for (
const auto& chamber : seed.parentBucket()->chamberLocations()) {
361 const auto* readoutEle = chamber.readoutEle();
375 crossedRE = readoutEle;
377 ATH_MSG_VERBOSE(__func__<<
"() "<<__LINE__<<
" - BIL recovery: Hough trajectory crosses "
383 ATH_MSG_VERBOSE(__func__<<
"() "<<__LINE__<<
" - BIL recovery rejected: trajectory crosses no BIL readout elements.");
388 recoveryHits.reserve(seed.getHitsInMax().size());
390 std::size_t nMdtHits{0};
396 recoveryHits.push_back(
hit);
400 if (
hit->primaryMeasurement()->readoutElement() != crossedRE) {
403 recoveryHits.push_back(
hit);
416 if (!seed.hasPhiExtension()) {
417 ATH_MSG_VERBOSE(
"BIM/BIR recovery rejected: seed has no phi extension.");
429 std::optional<int> recoveryStation{};
431 for (
const auto& chamber : seed.parentBucket()->chamberLocations()) {
433 const auto* readoutEle = chamber.readoutEle();
439 const int station = mdtHelper.stationName(
id);
453 if (!recoveryStation) {
454 recoveryStation = station;
463 if (*recoveryStation != station){
464 ATH_MSG_VERBOSE(__func__<<
"() "<<__LINE__<<
" - BIM/BIR recovery rejected: crossed readout " "elements belong to different station/phi regions.");
469 if (!recoveryStation) {
482 recoveryHits.reserve(seed.getHitsInMax().size());
484 std::size_t nMdtHits{0};
488 recoveryHits.push_back(
hit);
493 if (mdtHelper.stationName(hitId) != *recoveryStation) {
496 recoveryHits.push_back(
hit);
502 ATH_MSG_VERBOSE(__func__<<
"() "<<__LINE__<<
" - BIM/BIR recovery selected " << nMdtHits <<
" MDT hits from station " << mdtHelper.stationNameString(*recoveryStation));
#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,...)
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.
MuonReadoutElement is an abstract class representing the geometry of a muon detector.
Identifier identify() const override final
Return the ATLAS identifier.
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.
std::optional< SpacePointPerLayerSplitter::HitVec > makeBimBirRecoveryHits(const SegmentSeed &seed) const
BIM/BIR chambers are treated as the same sector, however, they don't overlap in many instances.
int m_birStation
Cached BIR station index for quick access.
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.
virtual ~SegmentFittingAlg()
int m_bimStation
Cached BIM station index for quick access.
int m_bilStation
Cached BIL station index for quick access.
Gaudi::Property< bool > m_allowSegmentSeedingFallback
Allow single multilayer fallback when standard segment reconstruction fails.
Gaudi::Property< bool > m_fastPreFitter
The fast fitter is treated as a pre fitter.
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.
Gaudi::Property< double > m_singleMlEdgeTolerance
Tolerance for the single multilayer edge crossing test, if the trajectory only slighty nicks the seco...
ServiceHandle< Muon::IMuonIdHelperSvc > m_idHelperSvc
IdHelperSvc.
Gaudi::Property< bool > m_doBeamspotConstraint
Add beamline constraint.
Gaudi::Property< double > m_singleMlPhiEdgeTolerance
Tolerance for the single multilayer edge crossing test in the phi projection in case the trajectory o...
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
std::optional< SpacePointPerLayerSplitter::HitVec > makeBilRecoveryHits(const SegmentSeed &seed) const
For BIL (specifically around eta3 chambers), there are cases where only a single multilayer is crosse...
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.
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.
MuonGMR4::SpectrometerSector::chamberLocation chamberLocation
std::vector< const SpacePoint * > HitVec
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.
std::string label(const std::string &format, int i)
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...
This class is not to needed in AthSimulation.
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.
bool trajectoryPassesThroughChamber(const SpacePointBucket::chamberLocation &loc, const SegmentSeed &seed, double etaEdgeTolerance=25. *Gaudi::Units::mm, double phiEdgeTolerance=0.)
brief checks if the trajectory passes through the given chamber in local y,z plane if phiExtension is...
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.
Helper struct to ensure that the spectrometer sectors & chambers are sorted.
double width(const double y0) const
Calculate the strip / tube length at a given position in the y-z plane.
double maxY() const
Returns the maximum u covered by the chamber location.
double minY() const
Returns the minimum y covered by the chamber location.
const Amg::Vector3D & location() const
Returns the location.
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.
Full configuration object.