File indexing completed on 2026-11-18 09:56:25
0001
0002
0003
0004
0005
0006
0007
0008
0009 #pragma once
0010
0011 #include "Acts/Definitions/Common.hpp"
0012 #include "Acts/EventData/MultiTrajectory.hpp"
0013 #include "Acts/EventData/MultiTrajectoryHelpers.hpp"
0014 #include "Acts/EventData/TrackStatePropMask.hpp"
0015 #include "Acts/EventData/TransformationHelpers.hpp"
0016 #include "Acts/EventData/Types.hpp"
0017 #include "Acts/Geometry/GeometryContext.hpp"
0018 #include "Acts/MagneticField/MagneticFieldContext.hpp"
0019 #include "Acts/Propagator/ActorList.hpp"
0020 #include "Acts/Propagator/ConstrainedStep.hpp"
0021 #include "Acts/Propagator/PropagatorState.hpp"
0022 #include "Acts/Propagator/StandardAborters.hpp"
0023 #include "Acts/Propagator/StepperConcept.hpp"
0024 #include "Acts/Propagator/detail/LoopProtection.hpp"
0025 #include "Acts/Propagator/detail/PointwiseMaterialInteraction.hpp"
0026 #include "Acts/TrackFinding/CombinatorialKalmanFilterError.hpp"
0027 #include "Acts/TrackFinding/CombinatorialKalmanFilterExtensions.hpp"
0028 #include "Acts/TrackFitting/BetheHeitlerApprox.hpp"
0029 #include "Acts/TrackFitting/GsfOptions.hpp"
0030 #include "Acts/TrackFitting/detail/GsfComponentMerging.hpp"
0031 #include "Acts/TrackFitting/detail/GsfUtils.hpp"
0032 #include "Acts/Utilities/CalibrationContext.hpp"
0033 #include "Acts/Utilities/Logger.hpp"
0034 #include "Acts/Utilities/Result.hpp"
0035
0036 #include <functional>
0037 #include <limits>
0038 #include <memory>
0039 #include <stdexcept>
0040 #include <type_traits>
0041
0042 namespace Acts {
0043
0044
0045
0046
0047
0048
0049
0050
0051 template <typename track_container_t>
0052 struct CombinatorialKalmanFilterOptions {
0053
0054 using TrackStateContainerBackend =
0055 typename track_container_t::TrackStateContainerBackend;
0056
0057 using TrackStateProxy = typename track_container_t::TrackStateProxy;
0058
0059
0060
0061
0062
0063
0064
0065
0066
0067
0068 CombinatorialKalmanFilterOptions(
0069 const GeometryContext& gctx, const MagneticFieldContext& mctx,
0070 std::reference_wrapper<const CalibrationContext> cctx,
0071 CombinatorialKalmanFilterExtensions<track_container_t> extensions_,
0072 const PropagatorPlainOptions& pOptions, bool mScattering = true,
0073 bool eLoss = true)
0074 : geoContext(gctx),
0075 magFieldContext(mctx),
0076 calibrationContext(cctx),
0077 extensions(extensions_),
0078 propagatorPlainOptions(pOptions),
0079 multipleScattering(mScattering),
0080 energyLoss(eLoss) {}
0081
0082
0083 CombinatorialKalmanFilterOptions() = delete;
0084
0085
0086 std::reference_wrapper<const GeometryContext> geoContext;
0087
0088 std::reference_wrapper<const MagneticFieldContext> magFieldContext;
0089
0090 std::reference_wrapper<const CalibrationContext> calibrationContext;
0091
0092
0093 CombinatorialKalmanFilterExtensions<track_container_t> extensions;
0094
0095
0096 PropagatorPlainOptions propagatorPlainOptions;
0097
0098
0099
0100
0101 const Surface* targetSurface = nullptr;
0102
0103
0104 bool multipleScattering = true;
0105
0106
0107 bool energyLoss = true;
0108
0109
0110
0111 bool skipPrePropagationUpdate = false;
0112
0113
0114
0115
0116
0117
0118 bool recordMaterialStates = true;
0119 };
0120
0121
0122
0123
0124
0125
0126
0127
0128
0129 template <typename track_container_t>
0130 struct BremCombinatorialKalmanFilterOptions
0131 : public CombinatorialKalmanFilterOptions<track_container_t> {
0132
0133 using CombinatorialKalmanFilterOptions<
0134 track_container_t>::CombinatorialKalmanFilterOptions;
0135
0136
0137 std::size_t maxComponents = 12;
0138
0139
0140 double weightCutoff = 1e-4;
0141
0142
0143 ComponentMergeMethod mergeMethod = ComponentMergeMethod::eMaxWeight;
0144
0145
0146 std::shared_ptr<const BetheHeitlerApprox> betheHeitlerApprox;
0147 };
0148
0149
0150
0151
0152 template <typename track_container_t>
0153 struct CombinatorialKalmanFilterResult {
0154
0155 using TrackStateContainerBackend =
0156 typename track_container_t::TrackStateContainerBackend;
0157
0158 using TrackProxy = typename track_container_t::TrackProxy;
0159
0160 using TrackStateProxy = typename track_container_t::TrackStateProxy;
0161
0162
0163 track_container_t* tracks{nullptr};
0164
0165
0166 TrackStateContainerBackend* trackStates{nullptr};
0167
0168
0169 std::vector<TrackProxy> activeBranches;
0170
0171
0172 std::vector<TrackProxy> collectedTracks;
0173
0174
0175 std::vector<TrackStateProxy> trackStateCandidates;
0176
0177
0178
0179 BoundMatrix accumulatedJacobian = BoundMatrix::Identity();
0180
0181
0182 bool finished = false;
0183
0184
0185 PathLimitReached pathLimitReached;
0186 };
0187
0188
0189
0190
0191
0192
0193
0194
0195
0196
0197
0198
0199
0200
0201
0202
0203
0204
0205
0206
0207 template <typename propagator_t, typename track_container_t>
0208 class CombinatorialKalmanFilter {
0209 public:
0210
0211
0212
0213 explicit CombinatorialKalmanFilter(propagator_t pPropagator,
0214 std::unique_ptr<const Logger> _logger =
0215 getDefaultLogger("CKF", Logging::INFO))
0216 : m_propagator(std::move(pPropagator)),
0217 m_logger(std::move(_logger)),
0218 m_actorLogger{m_logger->cloneWithSuffix("Actor")},
0219 m_updaterLogger{m_logger->cloneWithSuffix("Updater")} {}
0220
0221 private:
0222 using BoundState = std::tuple<BoundTrackParameters, BoundMatrix, double>;
0223 using TrackStateContainerBackend =
0224 typename track_container_t::TrackStateContainerBackend;
0225 using TrackProxy = typename track_container_t::TrackProxy;
0226 using TrackStateProxy = typename track_container_t::TrackStateProxy;
0227
0228 static constexpr bool IsMultiStepper =
0229 Concepts::MultiStepper<typename propagator_t::Stepper>;
0230 using TemporaryStates = detail::Gsf::TemporaryStates<VectorMultiTrajectory>;
0231
0232
0233
0234 using SingleBoundState =
0235 std::tuple<BoundTrackParameters, BoundMatrix, double>;
0236
0237
0238 propagator_t m_propagator;
0239
0240 std::unique_ptr<const Logger> m_logger;
0241 std::shared_ptr<const Logger> m_actorLogger;
0242 std::shared_ptr<const Logger> m_updaterLogger;
0243
0244 const Logger& logger() const { return *m_logger; }
0245
0246
0247
0248
0249
0250 class Actor {
0251 public:
0252 using BoundState = std::tuple<BoundTrackParameters, BoundMatrix, double>;
0253
0254 using result_type = CombinatorialKalmanFilterResult<track_container_t>;
0255
0256 using BranchStopperResult = CombinatorialKalmanFilterBranchStopperResult;
0257
0258
0259 SurfaceReached targetReached{std::numeric_limits<double>::lowest()};
0260
0261
0262 bool multipleScattering = true;
0263
0264
0265 bool energyLoss = true;
0266
0267
0268 bool skipPrePropagationUpdate = false;
0269
0270
0271 bool recordMaterialStates = true;
0272
0273
0274 const CalibrationContext* calibrationContextPtr{nullptr};
0275
0276 CombinatorialKalmanFilterExtensions<track_container_t> extensions;
0277
0278
0279 EndOfWorldReached endOfWorldReached;
0280
0281
0282 VolumeConstraintAborter volumeConstraintAborter;
0283
0284
0285
0286 struct BremState {
0287
0288 std::size_t maxComponents = 12;
0289
0290 double weightCutoff = 1e-4;
0291
0292 ComponentMergeMethod mergeMethod = ComponentMergeMethod::eMaxWeight;
0293
0294 const BetheHeitlerApprox* betheHeitlerApprox{nullptr};
0295
0296
0297
0298 TemporaryStates* temporaryStates{nullptr};
0299
0300 std::vector<BetheHeitlerApprox::Component>* betheHeitlerCache{nullptr};
0301
0302 std::vector<GsfComponent>* componentCache{nullptr};
0303 };
0304
0305 struct NoBremState {};
0306
0307
0308
0309 [[no_unique_address]] std::conditional_t<IsMultiStepper, BremState,
0310 NoBremState> brem;
0311
0312
0313 const Logger* actorLogger{nullptr};
0314
0315 const Logger* updaterLogger{nullptr};
0316
0317 const Logger& logger() const { return *actorLogger; }
0318
0319
0320
0321
0322
0323
0324
0325
0326
0327
0328 template <typename propagator_state_t, typename stepper_t,
0329 typename navigator_t>
0330 Result<void> act(propagator_state_t& state, const stepper_t& stepper,
0331 const navigator_t& navigator, result_type& result,
0332 const Logger& ) const {
0333 ACTS_VERBOSE("CKF Actor called");
0334
0335 assert(result.trackStates && "No MultiTrajectory set");
0336
0337 if (state.stage == PropagatorStage::prePropagation &&
0338 skipPrePropagationUpdate) {
0339 ACTS_VERBOSE("Skip pre-propagation update (first surface)");
0340 return Result<void>::success();
0341 }
0342 if (state.stage == PropagatorStage::postPropagation) {
0343 ACTS_VERBOSE("Skip post-propagation action");
0344 return Result<void>::success();
0345 }
0346
0347 ACTS_VERBOSE("CombinatorialKalmanFilter step");
0348
0349 assert(!result.activeBranches.empty() && "No active branches");
0350 assert(!result.finished && "Should never reach this when finished");
0351
0352
0353 if (result.pathLimitReached.internalLimit ==
0354 std::numeric_limits<double>::max()) {
0355 detail::setupLoopProtection(state, stepper, result.pathLimitReached,
0356 true, logger());
0357 }
0358
0359
0360
0361 if (const Surface* surface = navigator.currentSurface(state.navigation);
0362 surface != nullptr) {
0363
0364
0365
0366
0367
0368
0369
0370
0371
0372
0373
0374
0375
0376
0377 ACTS_VERBOSE("Perform filter step");
0378 auto res = filter(*surface, state, stepper, navigator, result);
0379 if (!res.ok()) {
0380 ACTS_DEBUG("Error in filter: " << res.error().message());
0381 return res.error();
0382 }
0383
0384 if (result.finished) {
0385 ACTS_VERBOSE("CKF Actor returns after filter step");
0386 return Result<void>::success();
0387 }
0388 }
0389
0390 assert(!result.activeBranches.empty() && "No active branches");
0391
0392 const bool isEndOfWorldReached =
0393 endOfWorldReached.checkAbort(state, stepper, navigator, logger());
0394 const bool isVolumeConstraintReached = volumeConstraintAborter.checkAbort(
0395 state, stepper, navigator, logger());
0396 const bool isPathLimitReached = result.pathLimitReached.checkAbort(
0397 state, stepper, navigator, logger());
0398 const bool isTargetReached =
0399 targetReached.checkAbort(state, stepper, navigator, logger());
0400 if (isEndOfWorldReached || isVolumeConstraintReached ||
0401 isPathLimitReached || isTargetReached) {
0402 if (isEndOfWorldReached) {
0403 ACTS_VERBOSE("End of world reached");
0404 } else if (isVolumeConstraintReached) {
0405 ACTS_VERBOSE("Volume constraint reached");
0406 } else if (isPathLimitReached) {
0407 ACTS_VERBOSE("Path limit reached");
0408 } else if (isTargetReached) {
0409 ACTS_VERBOSE("Target surface reached");
0410
0411
0412 auto res = stepper.boundState(state.stepping, *targetReached.surface);
0413 if (!res.ok()) {
0414 ACTS_DEBUG("Error while acquiring bound state for target surface: "
0415 << res.error() << " " << res.error().message());
0416 return res.error();
0417 }
0418
0419 const auto& [boundParams, jacobian, pathLength] = *res;
0420 auto currentBranch = result.activeBranches.back();
0421
0422 if constexpr (!IsMultiStepper) {
0423 currentBranch.parameters() = boundParams.parameters();
0424 currentBranch.covariance() = *boundParams.covariance();
0425 } else {
0426 const auto singleParams = boundParams.merge(brem.mergeMethod);
0427 currentBranch.parameters() = singleParams.parameters();
0428 currentBranch.covariance() = *singleParams.covariance();
0429 }
0430 currentBranch.setReferenceSurface(
0431 boundParams.referenceSurface().getSharedPtr());
0432
0433 stepper.releaseStepSize(state.stepping,
0434 ConstrainedStep::Type::Navigator);
0435 }
0436
0437
0438 storeLastActiveBranch(result);
0439 result.activeBranches.pop_back();
0440
0441
0442 auto resetRes = reset(state, stepper, navigator, result);
0443 if (!resetRes.ok()) {
0444 return resetRes.error();
0445 }
0446 }
0447
0448 return Result<void>::success();
0449 }
0450
0451 template <typename propagator_state_t, typename stepper_t,
0452 typename navigator_t>
0453 bool checkAbort(propagator_state_t& , const stepper_t& ,
0454 const navigator_t& , const result_type& result,
0455 const Logger& ) const {
0456 return result.finished;
0457 }
0458
0459
0460
0461
0462
0463
0464
0465
0466
0467
0468
0469 template <typename propagator_state_t, typename stepper_t,
0470 typename navigator_t>
0471 Result<void> reset(propagator_state_t& state, const stepper_t& stepper,
0472 const navigator_t& navigator,
0473 result_type& result) const {
0474 if (result.activeBranches.empty()) {
0475 ACTS_VERBOSE("Stop CKF with " << result.collectedTracks.size()
0476 << " found tracks");
0477 result.finished = true;
0478
0479 return Result<void>::success();
0480 }
0481
0482 auto currentBranch = result.activeBranches.back();
0483 auto currentState = currentBranch.outermostTrackState();
0484
0485 ACTS_VERBOSE("Propagation jumps to branch with tip = "
0486 << currentBranch.tipIndex());
0487
0488
0489 if constexpr (!IsMultiStepper) {
0490 stepper.initialize(state.stepping, currentState.filtered(),
0491 currentState.filteredCovariance(),
0492 stepper.particleHypothesis(state.stepping),
0493 currentState.referenceSurface());
0494 } else {
0495 const MultiComponentBoundTrackParameters multiBoundParameters(
0496 currentState.referenceSurface().getSharedPtr(),
0497 currentState.filtered(), currentState.filteredCovariance(),
0498 stepper.particleHypothesis(state.stepping));
0499
0500 stepper.initialize(state.stepping, multiBoundParameters);
0501 }
0502
0503
0504 result.accumulatedJacobian = BoundMatrix::Identity();
0505
0506
0507
0508 state.navigation.options.startSurface = ¤tState.referenceSurface();
0509 state.navigation.options.targetSurface = nullptr;
0510 auto navInitRes = navigator.initialize(
0511 state.navigation, stepper.position(state.stepping),
0512 stepper.direction(state.stepping), state.options.direction);
0513 if (!navInitRes.ok()) {
0514 ACTS_DEBUG("Navigation initialization failed: " << navInitRes.error());
0515 return navInitRes.error();
0516 }
0517
0518
0519
0520 const Result<void> materialRes = performMaterialInteraction(
0521 state, stepper, currentState.referenceSurface(),
0522 detail::determineMaterialUpdateMode(state, navigator,
0523 MaterialUpdateMode::PostUpdate));
0524 if (!materialRes.ok()) {
0525 ACTS_DEBUG("Material interaction failed during reset: "
0526 << materialRes.error().message());
0527 return materialRes.error();
0528 }
0529
0530
0531 detail::setupLoopProtection(state, stepper, result.pathLimitReached, true,
0532 logger());
0533
0534
0535 targetReached.checkAbort(state, stepper, navigator, logger());
0536
0537 return Result<void>::success();
0538 }
0539
0540
0541
0542
0543
0544
0545
0546
0547
0548
0549
0550
0551
0552
0553
0554 template <typename propagator_state_t, typename stepper_t,
0555 typename navigator_t>
0556 Result<void> filter(const Surface& surface, propagator_state_t& state,
0557 const stepper_t& stepper, const navigator_t& navigator,
0558 result_type& result) const {
0559 using PM = TrackStatePropMask;
0560
0561 const bool isSensitive = surface.isSensitive();
0562 const bool hasMaterial = surface.hasMaterial();
0563 const bool isMaterialOnly = hasMaterial && !isSensitive;
0564 bool expectMeasurements = isSensitive;
0565
0566 if (isSensitive) {
0567 ACTS_VERBOSE("Measurement surface " << surface.geometryId()
0568 << " detected.");
0569 } else if (isMaterialOnly) {
0570 ACTS_VERBOSE("Material surface " << surface.geometryId()
0571 << " detected.");
0572 } else {
0573 ACTS_VERBOSE("Passive surface " << surface.geometryId()
0574 << " detected.");
0575 return Result<void>::success();
0576 }
0577
0578
0579 if (isMaterialOnly) {
0580 stepper.transportCovarianceToCurvilinear(state.stepping);
0581 } else {
0582 stepper.transportCovarianceToBound(state.stepping, surface);
0583 }
0584
0585
0586 const Result<void> materialPreRes = performMaterialInteraction(
0587 state, stepper, surface,
0588 detail::determineMaterialUpdateMode(state, navigator,
0589 MaterialUpdateMode::PreUpdate));
0590 if (!materialPreRes.ok()) {
0591 ACTS_DEBUG("Material interaction failed during reset: "
0592 << materialPreRes.error().message());
0593 return materialPreRes.error();
0594 }
0595
0596 if constexpr (!IsMultiStepper) {
0597 if (isMaterialOnly && !recordMaterialStates) {
0598 ACTS_VERBOSE("Skip material track state on surface "
0599 << surface.geometryId());
0600
0601
0602 result.accumulatedJacobian =
0603 state.stepping.jacobian * result.accumulatedJacobian;
0604
0605
0606
0607 const Result<void> materialPostRes = performMaterialInteraction(
0608 state, stepper, surface,
0609 detail::determineMaterialUpdateMode(
0610 state, navigator, MaterialUpdateMode::PostUpdate));
0611 if (!materialPostRes.ok()) {
0612 ACTS_DEBUG("Material interaction failed during post-update: "
0613 << materialPostRes.error().message());
0614 }
0615 return materialPostRes;
0616 }
0617 }
0618
0619
0620 auto boundStateRes = [&]() -> Result<SingleBoundState> {
0621 if constexpr (!IsMultiStepper) {
0622 auto res = stepper.boundState(state.stepping, surface, false);
0623 if (!res.ok()) {
0624 return res.error();
0625 }
0626 auto& [boundParams, jacobian, pathLength] = *res;
0627 boundParams.covariance() = state.stepping.cov;
0628 return res;
0629 } else {
0630
0631
0632
0633
0634
0635
0636 auto res = stepper.boundState(state.stepping, surface, true);
0637 if (!res.ok()) {
0638 return res.error();
0639 }
0640 auto [multiBoundParams, jacobian, pathLength] = *res;
0641 const auto singleParams = multiBoundParams.merge(brem.mergeMethod);
0642 return Result<SingleBoundState>::success(
0643 {singleParams, jacobian, pathLength});
0644 }
0645 }();
0646 if (!boundStateRes.ok()) {
0647 return boundStateRes.error();
0648 }
0649 auto& boundState = *boundStateRes;
0650
0651 if constexpr (!IsMultiStepper) {
0652 if (!recordMaterialStates) {
0653
0654 std::get<1>(boundState) =
0655 std::get<1>(boundState) * result.accumulatedJacobian;
0656 result.accumulatedJacobian = BoundMatrix::Identity();
0657 }
0658 }
0659
0660 auto currentBranch = result.activeBranches.back();
0661 TrackIndexType prevTip = currentBranch.tipIndex();
0662
0663 using TrackStatesResult = Result<CkfTypes::BranchVector<TrackIndexType>>;
0664 TrackStatesResult tsRes = TrackStatesResult::success({});
0665 if (isSensitive) {
0666
0667
0668
0669 tsRes = extensions.createTrackStates(
0670 state.geoContext, *calibrationContextPtr, surface, boundState,
0671 prevTip, result.trackStateCandidates, *result.trackStates,
0672 logger());
0673 }
0674
0675 if (tsRes.ok() && !(*tsRes).empty()) {
0676 const CkfTypes::BranchVector<TrackIndexType>& newTrackStateList =
0677 *tsRes;
0678 const Result<unsigned int> procRes =
0679 processNewTrackStates(state, stepper, newTrackStateList, result);
0680 if (!procRes.ok()) {
0681 ACTS_DEBUG("Processing of selected track states failed: "
0682 << procRes.error().message());
0683 return procRes.error();
0684 }
0685 unsigned int nBranchesOnSurface = *procRes;
0686
0687 if (nBranchesOnSurface == 0) {
0688 ACTS_VERBOSE("All branches on surface " << surface.geometryId()
0689 << " have been stopped");
0690
0691 Result<void> resetRes = reset(state, stepper, navigator, result);
0692 if (!resetRes.ok()) {
0693 return resetRes.error();
0694 }
0695
0696 return Result<void>::success();
0697 }
0698
0699
0700 currentBranch = result.activeBranches.back();
0701 prevTip = currentBranch.tipIndex();
0702 } else {
0703 if (!tsRes.ok()) {
0704 if (static_cast<CombinatorialKalmanFilterError>(
0705 tsRes.error().value()) ==
0706 CombinatorialKalmanFilterError::NoMeasurementExpected) {
0707
0708 expectMeasurements = false;
0709 } else {
0710 ACTS_DEBUG("Track state creation failed on surface "
0711 << surface.geometryId() << ": " << tsRes.error());
0712 return tsRes.error();
0713 }
0714 }
0715
0716 if (expectMeasurements) {
0717 ACTS_VERBOSE("Detected hole after measurement selection on surface "
0718 << surface.geometryId());
0719 }
0720
0721 const auto stateMask = PM::Predicted | PM::Jacobian;
0722
0723
0724 TrackIndexType currentTip =
0725 addNonSourcelinkState(stateMask, boundState, result, isSensitive,
0726 expectMeasurements, prevTip);
0727 currentBranch.tipIndex() = currentTip;
0728 auto currentState = currentBranch.outermostTrackState();
0729 if (expectMeasurements) {
0730 currentBranch.nHoles()++;
0731 }
0732
0733 BranchStopperResult branchStopperResult =
0734 extensions.branchStopper(currentBranch, currentState);
0735
0736
0737 if (branchStopperResult == BranchStopperResult::Continue) {
0738
0739 } else {
0740
0741 if (branchStopperResult == BranchStopperResult::StopAndKeep) {
0742 storeLastActiveBranch(result);
0743 }
0744
0745 result.activeBranches.pop_back();
0746
0747
0748 ACTS_VERBOSE("Branch on surface " << surface.geometryId()
0749 << " has been stopped");
0750
0751 Result<void> resetRes = reset(state, stepper, navigator, result);
0752 if (!resetRes.ok()) {
0753 return resetRes.error();
0754 }
0755
0756 return Result<void>::success();
0757 }
0758 }
0759
0760 auto currentState = currentBranch.outermostTrackState();
0761
0762 if (currentState.typeFlags().isOutlier()) {
0763
0764 ACTS_VERBOSE("Outlier state detected on surface "
0765 << surface.geometryId());
0766 } else if (currentState.typeFlags().isMeasurement()) {
0767
0768
0769
0770 updateStepper(state, stepper, currentState);
0771 ACTS_VERBOSE("Stepping state is updated with filtered parameter:");
0772 ACTS_VERBOSE("-> " << currentState.filtered().transpose()
0773 << " of track state with tip = "
0774 << currentState.index());
0775 }
0776
0777
0778 const Result<void> materialPostRes = performMaterialInteraction(
0779 state, stepper, surface,
0780 detail::determineMaterialUpdateMode(state, navigator,
0781 MaterialUpdateMode::PostUpdate));
0782 if (!materialPostRes.ok()) {
0783 ACTS_DEBUG("Material interaction failed during post-update: "
0784 << materialPostRes.error().message());
0785 return materialPostRes.error();
0786 }
0787
0788 return Result<void>::success();
0789 }
0790
0791
0792
0793
0794
0795
0796
0797
0798
0799
0800
0801
0802
0803
0804 template <typename propagator_state_t, typename stepper_t>
0805 Result<unsigned int> processNewTrackStates(
0806 propagator_state_t& state, const stepper_t& stepper,
0807 const CkfTypes::BranchVector<TrackIndexType>& newTrackStateList,
0808 result_type& result) const {
0809 using PM = TrackStatePropMask;
0810
0811 unsigned int nBranchesOnSurface = 0;
0812
0813 auto rootBranch = result.activeBranches.back();
0814
0815
0816
0817 CkfTypes::BranchVector<TrackProxy> newBranches;
0818 for (auto it = newTrackStateList.rbegin(); it != newTrackStateList.rend();
0819 ++it) {
0820
0821
0822 auto shallowCopy = [&] {
0823 auto sc = rootBranch.container().makeTrack();
0824 sc.copyFromShallow(rootBranch);
0825 return sc;
0826 };
0827 auto newBranch =
0828 (it == newTrackStateList.rbegin()) ? rootBranch : shallowCopy();
0829 newBranch.tipIndex() = *it;
0830 newBranches.push_back(newBranch);
0831 }
0832
0833
0834 result.activeBranches.pop_back();
0835
0836
0837 for (TrackProxy newBranch : newBranches) {
0838 auto trackState = newBranch.outermostTrackState();
0839 TrackStateTypeMap typeFlags = trackState.typeFlags();
0840
0841 if (typeFlags.isOutlier()) {
0842
0843
0844
0845 trackState.shareFrom(PM::Predicted, PM::Filtered);
0846
0847 newBranch.nOutliers()++;
0848 } else if (typeFlags.isMeasurement()) {
0849
0850 trackState.addComponents(PM::Filtered);
0851
0852 const auto updateRes = kalmanUpdate(state, stepper, trackState);
0853 if (!updateRes.ok()) {
0854 ACTS_DEBUG("Update step failed: " << updateRes.error().message());
0855 return updateRes.error();
0856 }
0857 ACTS_VERBOSE("Appended measurement track state with tip = "
0858 << newBranch.tipIndex());
0859
0860 newBranch.nMeasurements()++;
0861 newBranch.nDoF() += trackState.calibratedSize();
0862 newBranch.chi2() += trackState.chi2();
0863 } else {
0864 ACTS_WARNING("Cannot handle this track state flags");
0865 continue;
0866 }
0867
0868 result.activeBranches.push_back(newBranch);
0869
0870 BranchStopperResult branchStopperResult =
0871 extensions.branchStopper(newBranch, trackState);
0872
0873
0874 if (branchStopperResult == BranchStopperResult::Continue) {
0875
0876 nBranchesOnSurface++;
0877 } else {
0878
0879 if (branchStopperResult == BranchStopperResult::StopAndKeep) {
0880 storeLastActiveBranch(result);
0881 }
0882
0883 result.activeBranches.pop_back();
0884 }
0885 }
0886
0887 return nBranchesOnSurface;
0888 }
0889
0890
0891
0892
0893
0894
0895
0896
0897
0898
0899
0900 TrackIndexType addNonSourcelinkState(TrackStatePropMask stateMask,
0901 const BoundState& boundState,
0902 result_type& result, bool isSensitive,
0903 bool expectMeasurements,
0904 TrackIndexType prevTip) const {
0905 using PM = TrackStatePropMask;
0906
0907
0908 auto trackStateProxy =
0909 result.trackStates->makeTrackState(stateMask, prevTip);
0910 ACTS_VERBOSE("Create "
0911 << (isSensitive
0912 ? (expectMeasurements ? "Hole"
0913 : "noMeasurementExpected")
0914 : "Material")
0915 << " output track state #" << trackStateProxy.index()
0916 << " with mask: " << stateMask);
0917
0918 const auto& [boundParams, jacobian, pathLength] = boundState;
0919
0920 trackStateProxy.predicted() = boundParams.parameters();
0921 trackStateProxy.predictedCovariance() = boundParams.covariance().value();
0922 trackStateProxy.jacobian() = jacobian;
0923 trackStateProxy.pathLength() = pathLength;
0924
0925 trackStateProxy.setReferenceSurface(
0926 boundParams.referenceSurface().getSharedPtr());
0927
0928
0929 auto typeFlags = trackStateProxy.typeFlags();
0930 if (trackStateProxy.referenceSurface().hasMaterial()) {
0931 typeFlags.setHasMaterial();
0932 }
0933 typeFlags.setHasParameters();
0934 if (isSensitive) {
0935 if (expectMeasurements) {
0936 typeFlags.setIsHole();
0937 } else {
0938 typeFlags.setHasNoExpectedHit();
0939 }
0940 }
0941
0942
0943
0944 trackStateProxy.shareFrom(PM::Predicted, PM::Filtered);
0945
0946 return trackStateProxy.index();
0947 }
0948
0949 void storeLastActiveBranch(result_type& result) const {
0950 auto currentBranch = result.activeBranches.back();
0951 TrackIndexType currentTip = currentBranch.tipIndex();
0952
0953 ACTS_VERBOSE("Storing track "
0954 << currentBranch.index() << " with tip index " << currentTip
0955 << ". nMeasurements = " << currentBranch.nMeasurements()
0956 << ", nOutliers = " << currentBranch.nOutliers()
0957 << ", nHoles = " << currentBranch.nHoles());
0958
0959 result.collectedTracks.push_back(currentBranch);
0960 }
0961
0962 template <typename propagator_state_t, typename stepper_t>
0963 Result<void> performMaterialInteraction(
0964 propagator_state_t& state, const stepper_t& stepper,
0965 const Surface& surface, MaterialUpdateMode updateMode) const {
0966 if (!surface.hasMaterial()) {
0967 return Result<void>::success();
0968 }
0969
0970 if constexpr (!IsMultiStepper) {
0971 const Result<detail::PointwiseMaterialEffects> materialInteractionRes =
0972 detail::performMaterialInteraction(
0973 state, stepper, surface, updateMode, NoiseUpdateMode::addNoise,
0974 multipleScattering, energyLoss, logger());
0975 if (!materialInteractionRes.ok()) {
0976 ACTS_DEBUG("Material interaction failed during reset: "
0977 << materialInteractionRes.error().message());
0978 return materialInteractionRes.error();
0979 }
0980
0981 return Result<void>::success();
0982 } else {
0983 if (ACTS_CHECK_BIT(updateMode, MaterialUpdateMode::PostUpdate)) {
0984 brem.betheHeitlerCache->clear();
0985 brem.componentCache->clear();
0986 std::size_t nInvalidBetheHeitler = 0;
0987 double maxPathXOverX0 = 0;
0988
0989 for (auto cmp : stepper.componentIterable(state.stepping)) {
0990 const auto boundParamsRes = transformFreeToBoundParameters(
0991 cmp.state().pars, surface, state.options.geoContext);
0992 if (!boundParamsRes.ok()) {
0993 ACTS_DEBUG(
0994 "Failed to transform free to bound parameters for "
0995 "Bethe-Heitler approximation: "
0996 << boundParamsRes.error());
0997 continue;
0998 }
0999
1000 const BoundTrackParameters bound(
1001 surface.getSharedPtr(), *boundParamsRes, cmp.state().cov,
1002 stepper.particleHypothesis(state.stepping));
1003
1004 detail::Gsf::applyBetheHeitler(
1005 state.options.geoContext, surface, state.options.direction,
1006 bound, cmp.weight(), *brem.betheHeitlerApprox,
1007 *brem.betheHeitlerCache, brem.weightCutoff,
1008 *brem.componentCache, nInvalidBetheHeitler, maxPathXOverX0,
1009 logger());
1010 }
1011
1012 if (brem.componentCache->empty()) {
1013 ACTS_WARNING(
1014 "No components left after applying energy loss. "
1015 "Is the weight cutoff "
1016 << brem.weightCutoff << " too high?");
1017 ACTS_WARNING("Return to propagator without applying energy loss");
1018 return Result<void>::success();
1019 }
1020
1021
1022 const auto finalCmpNumber =
1023 std::min(static_cast<std::size_t>(stepper.maxComponents),
1024 brem.maxComponents);
1025 extensions.mixtureReducer(*brem.componentCache, finalCmpNumber,
1026 surface);
1027
1028 detail::Gsf::removeLowWeightComponents(*brem.componentCache,
1029 brem.weightCutoff);
1030
1031 detail::Gsf::updateStepper(state, stepper, surface,
1032 *brem.componentCache);
1033 }
1034
1035 detail::Gsf::applyMultipleScattering(state, stepper, surface,
1036 updateMode, logger());
1037
1038 return Result<void>::success();
1039 }
1040 }
1041
1042 template <typename propagator_state_t, typename stepper_t>
1043 Result<void> kalmanUpdate(propagator_state_t& state,
1044 const stepper_t& stepper,
1045 TrackStateProxy& trackState) const {
1046 if constexpr (!IsMultiStepper) {
1047 return extensions.updater(state.geoContext, trackState, *updaterLogger);
1048 } else {
1049 using PrtProjector = detail::Gsf::MultiTrajectoryProjector<
1050 detail::Gsf::StatesType::ePredicted, TrackStateContainerBackend>;
1051 using FltProjector = detail::Gsf::MultiTrajectoryProjector<
1052 detail::Gsf::StatesType::eFiltered, TrackStateContainerBackend>;
1053
1054 const auto& surface = trackState.referenceSurface();
1055
1056 auto& temporaryStates = *brem.temporaryStates;
1057 temporaryStates.clear();
1058
1059 for (auto cmp : stepper.componentIterable(state.stepping)) {
1060 auto& singleState = cmp.singleState(state).stepping;
1061 const auto& singleStepper = cmp.singleStepper(stepper);
1062
1063 TrackStatePropMask mask = TrackStatePropMask::Predicted |
1064 TrackStatePropMask::Jacobian |
1065 TrackStatePropMask::Calibrated;
1066 TrackStateProxy trackStateProxy =
1067 temporaryStates.traj.makeTrackState(mask, kTrackIndexInvalid);
1068
1069
1070
1071 trackStateProxy.setReferenceSurface(surface.getSharedPtr());
1072
1073 auto res = singleStepper.boundState(singleState, surface);
1074 if (!res.ok()) {
1075 ACTS_ERROR("Propagate to surface " << surface.geometryId()
1076 << " failed: " << res.error());
1077 return res.error();
1078 }
1079 const auto& [boundParams, jacobian, pathLength] = *res;
1080
1081
1082 trackStateProxy.predicted() = boundParams.parameters();
1083 trackStateProxy.predictedCovariance() = *boundParams.covariance();
1084 trackStateProxy.allocateCalibrated(trackState.calibratedSize());
1085 trackStateProxy.setProjectorSubspaceIndices(
1086 trackState.projectorSubspaceIndices());
1087 trackStateProxy.effectiveCalibrated() =
1088 trackState.effectiveCalibrated();
1089 trackStateProxy.effectiveCalibratedCovariance() =
1090 trackState.effectiveCalibratedCovariance();
1091
1092
1093 trackStateProxy.addComponents(TrackStatePropMask::Filtered);
1094
1095 const auto updateRes = extensions.updater(
1096 state.geoContext, trackStateProxy, *updaterLogger);
1097 if (!updateRes.ok()) {
1098 return updateRes.error();
1099 }
1100
1101 temporaryStates.tips.push_back(trackStateProxy.index());
1102 temporaryStates.weights[trackStateProxy.index()] = cmp.weight();
1103 }
1104
1105 detail::Gsf::computePosteriorWeights(temporaryStates.traj,
1106 temporaryStates.tips,
1107 temporaryStates.weights);
1108
1109 detail::Gsf::normalizeWeights(temporaryStates.tips,
1110 [&](auto idx) -> double& {
1111 return temporaryStates.weights.at(idx);
1112 });
1113
1114 const auto [prtMean, prtCov] = detail::Gsf::mergeGaussianMixture(
1115 temporaryStates.tips,
1116 PrtProjector{temporaryStates.traj, temporaryStates.weights},
1117 surface, brem.mergeMethod);
1118 trackState.predicted() = prtMean;
1119 trackState.predictedCovariance() = prtCov;
1120
1121 const auto [fltMean, fltCov] = detail::Gsf::mergeGaussianMixture(
1122 temporaryStates.tips,
1123 FltProjector{temporaryStates.traj, temporaryStates.weights},
1124 surface, brem.mergeMethod);
1125 trackState.filtered() = fltMean;
1126 trackState.filteredCovariance() = fltCov;
1127
1128 return Result<void>::success();
1129 }
1130 }
1131
1132 template <typename propagator_state_t, typename stepper_t>
1133 void updateStepper(propagator_state_t& state, const stepper_t& stepper,
1134 const TrackStateProxy& currentState) const {
1135 if constexpr (!IsMultiStepper) {
1136 stepper.update(state.stepping,
1137 MultiTrajectoryHelpers::freeFiltered(
1138 state.options.geoContext, currentState),
1139 currentState.filtered(),
1140 currentState.filteredCovariance(),
1141 currentState.referenceSurface());
1142 } else {
1143
1144
1145
1146
1147
1148 detail::Gsf::updateStepper(state, stepper, *brem.temporaryStates,
1149 brem.weightCutoff);
1150 }
1151 }
1152 };
1153
1154
1155
1156 struct StubPathLimitReached {
1157 double internalLimit{};
1158
1159 template <typename propagator_state_t, typename stepper_t,
1160 typename navigator_t>
1161 bool checkAbort(propagator_state_t& , const stepper_t& ,
1162 const navigator_t& ,
1163 const Logger& ) const {
1164 return false;
1165 }
1166 };
1167
1168 public:
1169
1170
1171
1172
1173 using Options = std::conditional_t<
1174 IsMultiStepper, BremCombinatorialKalmanFilterOptions<track_container_t>,
1175 CombinatorialKalmanFilterOptions<track_container_t>>;
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191 Result<std::vector<TrackProxy>> findTracks(
1192 const BoundTrackParameters& initialParameters, const Options& tfOptions,
1193 track_container_t& trackContainer, TrackProxy rootBranch) const {
1194
1195 using CombinatorialKalmanFilterActor = Actor;
1196 using Actors = ActorList<CombinatorialKalmanFilterActor>;
1197
1198
1199 using PropagatorOptions = typename propagator_t::template Options<Actors>;
1200 PropagatorOptions propOptions(tfOptions.geoContext,
1201 tfOptions.magFieldContext);
1202
1203
1204 propOptions.setPlainOptions(tfOptions.propagatorPlainOptions);
1205
1206
1207 auto& combKalmanActor =
1208 propOptions.actorList.template get<CombinatorialKalmanFilterActor>();
1209 combKalmanActor.targetReached.surface = tfOptions.targetSurface;
1210 combKalmanActor.multipleScattering = tfOptions.multipleScattering;
1211 combKalmanActor.energyLoss = tfOptions.energyLoss;
1212 combKalmanActor.skipPrePropagationUpdate =
1213 tfOptions.skipPrePropagationUpdate;
1214 if constexpr (IsMultiStepper) {
1215
1216 if (!tfOptions.recordMaterialStates) {
1217 throw std::invalid_argument(
1218 "recordMaterialStates cannot be disabled with a multi-component "
1219 "stepper");
1220 }
1221 } else {
1222 combKalmanActor.recordMaterialStates = tfOptions.recordMaterialStates;
1223 }
1224 combKalmanActor.actorLogger = m_actorLogger.get();
1225 combKalmanActor.updaterLogger = m_updaterLogger.get();
1226 combKalmanActor.calibrationContextPtr = &tfOptions.calibrationContext.get();
1227
1228
1229 combKalmanActor.extensions = tfOptions.extensions;
1230
1231
1232
1233
1234 TemporaryStates temporaryStates;
1235 std::vector<BetheHeitlerApprox::Component> betheHeitlerCache;
1236 std::vector<GsfComponent> componentCache;
1237
1238
1239 if constexpr (IsMultiStepper) {
1240 combKalmanActor.brem.maxComponents = tfOptions.maxComponents;
1241 combKalmanActor.brem.weightCutoff = tfOptions.weightCutoff;
1242 combKalmanActor.brem.mergeMethod = tfOptions.mergeMethod;
1243 combKalmanActor.brem.betheHeitlerApprox =
1244 tfOptions.betheHeitlerApprox.get();
1245
1246 combKalmanActor.brem.temporaryStates = &temporaryStates;
1247 combKalmanActor.brem.betheHeitlerCache = &betheHeitlerCache;
1248 combKalmanActor.brem.componentCache = &componentCache;
1249 }
1250
1251 auto propState =
1252 m_propagator
1253 .template makeState<PropagatorOptions, StubPathLimitReached>(
1254 propOptions);
1255
1256 if constexpr (!IsMultiStepper) {
1257 const auto initResult =
1258 m_propagator
1259 .template initialize<decltype(propState), StubPathLimitReached>(
1260 propState, initialParameters);
1261 if (!initResult.ok()) {
1262 ACTS_DEBUG("Propagation initialization failed: " << initResult.error());
1263 return initResult.error();
1264 }
1265 } else {
1266 const MultiComponentBoundTrackParameters multiBoundInitialParameters(
1267 initialParameters.referenceSurface().getSharedPtr(),
1268 initialParameters.parameters(), initialParameters.covariance(),
1269 initialParameters.particleHypothesis());
1270
1271 const auto initResult =
1272 m_propagator
1273 .template initialize<decltype(propState), StubPathLimitReached>(
1274 propState, multiBoundInitialParameters);
1275 if (!initResult.ok()) {
1276 ACTS_DEBUG("Propagation initialization failed: " << initResult.error());
1277 return initResult.error();
1278 }
1279 }
1280
1281 auto& r =
1282 propState
1283 .template get<CombinatorialKalmanFilterResult<track_container_t>>();
1284 r.tracks = &trackContainer;
1285 r.trackStates = &trackContainer.trackStateContainer();
1286
1287
1288 rootBranch.setParticleHypothesis(initialParameters.particleHypothesis());
1289
1290 r.activeBranches.push_back(rootBranch);
1291
1292 auto propagationResult = m_propagator.propagate(propState);
1293
1294 auto result = m_propagator.makeResult(
1295 std::move(propState), propagationResult, propOptions, false);
1296
1297 if (!result.ok()) {
1298 ACTS_DEBUG("Propagation failed: " << result.error() << " "
1299 << result.error().message()
1300 << " with the initial parameters: \n"
1301 << initialParameters.parameters());
1302 return result.error();
1303 }
1304
1305 auto& propRes = *result;
1306
1307
1308 auto combKalmanResult =
1309 std::move(propRes.template get<
1310 CombinatorialKalmanFilterResult<track_container_t>>());
1311
1312
1313 if (!combKalmanResult.finished) {
1314 ACTS_DEBUG("CombinatorialKalmanFilter failed: "
1315 << "Propagation reached max steps "
1316 << "with the initial parameters: "
1317 << initialParameters.parameters().transpose());
1318 return CombinatorialKalmanFilterError::PropagationReachesMaxSteps;
1319 }
1320
1321 return std::move(combKalmanResult.collectedTracks);
1322 }
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336 Result<std::vector<TrackProxy>> findTracks(
1337 const BoundTrackParameters& initialParameters, const Options& tfOptions,
1338 track_container_t& trackContainer) const {
1339 auto rootBranch = trackContainer.makeTrack();
1340 return findTracks(initialParameters, tfOptions, trackContainer, rootBranch);
1341 }
1342 };
1343
1344
1345
1346 }