14 #include "Acts/Geometry/TrackingGeometry.hpp"
15 #include "Acts/Geometry/GeometryIdentifier.hpp"
16 #include "Acts/Utilities/TrackHelpers.hpp"
17 #include "Acts/TrackFitting/MbfSmoother.hpp"
18 #include "Acts/Utilities/Logger.hpp"
31 #include <Acts/Propagator/StandardAborters.hpp>
40 static std::size_t sourceLinkHash(
const Acts::SourceLink& slink) {
43 return uncalibMeas.identifier();
46 static bool sourceLinkEquality(
const Acts::SourceLink&
a,
const Acts::SourceLink&
b) {
52 static std::optional<ActsTrk::detail::RecoTrackStateContainerProxy> getFirstMeasurementFromTrack(
typename ActsTrk::detail::RecoTrackContainer::TrackProxy trackProxy) {
53 std::optional<ActsTrk::detail::RecoTrackStateContainerProxy> firstMeasurement {std::nullopt};
54 for (
auto st : trackProxy.trackStatesReversed()) {
58 if (not
st.typeFlags().test(Acts::TrackStateFlag::MeasurementFlag))
continue;
59 if (
st.typeFlags().test(Acts::TrackStateFlag::OutlierFlag))
continue;
60 firstMeasurement =
st;
62 return firstMeasurement;
109 return StatusCode::FAILURE;
115 return StatusCode::FAILURE;
121 return StatusCode::FAILURE;
125 Acts::GreedyAmbiguityResolution::Config
cfg;
136 return StatusCode::FAILURE;
140 return StatusCode::SUCCESS;
147 return StatusCode::SUCCESS;
165 std::vector<const ActsTrk::SeedContainer *> seedContainers;
166 std::size_t total_seeds = 0;
170 std::vector< std::unique_ptr< std::vector<int> > > destinies {};
172 destinies.reserve( seedContainers.size() );
173 for (std::size_t
i(0);
i<seedContainers.size(); ++
i) {
179 std::vector<const xAOD::UncalibratedMeasurementContainer *> uncalibratedMeasurementContainers;
180 std::size_t total_measurements = 0;
187 std::vector< const InDet::SiDetectorElementStatus *> det_el_status_arr;
188 const std::vector<const InDetDD::SiDetectorElementCollection*> &det_el_collections =volumeIdToDetectorElementCollMap->
collections();
189 det_el_status_arr.resize( det_el_collections.size(),
nullptr);
193 const std::vector<const InDetDD::SiDetectorElementCollection*>::const_iterator
194 det_el_col_iter =
std::find(det_el_collections.begin(),
195 det_el_collections.end(),
197 det_el_status_arr.at(det_el_col_iter - det_el_collections.begin()) = det_el_status.
cptr();
201 for (std::size_t icontainer = 0; icontainer < uncalibratedMeasurementContainers.size(); ++icontainer) {
202 measurementIndex.
addMeasurements(*uncalibratedMeasurementContainers[icontainer]);
206 for (std::size_t icontainer = 0; icontainer < uncalibratedMeasurementContainers.size(); ++icontainer) {
209 *uncalibratedMeasurementContainers[icontainer],
225 for (std::size_t icontainer = 0; icontainer < seedContainers.size(); ++icontainer)
227 duplicateSeedDetector.
addSeeds(icontainer, *seedContainers[icontainer], measurementIndex,
230 const bool reverseSearch = m_autoReverseSearch && shouldReverseSearch(seed);
231 const bool refitSeeds = icontainer < m_refitSeeds.size() && m_refitSeeds[icontainer];
232 const bool useTopSp = reverseSearch && !refitSeeds;
248 std::shared_ptr<Acts::PerigeeSurface> pSurface = Acts::Surface::makeShared<Acts::PerigeeSurface>(beamPos);
254 std::vector<const InDetDD::SiDetectorElementCollection*> detElementsCollections;
255 std::size_t total_detElems = 0;
261 Acts::VectorTrackContainer actsTrackBackend;
262 Acts::VectorMultiTrajectory actsTrackStateBackend;
264 std::lock_guard<std::mutex>
lock( m_mutex );
265 actsTrackBackend.reserve(m_nTrackReserve);
266 actsTrackStateBackend.reserve(m_nTrackStateReserve);
269 actsTrackStateBackend);
278 event_stat.resize(m_stat.size());
290 for (std::size_t icontainer = 0; icontainer < seedContainers.size(); ++icontainer)
296 duplicateSeedDetector,
297 *seedContainers.at(icontainer),
298 *detElementsCollections.at(icontainer),
307 ATH_MSG_DEBUG(
" \\__ Created " << actsTracksContainer.size() <<
" tracks");
309 mon_nTracks = actsTracksContainer.size();
319 for (std::size_t
i(0);
i<destinies.size(); ++
i) {
328 std::lock_guard<std::mutex>
lock( m_mutex );
330 if (actsTrackBackend.size() > m_nTrackReserve) {
331 m_nTrackReserve =
static_cast<std::size_t
>( std::ceil(
m_memorySafetyMargin * actsTrackBackend.size()) );
333 if (actsTrackStateBackend.size() > m_nTrackStateReserve) {
334 m_nTrackStateReserve =
static_cast<std::size_t
>( std::ceil(
m_memorySafetyMargin * actsTrackStateBackend.size()) );
342 ATH_MSG_DEBUG(
" \\__ Created " << actsTracksContainer.size() <<
" resolved tracks");
344 std::move(actsTrackBackend),
345 std::move(actsTrackStateBackend) ) );
346 return StatusCode::SUCCESS;
351 Acts::VectorTrackContainer resolvedTrackBackend;
352 Acts::VectorMultiTrajectory resolvedTrackStateBackend;
353 resolvedTrackBackend.reserve( actsTrackBackend.size() );
354 resolvedTrackStateBackend.reserve( actsTrackStateBackend.size() );
364 m_ambi->computeInitialState(actsTracksContainer, state, &sourceLinkHash,
365 &sourceLinkEquality);
374 for (
auto iTrack : state.selectedTracks) {
375 auto destProxy = resolvedTracksContainer.makeTrack();
376 destProxy.copyFrom(actsTracksContainer.getTrack(state.trackTips.at(iTrack)));
379 auto [nShared, nBadTrackMeasurements] = sharedHits_forFinalAmbi.
computeSharedHits(destProxy, resolvedTracksContainer, measurementIndex);
380 if (nBadTrackMeasurements > 0)
381 ATH_MSG_ERROR(
"computeSharedHits: " << nBadTrackMeasurements <<
" track measurements not found in input track");
385 ATH_MSG_DEBUG(
" \\__ Created " << resolvedTracksContainer.size() <<
" resolved tracks");
388 std::move(resolvedTrackBackend),
389 std::move(resolvedTrackStateBackend)) );
391 return StatusCode::SUCCESS;
395 Acts::VectorTrackContainer&& originalTrackBackend,
396 Acts::VectorMultiTrajectory&& originalTrackStateBackend)
const
399 Acts::ConstVectorTrackContainer constTrackBackend( std::move(originalTrackBackend) );
400 Acts::ConstVectorMultiTrajectory constTrackStateBackend( std::move(originalTrackStateBackend) );
401 std::unique_ptr< ActsTrk::TrackContainer> constTracksContainer = std::make_unique< ActsTrk::TrackContainer >( std::move(constTrackBackend),
402 std::move(constTrackStateBackend) );
406 ATH_CHECK(trackContainerHandle.
record(std::move(constTracksContainer)));
407 return StatusCode::SUCCESS;
411 const auto& bottom_sp = seed.sp().front();
413 const double r = bottom_sp->radius();
414 const double z = std::abs(bottom_sp->z());
419 return r > rBoundary ||
z > zBoundary;
433 std::size_t typeIndex,
434 const char *seedType,
436 std::vector<int>* destiny,
437 const Acts::PerigeeSurface& pSurface)
const
444 Acts::VectorTrackContainer trackBackend;
445 Acts::VectorMultiTrajectory trackStateBackend;
454 std::size_t category_i = 0;
456 auto stopBranchProxy = [&](
const detail::RecoTrackContainer::TrackProxy &
track,
458 return stopBranch(
track, trackState, trackSelectorCfg, detContext.
geometry, measurementIndex, typeIndex, event_stat[category_i]);
460 options.extensions.branchStopper.connect(stopBranchProxy);
463 Acts::ActorList<Acts::MaterialInteractor>>
466 Acts::TrackExtrapolationStrategy extrapolationStrategy =
470 ATH_MSG_DEBUG(
"Invoke track finding with " << seeds.size() <<
' ' << seedType <<
" seeds.");
473 std::size_t nPrinted = 0;
476 auto retrieveSurfaceFunction =
477 [
this, &detElements] (
const ActsTrk::Seed& seed,
bool useTopSp) ->
const Acts::Surface& {
478 const xAOD::SpacePoint* sp = useTopSp ? seed.sp().back() : seed.sp().front();
488 for (
unsigned int iseed = 0; iseed < seeds.size(); ++iseed)
494 tracksContainerTemp.clear();
498 const bool useTopSp = reverseSearch && !refitSeeds;
501 const bool isDupSeed = duplicateSeedDetector.
isDuplicate(typeIndex, iseed);
504 ATH_MSG_DEBUG(
"skip " << seedType <<
" seed " << iseed <<
" - already found");
513 options.propagatorPlainOptions.direction = reverseSearch ? Acts::Direction::Backward() : Acts::Direction::Forward();
514 secondOptions.propagatorPlainOptions.direction =
options.propagatorPlainOptions.direction.invert();
515 options.targetSurface = reverseSearch ? &pSurface :
nullptr;
516 secondOptions.targetSurface = reverseSearch ? nullptr : &pSurface;
520 std::optional<Acts::BoundTrackParameters> optTrackParams =
525 retrieveSurfaceFunction);
527 if (!optTrackParams) {
528 ATH_MSG_DEBUG(
"Failed to estimate track parameters for seed " << iseed);
538 Acts::BoundTrackParameters *initialParameters = &(*optTrackParams);
539 printSeed(iseed, detContext, seeds, *initialParameters, measurementIndex, nPrinted, seedType);
540 if (isDupSeed)
continue;
548 std::unique_ptr<Acts::BoundTrackParameters> refitSeedParameters;
550 refitSeedParameters =
doRefit(seed, *initialParameters, detContext, reverseSearch);
551 if (refitSeedParameters.get() ==
nullptr) {
556 if (refitSeedParameters.get() != initialParameters) {
557 initialParameters = refitSeedParameters.get();
558 printSeed(iseed, detContext, seeds, *initialParameters, measurementIndex, nPrinted, seedType,
true);
562 auto measurementRangesForced =
565 measurementSelector->setMeasurementRangesForced(measurementRangesForced.get());
566 if (measurementRangesForced)
575 ATH_MSG_WARNING(
"Track finding failed for " << seedType <<
" seed " << iseed <<
" with error" <<
result.error());
579 auto &tracksForSeed =
result.value();
583 std::size_t ntracks = 0
ul;
586 std::size_t nfirst = 0;
587 for (
TrkProxy &firstTrack : tracksForSeed) {
589 auto smoothingResult = Acts::smoothTrack(detContext.
geometry, firstTrack,
logger(), Acts::MbfSmoother());
590 if (!smoothingResult.ok()) {
592 << iseed <<
" and first track " << firstTrack.index()
593 <<
" failed with error " << smoothingResult.error());
603 extrapolationStrategy,
608 duplicateSeedDetector,
621 std::optional<detail::RecoTrackStateContainerProxy> firstMeas = getFirstMeasurementFromTrack(firstTrack);
623 if (not firstMeas.has_value()) {
624 ATH_MSG_ERROR(
"Could not retrieve first measurement from track proxy. Is it ill-formed?");
625 return StatusCode::FAILURE;
630 std::vector<typename detail::RecoTrackContainer::TrackProxy> secondTracksForSeed =
636 if ( secondTracksForSeed.empty() ) {
637 ATH_MSG_DEBUG(
"No viable result from second track finding for " << seedType <<
" seed " << iseed <<
" track " << nfirst);
642 extrapolationStrategy,
647 duplicateSeedDetector,
659 auto originalFirstMeasurementPrevious = firstMeasurement.previous();
660 for (
auto &secondTrack : secondTracksForSeed) {
661 secondTrack.reverseTrackStates(
true);
663 firstMeasurement.previous() = secondTrack.outermostTrackState().index();
664 secondTrack.tipIndex() = firstTrack.tipIndex();
668 auto secondSmoothingResult = Acts::smoothTrack(detContext.
geometry,
671 if ( not secondSmoothingResult.ok() ) {
674 secondTrack.reverseTrackStates(
true);
681 extrapolationStrategy,
686 duplicateSeedDetector,
697 firstMeasurement.previous() = originalFirstMeasurementPrevious;
704 destiny->at(iseed) = DestinyType::FAILURE;
706 destiny->at(iseed) = DestinyType::SUCCEED;
711 ATH_MSG_DEBUG(
"Track finding found no track candidates for " << seedType <<
" seed " << iseed);
713 }
else if (ntracks >= 2) {
723 return StatusCode::SUCCESS;
732 const auto lastMeasurementIndex =
track.tipIndex();
735 tracksContainer.trackStateContainer().visitBackwards(
736 lastMeasurementIndex,
737 [&duplicateSeedDetector,&measurementIndex](
const detail::RecoTrackStateContainer::ConstTrackStateProxy &state) ->
void
740 if (not state.hasUncalibratedSourceLink())
744 auto sl = state.getUncalibratedSourceLink().template get<ATLASUncalibSourceLink>();
750 const std::vector< const InDet::SiDetectorElementStatus *> &det_el_status_arr,
752 const Acts::TrackingGeometry *
754 ATH_CHECK(acts_tracking_geometry !=
nullptr);
756 using Counter =
struct {
unsigned int n_volumes, n_volumes_with_status, n_missing_detector_elements, n_detector_elements, n_disabled_detector_elements;};
758 acts_tracking_geometry->visitVolumes([&
counter,
759 &volume_id_to_det_el_coll,
762 this](
const Acts::TrackingVolume *volume_ptr) {
764 if (!volume_ptr)
return;
767 det_el_status = det_el_status_arr.at(volume_id_to_det_el_coll.
collecionMap().at(volume_ptr->geometryId().volume()));
769 ++
counter.n_volumes_with_status;
770 volume_ptr->visitSurfaces([&
counter, det_el_status, &measurements,
this](
const Acts::Surface *surface_ptr) {
771 if (!surface_ptr)
return;
772 const Acts::Surface &surface = *surface_ptr;
773 const Acts::DetectorElementBase*detector_element = surface.associatedDetectorElement();
774 if (detector_element) {
778 ActsTrk::detail::MeasurementRange old_range = measurements.markSurfaceInsensitive(surface_ptr->geometryId());
779 if (!old_range.empty()) {
780 auto geoid_to_string = [](const Acts::GeometryIdentifier &id) -> std::string {
781 std::stringstream amsg;
785 std::string a_msg ( geoid_to_string(surface_ptr->geometryId()));
786 ATH_MSG_WARNING(
"Reject " << (old_range.elementEndIndex() - old_range.elementBeginIndex())
787 <<
" measurements because surface " << a_msg);
789 ++
counter.n_disabled_detector_elements;
795 ++
counter.n_missing_detector_elements;
799 <<
" disabled detector elements " <<
counter.n_disabled_detector_elements
800 <<
" / " <<
counter.n_detector_elements
801 <<
" missing detector elements "
802 <<
counter.n_missing_detector_elements);
803 return StatusCode::SUCCESS;
806 std::size_t TrackFindingAlg::getSeedCategory(std::size_t typeIndex,
810 const xAOD::SpacePoint* sp = useTopSp ? seed.sp().back() : seed.sp().front();
812 double etaSeed = std::atanh(
pos[2] /
pos.norm());
813 return getStatCategory(typeIndex, etaSeed);
816 void TrackFindingAlg::printSeed(
unsigned int iseed,
819 const Acts::BoundTrackParameters &seedParameters,
821 std::size_t& nPrinted,
822 const char *seedType,
825 if (not m_trackStatePrinter.isSet())
return;
828 ATH_MSG_INFO(
"CKF results for " << seeds.size() <<
' ' << seedType <<
" seeds:");
831 m_trackStatePrinter->printSeed(detContext.
geometry, seeds[iseed], seedParameters, measurementIndex, iseed, isKF);
839 template <
typename propagator_state_t,
typename stepper_t,
840 typename navigator_t>
841 void act(propagator_state_t& state,
const stepper_t& ,
842 const navigator_t& navigator, result_type&
result,
843 const Acts::Logger& )
const {
844 const auto* currentSurface = navigator.currentSurface(state.navigation);
845 if (currentSurface ==
nullptr) {
849 assert(
result !=
nullptr &&
"Result type is nullptr");
851 if (currentSurface->associatedDetectorElement() !=
nullptr) {
852 const auto* detElem =
dynamic_cast<const ActsDetectorElement*
>(currentSurface->associatedDetectorElement());
853 if(detElem !=
nullptr) {
861 Acts::Result<void> TrackFindingAlg::extrapolateTrackToReferenceSurface(
864 const Acts::Surface &referenceSurface,
866 Acts::TrackExtrapolationStrategy
strategy,
870 Acts::ActorList<Acts::MaterialInteractor, Collector>>
873 auto findResult = findTrackStateForExtrapolation(
876 if (!findResult.ok()) {
878 return findResult.error();
881 auto &[trackState,
distance] = *findResult;
883 options.direction = Acts::Direction::fromScalarZeroAsPositive(
distance);
885 Acts::BoundTrackParameters
parameters =
track.createParametersFromState(trackState);
886 ATH_MSG_VERBOSE(
"Extrapolating track to reference surface at distance "
888 <<
" with starting parameters " <<
parameters);
890 auto state = propagator.makeState<decltype(
options), Acts::ForcedSurfaceReached>(referenceSurface,
options);
894 auto initRes = propagator.initialize(state,
parameters);
896 ATH_MSG_WARNING(
"Failed to initialize propagation state: " << initRes.error().message());
897 return initRes.error();
901 auto propagateOnlyResult =
902 propagator.propagate(state);
904 if (!propagateOnlyResult.ok()) {
905 ATH_MSG_WARNING(
"Failed to extrapolate track: " << propagateOnlyResult.error().message());
906 return propagateOnlyResult.error();
909 auto propagateResult = propagator.makeResult(
910 std::move(state), propagateOnlyResult, referenceSurface,
options);
912 if (!propagateResult.ok()) {
913 ATH_MSG_WARNING(
"Failed to extrapolate track: " << propagateResult.error().message());
914 return propagateResult.error();
917 track.setReferenceSurface(referenceSurface.getSharedPtr());
918 track.parameters() = propagateResult->endParameters.value().parameters();
920 propagateResult->endParameters.value().covariance().value();
922 return Acts::Result<void>::success();
927 const Acts::Surface& pSurface,
928 const Acts::TrackExtrapolationStrategy& extrapolationStrategy,
934 std::vector<int>* destiny,
936 std::size_t& ntracks,
938 std::size_t category_i,
939 const char *seedType)
const
947 if (not
track.hasReferenceSurface()) {
948 auto extrapolationResult =
949 extrapolateTrackToReferenceSurface(detContext,
track,
951 trackFinder().extrapolator,
952 extrapolationStrategy,
955 if (not extrapolationResult.ok()) {
957 << iseed <<
" and " <<
track.index()
958 <<
" failed with error " << extrapolationResult.error()
959 <<
" dropping track candidate.");
960 if (m_storeDestinies) destiny->at(iseed) = DestinyType::FAILURE;
961 return StatusCode::SUCCESS;
966 for(
const auto ts :
track.trackStatesReversed()) {
967 const auto& surface =
ts.referenceSurface();
968 if(surface.associatedDetectorElement() !=
nullptr) {
969 const auto* detElem =
dynamic_cast<const ActsDetectorElement*
>(surface.associatedDetectorElement());
970 if(detElem !=
nullptr) {
981 Acts::trimTrack(
track,
true,
true,
true,
true);
982 Acts::calculateTrackQuantities(
track);
985 for (
const auto trackState :
track.trackStatesReversed()) {
986 updateCounts(
track, trackState.typeFlags(), measurementType(trackState));
994 ++event_stat[category_i][kNOutputTracks];
996 if ( not trackFinder().trackSelector.isValidTrack(
track) or
997 not selectCountsFinal(
track)) {
998 ATH_MSG_DEBUG(
"Track " << ntracks <<
" from " << seedType <<
" seed " << iseed <<
" failed track selection");
999 if ( m_trackStatePrinter.isSet() ) {
1000 m_trackStatePrinter->printTrack(detContext.
geometry, tracksContainerTemp,
track, measurementIndex,
true);
1002 return StatusCode::SUCCESS;
1006 if (m_skipDuplicateSeeds) {
1007 storeSeedInfo(tracksContainerTemp,
track, duplicateSeedDetector, measurementIndex);
1010 auto actsDestProxy = actsTracksContainer.makeTrack();
1011 actsDestProxy.copyFrom(
track);
1015 if (not m_countSharedHits) {
1016 return StatusCode::SUCCESS;
1019 auto [nShared, nBadTrackMeasurements] = sharedHits.
computeSharedHits(actsDestProxy, actsTracksContainer, measurementIndex);
1021 if (nBadTrackMeasurements > 0) {
1022 ATH_MSG_ERROR(
"computeSharedHits: " << nBadTrackMeasurements <<
" track measurements not found in input for " << seedType <<
" seed " << iseed <<
" track");
1025 ATH_MSG_DEBUG(
"found " << actsDestProxy.nSharedHits() <<
" shared hits in " << seedType <<
" seed " << iseed <<
" track");
1027 event_stat[category_i][kNTotalSharedHits] += nShared;
1029 if (m_ambiStrategy == 2
u) {
1031 if (actsDestProxy.nSharedHits() <= m_maximumSharedHits) {
1032 ++event_stat[category_i][kNSelectedTracks];
1036 ATH_MSG_DEBUG(
"found " << actsDestProxy.nSharedHits() <<
" shared hits in " << seedType <<
" seed " << iseed <<
" track");
1040 auto [nSharedRemoved, nRemoveBadTrackMeasurements] = sharedHits.
computeSharedHits(actsDestProxy, actsTracksContainer, measurementIndex,
true);
1042 ATH_MSG_DEBUG(
"Removed " << nSharedRemoved <<
" shared hits in " << seedType <<
" seed " << iseed <<
" track and the matching track");
1044 if (nRemoveBadTrackMeasurements > 0) {
1045 ATH_MSG_ERROR(
"computeSharedHits with remove flag ON: " << nRemoveBadTrackMeasurements <<
1046 " track measurements not found in input for " << seedType <<
" seed " << iseed <<
" track");
1049 if (actsDestProxy.nSharedHits() != 0) {
1050 ATH_MSG_ERROR(
"computeSharedHits with remove flag ON returned " <<
1051 actsDestProxy.nSharedHits()<<
" while expecting 0 for" <<
1052 seedType <<
" seed " << iseed <<
" track");
1056 actsTracksContainer.removeTrack(actsDestProxy.index());
1057 ATH_MSG_DEBUG(
"Track " << ntracks <<
" from " << seedType <<
" seed " << iseed <<
" failed shared hit selection");
1061 ++event_stat[category_i][kNSelectedTracks];
1063 if (m_trackStatePrinter.isSet()) {
1064 m_trackStatePrinter->printTrack(detContext.
geometry, actsTracksContainer, actsDestProxy, measurementIndex);
1068 return StatusCode::SUCCESS;