20 if (newSegment.
nDoF() == oldSegment.
nDoF()) {
21 return newSegment.
chi2() < oldSegment.
chi2();
23 return newSegment.
nDoF() > oldSegment.
nDoF();
27 unsigned countNSWHits(
const std::vector<const MuonR4::SpacePoint*>& hits,
49using namespace Muon::MuonStationIndex;
50using namespace MuonR4::SegmentFit;
51using namespace Acts::UnitLiterals;
53constexpr auto phiIdx {Acts::toUnderlying(ParamDefs::phi)};
54constexpr auto x0Idx {Acts::toUnderlying(ParamDefs::x0)};
55constexpr auto thetaIdx {Acts::toUnderlying(ParamDefs::theta)};
56constexpr auto y0Idx {Acts::toUnderlying(ParamDefs::y0)};
67 fitCfg.calcAlongStrip =
false;
68 fitCfg.recalibrate = config.recalibInFit;
69 fitCfg.useFastFitter = config.useFastFitter;
70 fitCfg.fastPreFitter = config.fastPreFitter;
71 fitCfg.ignoreFailedPreFit = config.ignoreFailedPreFit;
72 fitCfg.useHessian = config.useHessianResidual;
77 fitCfg.maxIter = config.maxIter;
78 fitCfg.parsToUse = {ParamDefs::y0, ParamDefs::theta};
82 nswFitCfg.parsToUse = {ParamDefs::x0, ParamDefs::y0, ParamDefs::theta, ParamDefs::phi};
84 m_fitter = std::make_unique<LineFitter>(name, std::move(fitCfg));
85 m_nswFitter = std::make_unique<LineFitter>(name, std::move(nswFitCfg));
88 MdtSegmentSeeder::Config genCfg{};
89 genCfg.hitPullCut = config.seedHitChi2;
90 genCfg.busyLayerLimit = 3.;
91 genCfg.startWithPattern =
false;
97 m_trackSeeder = std::make_unique<MsTrackSeeder>(name, std::move(trackCfg));
108 std::vector<StIndex> stations {pattern.getStations()};
114 return layerRank(l1) < layerRank(l2);
117 std::vector<Segment_t> muonSegments{};
118 for (
const StIndex st : stations) {
120 if (muonSegments.size() > 2) {
125 if (std::ranges::any_of(muonSegments, [&layer](
const Segment_t& seg) {
127 seg->measurements().back()->spacePoint()->msSector()->chamberIndex()) == layer; })) {
128 ATH_MSG_VERBOSE(__func__<<
"() Already found a segment in layer " << layer
129 <<
" - skip station " << st);
133 const HitVec_t& hits {pattern.hitsInStation(st)};
134 const std::vector<Bucket_t>& buckets {pattern.bucketsInStation(st)};
137 std::unordered_map<const MuonGMR4::SpectrometerSector*, HitVec_t> hitsPerSector{};
138 std::ranges::for_each(hits, [&hitsPerSector](
Hit_t hit) {
139 hitsPerSector[hit->
msSector()].push_back(hit);
143 std::vector<const MuonGMR4::SpectrometerSector*> sectorsInStation{};
144 sectorsInStation.reserve(hitsPerSector.size());
145 std::ranges::transform(hitsPerSector, std::back_inserter(sectorsInStation),
146 [](
const auto&
pair) {
return pair.first; });
147 std::ranges::sort(sectorsInStation, std::ranges::greater{},
149 return hitsPerSector[s].size(); });
151 std::vector<Segment_t> stSegments{};
155 ATH_MSG_VERBOSE(__func__<<
"() Start segment fitting in sector " << sector->identString()
156 <<
" station " << st <<
" with " << hitsPerSector[sector].size() <<
" hits.");
157 const HitVec_t& sectorHits {hitsPerSector[sector]};
161 std::vector<Bucket_t> bucketsInSector {};
162 std::ranges::copy_if(buckets, std::back_inserter(bucketsInSector),
165 if (bucketsInSector.empty()) {
166 throw std::runtime_error(std::format(
"No parent bucket found for sector {} in station {}", sector->identString(),
stName(st)));
168 Bucket_t parentBucket {bucketsInSector.size() < 2u ? bucketsInSector.back()
169 : *std::ranges::max_element(bucketsInSector, std::ranges::less{}, [§orHits](
const Bucket_t& b) {
170 return std::ranges::count_if(sectorHits, [&b](
const Hit_t& hit) {
171 return std::ranges::any_of(*b, [&hit](
const auto&
h) {
172 return h.get() == hit; });
176 Segment_t segment {
fitSegment(ctx, sector->localToGlobalTransform(gctx), parentBucket, std::move(hitsPerSector[sector]))};
178 ATH_MSG_VERBOSE(__func__<<
"() Successfully fitted segment in station "<< st <<
": Pos: "
180 <<
", chi2: "<< segment->chi2()<<
", nDoF: "<<segment->nDoF()<<std::endl <<
print(segment->measurements()));
181 stSegments.push_back(std::move(segment));
183 if (calcRedChi2(*stSegments.back()) <=
m_cfg.goodSegmentCut) {
188 ATH_MSG_VERBOSE(__func__<<
"() No segment could be fitted. Try next sector, if any.");
190 if (stSegments.empty()) {
191 ATH_MSG_DEBUG(
"No segment could be fitted in station " << st <<
" for pattern" << pattern);
194 Segment_t& bestStSegment {stSegments.size() > 1
195 ? *std::ranges::max_element(stSegments, [](
const Segment_t& s1,
const Segment_t& s2) {
196 return betterSegment(*s2, *s1); })
197 : stSegments.back()};
199 <<
", dir: " <<
Amg::toString(bestStSegment->direction()) <<
", chi2: " << bestStSegment->chi2() <<
", nDoF: " << bestStSegment->nDoF());
201 muonSegments.push_back(std::move(bestStSegment));
204 ATH_MSG_VERBOSE(__func__<<
"() Found "<< muonSegments.size()<<
" muon segments to construct a candidate.");
205 if (muonSegments.size() < 2) {
206 ATH_MSG_DEBUG(__func__<<
"() Not enough muon segments to construct a candidate - abort.");
210 std::ranges::sort(muonSegments, std::ranges::less{},
211 [](
const Segment_t& seg) {
return seg->position().perp(); });
213 const Amg::Vector3D planeNorm {Acts::makeDirectionFromPhiTheta(pattern.phi() + 90._degree, 90._degree)};
214 auto point = [&planeNorm,
this](
const Segment_t& seg) {
215 int sector {seg->measurements().back()->spacePoint()->msSector()->sector()};
216 return std::make_pair(
m_trackSeeder->segPosOntoPhiPlane(planeNorm, sector, seg->position()),
217 m_trackSeeder->segDirOntoPhiPlane(planeNorm, seg->direction()));
220 assert(muonSegments.size() <= 3);
221 const double qtimesP {muonSegments.size() == 3
222 ?
m_trackSeeder->estimateQtimesP(magField, planeNorm, point(muonSegments[0]), point(muonSegments[1]), point(muonSegments[2]))
223 :
m_trackSeeder->estimateQtimesP(magField, planeNorm, point(muonSegments[0]), point(muonSegments[1]))};
225 const double theta {muonSegments[0]->position().theta()};
226 const double eta {-std::log(std::tan(
theta/2.))};
227 const double pt {std::abs(qtimesP) * std::sin(
theta)};
229 xAOD::Muon* newMuon = outMuons->push_back(std::make_unique<xAOD::Muon>());
230 newMuon->
setAuthor(xAOD::Muon::Author::MuidSA);
231 newMuon->
setP4(pt,
eta, pattern.phi());
232 newMuon->
setCharge(qtimesP > 0. ? 1 : -1);
233 newMuon->
setMuonType(xAOD::Muon::MuonType::MuonStandAlone);
240 std::vector<Hit_t>&& hits)
const {
242 const unsigned firstLayer {
m_spSorter.sectorLayerNum(*hits.front())};
243 if (hits.size() < 2 ||
244 std::ranges::none_of(hits, [&](
Hit_t hit) {
245 return m_spSorter.sectorLayerNum(*hit) != firstLayer; })) {
246 ATH_MSG_DEBUG(__func__<<
"() Not enough layers with hits to fit a segment, skipping!");
253 initialPars[
phiIdx] = 90._degree;
254 initialPars[
x0Idx] = 0;
258 if (
const unsigned nNSWhits {countNSWHits(hits, parentBucket)}; nNSWhits > 0) {
260 if (nNSWhits < hits.size()) {
261 ATH_MSG_DEBUG(__func__<<
"() Mixed hit types: "<<nNSWhits<<
" NSW over "
262 <<hits.size()<<
" total hits in the segment seed.");
264 std::vector<Hit_t> selHits{};
265 const bool useNSW {nNSWhits > (hits.size() - nNSWhits)};
266 std::ranges::copy_if(hits, std::back_inserter(selHits), [useNSW](
Hit_t hit) {
272 const auto [locPos, locDir] {
makeLine(initialPars)};
274 <<
", hits: "<<
print(validHits));
276 auto houghSeed {std::make_unique<SegmentSeed>(0., 0., 0., 0., 0., std::move(validHits), parentBucket)};
280 return m_nswFitter->fitSegment(ctx, houghSeed.get(), initialPars, localToGlobal, std::move(calibHits));
285 auto houghSeed {std::make_unique<SegmentSeed>(0., 0., 0., 0., 0., std::move(hits), parentBucket)};
286 std::vector<Segment_t> segments{};
290 while (
auto seed =
m_mdtSeeder->nextSeed(cctx, seedState)) {
291 ATH_MSG_VERBOSE(__func__<<
"() Found a seed. Try to fit the segment...");
294 localToGlobal, std::move(seed->hits))};
296 segments.push_back(std::move(segment));
300 if (!segments.empty()) {
301 ATH_MSG_VERBOSE(__func__<<
"() In total "<<segments.size()<<
" segment were constructed. Keep the best one.");
302 if (
msgLvl(MSG::VERBOSE) && segments.size() > 1) {
305 <<
", dir: "<<
Amg::toString(seg->direction())<<
", chi2: "<<seg->chi2()
306 <<
", nDoF: "<<seg->nDoF()<<std::endl<<
print(seg->measurements()));
309 return std::move(*std::ranges::max_element(segments, [&](
const Segment_t& s1,
const Segment_t& s2) {
310 return betterSegment(*s2, *s1);
320 double S {0.}, Sy {0.}, Sz {0.}, Szz {0.}, Syz {0.};
322 for (
const auto& hit : hits) {
324 const double z {locPos.z()};
325 const double y {locPos.y()};
326 const double sigma2 {hit->covariance()[
etaCovIdx]};
328 ATH_MSG_WARNING(__func__<<
"() Hit"<< *hit<<
" with very small eta covariance: " << sigma2 <<
". Skipping the measurement.");
331 validHits.push_back(hit);
332 const double w {1./sigma2};
340 const double det {S * Szz - Sz * Sz};
342 if (std::abs(det) < 1e-6) {
343 ATH_MSG_VERBOSE(__func__<<
"() Degenerate weigthed regression, using furthest hits...");
344 const auto [minZHit, maxZHit] = std::ranges::minmax_element(hits, std::ranges::less{},
345 [](
const Hit_t&
h) {
return h->localPosition().z(); });
346 const Amg::Vector3D& minLocPos {(*minZHit)->localPosition()};
347 const Amg::Vector3D& maxLocPos {(*maxZHit)->localPosition()};
348 const double deltaZ {maxLocPos.z() - minLocPos.z()};
350 assert(std::abs(deltaZ) > 1e-3);
352 pars[
thetaIdx] = std::atan2(maxLocPos.y() - minLocPos.y(), deltaZ);
353 pars[
y0Idx] = minLocPos.y() - std::tan(pars[
thetaIdx]) * minLocPos.z();
356 const double slope { (S * Syz - Sz * Sy) / det };
357 const double intercept { (Szz * Sy - Sz * Syz) / det };
360 pars[
y0Idx] = intercept;
Scalar eta() const
pseudorapidity method
Scalar theta() const
theta method
#define ATH_MSG_VERBOSE(x)
#define ATH_MSG_WARNING(x)
std::unique_ptr< const Acts::Logger > makeActsAthenaLogger(IMessageSvc *svc, const std::string &name, int level, std::optional< std::string > parent_name)
bool msgLvl(const MSG::Level lvl) const
Test the output level.
AthMessaging(IMessageSvc *msgSvc, const std::string &name)
Constructor.
A spectrometer sector forms the envelope of all chambers that are placed in the same MS sector & laye...
Muon::MuonStationIndex::ChIndex chamberIndex() const
Returns the chamber index scheme.
std::vector< Hit_t > HitVec_t
HitVec_t estimateBendingPars(HitVec_t &&hits, Parameters &pars) const
Estimate the bending parameters of a segment through a weighted linear regression.
std::unique_ptr< MdtSegmentSeeder > m_mdtSeeder
Pointer to the L-R segment seeder.
FastMuonSABuilder(const std::string &name, Config &&config)
Standard constructor.
Muon::MuonStationIndex::StIndex StIndex
Type alias for the station index.
std::unique_ptr< Segment > Segment_t
Type alias for the segment type.
SpacePointPerLayerSorter m_spSorter
Spacepoint sorter per logical measurement layer.
std::unique_ptr< LineFitter > m_fitter
Pointer to the actual segment fitter.
const SpacePoint * Hit_t
Type alias for the hit type & associated vector.
const SpacePointBucket * Bucket_t
Type alias for the bucket type.
std::unique_ptr< MsTrackSeeder > m_trackSeeder
Pointer to the track seeder for momentum estimate.
Segment_t fitSegment(const EventContext &ctx, const Amg::Transform3D &localToGlobal, Bucket_t parentBucket, std::vector< Hit_t > &&hits) const
Fit a segment using the provided seed.
std::unique_ptr< LineFitter > m_nswFitter
Pointer to the NSW segment fitter.
Config m_cfg
Global Pattern Recognition configuration.
xAOD::FillContainer< xAOD::MuonContainer, xAOD::MuonAuxContainerR4 > MuonCont_t
Define the muon container type.
xAOD::Muon * buildMuonCandidate(const EventContext &ctx, const ActsTrk::GeometryContext &gctx, const AtlasFieldCacheCondObj &magField, const GlobalPattern &pattern, MuonCont_t &outMuons) const
Main methods steering the muon candidate building.
SegmentFit::Parameters Parameters
Type alias for the segment fitting parameters.
Data class to represent an eta maximum in hough space.
std::vector< CalibSpacePointPtr > CalibSpacePointVec
SeedingState< HitVec_t, CalibCont_t, SeederStateBase > State_t
Define the state holder object.
Placeholder for what will later be the muon segment EDM representation.
unsigned int nDoF() const
Returns the number of degrees of freedom.
double chi2() const
Returns the chi2 of the segment fit.
: The muon space point bucket represents a collection of points that will bre processed together in t...
const MuonGMR4::SpectrometerSector * msSector() const
returns th associated muonChamber
The muon space point is the combination of two uncalibrated measurements one of them measures the eta...
xAOD::UncalibMeasType type() const
const MuonGMR4::SpectrometerSector * msSector() const
void setAuthor(const Author auth)
set author
void setMuonType(MuonType type)
void setP4(double pt, double eta, double phi)
Set method for IParticle values.
void setCharge(float charge)
Set the charge (must be the same as primaryTrackParticle() ).
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.
Eigen::Affine3d Transform3D
Eigen::Matrix< double, 3, 1 > Vector3D
std::pair< Amg::Vector3D, Amg::Vector3D > makeLine(const Parameters &pars)
Returns the parsed parameters into an Eigen line parametrization.
std::string toString(const Parameters &pars)
Dumps the parameters into a string with labels in front of each number.
ISpacePointCalibrator::CalibSpacePointVec CalibSpacePointVec
std::string print(const cont_t &container)
Print a space point container to string.
StIndex toStationIndex(ChIndex index)
convert ChIndex into StIndex
bool isBarrel(const ChIndex index)
Returns true if the chamber index points to a barrel chamber.
LayerIndex
enum to classify the different layers in the muon spectrometer
const std::string & stName(StIndex index)
convert StIndex into a string
LayerIndex toLayerIndex(ChIndex index)
convert ChIndex into LayerIndex
l
Printing final latex table to .tex output file.
void swap(ElementLinkVector< DOBJ > &lhs, ElementLinkVector< DOBJ > &rhs)
bool isNSW(const UncalibMeasType aodType)
Returns whether the measurement is a NSW measurement.
Muon_v1 Muon
Reference the current persistent version:
unsigned nFieldSteps
number of steps between two segments to integrate the magnetic field
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.
Full configuration object.