diff --git a/Core/include/Acts/EventData/ChargePolicy.hpp b/Core/include/Acts/EventData/ChargePolicy.hpp index 1e11f8c0f8694579b89e08a431931bff054b457e..110285eec9fed34d6c8dc87728346750d4981220 100644 --- a/Core/include/Acts/EventData/ChargePolicy.hpp +++ b/Core/include/Acts/EventData/ChargePolicy.hpp @@ -21,9 +21,8 @@ namespace Acts { /// track (parameters) at the C++ type level. This allows other class to employ /// optimized /// algorithms for either case by using template specializations. -class ChargedPolicy -{ -public: +class ChargedPolicy { + public: /// @brief constructor with given charge /// /// @param charge electric charge of particle/track (parameters) @@ -32,47 +31,29 @@ public: /// @brief equality operator /// /// @return @c true if rhs has the same charge, otherwise @c false - bool - operator==(const ChargedPolicy& rhs) const - { + bool operator==(const ChargedPolicy& rhs) const { return m_dCharge == rhs.m_dCharge; } /// @brief inequality operator /// /// @return @c true if rhs has a different charge, otherwise @c false - bool - operator!=(const ChargedPolicy& rhs) const - { - return !(*this == rhs); - } + bool operator!=(const ChargedPolicy& rhs) const { return !(*this == rhs); } /// @brief retrieve stored value of the electric charge /// /// @return value for charge - double - getCharge() const - { - return m_dCharge; - } + double getCharge() const { return m_dCharge; } /// @brief sets charge /// /// @param charge new value for the electric charge - void - setCharge(double charge) - { - m_dCharge = charge; - } + void setCharge(double charge) { m_dCharge = charge; } /// @brief flip sign of electric charge - void - flipSign() - { - m_dCharge *= -1.; - } + void flipSign() { m_dCharge *= -1.; } -private: + private: double m_dCharge; ///< value of electric charge }; @@ -88,34 +69,21 @@ private: /// track (parameters) at the C++ type level. This allows other class to employ /// optimized /// algorithms for either case by using template specializations. -class NeutralPolicy -{ -public: +class NeutralPolicy { + public: /// @brief equality operator /// /// @return always @c true - bool - operator==(const NeutralPolicy& /*other*/) const - { - return true; - } + bool operator==(const NeutralPolicy& /*other*/) const { return true; } /// @brief inequality operator /// /// @return always @c false - bool - operator!=(const NeutralPolicy& rhs) const - { - return !(*this == rhs); - } + bool operator!=(const NeutralPolicy& rhs) const { return !(*this == rhs); } /// @brief get electric charge /// /// @return always 0 - double - getCharge() const - { - return 0.; - } + double getCharge() const { return 0.; } }; } // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/EventData/Measurement.hpp b/Core/include/Acts/EventData/Measurement.hpp index 66786bac3a6b15adb403f4a65327116e36109b95..45cff3d9b1e625275e2c6f004da754de7834a16e 100644 --- a/Core/include/Acts/EventData/Measurement.hpp +++ b/Core/include/Acts/EventData/Measurement.hpp @@ -47,8 +47,7 @@ class Surface; /// @tparam Identifier identification object for this measurement /// @tparam params parameter pack containing the measured parameters template <typename source_link_t, ParID_t... params> -class Measurement -{ +class Measurement { // check type conditions static_assert(std::is_copy_constructible<source_link_t>::value, "'Identifier' must be copy-constructible"); @@ -59,13 +58,13 @@ class Measurement static_assert(std::is_move_assignable<source_link_t>::value, "'Identifier' must be move-assignable"); -private: + private: // private typedefs /// type of the underlying ParameterSet object using ParSet_t = ParameterSet<params...>; -public: + public: /// type of the vector containing the parameter values using ParVector_t = typename ParSet_t::ParVector_t; /// type of the covariance matrix of the measurement @@ -97,17 +96,14 @@ public: /// measurement template <typename... Tail> Measurement(std::shared_ptr<const Surface> surface, - const source_link_t& source, - CovMatrix_t cov, + const source_link_t& source, CovMatrix_t cov, typename std::enable_if<sizeof...(Tail) + 1 == sizeof...(params), ParValue_t>::type head, Tail... values) - : m_oParameters(std::make_unique<const CovMatrix_t>(std::move(cov)), - head, - values...) - , m_pSurface(std::move(surface)) - , m_sourceLink(source) - { + : m_oParameters(std::make_unique<const CovMatrix_t>(std::move(cov)), head, + values...), + m_pSurface(std::move(surface)), + m_sourceLink(source) { assert(m_pSurface); } @@ -121,11 +117,9 @@ public: /// /// @param copy is the source for the copy Measurement(const Measurement<source_link_t, params...>& copy) - : m_oParameters(copy.m_oParameters) - , m_pSurface(copy.m_pSurface) - , m_sourceLink(copy.m_sourceLink) - { - } + : m_oParameters(copy.m_oParameters), + m_pSurface(copy.m_pSurface), + m_sourceLink(copy.m_sourceLink) {} /// @brief move constructor /// @@ -134,11 +128,9 @@ public: /// /// @param other is the source for the move Measurement(Measurement<source_link_t, params...>&& other) - : m_oParameters(std::move(other.m_oParameters)) - , m_pSurface(std::move(other.m_pSurface)) - , m_sourceLink(std::move(other.m_sourceLink)) - { - } + : m_oParameters(std::move(other.m_oParameters)), + m_pSurface(std::move(other.m_pSurface)), + m_sourceLink(std::move(other.m_sourceLink)) {} /// @brief copy assignment operator /// @@ -146,14 +138,13 @@ public: /// @tparam params...The local parameter pack /// /// @param rhs is the source for the assignment - Measurement<source_link_t, params...>& - operator=(const Measurement<source_link_t, params...>& rhs) - { + Measurement<source_link_t, params...>& operator=( + const Measurement<source_link_t, params...>& rhs) { // check for self-assignment if (&rhs != this) { m_oParameters = rhs.m_oParameters; - m_pSurface = rhs.m_pSurface; - m_sourceLink = rhs.m_sourceLink; + m_pSurface = rhs.m_pSurface; + m_sourceLink = rhs.m_sourceLink; } return *this; } @@ -164,12 +155,11 @@ public: /// @tparam params...The local parameter pack /// /// @param rhs is the source for the move assignment - Measurement<source_link_t, params...>& - operator=(Measurement<source_link_t, params...>&& rhs) - { + Measurement<source_link_t, params...>& operator=( + Measurement<source_link_t, params...>&& rhs) { m_oParameters = std::move(rhs.m_oParameters); - m_pSurface = std::move(rhs.m_pSurface); - m_sourceLink = std::move(rhs.m_sourceLink); + m_pSurface = std::move(rhs.m_pSurface); + m_sourceLink = std::move(rhs.m_sourceLink); return *this; } @@ -183,9 +173,7 @@ public: /// /// @return value of the stored parameter template <ParID_t parameter> - ParValue_t - get() const - { + ParValue_t get() const { return m_oParameters.template getParameter<parameter>(); } @@ -196,20 +184,12 @@ public: /// given for the measured parameters in the order defined by the /// class /// template argument @c params. - ParVector_t - parameters() const - { - return m_oParameters.getParameters(); - } + ParVector_t parameters() const { return m_oParameters.getParameters(); } /// @brief access covariance matrix of the measured parameter values /// /// @return covariance matrix of the measurement - CovMatrix_t - covariance() const - { - return *m_oParameters.getCovariance(); - } + CovMatrix_t covariance() const { return *m_oParameters.getCovariance(); } /// @brief retrieve stored uncertainty for given parameter /// @@ -221,20 +201,14 @@ public: /// /// @return uncertainty \f$\sigma \ge 0\f$ for given parameter template <ParID_t parameter> - ParValue_t - uncertainty() const - { + ParValue_t uncertainty() const { return m_oParameters.template getUncertainty<parameter>(); } /// @brief number of measured parameters /// /// @return number of measured parameters - static constexpr unsigned int - size() - { - return ParSet_t::size(); - } + static constexpr unsigned int size() { return ParSet_t::size(); } /// @brief access associated surface /// @@ -242,11 +216,7 @@ public: /// must still be valid at the same memory location. /// /// @return reference to surface at which the measurement took place - const Acts::Surface& - referenceSurface() const - { - return *m_pSurface; - } + const Acts::Surface& referenceSurface() const { return *m_pSurface; } /// @brief link access to the source of the measurement. /// @@ -254,11 +224,7 @@ public: /// object, see description above. /// /// @return source_link_t object - const source_link_t& - sourceLink() const - { - return m_sourceLink; - } + const source_link_t& sourceLink() const { return m_sourceLink; } /// @brief calculate residual with respect to given track parameters /// @@ -276,9 +242,7 @@ public: /// @return vector with the residual parameter values (in valid range) /// /// @sa ParameterSet::residual - ParVector_t - residual(const TrackParameters& trackPars) const - { + ParVector_t residual(const TrackParameters& trackPars) const { return m_oParameters.residual(trackPars.getParameterSet()); } @@ -286,12 +250,11 @@ public: /// /// @return @c true if parameter sets and associated surfaces compare equal, /// otherwise @c false - virtual bool - operator==(const Measurement<source_link_t, params...>& rhs) const - { - return ((m_oParameters == rhs.m_oParameters) - && (*m_pSurface == *rhs.m_pSurface) - && (m_sourceLink == rhs.m_sourceLink)); + virtual bool operator==( + const Measurement<source_link_t, params...>& rhs) const { + return ((m_oParameters == rhs.m_oParameters) && + (*m_pSurface == *rhs.m_pSurface) && + (m_sourceLink == rhs.m_sourceLink)); } /// @brief inequality operator @@ -299,33 +262,24 @@ public: /// @return @c true if both objects are not equal, otherwise @c false /// /// @sa Measurement::operator== - bool - operator!=(const Measurement<source_link_t, params...>& rhs) const - { + bool operator!=(const Measurement<source_link_t, params...>& rhs) const { return !(*this == rhs); } /// @projection operator - static Projection_t - projector() - { - return ParSet_t::projector(); - } + static Projection_t projector() { return ParSet_t::projector(); } - friend std::ostream& - operator<<(std::ostream& out, const Measurement<source_link_t, params...>& m) - { + friend std::ostream& operator<<( + std::ostream& out, const Measurement<source_link_t, params...>& m) { m.print(out); return out; } -protected: - virtual std::ostream& - print(std::ostream& out) const - { + protected: + virtual std::ostream& print(std::ostream& out) const { out << sizeof...(params) << "D measurement: "; int dummy[sizeof...(params)] = {(out << params << ", ", 0)...}; - dummy[0] = dummy[0]; + dummy[0] = dummy[0]; out << std::endl; out << "measured values:" << std::endl; out << parameters() << std::endl; @@ -334,7 +288,7 @@ protected: return out; } -private: + private: ParSet_t m_oParameters; ///< measured parameter set std::shared_ptr<const Surface> m_pSurface; ///< surface at which the measurement took place @@ -347,11 +301,9 @@ private: * This encodes the source_link_t and hides it from the type generator. */ template <typename source_link_t> -struct fittable_measurement_helper -{ +struct fittable_measurement_helper { template <Acts::ParID_t... pars> - struct meas_factory - { + struct meas_factory { using type = Measurement<source_link_t, pars...>; }; diff --git a/Core/include/Acts/EventData/MeasurementHelpers.hpp b/Core/include/Acts/EventData/MeasurementHelpers.hpp index 1d57f36646d6494e08c74737722d2014367ff278..4e31f89e48026be4cfb74c22250504a381bca505 100644 --- a/Core/include/Acts/EventData/MeasurementHelpers.hpp +++ b/Core/include/Acts/EventData/MeasurementHelpers.hpp @@ -16,23 +16,19 @@ class Surface; namespace MeasurementHelpers { - /// @brief Extract surface from a type erased measurement object - /// @tparam T The FittableMeasurement type - /// @return const pointer to the extracted surface - template <typename T> - const Surface* - getSurface(const T& fittable_measurement) - { - return std::visit([](const auto& meas) { return &meas.referenceSurface(); }, - fittable_measurement); - } - - template <typename T> - size_t - getSize(const T& fittable_measurement) - { - return std::visit([](const auto& meas) { return meas.size(); }, - fittable_measurement); - } +/// @brief Extract surface from a type erased measurement object +/// @tparam T The FittableMeasurement type +/// @return const pointer to the extracted surface +template <typename T> +const Surface* getSurface(const T& fittable_measurement) { + return std::visit([](const auto& meas) { return &meas.referenceSurface(); }, + fittable_measurement); } + +template <typename T> +size_t getSize(const T& fittable_measurement) { + return std::visit([](const auto& meas) { return meas.size(); }, + fittable_measurement); } +} // namespace MeasurementHelpers +} // namespace Acts diff --git a/Core/include/Acts/EventData/NeutralParameters.hpp b/Core/include/Acts/EventData/NeutralParameters.hpp index 06b528fec1bcbf64f20cc66a1fc2a598af962c7a..44460a412f78db0f5efa97504910f617915f5a24 100644 --- a/Core/include/Acts/EventData/NeutralParameters.hpp +++ b/Core/include/Acts/EventData/NeutralParameters.hpp @@ -14,7 +14,7 @@ namespace Acts { using NeutralParameters = SingleTrackParameters<NeutralPolicy>; -using NeutralCurvilinearParameters - = SingleCurvilinearTrackParameters<NeutralPolicy>; +using NeutralCurvilinearParameters = + SingleCurvilinearTrackParameters<NeutralPolicy>; using NeutralBoundParameters = SingleBoundTrackParameters<NeutralPolicy>; } // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/EventData/ParameterSet.hpp b/Core/include/Acts/EventData/ParameterSet.hpp index d2865cb4e928a7783ce243d5ae797dc7517fdc61..ce1dc7f3787fc95a89a05c653d75c00374ef6bd7 100644 --- a/Core/include/Acts/EventData/ParameterSet.hpp +++ b/Core/include/Acts/EventData/ParameterSet.hpp @@ -77,21 +77,18 @@ using FullParameterSet = typename detail::full_parset::type; * stored in this class */ template <ParID_t... params> -class ParameterSet -{ -private: +class ParameterSet { + private: // local typedefs and constants using ParSet_t = ParameterSet<params...>; ///< type of this parameter set - static constexpr unsigned int NPars - = sizeof...(params); ///< number of parameters stored in this class + static constexpr unsigned int NPars = + sizeof...(params); ///< number of parameters stored in this class // static assert to check that the template parameters are consistent static_assert(detail::are_sorted<true, true, ParID_t, params...>::value, "parameter identifiers are not sorted"); static_assert( - detail::are_within<unsigned int, - 0, - Acts::NGlobalPars, + detail::are_within<unsigned int, 0, Acts::NGlobalPars, static_cast<unsigned int>(params)...>::value, "parameter identifiers must be greater or " "equal to zero and smaller than the total number of parameters"); @@ -100,7 +97,7 @@ private: NPars <= Acts::NGlobalPars, "number of stored parameters can not exceed number of total parameters"); -public: + public: // public typedefs /// matrix type for projecting full parameter vector onto local parameter /// space @@ -126,8 +123,7 @@ public: ParameterSet(CovPtr_t cov, std::enable_if_t<sizeof...(Tail) + 1 == NPars, ParValue_t> head, Tail... values) - : m_vValues(NPars), m_pCovariance(std::move(cov)) - { + : m_vValues(NPars), m_pCovariance(std::move(cov)) { detail::initialize_parset<ParID_t, params...>::init(*this, head, values...); } @@ -144,8 +140,7 @@ public: * @param values vector with parameter values */ ParameterSet(CovPtr_t cov, const ParVector_t& values) - : m_vValues(NPars), m_pCovariance(std::move(cov)) - { + : m_vValues(NPars), m_pCovariance(std::move(cov)) { detail::initialize_parset<ParID_t, params...>::init(*this, values); } @@ -156,8 +151,7 @@ public: * object */ ParameterSet(const ParSet_t& copy) - : m_vValues(copy.m_vValues), m_pCovariance(nullptr) - { + : m_vValues(copy.m_vValues), m_pCovariance(nullptr) { if (copy.m_pCovariance) { m_pCovariance = std::make_unique<const CovMatrix_t>(*copy.m_pCovariance); } @@ -170,10 +164,8 @@ public: * object */ ParameterSet(ParSet_t&& copy) - : m_vValues(std::move(copy.m_vValues)) - , m_pCovariance(std::move(copy.m_pCovariance)) - { - } + : m_vValues(std::move(copy.m_vValues)), + m_pCovariance(std::move(copy.m_pCovariance)) {} /** * @brief standard destructor @@ -185,14 +177,12 @@ public: * * @param rhs object whose content is assigned to this @c ParameterSet object */ - ParSet_t& - operator=(const ParSet_t& rhs) - { + ParSet_t& operator=(const ParSet_t& rhs) { m_vValues = rhs.m_vValues; - m_pCovariance - = (rhs.m_pCovariance - ? std::make_unique<const CovMatrix_t>(*rhs.m_pCovariance) - : nullptr); + m_pCovariance = + (rhs.m_pCovariance + ? std::make_unique<const CovMatrix_t>(*rhs.m_pCovariance) + : nullptr); return *this; } @@ -201,10 +191,8 @@ public: * * @param rhs object whose content is moved into this @c ParameterSet object */ - ParSet_t& - operator=(ParSet_t&& rhs) - { - m_vValues = std::move(rhs.m_vValues); + ParSet_t& operator=(ParSet_t&& rhs) { + m_vValues = std::move(rhs.m_vValues); m_pCovariance = std::move(rhs.m_pCovariance); return *this; } @@ -212,9 +200,7 @@ public: /** * @brief swap two objects */ - friend void - swap(ParSet_t& first, ParSet_t& second) noexcept - { + friend void swap(ParSet_t& first, ParSet_t& second) noexcept { using std::swap; swap(first.m_vValues, second.m_vValues); swap(first.m_pCovariance, second.m_pCovariance); @@ -230,9 +216,7 @@ public: * @return position of parameter in variadic template parameter set @c params */ template <ParID_t parameter> - static constexpr size_t - getIndex() - { + static constexpr size_t getIndex() { return detail::get_position<ParID_t, parameter, params...>::value; } @@ -248,9 +232,7 @@ public: * parameter set @c params */ template <size_t index> - static constexpr ParID_t - getParID() - { + static constexpr ParID_t getParID() { return detail::at_index<ParID_t, index, params...>::value; } @@ -264,9 +246,7 @@ public: * @return value of the stored parameter */ template <ParID_t parameter> - ParValue_t - getParameter() const - { + ParValue_t getParameter() const { return m_vValues(getIndex<parameter>()); } @@ -275,11 +255,7 @@ public: * * @return column vector with @c #NPars rows */ - ParVector_t - getParameters() const - { - return m_vValues; - } + ParVector_t getParameters() const { return m_vValues; } /** * @brief sets value for given parameter @@ -292,10 +268,8 @@ public: * @return previously stored value of this parameter */ template <ParID_t parameter> - void - setParameter(ParValue_t value) - { - using parameter_type = typename par_type<parameter>::type; + void setParameter(ParValue_t value) { + using parameter_type = typename par_type<parameter>::type; m_vValues(getIndex<parameter>()) = parameter_type::getValue(value); } @@ -308,9 +282,7 @@ public: * * @param values vector of length #NPars */ - void - setParameters(const ParVector_t& values) - { + void setParameters(const ParVector_t& values) { detail::initialize_parset<ParID_t, params...>::init(*this, values); } @@ -326,9 +298,7 @@ public: * @return @c true if the parameter is stored in this set, otherwise @c false */ template <ParID_t parameter> - bool - contains() const - { + bool contains() const { return detail::is_contained<ParID_t, parameter, params...>::value; } @@ -340,11 +310,7 @@ public: * * @return raw pointer to covariance matrix (can be a nullptr) */ - const CovMatrix_t* - getCovariance() const - { - return m_pCovariance.get(); - } + const CovMatrix_t* getCovariance() const { return m_pCovariance.get(); } /** * @brief access uncertainty for individual parameter @@ -359,9 +325,7 @@ public: * covariance matrix is set */ template <ParID_t parameter> - ParValue_t - getUncertainty() const - { + ParValue_t getUncertainty() const { if (m_pCovariance) { size_t index = getIndex<parameter>(); return sqrt((*m_pCovariance)(index, index)); @@ -377,11 +341,7 @@ public: * * @param cov unique pointer to new covariance matrix (nullptr is accepted) */ - void - setCovariance(CovPtr_t cov) - { - m_pCovariance = std::move(cov); - } + void setCovariance(CovPtr_t cov) { m_pCovariance = std::move(cov); } /** * @brief equality operator @@ -390,9 +350,7 @@ public: * matrices are * either identical or not set, otherwise @c false */ - bool - operator==(const ParSet_t& rhs) const - { + bool operator==(const ParSet_t& rhs) const { // shortcut comparison with myself if (&rhs == this) { return true; @@ -403,13 +361,13 @@ public: return false; } // both have covariance matrices set - if ((m_pCovariance && rhs.m_pCovariance) - && (*m_pCovariance != *rhs.m_pCovariance)) { + if ((m_pCovariance && rhs.m_pCovariance) && + (*m_pCovariance != *rhs.m_pCovariance)) { return false; } // only one has a covariance matrix set - if ((m_pCovariance && !rhs.m_pCovariance) - || (!m_pCovariance && rhs.m_pCovariance)) { + if ((m_pCovariance && !rhs.m_pCovariance) || + (!m_pCovariance && rhs.m_pCovariance)) { return false; } @@ -423,11 +381,7 @@ public: * * @sa ParameterSet::operator== */ - bool - operator!=(const ParSet_t& rhs) const - { - return !(*this == rhs); - } + bool operator!=(const ParSet_t& rhs) const { return !(*this == rhs); } /** * @brief project vector of full parameter set onto parameter sub-space @@ -454,9 +408,7 @@ public: * vector * which are also defined for this ParameterSet object */ - ParVector_t - project(const FullParameterSet& fullParSet) const - { + ParVector_t project(const FullParameterSet& fullParSet) const { return projector() * fullParSet.getParameters(); } @@ -499,9 +451,7 @@ public: typename T = ParSet_t, std::enable_if_t<not std::is_same<T, FullParameterSet>::value, int> = 0> /// @endcond - ParVector_t - residual(const FullParameterSet& fullParSet) const - { + ParVector_t residual(const FullParameterSet& fullParSet) const { return detail::residual_calculator<params...>::result( m_vValues, projector() * fullParSet.getParameters()); } @@ -538,9 +488,7 @@ public: * ParameterSet object * with respect to the given other parameter set */ - ParVector_t - residual(const ParSet_t& otherParSet) const - { + ParVector_t residual(const ParSet_t& otherParSet) const { return detail::residual_calculator<params...>::result( m_vValues, otherParSet.m_vValues); } @@ -555,9 +503,7 @@ public: * @return constant matrix with @c #NPars rows and @c #Acts::NGlobalPars * columns */ - static const ActsMatrix<ParValue_t, NPars, Acts::NGlobalPars> - projector() - { + static const ActsMatrix<ParValue_t, NPars, Acts::NGlobalPars> projector() { return sProjector; } @@ -566,11 +512,7 @@ public: * * @return number of stored parameters */ - static constexpr unsigned int - size() - { - return NPars; - } + static constexpr unsigned int size() { return NPars; } /** * @brief correct given parameter values @@ -584,15 +526,13 @@ public: * @param values vector with parameter values to be checked and corrected if * necessary */ - static void - correctValues(ParVector_t& values) - { + static void correctValues(ParVector_t& values) { detail::value_corrector<params...>::result(values); } -private: + private: ParVector_t - m_vValues; ///< column vector containing values of local parameters + m_vValues; ///< column vector containing values of local parameters CovPtr_t m_pCovariance; ///< unique pointer to covariance matrix static const Projection_t sProjector; ///< matrix to project full parameter @@ -605,8 +545,6 @@ constexpr unsigned int ParameterSet<params...>::NPars; template <ParID_t... params> const typename ParameterSet<params...>::Projection_t - ParameterSet<params...>::sProjector - = detail::make_projection_matrix<Acts::NGlobalPars, - static_cast<unsigned int>( - params)...>::init(); + ParameterSet<params...>::sProjector = detail::make_projection_matrix< + Acts::NGlobalPars, static_cast<unsigned int>(params)...>::init(); } // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/EventData/SingleBoundTrackParameters.hpp b/Core/include/Acts/EventData/SingleBoundTrackParameters.hpp index 25d339ed1ea2a4f0ec73c59de902cf17ac7d209d..2b8694e0d460f6087bcac859db0a56826331c3ce 100644 --- a/Core/include/Acts/EventData/SingleBoundTrackParameters.hpp +++ b/Core/include/Acts/EventData/SingleBoundTrackParameters.hpp @@ -24,11 +24,10 @@ namespace Acts { /// @note This class holds shared ownership on the surface it is associated /// to. template <class ChargePolicy> -class SingleBoundTrackParameters : public SingleTrackParameters<ChargePolicy> -{ -public: +class SingleBoundTrackParameters : public SingleTrackParameters<ChargePolicy> { + public: using ParVector_t = typename SingleTrackParameters<ChargePolicy>::ParVector_t; - using CovPtr_t = typename SingleTrackParameters<ChargePolicy>::CovPtr_t; + using CovPtr_t = typename SingleTrackParameters<ChargePolicy>::CovPtr_t; /// @brief Constructor of track parameters bound to a surface /// This is the constructor from global parameters, enabled only @@ -44,21 +43,16 @@ public: /// @param[in] surface The reference surface the parameters are bound to template <typename T = ChargePolicy, std::enable_if_t<std::is_same<T, ChargedPolicy>::value, int> = 0> - SingleBoundTrackParameters(const GeometryContext& gctx, - CovPtr_t cov, - const ParVector_t& parValues, + SingleBoundTrackParameters(const GeometryContext& gctx, CovPtr_t cov, + const ParVector_t& parValues, std::shared_ptr<const Surface> surface) - : SingleTrackParameters<ChargePolicy>( - std::move(cov), - parValues, - detail::coordinate_transformation::parameters2globalPosition( - gctx, - parValues, - *surface), - detail::coordinate_transformation::parameters2globalMomentum( - parValues)) - , m_pSurface(std::move(surface)) - { + : SingleTrackParameters<ChargePolicy>( + std::move(cov), parValues, + detail::coordinate_transformation::parameters2globalPosition( + gctx, parValues, *surface), + detail::coordinate_transformation::parameters2globalMomentum( + parValues)), + m_pSurface(std::move(surface)) { assert(m_pSurface); } @@ -79,23 +73,16 @@ public: /// @param[in] surface The reference surface the parameters are bound to template <typename T = ChargePolicy, std::enable_if_t<std::is_same<T, ChargedPolicy>::value, int> = 0> - SingleBoundTrackParameters(const GeometryContext& gctx, - CovPtr_t cov, - const ActsVectorD<3>& position, - const ActsVectorD<3>& momentum, - double dCharge, + SingleBoundTrackParameters(const GeometryContext& gctx, CovPtr_t cov, + const ActsVectorD<3>& position, + const ActsVectorD<3>& momentum, double dCharge, std::shared_ptr<const Surface> surface) - : SingleTrackParameters<ChargePolicy>( - std::move(cov), - detail::coordinate_transformation::global2parameters(gctx, - position, - momentum, - dCharge, - *surface), - position, - momentum) - , m_pSurface(std::move(surface)) - { + : SingleTrackParameters<ChargePolicy>( + std::move(cov), + detail::coordinate_transformation::global2parameters( + gctx, position, momentum, dCharge, *surface), + position, momentum), + m_pSurface(std::move(surface)) { assert(m_pSurface); } @@ -114,21 +101,16 @@ public: /// @param[in] surface The reference surface the parameters are bound to template <typename T = ChargePolicy, std::enable_if_t<std::is_same<T, NeutralPolicy>::value, int> = 0> - SingleBoundTrackParameters(const GeometryContext& gctx, - CovPtr_t cov, - const ParVector_t& parValues, + SingleBoundTrackParameters(const GeometryContext& gctx, CovPtr_t cov, + const ParVector_t& parValues, std::shared_ptr<const Surface> surface) - : SingleTrackParameters<ChargePolicy>( - std::move(cov), - parValues, - detail::coordinate_transformation::parameters2globalPosition( - gctx, - parValues, - *surface), - detail::coordinate_transformation::parameters2globalMomentum( - parValues)) - , m_pSurface(std::move(surface)) - { + : SingleTrackParameters<ChargePolicy>( + std::move(cov), parValues, + detail::coordinate_transformation::parameters2globalPosition( + gctx, parValues, *surface), + detail::coordinate_transformation::parameters2globalMomentum( + parValues)), + m_pSurface(std::move(surface)) { assert(m_pSurface); } @@ -150,66 +132,54 @@ public: /// @param[in] surface The reference surface the parameters are bound to template <typename T = ChargePolicy, std::enable_if_t<std::is_same<T, NeutralPolicy>::value, int> = 0> - SingleBoundTrackParameters(const GeometryContext& gctx, - CovPtr_t cov, - const ActsVectorD<3>& position, - const ActsVectorD<3>& momentum, + SingleBoundTrackParameters(const GeometryContext& gctx, CovPtr_t cov, + const ActsVectorD<3>& position, + const ActsVectorD<3>& momentum, std::shared_ptr<const Surface> surface) - : SingleTrackParameters<ChargePolicy>( - std::move(cov), - detail::coordinate_transformation::global2parameters(gctx, - position, - momentum, - 0, - *surface), - position, - momentum) - , m_pSurface(std::move(surface)) - { - } + : SingleTrackParameters<ChargePolicy>( + std::move(cov), + detail::coordinate_transformation::global2parameters( + gctx, position, momentum, 0, *surface), + position, momentum), + m_pSurface(std::move(surface)) {} /// @brief copy constructor - charged/neutral /// @param[in] copy The source parameters SingleBoundTrackParameters( const SingleBoundTrackParameters<ChargePolicy>& copy) - : SingleTrackParameters<ChargePolicy>(copy) - , m_pSurface(copy.m_pSurface) // copy shared_ptr - { - } + : SingleTrackParameters<ChargePolicy>(copy), + m_pSurface(copy.m_pSurface) // copy shared_ptr + {} /// @brief move constructor - charged/neutral /// @param[in] other The source parameters SingleBoundTrackParameters(SingleBoundTrackParameters<ChargePolicy>&& other) - : SingleTrackParameters<ChargePolicy>(std::move(other)) - , m_pSurface(std::move(other.m_pSurface)) - { - } + : SingleTrackParameters<ChargePolicy>(std::move(other)), + m_pSurface(std::move(other.m_pSurface)) {} /// @brief desctructor - charged/neutral /// checks if the surface is free and in such a case deletes it ~SingleBoundTrackParameters() override = default; /// @brief copy assignment operator - charged/neutral - SingleBoundTrackParameters<ChargePolicy>& - operator=(const SingleBoundTrackParameters<ChargePolicy>& rhs) - { + SingleBoundTrackParameters<ChargePolicy>& operator=( + const SingleBoundTrackParameters<ChargePolicy>& rhs) { // check for self-assignment if (this != &rhs) { SingleTrackParameters<ChargePolicy>::operator=(rhs); - m_pSurface = rhs.m_pSurface; + m_pSurface = rhs.m_pSurface; } return *this; } /// @brief move assignment operator - charged/neutral /// checks if the surface is free and in such a case delete-clones it - SingleBoundTrackParameters<ChargePolicy>& - operator=(SingleBoundTrackParameters<ChargePolicy>&& rhs) - { + SingleBoundTrackParameters<ChargePolicy>& operator=( + SingleBoundTrackParameters<ChargePolicy>&& rhs) { // check for self-assignment if (this != &rhs) { SingleTrackParameters<ChargePolicy>::operator=(std::move(rhs)); - m_pSurface = std::move(rhs.m_pSurface); + m_pSurface = std::move(rhs.m_pSurface); } return *this; @@ -217,9 +187,7 @@ public: /// @brief clone - charged/netural /// virtual constructor for type creation without casting - SingleBoundTrackParameters<ChargePolicy>* - clone() const override - { + SingleBoundTrackParameters<ChargePolicy>* clone() const override { return new SingleBoundTrackParameters<ChargePolicy>(*this); } @@ -229,19 +197,13 @@ public: /// @param[in] gctx is the Context object that is forwarded to the surface /// for local to global coordinate transformation template <ParID_t par> - void - set(const GeometryContext& gctx, ParValue_t newValue) - { + void set(const GeometryContext& gctx, ParValue_t newValue) { this->getParameterSet().template setParameter<par>(newValue); this->updateGlobalCoordinates(gctx, typename par_type<par>::type()); } /// @brief access method to the reference surface - const Surface& - referenceSurface() const final - { - return *m_pSurface; - } + const Surface& referenceSurface() const final { return *m_pSurface; } /// @brief access to the measurement frame, i.e. the rotation matrix with /// respect to the global coordinate system, in which the local error @@ -254,14 +216,12 @@ public: /// surface frame, for measurements with respect to a line this has to be /// constructed by the point of clostest approach to the line, for /// cylindrical surfaces this is (by convention) the tangential plane. - RotationMatrix3D - referenceFrame(const GeometryContext& gctx) const final - { + RotationMatrix3D referenceFrame(const GeometryContext& gctx) const final { return std::move( m_pSurface->referenceFrame(gctx, this->position(), this->momentum())); } -private: + private: std::shared_ptr<const Surface> m_pSurface; }; diff --git a/Core/include/Acts/EventData/SingleCurvilinearTrackParameters.hpp b/Core/include/Acts/EventData/SingleCurvilinearTrackParameters.hpp index 8ea78044a08f1e41f76aa33adb97fd97698c77e0..747b5e1dcd26025c1cda054c8cc0afef6c3e5f9d 100644 --- a/Core/include/Acts/EventData/SingleCurvilinearTrackParameters.hpp +++ b/Core/include/Acts/EventData/SingleCurvilinearTrackParameters.hpp @@ -24,9 +24,8 @@ namespace Acts { /// is constructed with the help of the global z axis. template <typename ChargePolicy> class SingleCurvilinearTrackParameters - : public SingleTrackParameters<ChargePolicy> -{ -public: + : public SingleTrackParameters<ChargePolicy> { + public: /// type of covariance matrix using CovPtr_t = typename SingleTrackParameters<ChargePolicy>::CovPtr_t; @@ -40,20 +39,15 @@ public: /// @param[in] dCharge The charge of this track parameterisation template <typename T = ChargePolicy, std::enable_if_t<std::is_same<T, ChargedPolicy>::value, int> = 0> - SingleCurvilinearTrackParameters(CovPtr_t cov, - const ActsVectorD<3>& position, + SingleCurvilinearTrackParameters(CovPtr_t cov, const ActsVectorD<3>& position, const ActsVectorD<3>& momentum, - double dCharge) - : SingleTrackParameters<ChargePolicy>( - std::move(cov), - detail::coordinate_transformation::global2curvilinear(position, - momentum, - dCharge), - position, - momentum) - , m_upSurface(Surface::makeShared<PlaneSurface>(position, momentum)) - { - } + double dCharge) + : SingleTrackParameters<ChargePolicy>( + std::move(cov), + detail::coordinate_transformation::global2curvilinear( + position, momentum, dCharge), + position, momentum), + m_upSurface(Surface::makeShared<PlaneSurface>(position, momentum)) {} /// @brief constructor for curvilienear representation /// This is the constructor from global parameters, enabled only @@ -64,73 +58,61 @@ public: /// @param[in] momentum The global momentum of this track parameterisation template <typename T = ChargePolicy, std::enable_if_t<std::is_same<T, NeutralPolicy>::value, int> = 0> - SingleCurvilinearTrackParameters(CovPtr_t cov, - const ActsVectorD<3>& position, + SingleCurvilinearTrackParameters(CovPtr_t cov, const ActsVectorD<3>& position, const ActsVectorD<3>& momentum) - : SingleTrackParameters<ChargePolicy>( - std::move(cov), - detail::coordinate_transformation::global2curvilinear(position, - momentum, - 0), - position, - momentum) - , m_upSurface(Surface::makeShared<PlaneSurface>(position, momentum)) - { - } + : SingleTrackParameters<ChargePolicy>( + std::move(cov), + detail::coordinate_transformation::global2curvilinear(position, + momentum, 0), + position, momentum), + m_upSurface(Surface::makeShared<PlaneSurface>(position, momentum)) {} /// @brief copy constructor - charged/neutral /// @param[in] copy The source parameters SingleCurvilinearTrackParameters( const SingleCurvilinearTrackParameters<ChargePolicy>& copy) - : SingleTrackParameters<ChargePolicy>(copy) - , m_upSurface(copy.m_upSurface) // copy shared ptr - { - } + : SingleTrackParameters<ChargePolicy>(copy), + m_upSurface(copy.m_upSurface) // copy shared ptr + {} /// @brief move constructor - charged/neutral /// @param[in] other The source parameters SingleCurvilinearTrackParameters( SingleCurvilinearTrackParameters<ChargePolicy>&& other) - : SingleTrackParameters<ChargePolicy>(std::move(other)) - , m_upSurface(std::move(other.m_upSurface)) - { - } + : SingleTrackParameters<ChargePolicy>(std::move(other)), + m_upSurface(std::move(other.m_upSurface)) {} /// @brief desctructor ~SingleCurvilinearTrackParameters() override = default; /// @brief copy assignment operator - charged/netural /// virtual constructor for type creation without casting - SingleCurvilinearTrackParameters<ChargePolicy>& - operator=(const SingleCurvilinearTrackParameters<ChargePolicy>& rhs) - { + SingleCurvilinearTrackParameters<ChargePolicy>& operator=( + const SingleCurvilinearTrackParameters<ChargePolicy>& rhs) { // check for self-assignment if (this != &rhs) { SingleTrackParameters<ChargePolicy>::operator=(rhs); - m_upSurface = Surface::makeShared<PlaneSurface>(this->position(), - this->momentum()); + m_upSurface = + Surface::makeShared<PlaneSurface>(this->position(), this->momentum()); } return *this; } /// @brief move assignment operator - charged/netural /// virtual constructor for type creation without casting - SingleCurvilinearTrackParameters<ChargePolicy>& - operator=(SingleCurvilinearTrackParameters<ChargePolicy>&& rhs) - { + SingleCurvilinearTrackParameters<ChargePolicy>& operator=( + SingleCurvilinearTrackParameters<ChargePolicy>&& rhs) { // check for self-assignment if (this != &rhs) { SingleTrackParameters<ChargePolicy>::operator=(std::move(rhs)); - m_upSurface = std::move(rhs.m_upSurface); + m_upSurface = std::move(rhs.m_upSurface); } return *this; } /// @brief clone - charged/netural /// virtual constructor for type creation without casting - SingleTrackParameters<ChargePolicy>* - clone() const override - { + SingleTrackParameters<ChargePolicy>* clone() const override { return new SingleCurvilinearTrackParameters<ChargePolicy>(*this); } @@ -148,9 +130,7 @@ public: std::enable_if_t<std::is_same<typename par_type<par>::type, local_parameter>::value, int> = 0> - void - set(const GeometryContext& gctx, ParValue_t newValue) - { + void set(const GeometryContext& gctx, ParValue_t newValue) { // set the parameter & update the new global position this->getParameterSet().template setParameter<par>(newValue); this->updateGlobalCoordinates(gctx, typename par_type<par>::type()); @@ -175,9 +155,7 @@ public: std::enable_if_t<not std::is_same<typename par_type<par>::type, local_parameter>::value, int> = 0> - void - set(const GeometryContext& gctx, ParValue_t newValue) - { + void set(const GeometryContext& gctx, ParValue_t newValue) { this->getParameterSet().template setParameter<par>(newValue); this->updateGlobalCoordinates(gctx, typename par_type<par>::type()); // recreate the surface @@ -186,11 +164,7 @@ public: } /// @brief access to the reference surface - const Surface& - referenceSurface() const final - { - return *m_upSurface; - } + const Surface& referenceSurface() const final { return *m_upSurface; } /// @brief access to the measurement frame, i.e. the rotation matrix with /// respect to the global coordinate system, in which the local error @@ -201,13 +175,11 @@ public: /// /// @note For a curvilinear track parameterisation this is identical to /// the rotation matrix of the intrinsic planar surface. - RotationMatrix3D - referenceFrame(const GeometryContext& gctx) const final - { + RotationMatrix3D referenceFrame(const GeometryContext& gctx) const final { return m_upSurface->transform(gctx).linear(); } -private: + private: std::shared_ptr<PlaneSurface> m_upSurface; }; } // namespace Acts diff --git a/Core/include/Acts/EventData/SingleTrackParameters.hpp b/Core/include/Acts/EventData/SingleTrackParameters.hpp index 09107512a8ffdb00f694d005a30058fa26611089..1a661ddf3f432ca83ff52ec968980130f264e362 100644 --- a/Core/include/Acts/EventData/SingleTrackParameters.hpp +++ b/Core/include/Acts/EventData/SingleTrackParameters.hpp @@ -31,14 +31,13 @@ namespace Acts { /// tracks/particles /// (must be either ChargedPolicy or NeutralPolicy) template <class ChargePolicy> -class SingleTrackParameters : public TrackParametersBase -{ - static_assert(std::is_same<ChargePolicy, ChargedPolicy>::value - or std::is_same<ChargePolicy, NeutralPolicy>::value, +class SingleTrackParameters : public TrackParametersBase { + static_assert(std::is_same<ChargePolicy, ChargedPolicy>::value or + std::is_same<ChargePolicy, NeutralPolicy>::value, "ChargePolicy must either be 'Acts::ChargedPolicy' or " "'Acts::NeutralPolicy"); -public: + public: // public typedef's /// vector type for stored track parameters @@ -54,56 +53,39 @@ public: ~SingleTrackParameters() override = default; /// @brief virtual constructor - SingleTrackParameters<ChargePolicy>* - clone() const override = 0; + SingleTrackParameters<ChargePolicy>* clone() const override = 0; /// @copydoc TrackParametersBase::position - ActsVectorD<3> - position() const final - { - return m_vPosition; - } + ActsVectorD<3> position() const final { return m_vPosition; } /// @copydoc TrackParametersBase::momentum - ActsVectorD<3> - momentum() const final - { - return m_vMomentum; - } + ActsVectorD<3> momentum() const final { return m_vMomentum; } /// @brief equality operator /// /// @return @c true of both objects have the same charge policy, parameter /// values, position and momentum, otherwise @c false - bool - operator==(const TrackParametersBase& rhs) const override - { + bool operator==(const TrackParametersBase& rhs) const override { auto casted = dynamic_cast<decltype(this)>(&rhs); if (!casted) { return false; } - return (m_oChargePolicy == casted->m_oChargePolicy - && m_oParameters == casted->m_oParameters - && m_vPosition == casted->m_vPosition - && m_vMomentum == casted->m_vMomentum); + return (m_oChargePolicy == casted->m_oChargePolicy && + m_oParameters == casted->m_oParameters && + m_vPosition == casted->m_vPosition && + m_vMomentum == casted->m_vMomentum); } /// @copydoc TrackParametersBase::charge - double - charge() const final - { - return m_oChargePolicy.getCharge(); - } + double charge() const final { return m_oChargePolicy.getCharge(); } /// @copydoc TrackParametersBase::getParameterSet - const FullParameterSet& - getParameterSet() const final - { + const FullParameterSet& getParameterSet() const final { return m_oParameters; } -protected: + protected: /// @brief standard constructor for track parameters of charged particles /// /// @param cov unique pointer to covariance matrix (nullptr is accepted) @@ -112,18 +94,15 @@ protected: /// @param momentum 3D vector with global momentum template <typename T = ChargePolicy, std::enable_if_t<std::is_same<T, ChargedPolicy>::value, int> = 0> - SingleTrackParameters(CovPtr_t cov, - const ParVector_t& parValues, + SingleTrackParameters(CovPtr_t cov, const ParVector_t& parValues, const ActsVectorD<3>& position, const ActsVectorD<3>& momentum) - : TrackParametersBase() - , m_oChargePolicy( - detail::coordinate_transformation::parameters2charge(parValues)) - , m_oParameters(std::move(cov), parValues) - , m_vPosition(position) - , m_vMomentum(momentum) - { - } + : TrackParametersBase(), + m_oChargePolicy( + detail::coordinate_transformation::parameters2charge(parValues)), + m_oParameters(std::move(cov), parValues), + m_vPosition(position), + m_vMomentum(momentum) {} /// @brief standard constructor for track parameters of neutral particles /// @@ -133,21 +112,18 @@ protected: /// @param momentum 3D vector with global momentum template <typename T = ChargePolicy, std::enable_if_t<std::is_same<T, NeutralPolicy>::value, int> = 0> - SingleTrackParameters(CovPtr_t cov, - const ParVector_t& parValues, + SingleTrackParameters(CovPtr_t cov, const ParVector_t& parValues, const ActsVectorD<3>& position, const ActsVectorD<3>& momentum) - : TrackParametersBase() - , m_oChargePolicy() - , m_oParameters(std::move(cov), parValues) - , m_vPosition(position) - , m_vMomentum(momentum) - { - } + : TrackParametersBase(), + m_oChargePolicy(), + m_oParameters(std::move(cov), parValues), + m_vPosition(position), + m_vMomentum(momentum) {} /// @brief default copy constructor - SingleTrackParameters(const SingleTrackParameters<ChargePolicy>& copy) - = default; + SingleTrackParameters(const SingleTrackParameters<ChargePolicy>& copy) = + default; /// @brief default move constructor SingleTrackParameters(SingleTrackParameters<ChargePolicy>&& copy) = default; @@ -155,15 +131,14 @@ protected: /// @brief copy assignment operator /// /// @param rhs object to be copied - SingleTrackParameters<ChargePolicy>& - operator=(const SingleTrackParameters<ChargePolicy>& rhs) - { + SingleTrackParameters<ChargePolicy>& operator=( + const SingleTrackParameters<ChargePolicy>& rhs) { // check for self-assignment if (this != &rhs) { m_oChargePolicy = rhs.m_oChargePolicy; - m_oParameters = rhs.m_oParameters; - m_vPosition = rhs.m_vPosition; - m_vMomentum = rhs.m_vMomentum; + m_oParameters = rhs.m_oParameters; + m_vPosition = rhs.m_vPosition; + m_vMomentum = rhs.m_vMomentum; } return *this; @@ -172,26 +147,21 @@ protected: /// @brief move assignment operator /// /// @param rhs object to be movied into `*this` - SingleTrackParameters<ChargePolicy>& - operator=(SingleTrackParameters<ChargePolicy>&& rhs) - { + SingleTrackParameters<ChargePolicy>& operator=( + SingleTrackParameters<ChargePolicy>&& rhs) { // check for self-assignment if (this != &rhs) { m_oChargePolicy = std::move(rhs.m_oChargePolicy); - m_oParameters = std::move(rhs.m_oParameters); - m_vPosition = std::move(rhs.m_vPosition); - m_vMomentum = std::move(rhs.m_vMomentum); + m_oParameters = std::move(rhs.m_oParameters); + m_vPosition = std::move(rhs.m_vPosition); + m_vMomentum = std::move(rhs.m_vMomentum); } return *this; } /// @copydoc TrackParametersBase::getParameterSet - virtual FullParameterSet& - getParameterSet() final - { - return m_oParameters; - } + virtual FullParameterSet& getParameterSet() final { return m_oParameters; } /// @brief update global momentum from current parameter values /// @@ -202,9 +172,8 @@ protected: /// @note This function is triggered when called with an argument of a type /// different from Acts::local_parameter template <typename T> - void - updateGlobalCoordinates(const GeometryContext& /*gctx*/, const T& /*unused*/) - { + void updateGlobalCoordinates(const GeometryContext& /*gctx*/, + const T& /*unused*/) { m_vMomentum = detail::coordinate_transformation::parameters2globalMomentum( getParameterSet().getParameters()); } @@ -213,10 +182,8 @@ protected: /// /// @note This function is triggered when called with an argument of a type /// Acts::local_parameter - void - updateGlobalCoordinates(const GeometryContext& gctx, - const local_parameter& /*unused*/) - { + void updateGlobalCoordinates(const GeometryContext& gctx, + const local_parameter& /*unused*/) { m_vPosition = detail::coordinate_transformation::parameters2globalPosition( gctx, getParameterSet().getParameters(), this->referenceSurface()); } diff --git a/Core/include/Acts/EventData/TrackParameters.hpp b/Core/include/Acts/EventData/TrackParameters.hpp index 635697530d534744a426ecd56a36c3f457e246f2..b36b5a9e6c2296257940c462d12cb4b8d19323da 100644 --- a/Core/include/Acts/EventData/TrackParameters.hpp +++ b/Core/include/Acts/EventData/TrackParameters.hpp @@ -13,7 +13,7 @@ #include "Acts/EventData/SingleTrackParameters.hpp" namespace Acts { -using TrackParameters = SingleTrackParameters<ChargedPolicy>; +using TrackParameters = SingleTrackParameters<ChargedPolicy>; using CurvilinearParameters = SingleCurvilinearTrackParameters<ChargedPolicy>; -using BoundParameters = SingleBoundTrackParameters<ChargedPolicy>; +using BoundParameters = SingleBoundTrackParameters<ChargedPolicy>; } // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/EventData/TrackParametersBase.hpp b/Core/include/Acts/EventData/TrackParametersBase.hpp index 3b94aae336a8778425877d28688225cb487ff470..e85a1b6338bfc187225353c32107cd3029f9ca7e 100644 --- a/Core/include/Acts/EventData/TrackParametersBase.hpp +++ b/Core/include/Acts/EventData/TrackParametersBase.hpp @@ -31,9 +31,8 @@ class Surface; /// system. The track parameters and their uncertainty are defined in local /// reference frame which depends on the associated surface /// of the track parameters. -class TrackParametersBase -{ -public: +class TrackParametersBase { + public: // public typedef's /// vector type for stored track parameters @@ -46,44 +45,34 @@ public: virtual ~TrackParametersBase() = default; /// @brief virtual constructor - virtual TrackParametersBase* - clone() const = 0; + virtual TrackParametersBase* clone() const = 0; /// @brief equality operator - virtual bool - operator==(const TrackParametersBase& rhs) const = 0; + virtual bool operator==(const TrackParametersBase& rhs) const = 0; /// @brief inequality operator /// /// @return `not (*this == rhs)` - bool - operator!=(const TrackParametersBase& rhs) const - { + bool operator!=(const TrackParametersBase& rhs) const { return !(*this == rhs); } /// @brief access position in global coordinate system /// /// @return 3D vector with global position - virtual ActsVectorD<3> - position() const = 0; + virtual ActsVectorD<3> position() const = 0; /// @brief access momentum in global coordinate system /// /// @return 3D vector with global momentum - virtual ActsVectorD<3> - momentum() const = 0; + virtual ActsVectorD<3> momentum() const = 0; /// @brief access track parameters /// /// @return Eigen vector of dimension Acts::NGlobalPars with values of the /// track parameters /// (in the order as defined by the ParID_t enumeration) - ParVector_t - parameters() const - { - return getParameterSet().getParameters(); - } + ParVector_t parameters() const { return getParameterSet().getParameters(); } /// @brief access track parameter /// @@ -93,9 +82,7 @@ public: /// /// @sa ParameterSet::get template <ParID_t par> - ParValue_t - get() const - { + ParValue_t get() const { return getParameterSet().template getParameter<par>(); } @@ -105,9 +92,7 @@ public: /// /// @return value of the requested track parameter uncertainty template <ParID_t par> - ParValue_t - uncertainty() const - { + ParValue_t uncertainty() const { return getParameterSet().template getUncertainty<par>(); } @@ -119,38 +104,26 @@ public: /// @return raw pointer to covariance matrix (can be a nullptr) /// /// @sa ParameterSet::getCovariance - const CovMatrix_t* - covariance() const - { + const CovMatrix_t* covariance() const { return getParameterSet().getCovariance(); } /// @brief convenience method to retrieve transverse momentum - double - pT() const - { - return VectorHelpers::perp(momentum()); - } + double pT() const { return VectorHelpers::perp(momentum()); } /// @brief convenience method to retrieve pseudorapidity - double - eta() const - { - return VectorHelpers::eta(momentum()); - } + double eta() const { return VectorHelpers::eta(momentum()); } /// @brief retrieve electric charge /// /// @return value of electric charge - virtual double - charge() const = 0; + virtual double charge() const = 0; /// @brief access associated surface defining the coordinate system for track /// parameters and their covariance /// /// @return associated surface - virtual const Surface& - referenceSurface() const = 0; + virtual const Surface& referenceSurface() const = 0; /// @brief access to the measurement frame, i.e. the rotation matrix with /// respect to the global coordinate system, in which the local error @@ -164,8 +137,8 @@ public: /// surface frame, for measurements with respect to a line this has to be /// constructed by the point of clostest approach to the line, for /// cylindrical surfaces this is (by convention) the tangential plane. - virtual RotationMatrix3D - referenceFrame(const GeometryContext& gctx) const = 0; + virtual RotationMatrix3D referenceFrame( + const GeometryContext& gctx) const = 0; /// @brief output stream operator /// @@ -174,9 +147,8 @@ public: /// TrackParameters::print method. /// /// @return modified output stream object - friend std::ostream& - operator<<(std::ostream& out, const TrackParametersBase& tp) - { + friend std::ostream& operator<<(std::ostream& out, + const TrackParametersBase& tp) { tp.print(out); return out; } @@ -185,14 +157,12 @@ public: /// /// @return ParameterSet object holding parameter values and their covariance /// matrix - virtual const FullParameterSet& - getParameterSet() const = 0; + virtual const FullParameterSet& getParameterSet() const = 0; -protected: + protected: /// @brief print information to output stream /// /// @return modified output stream object - virtual std::ostream& - print(std::ostream& sl) const; + virtual std::ostream& print(std::ostream& sl) const; }; } // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/EventData/TrackState.hpp b/Core/include/Acts/EventData/TrackState.hpp index 16203618810c4c444d8124624ad0982f13f59845..f303cc3ff85ed8ffd762f6dad720754449a7412b 100644 --- a/Core/include/Acts/EventData/TrackState.hpp +++ b/Core/include/Acts/EventData/TrackState.hpp @@ -29,21 +29,18 @@ class Surface; /// @note the Surface is only stored as a pointer, i.e. it is /// assumed the surface lives longer than the TrackState template <typename identifier_t, typename parameters_t> -class TrackState -{ - -public: +class TrackState { + public: using Identifier = identifier_t; using Parameters = parameters_t; - using Jacobian = typename Parameters::CovMatrix_t; + using Jacobian = typename Parameters::CovMatrix_t; /// Constructor from (uncalibrated) measurement /// /// @tparam measurement_t Type of the measurement /// @param m The measurement object - TrackState(FittableMeasurement<identifier_t> m) - { - m_surface = MeasurementHelpers::getSurface(m); + TrackState(FittableMeasurement<identifier_t> m) { + m_surface = MeasurementHelpers::getSurface(m); measurement.uncalibrated = std::move(m); } @@ -51,9 +48,8 @@ public: /// /// @tparam parameters_t Type of the predicted parameters /// @param p The parameters object - TrackState(parameters_t p) - { - m_surface = &p.referenceSurface(); + TrackState(parameters_t p) { + m_surface = &p.referenceSurface(); parameter.predicted = std::move(p); } @@ -64,61 +60,47 @@ public: /// /// @param rhs is the source TrackState TrackState(const TrackState& rhs) - : parameter(rhs.parameter) - , measurement(rhs.measurement) - , m_surface(rhs.m_surface) - { - } + : parameter(rhs.parameter), + measurement(rhs.measurement), + m_surface(rhs.m_surface) {} /// Copy move constructor /// /// @param rhs is the source TrackState TrackState(TrackState&& rhs) - : parameter(std::move(rhs.parameter)) - , measurement(std::move(rhs.measurement)) - , m_surface(std::move(rhs.m_surface)) - { - } + : parameter(std::move(rhs.parameter)), + measurement(std::move(rhs.measurement)), + m_surface(std::move(rhs.m_surface)) {} /// Assignment operator /// /// @param rhs is the source TrackState - TrackState& - operator=(const TrackState& rhs) - { - parameter = rhs.parameter; + TrackState& operator=(const TrackState& rhs) { + parameter = rhs.parameter; measurement = rhs.measurement; - m_surface = rhs.m_surface; + m_surface = rhs.m_surface; return (*this); } /// Assignment move operator /// /// @param rhs is the source TrackState - TrackState& - operator=(TrackState&& rhs) - { - parameter = std::move(rhs.parameter); + TrackState& operator=(TrackState&& rhs) { + parameter = std::move(rhs.parameter); measurement = std::move(rhs.measurement); - m_surface = std::move(rhs.m_surface); + m_surface = std::move(rhs.m_surface); return (*this); } /// @brief return method for the surface - const Surface& - referenceSurface() const - { - return (*m_surface); - } + const Surface& referenceSurface() const { return (*m_surface); } /// @brief number of Measured parameters, forwarded /// @note This only returns a value if either of the measurements /// are set. If not, this returns boost::none /// /// @return number of measured parameters, or boost::none - boost::optional<size_t> - size() - { + boost::optional<size_t> size() { if (this->measurement.uncalibrated) { return MeasurementHelpers::getSize(*this->measurement.uncalibrated); } @@ -132,8 +114,7 @@ public: /// This is all the information that concerns the /// the track parameterisation and the jacobian /// It is enough to to run the track smoothing - struct - { + struct { /// The predicted state boost::optional<Parameters> predicted{boost::none}; /// The filtered state @@ -151,8 +132,7 @@ public: /// @brief Nested measurement part /// This is the uncalibrated and calibrated measurement /// (in case the latter is different) - struct - { + struct { /// The optional (uncalibrated) measurement boost::optional<FittableMeasurement<identifier_t>> uncalibrated{ boost::none}; @@ -160,8 +140,8 @@ public: boost::optional<FittableMeasurement<identifier_t>> calibrated{boost::none}; } measurement; -private: + private: /// The surface of this TrackState const Surface* m_surface = nullptr; }; -} +} // namespace Acts diff --git a/Core/include/Acts/EventData/TrackStateSorters.hpp b/Core/include/Acts/EventData/TrackStateSorters.hpp index f390153a5f2ed80289926ae36ad415bc0304b589..db3956b40f92e7956dcd6b047d7a12fd25bda8a6 100644 --- a/Core/include/Acts/EventData/TrackStateSorters.hpp +++ b/Core/include/Acts/EventData/TrackStateSorters.hpp @@ -13,9 +13,8 @@ namespace Acts { * Struct that sorts trackstates using their path lengths. * This can be used as a sorter in STL functions. */ -struct TrackStatePathLengthSorter -{ -public: +struct TrackStatePathLengthSorter { + public: /** * The sorting operator * @tparam identifier_t Identifier of the track state @@ -25,11 +24,9 @@ public: * @return bool */ template <typename identifier_t, typename parameters_t> - bool - operator()(const TrackState<identifier_t, parameters_t>& lhs, - const TrackState<identifier_t, parameters_t>& rhs) - { + bool operator()(const TrackState<identifier_t, parameters_t>& lhs, + const TrackState<identifier_t, parameters_t>& rhs) { return lhs.parameter.pathLength < rhs.parameter.pathLength; } }; -} +} // namespace Acts diff --git a/Core/include/Acts/EventData/detail/coordinate_transformations.hpp b/Core/include/Acts/EventData/detail/coordinate_transformations.hpp index b8879e77d7b7d9fbe20bbd77feabf7a942b1f325..812c92a5a7c73747ce02da4587ec0c3ee522e397 100644 --- a/Core/include/Acts/EventData/detail/coordinate_transformations.hpp +++ b/Core/include/Acts/EventData/detail/coordinate_transformations.hpp @@ -23,124 +23,111 @@ namespace Acts { /// @cond detail namespace detail { - /// @brief helper structure summarizing coordinate transformations - /// - struct coordinate_transformation - { - using ParVector_t = ActsVector<ParValue_t, Acts::NGlobalPars>; +/// @brief helper structure summarizing coordinate transformations +/// +struct coordinate_transformation { + using ParVector_t = ActsVector<ParValue_t, Acts::NGlobalPars>; - /// @brief static method to transform the local information in - /// the track parameterisation to a global position - /// - /// This transformation uses the surface and hence needs a context - /// object to guarantee the local to global transformation is done - /// within the right (alginment/conditions) context - /// - /// @param gctx The current geometry context object, e.g. alignment - /// @param pars the parameter vector - /// @param s the surface for the local to global transform - /// - /// @return position in the global frame - static ActsVectorD<3> - parameters2globalPosition(const GeometryContext& gctx, - const ParVector_t& pars, - const Surface& s) - { - ActsVectorD<3> globalPosition; - s.localToGlobal(gctx, - ActsVectorD<2>(pars(Acts::eLOC_0), pars(Acts::eLOC_1)), - parameters2globalMomentum(pars), - globalPosition); - return globalPosition; - } + /// @brief static method to transform the local information in + /// the track parameterisation to a global position + /// + /// This transformation uses the surface and hence needs a context + /// object to guarantee the local to global transformation is done + /// within the right (alginment/conditions) context + /// + /// @param gctx The current geometry context object, e.g. alignment + /// @param pars the parameter vector + /// @param s the surface for the local to global transform + /// + /// @return position in the global frame + static ActsVectorD<3> parameters2globalPosition(const GeometryContext& gctx, + const ParVector_t& pars, + const Surface& s) { + ActsVectorD<3> globalPosition; + s.localToGlobal(gctx, + ActsVectorD<2>(pars(Acts::eLOC_0), pars(Acts::eLOC_1)), + parameters2globalMomentum(pars), globalPosition); + return globalPosition; + } - /// @brief static method to transform the momentum parameterisation - /// into a global momentum vector - /// - /// This transformation does not use the surface and hence no context - /// object is needed - /// - /// @param pars the parameter vector - /// - /// @return momentum in the global frame - static ActsVectorD<3> - parameters2globalMomentum(const ParVector_t& pars) - { - ActsVectorD<3> momentum; - double p = std::abs(1. / pars(Acts::eQOP)); - double phi = pars(Acts::ePHI); - double theta = pars(Acts::eTHETA); - momentum << p * sin(theta) * cos(phi), p * sin(theta) * sin(phi), - p * cos(theta); + /// @brief static method to transform the momentum parameterisation + /// into a global momentum vector + /// + /// This transformation does not use the surface and hence no context + /// object is needed + /// + /// @param pars the parameter vector + /// + /// @return momentum in the global frame + static ActsVectorD<3> parameters2globalMomentum(const ParVector_t& pars) { + ActsVectorD<3> momentum; + double p = std::abs(1. / pars(Acts::eQOP)); + double phi = pars(Acts::ePHI); + double theta = pars(Acts::eTHETA); + momentum << p * sin(theta) * cos(phi), p * sin(theta) * sin(phi), + p * cos(theta); - return momentum; - } + return momentum; + } - /// @brief static method to transform a global representation into - /// a curvilinear represenation - /// - /// This transformation does not use the surface and hence no context - /// object is needed - /// - /// @param pos - ignored - /// @param mom the global momentum parameters - /// @param charge of the particle/track - /// - /// @return curvilinear parameter representation - static ParVector_t - global2curvilinear(const ActsVectorD<3>& /*pos*/, - const ActsVectorD<3>& mom, - double charge) - { - using VectorHelpers::phi; - using VectorHelpers::theta; - ParVector_t parameters; - parameters << 0, 0, phi(mom), theta(mom), - ((std::abs(charge) < 1e-4) ? 1. : charge) / mom.norm(); + /// @brief static method to transform a global representation into + /// a curvilinear represenation + /// + /// This transformation does not use the surface and hence no context + /// object is needed + /// + /// @param pos - ignored + /// @param mom the global momentum parameters + /// @param charge of the particle/track + /// + /// @return curvilinear parameter representation + static ParVector_t global2curvilinear(const ActsVectorD<3>& /*pos*/, + const ActsVectorD<3>& mom, + double charge) { + using VectorHelpers::phi; + using VectorHelpers::theta; + ParVector_t parameters; + parameters << 0, 0, phi(mom), theta(mom), + ((std::abs(charge) < 1e-4) ? 1. : charge) / mom.norm(); - return parameters; - } + return parameters; + } - /// @brief static method to transform the global information into - /// the track parameterisation - /// - /// This transformation uses the surface and hence needs a context - /// object to guarantee the local to global transformation is done - /// within the right (alginment/conditions) context - /// - /// @param gctx The current geometry context object, e.g. alignment - /// @param pos position of the parameterisation in global - /// @param mom position of the parameterisation in global - /// @param charge of the particle/track - /// @param s the surface for the global to local transform - /// - /// @return the track parameterisation - static ParVector_t - global2parameters(const GeometryContext& gctx, - const ActsVectorD<3>& pos, - const ActsVectorD<3>& mom, - double charge, - const Surface& s) - { - using VectorHelpers::phi; - using VectorHelpers::theta; - ActsVectorD<2> localPosition; - s.globalToLocal(gctx, pos, mom, localPosition); - ParVector_t result; - result << localPosition(0), localPosition(1), phi(mom), theta(mom), - ((std::abs(charge) < 1e-4) ? 1. : charge) / mom.norm(); - return result; - } + /// @brief static method to transform the global information into + /// the track parameterisation + /// + /// This transformation uses the surface and hence needs a context + /// object to guarantee the local to global transformation is done + /// within the right (alginment/conditions) context + /// + /// @param gctx The current geometry context object, e.g. alignment + /// @param pos position of the parameterisation in global + /// @param mom position of the parameterisation in global + /// @param charge of the particle/track + /// @param s the surface for the global to local transform + /// + /// @return the track parameterisation + static ParVector_t global2parameters(const GeometryContext& gctx, + const ActsVectorD<3>& pos, + const ActsVectorD<3>& mom, double charge, + const Surface& s) { + using VectorHelpers::phi; + using VectorHelpers::theta; + ActsVectorD<2> localPosition; + s.globalToLocal(gctx, pos, mom, localPosition); + ParVector_t result; + result << localPosition(0), localPosition(1), phi(mom), theta(mom), + ((std::abs(charge) < 1e-4) ? 1. : charge) / mom.norm(); + return result; + } - /// @brief static calculate the charge from the track parameterisation - /// - /// @return the charge as a double - static double - parameters2charge(const ParVector_t& pars) - { - return (pars(Acts::eQOP) > 0) ? 1. : -1.; - } - }; + /// @brief static calculate the charge from the track parameterisation + /// + /// @return the charge as a double + static double parameters2charge(const ParVector_t& pars) { + return (pars(Acts::eQOP) > 0) ? 1. : -1.; + } +}; } // namespace detail /// @endcond } // namespace Acts diff --git a/Core/include/Acts/EventData/detail/fittable_type_generator.hpp b/Core/include/Acts/EventData/detail/fittable_type_generator.hpp index 2ccce17c621e1747a24d7788cca832ab3a571a60..59f0678dd09818fb8631889b411b94169581b290 100644 --- a/Core/include/Acts/EventData/detail/fittable_type_generator.hpp +++ b/Core/include/Acts/EventData/detail/fittable_type_generator.hpp @@ -28,94 +28,89 @@ class Measurement; /// @cond detail namespace detail { - namespace hana = boost::hana; +namespace hana = boost::hana; - /** - * @brief Constexpr function which produces a tuple that contains all unique - * ordered sublists of the range from 0 to W. - * This will generate: - * | W | output | - * |:---|:---------------------------------------------------| - * | 1 | [(0)] | - * | 2 | [(0), (1), (0, 1)] | - * | 3 | [(0), (1), (0, 1), (2), (0, 2), (1, 2), (0, 1, 2)] | - * - * In python, this algorithm would be roughly equivalent to - * ```python - * comb = [()] - * for i in range(0, 6): - * comb = comb + [c + (i,) for c in comb] - * comb = comb[1:] - * ``` - * or using `foldl = lambda func, acc, xs: functools.reduce(func, xs, acc)`: - * ```python - * def unique_ordered_subset(n): - * comb = [()] - * comb = foldl(lambda c, i: c+[c_i+(i,) for c_i in c], comb, range(0, n)) - * return comb[1:] - * ``` - * - * @tparam W End of the range (exclusive) - */ - template <size_t W> - constexpr auto - unique_ordered_sublists() - { - using namespace hana::literals; - // generate an empty tuple to start off - constexpr auto combinations = hana::make_tuple(hana::make_tuple()); - // generate range over which to fold - constexpr auto w_range - = hana::to_tuple(hana::make_range(0_c, hana::size_c<W>)); - // main fold expression. This successively adds variations to `state` and - // then - // returns the result. - constexpr auto comb2 - = hana::fold_left(w_range, combinations, [](auto state, auto i) { - auto mapped = hana::transform( - state, [i](auto c_i) { return hana::append(c_i, i); }); - return hana::concat(state, mapped); - }); - // we need to pop off the initial empty tuple, which isn't really valid - return hana::remove_at(comb2, 0_c); - } - - /** - * Generates a tuple of types using `unique_ordered_sublists` from above. - * @tparam meas_meta Metafunction which will create a type given a parameter - * list - * @tparam W The size of the parameter pack to generate the sublists over. - */ - template <template <ParID_t...> class meas_meta, size_t W> - constexpr auto - type_generator() - { - // generate sublists - constexpr auto sublists = unique_ordered_sublists<W>(); - // map each sublist (tuple of paramater indices) into a measurement using - // the provided `meas_meta` metafunction. - constexpr auto measurements_h = hana::transform(sublists, [](auto s) { - return hana::unpack(s, [](auto... i) { - return hana::type_c< - typename meas_meta<ParID_t(decltype(i)::value)...>::type>; +/** + * @brief Constexpr function which produces a tuple that contains all unique + * ordered sublists of the range from 0 to W. + * This will generate: + * | W | output | + * |:---|:---------------------------------------------------| + * | 1 | [(0)] | + * | 2 | [(0), (1), (0, 1)] | + * | 3 | [(0), (1), (0, 1), (2), (0, 2), (1, 2), (0, 1, 2)] | + * + * In python, this algorithm would be roughly equivalent to + * ```python + * comb = [()] + * for i in range(0, 6): + * comb = comb + [c + (i,) for c in comb] + * comb = comb[1:] + * ``` + * or using `foldl = lambda func, acc, xs: functools.reduce(func, xs, acc)`: + * ```python + * def unique_ordered_subset(n): + * comb = [()] + * comb = foldl(lambda c, i: c+[c_i+(i,) for c_i in c], comb, range(0, n)) + * return comb[1:] + * ``` + * + * @tparam W End of the range (exclusive) + */ +template <size_t W> +constexpr auto unique_ordered_sublists() { + using namespace hana::literals; + // generate an empty tuple to start off + constexpr auto combinations = hana::make_tuple(hana::make_tuple()); + // generate range over which to fold + constexpr auto w_range = + hana::to_tuple(hana::make_range(0_c, hana::size_c<W>)); + // main fold expression. This successively adds variations to `state` and + // then + // returns the result. + constexpr auto comb2 = + hana::fold_left(w_range, combinations, [](auto state, auto i) { + auto mapped = hana::transform( + state, [i](auto c_i) { return hana::append(c_i, i); }); + return hana::concat(state, mapped); }); + // we need to pop off the initial empty tuple, which isn't really valid + return hana::remove_at(comb2, 0_c); +} + +/** + * Generates a tuple of types using `unique_ordered_sublists` from above. + * @tparam meas_meta Metafunction which will create a type given a parameter + * list + * @tparam W The size of the parameter pack to generate the sublists over. + */ +template <template <ParID_t...> class meas_meta, size_t W> +constexpr auto type_generator() { + // generate sublists + constexpr auto sublists = unique_ordered_sublists<W>(); + // map each sublist (tuple of paramater indices) into a measurement using + // the provided `meas_meta` metafunction. + constexpr auto measurements_h = hana::transform(sublists, [](auto s) { + return hana::unpack(s, [](auto... i) { + return hana::type_c< + typename meas_meta<ParID_t(decltype(i)::value)...>::type>; }); - // return tuple of measurements - return measurements_h; - } + }); + // return tuple of measurements + return measurements_h; +} - /** - * Type alias which unpacks the hana tuple generated in `type_generator` - * into an `std::variant`. - * @tparam meas_meta Factory meta function for measurements. - * @tparam W max number of parameters. - */ - template <template <ParID_t...> class meas_meta, size_t W> - using type_generator_t = - typename decltype(hana::unpack(type_generator<meas_meta, W>(), - hana::template_<std::variant>))::type; +/** + * Type alias which unpacks the hana tuple generated in `type_generator` + * into an `std::variant`. + * @tparam meas_meta Factory meta function for measurements. + * @tparam W max number of parameters. + */ +template <template <ParID_t...> class meas_meta, size_t W> +using type_generator_t = typename decltype(hana::unpack( + type_generator<meas_meta, W>(), hana::template_<std::variant>))::type; - /// @endcond +/// @endcond } // namespace detail /// @endcond } // namespace Acts diff --git a/Core/include/Acts/EventData/detail/full_parameter_set.hpp b/Core/include/Acts/EventData/detail/full_parameter_set.hpp index 14d95b6e30c628e9bfdbab4ae3495135d6449e3e..284e5806e48619ba4a382066cc6d70d7d479c0dd 100644 --- a/Core/include/Acts/EventData/detail/full_parameter_set.hpp +++ b/Core/include/Acts/EventData/detail/full_parameter_set.hpp @@ -22,50 +22,43 @@ class ParameterSet; /// @cond detail namespace detail { - /// @brief generate ParameterSet type containing all defined parameters - /// - /// @return full_parset<Policy>::type is equivalent to - /// `ParameterSet<Policy,ID_t(0),ID_t(1),...,ID_t(N-1)>` where @c ID_t - /// is a @c typedef to `Policy::par_id_type` and @c N is the total - /// number of parameters - struct full_parset - { - template <ParID_t v, typename C> - struct add_to_value_container; +/// @brief generate ParameterSet type containing all defined parameters +/// +/// @return full_parset<Policy>::type is equivalent to +/// `ParameterSet<Policy,ID_t(0),ID_t(1),...,ID_t(N-1)>` where @c ID_t +/// is a @c typedef to `Policy::par_id_type` and @c N is the total +/// number of parameters +struct full_parset { + template <ParID_t v, typename C> + struct add_to_value_container; - template <ParID_t v, ParID_t... others> - struct add_to_value_container<v, std::integer_sequence<ParID_t, others...>> - { - using type = std::integer_sequence<ParID_t, others..., v>; - }; - - template <typename T, unsigned int N> - struct tparam_generator - { - using type = - typename add_to_value_container<static_cast<T>(N), - typename tparam_generator<T, N - 1>:: - type>::type; - }; + template <ParID_t v, ParID_t... others> + struct add_to_value_container<v, std::integer_sequence<ParID_t, others...>> { + using type = std::integer_sequence<ParID_t, others..., v>; + }; - template <typename T> - struct tparam_generator<T, 0> - { - using type = std::integer_sequence<T, static_cast<T>(0)>; - }; + template <typename T, unsigned int N> + struct tparam_generator { + using type = typename add_to_value_container< + static_cast<T>(N), typename tparam_generator<T, N - 1>::type>::type; + }; - template <typename T> - struct converter; + template <typename T> + struct tparam_generator<T, 0> { + using type = std::integer_sequence<T, static_cast<T>(0)>; + }; - template <ParID_t... values> - struct converter<std::integer_sequence<ParID_t, values...>> - { - using type = ParameterSet<values...>; - }; + template <typename T> + struct converter; - using type = typename converter< - typename tparam_generator<ParID_t, Acts::NGlobalPars - 1>::type>::type; + template <ParID_t... values> + struct converter<std::integer_sequence<ParID_t, values...>> { + using type = ParameterSet<values...>; }; + + using type = typename converter< + typename tparam_generator<ParID_t, Acts::NGlobalPars - 1>::type>::type; +}; } // namespace detail /// @endcond } // namespace Acts diff --git a/Core/include/Acts/EventData/detail/initialize_parameter_set.hpp b/Core/include/Acts/EventData/detail/initialize_parameter_set.hpp index d6dabf5641461df58fc377c905437a5cb797cc30..c4d3413dfce0bbfa54c30cddd98a6a0bd67f6539 100644 --- a/Core/include/Acts/EventData/detail/initialize_parameter_set.hpp +++ b/Core/include/Acts/EventData/detail/initialize_parameter_set.hpp @@ -10,72 +10,60 @@ namespace Acts { /// @cond detail namespace detail { - /// @brief initialize parameter set with given parameter values - /// - /// @tparam T type of the parameters stored in the corresponding @c - /// ParameterSet class - /// @tparam params template parameter pack containing the multiple identifiers - /// - /// @note uses the templated ParameterSet::setParameter method for assigning - /// the individual components - /// - /// Possible invocations are: - /// * initialize<T,params...>::init(parSet,values...) where `parSet` is the - /// ParameterSet object to be initialized and `values` are a consistent - /// number of parameter values (with compatible type) - /// * initialize<T,params...>::init(parSet,values) where `parSet` is the - /// ParameterSet object to be initialized and `values` is an Eigen vector of - /// consistent size - template <typename T, T... params> - struct initialize_parset; +/// @brief initialize parameter set with given parameter values +/// +/// @tparam T type of the parameters stored in the corresponding @c +/// ParameterSet class +/// @tparam params template parameter pack containing the multiple identifiers +/// +/// @note uses the templated ParameterSet::setParameter method for assigning +/// the individual components +/// +/// Possible invocations are: +/// * initialize<T,params...>::init(parSet,values...) where `parSet` is the +/// ParameterSet object to be initialized and `values` are a consistent +/// number of parameter values (with compatible type) +/// * initialize<T,params...>::init(parSet,values) where `parSet` is the +/// ParameterSet object to be initialized and `values` is an Eigen vector of +/// consistent size +template <typename T, T... params> +struct initialize_parset; - /// @cond - template <typename T, T first, T... others> - struct initialize_parset<T, first, others...> - { - template <typename ParSetType, - typename first_value_type, - typename... other_value_types> - static void - init(ParSetType& parSet, - const first_value_type& v1, - const other_value_types&... values) - { - parSet.template setParameter<first>(v1); - initialize_parset<T, others...>::init(parSet, values...); - } +/// @cond +template <typename T, T first, T... others> +struct initialize_parset<T, first, others...> { + template <typename ParSetType, typename first_value_type, + typename... other_value_types> + static void init(ParSetType& parSet, const first_value_type& v1, + const other_value_types&... values) { + parSet.template setParameter<first>(v1); + initialize_parset<T, others...>::init(parSet, values...); + } - template <typename ParSetType> - static void - init(ParSetType& parSet, - const typename ParSetType::ParVector_t& values, - const unsigned int& pos = 0) - { - parSet.template setParameter<first>(values(pos)); - initialize_parset<T, others...>::init(parSet, values, pos + 1); - } - }; + template <typename ParSetType> + static void init(ParSetType& parSet, + const typename ParSetType::ParVector_t& values, + const unsigned int& pos = 0) { + parSet.template setParameter<first>(values(pos)); + initialize_parset<T, others...>::init(parSet, values, pos + 1); + } +}; - template <typename T, T last> - struct initialize_parset<T, last> - { - template <typename ParSet_tType, typename last_value_type> - static void - init(ParSet_tType& ParSet_t, const last_value_type& v1) - { - ParSet_t.template setParameter<last>(v1); - } +template <typename T, T last> +struct initialize_parset<T, last> { + template <typename ParSet_tType, typename last_value_type> + static void init(ParSet_tType& ParSet_t, const last_value_type& v1) { + ParSet_t.template setParameter<last>(v1); + } - template <typename ParSetType> - static void - init(ParSetType& parSet, - const typename ParSetType::ParVector_t& values, - const unsigned int& pos = 0) - { - parSet.template setParameter<last>(values(pos)); - } - }; - /// @endcond + template <typename ParSetType> + static void init(ParSetType& parSet, + const typename ParSetType::ParVector_t& values, + const unsigned int& pos = 0) { + parSet.template setParameter<last>(values(pos)); + } +}; +/// @endcond } // namespace detail /// @endcond } // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/EventData/detail/make_projection_matrix.hpp b/Core/include/Acts/EventData/detail/make_projection_matrix.hpp index 9c370e5f4421221ba3248d8ddba996dc567f0965..368b17992f6cef1da5edc281b381eeaf87412a96 100644 --- a/Core/include/Acts/EventData/detail/make_projection_matrix.hpp +++ b/Core/include/Acts/EventData/detail/make_projection_matrix.hpp @@ -13,57 +13,51 @@ namespace Acts { /// @cond detail namespace detail { - /// @brief initialize projection matrices - /// - /// @tparam columns number of columns (= dimension of full parameter space) - /// @tparam rows template parameter pack containing the indices of the - /// parameters to be projected - /// - /// This struct provides an initialization method for a projection matrix M - /// such that only the entries with the given indices are selected from a full - /// parameter vector. That means, M is a mapping M: (Nx1) --> (Sx1) if N is - /// the total number of parameters and S is the number of given indices. - /// - /// @return make_projection_matrix<columns,rows...>::init() returns a matrix - /// with dimensions (`sizeof...(rows)` x columns) - template <unsigned int columns, unsigned int... rows> - struct make_projection_matrix; +/// @brief initialize projection matrices +/// +/// @tparam columns number of columns (= dimension of full parameter space) +/// @tparam rows template parameter pack containing the indices of the +/// parameters to be projected +/// +/// This struct provides an initialization method for a projection matrix M +/// such that only the entries with the given indices are selected from a full +/// parameter vector. That means, M is a mapping M: (Nx1) --> (Sx1) if N is +/// the total number of parameters and S is the number of given indices. +/// +/// @return make_projection_matrix<columns,rows...>::init() returns a matrix +/// with dimensions (`sizeof...(rows)` x columns) +template <unsigned int columns, unsigned int... rows> +struct make_projection_matrix; - /// @cond - // build projection matrix by iteratively stacking row vectors - template <unsigned int columns, unsigned int i, unsigned int... N> - struct make_projection_matrix<columns, i, N...> - { - static ActsMatrixD<sizeof...(N) + 1, columns> - init() - { - ActsRowVectorD<columns> v; - v.setZero(); - v(i) = 1; +/// @cond +// build projection matrix by iteratively stacking row vectors +template <unsigned int columns, unsigned int i, unsigned int... N> +struct make_projection_matrix<columns, i, N...> { + static ActsMatrixD<sizeof...(N) + 1, columns> init() { + ActsRowVectorD<columns> v; + v.setZero(); + v(i) = 1; - ActsMatrixD<sizeof...(N) + 1, columns> m; - m.row(0) << v; - m.block(1, 0, sizeof...(N), columns) - << make_projection_matrix<columns, N...>::init(); + ActsMatrixD<sizeof...(N) + 1, columns> m; + m.row(0) << v; + m.block(1, 0, sizeof...(N), columns) + << make_projection_matrix<columns, N...>::init(); - return m; - } - }; + return m; + } +}; - // projection matrix for a single local parameter is a simple row vector - template <unsigned int columns, unsigned int i> - struct make_projection_matrix<columns, i> - { - static ActsRowVectorD<columns> - init() - { - ActsRowVectorD<columns> v; - v.setZero(); - v(i) = 1; - return v; - } - }; - /// @endcond +// projection matrix for a single local parameter is a simple row vector +template <unsigned int columns, unsigned int i> +struct make_projection_matrix<columns, i> { + static ActsRowVectorD<columns> init() { + ActsRowVectorD<columns> v; + v.setZero(); + v(i) = 1; + return v; + } +}; +/// @endcond } // namespace detail /// @endcond } // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/EventData/detail/residual_calculator.hpp b/Core/include/Acts/EventData/detail/residual_calculator.hpp index 839c6b9a9200ec5568fd43e928684ed7e8291b74..3cdd686b2d7b29f7c34098c7731bcc4c59818960 100644 --- a/Core/include/Acts/EventData/detail/residual_calculator.hpp +++ b/Core/include/Acts/EventData/detail/residual_calculator.hpp @@ -14,62 +14,55 @@ namespace Acts { /// @cond detail namespace detail { - /// @brief calculate residuals from two parameter vectors - /// - /// @tparam params template parameter pack containing the multiple parameter - /// identifiers - /// - /// Calculate the difference between the two given vectors with parameter - /// values. Possible corrections for bounded or cyclic parameters are applied. - /// - /// @return residual_calculator<params...>::result(first,second) yields the - /// residuals of `first` with respect to `second` - template <ParID_t... params> - struct residual_calculator; +/// @brief calculate residuals from two parameter vectors +/// +/// @tparam params template parameter pack containing the multiple parameter +/// identifiers +/// +/// Calculate the difference between the two given vectors with parameter +/// values. Possible corrections for bounded or cyclic parameters are applied. +/// +/// @return residual_calculator<params...>::result(first,second) yields the +/// residuals of `first` with respect to `second` +template <ParID_t... params> +struct residual_calculator; - /// @cond - template <typename R, ParID_t... params> - struct residual_calculator_impl; +/// @cond +template <typename R, ParID_t... params> +struct residual_calculator_impl; - template <ParID_t... params> - struct residual_calculator - { - using ParVector_t = ActsVector<ParValue_t, sizeof...(params)>; +template <ParID_t... params> +struct residual_calculator { + using ParVector_t = ActsVector<ParValue_t, sizeof...(params)>; - static ParVector_t - result(const ParVector_t& test, const ParVector_t& ref) - { - ParVector_t result; - residual_calculator_impl<ParVector_t, params...>::calculate( - result, test, ref, 0); - return result; - } - }; + static ParVector_t result(const ParVector_t& test, const ParVector_t& ref) { + ParVector_t result; + residual_calculator_impl<ParVector_t, params...>::calculate(result, test, + ref, 0); + return result; + } +}; - template <typename R, ParID_t first, ParID_t... others> - struct residual_calculator_impl<R, first, others...> - { - static void - calculate(R& result, const R& test, const R& ref, unsigned int pos) - { - using parameter_type = typename par_type<first>::type; - result(pos) = parameter_type::getDifference(test(pos), ref(pos)); - residual_calculator_impl<R, others...>::calculate( - result, test, ref, pos + 1); - } - }; +template <typename R, ParID_t first, ParID_t... others> +struct residual_calculator_impl<R, first, others...> { + static void calculate(R& result, const R& test, const R& ref, + unsigned int pos) { + using parameter_type = typename par_type<first>::type; + result(pos) = parameter_type::getDifference(test(pos), ref(pos)); + residual_calculator_impl<R, others...>::calculate(result, test, ref, + pos + 1); + } +}; - template <typename R, ParID_t last> - struct residual_calculator_impl<R, last> - { - static void - calculate(R& result, const R& test, const R& ref, unsigned int pos) - { - using parameter_type = typename par_type<last>::type; - result(pos) = parameter_type::getDifference(test(pos), ref(pos)); - } - }; - /// @endcond +template <typename R, ParID_t last> +struct residual_calculator_impl<R, last> { + static void calculate(R& result, const R& test, const R& ref, + unsigned int pos) { + using parameter_type = typename par_type<last>::type; + result(pos) = parameter_type::getDifference(test(pos), ref(pos)); + } +}; +/// @endcond } // namespace detail /// @endcond } // namespace Acts diff --git a/Core/include/Acts/EventData/detail/value_corrector.hpp b/Core/include/Acts/EventData/detail/value_corrector.hpp index e3d181552e67a507151d1cbbf8458e5d83c967b3..ddd50d7d82de9d050caae1def5fe9532df1b42c3 100644 --- a/Core/include/Acts/EventData/detail/value_corrector.hpp +++ b/Core/include/Acts/EventData/detail/value_corrector.hpp @@ -14,67 +14,58 @@ namespace Acts { /// @cond detail namespace detail { - /// @brief check and correct parameter values - /// - /// @tparam params template parameter pack containing the multiple parameter - /// identifiers - /// - /// Values in the given vector are interpreted as values for the given - /// parameters. As those they are checked whether they are inside the allowed - /// range and corrected if necessary. - /// - /// Invocation: - /// - value_corrector<params...>::result(parVector) where `parVector` - /// contains `sizeof...(params)` elements - /// - /// @post All values in the argument `parVector` are within the valid - /// parameter range. - template <ParID_t... params> - struct value_corrector; +/// @brief check and correct parameter values +/// +/// @tparam params template parameter pack containing the multiple parameter +/// identifiers +/// +/// Values in the given vector are interpreted as values for the given +/// parameters. As those they are checked whether they are inside the allowed +/// range and corrected if necessary. +/// +/// Invocation: +/// - value_corrector<params...>::result(parVector) where `parVector` +/// contains `sizeof...(params)` elements +/// +/// @post All values in the argument `parVector` are within the valid +/// parameter range. +template <ParID_t... params> +struct value_corrector; - /// @cond - template <typename R, ParID_t... params> - struct value_corrector_impl; +/// @cond +template <typename R, ParID_t... params> +struct value_corrector_impl; - template <ParID_t... params> - struct value_corrector - { - using ParVector_t = ActsVector<ParValue_t, sizeof...(params)>; +template <ParID_t... params> +struct value_corrector { + using ParVector_t = ActsVector<ParValue_t, sizeof...(params)>; - static void - result(ParVector_t& values) - { - value_corrector_impl<ParVector_t, params...>::calculate(values, 0); - } - }; + static void result(ParVector_t& values) { + value_corrector_impl<ParVector_t, params...>::calculate(values, 0); + } +}; - template <typename R, ParID_t first, ParID_t... others> - struct value_corrector_impl<R, first, others...> - { - static void - calculate(R& values, unsigned int pos) - { - using parameter_type = typename par_type<first>::type; - if (parameter_type::may_modify_value) { - values(pos) = parameter_type::getValue(values(pos)); - } - value_corrector_impl<R, others...>::calculate(values, pos + 1); +template <typename R, ParID_t first, ParID_t... others> +struct value_corrector_impl<R, first, others...> { + static void calculate(R& values, unsigned int pos) { + using parameter_type = typename par_type<first>::type; + if (parameter_type::may_modify_value) { + values(pos) = parameter_type::getValue(values(pos)); } - }; + value_corrector_impl<R, others...>::calculate(values, pos + 1); + } +}; - template <typename R, ParID_t last> - struct value_corrector_impl<R, last> - { - static void - calculate(R& values, unsigned int pos) - { - using parameter_type = typename par_type<last>::type; - if (parameter_type::may_modify_value) { - values(pos) = parameter_type::getValue(values(pos)); - } +template <typename R, ParID_t last> +struct value_corrector_impl<R, last> { + static void calculate(R& values, unsigned int pos) { + using parameter_type = typename par_type<last>::type; + if (parameter_type::may_modify_value) { + values(pos) = parameter_type::getValue(values(pos)); } - }; - /// @endcond + } +}; +/// @endcond } // namespace detail /// @endcond } // namespace Acts diff --git a/Core/include/Acts/Fitter/GainMatrixSmoother.hpp b/Core/include/Acts/Fitter/GainMatrixSmoother.hpp index 26d08baa1ed79f6e9836de346379a3a5ed49baba..29cfa430e227ceae8064969785f168c2bfdddc2e 100644 --- a/Core/include/Acts/Fitter/GainMatrixSmoother.hpp +++ b/Core/include/Acts/Fitter/GainMatrixSmoother.hpp @@ -19,24 +19,21 @@ namespace Acts { /// @tparam parameters_t Type of the track parameters /// @tparam jacobian_t Type of the Jacobian template <typename parameters_t> -class GainMatrixSmoother -{ - +class GainMatrixSmoother { using jacobian_t = typename parameters_t::CovMatrix_t; -public: + public: /// @brief Gain Matrix smoother implementation /// template <typename track_states_t> - boost::optional<parameters_t> - operator()(const GeometryContext& gctx, track_states_t& filteredStates) const - { + boost::optional<parameters_t> operator()( + const GeometryContext& gctx, track_states_t& filteredStates) const { using namespace boost::adaptors; using track_state_t = typename track_states_t::value_type; - using ParVector_t = typename parameters_t::ParVector_t; - using CovMatrix_t = typename parameters_t::CovMatrix_t; + using ParVector_t = typename parameters_t::ParVector_t; + using CovMatrix_t = typename parameters_t::CovMatrix_t; using gain_matrix_t = CovMatrix_t; // smoothed parameter vector and covariance matrix @@ -44,7 +41,7 @@ public: CovMatrix_t smoothedCov; // For the last state: smoothed is filtered - also: switch to next - auto& prev_ts = filteredStates.back(); + auto& prev_ts = filteredStates.back(); prev_ts.parameter.smoothed = *prev_ts.parameter.filtered; // Smoothing gain matrix @@ -53,7 +50,6 @@ public: // Loop and smooth the remaining states for (track_state_t& ts : filteredStates | sliced(0, filteredStates.size()) | reversed) { - // The current state assert(ts.parameter.filtered); assert(ts.parameter.predicted); @@ -84,11 +80,9 @@ public: // clang-format on // Create smoothed track parameters - ts.parameter.smoothed - = parameters_t(gctx, - std::make_unique<CovMatrix_t>(std::move(smoothedCov)), - smoothedPars, - ts.referenceSurface().getSharedPtr()); + ts.parameter.smoothed = parameters_t( + gctx, std::make_unique<CovMatrix_t>(std::move(smoothedCov)), + smoothedPars, ts.referenceSurface().getSharedPtr()); // Point prev state to current state prev_ts = ts; @@ -97,4 +91,4 @@ public: return prev_ts.parameter.smoothed; } }; -} +} // namespace Acts diff --git a/Core/include/Acts/Fitter/GainMatrixUpdator.hpp b/Core/include/Acts/Fitter/GainMatrixUpdator.hpp index 3cad9d0ef9deeec3b449ea412f9d443f7ee06332..6e9a664b9b302879bbadf113d18eed03399a3b81 100644 --- a/Core/include/Acts/Fitter/GainMatrixUpdator.hpp +++ b/Core/include/Acts/Fitter/GainMatrixUpdator.hpp @@ -26,20 +26,16 @@ namespace Acts { /// This is implemented as a boost vistor pattern for use of the /// boost variant container template <typename parameters_t, typename calibrator_t = VoidKalmanComponents> -class GainMatrixUpdator -{ - +class GainMatrixUpdator { using jacobian_t = typename parameters_t::CovMatrix_t; -public: + public: /// Explicit constructor /// /// @param calibrator is the calibration struct/class that converts /// uncalibrated measurements into calibrated ones GainMatrixUpdator(calibrator_t calibrator = calibrator_t()) - : m_mCalibrator(std::move(calibrator)) - { - } + : m_mCalibrator(std::move(calibrator)) {} /// @brief Public call operator for the boost visitor pattern /// @@ -52,9 +48,8 @@ public: /// @note Non-'successful' updates could be holes or outliers, /// which need to be treated differently in calling code. template <typename track_state_t> - bool - operator()(const GeometryContext& gctx, track_state_t& trackState) const - { + bool operator()(const GeometryContext& gctx, + track_state_t& trackState) const { using CovMatrix_t = typename parameters_t::CovMatrix_t; using ParVector_t = typename parameters_t::ParVector_t; @@ -80,9 +75,9 @@ public: std::visit( [&](const auto& uncalibrated) { // type of measurement - using meas_t = typename std::remove_const< - typename std::remove_reference<decltype(uncalibrated)>::type>:: - type; + using meas_t = + typename std::remove_const<typename std::remove_reference< + decltype(uncalibrated)>::type>::type; // measurement covariance matrix using meas_cov_t = typename meas_t::CovMatrix_t; // measurement (local) parameter vector @@ -100,18 +95,18 @@ public: const projection_t& H = calibrated.projector(); // The Kalman gain matrix - gain_matrix_t K = predicted_covariance * H.transpose() - * (H * predicted_covariance * H.transpose() - + calibrated.covariance()) - .inverse(); + gain_matrix_t K = predicted_covariance * H.transpose() * + (H * predicted_covariance * H.transpose() + + calibrated.covariance()) + .inverse(); // filtered new parameters after update - filtered_parameters - = predicted.parameters() + K * calibrated.residual(predicted); + filtered_parameters = + predicted.parameters() + K * calibrated.residual(predicted); // updated covariance after filtering - filtered_covariance - = (CovMatrix_t::Identity() - K * H) * predicted_covariance; + filtered_covariance = + (CovMatrix_t::Identity() - K * H) * predicted_covariance; // Create new filtered parameters and covariance parameters_t filtered(gctx, @@ -125,18 +120,17 @@ public: // r is the residual of the filtered state // R is the covariance matrix of the filtered residual meas_par_t residual = calibrated.residual(filtered); - trackState.parameter.chi2 - = (residual.transpose() - * ((meas_cov_t::Identity() - H * K) * calibrated.covariance()) - .inverse() - * residual) - .eval()(0, 0); + trackState.parameter.chi2 = + (residual.transpose() * + ((meas_cov_t::Identity() - H * K) * calibrated.covariance()) + .inverse() * + residual) + .eval()(0, 0); // plug calibrated measurement back into track state trackState.measurement.calibrated = std::move(calibrated); trackState.parameter.filtered = std::move(filtered); - }, *trackState.measurement.uncalibrated); @@ -144,7 +138,7 @@ public: return true; } -private: + private: /// The measurement calibrator calibrator_t m_mCalibrator; }; diff --git a/Core/include/Acts/Fitter/KalmanFitter.hpp b/Core/include/Acts/Fitter/KalmanFitter.hpp index cf6d3b9a3026d401cba9fc2f782d284452ee04f2..e3901e03daa7ca51eda7467c60da756f582ba02f 100644 --- a/Core/include/Acts/Fitter/KalmanFitter.hpp +++ b/Core/include/Acts/Fitter/KalmanFitter.hpp @@ -33,9 +33,7 @@ namespace Acts { /// surface where to express the fit result /// /// @note the context objects must be provided -struct KalmanFitterOptions -{ - +struct KalmanFitterOptions { /// Deleted default constructor KalmanFitterOptions() = delete; @@ -45,16 +43,14 @@ struct KalmanFitterOptions /// @param mctx The magnetic context for this fit /// @param cctx The calibration context for this fit /// @param rSurface The reference surface for the fit to be expressed at - KalmanFitterOptions(std::reference_wrapper<const GeometryContext> gctx, + KalmanFitterOptions(std::reference_wrapper<const GeometryContext> gctx, std::reference_wrapper<const MagneticFieldContext> mctx, - std::reference_wrapper<const CalibrationContext> cctx, + std::reference_wrapper<const CalibrationContext> cctx, const Surface* rSurface = nullptr) - : geoContext(gctx) - , magFieldContext(mctx) - , calibrationContext(cctx) - , referenceSurface(rSurface) - { - } + : geoContext(gctx), + magFieldContext(mctx), + calibrationContext(cctx), + referenceSurface(rSurface) {} /// Context object for the geometry std::reference_wrapper<const GeometryContext> geoContext; @@ -102,15 +98,13 @@ struct KalmanFitterOptions /// set of track states into a given track/track particle class /// /// The void components are provided mainly for unit testing. -template <typename propagator_t, - typename updator_t = VoidKalmanUpdator, - typename smoother_t = VoidKalmanSmoother, - typename calibrator_t = VoidKalmanComponents, - typename input_converter_t = VoidKalmanComponents, +template <typename propagator_t, typename updator_t = VoidKalmanUpdator, + typename smoother_t = VoidKalmanSmoother, + typename calibrator_t = VoidKalmanComponents, + typename input_converter_t = VoidKalmanComponents, typename output_converter_t = VoidKalmanComponents> -class KalmanFitter -{ -public: +class KalmanFitter { + public: /// Shorthand definition using MeasurementSurfaces = std::multimap<const Layer*, const Surface*>; @@ -118,14 +112,12 @@ public: KalmanFitter() = delete; /// Constructor from arguments - KalmanFitter(propagator_t pPropagator, - input_converter_t pInputCnv = input_converter_t(), + KalmanFitter(propagator_t pPropagator, + input_converter_t pInputCnv = input_converter_t(), output_converter_t pOutputCnv = output_converter_t()) - : m_propagator(std::move(pPropagator)) - , m_inputConverter(std::move(pInputCnv)) - , m_outputConverter(std::move(pOutputCnv)) - { - } + : m_propagator(std::move(pPropagator)), + m_inputConverter(std::move(pInputCnv)), + m_outputConverter(std::move(pOutputCnv)) {} /// Fit implementation of the foward filter, calls the /// the forward filter and backward smoother @@ -140,19 +132,16 @@ public: /// /// @return the output as an output track template <typename input_measurements_t, typename parameters_t> - auto - fit(input_measurements_t measurements, - const parameters_t& sParameters, - const KalmanFitterOptions& kfOptions) const - { + auto fit(input_measurements_t measurements, const parameters_t& sParameters, + const KalmanFitterOptions& kfOptions) const { // Bring the measurements into Acts style auto trackStates = m_inputConverter(measurements); // Create the ActionList and AbortList - using KalmanActor = Actor<decltype(trackStates)>; + using KalmanActor = Actor<decltype(trackStates)>; using KalmanResult = typename KalmanActor::result_type; - using Actors = ActionList<KalmanActor>; - using Aborters = AbortList<>; + using Actors = ActionList<KalmanActor>; + using Aborters = AbortList<>; // Create relevant options for the propagation options PropagatorOptions<Actors, Aborters> kalmanOptions( @@ -160,12 +149,12 @@ public: // Catch the actor and set the measurements auto& kalmanActor = kalmanOptions.actionList.template get<KalmanActor>(); - kalmanActor.trackStates = std::move(trackStates); + kalmanActor.trackStates = std::move(trackStates); kalmanActor.targetSurface = kfOptions.referenceSurface; // Run the fitter - const auto& result - = m_propagator.template propagate(sParameters, kalmanOptions).value(); + const auto& result = + m_propagator.template propagate(sParameters, kalmanOptions).value(); /// Get the result of the fit auto kalmanResult = result.template get<KalmanResult>(); @@ -174,7 +163,7 @@ public: return m_outputConverter(std::move(kalmanResult)); } -private: + private: /// The propgator for the transport and material update propagator_t m_propagator; @@ -197,26 +186,21 @@ private: /// The KalmanActor does not rely on the measurements to be /// sorted along the track. template <typename track_states_t> - class Actor - { - public: + class Actor { + public: using TrackState = typename track_states_t::value_type; /// Explicit constructor with updator and calibrator - Actor(updator_t pUpdator = updator_t(), - smoother_t pSmoother = smoother_t(), + Actor(updator_t pUpdator = updator_t(), smoother_t pSmoother = smoother_t(), calibrator_t pCalibrator = calibrator_t()) - : m_updator(std::move(pUpdator)) - , m_smoother(std::move(pSmoother)) - , m_calibrator(std::move(pCalibrator)) - { - } + : m_updator(std::move(pUpdator)), + m_smoother(std::move(pSmoother)), + m_calibrator(std::move(pCalibrator)) {} /// Simple result struct to be returned /// It mainly acts as an internal state which is /// created for every propagation/extrapolation step - struct this_result - { + struct this_result { // Move the result into the fitted states track_states_t fittedStates = {}; @@ -254,11 +238,8 @@ private: /// @param stepper The stepper in use /// @param result is the mutable result state object template <typename propagator_state_t, typename stepper_t> - void - operator()(propagator_state_t& state, - const stepper_t& stepper, - result_type& result) const - { + void operator()(propagator_state_t& state, const stepper_t& stepper, + result_type& result) const { // Initialization: // - Only when track states are not set if (result.fittedStates.empty()) { @@ -282,8 +263,8 @@ private: // Finalization: // - When all track states have been handled - if (result.processedStates == trackStates.size() - and not result.smoothed) { + if (result.processedStates == trackStates.size() and + not result.smoothed) { // -> Sort the track states (as now the path length is set) // -> Call the smoothing // -> Set a stop condition when all track states have been handled @@ -294,8 +275,8 @@ private: // parameters if (result.smoothed and targetReached(state, stepper, *targetSurface)) { // Transport & bind the parameter to the final surface - auto fittedState - = stepper.boundState(state.stepping, *targetSurface, true); + auto fittedState = + stepper.boundState(state.stepping, *targetSurface, true); // Assign the fitted parameters result.fittedParameters = std::get<BoundParameters>(fittedState); // Break the navigation for stopping the Propagation @@ -303,7 +284,7 @@ private: } } - private: + private: /// @brief Kalman actor operation : initialize /// /// @tparam propagator_state_t is the type of Propagagor state @@ -313,11 +294,8 @@ private: /// @param stepper The stepper in use /// @param result is the mutable result state object template <typename propagator_state_t, typename stepper_t> - void - initialize(propagator_state_t& state, - const stepper_t& stepper, - result_type& result) const - { + void initialize(propagator_state_t& state, const stepper_t& stepper, + result_type& result) const { // Screen output message debugLog(state, [&] { std::stringstream dstream; @@ -339,21 +317,18 @@ private: auto layer = surface.associatedLayer(); if (layer == nullptr) { // Find the intersection to allocate the layer - auto surfaceIntersection - = surface.intersectionEstimate(state.geoContext, - stepper.position(state.stepping), - stepper.direction(state.stepping), - state.stepping.navDir, - false); + auto surfaceIntersection = surface.intersectionEstimate( + state.geoContext, stepper.position(state.stepping), + stepper.direction(state.stepping), state.stepping.navDir, false); // Allocate the layer via the tracking geometry search if (surfaceIntersection and state.navigation.worldVolume) { auto intersection = surfaceIntersection.position; - auto layerVolume - = state.navigation.worldVolume->lowestTrackingVolume( + auto layerVolume = + state.navigation.worldVolume->lowestTrackingVolume( state.geoContext, intersection); - layer = layerVolume - ? layerVolume->associatedLayer(state.geoContext, intersection) - : nullptr; + layer = layerVolume ? layerVolume->associatedLayer(state.geoContext, + intersection) + : nullptr; } } // Insert the surface into the measurementsurfaces multimap @@ -387,12 +362,8 @@ private: /// @param stepper The stepper in use /// @param result The mutable result state object template <typename propagator_state_t, typename stepper_t> - void - filter(const Surface* surface, - propagator_state_t& state, - const stepper_t& stepper, - result_type& result) const - { + void filter(const Surface* surface, propagator_state_t& state, + const stepper_t& stepper, result_type& result) const { // Try to find the surface in the measurement surfaces auto cindexItr = result.accessIndices.find(surface); if (cindexItr != result.accessIndices.end()) { @@ -410,12 +381,11 @@ private: // Transport & bind the state to the current surface std::tuple<BoundParameters, - typename TrackState::Parameters::CovMatrix_t, - double> + typename TrackState::Parameters::CovMatrix_t, double> boundState = stepper.boundState(state.stepping, *surface, true); // Fill the track state - trackState.parameter.predicted = std::get<0>(boundState); - trackState.parameter.jacobian = std::get<1>(boundState); + trackState.parameter.predicted = std::get<0>(boundState); + trackState.parameter.jacobian = std::get<1>(boundState); trackState.parameter.pathLength = std::get<2>(boundState); // If the update is successful, set covariance and @@ -448,18 +418,15 @@ private: /// @param stepper The stepper in use /// @param result is the mutable result state object template <typename propagator_state_t, typename stepper_t> - void - finalize(propagator_state_t& state, - const stepper_t& stepper, - result_type& result) const - { + void finalize(propagator_state_t& state, const stepper_t& stepper, + result_type& result) const { // Remember you smoothed the track states result.smoothed = true; // Sort the TrackStates according to the path length TrackStatePathLengthSorter plSorter; - std::sort( - result.fittedStates.begin(), result.fittedStates.end(), plSorter); + std::sort(result.fittedStates.begin(), result.fittedStates.end(), + plSorter); // Screen output for debugging debugLog(state, [&] { std::stringstream dstream; @@ -469,19 +436,20 @@ private: return dstream.str(); }); // Smooth the track states and obtain the last smoothed track parameters - const auto& smoothedPars - = m_smoother(state.geoContext, result.fittedStates); + const auto& smoothedPars = + m_smoother(state.geoContext, result.fittedStates); // Update the stepping parameters - in order to progress to destination if (smoothedPars) { // Update the stepping state debugLog(state, [&] { - return std::string("Smoothing successful, updating stepping state, " - "set target surface."); + return std::string( + "Smoothing successful, updating stepping state, " + "set target surface."); }); stepper.update(state.stepping, smoothedPars.get()); // Reverse the propagation direction - state.stepping.stepSize - = detail::ConstrainedStep(-1. * state.options.maxStepSize); + state.stepping.stepSize = + detail::ConstrainedStep(-1. * state.options.maxStepSize); state.options.direction = backward; } } @@ -497,10 +465,8 @@ private: /// @param state the propagator state for the debug flag, prefix/length /// @param logAction is a callable function that returns a stremable object template <typename propagator_state_t> - void - debugLog(propagator_state_t& state, - const std::function<std::string()>& logAction) const - { + void debugLog(propagator_state_t& state, + const std::function<std::string()>& logAction) const { if (state.options.debug) { std::stringstream dstream; dstream << "K->" << std::setw(state.options.debugPfxWidth); diff --git a/Core/include/Acts/Fitter/detail/VoidKalmanComponents.hpp b/Core/include/Acts/Fitter/detail/VoidKalmanComponents.hpp index eeca26d649690172d1ea207f9f803ceeaff5e66a..bdee13078603a0c5629b617addd8eba7f0e7c24b 100644 --- a/Core/include/Acts/Fitter/detail/VoidKalmanComponents.hpp +++ b/Core/include/Acts/Fitter/detail/VoidKalmanComponents.hpp @@ -11,8 +11,7 @@ namespace Acts { /// @brief void Measurement calibrator and converter -struct VoidKalmanComponents -{ +struct VoidKalmanComponents { /// @brief Public call mimicking a calibrator /// /// @tparam measurement_t Type of the measurement @@ -23,9 +22,8 @@ struct VoidKalmanComponents /// /// @return void-calibrated measurement template <typename measurement_t, typename parameters_t> - measurement_t - operator()(measurement_t m, const parameters_t& /*pars*/) const - { + measurement_t operator()(measurement_t m, + const parameters_t& /*pars*/) const { return m; } @@ -38,16 +36,13 @@ struct VoidKalmanComponents /// /// @return moved measurements template <typename measurements_t> - measurements_t - operator()(measurements_t ms) const - { + measurements_t operator()(measurements_t ms) const { return std::move(ms); } }; /// @brief void Kalman updator -struct VoidKalmanUpdator -{ +struct VoidKalmanUpdator { /// @brief Public call mimicking an updator /// /// @tparam measurement_t Type of the measurement to be used @@ -58,16 +53,14 @@ struct VoidKalmanUpdator /// /// @return The copied predicted parameters template <typename track_state_t, typename predicted_state_t> - auto - operator()(track_state_t& /*m*/, const predicted_state_t& predicted) const - { + auto operator()(track_state_t& /*m*/, + const predicted_state_t& predicted) const { return &(predicted.parameters); } }; /// @brief void Kalman smoother -struct VoidKalmanSmoother -{ +struct VoidKalmanSmoother { /// @brief Public call mimicking an updator /// /// @tparam track_states_t Type of the track states @@ -76,9 +69,7 @@ struct VoidKalmanSmoother /// /// @return The resulting template <typename parameters_t, typename track_states_t> - const parameters_t* - operator()(track_states_t& /*states*/) const - { + const parameters_t* operator()(track_states_t& /*states*/) const { return nullptr; } }; diff --git a/Core/include/Acts/Geometry/AbstractVolume.hpp b/Core/include/Acts/Geometry/AbstractVolume.hpp index 0e1466777c3985a876be62462bbc6d497d4a2ac7..980be5016ad66c50bfc6f03a5adaadece515b1f1 100644 --- a/Core/include/Acts/Geometry/AbstractVolume.hpp +++ b/Core/include/Acts/Geometry/AbstractVolume.hpp @@ -19,8 +19,8 @@ namespace Acts { class AbstractVolume; -using BoundarySurfacePtr - = std::shared_ptr<const BoundarySurfaceT<AbstractVolume>>; +using BoundarySurfacePtr = + std::shared_ptr<const BoundarySurfaceT<AbstractVolume>>; class VolumeBounds; using VolumeBoundsPtr = std::shared_ptr<const VolumeBounds>; @@ -49,15 +49,14 @@ using VolumeBoundsPtr = std::shared_ptr<const VolumeBounds>; /// /// @image html VolumeShapes.gif -class AbstractVolume : public Volume -{ -public: +class AbstractVolume : public Volume { + public: /// Constructor with shared Transform3D*, VolumeBounds* /// /// @param htrans is the transform 3D the positions the volume in global frame /// @param volbounds is the boundary definition AbstractVolume(std::shared_ptr<const Transform3D> htrans, - VolumeBoundsPtr volbounds); + VolumeBoundsPtr volbounds); /// Copy constructor - deleted AbstractVolume(const AbstractVolume& vol) = delete; @@ -69,23 +68,19 @@ public: ~AbstractVolume() override; /// Assignment operator - deleted - AbstractVolume& - operator=(const AbstractVolume& vol) - = delete; + AbstractVolume& operator=(const AbstractVolume& vol) = delete; /// Method to return the BoundarySurfaces /// /// @return the vector of boundary surfaces - const std::vector<BoundarySurfacePtr>& - boundarySurfaces() const; + const std::vector<BoundarySurfacePtr>& boundarySurfaces() const; -private: + private: /// Private method to create BoundarySurfaces - void - createBoundarySurfaces(); + void createBoundarySurfaces(); /// boundary Surfaces for this volume std::vector<BoundarySurfacePtr> m_boundarySurfaces; }; -} // namespace \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Geometry/ApproachDescriptor.hpp b/Core/include/Acts/Geometry/ApproachDescriptor.hpp index efa94cf8356544e85764b37de68932a2b0349eb0..91d9a102a09e8c813602a8b4e7f71ccafeeff4d6 100644 --- a/Core/include/Acts/Geometry/ApproachDescriptor.hpp +++ b/Core/include/Acts/Geometry/ApproachDescriptor.hpp @@ -32,9 +32,8 @@ class BoundaryCheck; /// representingVolume of the Layer /// /// -class ApproachDescriptor -{ -public: +class ApproachDescriptor { + public: /// Default constructor ApproachDescriptor() = default; @@ -45,9 +44,7 @@ public: /// this gives the approach surfaces the link to the layer /// /// @param lay is the layer to be assigned - virtual void - registerLayer(const Layer& lay) - = 0; + virtual void registerLayer(const Layer& lay) = 0; /// @brief Get the surface on approach /// @@ -59,14 +56,12 @@ public: /// @param parameters The actual parameters object /// @param options are the steering options for the search /// @param corrfnc The actual Corrector object - template <typename parameters_t, - typename options_t, + template <typename parameters_t, typename options_t, typename corrector_t = VoidIntersectionCorrector> - ObjectIntersection<Surface> - approachSurface(const GeometryContext& gctx, - const parameters_t& parameters, - const options_t& options, - const corrector_t& corrfnc = corrector_t()) const; + ObjectIntersection<Surface> approachSurface( + const GeometryContext& gctx, const parameters_t& parameters, + const options_t& options, + const corrector_t& corrfnc = corrector_t()) const; /// @brief Get the surface on approach /// @@ -77,39 +72,26 @@ public: /// @param correciton is the function pointer to a corrector /// /// @return is a surface intersection - virtual ObjectIntersection<Surface> - approachSurface(const GeometryContext& gctx, - const Vector3D& pos, - const Vector3D& gdir, - NavigationDirection navDir, - const BoundaryCheck& bcheck, - CorrFnc correct = nullptr) const = 0; + virtual ObjectIntersection<Surface> approachSurface( + const GeometryContext& gctx, const Vector3D& pos, const Vector3D& gdir, + NavigationDirection navDir, const BoundaryCheck& bcheck, + CorrFnc correct = nullptr) const = 0; /// Tet to all the contained surfaces /// @return all contained surfaces of this approach descriptor - virtual const std::vector<const Surface*>& - containedSurfaces() const = 0; + virtual const std::vector<const Surface*>& containedSurfaces() const = 0; /// Non-const version - virtual std::vector<const Surface*>& - containedSurfaces() - = 0; + virtual std::vector<const Surface*>& containedSurfaces() = 0; }; template <typename parameters_t, typename options_t, typename corrector_t> -ObjectIntersection<Surface> -ApproachDescriptor::approachSurface(const GeometryContext& gctx, - const parameters_t& parameters, - const options_t& options, - const corrector_t& corrfnc) const -{ +ObjectIntersection<Surface> ApproachDescriptor::approachSurface( + const GeometryContext& gctx, const parameters_t& parameters, + const options_t& options, const corrector_t& corrfnc) const { // calculate the actual intersection - return approachSurface(gctx, - parameters.position(), - parameters.direction(), - options.navDir, - options.boundaryCheck, - corrfnc); + return approachSurface(gctx, parameters.position(), parameters.direction(), + options.navDir, options.boundaryCheck, corrfnc); } } // namespace Acts diff --git a/Core/include/Acts/Geometry/BoundarySurfaceFace.hpp b/Core/include/Acts/Geometry/BoundarySurfaceFace.hpp index bb1bfbfeaee9b8313c471e0511b2e42e87700c62..0873624415b2f09bafe181f0ffcb657bc5b84f7d 100644 --- a/Core/include/Acts/Geometry/BoundarySurfaceFace.hpp +++ b/Core/include/Acts/Geometry/BoundarySurfaceFace.hpp @@ -29,73 +29,71 @@ namespace Acts { /// possible - a cycular structure. enum BoundarySurfaceFace { - negativeFaceXY = 0, - positiveFaceXY = 1, - negativeFaceYZ = 2, - positiveFaceYZ = 3, - negativeFaceZX = 4, - positiveFaceZX = 5, - cylinderCover = 2, - tubeInnerCover = 3, - tubeOuterCover = 2, + negativeFaceXY = 0, + positiveFaceXY = 1, + negativeFaceYZ = 2, + positiveFaceYZ = 3, + negativeFaceZX = 4, + positiveFaceZX = 5, + cylinderCover = 2, + tubeInnerCover = 3, + tubeOuterCover = 2, tubeSectorNegativePhi = 4, tubeSectorPositivePhi = 5, - tubeSectorInnerCover = 3, - tubeSectorOuterCover = 2, - trapezoidFaceAlpha = 2, - trapezoidFaceBeta = 3, - index0 = 0, - index1 = 1, - index2 = 2, - index3 = 3, - index4 = 4, - index5 = 5, - index6 = 6, - index7 = 7, - index8 = 8, - index9 = 9, - index10 = 10, - index11 = 11, - undefinedFace = 99 + tubeSectorInnerCover = 3, + tubeSectorOuterCover = 2, + trapezoidFaceAlpha = 2, + trapezoidFaceBeta = 3, + index0 = 0, + index1 = 1, + index2 = 2, + index3 = 3, + index4 = 4, + index5 = 5, + index6 = 6, + index7 = 7, + index8 = 8, + index9 = 9, + index10 = 10, + index11 = 11, + undefinedFace = 99 }; /// @brief specify the inside/outside with respect to the normal vector enum BoundaryOrientation { insideVolume = -1, outsideVolume = 1 }; -inline std::ostream& -operator<<(std::ostream& os, BoundarySurfaceFace& face) -{ +inline std::ostream& operator<<(std::ostream& os, BoundarySurfaceFace& face) { os << "BoundarySurfaceFace::"; switch (face) { - case negativeFaceXY: - os << "negativeFaceXY"; - break; - case positiveFaceXY: - os << "positiveFaceXY"; - break; - case negativeFaceYZ: - os << "negativeFaceYZ|cylinderCover|tubeOuterCover|tubeSectorOuterCover|" - "trapezoidFaceAlpha"; - break; - case positiveFaceYZ: - os << "positiveFaceYZ|tubeInnerCover|tubeSectorInnerCover|" - "trapezoidFaceBeta"; - break; - case negativeFaceZX: - os << "negativeFaceZX|tubeSectorNegativePhi"; - break; - case positiveFaceZX: - os << "positiveFaceZX|tubeSectorPositivePhi"; - break; - case undefinedFace: - os << "undefinedFace"; - break; - default: - os << face; + case negativeFaceXY: + os << "negativeFaceXY"; + break; + case positiveFaceXY: + os << "positiveFaceXY"; + break; + case negativeFaceYZ: + os << "negativeFaceYZ|cylinderCover|tubeOuterCover|tubeSectorOuterCover|" + "trapezoidFaceAlpha"; + break; + case positiveFaceYZ: + os << "positiveFaceYZ|tubeInnerCover|tubeSectorInnerCover|" + "trapezoidFaceBeta"; + break; + case negativeFaceZX: + os << "negativeFaceZX|tubeSectorNegativePhi"; + break; + case positiveFaceZX: + os << "positiveFaceZX|tubeSectorPositivePhi"; + break; + case undefinedFace: + os << "undefinedFace"; + break; + default: + os << face; } return os; } -} +} // namespace Acts diff --git a/Core/include/Acts/Geometry/BoundarySurfaceT.hpp b/Core/include/Acts/Geometry/BoundarySurfaceT.hpp index db2dad517e2fe61d0830fe766eb29a04d254883c..6dd3dbe8b14b2080d863193f8ddbe27a874cb99d 100644 --- a/Core/include/Acts/Geometry/BoundarySurfaceT.hpp +++ b/Core/include/Acts/Geometry/BoundarySurfaceT.hpp @@ -37,24 +37,21 @@ class Surface; /// nominclature template <class T> -class BoundarySurfaceT -{ +class BoundarySurfaceT { /// declare the TrackingVolume as friend friend T; - using VolumePtr = std::shared_ptr<const T>; + using VolumePtr = std::shared_ptr<const T>; using VolumeArray = BinnedArray<VolumePtr>; -public: + public: /// Default Constructor BoundarySurfaceT() - : m_surface(nullptr) - , m_insideVolume(nullptr) - , m_outsideVolume(nullptr) - , m_insideVolumeArray(nullptr) - , m_outsideVolumeArray(nullptr) - { - } + : m_surface(nullptr), + m_insideVolume(nullptr), + m_outsideVolume(nullptr), + m_insideVolumeArray(nullptr), + m_outsideVolumeArray(nullptr) {} /// Constructor for a Boundary with exact two Volumes attached to it /// - usually used in a volume constructor @@ -62,16 +59,13 @@ public: /// @param surface The unqiue surface the boundary represents /// @param inside The inside volume the bounday surface points to /// @param outside The outside volume the boundary surface points to - BoundarySurfaceT(std::shared_ptr<const Surface> surface, - const T* inside, - const T* outside) - : m_surface(std::move(surface)) - , m_insideVolume(inside) - , m_outsideVolume(outside) - , m_insideVolumeArray(nullptr) - , m_outsideVolumeArray(nullptr) - { - } + BoundarySurfaceT(std::shared_ptr<const Surface> surface, const T* inside, + const T* outside) + : m_surface(std::move(surface)), + m_insideVolume(inside), + m_outsideVolume(outside), + m_insideVolumeArray(nullptr), + m_outsideVolumeArray(nullptr) {} /// Constructor for a Boundary with exact two Volumes attached to it /// - usually used in a volume constructor @@ -79,16 +73,13 @@ public: /// @param surface The unqiue surface the boundary represents /// @param inside The inside volume the bounday surface points to /// @param outside The outside volume the boundary surface points to - BoundarySurfaceT(std::shared_ptr<const Surface> surface, - VolumePtr inside, - VolumePtr outside) - : m_surface(std::move(surface)) - , m_insideVolume(inside.get()) - , m_outsideVolume(outside.get()) - , m_insideVolumeArray(nullptr) - , m_outsideVolumeArray(nullptr) - { - } + BoundarySurfaceT(std::shared_ptr<const Surface> surface, VolumePtr inside, + VolumePtr outside) + : m_surface(std::move(surface)), + m_insideVolume(inside.get()), + m_outsideVolume(outside.get()), + m_insideVolumeArray(nullptr), + m_outsideVolumeArray(nullptr) {} /// Constructor for a Boundary with exact multiple Volumes attached to it /// - usually used in a volume constructor @@ -97,16 +88,14 @@ public: /// @param insideArray The inside volume array the bounday surface points to /// @param outsideArray The outside volume array the boundary surface /// points to - BoundarySurfaceT(std::shared_ptr<const Surface> surface, + BoundarySurfaceT(std::shared_ptr<const Surface> surface, std::shared_ptr<const VolumeArray> insideArray, std::shared_ptr<const VolumeArray> outsideArray) - : m_surface(std::move(surface)) - , m_insideVolume(nullptr) - , m_outsideVolume(nullptr) - , m_insideVolumeArray(insideArray) - , m_outsideVolumeArray(outsideArray) - { - } + : m_surface(std::move(surface)), + m_insideVolume(nullptr), + m_outsideVolume(nullptr), + m_insideVolumeArray(insideArray), + m_outsideVolumeArray(outsideArray) {} /// Get the next Volume depending on GlobalPosition, GlobalMomentum, dir on /// the TrackParameters and the requested direction @@ -117,11 +106,9 @@ public: /// @param dir is an aditional direction corrective /// /// @return The attached volume at that position - virtual const T* - attachedVolume(const GeometryContext& gctx, - const Vector3D& pos, - const Vector3D& mom, - NavigationDirection pdir) const; + virtual const T* attachedVolume(const GeometryContext& gctx, + const Vector3D& pos, const Vector3D& mom, + NavigationDirection pdir) const; /// templated onBoundary method /// @@ -130,15 +117,12 @@ public: /// @param gctx The current geometry context object, e.g. alignment /// @param pars The parameters used for this call template <class P> - bool - onBoundary(const GeometryContext& gctx, const P& pars) const - { + bool onBoundary(const GeometryContext& gctx, const P& pars) const { return surfaceRepresentation().isOnSurface(gctx, pars); } /// The Surface Representation of this - virtual const Surface& - surfaceRepresentation() const; + virtual const Surface& surfaceRepresentation() const; /// Virtual Destructor virtual ~BoundarySurfaceT() = default; @@ -150,8 +134,7 @@ public: /// @param gctx The current geometry context object, e.g. alignment /// @param volume The volume to be attached /// @param inout The boundary orientation @todo update to along/opposite - void - attachVolume(VolumePtr volume, BoundaryOrientation inout); + void attachVolume(VolumePtr volume, BoundaryOrientation inout); /// Helper metho: attach a Volume to this BoundarySurfaceT /// this si done during the geometry construction and only called by @@ -159,11 +142,10 @@ public: /// /// @param volumes The volume array to be attached /// @param inout The boundary orientation @todo update to along/opposite - void - attachVolumeArray(std::shared_ptr<const VolumeArray> volumes, - BoundaryOrientation inout); + void attachVolumeArray(std::shared_ptr<const VolumeArray> volumes, + BoundaryOrientation inout); -protected: + protected: /// the represented surface by this std::shared_ptr<const Surface> m_surface; /// the inside (w.r.t. normal vector) volume to point to if only one exists @@ -177,16 +159,13 @@ protected: }; template <class T> -inline const Surface& -BoundarySurfaceT<T>::surfaceRepresentation() const -{ +inline const Surface& BoundarySurfaceT<T>::surfaceRepresentation() const { return (*(m_surface.get())); } template <class T> -void -BoundarySurfaceT<T>::attachVolume(VolumePtr volume, BoundaryOrientation inout) -{ +void BoundarySurfaceT<T>::attachVolume(VolumePtr volume, + BoundaryOrientation inout) { if (inout == insideVolume) { m_insideVolume = volume.get(); } else { @@ -195,11 +174,9 @@ BoundarySurfaceT<T>::attachVolume(VolumePtr volume, BoundaryOrientation inout) } template <class T> -void -BoundarySurfaceT<T>::attachVolumeArray( +void BoundarySurfaceT<T>::attachVolumeArray( const std::shared_ptr<const VolumeArray> volumes, - BoundaryOrientation inout) -{ + BoundaryOrientation inout) { if (inout == insideVolume) { m_insideVolumeArray = volumes; } else { @@ -208,12 +185,10 @@ BoundarySurfaceT<T>::attachVolumeArray( } template <class T> -const T* -BoundarySurfaceT<T>::attachedVolume(const GeometryContext& gctx, - const Vector3D& pos, - const Vector3D& mom, - NavigationDirection pdir) const -{ +const T* BoundarySurfaceT<T>::attachedVolume(const GeometryContext& gctx, + const Vector3D& pos, + const Vector3D& mom, + NavigationDirection pdir) const { const T* attVolume = nullptr; // dot product with normal vector to distinguish inside/outside if ((surfaceRepresentation().normal(gctx, pos)).dot(pdir * mom) > 0.) { diff --git a/Core/include/Acts/Geometry/ConeLayer.hpp b/Core/include/Acts/Geometry/ConeLayer.hpp index c06061754d5bc78a9403a68a9b29277e40825ebb..215362699a7a02ab331096d4baf5878573caf451 100644 --- a/Core/include/Acts/Geometry/ConeLayer.hpp +++ b/Core/include/Acts/Geometry/ConeLayer.hpp @@ -26,9 +26,8 @@ class ApproachDescriptor; /// Class to describe a conical detector layer for tracking, it inhertis from /// both, Layer base class and ConeSurface class /// -class ConeLayer : virtual public ConeSurface, public Layer -{ -public: +class ConeLayer : virtual public ConeSurface, public Layer { + public: /// Factory for shared layer /// /// @param transform is the 3D transform that poisitions the layer in 3D frame @@ -41,20 +40,15 @@ public: /// @todo chage od and ad to unique_ptr /// /// @return is a shared pointer to a layer - static MutableLayerPtr - create(std::shared_ptr<const Transform3D> transform, - std::shared_ptr<const ConeBounds> cbounds, - std::unique_ptr<SurfaceArray> surfaceArray, - double thickness = 0., - std::unique_ptr<ApproachDescriptor> ad = nullptr, - LayerType laytyp = Acts::active) - { - return MutableLayerPtr(new ConeLayer(std::move(transform), - std::move(cbounds), - std::move(surfaceArray), - thickness, - std::move(ad), - laytyp)); + static MutableLayerPtr create( + std::shared_ptr<const Transform3D> transform, + std::shared_ptr<const ConeBounds> cbounds, + std::unique_ptr<SurfaceArray> surfaceArray, double thickness = 0., + std::unique_ptr<ApproachDescriptor> ad = nullptr, + LayerType laytyp = Acts::active) { + return MutableLayerPtr(new ConeLayer( + std::move(transform), std::move(cbounds), std::move(surfaceArray), + thickness, std::move(ad), laytyp)); } /// Default Constructor - delete @@ -64,22 +58,18 @@ public: ConeLayer(const ConeLayer& cla) = delete; /// Assignment operator for ConeLayers - delete - ConeLayer& - operator=(const ConeLayer&) - = delete; + ConeLayer& operator=(const ConeLayer&) = delete; /// Destructor ~ConeLayer() override = default; /// Transforms the layer into a Surface representation for extrapolation - const ConeSurface& - surfaceRepresentation() const override; + const ConeSurface& surfaceRepresentation() const override; // Non-const version - ConeSurface& - surfaceRepresentation() override; + ConeSurface& surfaceRepresentation() override; -protected: + protected: /// Private constructor with arguments /// /// @param transform is the 3D transform that poisitions the layer in 3D frame @@ -90,12 +80,11 @@ protected: /// @param laytyp is the layer type /// /// @todo chage od and ad to unique_ptr - ConeLayer(std::shared_ptr<const Transform3D> transform, - std::shared_ptr<const ConeBounds> cbounds, - std::unique_ptr<SurfaceArray> surfaceArray, - double thickness = 0., - std::unique_ptr<ApproachDescriptor> ade = nullptr, - LayerType laytyp = Acts::active); + ConeLayer(std::shared_ptr<const Transform3D> transform, + std::shared_ptr<const ConeBounds> cbounds, + std::unique_ptr<SurfaceArray> surfaceArray, double thickness = 0., + std::unique_ptr<ApproachDescriptor> ade = nullptr, + LayerType laytyp = Acts::active); /// Private copy constructor with shift, called by create(args*) /// @@ -104,4 +93,4 @@ protected: ConeLayer(const ConeLayer& cla, const Transform3D& shift); }; -} // namespace \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Geometry/CuboidVolumeBounds.hpp b/Core/include/Acts/Geometry/CuboidVolumeBounds.hpp index df5eec3329acd5c8eb6d97723cfad025fbe7a7f3..96495d13f3f207098bacb9d098a877cc13f1e03c 100644 --- a/Core/include/Acts/Geometry/CuboidVolumeBounds.hpp +++ b/Core/include/Acts/Geometry/CuboidVolumeBounds.hpp @@ -43,9 +43,8 @@ class Surface; /// /// @image html CuboidVolumeBounds_decomp.gif -class CuboidVolumeBounds : public VolumeBounds -{ -public: +class CuboidVolumeBounds : public VolumeBounds { + public: /// @enum BoundValues for readability enum BoundValues { bv_halfX = 0, bv_halfY = 1, bv_halfZ = 2, bv_length = 3 }; @@ -70,111 +69,88 @@ public: /// Assignment operator /// /// @param bobo is the source volume bounds to be assigned - CuboidVolumeBounds& - operator=(const CuboidVolumeBounds& bobo); + CuboidVolumeBounds& operator=(const CuboidVolumeBounds& bobo); /// Virtual constructor - CuboidVolumeBounds* - clone() const override; + CuboidVolumeBounds* clone() const override; /// This method checks if position in the 3D volume /// frame is inside the cylinder /// /// @param pos is the position in volume frame to be checked /// @param tol is the absolute tolerance to be applied - bool - inside(const Vector3D& pos, double tol = 0.) const override; + bool inside(const Vector3D& pos, double tol = 0.) const override; /// Method to decompose the Bounds into boundarySurfaces /// @note this method is a pure factory the volume is resposible /// for the memory management /// /// @param transformPtr is the transfrom of the volume - std::vector<std::shared_ptr<const Surface>> - decomposeToSurfaces(const Transform3D* transformPtr) const override; + std::vector<std::shared_ptr<const Surface>> decomposeToSurfaces( + const Transform3D* transformPtr) const override; /// This method returns the halflength in local x - double - halflengthX() const; + double halflengthX() const; /// This method returns the halflength in local y - double - halflengthY() const; + double halflengthY() const; /// This method returns the halflength in local z - double - halflengthZ() const; + double halflengthZ() const; /// Output Method for std::ostream /// /// @param sl is ostream operator to be dumped into - std::ostream& - toStream(std::ostream& sl) const override; + std::ostream& toStream(std::ostream& sl) const override; -private: + private: /// Templated dumpT method template <class T> - T& - dumpT(T& dt) const; + T& dumpT(T& dt) const; /// This method returns the associated RecantleBounds of the face PlaneSurface /// parallel to local xy plane - std::shared_ptr<const RectangleBounds> - faceXYRectangleBounds() const; + std::shared_ptr<const RectangleBounds> faceXYRectangleBounds() const; /// This method returns the associated RecantleBounds of the face PlaneSurface /// parallel to local yz plane - std::shared_ptr<const RectangleBounds> - faceYZRectangleBounds() const; + std::shared_ptr<const RectangleBounds> faceYZRectangleBounds() const; /// This method returns the associated RecantleBounds of the face PlaneSurface // parallel to local zx plane - std::shared_ptr<const RectangleBounds> - faceZXRectangleBounds() const; + std::shared_ptr<const RectangleBounds> faceZXRectangleBounds() const; /// The bound values - std::vector<TDD_real_t> m_valueStore; + std::vector<TDD_real_t> m_valueStore; std::shared_ptr<const RectangleBounds> m_xyBounds; std::shared_ptr<const RectangleBounds> m_yzBounds; std::shared_ptr<const RectangleBounds> m_zxBounds; }; -inline CuboidVolumeBounds* -CuboidVolumeBounds::clone() const -{ +inline CuboidVolumeBounds* CuboidVolumeBounds::clone() const { return new CuboidVolumeBounds(*this); } -inline bool -CuboidVolumeBounds::inside(const Vector3D& pos, double tol) const -{ - return (std::abs(pos.x()) <= m_valueStore.at(bv_halfX) + tol - && std::abs(pos.y()) <= m_valueStore.at(bv_halfY) + tol - && std::abs(pos.z()) <= m_valueStore.at(bv_halfZ) + tol); +inline bool CuboidVolumeBounds::inside(const Vector3D& pos, double tol) const { + return (std::abs(pos.x()) <= m_valueStore.at(bv_halfX) + tol && + std::abs(pos.y()) <= m_valueStore.at(bv_halfY) + tol && + std::abs(pos.z()) <= m_valueStore.at(bv_halfZ) + tol); } -inline double -CuboidVolumeBounds::halflengthX() const -{ +inline double CuboidVolumeBounds::halflengthX() const { return m_valueStore.at(bv_halfX); } -inline double -CuboidVolumeBounds::halflengthY() const -{ +inline double CuboidVolumeBounds::halflengthY() const { return m_valueStore.at(bv_halfY); } -inline double -CuboidVolumeBounds::halflengthZ() const -{ +inline double CuboidVolumeBounds::halflengthZ() const { return m_valueStore.at(bv_halfZ); } template <class T> -T& -CuboidVolumeBounds::dumpT(T& dt) const -{ +T& CuboidVolumeBounds::dumpT(T& dt) const { dt << std::setiosflags(std::ios::fixed); dt << std::setprecision(5); dt << "Acts::CuboidVolumeBounds: (halfX, halfY, halfZ) = "; @@ -182,4 +158,4 @@ CuboidVolumeBounds::dumpT(T& dt) const << ", " << m_valueStore.at(bv_halfZ) << ")"; return dt; } -} \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Geometry/CuboidVolumeBuilder.hpp b/Core/include/Acts/Geometry/CuboidVolumeBuilder.hpp index 6b3290397ba7bcf4cdc06db797bf828a97de6028..64f0fa9fbc6f398d87ce44641af74f782f8b5f64 100644 --- a/Core/include/Acts/Geometry/CuboidVolumeBuilder.hpp +++ b/Core/include/Acts/Geometry/CuboidVolumeBuilder.hpp @@ -30,13 +30,11 @@ class PlaneSurface; /// mostly unit test applications. Therefore this class does not demand to be a /// universal construction factory but a raw first draft of the idea of factory /// that may be extended in the future. -class CuboidVolumeBuilder : public ITrackingVolumeBuilder -{ -public: +class CuboidVolumeBuilder : public ITrackingVolumeBuilder { + public: /// @brief This struct stores the data for the construction of a single /// PlaneSurface - struct SurfaceConfig - { + struct SurfaceConfig { // Center position Vector3D position; // Rotation @@ -57,8 +55,7 @@ public: /// @brief This struct stores the data for the construction of a PlaneLayer /// that has a single PlaneSurface encapsulated - struct LayerConfig - { + struct LayerConfig { // Configuration of the surface SurfaceConfig surfaceCfg; // Encapsulated surface @@ -73,8 +70,7 @@ public: /// @brief This struct stores the data for the construction of a cuboid /// TrackingVolume with a given number of PlaneLayers - struct VolumeConfig - { + struct VolumeConfig { // Center position Vector3D position; // Lengths in x,y,z @@ -90,8 +86,7 @@ public: }; /// @brief This struct stores the configuration of the tracking geometry - struct Config - { + struct Config { // Center position Vector3D position = Vector3D(0., 0., 0.); // Length in x,y,z @@ -111,11 +106,7 @@ public: /// @brief Setter of the config /// /// @param [in] cfg Configuration that is set - void - setConfig(Config& cfg) - { - m_cfg = cfg; - } + void setConfig(Config& cfg) { m_cfg = cfg; } /// @brief This function creates a surface with a given configuration. A /// detector element is attached if the template parameter is non-void. @@ -124,8 +115,8 @@ public: /// @param [in] cfg Configuration of the surface /// /// @return Pointer to the created surface - std::shared_ptr<const PlaneSurface> - buildSurface(const GeometryContext& gctx, const SurfaceConfig& cfg) const; + std::shared_ptr<const PlaneSurface> buildSurface( + const GeometryContext& gctx, const SurfaceConfig& cfg) const; /// @brief This function creates a layer with a surface encaspulated with a /// given configuration. The surface gets a detector element attached if the @@ -135,8 +126,8 @@ public: /// @param [in, out] cfg Configuration of the layer and the surface /// /// @return Pointer to the created layer - std::shared_ptr<const Layer> - buildLayer(const GeometryContext& gctx, LayerConfig& cfg) const; + std::shared_ptr<const Layer> buildLayer(const GeometryContext& gctx, + LayerConfig& cfg) const; /// @brief This function creates a TrackingVolume with a configurable number /// of layers and surfaces. Each surface gets a detector element attached if @@ -146,8 +137,8 @@ public: /// @param [in, out] cfg Configuration of the TrackingVolume /// /// @return Pointer to the created TrackingVolume - std::shared_ptr<TrackingVolume> - buildVolume(const GeometryContext& gctx, VolumeConfig& cfg) const; + std::shared_ptr<TrackingVolume> buildVolume(const GeometryContext& gctx, + VolumeConfig& cfg) const; /// @brief This function evaluates the minimum and maximum of the binning as /// given by the configurations of the surfaces and layers. The ordering @@ -158,8 +149,8 @@ public: /// /// @return Pair containing the minimum and maximum along the binning /// direction - std::pair<double, double> - binningRange(const GeometryContext& gctx, const VolumeConfig& cfg) const; + std::pair<double, double> binningRange(const GeometryContext& gctx, + const VolumeConfig& cfg) const; /// @brief This function builds a world TrackingVolume based on a given /// configuration @@ -167,12 +158,12 @@ public: /// @param [in] gctx the geometry context for this building /// /// @return Pointer to the created TrackingGeometry - std::shared_ptr<TrackingVolume> - trackingVolume(const GeometryContext& gctx, - std::shared_ptr<const TrackingVolume> /*unused*/, - std::shared_ptr<const VolumeBounds> /*unused*/) const override; + std::shared_ptr<TrackingVolume> trackingVolume( + const GeometryContext& gctx, + std::shared_ptr<const TrackingVolume> /*unused*/, + std::shared_ptr<const VolumeBounds> /*unused*/) const override; -private: + private: /// Configuration of the world volume Config m_cfg; }; diff --git a/Core/include/Acts/Geometry/CutoutCylinderVolumeBounds.hpp b/Core/include/Acts/Geometry/CutoutCylinderVolumeBounds.hpp index 94259b5853c45a89aecc19a7c6cfd07aa21caa6a..db9de6debe2dc59f1ac60d4f8e2e0f2884bd73f7 100644 --- a/Core/include/Acts/Geometry/CutoutCylinderVolumeBounds.hpp +++ b/Core/include/Acts/Geometry/CutoutCylinderVolumeBounds.hpp @@ -30,10 +30,8 @@ class IVisualization; * -------- dz1 ------- * */ -class CutoutCylinderVolumeBounds : public VolumeBounds -{ - -public: +class CutoutCylinderVolumeBounds : public VolumeBounds { + public: /** * Constructor from defining parameters * @param rmin Minimum radius at the "choke points" @@ -42,14 +40,9 @@ public: * @param dz1 The longer halflength of the shape * @param dz2 The shorter halflength of the shape */ - CutoutCylinderVolumeBounds(double rmin, - double rmed, - double rmax, - double dz1, + CutoutCylinderVolumeBounds(double rmin, double rmed, double rmax, double dz1, double dz2) - : m_rmin(rmin), m_rmed(rmed), m_rmax(rmax), m_dz1(dz1), m_dz2(dz2) - { - } + : m_rmin(rmin), m_rmed(rmed), m_rmax(rmax), m_dz1(dz1), m_dz2(dz2) {} /** * Virtual default constructor @@ -60,8 +53,7 @@ public: * Clone method. * @return Pointer to a copy of the shape */ - VolumeBounds* - clone() const override; + VolumeBounds* clone() const override; /** * Inside method to test whether a point is inside the shape @@ -69,8 +61,7 @@ public: * @param tol The tolerance to test with * @return Whether the point is inside or not. */ - bool - inside(const Vector3D& gpos, double tol = 0) const override; + bool inside(const Vector3D& gpos, double tol = 0) const override; /** * Method to decompose the Bounds into Surfaces @@ -80,77 +71,55 @@ public: * * @return vector of surfaces from the decopmosition */ - std::vector<std::shared_ptr<const Surface>> - decomposeToSurfaces(const Transform3D* transform) const override; + std::vector<std::shared_ptr<const Surface>> decomposeToSurfaces( + const Transform3D* transform) const override; /** * Write information about this instance to an outstream * @param sl The outstream * @return The outstream */ - std::ostream& - toStream(std::ostream& sl) const override; + std::ostream& toStream(std::ostream& sl) const override; /** * Draw this shape using a visualization helper * @param helper The visualizatin helper * @param transform Optional transformation matrix */ - void - draw(IVisualization& helper, - const Transform3D& transform = Transform3D::Identity()) const; + void draw(IVisualization& helper, + const Transform3D& transform = Transform3D::Identity()) const; /** * Return the minimum radius * @return The minimum radius */ - double - rMin() const - { - return m_rmin; - } + double rMin() const { return m_rmin; } /** * Return the medium radius * @return The medium radius */ - double - rMed() const - { - return m_rmed; - } + double rMed() const { return m_rmed; } /** * Return the maximum radius * @return The maximum radius */ - double - rMax() const - { - return m_rmax; - } + double rMax() const { return m_rmax; } /** * Return the longer halflength in z. * @return The halflength */ - double - dZ1() const - { - return m_dz1; - } + double dZ1() const { return m_dz1; } /** * Return the shorter halflength in z. * @return The halflength */ - double - dZ2() const - { - return m_dz2; - } + double dZ2() const { return m_dz2; } -private: + private: double m_rmin; double m_rmed; double m_rmax; diff --git a/Core/include/Acts/Geometry/CylinderLayer.hpp b/Core/include/Acts/Geometry/CylinderLayer.hpp index 54df7b8dfcd5792e35ee9803374665709b3b9ad9..1360143431fa61d88acd5e8c6bfb15157ed075f9 100644 --- a/Core/include/Acts/Geometry/CylinderLayer.hpp +++ b/Core/include/Acts/Geometry/CylinderLayer.hpp @@ -31,9 +31,8 @@ class ApproachDescriptor; /// both, /// Layer base class and CylinderSurface class /// -class CylinderLayer : public CylinderSurface, public Layer -{ -public: +class CylinderLayer : public CylinderSurface, public Layer { + public: /// Factory for shared Layer pointer /// create a shared, fully deployed CylinderLayer /// @@ -47,29 +46,22 @@ public: /// @todo ApproachDescriptor to unique_ptr /// /// @return The return object is a shared poiter to the layer. - static MutableLayerPtr - create(const std::shared_ptr<const Transform3D>& transform, - const std::shared_ptr<const CylinderBounds>& cbounds, - std::unique_ptr<SurfaceArray> surfaceArray = nullptr, - double thickness = 0., - std::unique_ptr<ApproachDescriptor> ad = nullptr, - LayerType laytyp = passive) - { - return MutableLayerPtr(new CylinderLayer(transform, - cbounds, - std::move(surfaceArray), - thickness, - std::move(ad), - laytyp)); + static MutableLayerPtr create( + const std::shared_ptr<const Transform3D>& transform, + const std::shared_ptr<const CylinderBounds>& cbounds, + std::unique_ptr<SurfaceArray> surfaceArray = nullptr, + double thickness = 0., std::unique_ptr<ApproachDescriptor> ad = nullptr, + LayerType laytyp = passive) { + return MutableLayerPtr(new CylinderLayer(transform, cbounds, + std::move(surfaceArray), thickness, + std::move(ad), laytyp)); } /// Copy constructor - deleted CylinderLayer(const CylinderLayer& cla) = delete; /// Assignment operator for CylinderLayers - deleted - CylinderLayer& - operator=(const CylinderLayer&) - = delete; + CylinderLayer& operator=(const CylinderLayer&) = delete; /// Default Constructor CylinderLayer() = delete; @@ -79,19 +71,16 @@ public: /// Transforms the layer into a Surface representation /// This is for positioning and extrapolation - const CylinderSurface& - surfaceRepresentation() const override; + const CylinderSurface& surfaceRepresentation() const override; // Non-const version - CylinderSurface& - surfaceRepresentation() override; + CylinderSurface& surfaceRepresentation() override; -private: + private: /// build approach surfaces */ - void - buildApproachDescriptor(); + void buildApproachDescriptor(); -protected: + protected: /// Private constructor for CylinderLayer, called by create(args*) factory /// /// @param transform is the 3D transform that places the layer in 3D space @@ -103,12 +92,12 @@ protected: /// @todo change ApproachDescriptor to unique_ptr /// /// @return The return object is a shared poiter to the layer. - CylinderLayer(const std::shared_ptr<const Transform3D>& transform, + CylinderLayer(const std::shared_ptr<const Transform3D>& transform, const std::shared_ptr<const CylinderBounds>& cBounds, - std::unique_ptr<SurfaceArray> surfaceArray = nullptr, - double thickness = 0., - std::unique_ptr<ApproachDescriptor> ades = nullptr, - LayerType laytyp = passive); + std::unique_ptr<SurfaceArray> surfaceArray = nullptr, + double thickness = 0., + std::unique_ptr<ApproachDescriptor> ades = nullptr, + LayerType laytyp = passive); /// Private copy constructor with shift, called by create(args*) /// diff --git a/Core/include/Acts/Geometry/CylinderVolumeBounds.hpp b/Core/include/Acts/Geometry/CylinderVolumeBounds.hpp index 325b8d9c560ffb79950d32db91954b11ccae4587..36ab891430d11f4b5725cc2bbda34df5775e1725 100644 --- a/Core/include/Acts/Geometry/CylinderVolumeBounds.hpp +++ b/Core/include/Acts/Geometry/CylinderVolumeBounds.hpp @@ -69,16 +69,15 @@ class IVisualization; /// /// @image html CylinderVolumeBounds_decomp.gif -class CylinderVolumeBounds : public VolumeBounds -{ -public: +class CylinderVolumeBounds : public VolumeBounds { + public: /// @enum BoundValues for readability enum BoundValues { - bv_innerRadius = 0, - bv_outerRadius = 1, + bv_innerRadius = 0, + bv_outerRadius = 1, bv_halfPhiSector = 2, - bv_halfZ = 3, - bv_length = 4 + bv_halfZ = 3, + bv_length = 4 }; /// Default Constructor @@ -103,9 +102,7 @@ public: /// @param router is the outer radius of the cylinder /// @param haphi is the half opening angle /// @param halez is the half length in z - CylinderVolumeBounds(double rinner, - double router, - double haphi, + CylinderVolumeBounds(double rinner, double router, double haphi, double halez); /// Constructor - from cylinder bounds and thickness @@ -129,100 +126,82 @@ public: ~CylinderVolumeBounds() override; /// Assignment operator - CylinderVolumeBounds& - operator=(const CylinderVolumeBounds& cylbo); + CylinderVolumeBounds& operator=(const CylinderVolumeBounds& cylbo); /// Virtual constructor - CylinderVolumeBounds* - clone() const override; + CylinderVolumeBounds* clone() const override; /// This method checks if position in the 3D volume /// frame is inside the cylinder /// /// @param pos is a global position to be checked /// @param tol is the tolerance for the check - bool - inside(const Vector3D& pos, double tol = 0.) const override; + bool inside(const Vector3D& pos, double tol = 0.) const override; /// Method to decompose the Bounds into boundarySurfaces /// @param transformPtr is the transform where the boundary surfaces are /// situated /// @note this surface is a factory method, the volume handles the memory - std::vector<std::shared_ptr<const Surface>> - decomposeToSurfaces(const Transform3D* transformPtr) const override; + std::vector<std::shared_ptr<const Surface>> decomposeToSurfaces( + const Transform3D* transformPtr) const override; /// Binning offset - overloaded for some R-binning types /// /// @param bValue is the type used for the binning - Vector3D - binningOffset(BinningValue bValue) const override; + Vector3D binningOffset(BinningValue bValue) const override; /// Binning borders in double /// /// @param bValue is the type used for the binning - double - binningBorder(BinningValue bValue) const override; + double binningBorder(BinningValue bValue) const override; /// This method returns the inner radius - double - innerRadius() const; + double innerRadius() const; /// This method returns the outer radius - double - outerRadius() const; + double outerRadius() const; /// This method returns the medium radius - double - mediumRadius() const; + double mediumRadius() const; /// This method returns the delta radius - double - deltaRadius() const; + double deltaRadius() const; /// This method returns the halfPhiSector angle - double - halfPhiSector() const; + double halfPhiSector() const; /// This method returns the halflengthZ - double - halflengthZ() const; + double halflengthZ() const; /// Output Method for std::ostream - std::ostream& - toStream(std::ostream& sl) const override; + std::ostream& toStream(std::ostream& sl) const override; /// Draw this cylinder to a given helper /// @param helper The helper instance /// @param transform An additional transform, default is identity - void - draw(IVisualization& helper, - const Transform3D& transform = Transform3D::Identity()) const; + void draw(IVisualization& helper, + const Transform3D& transform = Transform3D::Identity()) const; -private: + private: /// templated dumpT method template <class T> - T& - dumpT(T& tstream) const; + T& dumpT(T& tstream) const; /// This method returns the associated CylinderBounds /// of the inner CylinderSurfaces. - std::shared_ptr<const CylinderBounds> - innerCylinderBounds() const; + std::shared_ptr<const CylinderBounds> innerCylinderBounds() const; /// This method returns the associated CylinderBounds /// of the inner CylinderSurfaces. - std::shared_ptr<const CylinderBounds> - outerCylinderBounds() const; + std::shared_ptr<const CylinderBounds> outerCylinderBounds() const; /// This method returns the associated RadialBounds /// for the bottom/top DiscSurface - std::shared_ptr<const DiscBounds> - discBounds() const; + std::shared_ptr<const DiscBounds> discBounds() const; /// This method returns the associated PlaneBounds /// limiting a sectoral CylinderVolume - std::shared_ptr<const PlanarBounds> - sectorPlaneBounds() const; + std::shared_ptr<const PlanarBounds> sectorPlaneBounds() const; /// The internal version of the bounds can be float/double std::vector<TDD_real_t> m_valueStore; @@ -232,39 +211,34 @@ private: static const double s_numericalStable; }; -inline CylinderVolumeBounds* -CylinderVolumeBounds::clone() const -{ +inline CylinderVolumeBounds* CylinderVolumeBounds::clone() const { return new CylinderVolumeBounds(*this); } -inline bool -CylinderVolumeBounds::inside(const Vector3D& pos, double tol) const -{ +inline bool CylinderVolumeBounds::inside(const Vector3D& pos, + double tol) const { using VectorHelpers::perp; using VectorHelpers::phi; - double ros = perp(pos); - bool insidePhi = cos(phi(pos)) >= cos(m_valueStore[bv_halfPhiSector]) - tol; - bool insideR = insidePhi ? ((ros >= m_valueStore[bv_innerRadius] - tol) - && (ros <= m_valueStore[bv_outerRadius] + tol)) + double ros = perp(pos); + bool insidePhi = cos(phi(pos)) >= cos(m_valueStore[bv_halfPhiSector]) - tol; + bool insideR = insidePhi ? ((ros >= m_valueStore[bv_innerRadius] - tol) && + (ros <= m_valueStore[bv_outerRadius] + tol)) : false; - bool insideZ - = insideR ? (std::abs(pos.z()) <= m_valueStore[bv_halfZ] + tol) : false; + bool insideZ = + insideR ? (std::abs(pos.z()) <= m_valueStore[bv_halfZ] + tol) : false; return (insideZ && insideR && insidePhi); } -inline Vector3D -CylinderVolumeBounds::binningOffset(BinningValue bValue) const -{ // the medium radius is taken for r-type binning +inline Vector3D CylinderVolumeBounds::binningOffset(BinningValue bValue) + const { // the medium radius is taken for r-type binning if (bValue == Acts::binR || bValue == Acts::binRPhi) { return Vector3D(mediumRadius(), 0., 0.); } return VolumeBounds::binningOffset(bValue); } -inline double -CylinderVolumeBounds::binningBorder(BinningValue bValue) const -{ // the medium radius is taken for r-type binning +inline double CylinderVolumeBounds::binningBorder(BinningValue bValue) + const { // the medium radius is taken for r-type binning if (bValue == Acts::binR) { return 0.5 * deltaRadius(); } @@ -274,47 +248,33 @@ CylinderVolumeBounds::binningBorder(BinningValue bValue) const return VolumeBounds::binningBorder(bValue); } -inline double -CylinderVolumeBounds::innerRadius() const -{ +inline double CylinderVolumeBounds::innerRadius() const { return m_valueStore.at(bv_innerRadius); } -inline double -CylinderVolumeBounds::outerRadius() const -{ +inline double CylinderVolumeBounds::outerRadius() const { return m_valueStore.at(bv_outerRadius); } -inline double -CylinderVolumeBounds::mediumRadius() const -{ - return 0.5 - * (m_valueStore.at(bv_innerRadius) + m_valueStore.at(bv_outerRadius)); +inline double CylinderVolumeBounds::mediumRadius() const { + return 0.5 * + (m_valueStore.at(bv_innerRadius) + m_valueStore.at(bv_outerRadius)); } -inline double -CylinderVolumeBounds::deltaRadius() const -{ +inline double CylinderVolumeBounds::deltaRadius() const { return (m_valueStore.at(bv_outerRadius) - m_valueStore.at(bv_innerRadius)); } -inline double -CylinderVolumeBounds::halfPhiSector() const -{ +inline double CylinderVolumeBounds::halfPhiSector() const { return m_valueStore.at(bv_halfPhiSector); } -inline double -CylinderVolumeBounds::halflengthZ() const -{ +inline double CylinderVolumeBounds::halflengthZ() const { return m_valueStore.at(bv_halfZ); } template <class T> -T& -CylinderVolumeBounds::dumpT(T& tstream) const -{ +T& CylinderVolumeBounds::dumpT(T& tstream) const { tstream << std::setiosflags(std::ios::fixed); tstream << std::setprecision(5); tstream << "Acts::CylinderVolumeBounds: (rMin, rMax, halfPhi, halfZ) = "; @@ -324,4 +284,4 @@ CylinderVolumeBounds::dumpT(T& tstream) const << m_valueStore.at(bv_halfZ); return tstream; } -} \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Geometry/CylinderVolumeBuilder.hpp b/Core/include/Acts/Geometry/CylinderVolumeBuilder.hpp index 178ad3ecd93e0a2bda0aba88e7f330c55440666c..bdcfae3e38ec2bdb52f2f5208ec40cdc1af56856 100644 --- a/Core/include/Acts/Geometry/CylinderVolumeBuilder.hpp +++ b/Core/include/Acts/Geometry/CylinderVolumeBuilder.hpp @@ -24,9 +24,9 @@ #ifndef ATAS_GEOMETRYTOOLS_TAKESMALLERBIGGER #define ATAS_GEOMETRYTOOLS_TAKESMALLERBIGGER #define takeSmaller(current, test) current = current < test ? current : test -#define takeBigger(current, test) current = current > test ? current : test -#define takeSmallerBigger(cSmallest, cBiggest, test) \ - takeSmaller(cSmallest, test); \ +#define takeBigger(current, test) current = current > test ? current : test +#define takeSmallerBigger(cSmallest, cBiggest, test) \ + takeSmaller(cSmallest, test); \ takeBigger(cBiggest, test) #endif @@ -38,43 +38,38 @@ class IVolumeMaterial; /// @enum WrappingCondition enum WrappingCondition { - Undefined = 0, ///< inconsistency detected - Attaching = 1, ///< attach the volumes - Inserting = 2, ///< insert the new volume - Wrapping = 3, ///< wrap the new volume around + Undefined = 0, ///< inconsistency detected + Attaching = 1, ///< attach the volumes + Inserting = 2, ///< insert the new volume + Wrapping = 3, ///< wrap the new volume around CentralInserting = 4, ///< insert the new one into the center - CentralWrapping = 5, ///< wrap the new central volume around - NoWrapping = 6 ///< no inner volume present - no wrapping needed + CentralWrapping = 5, ///< wrap the new central volume around + NoWrapping = 6 ///< no inner volume present - no wrapping needed }; /// VolumeConfig struct to understand the layer config -struct VolumeConfig -{ - bool present{false}; ///< layers are present - bool wrapping{false}; ///< in what way they are binned - double rMin; ///< min parameter r - double rMax; ///< max parameter r - double zMin; ///< min parameter z - double zMax; ///< max parameter z - LayerVector layers; ///< the layers you have +struct VolumeConfig { + bool present{false}; ///< layers are present + bool wrapping{false}; ///< in what way they are binned + double rMin; ///< min parameter r + double rMax; ///< max parameter r + double zMin; ///< min parameter z + double zMax; ///< max parameter z + LayerVector layers; ///< the layers you have /// Default constructor VolumeConfig() - : rMin(std::numeric_limits<double>::max()) - , rMax(std::numeric_limits<double>::lowest()) - , zMin(std::numeric_limits<double>::max()) - , zMax(std::numeric_limits<double>::lowest()) - , layers() - { - } + : rMin(std::numeric_limits<double>::max()), + rMax(std::numeric_limits<double>::lowest()), + zMin(std::numeric_limits<double>::max()), + zMax(std::numeric_limits<double>::lowest()), + layers() {} /// Adapt to the dimensions of another config in Z /// it will take the maximum/minimum values and just overwrite them /// /// @param [in] lConfig is the config to which it should be adapded - void - adaptZ(const VolumeConfig& lConfig) - { + void adaptZ(const VolumeConfig& lConfig) { if (lConfig) { takeSmaller(zMin, lConfig.zMin); takeBigger(zMax, lConfig.zMax); @@ -85,9 +80,7 @@ struct VolumeConfig /// it will take the maximum/minimum values and just overwrite them /// /// @param [in] lConfig is the config to which it should be adapded - void - adaptR(const VolumeConfig& lConfig) - { + void adaptR(const VolumeConfig& lConfig) { if (lConfig) { takeSmaller(rMin, lConfig.rMin); takeBigger(rMax, lConfig.rMax); @@ -98,9 +91,7 @@ struct VolumeConfig /// it will take the maximum/minimum values and just overwrite them /// /// @param [in] lConfig is the config to which it should be adapded - void - adapt(const VolumeConfig& lConfig) - { + void adapt(const VolumeConfig& lConfig) { adaptZ(lConfig); adaptR(lConfig); } @@ -111,17 +102,15 @@ struct VolumeConfig /// /// @param [in] lConfig is the config to which it should be attached /// @note lConfig will be changed - void - midPointAttachZ(VolumeConfig& lConfig) - { + void midPointAttachZ(VolumeConfig& lConfig) { if (lConfig.zMin >= zMax) { - double zMid = 0.5 * (lConfig.zMin + zMax); + double zMid = 0.5 * (lConfig.zMin + zMax); lConfig.zMin = zMid; - zMax = zMid; + zMax = zMid; } else { - double zMid = 0.5 * (zMin + lConfig.zMax); + double zMid = 0.5 * (zMin + lConfig.zMax); lConfig.zMax = zMid; - zMin = zMid; + zMin = zMid; } } @@ -129,9 +118,7 @@ struct VolumeConfig /// it attaches the one volume config to the other one /// /// @param [in] lConfig is the confit to which it should be attached - void - attachZ(const VolumeConfig& lConfig) - { + void attachZ(const VolumeConfig& lConfig) { if (lConfig.zMin >= zMax) { zMax = lConfig.zMin; } else { @@ -143,9 +130,7 @@ struct VolumeConfig /// /// @param [in] vConfig is the config against which is checked /// @return boolean if the overlap in r exists - bool - overlapsInR(const VolumeConfig& vConfig) const - { + bool overlapsInR(const VolumeConfig& vConfig) const { if (!present) { return false; } @@ -156,9 +141,7 @@ struct VolumeConfig /// /// @param [in] vConfig is the config against which is checked /// @return boolean if the overlap in z exists - bool - overlapsInZ(const VolumeConfig& vConfig) const - { + bool overlapsInZ(const VolumeConfig& vConfig) const { if (!present) { return false; } @@ -169,9 +152,7 @@ struct VolumeConfig /// /// @param [in] vConfig is the config against which is checked /// @return boolean if the current volume wraps the vConfig fully - bool - wraps(const VolumeConfig& vConfig) const - { + bool wraps(const VolumeConfig& vConfig) const { if ((zMax <= vConfig.zMin) || (zMin >= vConfig.zMax)) { return true; } @@ -181,34 +162,26 @@ struct VolumeConfig /// Check if contained full set /// /// @param [in] vConfig is the config against which is checked - bool - contains(const VolumeConfig& vConfig) const - { + bool contains(const VolumeConfig& vConfig) const { return (containsInR(vConfig) && containsInZ(vConfig)); } /// Check if contained radially /// /// @param [in] vConfig is the config against which is checked - bool - containsInR(const VolumeConfig& vConfig) const - { + bool containsInR(const VolumeConfig& vConfig) const { return (rMin >= vConfig.rMax); } /// Check if contained longitudinally /// /// @param [in] vConfig is the config against which is checked - bool - containsInZ(const VolumeConfig& vConfig) const - { + bool containsInZ(const VolumeConfig& vConfig) const { return (vConfig.zMin > zMin && vConfig.zMax < zMax); } /// Method for output formatting - std::string - toString() const - { + std::string toString() const { /// for screen output std::stringstream sl; sl << rMin << ", " << rMax << " / " << zMin << ", " << zMax; @@ -220,9 +193,8 @@ struct VolumeConfig }; /// @brief The WrappingSetup that is happening here -struct WrappingConfig -{ -public: +struct WrappingConfig { + public: /// the new volumes VolumeConfig nVolumeConfig; VolumeConfig cVolumeConfig; @@ -241,23 +213,21 @@ public: VolumeConfig externalVolumeConfig; // WrappingCondition - WrappingCondition wCondition = Undefined; - std::string wConditionScreen = "[left untouched]"; + WrappingCondition wCondition = Undefined; + std::string wConditionScreen = "[left untouched]"; /// constructor WrappingConfig() = default; /// configure the new Volume - void - configureContainerVolume() - { + void configureContainerVolume() { // set the container to be present containerVolumeConfig.present = true; - std::string wConditionAddon = ""; + std::string wConditionAddon = ""; // if we have more than one config present - if ((nVolumeConfig && cVolumeConfig) || (cVolumeConfig && pVolumeConfig) - || (nVolumeConfig && pVolumeConfig)) { - wCondition = Wrapping; + if ((nVolumeConfig && cVolumeConfig) || (cVolumeConfig && pVolumeConfig) || + (nVolumeConfig && pVolumeConfig)) { + wCondition = Wrapping; wConditionScreen = "grouped to "; } // adapt the new volume config to the existing configs @@ -295,9 +265,7 @@ public: } /// wrap, insert, attach - void - wrapInsertAttach() - { + void wrapInsertAttach() { // action is only needed if an existing volume // is present if (existingVolumeConfig) { @@ -307,13 +275,13 @@ public: if (nVolumeConfig && nVolumeConfig.zMax < existingVolumeConfig.zMin) { nVolumeConfig.attachZ(existingVolumeConfig); // will attach the new volume(s) - wCondition = Attaching; + wCondition = Attaching; wConditionScreen = "[n attched]"; } if (pVolumeConfig && pVolumeConfig.zMin > existingVolumeConfig.zMax) { pVolumeConfig.attachZ(existingVolumeConfig); // will attach the new volume(s) - wCondition = Attaching; + wCondition = Attaching; wConditionScreen = "[p attched]"; } // see if inner glue volumes are needed @@ -351,7 +319,7 @@ public: cVolumeConfig.rMax = containerVolumeConfig.rMax; pVolumeConfig.rMax = containerVolumeConfig.rMax; // will wrap the new volume(s) around existing - wCondition = Wrapping; + wCondition = Wrapping; wConditionScreen = "[fully wrapped]"; } else if (existingVolumeConfig.rMin > containerVolumeConfig.rMax) { // full insertion case @@ -364,7 +332,7 @@ public: cVolumeConfig.rMin = containerVolumeConfig.rMin; pVolumeConfig.rMin = containerVolumeConfig.rMin; // will insert the new volume(s) into existing - wCondition = Inserting; + wCondition = Inserting; wConditionScreen = "[fully inserted]"; } else if (cVolumeConfig.wraps(existingVolumeConfig)) { // central wrapping case @@ -377,7 +345,7 @@ public: cVolumeConfig.rMin = existingVolumeConfig.rMax; pVolumeConfig.rMin = existingVolumeConfig.rMin; // set the Central Wrapping - wCondition = CentralWrapping; + wCondition = CentralWrapping; wConditionScreen = "[centrally wrapped]"; } else if (existingVolumeConfig.wraps(cVolumeConfig)) { // central insertion case @@ -390,7 +358,7 @@ public: cVolumeConfig.rMin = containerVolumeConfig.rMin; pVolumeConfig.rMin = containerVolumeConfig.rMin; // set the Central Wrapping - wCondition = CentralWrapping; + wCondition = CentralWrapping; wConditionScreen = "[centrally inserted]"; } @@ -399,10 +367,10 @@ public: // the gap reference is either the container for FULL wrapping, // insertion // or it is the centralVolume for central wrapping, insertion - VolumeConfig referenceVolume - = (wCondition == Wrapping || wCondition == Inserting) - ? containerVolumeConfig - : cVolumeConfig; + VolumeConfig referenceVolume = + (wCondition == Wrapping || wCondition == Inserting) + ? containerVolumeConfig + : cVolumeConfig; // - at the negative sector if (existingVolumeConfig.zMin > referenceVolume.zMin) { fGapVolumeConfig.present = true; @@ -437,9 +405,7 @@ public: } /// Method for output formatting - std::string - toString() const - { + std::string toString() const { // for screen output std::stringstream sl; if (containerVolumeConfig) { @@ -495,13 +461,11 @@ public: /// barrel and the third the layers of the positive endcap. If the one of these /// pointers is a nullptr no layers will be created for this volume -class CylinderVolumeBuilder : public ITrackingVolumeBuilder -{ -public: +class CylinderVolumeBuilder : public ITrackingVolumeBuilder { + public: /// @struct Config /// Nested configuration struct for this CylinderVolumeBuilder - struct Config - { + struct Config { /// the trackign volume helper for construction std::shared_ptr<const ITrackingVolumeHelper> trackingVolumeHelper = nullptr; /// the string based indenfication @@ -515,8 +479,8 @@ public: /// needed to build layers within the volume std::shared_ptr<const ILayerBuilder> layerBuilder = nullptr; /// the additional envelope in R to create rMin, rMax - std::pair<double, double> layerEnvelopeR - = {1. * Acts::units::_mm, 1. * Acts::units::_mm}; + std::pair<double, double> layerEnvelopeR = {1. * Acts::units::_mm, + 1. * Acts::units::_mm}; /// the additional envelope in Z to create zMin, zMax double layerEnvelopeZ = 10. * Acts::units::_mm; @@ -528,10 +492,9 @@ public: /// /// @param [in] cvbConfig is the configuraiton struct to steer the builder /// @param [in] logger logging instance - CylinderVolumeBuilder(const Config& cvbConfig, - std::unique_ptr<const Logger> logger - = getDefaultLogger("CylinderVolumeBuilder", - Logging::INFO)); + CylinderVolumeBuilder(const Config& cvbConfig, + std::unique_ptr<const Logger> logger = getDefaultLogger( + "CylinderVolumeBuilder", Logging::INFO)); /// Destructor ~CylinderVolumeBuilder() override; @@ -545,28 +508,24 @@ public: /// @return a mutable pointer to a new TrackingVolume which includes the /// optionally provided exisitingVolume consistently for further /// processing - MutableTrackingVolumePtr - trackingVolume(const GeometryContext& gctx, - TrackingVolumePtr existingVolume = nullptr, - VolumeBoundsPtr externalBounds = nullptr) const override; + MutableTrackingVolumePtr trackingVolume( + const GeometryContext& gctx, TrackingVolumePtr existingVolume = nullptr, + VolumeBoundsPtr externalBounds = nullptr) const override; /// Set configuration method /// /// @param [in] cvbConfig is the new configuration to be set - void - setConfiguration(const Config& cvbConfig); + void setConfiguration(const Config& cvbConfig); /// Get configuration method /// /// @return a copy of the config object - Config - getConfiguration() const; + Config getConfiguration() const; /// set logging instance /// /// @param [in] newLogger is the logging istance to be set - void - setLogger(std::unique_ptr<const Logger> newLogger); + void setLogger(std::unique_ptr<const Logger> newLogger); /// Analyze the layer config to gather needed dimension /// @@ -574,21 +533,17 @@ public: /// @param [in] lVector is the vector of layers that are parsed /// /// @return a VolumeConfig representing this layer - VolumeConfig - analyzeLayers(const GeometryContext& gctx, const LayerVector& lVector) const; + VolumeConfig analyzeLayers(const GeometryContext& gctx, + const LayerVector& lVector) const; -private: + private: /// Configuration struct Config m_cfg; /// Private access to the logger /// /// @return a const reference to the logger - const Logger& - logger() const - { - return *m_logger; - } + const Logger& logger() const { return *m_logger; } /// the logging instance std::unique_ptr<const Logger> m_logger; @@ -605,19 +560,16 @@ private: /// @param [in] sign distinguishes inside/outside testing /// /// @return boolean that indicates the test result - bool - checkLayerContainment(const GeometryContext& gctx, - VolumeConfig& layerConfig, - const VolumeConfig& insideConfig, - const VolumeConfig& volumeConfig, - int sign) const; + bool checkLayerContainment(const GeometryContext& gctx, + VolumeConfig& layerConfig, + const VolumeConfig& insideConfig, + const VolumeConfig& volumeConfig, int sign) const; }; /// Return the configuration object -inline CylinderVolumeBuilder::Config -CylinderVolumeBuilder::getConfiguration() const -{ +inline CylinderVolumeBuilder::Config CylinderVolumeBuilder::getConfiguration() + const { return m_cfg; } -} // namespace +} // namespace Acts diff --git a/Core/include/Acts/Geometry/CylinderVolumeHelper.hpp b/Core/include/Acts/Geometry/CylinderVolumeHelper.hpp index 87261e4944fb65e266a12f785654defbee4db75e..d5de14615305969006c5050fce2d0c104610fae0 100644 --- a/Core/include/Acts/Geometry/CylinderVolumeHelper.hpp +++ b/Core/include/Acts/Geometry/CylinderVolumeHelper.hpp @@ -15,9 +15,9 @@ #ifndef ACTS_TOOLS_TAKESMALLERBIGGER #define ACTS_TOOLS_TAKESMALLERBIGGER #define takeSmaller(current, test) current = current < test ? current : test -#define takeBigger(current, test) current = current > test ? current : test -#define takeSmallerBigger(cSmallest, cBiggest, test) \ - takeSmaller(cSmallest, test); \ +#define takeBigger(current, test) current = current > test ? current : test +#define takeSmallerBigger(cSmallest, cBiggest, test) \ + takeSmaller(cSmallest, test); \ takeBigger(cBiggest, test) #endif @@ -44,13 +44,11 @@ class IVolumeMaterial; /// The concrete implementation for cylindrical TrackingVolume /// objects of the ITrackingVolumeCreator interface /// -class CylinderVolumeHelper : public ITrackingVolumeHelper -{ -public: +class CylinderVolumeHelper : public ITrackingVolumeHelper { + public: /// @struct Config /// Nested configuration struct for this CylinderVolumeHelper - struct Config - { + struct Config { /// a tool for coherent LayerArray creation std::shared_ptr<const ILayerArrayCreator> layerArrayCreator = nullptr; /// Helper Tool to create TrackingVolume @@ -67,10 +65,9 @@ public: /// Constructor /// @param cvhConfig is the configuration struct for this builder /// @param logger logging instance - CylinderVolumeHelper(const Config& cvhConfig, - std::unique_ptr<const Logger> logger - = getDefaultLogger("CylinderVolumeHelper", - Logging::INFO)); + CylinderVolumeHelper(const Config& cvhConfig, + std::unique_ptr<const Logger> logger = getDefaultLogger( + "CylinderVolumeHelper", Logging::INFO)); /// Destructor ~CylinderVolumeHelper() override = default; @@ -88,14 +85,13 @@ public: /// @param bType (optional) BinningType - arbitrary(default) or equidistant /// /// @return shared pointer to a new TrackingVolume - MutableTrackingVolumePtr - createTrackingVolume(const GeometryContext& gctx, - const LayerVector& layers, - std::shared_ptr<const IVolumeMaterial> volumeMaterial, - VolumeBoundsPtr volumeBounds, - std::shared_ptr<const Transform3D> transform = nullptr, - const std::string& volumeName = "UndefinedVolume", - BinningType bType = arbitrary) const override; + MutableTrackingVolumePtr createTrackingVolume( + const GeometryContext& gctx, const LayerVector& layers, + std::shared_ptr<const IVolumeMaterial> volumeMaterial, + VolumeBoundsPtr volumeBounds, + std::shared_ptr<const Transform3D> transform = nullptr, + const std::string& volumeName = "UndefinedVolume", + BinningType bType = arbitrary) const override; /// Create a TrackingVolume* from a set of layers and (optional) parameters /// @@ -112,16 +108,12 @@ public: /// @param bType (optional) BinningType - arbitrary(default) or equidistant /// /// @return shared pointer to a new TrackingVolume - MutableTrackingVolumePtr - createTrackingVolume(const GeometryContext& gctx, - const LayerVector& layers, - std::shared_ptr<const IVolumeMaterial> volumeMaterial, - double rMin, - double rMax, - double zMin, - double zMax, - const std::string& volumeName = "UndefinedVolume", - BinningType bType = arbitrary) const override; + MutableTrackingVolumePtr createTrackingVolume( + const GeometryContext& gctx, const LayerVector& layers, + std::shared_ptr<const IVolumeMaterial> volumeMaterial, double rMin, + double rMax, double zMin, double zMax, + const std::string& volumeName = "UndefinedVolume", + BinningType bType = arbitrary) const override; /// Create a gap volume from dimensions and /// @note this TrackingVolume is restricted to Translation only @@ -137,17 +129,12 @@ public: /// @param volumeName volume name to be given /// /// @return shared pointer to a new TrackingVolume - MutableTrackingVolumePtr - createGapTrackingVolume(const GeometryContext& gctx, - std::shared_ptr<const IVolumeMaterial> volumeMaterial, - double rMin, - double rMax, - double zMin, - double zMax, - unsigned int materialLayers, - bool cylinder = true, - const std::string& volumeName - = "UndefinedVolume") const override; + MutableTrackingVolumePtr createGapTrackingVolume( + const GeometryContext& gctx, + std::shared_ptr<const IVolumeMaterial> volumeMaterial, double rMin, + double rMax, double zMin, double zMax, unsigned int materialLayers, + bool cylinder = true, + const std::string& volumeName = "UndefinedVolume") const override; /// Create a gap volume from dimensions and /// @@ -163,17 +150,13 @@ public: /// @param bType (optional) BinningType - arbitrary(default) or equidistant /// /// @return shared pointer to a new TrackingVolume - MutableTrackingVolumePtr - createGapTrackingVolume(const GeometryContext& gctx, - std::shared_ptr<const IVolumeMaterial> volumeMaterial, - double rMin, - double rMax, - double zMin, - double zMax, - const std::vector<double>& layerPositions, - bool cylinder = true, - const std::string& volumeName = "UndefinedVolume", - BinningType bType = arbitrary) const override; + MutableTrackingVolumePtr createGapTrackingVolume( + const GeometryContext& gctx, + std::shared_ptr<const IVolumeMaterial> volumeMaterial, double rMin, + double rMax, double zMin, double zMax, + const std::vector<double>& layerPositions, bool cylinder = true, + const std::string& volumeName = "UndefinedVolume", + BinningType bType = arbitrary) const override; /// Create a container volumes from sub volumes, input volumes are ordered in /// R or Z by convention @@ -183,38 +166,30 @@ public: /// /// /// @return shared pointer to a new TrackingVolume - MutableTrackingVolumePtr - createContainerTrackingVolume( - const GeometryContext& gctx, + MutableTrackingVolumePtr createContainerTrackingVolume( + const GeometryContext& gctx, const TrackingVolumeVector& volumes) const override; /// Set configuration method /// /// @param cvhConfig is the configurtion struct assigned - void - setConfiguration(const Config& cvhConfig); + void setConfiguration(const Config& cvhConfig); /// Get configuration method - Config - getConfiguration() const; + Config getConfiguration() const; /// Set logging instance /// /// @param newLogger is the logger isntance to be set - void - setLogger(std::unique_ptr<const Logger> newLogger); + void setLogger(std::unique_ptr<const Logger> newLogger); -protected: + protected: /// Configuration object Config m_cfg; -private: + private: /// Private access method to the logging instance - const Logger& - logger() const - { - return *m_logger; - } + const Logger& logger() const { return *m_logger; } /// the looging instance std::unique_ptr<const Logger> m_logger; @@ -232,17 +207,12 @@ private: /// @param zMaxClean the maximal z extend given by layers /// @param bValue the binning value in which the binning works /// @param bType is the type of binning: equidistant, arbitrary - bool - estimateAndCheckDimension(const GeometryContext& gctx, - const LayerVector& layers, - const CylinderVolumeBounds*& cylinderVolumeBounds, - std::shared_ptr<const Transform3D>& transform, - double& rMinClean, - double& rMaxClean, - double& zMinClean, - double& zMaxClean, - BinningValue& bValue, - BinningType bType = arbitrary) const; + bool estimateAndCheckDimension( + const GeometryContext& gctx, const LayerVector& layers, + const CylinderVolumeBounds*& cylinderVolumeBounds, + std::shared_ptr<const Transform3D>& transform, double& rMinClean, + double& rMaxClean, double& zMinClean, double& zMaxClean, + BinningValue& bValue, BinningType bType = arbitrary) const; /// Private method - interglue all volumes contained by a TrackingVolume /// and set the outside glue volumes in the descriptor @@ -255,15 +225,10 @@ private: /// @param rMax the maximim radius of the volume /// @param zMin the minimum z extend of the volume /// @param zMax the maximum z extend of the volume - bool - interGlueTrackingVolume(const GeometryContext& gctx, - const MutableTrackingVolumePtr& tVolume, - bool rBinned, - double rMin, - double rGlueMin, - double rMax, - double zMin, - double zMax) const; + bool interGlueTrackingVolume(const GeometryContext& gctx, + const MutableTrackingVolumePtr& tVolume, + bool rBinned, double rMin, double rGlueMin, + double rMax, double zMin, double zMax) const; /// Private method - glue volume to the other /// @@ -277,27 +242,22 @@ private: /// @param rMax the maximim radius of the volume /// @param zMin the minimum z extend of the volume /// @param zMax the maximum z extend of the volume - void - glueTrackingVolumes(const GeometryContext& gctx, - const MutableTrackingVolumePtr& tvolOne, - BoundarySurfaceFace faceOne, - const MutableTrackingVolumePtr& tvolTwo, - BoundarySurfaceFace faceTwo, - double rMin, - double rGlueMin, - double rMax, - double zMin, - double zMax) const; + void glueTrackingVolumes(const GeometryContext& gctx, + const MutableTrackingVolumePtr& tvolOne, + BoundarySurfaceFace faceOne, + const MutableTrackingVolumePtr& tvolTwo, + BoundarySurfaceFace faceTwo, double rMin, + double rGlueMin, double rMax, double zMin, + double zMax) const; /// Private method - helper method not to duplicate code /// /// @param tVolume is the volume to which faces are added /// @param bsf is the boundary surface to which faces are added /// @param vols are the voluems which are added - void - addFaceVolumes(const MutableTrackingVolumePtr& tvol, - BoundarySurfaceFace glueFace, - TrackingVolumeVector& vols) const; + void addFaceVolumes(const MutableTrackingVolumePtr& tvol, + BoundarySurfaceFace glueFace, + TrackingVolumeVector& vols) const; /// Private method - helper method to save some code /// @@ -309,13 +269,8 @@ private: /// @param binsZ are the bins for the material in z /// /// @return shared pointer to newly created cylinder layer - LayerPtr - createCylinderLayer(double z, - double r, - double halflengthZ, - double thickness, - int binsPhi, - int binsZ) const; + LayerPtr createCylinderLayer(double z, double r, double halflengthZ, + double thickness, int binsPhi, int binsZ) const; /// Private method - helper method to save some code /// @@ -327,18 +282,12 @@ private: /// @param binsR are the bins for the material in R /// /// @return shared pointer to newly created cylinder layer - LayerPtr - createDiscLayer(double z, - double rMin, - double rMax, - double thickness, - int binsPhi, - int binsR) const; + LayerPtr createDiscLayer(double z, double rMin, double rMax, double thickness, + int binsPhi, int binsR) const; }; -inline CylinderVolumeHelper::Config -CylinderVolumeHelper::getConfiguration() const -{ +inline CylinderVolumeHelper::Config CylinderVolumeHelper::getConfiguration() + const { return m_cfg; } -} \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Geometry/DiscLayer.hpp b/Core/include/Acts/Geometry/DiscLayer.hpp index 8dd437c294039403a4eb11941fcfe7de4ca318aa..664013eab566cafd516dbdcfa5b39854fa596c37 100644 --- a/Core/include/Acts/Geometry/DiscLayer.hpp +++ b/Core/include/Acts/Geometry/DiscLayer.hpp @@ -29,9 +29,8 @@ class ApproachDescriptor; /// it inhertis from both, Layer base class /// and DiscSurface class -class DiscLayer : virtual public DiscSurface, public Layer -{ -public: +class DiscLayer : virtual public DiscSurface, public Layer { + public: /// Factory constructor with DiscSurface components /// /// @param transform is the transform to place the layer in the 3D frame @@ -44,20 +43,15 @@ public: /// @todo move ApproachDescriptor to unqique_ptr /// /// @return a sharted pointer to the new layer - static MutableLayerPtr - create(const std::shared_ptr<const Transform3D>& transform, - const std::shared_ptr<const DiscBounds>& dbounds, - std::unique_ptr<SurfaceArray> surfaceArray = nullptr, - double thickness = 0., - std::unique_ptr<ApproachDescriptor> ad = nullptr, - LayerType laytyp = Acts::passive) - { - return MutableLayerPtr(new DiscLayer(transform, - dbounds, - std::move(surfaceArray), - thickness, - std::move(ad), - laytyp)); + static MutableLayerPtr create( + const std::shared_ptr<const Transform3D>& transform, + const std::shared_ptr<const DiscBounds>& dbounds, + std::unique_ptr<SurfaceArray> surfaceArray = nullptr, + double thickness = 0., std::unique_ptr<ApproachDescriptor> ad = nullptr, + LayerType laytyp = Acts::passive) { + return MutableLayerPtr(new DiscLayer(transform, dbounds, + std::move(surfaceArray), thickness, + std::move(ad), laytyp)); } /// Default Constructor @@ -67,28 +61,23 @@ public: DiscLayer(const DiscLayer& cla) = delete; /// Assignment operator for DiscLayers - deleted - DiscLayer& - operator=(const DiscLayer&) - = delete; + DiscLayer& operator=(const DiscLayer&) = delete; /// Destructor ~DiscLayer() override = default; /// Transforms the layer into a Surface representation for extrapolation /// @return This method returns a surface reference - const DiscSurface& - surfaceRepresentation() const override; + const DiscSurface& surfaceRepresentation() const override; // Non-const version - DiscSurface& - surfaceRepresentation() override; + DiscSurface& surfaceRepresentation() override; -private: + private: /// build approach surfaces - void - buildApproachDescriptor(); + void buildApproachDescriptor(); -protected: + protected: // Constructor with DiscSurface components and pointer to SurfaceArray /// /// @param transform is the transform to place the layer in the 3D frame @@ -98,14 +87,14 @@ protected: /// @param ad is the approach descriptor that provides the approach surface /// @param laytyp is the layer taype DiscLayer(const std::shared_ptr<const Transform3D>& transform, - const std::shared_ptr<const DiscBounds>& dbounds, - std::unique_ptr<SurfaceArray> surfaceArray = nullptr, - double thickness = 0., - std::unique_ptr<ApproachDescriptor> ades = nullptr, - LayerType laytyp = Acts::active); + const std::shared_ptr<const DiscBounds>& dbounds, + std::unique_ptr<SurfaceArray> surfaceArray = nullptr, + double thickness = 0., + std::unique_ptr<ApproachDescriptor> ades = nullptr, + LayerType laytyp = Acts::active); /// Copy constructor with shift DiscLayer(const DiscLayer& cla, const Transform3D& tr); }; -} // namespace +} // namespace Acts diff --git a/Core/include/Acts/Geometry/DoubleTrapezoidVolumeBounds.hpp b/Core/include/Acts/Geometry/DoubleTrapezoidVolumeBounds.hpp index 9bcda5e881b682647432dbc358373936b47ed960..0501c6565952e4bdbdfa130773e1572f7c7d7733 100644 --- a/Core/include/Acts/Geometry/DoubleTrapezoidVolumeBounds.hpp +++ b/Core/include/Acts/Geometry/DoubleTrapezoidVolumeBounds.hpp @@ -53,20 +53,19 @@ class DiamondBounds; /// /// @image html DoubleTrapezoidVolumeBounds_decomp.gif -class DoubleTrapezoidVolumeBounds : public VolumeBounds -{ -public: +class DoubleTrapezoidVolumeBounds : public VolumeBounds { + public: /// @enum BoundValues for readability enum BoundValues { bv_minHalfX = 0, bv_medHalfX = 1, bv_maxHalfX = 2, - bv_halfY1 = 3, - bv_halfY2 = 4, - bv_halfZ = 5, - bv_alpha1 = 6, - bv_alpha2 = 7, - bv_length = 8 + bv_halfY1 = 3, + bv_halfY2 = 4, + bv_halfZ = 5, + bv_alpha1 = 6, + bv_alpha2 = 7, + bv_length = 8 }; /// Default Constructor @@ -81,12 +80,8 @@ public: /// @param haley1 first half length in y (to negative) /// @param haley2 second half length in y (to positive) /// @param halez half length in z - DoubleTrapezoidVolumeBounds(double minhalex, - double medhalex, - double maxhalex, - double haley1, - double haley2, - double halez); + DoubleTrapezoidVolumeBounds(double minhalex, double medhalex, double maxhalex, + double haley1, double haley2, double halez); /// Copy Constructor /// @@ -99,169 +94,130 @@ public: /// Assignment operator /// /// @param trabo is the source bounds - DoubleTrapezoidVolumeBounds& - operator=(const DoubleTrapezoidVolumeBounds& trabo); + DoubleTrapezoidVolumeBounds& operator=( + const DoubleTrapezoidVolumeBounds& trabo); /// Virtual constructor - DoubleTrapezoidVolumeBounds* - clone() const override; + DoubleTrapezoidVolumeBounds* clone() const override; /// This method checks if position in the 3D volume frame /// is inside the cylinder /// /// @param pos is the global position to be checked for inside /// @param tol is the tolerance parametere - bool - inside(const Vector3D& pos, double tol = 0.) const override; + bool inside(const Vector3D& pos, double tol = 0.) const override; /// decompose into boundary surfaces /// /// @param transformPtr is the transform applied by the volume /// /// @return a vector of surfaces to be used as boundary surfaces - std::vector<std::shared_ptr<const Surface>> - decomposeToSurfaces(const Transform3D* transformPtr) const override; + std::vector<std::shared_ptr<const Surface>> decomposeToSurfaces( + const Transform3D* transformPtr) const override; /// This method returns the X halflength at minimal Y - double - minHalflengthX() const; + double minHalflengthX() const; /// This method returns the (maximal) halflength in local x - double - medHalflengthX() const; + double medHalflengthX() const; /// This method returns the X halflength at maximal Y (local coordinates) - double - maxHalflengthX() const; + double maxHalflengthX() const; /// This method returns the halflength1 in local y - double - halflengthY1() const; + double halflengthY1() const; /// This method returns the halflength2 in local y - double - halflengthY2() const; + double halflengthY2() const; /// This method returns the halflength in local z - double - halflengthZ() const; + double halflengthZ() const; /// This method returns the opening angle in point A (negative local x) - double - alpha1() const; + double alpha1() const; /// This method returns the opening angle in point A' (negative local x) - double - alpha2() const; + double alpha2() const; /// Output Method for std::ostream - std::ostream& - toStream(std::ostream& sl) const override; + std::ostream& toStream(std::ostream& sl) const override; -private: + private: /// dump method /// /// @tparam dT is the output stream to be dumped into template <class T> - T& - dumpT(T& dT) const; + T& dumpT(T& dT) const; /// This method returns the associated DoubleTrapezoidBounds of the face /// PlaneSurface parallel to local xy plane - DiamondBounds* - faceXYDiamondBounds() const; + DiamondBounds* faceXYDiamondBounds() const; /// This method returns the associated RecantleBounds of the face PlaneSurface /// attached to alpha (negative local x) - RectangleBounds* - faceAlpha1RectangleBounds() const; + RectangleBounds* faceAlpha1RectangleBounds() const; /// This method returns the associated RecantleBounds of the face PlaneSurface /// attached to alpha (negative local x) - RectangleBounds* - faceAlpha2RectangleBounds() const; + RectangleBounds* faceAlpha2RectangleBounds() const; /// This method returns the associated RecantleBounds of the face PlaneSurface /// attached to beta (positive local x) - RectangleBounds* - faceBeta1RectangleBounds() const; + RectangleBounds* faceBeta1RectangleBounds() const; /// This method returns the associated RecantleBounds of the face PlaneSurface /// attached to beta (positive local x) - RectangleBounds* - faceBeta2RectangleBounds() const; + RectangleBounds* faceBeta2RectangleBounds() const; /// This method returns the associated RecantleBounds of the face PlaneSurface /// parallel to local zx plane, negative local y - RectangleBounds* - faceZXRectangleBoundsBottom() const; + RectangleBounds* faceZXRectangleBoundsBottom() const; /// This method returns the associated RecantleBounds of the face PlaneSurface /// parallel to local zx plane, positive local y - RectangleBounds* - faceZXRectangleBoundsTop() const; + RectangleBounds* faceZXRectangleBoundsTop() const; std::vector<TDD_real_t> m_valueStore; ///< the internal store }; -inline DoubleTrapezoidVolumeBounds* -DoubleTrapezoidVolumeBounds::clone() const -{ +inline DoubleTrapezoidVolumeBounds* DoubleTrapezoidVolumeBounds::clone() const { return new DoubleTrapezoidVolumeBounds(*this); } -inline double -DoubleTrapezoidVolumeBounds::minHalflengthX() const -{ +inline double DoubleTrapezoidVolumeBounds::minHalflengthX() const { return m_valueStore.at(bv_minHalfX); } -inline double -DoubleTrapezoidVolumeBounds::medHalflengthX() const -{ +inline double DoubleTrapezoidVolumeBounds::medHalflengthX() const { return m_valueStore.at(bv_medHalfX); } -inline double -DoubleTrapezoidVolumeBounds::maxHalflengthX() const -{ +inline double DoubleTrapezoidVolumeBounds::maxHalflengthX() const { return m_valueStore.at(bv_maxHalfX); } -inline double -DoubleTrapezoidVolumeBounds::halflengthY1() const -{ +inline double DoubleTrapezoidVolumeBounds::halflengthY1() const { return m_valueStore.at(bv_halfY1); } -inline double -DoubleTrapezoidVolumeBounds::halflengthY2() const -{ +inline double DoubleTrapezoidVolumeBounds::halflengthY2() const { return m_valueStore.at(bv_halfY2); } -inline double -DoubleTrapezoidVolumeBounds::halflengthZ() const -{ +inline double DoubleTrapezoidVolumeBounds::halflengthZ() const { return m_valueStore.at(bv_halfZ); } -inline double -DoubleTrapezoidVolumeBounds::alpha1() const -{ +inline double DoubleTrapezoidVolumeBounds::alpha1() const { return m_valueStore.at(bv_alpha1); } -inline double -DoubleTrapezoidVolumeBounds::alpha2() const -{ +inline double DoubleTrapezoidVolumeBounds::alpha2() const { return m_valueStore.at(bv_alpha2); } template <class T> -T& -DoubleTrapezoidVolumeBounds::dumpT(T& dT) const -{ +T& DoubleTrapezoidVolumeBounds::dumpT(T& dT) const { dT << std::setiosflags(std::ios::fixed); dT << std::setprecision(5); dT << "Acts::DoubleTrapezoidVolumeBounds: (minhalfX, medhalfX, maxhalfX, " @@ -272,4 +228,4 @@ DoubleTrapezoidVolumeBounds::dumpT(T& dT) const << ", " << m_valueStore.at(bv_halfZ) << ")"; return dT; } -} \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Geometry/GenericApproachDescriptor.hpp b/Core/include/Acts/Geometry/GenericApproachDescriptor.hpp index 1d49b84b81ad785eeeda07db5bc84b41f8a25b12..b7506d1f4b209b8361fd5c400528ac2e880cbf59 100644 --- a/Core/include/Acts/Geometry/GenericApproachDescriptor.hpp +++ b/Core/include/Acts/Geometry/GenericApproachDescriptor.hpp @@ -29,17 +29,17 @@ namespace Acts { /// It is templated in order to allow for BoundarySurfaces from /// representing volumes of layers to be re-used -class GenericApproachDescriptor : public ApproachDescriptor -{ -public: +class GenericApproachDescriptor : public ApproachDescriptor { + public: /// A generic approach descriptor for new Acts::Surface objects /// passing ownership /// /// @param aSurfaces are the approach surfaces GenericApproachDescriptor( std::vector<std::shared_ptr<const Surface>> aSurfaces) - : ApproachDescriptor(), m_surfaces(std::move(aSurfaces)), m_surfaceCache() - { + : ApproachDescriptor(), + m_surfaces(std::move(aSurfaces)), + m_surfaceCache() { m_surfaceCache = unpack_shared_vector(m_surfaces); } @@ -49,8 +49,7 @@ public: /// @brief Register the Layer to the surfaces /// /// @param lay is the layer to be registerd - void - registerLayer(const Layer& lay) override; + void registerLayer(const Layer& lay) override; /// get the compatible surfaces /// @@ -61,23 +60,18 @@ public: /// @param corrfnc is an noption correction function /// /// @return : a boolean indicating if an actual intersection had been tried - ObjectIntersection<Surface> - approachSurface(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& gdir, - NavigationDirection navDir, - const BoundaryCheck& bcheck, - CorrFnc corrfnc = nullptr) const override; + ObjectIntersection<Surface> approachSurface( + const GeometryContext& gctx, const Vector3D& gpos, const Vector3D& gdir, + NavigationDirection navDir, const BoundaryCheck& bcheck, + CorrFnc corrfnc = nullptr) const override; /// return all contained surfaces of this approach descriptor - const std::vector<const Surface*>& - containedSurfaces() const override; + const std::vector<const Surface*>& containedSurfaces() const override; /// Non-const version - std::vector<const Surface*>& - containedSurfaces() override; + std::vector<const Surface*>& containedSurfaces() override; -private: + private: /// approach surfaces with ownership control std::vector<std::shared_ptr<const Surface>> m_surfaces; diff --git a/Core/include/Acts/Geometry/GenericCuboidVolumeBounds.hpp b/Core/include/Acts/Geometry/GenericCuboidVolumeBounds.hpp index 6efd79ce0c885298ecdc2549c60d96314c0bca43..cc52935ded5cc5de65ff0e1d48bb4e8d47168ad2 100644 --- a/Core/include/Acts/Geometry/GenericCuboidVolumeBounds.hpp +++ b/Core/include/Acts/Geometry/GenericCuboidVolumeBounds.hpp @@ -19,10 +19,8 @@ namespace Acts { class IVisualization; -class GenericCuboidVolumeBounds : public VolumeBounds -{ - -public: +class GenericCuboidVolumeBounds : public VolumeBounds { + public: GenericCuboidVolumeBounds() = delete; /// Constructor from a set of vertices @@ -36,8 +34,7 @@ public: /// clone() method to make deep copy in Volume copy constructor and for /// assigment operator of the Surface class. - VolumeBounds* - clone() const override; + VolumeBounds* clone() const override; /// Checking if position given in volume frame is inside /// @@ -45,8 +42,7 @@ public: /// @param tol is the tolerance applied for the inside check /// /// @return boolean indicating if the position is inside - bool - inside(const Vector3D& gpos, double tol = 0.) const override; + bool inside(const Vector3D& gpos, double tol = 0.) const override; /// Method to decompose the Bounds into Surfaces /// the Volume can turn them into BoundarySurfaces @@ -56,24 +52,22 @@ public: /// @note this is factory method /// /// @return a vector of surfaces bounding this volume - std::vector<std::shared_ptr<const Surface>> - decomposeToSurfaces(const Transform3D* transform) const override; + std::vector<std::shared_ptr<const Surface>> decomposeToSurfaces( + const Transform3D* transform) const override; /// Output Method for std::ostream, to be overloaded by child classes /// /// @param sl is the output stream to be written into - std::ostream& - toStream(std::ostream& sl) const override; + std::ostream& toStream(std::ostream& sl) const override; /** * Draw this shape using a visualization helper * @param helper The visualizatin helper * @param transform Optional transformation matrix */ - void - draw(IVisualization& helper, - const Transform3D& transform = Transform3D::Identity()) const; + void draw(IVisualization& helper, + const Transform3D& transform = Transform3D::Identity()) const; -private: + private: std::array<Vector3D, 8> m_vertices; std::array<Vector3D, 6> m_normals; }; diff --git a/Core/include/Acts/Geometry/GeometryID.hpp b/Core/include/Acts/Geometry/GeometryID.hpp index c6b568fa0f3925ed698837449087de79dfc20ced..951596a89edccf2474f5a5ed9e792c27cbb53d39 100644 --- a/Core/include/Acts/Geometry/GeometryID.hpp +++ b/Core/include/Acts/Geometry/GeometryID.hpp @@ -28,10 +28,8 @@ namespace Acts { /// - (Boundary) Surfaces - uses counting through boundary surfaces /// - Volumes - uses counting given by TrackingGeometry -class GeometryID -{ - -public: +class GeometryID { + public: // clang-format off constexpr static geo_id_value volume_mask = 0xff00000000000000; // 255 volumes constexpr static geo_id_value boundary_mask = 0x00ff000000000000; // 255 boundaries @@ -54,9 +52,7 @@ public: /// @param id type_id numbered object /// @param type_mask is necessary for the decoding GeometryID(geo_id_value type_id, geo_id_value type_mask) - : m_value(ACTS_BIT_ENCODE(type_id, type_mask)) - { - } + : m_value(ACTS_BIT_ENCODE(type_id, type_mask)) {} /// Copy constructor /// @@ -66,9 +62,7 @@ public: /// Assignement operator /// /// @param tddID is the geometry ID that will be assigned - GeometryID& - operator=(const GeometryID& tddID) - { + GeometryID& operator=(const GeometryID& tddID) { if (&tddID != this) { m_value = tddID.m_value; } @@ -78,9 +72,7 @@ public: /// Add some stuff - a new GeometryID /// /// @param tddID is the geometry ID that will be added - GeometryID& - operator+=(const GeometryID& tddID) - { + GeometryID& operator+=(const GeometryID& tddID) { m_value += tddID.value(); return (*this); } @@ -88,9 +80,7 @@ public: /// Add some stuff - a decoded value /// /// @param add_value is the fully decoded value to be added - GeometryID& - operator+=(geo_id_value add_value) - { + GeometryID& operator+=(geo_id_value add_value) { m_value += add_value; return (*this); } @@ -98,62 +88,47 @@ public: /// Equality operator /// /// @param tddID is the geometry ID that will be compared on equality - bool - operator==(const GeometryID& tddID) const - { + bool operator==(const GeometryID& tddID) const { return (m_value == tddID.value()); } /// Non-equality operator /// /// @param tddID is the geometry ID that will be compared on equality - bool - operator!=(const GeometryID& tddID) const - { - return !operator==(tddID); - } + bool operator!=(const GeometryID& tddID) const { return !operator==(tddID); } /// Add some stuff /// /// @param type_id which identifier do you wanna add /// @param type_mask the mask that is supposed to be applied - void - add(geo_id_value type_id, geo_id_value type_mask) - { + void add(geo_id_value type_id, geo_id_value type_mask) { m_value += ACTS_BIT_ENCODE(type_id, type_mask); } /// return the value /// /// @param mask is the mask to be applied - geo_id_value - value(geo_id_value mask = 0) const; + geo_id_value value(geo_id_value mask = 0) const; /// return the split value as string for debugging - std::string - toString() const; + std::string toString() const; -private: + private: geo_id_value m_value = 0; }; -inline geo_id_value -GeometryID::value(geo_id_value mask) const -{ +inline geo_id_value GeometryID::value(geo_id_value mask) const { if (mask != 0u) { return ACTS_BIT_DECODE(m_value, mask); } return m_value; } -inline std::string -GeometryID::toString() const -{ - - geo_id_value volume_id = value(volume_mask); - geo_id_value boundary_id = value(boundary_mask); - geo_id_value layer_id = value(layer_mask); - geo_id_value approach_id = value(approach_mask); +inline std::string GeometryID::toString() const { + geo_id_value volume_id = value(volume_mask); + geo_id_value boundary_id = value(boundary_mask); + geo_id_value layer_id = value(layer_mask); + geo_id_value approach_id = value(approach_mask); geo_id_value sensitive_id = value(sensitive_mask); std::stringstream dstream; @@ -166,16 +141,11 @@ GeometryID::toString() const } /// Overload of operator< | <= | > | >= for the usage in a map -bool -operator<(const GeometryID& one, const GeometryID& two); -bool -operator<=(const GeometryID& one, const GeometryID& two); -bool -operator>(const GeometryID& one, const GeometryID& two); -bool -operator>=(const GeometryID& one, const GeometryID& two); +bool operator<(const GeometryID& one, const GeometryID& two); +bool operator<=(const GeometryID& one, const GeometryID& two); +bool operator>(const GeometryID& one, const GeometryID& two); +bool operator>=(const GeometryID& one, const GeometryID& two); /// Overload of << operator for std::ostream for debug output -std::ostream& -operator<<(std::ostream& sl, const GeometryID& tid); -} +std::ostream& operator<<(std::ostream& sl, const GeometryID& tid); +} // namespace Acts diff --git a/Core/include/Acts/Geometry/GeometryObject.hpp b/Core/include/Acts/Geometry/GeometryObject.hpp index 2dc072bba2351a1824e97ed15251a8eca4da0c21..90ee1ad0559c98bb110f173dc0a7f6261fa9fb8a 100644 --- a/Core/include/Acts/Geometry/GeometryObject.hpp +++ b/Core/include/Acts/Geometry/GeometryObject.hpp @@ -26,9 +26,8 @@ namespace Acts { /// It also provides the binningPosition method for /// Geometry geometrical object to be binned in BinnedArrays /// -class GeometryObject -{ -public: +class GeometryObject { + public: /// default constructor GeometryObject() : m_geoID(0) {} @@ -45,9 +44,7 @@ public: /// assignment operator /// /// @param geoID the source geoID - GeometryObject& - operator=(const GeometryObject& geoID) - { + GeometryObject& operator=(const GeometryObject& geoID) { if (&geoID != this) { m_geoID = geoID.m_geoID; } @@ -56,8 +53,7 @@ public: /// Return the value /// @return the geometry id by reference - const GeometryID& - geoID() const; + const GeometryID& geoID() const; /// Force a binning position method /// @@ -65,8 +61,8 @@ public: /// @param bValue is the value in which you want to bin /// /// @return vector 3D used for the binning schema - virtual const Vector3D - binningPosition(const GeometryContext& gctx, BinningValue bValue) const = 0; + virtual const Vector3D binningPosition(const GeometryContext& gctx, + BinningValue bValue) const = 0; /// Implement the binningValue /// @@ -74,57 +70,50 @@ public: /// @param bValue is the dobule in which you want to bin /// /// @return float to be used for the binning schema - double - binningPositionValue(const GeometryContext& gctx, BinningValue bValue) const; + double binningPositionValue(const GeometryContext& gctx, + BinningValue bValue) const; /// Set the value /// /// @param geoID the geometry identifier to be assigned - void - assignGeoID(const GeometryID& geoID); + void assignGeoID(const GeometryID& geoID); -protected: + protected: GeometryID m_geoID; }; -inline const GeometryID& -GeometryObject::geoID() const -{ +inline const GeometryID& GeometryObject::geoID() const { return m_geoID; } -inline void -GeometryObject::assignGeoID(const GeometryID& geoID) -{ +inline void GeometryObject::assignGeoID(const GeometryID& geoID) { m_geoID = geoID; } -inline double -GeometryObject::binningPositionValue(const GeometryContext& gctx, - BinningValue bValue) const -{ +inline double GeometryObject::binningPositionValue(const GeometryContext& gctx, + BinningValue bValue) const { using VectorHelpers::perp; // now switch switch (bValue) { - // case x - case Acts::binX: { - return binningPosition(gctx, bValue).x(); - } break; - // case y - case Acts::binY: { - return binningPosition(gctx, bValue).y(); - } break; - // case z - case Acts::binZ: { - return binningPosition(gctx, bValue).z(); - } break; - // case - case Acts::binR: { - return perp(binningPosition(gctx, bValue)); - } break; - // do nothing for the default - default: - return 0.; + // case x + case Acts::binX: { + return binningPosition(gctx, bValue).x(); + } break; + // case y + case Acts::binY: { + return binningPosition(gctx, bValue).y(); + } break; + // case z + case Acts::binZ: { + return binningPosition(gctx, bValue).z(); + } break; + // case + case Acts::binR: { + return perp(binningPosition(gctx, bValue)); + } break; + // do nothing for the default + default: + return 0.; } } -} +} // namespace Acts diff --git a/Core/include/Acts/Geometry/GeometryObjectSorter.hpp b/Core/include/Acts/Geometry/GeometryObjectSorter.hpp index 8387fe5d23654b5d5782cf097117560ea1bccfcc..21456a27ac8f9161c78672c4f588b9f7f26b151b 100644 --- a/Core/include/Acts/Geometry/GeometryObjectSorter.hpp +++ b/Core/include/Acts/Geometry/GeometryObjectSorter.hpp @@ -21,9 +21,8 @@ namespace Acts { // @class ObjectSorterT /// template <class T> -class ObjectSorterT : public std::binary_function<T, T, bool> -{ -public: +class ObjectSorterT : public std::binary_function<T, T, bool> { + public: /// Constructor from a binning value /// /// @param bValue is the value in which the binning is done @@ -36,53 +35,47 @@ public: /// @tparam two second object /// /// @return boolen indicator - bool - operator()(T one, T two) const - { + bool operator()(T one, T two) const { + using Acts::VectorHelpers::eta; using Acts::VectorHelpers::perp; using Acts::VectorHelpers::phi; - using Acts::VectorHelpers::eta; // switch the binning value // - binX, binY, binZ, binR, binPhi, binRPhi, binH, binEta switch (m_binningValue) { - // compare on x - case binX: { - return (one.x() < two.x()); - } - // compare on y - case binY: { - return (one.y() < two.y()); - } - // compare on z - case binZ: { - return (one.z() < two.z()); - } - // compare on r - case binR: { - return (perp(one) < perp(two)); - } - // compare on phi - case binPhi: { - return (phi(one) < phi(two)); - } - // compare on eta - case binEta: { - return (eta(one) < eta(two)); - } - // default for the moment - default: { - return (one.norm() < two.norm()); - } + // compare on x + case binX: { + return (one.x() < two.x()); + } + // compare on y + case binY: { + return (one.y() < two.y()); + } + // compare on z + case binZ: { + return (one.z() < two.z()); + } + // compare on r + case binR: { + return (perp(one) < perp(two)); + } + // compare on phi + case binPhi: { + return (phi(one) < phi(two)); + } + // compare on eta + case binEta: { + return (eta(one) < eta(two)); + } + // default for the moment + default: { + return (one.norm() < two.norm()); + } } } - BinningValue - binningValue() const - { - return m_binningValue; - } + BinningValue binningValue() const { return m_binningValue; } -private: + private: BinningValue m_binningValue; ///< the binning value }; @@ -90,21 +83,18 @@ private: /// /// This will check on absolute distance template <class T> -class DistanceSorterT : public std::binary_function<T, T, bool> -{ -public: +class DistanceSorterT : public std::binary_function<T, T, bool> { + public: /// Constructor from a binning value /// /// @param bValue is the value in which the binning is done /// @param reference is the reference point DistanceSorterT(BinningValue bValue, Vector3D reference) - : m_binningValue(bValue) - , m_reference(reference) - , m_refR(VectorHelpers::perp(reference)) - , m_refPhi(VectorHelpers::phi(reference)) - , m_refEta(VectorHelpers::eta(reference)) - { - } + : m_binningValue(bValue), + m_reference(reference), + m_refR(VectorHelpers::perp(reference)), + m_refPhi(VectorHelpers::phi(reference)), + m_refEta(VectorHelpers::eta(reference)) {} /// Comparison operator /// @@ -112,84 +102,80 @@ public: /// @tparam two second object /// /// @return boolen indicator - bool - operator()(T one, T two) const - { + bool operator()(T one, T two) const { + using Acts::VectorHelpers::eta; using Acts::VectorHelpers::perp; using Acts::VectorHelpers::phi; - using Acts::VectorHelpers::eta; // switch the binning value // - binX, binY, binZ, binR, binPhi, binRPhi, binH, binEta switch (m_binningValue) { - // compare on diff x - case binX: { - double diffOneX = one.x() - m_reference.x(); - double diffTwoX = two.x() - m_reference.x(); - return (diffOneX * diffOneX < diffTwoX * diffTwoX); - } - // compare on diff y - case binY: { - double diffOneY = one.y() - m_reference.y(); - double diffTwoY = two.y() - m_reference.y(); - return (diffOneY * diffOneY < diffTwoY * diffTwoY); - } - // compare on diff z - case binZ: { - double diffOneZ = one.z() - m_reference.z(); - double diffTwoZ = two.z() - m_reference.z(); - return (diffOneZ * diffOneZ < diffTwoZ * diffTwoZ); - } - // compare on r - case binR: { - double diffOneR = perp(one) - m_refR; - double diffTwoR = perp(two) - m_refR; - return (diffOneR * diffOneR < diffTwoR * diffTwoR); - } - // compare on phi /// @todo add cyclic value - case binPhi: { - double diffOnePhi = phi(one) - m_refPhi; - double diffTwoPhi = phi(two) - m_refPhi; - return (diffOnePhi * diffOnePhi < diffTwoPhi * diffTwoPhi); - } - // compare on eta - case binEta: { - double diffOneEta = eta(one) - m_refEta; - double diffTwoEta = eta(two) - m_refEta; - return (diffOneEta * diffOneEta < diffTwoEta * diffTwoEta); - } - // default for the moment - default: { - T diffOne(one - m_reference); - T diffTwo(two - m_reference); - return (diffOne.mag2() < diffTwo.mag2()); - } + // compare on diff x + case binX: { + double diffOneX = one.x() - m_reference.x(); + double diffTwoX = two.x() - m_reference.x(); + return (diffOneX * diffOneX < diffTwoX * diffTwoX); + } + // compare on diff y + case binY: { + double diffOneY = one.y() - m_reference.y(); + double diffTwoY = two.y() - m_reference.y(); + return (diffOneY * diffOneY < diffTwoY * diffTwoY); + } + // compare on diff z + case binZ: { + double diffOneZ = one.z() - m_reference.z(); + double diffTwoZ = two.z() - m_reference.z(); + return (diffOneZ * diffOneZ < diffTwoZ * diffTwoZ); + } + // compare on r + case binR: { + double diffOneR = perp(one) - m_refR; + double diffTwoR = perp(two) - m_refR; + return (diffOneR * diffOneR < diffTwoR * diffTwoR); + } + // compare on phi /// @todo add cyclic value + case binPhi: { + double diffOnePhi = phi(one) - m_refPhi; + double diffTwoPhi = phi(two) - m_refPhi; + return (diffOnePhi * diffOnePhi < diffTwoPhi * diffTwoPhi); + } + // compare on eta + case binEta: { + double diffOneEta = eta(one) - m_refEta; + double diffTwoEta = eta(two) - m_refEta; + return (diffOneEta * diffOneEta < diffTwoEta * diffTwoEta); + } + // default for the moment + default: { + T diffOne(one - m_reference); + T diffTwo(two - m_reference); + return (diffOne.mag2() < diffTwo.mag2()); + } } } -private: + private: BinningValue m_binningValue; ///< the binning value - T m_reference; - double m_refR; - double m_refPhi; - double m_refEta; + T m_reference; + double m_refR; + double m_refPhi; + double m_refEta; }; /// @class GeometryObjectSorter /// template <class T> -class GeometryObjectSorterT : public std::binary_function<T, T, bool> -{ -public: +class GeometryObjectSorterT : public std::binary_function<T, T, bool> { + public: /// Constructor from a binning value /// /// @param bValue is the value in which the binning is done /// @param transform is an optional transform to be performed - GeometryObjectSorterT(const GeometryContext& gctx, - BinningValue bValue, + GeometryObjectSorterT(const GeometryContext& gctx, BinningValue bValue, std::shared_ptr<const Transform3D> transform = nullptr) - : m_context(gctx), m_objectSorter(bValue), m_transform(std::move(transform)) - { - } + : m_context(gctx), + m_objectSorter(bValue), + m_transform(std::move(transform)) {} /// Comparison operator /// @@ -197,25 +183,25 @@ public: /// @tparam two second object /// /// @return boolen indicator - bool - operator()(T one, T two) const - { + bool operator()(T one, T two) const { // get the pos one / pos two - Vector3D posOne = m_transform - ? m_transform->inverse() - * one->binningPosition(m_context, m_objectSorter.binningValue()) - : one->binningPosition(m_context, m_objectSorter.binningValue()); - Vector3D posTwo = m_transform - ? m_transform->inverse() - * two->binningPosition(m_context, m_objectSorter.binningValue()) - : two->binningPosition(m_context, m_objectSorter.binningValue()); + Vector3D posOne = + m_transform + ? m_transform->inverse() * + one->binningPosition(m_context, m_objectSorter.binningValue()) + : one->binningPosition(m_context, m_objectSorter.binningValue()); + Vector3D posTwo = + m_transform + ? m_transform->inverse() * + two->binningPosition(m_context, m_objectSorter.binningValue()) + : two->binningPosition(m_context, m_objectSorter.binningValue()); // now call the distance sorter return m_objectSorter.operator()(posOne, posTwo); } -protected: + protected: std::reference_wrapper<const GeometryContext> m_context; - ObjectSorterT<Vector3D> m_objectSorter; - std::shared_ptr<const Transform3D> m_transform; + ObjectSorterT<Vector3D> m_objectSorter; + std::shared_ptr<const Transform3D> m_transform; }; -} \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Geometry/GeometrySignature.hpp b/Core/include/Acts/Geometry/GeometrySignature.hpp index 1c170593508f1b8629dc5b1f9013dce6c4ad8906..aff87c41b882b7d678d84d03da2ed824773fb59e 100644 --- a/Core/include/Acts/Geometry/GeometrySignature.hpp +++ b/Core/include/Acts/Geometry/GeometrySignature.hpp @@ -21,23 +21,23 @@ namespace Acts { /// @todo will be in the future be replace by GeometryID mechanism /// enum GeometrySignature { - Global = 0, - ID = 1, - BeamPipe = 2, - Calo = 3, - MS = 4, - Cavern = 5, + Global = 0, + ID = 1, + BeamPipe = 2, + Calo = 3, + MS = 4, + Cavern = 5, NumberOfSignatures = 6, - Unsigned = 99 + Unsigned = 99 }; enum GeometryType { - Static = 0, - Dense = 1, - DenseWithLayers = 1, - Detached = 2, - Master = 3, + Static = 0, + Dense = 1, + DenseWithLayers = 1, + Detached = 2, + Master = 3, NumberOfGeometryTypes = 3 }; -} // namespace \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Geometry/GeometryStatics.hpp b/Core/include/Acts/Geometry/GeometryStatics.hpp index 4f266bac2dd08b78203799351df8fbbe455a16c9..77014d903c246e826057effe8538876079293ea7 100644 --- a/Core/include/Acts/Geometry/GeometryStatics.hpp +++ b/Core/include/Acts/Geometry/GeometryStatics.hpp @@ -19,10 +19,10 @@ namespace Acts { // transformations -static const Transform3D s_idTransform - = Transform3D::Identity(); //!< idendity transformation -static const Rotation3D s_idRotation - = Rotation3D::Identity(); //!< idendity rotation +static const Transform3D s_idTransform = + Transform3D::Identity(); //!< idendity transformation +static const Rotation3D s_idRotation = + Rotation3D::Identity(); //!< idendity rotation // axis system static const Vector3D s_xAxis(1, 0, 0); //!< global x Axis; @@ -37,8 +37,8 @@ static const Vector2D s_origin2D(0., 0.); static const Vector3D s_origin(0, 0, 0); //!< origin position namespace detail { - static const double _helper[9] = {0., 1., 0., 1., 0., 0., 0., 0., -1.}; +static const double _helper[9] = {0., 1., 0., 1., 0., 0., 0., 0., -1.}; } static const RotationMatrix3D s_idRotationZinverse(detail::_helper); -} \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Geometry/GlueVolumesDescriptor.hpp b/Core/include/Acts/Geometry/GlueVolumesDescriptor.hpp index 789a20d6af35f104e8e2f93cf10dd96df5b6bec2..694a3047ee5aaab915a7852716ccafafc765f056 100644 --- a/Core/include/Acts/Geometry/GlueVolumesDescriptor.hpp +++ b/Core/include/Acts/Geometry/GlueVolumesDescriptor.hpp @@ -20,7 +20,7 @@ namespace Acts { class TrackingVolume; -using TrackingVolumePtr = std::shared_ptr<const TrackingVolume>; +using TrackingVolumePtr = std::shared_ptr<const TrackingVolume>; using TrackingVolumeArray = BinnedArray<TrackingVolumePtr>; /// @class GlueVolumesDescriptor @@ -30,9 +30,8 @@ using TrackingVolumeArray = BinnedArray<TrackingVolumePtr>; /// Detector /// by another one. /// -class GlueVolumesDescriptor -{ -public: +class GlueVolumesDescriptor { + public: /// Constructor GlueVolumesDescriptor() = default; /// Constructor - with arguments @@ -48,9 +47,8 @@ public: /// /// @param bsf is the boundary surface face where the volume array is attached /// @param gvs is the array of volumes to be attached - void - registerGlueVolumes(Acts::BoundarySurfaceFace bsf, - std::shared_ptr<const TrackingVolumeArray> gvs); + void registerGlueVolumes(Acts::BoundarySurfaceFace bsf, + std::shared_ptr<const TrackingVolumeArray> gvs); /// Retrieve the glue volumes /// @@ -58,30 +56,26 @@ public: /// array /// /// @return the shared pointer to the TrackingVolume array - std::shared_ptr<const TrackingVolumeArray> - glueVolumes(BoundarySurfaceFace bsf) const; + std::shared_ptr<const TrackingVolumeArray> glueVolumes( + BoundarySurfaceFace bsf) const; /// Retrieve the available Glue Faces /// @return the list of faces for which glue information is there - const std::vector<BoundarySurfaceFace>& - glueFaces() const; + const std::vector<BoundarySurfaceFace>& glueFaces() const; /// Dump it to the screen - std::string - screenOutput() const; + std::string screenOutput() const; -private: + private: std::map<BoundarySurfaceFace, std::shared_ptr<const TrackingVolumeArray>> - m_glueVolumes; + m_glueVolumes; std::vector<BoundarySurfaceFace> m_glueFaces; }; inline const std::vector<BoundarySurfaceFace>& -GlueVolumesDescriptor::glueFaces() const -{ +GlueVolumesDescriptor::glueFaces() const { return m_glueFaces; } -std::ostream& -operator<<(std::ostream& sl, const GlueVolumesDescriptor& gvd); -} +std::ostream& operator<<(std::ostream& sl, const GlueVolumesDescriptor& gvd); +} // namespace Acts diff --git a/Core/include/Acts/Geometry/ILayerArrayCreator.hpp b/Core/include/Acts/Geometry/ILayerArrayCreator.hpp index 40758a2e8b76408b62ea2907c2f5eced7cfab22a..74f014e2407ff1c42eabe0ebc7695093bf578539 100644 --- a/Core/include/Acts/Geometry/ILayerArrayCreator.hpp +++ b/Core/include/Acts/Geometry/ILayerArrayCreator.hpp @@ -34,9 +34,8 @@ using LayerVector = std::vector<LayerPtr>; /// It receives the LayerVector and creaets an array with NaivgationLayer /// objects /// filled in between. -class ILayerArrayCreator -{ -public: +class ILayerArrayCreator { + public: /// Virtual destructor virtual ~ILayerArrayCreator() = default; @@ -50,12 +49,9 @@ public: /// @param bvalue is the value in which the binning should be done /// /// @return unqiue pointer to a new LayerArray - virtual std::unique_ptr<const LayerArray> - layerArray(const GeometryContext& gctx, - const LayerVector& layers, - double min, - double max, - BinningType btype = arbitrary, - BinningValue bvalue = binX) const = 0; + virtual std::unique_ptr<const LayerArray> layerArray( + const GeometryContext& gctx, const LayerVector& layers, double min, + double max, BinningType btype = arbitrary, + BinningValue bvalue = binX) const = 0; }; -} // namespace \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Geometry/ILayerBuilder.hpp b/Core/include/Acts/Geometry/ILayerBuilder.hpp index 70cbbd22af220e1e74383143ca68476e97b556f3..23b0d436bfcbf2ae5e014db6a61a9b2e765a6d13 100644 --- a/Core/include/Acts/Geometry/ILayerBuilder.hpp +++ b/Core/include/Acts/Geometry/ILayerBuilder.hpp @@ -19,7 +19,7 @@ namespace Acts { class Layer; -using LayerPtr = std::shared_ptr<const Layer>; +using LayerPtr = std::shared_ptr<const Layer>; using LayerVector = std::vector<LayerPtr>; /// @class ILayerBuilder @@ -28,9 +28,8 @@ using LayerVector = std::vector<LayerPtr>; /// | EC- | Central | EC+ | /// detector setup. /// -class ILayerBuilder -{ -public: +class ILayerBuilder { + public: /// Virtual destructor virtual ~ILayerBuilder() = default; @@ -40,8 +39,8 @@ public: /// which the geometry is built /// /// @return the layers at negative side - virtual const LayerVector - negativeLayers(const GeometryContext& gctx) const = 0; + virtual const LayerVector negativeLayers( + const GeometryContext& gctx) const = 0; /// LayerBuilder interface method /// @@ -49,8 +48,8 @@ public: /// which the geometry is built /// /// @return the layers at the central sector - virtual const LayerVector - centralLayers(const GeometryContext& gctx) const = 0; + virtual const LayerVector centralLayers( + const GeometryContext& gctx) const = 0; /// LayerBuilder interface method /// @@ -58,13 +57,12 @@ public: /// which the geometry is built /// /// @return the layers at positive side - virtual const LayerVector - positiveLayers(const GeometryContext& gctx) const = 0; + virtual const LayerVector positiveLayers( + const GeometryContext& gctx) const = 0; /// Name identification /// @return the string based identification - virtual const std::string& - identification() const = 0; + virtual const std::string& identification() const = 0; }; -} // namespace +} // namespace Acts diff --git a/Core/include/Acts/Geometry/ITrackingGeometryBuilder.hpp b/Core/include/Acts/Geometry/ITrackingGeometryBuilder.hpp index 0557a809d4a28f271bf2b83c9d2c3da1dd147368..624e7ecfd9d5add20b5ece11f111f2c4f53e24f9 100644 --- a/Core/include/Acts/Geometry/ITrackingGeometryBuilder.hpp +++ b/Core/include/Acts/Geometry/ITrackingGeometryBuilder.hpp @@ -28,9 +28,8 @@ class TrackingGeometry; /// The TrackingGeometry is returned as a non-const object in order to recreate /// from conditions callback if necessary. /// -class ITrackingGeometryBuilder -{ -public: +class ITrackingGeometryBuilder { + public: /// Virtual destructor virtual ~ITrackingGeometryBuilder() = default; @@ -39,7 +38,7 @@ public: /// @param gctx ist the geometry context for witch the geometry is built /// /// @return unique pointer to a newly created TrackingGeometry - virtual std::unique_ptr<const TrackingGeometry> - trackingGeometry(const GeometryContext& gctx) const = 0; + virtual std::unique_ptr<const TrackingGeometry> trackingGeometry( + const GeometryContext& gctx) const = 0; }; -} // namespace \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Geometry/ITrackingVolumeArrayCreator.hpp b/Core/include/Acts/Geometry/ITrackingVolumeArrayCreator.hpp index b838817d24470cc9e69bf88d8e7ff9ebb98b5b34..191ad41806024414d8563698854b0e6968fda660 100644 --- a/Core/include/Acts/Geometry/ITrackingVolumeArrayCreator.hpp +++ b/Core/include/Acts/Geometry/ITrackingVolumeArrayCreator.hpp @@ -22,7 +22,7 @@ namespace Acts { class TrackingVolume; /// A std::shared_ptr to a tracking volume -using TrackingVolumePtr = std::shared_ptr<const TrackingVolume>; +using TrackingVolumePtr = std::shared_ptr<const TrackingVolume>; using MutableTrackingVolumePtr = std::shared_ptr<TrackingVolume>; /// A BinnedArray of a std::shared_tr to a TrackingVolume @@ -42,9 +42,8 @@ using TrackingVolumeVector = std::vector<TrackingVolumePtr>; /// /// Arrays for glueing and confinement are often the same, /// therefore the newly created TrackingVolumeArray is done by a shared_ptr -class ITrackingVolumeArrayCreator -{ -public: +class ITrackingVolumeArrayCreator { + public: /// Virtual destructor virtual ~ITrackingVolumeArrayCreator() = default; @@ -56,9 +55,8 @@ public: /// @param bVal is the binning value for the volume binning /// /// @return sahred pointer to a new TrackingVolumeArray - virtual std::shared_ptr<const TrackingVolumeArray> - trackingVolumeArray(const GeometryContext& gctx, - const TrackingVolumeVector& vols, - BinningValue bVal) const = 0; + virtual std::shared_ptr<const TrackingVolumeArray> trackingVolumeArray( + const GeometryContext& gctx, const TrackingVolumeVector& vols, + BinningValue bVal) const = 0; }; -} // namespace \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Geometry/ITrackingVolumeBuilder.hpp b/Core/include/Acts/Geometry/ITrackingVolumeBuilder.hpp index dbfb23b43797d641e8e1c74ac57eb2c7088e7758..df4bd5117a1832afa4573420af2572b9923dce38 100644 --- a/Core/include/Acts/Geometry/ITrackingVolumeBuilder.hpp +++ b/Core/include/Acts/Geometry/ITrackingVolumeBuilder.hpp @@ -22,11 +22,11 @@ class VolumeBounds; class TrackingVolume; class Layer; class Volume; -using TrackingVolumePtr = std::shared_ptr<const TrackingVolume>; +using TrackingVolumePtr = std::shared_ptr<const TrackingVolume>; using MutableTrackingVolumePtr = std::shared_ptr<TrackingVolume>; -using VolumeBoundsPtr = std::shared_ptr<const VolumeBounds>; -using LayerPtr = std::shared_ptr<const Layer>; -using LayerVector = std::vector<LayerPtr>; +using VolumeBoundsPtr = std::shared_ptr<const VolumeBounds>; +using LayerPtr = std::shared_ptr<const Layer>; +using LayerVector = std::vector<LayerPtr>; /// @class ITrackingVolumeBuilder /// /// Interface class ITrackingVolumeBuilders @@ -39,9 +39,8 @@ using LayerVector = std::vector<LayerPtr>; /// If a VolumeBounds object is given this defines the maximum extent. /// -class ITrackingVolumeBuilder -{ -public: +class ITrackingVolumeBuilder { + public: /// Virtual destructor virtual ~ITrackingVolumeBuilder() = default; @@ -52,10 +51,9 @@ public: /// @param outsideBounds is an (optional) outside confinement /// /// @return shared pointer to a newly created TrackingVolume - virtual MutableTrackingVolumePtr - trackingVolume(const GeometryContext& gctx, - TrackingVolumePtr insideVolume = nullptr, - VolumeBoundsPtr outsideBounds = nullptr) const = 0; + virtual MutableTrackingVolumePtr trackingVolume( + const GeometryContext& gctx, TrackingVolumePtr insideVolume = nullptr, + VolumeBoundsPtr outsideBounds = nullptr) const = 0; }; -} // namespace \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Geometry/ITrackingVolumeHelper.hpp b/Core/include/Acts/Geometry/ITrackingVolumeHelper.hpp index 6179cfac052e39ac3dc48aa7154438d274658f96..1d94d366cf9e782091eacb84ca912f8eec1b2cb2 100644 --- a/Core/include/Acts/Geometry/ITrackingVolumeHelper.hpp +++ b/Core/include/Acts/Geometry/ITrackingVolumeHelper.hpp @@ -25,12 +25,12 @@ class TrackingVolume; class VolumeBounds; class IVolumeMaterial; -using LayerPtr = std::shared_ptr<const Layer>; -using TrackingVolumePtr = std::shared_ptr<const TrackingVolume>; +using LayerPtr = std::shared_ptr<const Layer>; +using TrackingVolumePtr = std::shared_ptr<const TrackingVolume>; using MutableTrackingVolumePtr = std::shared_ptr<TrackingVolume>; -using VolumeBoundsPtr = std::shared_ptr<const VolumeBounds>; +using VolumeBoundsPtr = std::shared_ptr<const VolumeBounds>; -using LayerVector = std::vector<LayerPtr>; +using LayerVector = std::vector<LayerPtr>; using TrackingVolumeVector = std::vector<TrackingVolumePtr>; /// @class ITrackingVolumeHelper @@ -43,9 +43,8 @@ using TrackingVolumeVector = std::vector<TrackingVolumePtr>; /// /// TrackingVolumes only exist as std::shared_ptr /// -class ITrackingVolumeHelper -{ -public: +class ITrackingVolumeHelper { + public: /// Virtual destructor virtual ~ITrackingVolumeHelper() = default; @@ -62,14 +61,13 @@ public: /// @param btype (optional) BinningType - arbitrary(default) or equidistant /// /// @return shared pointer to a new TrackingVolume - virtual MutableTrackingVolumePtr - createTrackingVolume(const GeometryContext& gctx, - const LayerVector& layers, - std::shared_ptr<const IVolumeMaterial> volumeMaterial, - VolumeBoundsPtr volumeBounds, - std::shared_ptr<const Transform3D> transform = nullptr, - const std::string& volumeName = "UndefinedVolume", - BinningType btype = arbitrary) const = 0; + virtual MutableTrackingVolumePtr createTrackingVolume( + const GeometryContext& gctx, const LayerVector& layers, + std::shared_ptr<const IVolumeMaterial> volumeMaterial, + VolumeBoundsPtr volumeBounds, + std::shared_ptr<const Transform3D> transform = nullptr, + const std::string& volumeName = "UndefinedVolume", + BinningType btype = arbitrary) const = 0; /// Create a TrackingVolume* from a set of layers and (optional) parameters /// @@ -84,16 +82,12 @@ public: /// @param btype (optional) BinningType - arbitrary(default) or equidistant /// /// @return shared pointer to a new TrackingVolume - virtual MutableTrackingVolumePtr - createTrackingVolume(const GeometryContext& gctx, - const LayerVector& layers, - std::shared_ptr<const IVolumeMaterial> volumeMaterial, - double loc0Min, - double loc0Max, - double loc1Min, - double loc1Max, - const std::string& volumeName = "UndefinedVolume", - BinningType btype = arbitrary) const = 0; + virtual MutableTrackingVolumePtr createTrackingVolume( + const GeometryContext& gctx, const LayerVector& layers, + std::shared_ptr<const IVolumeMaterial> volumeMaterial, double loc0Min, + double loc0Max, double loc1Min, double loc1Max, + const std::string& volumeName = "UndefinedVolume", + BinningType btype = arbitrary) const = 0; /// Create a gap volume from dimensions and /// @@ -106,17 +100,12 @@ public: /// @param volumeName volume name to be given /// /// @return shared pointer to a new TrackingVolume - virtual MutableTrackingVolumePtr - createGapTrackingVolume(const GeometryContext& gctx, - std::shared_ptr<const IVolumeMaterial> volumeMaterial, - double loc0Min, - double loc0Max, - double loc1Min, - double loc1Max, - unsigned int materialLayers, - bool cylinder = true, - const std::string& volumeName - = "UndefinedVolume") const = 0; + virtual MutableTrackingVolumePtr createGapTrackingVolume( + const GeometryContext& gctx, + std::shared_ptr<const IVolumeMaterial> volumeMaterial, double loc0Min, + double loc0Max, double loc1Min, double loc1Max, + unsigned int materialLayers, bool cylinder = true, + const std::string& volumeName = "UndefinedVolume") const = 0; /// Create a gap volume from dimensions and /// @@ -129,17 +118,13 @@ public: /// @param btype (optional) BinningType - arbitrary(default) or equidistant /// /// @return shared pointer to a new TrackingVolume - virtual MutableTrackingVolumePtr - createGapTrackingVolume(const GeometryContext& gctx, - std::shared_ptr<const IVolumeMaterial> volumeMaterial, - double loc0Min, - double loc0Max, - double loc1Min, - double loc1Max, - const std::vector<double>& layerPositions, - bool cylinder = true, - const std::string& volumeName = "UndefinedVolume", - BinningType btype = arbitrary) const = 0; + virtual MutableTrackingVolumePtr createGapTrackingVolume( + const GeometryContext& gctx, + std::shared_ptr<const IVolumeMaterial> volumeMaterial, double loc0Min, + double loc0Max, double loc1Min, double loc1Max, + const std::vector<double>& layerPositions, bool cylinder = true, + const std::string& volumeName = "UndefinedVolume", + BinningType btype = arbitrary) const = 0; /// Create a one level higher TrackingVolue /// @@ -147,9 +132,9 @@ public: /// @param volumes the volumes to be contained /// /// @return shared pointer to a new TrackingVolume - virtual MutableTrackingVolumePtr - createContainerTrackingVolume(const GeometryContext& gctx, - const TrackingVolumeVector& volumes) const = 0; + virtual MutableTrackingVolumePtr createContainerTrackingVolume( + const GeometryContext& gctx, + const TrackingVolumeVector& volumes) const = 0; }; -} // namespace \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Geometry/Layer.hpp b/Core/include/Acts/Geometry/Layer.hpp index 0b65f8bebf0ef5d089bba43d8a1f148d7d912171..3fbda82698ce34818390422c6f647bf0877641b3 100644 --- a/Core/include/Acts/Geometry/Layer.hpp +++ b/Core/include/Acts/Geometry/Layer.hpp @@ -43,9 +43,9 @@ using SurfaceIntersection = ObjectIntersection<Surface>; // master typedef class Layer; -using LayerPtr = std::shared_ptr<const Layer>; +using LayerPtr = std::shared_ptr<const Layer>; using MutableLayerPtr = std::shared_ptr<Layer>; -using NextLayers = std::pair<const Layer*, const Layer*>; +using NextLayers = std::pair<const Layer*, const Layer*>; /// @enum LayerType /// @@ -82,13 +82,12 @@ enum LayerType { navigation = -1, passive = 0, active = 1 }; /// - m_ssSensitiveSurfaces -> can or not exist (0,1), can have material (2) /// - m_ssApproachSurfaces -> can or not exist (0,1) cam have material (2) /// -class Layer : public virtual GeometryObject -{ +class Layer : public virtual GeometryObject { /// Declare the TrackingVolume as a friend, to be able to register previous, /// next and set the enclosing TrackingVolume friend class TrackingVolume; -public: + public: /// Default Constructor - deleted Layer() = delete; @@ -101,33 +100,25 @@ public: /// Assignment operator - forbidden, layer assignment must not be ambiguous /// /// @param lay is the source layer for assignment - Layer& - operator=(const Layer&) - = delete; + Layer& operator=(const Layer&) = delete; /// Return the entire SurfaceArray, returns a nullptr if no SurfaceArray - const SurfaceArray* - surfaceArray() const; + const SurfaceArray* surfaceArray() const; /// Non-const version - SurfaceArray* - surfaceArray(); + SurfaceArray* surfaceArray(); /// Transforms the layer into a Surface representation for extrapolation /// @note the layer can be hosting many surfaces, but this is the global /// one to which one can extrapolate - virtual const Surface& - surfaceRepresentation() const = 0; + virtual const Surface& surfaceRepresentation() const = 0; // Non-const version - virtual Surface& - surfaceRepresentation() - = 0; + virtual Surface& surfaceRepresentation() = 0; /// Return the Thickness of the Layer /// this is by definition along the normal vector of the surfaceRepresentation - double - thickness() const; + double thickness() const; /// templated onLayer() method /// @@ -137,10 +128,8 @@ public: /// /// @return boolean that indicates success of the operation template <typename parameters_t> - bool - onLayer(const GeometryContext& gctx, - const parameters_t& pars, - const BoundaryCheck& bcheck = true) const; + bool onLayer(const GeometryContext& gctx, const parameters_t& pars, + const BoundaryCheck& bcheck = true) const; /// geometrical isOnLayer() method /// @@ -151,18 +140,14 @@ public: /// @param bcheck is the boundary check directive /// /// @return boolean that indicates success of the operation - virtual bool - isOnLayer(const GeometryContext& gctx, - const Vector3D& gp, - const BoundaryCheck& bcheck = true) const; + virtual bool isOnLayer(const GeometryContext& gctx, const Vector3D& gp, + const BoundaryCheck& bcheck = true) const; /// Return method for the approach descriptor, can be nullptr - const ApproachDescriptor* - approachDescriptor() const; + const ApproachDescriptor* approachDescriptor() const; /// Non-const version of the approach descriptor - ApproachDescriptor* - approachDescriptor(); + ApproachDescriptor* approachDescriptor(); /// Accept layer according to the following collection directives /// @@ -170,11 +155,8 @@ public: /// /// @return a boolean whether the layer is accepted for processing template <typename options_t> - bool - resolve(const options_t& options) const - { - return resolve(options.resolveSensitive, - options.resolveMaterial, + bool resolve(const options_t& options) const { + return resolve(options.resolveSensitive, options.resolveMaterial, options.resolvePassive); } @@ -185,10 +167,8 @@ public: /// @param resolvePassive is the prescription to find all passive surfaces /// /// @return a boolean whether the layer is accepted for processing - virtual bool - resolve(bool resolveSensitive, - bool resolveMaterial, - bool resolvePassive) const; + virtual bool resolve(bool resolveSensitive, bool resolveMaterial, + bool resolvePassive) const; /// @brief Decompose Layer into (compatible) surfaces /// @@ -204,12 +184,10 @@ public: /// @return list of intersection of surfaces on the layer template <typename options_t, typename corrector_t = VoidIntersectionCorrector> - std::vector<SurfaceIntersection> - compatibleSurfaces(const GeometryContext& gctx, - const Vector3D& position, - const Vector3D& momentum, - const options_t& options, - const corrector_t& corrfnc = corrector_t()) const; + std::vector<SurfaceIntersection> compatibleSurfaces( + const GeometryContext& gctx, const Vector3D& position, + const Vector3D& momentum, const options_t& options, + const corrector_t& corrfnc = corrector_t()) const; /// @brief Decompose Layer into (compatible) surfaces /// @@ -223,14 +201,12 @@ public: /// @tparam corrector_t is an (optional) intersection corrector /// /// @return list of intersection of surfaces on the layer - template <typename parameters_t, - typename options_t, + template <typename parameters_t, typename options_t, typename corrector_t = VoidIntersectionCorrector> - std::vector<SurfaceIntersection> - compatibleSurfaces(const GeometryContext& gctx, - const parameters_t& parameters, - const options_t& options, - const corrector_t& corrfnc = corrector_t()) const; + std::vector<SurfaceIntersection> compatibleSurfaces( + const GeometryContext& gctx, const parameters_t& parameters, + const options_t& options, + const corrector_t& corrfnc = corrector_t()) const; /// Surface seen on approach /// @@ -247,14 +223,12 @@ public: /// @tparam corrector_t is an (optional) intersection corrector /// /// @return the Surface intersection of the approach surface - template <typename parameters_t, - typename options_t, + template <typename parameters_t, typename options_t, typename corrector_t = VoidIntersectionCorrector> - const SurfaceIntersection - surfaceOnApproach(const GeometryContext& gctx, - const parameters_t& parameters, - const options_t& options, - const corrector_t& corrfnc = corrector_t()) const; + const SurfaceIntersection surfaceOnApproach( + const GeometryContext& gctx, const parameters_t& parameters, + const options_t& options, + const corrector_t& corrfnc = corrector_t()) const; /// Surface seen on approach /// @@ -273,12 +247,10 @@ public: /// @return the Surface intersection of the approach surface template <typename options_t, typename corrector_t = VoidIntersectionCorrector> - const SurfaceIntersection - surfaceOnApproach(const GeometryContext& gctx, - const Vector3D& position, - const Vector3D& direction, - const options_t& options, - const corrector_t& corrfnc = corrector_t()) const; + const SurfaceIntersection surfaceOnApproach( + const GeometryContext& gctx, const Vector3D& position, + const Vector3D& direction, const options_t& options, + const corrector_t& corrfnc = corrector_t()) const; /// Fast navigation to next layer /// @@ -287,38 +259,32 @@ public: /// @param mom is the direction for the search /// /// @return the pointer to the next layer - const Layer* - nextLayer(const GeometryContext& gctx, - const Vector3D& gp, - const Vector3D& mom) const; + const Layer* nextLayer(const GeometryContext& gctx, const Vector3D& gp, + const Vector3D& mom) const; /// get the confining TrackingVolume /// /// @return the pointer to the enclosing volume - const TrackingVolume* - trackingVolume() const; + const TrackingVolume* trackingVolume() const; /// return the abstract volume that represents the layer /// /// @return the representing volume of the layer - const AbstractVolume* - representingVolume() const; + const AbstractVolume* representingVolume() const; /// return the LayerType - LayerType - layerType() const; + LayerType layerType() const; -protected: + protected: /// Constructor with pointer to SurfaceArray (passing ownership) /// /// @param surfaceArray is the array of sensitive surfaces /// @param thickness is the normal thickness of the Layer /// @param ades oapproach descriptor /// @param laytyp is the layer type if active or passive - Layer(std::unique_ptr<SurfaceArray> surfaceArray, - double thickness = 0., - std::unique_ptr<ApproachDescriptor> ades = nullptr, - LayerType laytyp = passive); + Layer(std::unique_ptr<SurfaceArray> surfaceArray, double thickness = 0., + std::unique_ptr<ApproachDescriptor> ades = nullptr, + LayerType laytyp = passive); /// private method to set enclosing TrackingVolume, called by friend class /// only @@ -329,8 +295,7 @@ protected: /// - SubSurface array boundaries are NOT resized /// /// @param tvol is the tracking volume the layer is confined - void - encloseTrackingVolume(const TrackingVolume& tvol); + void encloseTrackingVolume(const TrackingVolume& tvol); /// the previous Layer according to BinGenUtils NextLayers m_nextLayers; @@ -368,10 +333,10 @@ protected: /// sub structure indication int m_ssRepresentingSurface = 0; - int m_ssSensitiveSurfaces = 0; - int m_ssApproachSurfaces = 0; + int m_ssSensitiveSurfaces = 0; + int m_ssApproachSurfaces = 0; -private: + private: /// Private helper method to close the geometry /// - it will assign material to the surfaces if needed /// - it will set the layer geometry ID for a unique identification @@ -381,15 +346,14 @@ private: /// optionally the surface material to where they belong /// @param layerID is the geometry id of the volume /// as calculated by the TrackingGeometry - void - closeGeometry(const IMaterialDecorator* materialDecorator, - const GeometryID& layerID); + void closeGeometry(const IMaterialDecorator* materialDecorator, + const GeometryID& layerID); }; /// Layers are constructedd with shared_ptr factories, hence the layer array is /// describes as: using LayerArray = BinnedArray<LayerPtr>; -} // namespace +} // namespace Acts #include "Acts/Geometry/detail/Layer.ipp" \ No newline at end of file diff --git a/Core/include/Acts/Geometry/LayerArrayCreator.hpp b/Core/include/Acts/Geometry/LayerArrayCreator.hpp index 696f8e16ce98ab2e3fc5d77c13abe18259f27505..6835c7c1842b090cffe71724d0ec283e3d00ac00 100644 --- a/Core/include/Acts/Geometry/LayerArrayCreator.hpp +++ b/Core/include/Acts/Geometry/LayerArrayCreator.hpp @@ -14,9 +14,9 @@ #ifndef ACTS_TOOLS_TAKESMALLERBIGGER #define ACTS_TOOLS_TAKESMALLERBIGGER #define takeSmaller(current, test) current = current < test ? current : test -#define takeBigger(current, test) current = current > test ? current : test -#define takeSmallerBigger(cSmallest, cBiggest, test) \ - takeSmaller(cSmallest, test); \ +#define takeBigger(current, test) current = current > test ? current : test +#define takeSmallerBigger(cSmallest, cBiggest, test) \ + takeSmaller(cSmallest, test); \ takeBigger(cBiggest, test) #endif @@ -41,23 +41,18 @@ class Layer; /// Navigation of the Extrapolation process. /// -class LayerArrayCreator : public ILayerArrayCreator -{ -public: +class LayerArrayCreator : public ILayerArrayCreator { + public: /// @brief This struct stores the configuration of the tracking geometry - struct Config - { - }; + struct Config {}; /// Constructor /// /// @param logger logging instance LayerArrayCreator(const Config& /*cfg*/, - std::unique_ptr<const Logger> logger - = getDefaultLogger("LayerArrayCreator", Logging::INFO)) - : m_logger(std::move(logger)) - { - } + std::unique_ptr<const Logger> logger = + getDefaultLogger("LayerArrayCreator", Logging::INFO)) + : m_logger(std::move(logger)) {} /// Destructor ~LayerArrayCreator() override = default; @@ -72,28 +67,19 @@ public: /// @param bValue is the value in which the binning should be done /// /// @return unique pointer to a newly created LayerArray - std::unique_ptr<const LayerArray> - layerArray(const GeometryContext& gctx, - const LayerVector& layersInput, - double min, - double max, - BinningType bType = arbitrary, - BinningValue bValue = binX) const override; + std::unique_ptr<const LayerArray> layerArray( + const GeometryContext& gctx, const LayerVector& layersInput, double min, + double max, BinningType bType = arbitrary, + BinningValue bValue = binX) const override; /// set logging instance - void - setLogger(std::unique_ptr<const Logger> logger) - { + void setLogger(std::unique_ptr<const Logger> logger) { m_logger = std::move(logger); } -private: + private: /// Private access method to the logging instance - const Logger& - logger() const - { - return *m_logger; - } + const Logger& logger() const { return *m_logger; } /// logging instance std::unique_ptr<const Logger> m_logger = nullptr; @@ -105,11 +91,10 @@ private: /// /// @param bValue is the Binning value for the layer array /// @param offset is the sift for the navigation layer - std::shared_ptr<Surface> - createNavigationSurface(const GeometryContext& gctx, - const Layer& layer, - BinningValue bValue, - double offset) const; + std::shared_ptr<Surface> createNavigationSurface(const GeometryContext& gctx, + const Layer& layer, + BinningValue bValue, + double offset) const; }; -} // namespace \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Geometry/LayerCreator.hpp b/Core/include/Acts/Geometry/LayerCreator.hpp index 3557a1e85551058f025d1d4bd167f6b15fffb6f4..7d79f507fcf3dc03948a17fd57cb63072993210d 100644 --- a/Core/include/Acts/Geometry/LayerCreator.hpp +++ b/Core/include/Acts/Geometry/LayerCreator.hpp @@ -23,16 +23,16 @@ #ifndef ACTS_LAYERCREATOR_TAKESMALLERBIGGER #define ACTS_LAYERCREATOR_TAKESMALLERBIGGER #define takeSmaller(current, test) current = current < test ? current : test -#define takeBigger(current, test) current = current > test ? current : test -#define takeSmallerBigger(cSmallest, cBiggest, test) \ - takeSmaller(cSmallest, test); \ +#define takeBigger(current, test) current = current > test ? current : test +#define takeSmallerBigger(cSmallest, cBiggest, test) \ + takeSmaller(cSmallest, test); \ takeBigger(cBiggest, test) #endif namespace Acts { namespace Test { - struct LayerCreatorFixture; +struct LayerCreatorFixture; } class Surface; class Layer; @@ -43,15 +43,13 @@ using MutableLayerPtr = std::shared_ptr<Layer>; /// The LayerCreator is able to build cylinde,r disc layers or plane layers from /// detector elements /// -class LayerCreator -{ -public: +class LayerCreator { + public: friend Acts::Test::LayerCreatorFixture; /// @struct Config /// Configuration for the LayerCreator /// This is the nexted configuration struct for the LayerCreator class - struct Config - { + struct Config { /// surface array helper std::shared_ptr<const SurfaceArrayCreator> surfaceArrayCreator = nullptr; /// cylinder module z tolerance : it counts at same z, if ... @@ -66,9 +64,9 @@ public: /// /// @param lcConfig is the configuration object /// @param logger logging instance - LayerCreator(const Config& lcConfig, - std::unique_ptr<const Logger> logger - = getDefaultLogger("LayerCreator", Logging::INFO)); + LayerCreator(const Config& lcConfig, + std::unique_ptr<const Logger> logger = + getDefaultLogger("LayerCreator", Logging::INFO)); /// Destructor ~LayerCreator() = default; @@ -90,14 +88,12 @@ public: /// be taken used for this layer /// /// @return shared pointer to a newly created layer - MutableLayerPtr - cylinderLayer(const GeometryContext& gctx, - std::vector<std::shared_ptr<const Surface>> surfaces, - size_t binsPhi, - size_t binsZ, - boost::optional<ProtoLayer> _protoLayer = boost::none, - std::shared_ptr<const Transform3D> transform = nullptr, - std::unique_ptr<ApproachDescriptor> ad = nullptr) const; + MutableLayerPtr cylinderLayer( + const GeometryContext& gctx, + std::vector<std::shared_ptr<const Surface>> surfaces, size_t binsPhi, + size_t binsZ, boost::optional<ProtoLayer> _protoLayer = boost::none, + std::shared_ptr<const Transform3D> transform = nullptr, + std::unique_ptr<ApproachDescriptor> ad = nullptr) const; /// returning a cylindrical layer /// @@ -116,14 +112,13 @@ public: /// be taken used for this layer /// /// @return shared pointer to a newly created layer - MutableLayerPtr - cylinderLayer(const GeometryContext& gctx, - std::vector<std::shared_ptr<const Surface>> surfaces, - BinningType bTypePhi, - BinningType bTypeZ, - boost::optional<ProtoLayer> _protoLayer = boost::none, - std::shared_ptr<const Transform3D> transform = nullptr, - std::unique_ptr<ApproachDescriptor> ad = nullptr) const; + MutableLayerPtr cylinderLayer( + const GeometryContext& gctx, + std::vector<std::shared_ptr<const Surface>> surfaces, + BinningType bTypePhi, BinningType bTypeZ, + boost::optional<ProtoLayer> _protoLayer = boost::none, + std::shared_ptr<const Transform3D> transform = nullptr, + std::unique_ptr<ApproachDescriptor> ad = nullptr) const; /// returning a disc layer /// @@ -142,14 +137,12 @@ public: /// be taken used for this layer /// /// @return shared pointer to a newly created layer - MutableLayerPtr - discLayer(const GeometryContext& gctx, - std::vector<std::shared_ptr<const Surface>> surfaces, - size_t binsR, - size_t binsPhi, - boost::optional<ProtoLayer> _protoLayer = boost::none, - std::shared_ptr<const Transform3D> transform = nullptr, - std::unique_ptr<ApproachDescriptor> ad = nullptr) const; + MutableLayerPtr discLayer( + const GeometryContext& gctx, + std::vector<std::shared_ptr<const Surface>> surfaces, size_t binsR, + size_t binsPhi, boost::optional<ProtoLayer> _protoLayer = boost::none, + std::shared_ptr<const Transform3D> transform = nullptr, + std::unique_ptr<ApproachDescriptor> ad = nullptr) const; /// returning a disc layer /// @@ -168,14 +161,13 @@ public: /// be taken used for this layer /// /// @return shared pointer to a newly created layer - MutableLayerPtr - discLayer(const GeometryContext& gctx, - std::vector<std::shared_ptr<const Surface>> surfaces, - BinningType bTypeR, - BinningType bTypePhi, - boost::optional<ProtoLayer> _protoLayer = boost::none, - std::shared_ptr<const Transform3D> transform = nullptr, - std::unique_ptr<ApproachDescriptor> ad = nullptr) const; + MutableLayerPtr discLayer( + const GeometryContext& gctx, + std::vector<std::shared_ptr<const Surface>> surfaces, BinningType bTypeR, + BinningType bTypePhi, + boost::optional<ProtoLayer> _protoLayer = boost::none, + std::shared_ptr<const Transform3D> transform = nullptr, + std::unique_ptr<ApproachDescriptor> ad = nullptr) const; /// returning a plane layer /// @@ -198,60 +190,48 @@ public: /// ApproachDescriptor will be taken used for this layer /// /// @return shared pointer to a newly created layer - MutableLayerPtr - planeLayer(const GeometryContext& gctx, - std::vector<std::shared_ptr<const Surface>> surfaces, - size_t bins1, - size_t bins2, - BinningValue bValue = BinningValue::binX, - boost::optional<ProtoLayer> _protoLayer = boost::none, - std::shared_ptr<const Transform3D> transform = nullptr, - std::unique_ptr<ApproachDescriptor> ad = nullptr) const; + MutableLayerPtr planeLayer( + const GeometryContext& gctx, + std::vector<std::shared_ptr<const Surface>> surfaces, size_t bins1, + size_t bins2, BinningValue bValue = BinningValue::binX, + boost::optional<ProtoLayer> _protoLayer = boost::none, + std::shared_ptr<const Transform3D> transform = nullptr, + std::unique_ptr<ApproachDescriptor> ad = nullptr) const; /// Set the configuration object /// @param lcConfig is the configuration struct - void - setConfiguration(const Config& lcConfig); + void setConfiguration(const Config& lcConfig); /// Access th configuration object - Config - getConfiguration() const; + Config getConfiguration() const; /// set logging instance /// @param newLogger the logger instance - void - setLogger(std::unique_ptr<const Logger> newLogger); + void setLogger(std::unique_ptr<const Logger> newLogger); // associate surfaces contained by this layer to this layer - void - associateSurfacesToLayer(Layer& layer) const; + void associateSurfacesToLayer(Layer& layer) const; -private: + private: /// Validates that all the sensitive surfaces are actually accessible through /// the binning /// /// @param surfGrid is the object grid from the surface array /// @para surfaces is the vector of sensitive surfaces - bool - checkBinning(const GeometryContext& gctx, const SurfaceArray& sArray) const; + bool checkBinning(const GeometryContext& gctx, + const SurfaceArray& sArray) const; /// configuration object Config m_cfg; /// Private acces method to the logger - const Logger& - logger() const - { - return *m_logger; - } + const Logger& logger() const { return *m_logger; } /// logging instance std::unique_ptr<const Logger> m_logger; }; -inline LayerCreator::Config -LayerCreator::getConfiguration() const -{ +inline LayerCreator::Config LayerCreator::getConfiguration() const { return m_cfg; } diff --git a/Core/include/Acts/Geometry/NavigationLayer.hpp b/Core/include/Acts/Geometry/NavigationLayer.hpp index 886f4b7e49fd889a5edb01ba74db4b15a9a7ecdb..d64a872f5c6fdccac4f6a0fd22d7648204bd76e4 100644 --- a/Core/include/Acts/Geometry/NavigationLayer.hpp +++ b/Core/include/Acts/Geometry/NavigationLayer.hpp @@ -29,17 +29,15 @@ class BinUtility; /// Navigation Layers have a surface representation, but should usually never be /// propagated to. -class NavigationLayer : public Layer -{ -public: +class NavigationLayer : public Layer { + public: /// Factory Constructor - the surface representation is given by pointer /// (ownership passed) /// /// @param sRepresentation is the representation for extrapolation /// @param thickness is the thickness for the binning - static LayerPtr - create(std::shared_ptr<const Surface> sRepresentation, double thickness = 0.) - { + static LayerPtr create(std::shared_ptr<const Surface> sRepresentation, + double thickness = 0.) { return LayerPtr(new NavigationLayer(std::move(sRepresentation), thickness)); } @@ -53,8 +51,8 @@ public: /// - as default the center is given, but may be overloaded /// /// @return The return vector can be used for binning in a TrackingVolume - const Vector3D - binningPosition(const GeometryContext& gctx, BinningValue bValue) const final; + const Vector3D binningPosition(const GeometryContext& gctx, + BinningValue bValue) const final; /// Default Constructor - deleted NavigationLayer() = delete; @@ -63,18 +61,14 @@ public: NavigationLayer(const NavigationLayer&) = delete; /// Assignment operator - deleted - NavigationLayer& - operator=(const NavigationLayer&) - = delete; + NavigationLayer& operator=(const NavigationLayer&) = delete; /// Transforms the layer into a Surface representation for extrapolation /// In general, extrapolation to a surface should be avoided - const Surface& - surfaceRepresentation() const final; + const Surface& surfaceRepresentation() const final; // Non-const version - Surface& - surfaceRepresentation() final; + Surface& surfaceRepresentation() final; /// Geometric isOnLayer() method /// using isOnSurface() with Layer specific tolerance @@ -84,10 +78,8 @@ public: /// @param bcheck is the boundary check directive /// /// @return boolean that indicates if the position is on surface - bool - isOnLayer(const GeometryContext& gctx, - const Vector3D& gp, - const BoundaryCheck& bcheck = true) const final; + bool isOnLayer(const GeometryContext& gctx, const Vector3D& gp, + const BoundaryCheck& bcheck = true) const final; /// Accept layer according to the following colelction directives /// @@ -98,12 +90,10 @@ public: /// @note navigation layers are never accepted /// /// @return a boolean whether the layer is accepted for processing - bool - resolve(bool resolveSensitive, - bool resolveMaterial, - bool resolvePassive) const final; + bool resolve(bool resolveSensitive, bool resolveMaterial, + bool resolvePassive) const final; -protected: + protected: /// Private Constructor /// - this is called by the creat(args*) method /// passed spacer layer if needed @@ -111,7 +101,7 @@ protected: /// @param surfaceRepresentation is the surface of the layer /// @param thickness ithe layer thickness NavigationLayer(std::shared_ptr<const Surface> surfaceRepresentation, - double thickness); + double thickness); /// for the navigation Volume the surface /// @@ -121,38 +111,28 @@ protected: std::shared_ptr<const Surface> m_surfaceRepresentation; }; -inline const Surface& -NavigationLayer::surfaceRepresentation() const -{ +inline const Surface& NavigationLayer::surfaceRepresentation() const { return (*m_surfaceRepresentation); } -inline Surface& -NavigationLayer::surfaceRepresentation() -{ +inline Surface& NavigationLayer::surfaceRepresentation() { return *(const_cast<Surface*>(m_surfaceRepresentation.get())); } -inline const Vector3D -NavigationLayer::binningPosition(const GeometryContext& gctx, - BinningValue bValue) const -{ +inline const Vector3D NavigationLayer::binningPosition( + const GeometryContext& gctx, BinningValue bValue) const { return m_surfaceRepresentation->binningPosition(gctx, bValue); } -inline bool -NavigationLayer::isOnLayer(const GeometryContext& gctx, - const Vector3D& gp, - const BoundaryCheck& bcheck) const -{ +inline bool NavigationLayer::isOnLayer(const GeometryContext& gctx, + const Vector3D& gp, + const BoundaryCheck& bcheck) const { return m_surfaceRepresentation->isOnSurface(gctx, gp, s_origin, bcheck); } -inline bool -NavigationLayer::resolve(bool /*resolveSensitive*/, - bool /*resolveMaterial*/, - bool /*reolvePassive*/) const -{ +inline bool NavigationLayer::resolve(bool /*resolveSensitive*/, + bool /*resolveMaterial*/, + bool /*reolvePassive*/) const { return false; } diff --git a/Core/include/Acts/Geometry/PassiveLayerBuilder.hpp b/Core/include/Acts/Geometry/PassiveLayerBuilder.hpp index 2ddf862f70243e9aefcb4ec1da1fabb5eb37ff69..db6686fb6e87dc35d974802e9ed8fde17d4300ec 100644 --- a/Core/include/Acts/Geometry/PassiveLayerBuilder.hpp +++ b/Core/include/Acts/Geometry/PassiveLayerBuilder.hpp @@ -26,14 +26,12 @@ namespace Acts { /// dimensions and material. The specifications of the the layers have to be /// given by the configuration struct. -class PassiveLayerBuilder : public ILayerBuilder -{ -public: +class PassiveLayerBuilder : public ILayerBuilder { + public: /// @struct Config /// Configuration struct for the passive layer builder /// This nested struct is used to configure the layer building - struct Config - { + struct Config { /// string based identification std::string layerIdentification; @@ -56,9 +54,9 @@ public: /// /// @param plConfig is the ocnfiguration struct that steers behavior /// @param logger logging instance - PassiveLayerBuilder(const Config& plConfig, - std::unique_ptr<const Logger> logger - = getDefaultLogger("PassiveLayerBuilder", Logging::INFO)); + PassiveLayerBuilder(const Config& plConfig, + std::unique_ptr<const Logger> logger = getDefaultLogger( + "PassiveLayerBuilder", Logging::INFO)); /// Destructor ~PassiveLayerBuilder() override = default; @@ -69,8 +67,7 @@ public: /// which the geometry is built /// /// @return the layers at negative side - const LayerVector - negativeLayers(const GeometryContext& gctx) const override; + const LayerVector negativeLayers(const GeometryContext& gctx) const override; /// LayerBuilder interface method /// @@ -78,8 +75,7 @@ public: /// which the geometry is built /// /// @return the layers at the central sector - const LayerVector - centralLayers(const GeometryContext& gctx) const override; + const LayerVector centralLayers(const GeometryContext& gctx) const override; /// LayerBuilder interface method /// @@ -87,14 +83,11 @@ public: /// which the geometry is built /// /// @return the layers at positive side - const LayerVector - positiveLayers(const GeometryContext& gctx) const override; + const LayerVector positiveLayers(const GeometryContext& gctx) const override; /// Name identification /// @return the string based identification - const std::string& - identification() const override - { + const std::string& identification() const override { return m_cfg.layerIdentification; } @@ -102,23 +95,20 @@ public: /// /// @param plConfig is a configuration struct /// it overwrites the current configuration - void - setConfiguration(const Config& plConfig); + void setConfiguration(const Config& plConfig); /// Get configuration method - Config - getConfiguration() const; + Config getConfiguration() const; /// Set logging instance /// /// @param newLogger the logger instance - void - setLogger(std::unique_ptr<const Logger> newLogger); + void setLogger(std::unique_ptr<const Logger> newLogger); -protected: + protected: Config m_cfg; //!< configuration -private: + private: /// Helper interface method /// /// @param gctx ist the geometry context under @@ -126,23 +116,17 @@ private: /// @param side is the side of the layer to be built /// /// @return the layers at positive side - const LayerVector - endcapLayers(const GeometryContext& gctx, int side) const; + const LayerVector endcapLayers(const GeometryContext& gctx, int side) const; - const Logger& - logger() const - { - return *m_logger; - } + const Logger& logger() const { return *m_logger; } /// logging instance std::unique_ptr<const Logger> m_logger; }; -inline PassiveLayerBuilder::Config -PassiveLayerBuilder::getConfiguration() const -{ +inline PassiveLayerBuilder::Config PassiveLayerBuilder::getConfiguration() + const { return m_cfg; } -} // namespace \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Geometry/PlaneLayer.hpp b/Core/include/Acts/Geometry/PlaneLayer.hpp index 36a364b1dc40f58aae319c19483484fc3e4e72d0..985bbf4e3b1eb83fd646d56480886b2788be9824 100644 --- a/Core/include/Acts/Geometry/PlaneLayer.hpp +++ b/Core/include/Acts/Geometry/PlaneLayer.hpp @@ -25,9 +25,8 @@ class ApproachDescriptor; /// Class to describe a planar detector layer for tracking, /// it inhertis from both, Layer base class and PlaneSurface class /// -class PlaneLayer : virtual public PlaneSurface, public Layer -{ -public: +class PlaneLayer : virtual public PlaneSurface, public Layer { + public: /// Factory for a shared plane layer /// /// @param transform which places the layer in the global frame @@ -38,20 +37,15 @@ public: /// @param laytyp is the layer type /// /// @return shared pointer to a PlaneLayer - static MutableLayerPtr - create(std::shared_ptr<const Transform3D> transform, - std::shared_ptr<const PlanarBounds> pbounds, - std::unique_ptr<SurfaceArray> surfaceArray = nullptr, - double thickness = 0., - std::unique_ptr<ApproachDescriptor> ad = nullptr, - LayerType laytyp = Acts::active) - { - return MutableLayerPtr(new PlaneLayer(std::move(transform), - pbounds, - std::move(surfaceArray), - thickness, - std::move(ad), - laytyp)); + static MutableLayerPtr create( + std::shared_ptr<const Transform3D> transform, + std::shared_ptr<const PlanarBounds> pbounds, + std::unique_ptr<SurfaceArray> surfaceArray = nullptr, + double thickness = 0., std::unique_ptr<ApproachDescriptor> ad = nullptr, + LayerType laytyp = Acts::active) { + return MutableLayerPtr(new PlaneLayer(std::move(transform), pbounds, + std::move(surfaceArray), thickness, + std::move(ad), laytyp)); } /// Default Constructor - deleted @@ -61,28 +55,23 @@ public: PlaneLayer(const PlaneLayer& pla) = delete; /// Assignment operator for PlaneLayers - deleted - PlaneLayer& - operator=(const PlaneLayer&) - = delete; + PlaneLayer& operator=(const PlaneLayer&) = delete; /// Destructor ~PlaneLayer() override = default; /// Transforms the layer into a Surface representation for extrapolation /// @return returns a reference to a PlaneSurface - const PlaneSurface& - surfaceRepresentation() const override; + const PlaneSurface& surfaceRepresentation() const override; // Non-const version - PlaneSurface& - surfaceRepresentation() override; + PlaneSurface& surfaceRepresentation() override; -private: + private: /// private helper method to build approach surfaces - void - buildApproachDescriptor(); + void buildApproachDescriptor(); -protected: + protected: /// Private constructor for a PlaneLayer is called by create(args*) /// /// @param transform which places the layer in the global frame @@ -93,12 +82,12 @@ protected: /// @param laytyp is the layer type /// /// @return shared pointer to a PlaneLayer - PlaneLayer(std::shared_ptr<const Transform3D> transform, + PlaneLayer(std::shared_ptr<const Transform3D> transform, std::shared_ptr<const PlanarBounds>& pbounds, - std::unique_ptr<SurfaceArray> surfaceArray = nullptr, - double thickness = 0., - std::unique_ptr<ApproachDescriptor> ades = nullptr, - LayerType laytyp = Acts::active); + std::unique_ptr<SurfaceArray> surfaceArray = nullptr, + double thickness = 0., + std::unique_ptr<ApproachDescriptor> ades = nullptr, + LayerType laytyp = Acts::active); /// Private constructor for a PlaneLayer, is called by create(arge* /// @@ -107,4 +96,4 @@ protected: PlaneLayer(const PlaneLayer& pla, const Transform3D& shift); }; -} // namespace \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Geometry/ProtoLayer.hpp b/Core/include/Acts/Geometry/ProtoLayer.hpp index 8bdf238d8bb1b27d56b2d9a4514a8056a6001d28..2274646e51d1a63f994f3d14c1619dd01cbe8211 100644 --- a/Core/include/Acts/Geometry/ProtoLayer.hpp +++ b/Core/include/Acts/Geometry/ProtoLayer.hpp @@ -21,9 +21,8 @@ namespace Acts { /// The struct allows this information to be obtained in a consistent /// way, or be caller provided. -struct ProtoLayer -{ -public: +struct ProtoLayer { + public: double maxX; double minX; @@ -39,10 +38,10 @@ public: double maxPhi; double minPhi; - std::pair<double, double> envX = {0, 0}; - std::pair<double, double> envY = {0, 0}; - std::pair<double, double> envZ = {0, 0}; - std::pair<double, double> envR = {0, 0}; + std::pair<double, double> envX = {0, 0}; + std::pair<double, double> envY = {0, 0}; + std::pair<double, double> envZ = {0, 0}; + std::pair<double, double> envR = {0, 0}; std::pair<double, double> envPhi = {0, 0}; /// Constructor @@ -53,7 +52,7 @@ public: /// /// @param gctx The current geometry context object, e.g. alignment /// @param surfaces The vector of surfaces to consider - ProtoLayer(const GeometryContext& gctx, + ProtoLayer(const GeometryContext& gctx, const std::vector<const Surface*>& surfaces); /// Constructor @@ -64,14 +63,13 @@ public: /// /// @param gctx The current geometry context object, e.g. alignment /// @param surfaces The vector of surfaces to consider - ProtoLayer(const GeometryContext& gctx, + ProtoLayer(const GeometryContext& gctx, const std::vector<std::shared_ptr<const Surface>>& surfaces); // normal empty constructor ProtoLayer() = default; - std::ostream& - toStream(std::ostream& sl) const; + std::ostream& toStream(std::ostream& sl) const; /// Calculates the closest radial distance of a line /// @@ -79,16 +77,14 @@ public: /// @param pos2 is the second position on the line /// /// @return is the closest distance - double - radialDistance(const Vector3D& pos1, const Vector3D& pos2) const; + double radialDistance(const Vector3D& pos1, const Vector3D& pos2) const; -private: + private: /// Helper method which performs the actual min/max calculation /// /// @param gctx The current geometry context object, e.g. alignment /// @param surfaces The surfaces to build this protolayer out of - void - measure(const GeometryContext& gctx, - const std::vector<const Surface*>& surfaces); + void measure(const GeometryContext& gctx, + const std::vector<const Surface*>& surfaces); }; } // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Geometry/SurfaceArrayCreator.hpp b/Core/include/Acts/Geometry/SurfaceArrayCreator.hpp index 44d2785c6731453f3292970f09fd7ff023658550..d4edad8ba9c50876d156bfb5e65ea07ddc0118d0 100644 --- a/Core/include/Acts/Geometry/SurfaceArrayCreator.hpp +++ b/Core/include/Acts/Geometry/SurfaceArrayCreator.hpp @@ -25,13 +25,11 @@ namespace Acts { namespace Test { - struct SurfaceArrayCreatorFixture; +struct SurfaceArrayCreatorFixture; } -using SurfaceMatcher = std::function<bool(const GeometryContext& gctx, - BinningValue, - const Surface*, - const Surface*)>; +using SurfaceMatcher = std::function<bool( + const GeometryContext& gctx, BinningValue, const Surface*, const Surface*)>; using SurfaceVector = std::vector<const Surface*>; using SurfaceMatrix = std::vector<SurfaceVector>; @@ -44,40 +42,35 @@ using V3Matrix = std::vector<V3Vector>; /// It is designed create sub surface arrays to be ordered on Surfaces /// /// @todo write more documentation on how this is done -class SurfaceArrayCreator -{ -public: +class SurfaceArrayCreator { + public: friend Acts::Test::SurfaceArrayCreatorFixture; friend Acts::SurfaceArray; - struct ProtoAxis - { - BinningType bType; - BinningValue bValue; - size_t nBins; - double min; - double max; + struct ProtoAxis { + BinningType bType; + BinningValue bValue; + size_t nBins; + double min; + double max; std::vector<double> binEdges; - size_t - getBin(double x) const - { + size_t getBin(double x) const { if (binEdges.empty()) { // equidistant double w = (max - min) / nBins; return std::floor((x - min) / w); } else { // variable - const auto it - = std::upper_bound(std::begin(binEdges), std::end(binEdges), x); + const auto it = + std::upper_bound(std::begin(binEdges), std::end(binEdges), x); return std::distance(std::begin(binEdges), it) - 1; } } }; // Configuration struct - struct Config - { + struct Config { /// Type-erased function which determines whether two surfaces are supposed /// to be considered equivalent in terms of the binning SurfaceMatcher surfaceMatcher = SurfaceArrayCreator::isSurfaceEquivalent; @@ -91,21 +84,17 @@ public: /// Constructor with default config /// /// @param logger logging instance - SurfaceArrayCreator(std::unique_ptr<const Logger> logger - = getDefaultLogger("SurfaceArrayCreator", Logging::INFO)) - : m_cfg(Config()), m_logger(std::move(logger)) - { - } + SurfaceArrayCreator(std::unique_ptr<const Logger> logger = getDefaultLogger( + "SurfaceArrayCreator", Logging::INFO)) + : m_cfg(Config()), m_logger(std::move(logger)) {} /// Constructor with explicit config /// /// @param cfg Explicit config struct /// @param logger logging instance - SurfaceArrayCreator(const Config& cfg, - std::unique_ptr<const Logger> logger - = getDefaultLogger("SurfaceArrayCreator", Logging::INFO)) - : m_cfg(cfg), m_logger(std::move(logger)) - { - } + SurfaceArrayCreator(const Config& cfg, + std::unique_ptr<const Logger> logger = getDefaultLogger( + "SurfaceArrayCreator", Logging::INFO)) + : m_cfg(cfg), m_logger(std::move(logger)) {} /// Destructor virtual ~SurfaceArrayCreator() = default; @@ -126,15 +115,11 @@ public: /// @param transform is the (optional) additional transform applied /// /// @return a unique pointer to a new SurfaceArray - std::unique_ptr<SurfaceArray> - surfaceArrayOnCylinder(const GeometryContext& gctx, - std::vector<std::shared_ptr<const Surface>> surfaces, - size_t binsPhi, - size_t binsZ, - boost::optional<ProtoLayer> protoLayerOpt - = boost::none, - const std::shared_ptr<const Transform3D>& transformOpt - = nullptr) const; + std::unique_ptr<SurfaceArray> surfaceArrayOnCylinder( + const GeometryContext& gctx, + std::vector<std::shared_ptr<const Surface>> surfaces, size_t binsPhi, + size_t binsZ, boost::optional<ProtoLayer> protoLayerOpt = boost::none, + const std::shared_ptr<const Transform3D>& transformOpt = nullptr) const; /// SurfaceArrayCreator interface method /// @@ -153,15 +138,12 @@ public: /// @param transform is the (optional) additional transform applied /// /// @return a unique pointer a new SurfaceArray - std::unique_ptr<Acts::SurfaceArray> - surfaceArrayOnCylinder(const GeometryContext& gctx, - std::vector<std::shared_ptr<const Surface>> surfaces, - BinningType bTypePhi = equidistant, - BinningType bTypeZ = equidistant, - boost::optional<ProtoLayer> protoLayerOpt - = boost::none, - const std::shared_ptr<const Transform3D>& transformOpt - = nullptr) const; + std::unique_ptr<Acts::SurfaceArray> surfaceArrayOnCylinder( + const GeometryContext& gctx, + std::vector<std::shared_ptr<const Surface>> surfaces, + BinningType bTypePhi = equidistant, BinningType bTypeZ = equidistant, + boost::optional<ProtoLayer> protoLayerOpt = boost::none, + const std::shared_ptr<const Transform3D>& transformOpt = nullptr) const; /// SurfaceArrayCreator interface method /// - create an array on a disc, binned in r, phi when extremas and @@ -179,14 +161,11 @@ public: /// @param transformOpt is the (optional) additional transform applied /// /// @return a unique pointer a new SurfaceArray - std::unique_ptr<SurfaceArray> - surfaceArrayOnDisc(const GeometryContext& gctx, - std::vector<std::shared_ptr<const Surface>> surfaces, - size_t binsR, - size_t binsPhi, - boost::optional<ProtoLayer> protoLayerOpt = boost::none, - const std::shared_ptr<const Transform3D>& transformOpt - = nullptr) const; + std::unique_ptr<SurfaceArray> surfaceArrayOnDisc( + const GeometryContext& gctx, + std::vector<std::shared_ptr<const Surface>> surfaces, size_t binsR, + size_t binsPhi, boost::optional<ProtoLayer> protoLayerOpt = boost::none, + const std::shared_ptr<const Transform3D>& transformOpt = nullptr) const; /// SurfaceArrayCreator interface method /// @@ -208,14 +187,12 @@ public: /// @note If there is more than on R-Ring, number of phi bins /// will be set to lowest number of surfaces of any R-ring. /// This ignores bTypePhi and produces equidistant binning in phi - std::unique_ptr<Acts::SurfaceArray> - surfaceArrayOnDisc(const GeometryContext& gctx, - std::vector<std::shared_ptr<const Surface>> surfaces, - BinningType bTypeR, - BinningType bTypePhi, - boost::optional<ProtoLayer> protoLayerOpt = boost::none, - const std::shared_ptr<const Transform3D>& transformOpt - = nullptr) const; + std::unique_ptr<Acts::SurfaceArray> surfaceArrayOnDisc( + const GeometryContext& gctx, + std::vector<std::shared_ptr<const Surface>> surfaces, BinningType bTypeR, + BinningType bTypePhi, + boost::optional<ProtoLayer> protoLayerOpt = boost::none, + const std::shared_ptr<const Transform3D>& transformOpt = nullptr) const; /// SurfaceArrayCreator interface method /// - create an array on a plane @@ -237,15 +214,12 @@ public: /// @param [in] transformOpt is the (optional) additional transform applied /// /// @return a unique pointer a new SurfaceArray - std::unique_ptr<SurfaceArray> - surfaceArrayOnPlane(const GeometryContext& gctx, - std::vector<std::shared_ptr<const Surface>> surfaces, - size_t bins1, - size_t bins2, - BinningValue bValue = BinningValue::binX, - boost::optional<ProtoLayer> protoLayerOpt = boost::none, - const std::shared_ptr<const Transform3D>& transformOpt - = nullptr) const; + std::unique_ptr<SurfaceArray> surfaceArrayOnPlane( + const GeometryContext& gctx, + std::vector<std::shared_ptr<const Surface>> surfaces, size_t bins1, + size_t bins2, BinningValue bValue = BinningValue::binX, + boost::optional<ProtoLayer> protoLayerOpt = boost::none, + const std::shared_ptr<const Transform3D>& transformOpt = nullptr) const; /// Static check funtion for surface equivalent /// @@ -253,12 +227,9 @@ public: /// @param bValue the binning value for the binning /// @param a first surface for checking /// @param b second surface for checking - static bool - isSurfaceEquivalent(const GeometryContext& gctx, - BinningValue bValue, - const Surface* a, - const Surface* b) - { + static bool isSurfaceEquivalent(const GeometryContext& gctx, + BinningValue bValue, const Surface* a, + const Surface* b) { using Acts::VectorHelpers::perp; if (bValue == Acts::binPhi) { @@ -280,15 +251,14 @@ public: } if (bValue == Acts::binZ) { - return (std::abs(a->binningPosition(gctx, binR).z() - - b->binningPosition(gctx, binR).z()) - < Acts::units::_um); + return (std::abs(a->binningPosition(gctx, binR).z() - + b->binningPosition(gctx, binR).z()) < Acts::units::_um); } if (bValue == Acts::binR) { - return (std::abs(perp(a->binningPosition(gctx, binR)) - - perp(b->binningPosition(gctx, binR))) - < Acts::units::_um); + return (std::abs(perp(a->binningPosition(gctx, binR)) - + perp(b->binningPosition(gctx, binR))) < + Acts::units::_um); } return false; @@ -296,32 +266,24 @@ public: /// Set logging instance /// @param logger is the logging instance to be set - void - setLogger(std::unique_ptr<const Logger> logger) - { + void setLogger(std::unique_ptr<const Logger> logger) { m_logger = std::move(logger); } -private: + private: /// configuration object Config m_cfg; /// Private access to logger - const Logger& - logger() const - { - return *m_logger; - } + const Logger& logger() const { return *m_logger; } - std::vector<const Surface*> - findKeySurfaces( + std::vector<const Surface*> findKeySurfaces( const std::vector<const Surface*>& surfaces, const std::function<bool(const Surface*, const Surface*)>& equal) const; - size_t - determineBinCount(const GeometryContext& gctx, - const std::vector<const Surface*>& surfaces, - BinningValue bValue) const; + size_t determineBinCount(const GeometryContext& gctx, + const std::vector<const Surface*>& surfaces, + BinningValue bValue) const; /// SurfaceArrayCreator internal method /// Creates a variable @c ProtoAxis from a vector of (unsorted) surfaces with @@ -344,12 +306,10 @@ private: /// @return Instance of @c ProtoAxis containing determined properties /// @note This only creates the @c ProtoAxis, this needs to be turned /// into an actual @c Axis object to be used - ProtoAxis - createVariableAxis(const GeometryContext& gctx, - const std::vector<const Surface*>& surfaces, - BinningValue bValue, - ProtoLayer protoLayer, - Transform3D& transform) const; + ProtoAxis createVariableAxis(const GeometryContext& gctx, + const std::vector<const Surface*>& surfaces, + BinningValue bValue, ProtoLayer protoLayer, + Transform3D& transform) const; /// SurfaceArrayCreator internal method /// Creates a equidistant @c ProtoAxis when the extremas and the bin number @@ -372,13 +332,11 @@ private: /// @return Instance of @c ProtoAxis containing determined properties /// @note This only creates the @c ProtoAxis, this needs to be turned /// into an actual @c Axis object to be used - ProtoAxis - createEquidistantAxis(const GeometryContext& gctx, - const std::vector<const Surface*>& surfaces, - BinningValue bValue, - ProtoLayer protoLayer, - Transform3D& transform, - size_t nBins = 0) const; + ProtoAxis createEquidistantAxis(const GeometryContext& gctx, + const std::vector<const Surface*>& surfaces, + BinningValue bValue, ProtoLayer protoLayer, + Transform3D& transform, + size_t nBins = 0) const; /// SurfaceArrayCreator internal method /// @brief Creates a SurfaceGridLookup instance within an any @@ -392,17 +350,11 @@ private: /// @param localToGlobal transform callable /// @param pAxisA ProtoAxis object for axis A /// @param pAxisB ProtoAxis object for axis B - template <detail::AxisBoundaryType bdtA, - detail::AxisBoundaryType bdtB, - typename F1, - typename F2> + template <detail::AxisBoundaryType bdtA, detail::AxisBoundaryType bdtB, + typename F1, typename F2> static std::unique_ptr<SurfaceArray::ISurfaceGridLookup> - makeSurfaceGridLookup2D(F1 globalToLocal, - F2 localToGlobal, - ProtoAxis pAxisA, - ProtoAxis pAxisB) - { - + makeSurfaceGridLookup2D(F1 globalToLocal, F2 localToGlobal, ProtoAxis pAxisA, + ProtoAxis pAxisB) { using ISGL = SurfaceArray::ISurfaceGridLookup; std::unique_ptr<ISGL> ptr; @@ -469,13 +421,12 @@ private: /// @param [in] gctx the geometry context for this call /// @param sl The @c SurfaceGridLookup /// @param surfaces the surfaces - void - completeBinning(const GeometryContext& gctx, - SurfaceArray::ISurfaceGridLookup& sl, - const std::vector<const Surface*>& surfaces) const - { - ACTS_VERBOSE("Complete binning by filling closest neighbour surfaces into " - "empty bins."); + void completeBinning(const GeometryContext& gctx, + SurfaceArray::ISurfaceGridLookup& sl, + const std::vector<const Surface*>& surfaces) const { + ACTS_VERBOSE( + "Complete binning by filling closest neighbour surfaces into " + "empty bins."); size_t binCompleted = sl.completeBinning(gctx, surfaces); @@ -489,10 +440,9 @@ private: /// @param surface the surface associated with the given vertices /// @param locVertices a vector of the vertices in local coordinates /// @return a vector of the vertices in global coordinates - std::vector<Acts::Vector3D> - makeGlobalVertices(const GeometryContext& gctx, - const Acts::Surface& surface, - const std::vector<Acts::Vector2D>& locVertices) const; + std::vector<Acts::Vector3D> makeGlobalVertices( + const GeometryContext& gctx, const Acts::Surface& surface, + const std::vector<Acts::Vector2D>& locVertices) const; }; } // namespace Acts diff --git a/Core/include/Acts/Geometry/TrackingGeometry.hpp b/Core/include/Acts/Geometry/TrackingGeometry.hpp index d787daa237279b64f6b254ed6a17cb1fd8295850..e7a94ca6f47d2ff7247f88b84fe4ce48a676ee52 100644 --- a/Core/include/Acts/Geometry/TrackingGeometry.hpp +++ b/Core/include/Acts/Geometry/TrackingGeometry.hpp @@ -29,7 +29,7 @@ class Surface; class PerigeeSurface; class IMaterialDecorator; -using TrackingVolumePtr = std::shared_ptr<const TrackingVolume>; +using TrackingVolumePtr = std::shared_ptr<const TrackingVolume>; using MutableTrackingVolumePtr = std::shared_ptr<TrackingVolume>; /// @class TrackingGeometry @@ -40,27 +40,25 @@ using MutableTrackingVolumePtr = std::shared_ptr<TrackingVolume>; /// (respectively, if existing, a global search of an associated Layer or the /// next associated Layer), such as a continous navigation by BoundarySurfaces /// between the confined TrackingVolumes. -class TrackingGeometry -{ +class TrackingGeometry { /// Give the GeometryBuilder friend rights friend class TrackingGeometryBuilder; -public: + public: /// Constructor /// /// @param highestVolume is the world volume /// @param materialDecorator is a dediated decorator that can assign /// surface or volume based material to the TrackingVolume TrackingGeometry(const MutableTrackingVolumePtr& highestVolume, - const IMaterialDecorator* materialDecorator = nullptr); + const IMaterialDecorator* materialDecorator = nullptr); /// Destructor ~TrackingGeometry(); /// Access to the world volume /// @return plain pointer to the world volume - const TrackingVolume* - highestTrackingVolume() const; + const TrackingVolume* highestTrackingVolume() const; /// return the lowest tracking Volume /// @@ -68,16 +66,15 @@ public: /// @param gp is the global position of the call /// /// @return plain pointer to the lowest TrackingVolume - const TrackingVolume* - lowestTrackingVolume(const GeometryContext& gctx, const Vector3D& gp) const; + const TrackingVolume* lowestTrackingVolume(const GeometryContext& gctx, + const Vector3D& gp) const; /// return the lowest tracking Volume /// /// @param name is the name for the volume search /// /// @return plain pointer to the lowest TrackingVolume - const TrackingVolume* - trackingVolume(const std::string& name) const; + const TrackingVolume* trackingVolume(const std::string& name) const; /// Forward the associated Layer information /// @@ -85,14 +82,13 @@ public: /// @param gp is the global position of the call /// /// @return plain pointer to assocaiated layer - const Layer* - associatedLayer(const GeometryContext& gctx, const Vector3D& gp) const; + const Layer* associatedLayer(const GeometryContext& gctx, + const Vector3D& gp) const; /// Register the beam tube /// /// @param beam is the beam line surface - void - registerBeamTube(std::shared_ptr<const PerigeeSurface> beam); + void registerBeamTube(std::shared_ptr<const PerigeeSurface> beam); /// @brief surface representing the beam pipe /// @@ -100,30 +96,28 @@ public: /// /// @return raw pointer to surface representing the beam pipe /// (could be a null pointer) - const Surface* - getBeamline() const; + const Surface* getBeamline() const; /// @brief Visit all sensitive surfaces /// /// @param visitor The callable. Will be called for each sensitive surface /// that is found - void - visitSurfaces(const std::function<void(const Acts::Surface*)>& visitor) const; + void visitSurfaces( + const std::function<void(const Acts::Surface*)>& visitor) const; -private: + private: /// Geometry Builder busineess: the geometry builder has to sign /// /// @param geosit is the volume signature /// @param geotype is the volume navigation type - void - sign(GeometrySignature geosit, GeometryType geotype = Static); + void sign(GeometrySignature geosit, GeometryType geotype = Static); /// The known world - and the beamline - TrackingVolumePtr m_world; + TrackingVolumePtr m_world; std::shared_ptr<const PerigeeSurface> m_beam; /// The Volumes in a map for string based search std::map<std::string, const TrackingVolume*> m_trackingVolumes; }; -} // namespace +} // namespace Acts diff --git a/Core/include/Acts/Geometry/TrackingGeometryBuilder.hpp b/Core/include/Acts/Geometry/TrackingGeometryBuilder.hpp index 07c30ced9a02ed8db2e71ed00b2a4fa4ee1295dc..98a8714ccb02e1cac3a2cc4edd6a03b8dec1a364 100644 --- a/Core/include/Acts/Geometry/TrackingGeometryBuilder.hpp +++ b/Core/include/Acts/Geometry/TrackingGeometryBuilder.hpp @@ -38,18 +38,14 @@ class IMaterialDecorator; /// - attached (e.g. a neighbor detector attaching to the previous one) /// /// The returned volume of each step must be processable by the previous step -class TrackingGeometryBuilder : public ITrackingGeometryBuilder -{ -public: +class TrackingGeometryBuilder : public ITrackingGeometryBuilder { + public: /// @struct Config /// Nested Configuration for the CylinderVolumeBuilder - struct Config - { - + struct Config { /// The list of tracking volume builders std::vector<std::function<std::shared_ptr<TrackingVolume>( - const GeometryContext& gctx, - const TrackingVolumePtr&, + const GeometryContext& gctx, const TrackingVolumePtr&, const VolumeBoundsPtr&)>> trackingVolumeBuilders; @@ -64,10 +60,10 @@ public: /// /// @param [in] cgbConfig is the configuration struct for this builder /// @param [in] logger logging instance - TrackingGeometryBuilder(const Config& cgbConfig, - std::unique_ptr<const Logger> logger - = getDefaultLogger("TrackingGeometryBuilder", - Logging::INFO)); + TrackingGeometryBuilder(const Config& cgbConfig, + std::unique_ptr<const Logger> logger = + getDefaultLogger("TrackingGeometryBuilder", + Logging::INFO)); /// Destructor ~TrackingGeometryBuilder() override = default; @@ -77,44 +73,36 @@ public: /// @param gctx geometry context of that building call /// /// @return a unique pointer to a TrackingGeometry - std::unique_ptr<const TrackingGeometry> - trackingGeometry(const GeometryContext& gctx) const final; + std::unique_ptr<const TrackingGeometry> trackingGeometry( + const GeometryContext& gctx) const final; /// Set configuration method /// /// @param cgbConfig is the new configuration struct - void - setConfiguration(const Config& cgbConfig); + void setConfiguration(const Config& cgbConfig); /// Get configuration method /// @return the current configuration - Config - getConfiguration() const; + Config getConfiguration() const; /// set logging instance /// @param newLogger the new logging instance - void - setLogger(std::unique_ptr<const Logger> newLogger); + void setLogger(std::unique_ptr<const Logger> newLogger); -private: + private: /// Configuration member Config m_cfg; /// Private access method to the logger - const Logger& - logger() const - { - return *m_logger; - } + const Logger& logger() const { return *m_logger; } /// the logging instance std::unique_ptr<const Logger> m_logger; }; inline TrackingGeometryBuilder::Config -TrackingGeometryBuilder::getConfiguration() const -{ +TrackingGeometryBuilder::getConfiguration() const { return m_cfg; } -} // namespace \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Geometry/TrackingVolume.hpp b/Core/include/Acts/Geometry/TrackingVolume.hpp index bdb4d9e92b56c8f4306504fc726f2472ba891000..82dc5b15d50d0984263d7dfdede35d38f39ec53f 100644 --- a/Core/include/Acts/Geometry/TrackingVolume.hpp +++ b/Core/include/Acts/Geometry/TrackingVolume.hpp @@ -33,24 +33,24 @@ class GlueVolumesDescriptor; class VolumeBounds; // master typedefs -using TrackingVolumePtr = std::shared_ptr<const TrackingVolume>; +using TrackingVolumePtr = std::shared_ptr<const TrackingVolume>; using MutableTrackingVolumePtr = std::shared_ptr<TrackingVolume>; -using TrackingVolumeBoundaryPtr - = std::shared_ptr<const BoundarySurfaceT<TrackingVolume>>; +using TrackingVolumeBoundaryPtr = + std::shared_ptr<const BoundarySurfaceT<TrackingVolume>>; // possible contained -using TrackingVolumeArray = BinnedArray<TrackingVolumePtr>; +using TrackingVolumeArray = BinnedArray<TrackingVolumePtr>; using TrackingVolumeVector = std::vector<TrackingVolumePtr>; -using LayerArray = BinnedArray<LayerPtr>; -using LayerVector = std::vector<LayerPtr>; +using LayerArray = BinnedArray<LayerPtr>; +using LayerVector = std::vector<LayerPtr>; // full intersection with Layer using LayerIntersection = FullIntersection<Layer, Surface>; // full intersection with surface -using BoundaryIntersection - = FullIntersection<BoundarySurfaceT<TrackingVolume>, Surface>; +using BoundaryIntersection = + FullIntersection<BoundarySurfaceT<TrackingVolume>, Surface>; /// @class TrackingVolume /// @@ -73,11 +73,10 @@ using BoundaryIntersection /// In addition it is capable of holding a subarray of Layers and /// TrackingVolumes. /// -class TrackingVolume : public Volume -{ +class TrackingVolume : public Volume { friend class TrackingGeometry; -public: + public: /// Destructor ~TrackingVolume() override; @@ -90,17 +89,14 @@ public: /// @param volumeName is a string identifier /// /// @return shared pointer to a new TrackingVolume - static MutableTrackingVolumePtr - create(std::shared_ptr<const Transform3D> htrans, - VolumeBoundsPtr volumeBounds, - const std::shared_ptr<const TrackingVolumeArray>& containedVolumes - = nullptr, - const std::string& volumeName = "undefined") - { - return MutableTrackingVolumePtr(new TrackingVolume(std::move(htrans), - std::move(volumeBounds), - containedVolumes, - volumeName)); + static MutableTrackingVolumePtr create( + std::shared_ptr<const Transform3D> htrans, VolumeBoundsPtr volumeBounds, + const std::shared_ptr<const TrackingVolumeArray>& containedVolumes = + nullptr, + const std::string& volumeName = "undefined") { + return MutableTrackingVolumePtr( + new TrackingVolume(std::move(htrans), std::move(volumeBounds), + containedVolumes, volumeName)); } /// Factory constructor for Tracking Volumes with content @@ -114,21 +110,15 @@ public: /// @param volumeName is a string identifier /// /// @return shared pointer to a new TrackingVolume - static MutableTrackingVolumePtr - create(std::shared_ptr<const Transform3D> htrans, - VolumeBoundsPtr volumeBounds, - std::shared_ptr<const IVolumeMaterial> volumeMaterial, - std::unique_ptr<const LayerArray> containedLayers = nullptr, - std::shared_ptr<const TrackingVolumeArray> containedVolumes = nullptr, - const std::string& volumeName = "undefined") - { - return MutableTrackingVolumePtr( - new TrackingVolume(std::move(htrans), - std::move(volumeBounds), - std::move(volumeMaterial), - std::move(containedLayers), - std::move(containedVolumes), - volumeName)); + static MutableTrackingVolumePtr create( + std::shared_ptr<const Transform3D> htrans, VolumeBoundsPtr volumeBounds, + std::shared_ptr<const IVolumeMaterial> volumeMaterial, + std::unique_ptr<const LayerArray> containedLayers = nullptr, + std::shared_ptr<const TrackingVolumeArray> containedVolumes = nullptr, + const std::string& volumeName = "undefined") { + return MutableTrackingVolumePtr(new TrackingVolume( + std::move(htrans), std::move(volumeBounds), std::move(volumeMaterial), + std::move(containedLayers), std::move(containedVolumes), volumeName)); } /// Return the associated Layer to the global position @@ -137,8 +127,8 @@ public: /// @param gp is the associated global position /// /// @return plain pointer to layer object - const Layer* - associatedLayer(const GeometryContext& gctx, const Vector3D& gp) const; + const Layer* associatedLayer(const GeometryContext& gctx, + const Vector3D& gp) const; /// @brief Resolves the volume into (compatible) Layers /// @@ -155,12 +145,10 @@ public: /// @return vector of compatible intersections with layers template <typename options_t, typename corrector_t = VoidIntersectionCorrector> - std::vector<LayerIntersection> - compatibleLayers(const GeometryContext& gctx, - const Vector3D& position, - const Vector3D& direction, - const options_t& options, - const corrector_t& corrfnc = corrector_t()) const; + std::vector<LayerIntersection> compatibleLayers( + const GeometryContext& gctx, const Vector3D& position, + const Vector3D& direction, const options_t& options, + const corrector_t& corrfnc = corrector_t()) const; /// @brief Resolves the volume into (compatible) Layers /// @@ -175,14 +163,12 @@ public: /// @param corrfnc is the corrector struct / function /// /// @return vector of compatible intersections with layers - template <typename parameters_t, - typename options_t, + template <typename parameters_t, typename options_t, typename corrector_t = VoidIntersectionCorrector> - std::vector<LayerIntersection> - compatibleLayers(const GeometryContext& gctx, - const parameters_t& parameters, - const options_t& options, - const corrector_t& corrfnc = corrector_t()) const; + std::vector<LayerIntersection> compatibleLayers( + const GeometryContext& gctx, const parameters_t& parameters, + const options_t& options, + const corrector_t& corrfnc = corrector_t()) const; /// @brief Returns all boundary surfaces sorted by the user. /// @@ -200,14 +186,12 @@ public: /// @return is the templated boundary intersection template <typename options_t, typename corrector_t = VoidIntersectionCorrector, - typename sorter_t = DefaultBoundaryIntersectionSorter> - std::vector<BoundaryIntersection> - compatibleBoundaries(const GeometryContext& gctx, - const Vector3D& position, - const Vector3D& direction, - const options_t& options, - const corrector_t& corrfnc = corrector_t(), - const sorter_t& sorter = sorter_t()) const; + typename sorter_t = DefaultBoundaryIntersectionSorter> + std::vector<BoundaryIntersection> compatibleBoundaries( + const GeometryContext& gctx, const Vector3D& position, + const Vector3D& direction, const options_t& options, + const corrector_t& corrfnc = corrector_t(), + const sorter_t& sorter = sorter_t()) const; /// @brief Returns all boundary surfaces sorted by the user. /// @@ -223,16 +207,13 @@ public: /// @param sorter Sorter of the boundary surfaces /// /// @return is the templated boundary intersection - template <typename parameters_t, - typename options_t, + template <typename parameters_t, typename options_t, typename corrector_t = VoidIntersectionCorrector, - typename sorter_t = DefaultBoundaryIntersectionSorter> - std::vector<BoundaryIntersection> - compatibleBoundaries(const GeometryContext& gctx, - const parameters_t& parameters, - const options_t& options, - const corrector_t& corrfnc = corrector_t(), - const sorter_t& sorter = sorter_t()) const; + typename sorter_t = DefaultBoundaryIntersectionSorter> + std::vector<BoundaryIntersection> compatibleBoundaries( + const GeometryContext& gctx, const parameters_t& parameters, + const options_t& options, const corrector_t& corrfnc = corrector_t(), + const sorter_t& sorter = sorter_t()) const; /// Return the associated sub Volume, returns THIS if no subVolume exists /// @@ -240,17 +221,15 @@ public: /// @param gp is the global position associated with that search /// /// @return plain pointer to associated with the position - const TrackingVolume* - lowestTrackingVolume(const GeometryContext& gctx, const Vector3D& gp) const; + const TrackingVolume* lowestTrackingVolume(const GeometryContext& gctx, + const Vector3D& gp) const; /// Return the confined static layer array - if it exists /// @return the BinnedArray of static layers if exists - const LayerArray* - confinedLayers() const; + const LayerArray* confinedLayers() const; /// Return the confined volumes of this container array - if it exists - std::shared_ptr<const TrackingVolumeArray> - confinedVolumes() const; + std::shared_ptr<const TrackingVolumeArray> confinedVolumes() const; /// @brief Visit all sensitive surfaces /// @@ -259,20 +238,17 @@ public: /// /// If a context is needed for the vist, the vistitor has to provide this /// e.g. as a private member - void - visitSurfaces(const std::function<void(const Acts::Surface*)>& visitor) const; + void visitSurfaces( + const std::function<void(const Acts::Surface*)>& visitor) const; /// Returns the VolumeName - for debug reason, might be depreciated later - const std::string& - volumeName() const; + const std::string& volumeName() const; /// Method to return the BoundarySurfaces - const std::vector<TrackingVolumeBoundaryPtr>& - boundarySurfaces() const; + const std::vector<TrackingVolumeBoundaryPtr>& boundarySurfaces() const; /// Return the material of the volume - std::shared_ptr<const IVolumeMaterial> - volumeMaterial() const; + std::shared_ptr<const IVolumeMaterial> volumeMaterial() const; /// Set the volume material description /// @@ -281,8 +257,7 @@ public: /// the same material description, it is provided as a shared object /// /// @param material Material description of this volume - void - assignVolumeMaterial(std::shared_ptr<const IVolumeMaterial> material); + void assignVolumeMaterial(std::shared_ptr<const IVolumeMaterial> material); /// Glue another tracking volume to this one /// - if common face is set the glued volumes are sharing the boundary, down @@ -292,11 +267,10 @@ public: /// @param bsfMine is the boundary face indicater where to glue /// @param neighbor is the TrackingVolume to be glued /// @param bsfNeighbor is the boudnary surface of the neighbor - void - glueTrackingVolume(const GeometryContext& gctx, - BoundarySurfaceFace bsfMine, - const MutableTrackingVolumePtr& neighbor, - BoundarySurfaceFace bsfNeighbor); + void glueTrackingVolume(const GeometryContext& gctx, + BoundarySurfaceFace bsfMine, + const MutableTrackingVolumePtr& neighbor, + BoundarySurfaceFace bsfNeighbor); /// Glue another tracking volume to this one /// - if common face is set the glued volumes are sharing the boundary, down @@ -306,20 +280,18 @@ public: /// @param bsfMine is the boundary face indicater where to glue /// @param neighbors are the TrackingVolumes to be glued /// @param bsfNeighbor are the boudnary surface of the neighbors - void - glueTrackingVolumes(const GeometryContext& gctx, - BoundarySurfaceFace bsfMine, - const std::shared_ptr<TrackingVolumeArray>& neighbors, - BoundarySurfaceFace bsfNeighbor); + void glueTrackingVolumes( + const GeometryContext& gctx, BoundarySurfaceFace bsfMine, + const std::shared_ptr<TrackingVolumeArray>& neighbors, + BoundarySurfaceFace bsfNeighbor); /// Provide a new BoundarySurface from the glueing /// /// /// @param bsf is the boundary face indicater where to glue /// @param bs is the new boudnary surface - void - updateBoundarySurface( - BoundarySurfaceFace bsf, + void updateBoundarySurface( + BoundarySurfaceFace bsf, std::shared_ptr<const BoundarySurfaceT<TrackingVolume>> bs); /// Register the outside glue volumes - @@ -330,53 +302,44 @@ public: /// /// @param gvd register a new GlueVolumeDescriptor /// @todo update to shared/unique ptr - void - registerGlueVolumeDescriptor(GlueVolumesDescriptor* gvd); + void registerGlueVolumeDescriptor(GlueVolumesDescriptor* gvd); /// Register the outside glue volumes - /// ordering is in the TrackingVolume Frame: /// - negativeFaceXY /// - (faces YZ, ZY, radial faces) /// - positiveFaceXY - GlueVolumesDescriptor& - glueVolumesDescriptor(); + GlueVolumesDescriptor& glueVolumesDescriptor(); /// Sign the volume - the geometry builder has to do that /// /// @param geosign is the volume signature /// @param geotype is the volume navigation type - void - sign(GeometrySignature geosign, GeometryType geotype = Static); + void sign(GeometrySignature geosign, GeometryType geotype = Static); /// return the Signature - GeometrySignature - geometrySignature() const; + GeometrySignature geometrySignature() const; /// return the Signature - GeometryType - geometryType() const; + GeometryType geometryType() const; /// Register the color code /// /// @param icolor is a color number - void - registerColorCode(unsigned int icolor); + void registerColorCode(unsigned int icolor); /// Get the color code - unsigned int - colorCode() const; + unsigned int colorCode() const; /// Return the MotherVolume - if it exists - const TrackingVolume* - motherVolume() const; + const TrackingVolume* motherVolume() const; /// Set the MotherVolume /// /// @param mvol is the mother volume - void - setMotherVolume(const TrackingVolume* mvol); + void setMotherVolume(const TrackingVolume* mvol); -protected: + protected: /// Default constructor TrackingVolume(); @@ -387,12 +350,11 @@ protected: /// @param volbounds is the description of the volume boundaries /// @param containedVolumeArray are the static volumes that fill this volume /// @param volumeName is a string identifier - TrackingVolume( - std::shared_ptr<const Transform3D> htrans, - VolumeBoundsPtr volbounds, - const std::shared_ptr<const TrackingVolumeArray>& containedVolumeArray - = nullptr, - const std::string& volumeName = "undefined"); + TrackingVolume(std::shared_ptr<const Transform3D> htrans, + VolumeBoundsPtr volbounds, + const std::shared_ptr<const TrackingVolumeArray>& + containedVolumeArray = nullptr, + const std::string& volumeName = "undefined"); /// Constructor for a full equipped Tracking Volume /// @@ -402,25 +364,22 @@ protected: /// @param staticLayerArray is the confined layer array (optional) /// @param containedVolumeArray is the confined volume array /// @param volumeName is a string identifier - TrackingVolume(std::shared_ptr<const Transform3D> htrans, - VolumeBoundsPtr volumeBounds, - std::shared_ptr<const IVolumeMaterial> volumeMaterial, - std::unique_ptr<const LayerArray> staticLayerArray = nullptr, - std::shared_ptr<const TrackingVolumeArray> containedVolumeArray - = nullptr, - const std::string& volumeName = "undefined"); + TrackingVolume( + std::shared_ptr<const Transform3D> htrans, VolumeBoundsPtr volumeBounds, + std::shared_ptr<const IVolumeMaterial> volumeMaterial, + std::unique_ptr<const LayerArray> staticLayerArray = nullptr, + std::shared_ptr<const TrackingVolumeArray> containedVolumeArray = nullptr, + const std::string& volumeName = "undefined"); -private: + private: /// Create Boundary Surface - void - createBoundarySurfaces(); + void createBoundarySurfaces(); /// method to synchronize the layers with potentially updated volume bounds: /// - adapts the layer dimensions to the new volumebounds + envelope /// /// @param envelope is the clearance between volume boundary and layer - void - synchronizeLayers(double envelope = 1.) const; + void synchronizeLayers(double envelope = 1.) const; /// close the Geometry, i.e. set the GeometryID and assign material /// @@ -431,22 +390,18 @@ private: /// @param vol is the geometry id of the volume /// as calculated by the TrackingGeometry /// - void - closeGeometry(const IMaterialDecorator* materialDecorator, - std::map<std::string, const TrackingVolume*>& volumeMap, - size_t& vol); + void closeGeometry(const IMaterialDecorator* materialDecorator, + std::map<std::string, const TrackingVolume*>& volumeMap, + size_t& vol); /// interlink the layers in this TrackingVolume - void - interlinkLayers(); + void interlinkLayers(); /// Forbidden copy constructor - deleted TrackingVolume(const TrackingVolume&) = delete; /// Forbidden assignment - deleted - TrackingVolume& - operator=(const TrackingVolume&) - = delete; + TrackingVolume& operator=(const TrackingVolume&) = delete; /// The volume based material the TrackingVolume consists of std::shared_ptr<const IVolumeMaterial> m_volumeMaterial{nullptr}; @@ -480,70 +435,50 @@ private: unsigned int m_colorCode{20}; }; -inline const std::string& -TrackingVolume::volumeName() const -{ +inline const std::string& TrackingVolume::volumeName() const { return m_name; } -inline std::shared_ptr<const IVolumeMaterial> -TrackingVolume::volumeMaterial() const -{ +inline std::shared_ptr<const IVolumeMaterial> TrackingVolume::volumeMaterial() + const { return m_volumeMaterial; } -inline void -TrackingVolume::assignVolumeMaterial( - std::shared_ptr<const IVolumeMaterial> material) -{ +inline void TrackingVolume::assignVolumeMaterial( + std::shared_ptr<const IVolumeMaterial> material) { m_volumeMaterial = std::move(material); } -inline const LayerArray* -TrackingVolume::confinedLayers() const -{ +inline const LayerArray* TrackingVolume::confinedLayers() const { return m_confinedLayers.get(); } inline std::shared_ptr<const TrackingVolumeArray> -TrackingVolume::confinedVolumes() const -{ +TrackingVolume::confinedVolumes() const { return m_confinedVolumes; } -inline GeometrySignature -TrackingVolume::geometrySignature() const -{ +inline GeometrySignature TrackingVolume::geometrySignature() const { return m_geometrySignature; } -inline GeometryType -TrackingVolume::geometryType() const -{ +inline GeometryType TrackingVolume::geometryType() const { return m_geometryType; } -inline void -TrackingVolume::registerColorCode(unsigned int icolor) -{ +inline void TrackingVolume::registerColorCode(unsigned int icolor) { m_colorCode = icolor; } -inline unsigned int -TrackingVolume::colorCode() const -{ +inline unsigned int TrackingVolume::colorCode() const { return m_colorCode; } -inline const TrackingVolume* -TrackingVolume::motherVolume() const -{ +inline const TrackingVolume* TrackingVolume::motherVolume() const { return m_motherVolume; } -inline void -TrackingVolume::setMotherVolume(const TrackingVolume* mvol) -{ +inline void TrackingVolume::setMotherVolume(const TrackingVolume* mvol) { m_motherVolume = mvol; } diff --git a/Core/include/Acts/Geometry/TrackingVolumeArrayCreator.hpp b/Core/include/Acts/Geometry/TrackingVolumeArrayCreator.hpp index 7d845bee25beb35b94a5af2fe3ed3719aa3926cc..b2a84a33491423d8a1d24879c0299749059b50cb 100644 --- a/Core/include/Acts/Geometry/TrackingVolumeArrayCreator.hpp +++ b/Core/include/Acts/Geometry/TrackingVolumeArrayCreator.hpp @@ -31,24 +31,19 @@ using TrackingVolumeOrderPosition = std::pair<TrackingVolumePtr, Vector3D>; /// binned arrays of TrackingVolumes for both, confinement in another volume /// and navigation issues. /// -class TrackingVolumeArrayCreator : public ITrackingVolumeArrayCreator -{ -public: +class TrackingVolumeArrayCreator : public ITrackingVolumeArrayCreator { + public: /// @brief This struct stores the configuration of the tracking geometry - struct Config - { - }; + struct Config {}; /// Constructor /// /// @param logger logging instance TrackingVolumeArrayCreator(const Config& /*cfg*/, - std::unique_ptr<const Logger> logger - = getDefaultLogger("LayerArrayCreator", - Logging::INFO)) - : m_logger(std::move(logger)) - { - } + std::unique_ptr<const Logger> logger = + getDefaultLogger("LayerArrayCreator", + Logging::INFO)) + : m_logger(std::move(logger)) {} /// Destructor ~TrackingVolumeArrayCreator() override = default; @@ -60,29 +55,22 @@ public: /// @param [in] bValue is the binning value /// /// @return new created volume array - std::shared_ptr<const TrackingVolumeArray> - trackingVolumeArray(const GeometryContext& gctx, - const TrackingVolumeVector& tVolumes, - BinningValue bValue) const override; + std::shared_ptr<const TrackingVolumeArray> trackingVolumeArray( + const GeometryContext& gctx, const TrackingVolumeVector& tVolumes, + BinningValue bValue) const override; /// Set logging instance /// /// @param logger is the logging instance to be set - void - setLogger(std::unique_ptr<const Logger> logger) - { + void setLogger(std::unique_ptr<const Logger> logger) { m_logger = std::move(logger); } -private: + private: // Private access to the logger method - const Logger& - logger() const - { - return *m_logger; - } + const Logger& logger() const { return *m_logger; } /// logging instance std::unique_ptr<const Logger> m_logger; }; -} \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Geometry/TrapezoidVolumeBounds.hpp b/Core/include/Acts/Geometry/TrapezoidVolumeBounds.hpp index ba782167f9a546c2d3cdb79bc0c39d9c9219689f..e15708a48ed10609738657725d0afdd4a6793012 100644 --- a/Core/include/Acts/Geometry/TrapezoidVolumeBounds.hpp +++ b/Core/include/Acts/Geometry/TrapezoidVolumeBounds.hpp @@ -44,18 +44,17 @@ class TrapezoidBounds; /// /// @image html TrapezoidVolumeBounds_decomp.gif -class TrapezoidVolumeBounds : public VolumeBounds -{ -public: +class TrapezoidVolumeBounds : public VolumeBounds { + public: /// @enum BoundValues for readability enum BoundValues { bv_minHalfX = 0, //!< minimal halflength in x bv_maxHalfX = 1, //!< maximal halflength in x - bv_halfY = 2, //!< halflength in y - bv_halfZ = 3, //!< halflength in z - bv_alpha = 4, //!< opening angle alpha (in point A) - bv_beta = 5, //!< opening angle beta (in point B) - bv_length = 6 // length of the bounds vector + bv_halfY = 2, //!< halflength in y + bv_halfZ = 3, //!< halflength in z + bv_alpha = 4, //!< opening angle alpha (in point A) + bv_beta = 5, //!< opening angle beta (in point B) + bv_length = 6 // length of the bounds vector }; @@ -68,9 +67,7 @@ public: /// @param maxhalex is the half length in x at maximal y /// @param haley is the half length in y /// @param halez is the half length in z - TrapezoidVolumeBounds(double minhalex, - double maxhalex, - double haley, + TrapezoidVolumeBounds(double minhalex, double maxhalex, double haley, double halez); /// Constructor - the trapezoid boundaries (arbitrary trapezoid) @@ -80,11 +77,8 @@ public: /// @param halez is the half length in z /// @param alpha is the openeing angle at -x,-y /// @param beta is the openeing angle at +x,-y - TrapezoidVolumeBounds(double minhalex, - double haley, - double halez, - double alpha, - double beta); + TrapezoidVolumeBounds(double minhalex, double haley, double halez, + double alpha, double beta); /// Copy Constructor /// @param trabo The object to be copied @@ -95,12 +89,10 @@ public: /// Assignment operator /// @param trabo The object to be assigned - TrapezoidVolumeBounds& - operator=(const TrapezoidVolumeBounds& trabo); + TrapezoidVolumeBounds& operator=(const TrapezoidVolumeBounds& trabo); /// Virtual constructor - TrapezoidVolumeBounds* - clone() const override; + TrapezoidVolumeBounds* clone() const override; /// This method checks if position in the 3D volume frame /// is inside the cylinder @@ -109,8 +101,7 @@ public: /// @param tol is the tolerance applied /// /// @return boolean indicator if position is inside - bool - inside(const Vector3D& pos, double tol = 0.) const override; + bool inside(const Vector3D& pos, double tol = 0.) const override; /// Method to decompose the Bounds into Surfaces /// @@ -118,113 +109,84 @@ public: /// @note this is a factory method /// /// @return vector of surfaces from the decopmosition - std::vector<std::shared_ptr<const Surface>> - decomposeToSurfaces(const Transform3D* transformPtr) const override; + std::vector<std::shared_ptr<const Surface>> decomposeToSurfaces( + const Transform3D* transformPtr) const override; /// This method returns the minimal halflength in local x - double - minHalflengthX() const; + double minHalflengthX() const; /// This method returns the maximal halflength in local x - double - maxHalflengthX() const; + double maxHalflengthX() const; /// This method returns the halflength in local y - double - halflengthY() const; + double halflengthY() const; /// This method returns the halflength in local z - double - halflengthZ() const; + double halflengthZ() const; /// This method returns the opening angle in point A (negative local x) - double - alpha() const; + double alpha() const; /// This method returns the opening angle in point B (negative local x) - double - beta() const; + double beta() const; /// Output Method for std::ostream - std::ostream& - toStream(std::ostream& sl) const override; + std::ostream& toStream(std::ostream& sl) const override; -private: + private: /// Templated dump methos template <class T> - T& - dumpT(T& dt) const; + T& dumpT(T& dt) const; /// This method returns the associated TrapezoidBounds /// of the face PlaneSurface parallel to local xy plane - TrapezoidBounds* - faceXYTrapezoidBounds() const; + TrapezoidBounds* faceXYTrapezoidBounds() const; /// This method returns the associated RecangleBounds /// of the face PlaneSurface attached to alpha (negative local x) - RectangleBounds* - faceAlphaRectangleBounds() const; + RectangleBounds* faceAlphaRectangleBounds() const; /// This method returns the associated RectangleBounds /// of the face PlaneSurface attached to beta (positive local x) - RectangleBounds* - faceBetaRectangleBounds() const; + RectangleBounds* faceBetaRectangleBounds() const; /// This method returns the associated RectangleBounds /// of the face PlaneSurface parallel to local zx plane, negative local y - RectangleBounds* - faceZXRectangleBoundsBottom() const; + RectangleBounds* faceZXRectangleBoundsBottom() const; /// This method returns the associated RectangleBounds /// of the face PlaneSurface parallel to local zx plane, positive local y - RectangleBounds* - faceZXRectangleBoundsTop() const; + RectangleBounds* faceZXRectangleBoundsTop() const; /// the bounds values std::vector<TDD_real_t> m_valueStore; }; -inline TrapezoidVolumeBounds* -TrapezoidVolumeBounds::clone() const -{ +inline TrapezoidVolumeBounds* TrapezoidVolumeBounds::clone() const { return new TrapezoidVolumeBounds(*this); } -inline double -TrapezoidVolumeBounds::minHalflengthX() const -{ +inline double TrapezoidVolumeBounds::minHalflengthX() const { return m_valueStore.at(bv_minHalfX); } -inline double -TrapezoidVolumeBounds::maxHalflengthX() const -{ +inline double TrapezoidVolumeBounds::maxHalflengthX() const { return m_valueStore.at(bv_maxHalfX); } -inline double -TrapezoidVolumeBounds::halflengthY() const -{ +inline double TrapezoidVolumeBounds::halflengthY() const { return m_valueStore.at(bv_halfY); } -inline double -TrapezoidVolumeBounds::halflengthZ() const -{ +inline double TrapezoidVolumeBounds::halflengthZ() const { return m_valueStore.at(bv_halfZ); } -inline double -TrapezoidVolumeBounds::alpha() const -{ +inline double TrapezoidVolumeBounds::alpha() const { return m_valueStore.at(bv_alpha); } -inline double -TrapezoidVolumeBounds::beta() const -{ +inline double TrapezoidVolumeBounds::beta() const { return m_valueStore.at(bv_beta); } template <class T> -T& -TrapezoidVolumeBounds::dumpT(T& dt) const -{ +T& TrapezoidVolumeBounds::dumpT(T& dt) const { dt << std::setiosflags(std::ios::fixed); dt << std::setprecision(5); dt << "Acts::TrapezoidVolumeBounds: (minhalfX, halfY, halfZ, alpha, beta) = "; @@ -234,4 +196,4 @@ TrapezoidVolumeBounds::dumpT(T& dt) const << ")"; return dt; } -} \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Geometry/Volume.hpp b/Core/include/Acts/Geometry/Volume.hpp index 0541d7e98674b76428664e583773121d67149bd3..8677e3072e559db84ecf40949ddea7879b180381 100644 --- a/Core/include/Acts/Geometry/Volume.hpp +++ b/Core/include/Acts/Geometry/Volume.hpp @@ -29,9 +29,8 @@ using VolumeBoundsPtr = std::shared_ptr<const VolumeBounds>; /// the interface for inherited Volume classes /// regarding the geometrical information. -class Volume : public virtual GeometryObject -{ -public: +class Volume : public virtual GeometryObject { + public: /// Default constructor Volume(); @@ -40,7 +39,7 @@ public: /// @param htrans is the transform to position the volume in 3D space /// @param volbounds is the volume boundary definitions Volume(const std::shared_ptr<const Transform3D>& htrans, - VolumeBoundsPtr volbounds); + VolumeBoundsPtr volbounds); /// Copy Constructor - with optional shift /// @@ -54,24 +53,19 @@ public: /// Assignment operator /// /// @param vol is the source volume to be copied - Volume& - operator=(const Volume& vol); + Volume& operator=(const Volume& vol); /// Pseudo-constructor - virtual Volume* - clone() const; + virtual Volume* clone() const; //// Return methods for geometry transform - const Transform3D& - transform() const; + const Transform3D& transform() const; /// returns the center of the volume - const Vector3D& - center() const; + const Vector3D& center() const; /// returns the volumeBounds() - const VolumeBounds& - volumeBounds() const; + const VolumeBounds& volumeBounds() const; /// Inside() method for checks /// @@ -79,8 +73,7 @@ public: /// @param tol is the tolerance parameter /// /// @return boolean indicator if the position is inside - bool - inside(const Vector3D& gpos, double tol = 0.) const; + bool inside(const Vector3D& gpos, double tol = 0.) const; /// The binning position method /// - as default the center is given, but may be overloaded @@ -89,39 +82,31 @@ public: /// @param bValue is the binning value schema /// /// @return vector 3D that can be used for the binning - const Vector3D - binningPosition(const GeometryContext& gctx, - BinningValue bValue) const override; + const Vector3D binningPosition(const GeometryContext& gctx, + BinningValue bValue) const override; -protected: + protected: std::shared_ptr<const Transform3D> m_transform; - Vector3D m_center; - VolumeBoundsPtr m_volumeBounds; + Vector3D m_center; + VolumeBoundsPtr m_volumeBounds; }; -inline const Transform3D& -Volume::transform() const -{ +inline const Transform3D& Volume::transform() const { if (m_transform) { return (*(m_transform.get())); } return Acts::s_idTransform; } -inline const Vector3D& -Volume::center() const -{ +inline const Vector3D& Volume::center() const { return m_center; } -inline const VolumeBounds& -Volume::volumeBounds() const -{ +inline const VolumeBounds& Volume::volumeBounds() const { return (*(m_volumeBounds.get())); } /**Overload of << operator for std::ostream for debug output*/ -std::ostream& -operator<<(std::ostream& sl, const Volume& vol); +std::ostream& operator<<(std::ostream& sl, const Volume& vol); } // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Geometry/VolumeBounds.hpp b/Core/include/Acts/Geometry/VolumeBounds.hpp index 0988a2f1521ec8f823d6677f429f8e30da697768..bf422d7f8b096d11388c583d5f4ea7011d7f8b85 100644 --- a/Core/include/Acts/Geometry/VolumeBounds.hpp +++ b/Core/include/Acts/Geometry/VolumeBounds.hpp @@ -39,17 +39,15 @@ using VolumeBoundsPtr = std::shared_ptr<const VolumeBounds>; /// /// The Volume, retrieving a set of Surfaces from the VolumeBounds, can turn the /// Surfaces into BoundarySurfaces. -class VolumeBounds -{ -public: +class VolumeBounds { + public: /// Default Constructor*/ VolumeBounds() = default; /// Destructor virtual ~VolumeBounds() = default; /// clone() method to make deep copy in Volume copy constructor and for /// assigment operator of the Surface class. - virtual VolumeBounds* - clone() const = 0; + virtual VolumeBounds* clone() const = 0; /// Checking if position given in volume frame is inside /// @@ -57,8 +55,7 @@ public: /// @param tol is the tolerance applied for the inside check /// /// @return boolean indicating if the position is inside - virtual bool - inside(const Vector3D& gpos, double tol = 0.) const = 0; + virtual bool inside(const Vector3D& gpos, double tol = 0.) const = 0; /// Method to decompose the Bounds into Surfaces /// the Volume can turn them into BoundarySurfaces @@ -68,45 +65,40 @@ public: /// @note this is factory method /// /// @return a vector of surfaces bounding this volume - virtual std::vector<std::shared_ptr<const Surface>> - decomposeToSurfaces(const Transform3D* transform) const = 0; + virtual std::vector<std::shared_ptr<const Surface>> decomposeToSurfaces( + const Transform3D* transform) const = 0; /// Binning offset - overloaded for some R-binning types /// /// @param bValue is the binning schema used /// /// @return vector 3D to be used for the binning - virtual Vector3D - binningOffset(BinningValue bValue) const; + virtual Vector3D binningOffset(BinningValue bValue) const; /// Binning borders in double /// /// @param bValue is the binning schema used /// /// @return float offset to be used for the binning - virtual double - binningBorder(BinningValue bValue) const; + virtual double binningBorder(BinningValue bValue) const; /// Output Method for std::ostream, to be overloaded by child classes /// /// @param sl is the output stream to be dumped into - virtual std::ostream& - toStream(std::ostream& sl) const = 0; + virtual std::ostream& toStream(std::ostream& sl) const = 0; }; /// Binning offset - overloaded for some R-binning types -inline Vector3D VolumeBounds::binningOffset(BinningValue /*bValue*/) const -{ // standard offset is 0.,0.,0. +inline Vector3D VolumeBounds::binningOffset( + BinningValue /*bValue*/) const { // standard offset is 0.,0.,0. return Vector3D(0., 0., 0.); } -inline double VolumeBounds::binningBorder(BinningValue /*bValue*/) const -{ +inline double VolumeBounds::binningBorder(BinningValue /*bValue*/) const { return 0.; } /// Overload of << operator for std::ostream for debug output -std::ostream& -operator<<(std::ostream& sl, const VolumeBounds& vb); +std::ostream& operator<<(std::ostream& sl, const VolumeBounds& vb); -} // namespace +} // namespace Acts diff --git a/Core/include/Acts/Geometry/detail/BoundaryIntersectionSorter.hpp b/Core/include/Acts/Geometry/detail/BoundaryIntersectionSorter.hpp index 07db00e637177bbe5cc84b3fae2ad09dc61a9863..4b3d4f7a90f6f722c03c25d94477e9098fb73a8a 100644 --- a/Core/include/Acts/Geometry/detail/BoundaryIntersectionSorter.hpp +++ b/Core/include/Acts/Geometry/detail/BoundaryIntersectionSorter.hpp @@ -21,8 +21,8 @@ namespace Acts { // Full intersection with surface -using BoundaryIntersection - = FullIntersection<BoundarySurfaceT<TrackingVolume>, Surface>; +using BoundaryIntersection = + FullIntersection<BoundarySurfaceT<TrackingVolume>, Surface>; // Typedef of the surface intersection using SurfaceIntersection = ObjectIntersection<Surface>; @@ -30,8 +30,7 @@ using SurfaceIntersection = ObjectIntersection<Surface>; /// @brief This struct sorts the boundary surfaces of a tracking volume. The /// sorting is based on the intersection with a straight line along propagation /// direction. -struct DefaultBoundaryIntersectionSorter -{ +struct DefaultBoundaryIntersectionSorter { /// @brief Default constructor DefaultBoundaryIntersectionSorter() = default; @@ -52,29 +51,24 @@ struct DefaultBoundaryIntersectionSorter /// @return Vector of intersections with the boundaries ordered by the /// intersection probability template <typename options_t, typename corrector_t> - std::vector<BoundaryIntersection> - operator()(const GeometryContext& gctx, - std::vector<const BoundarySurfaceT<TrackingVolume>*>& boundaries, - const Vector3D& position, - const Vector3D& direction, - const options_t& options, - const corrector_t& corrfnc) const - { + std::vector<BoundaryIntersection> operator()( + const GeometryContext& gctx, + std::vector<const BoundarySurfaceT<TrackingVolume>*>& boundaries, + const Vector3D& position, const Vector3D& direction, + const options_t& options, const corrector_t& corrfnc) const { std::vector<BoundaryIntersection> bIntersections; for (auto& bSurface : boundaries) { const auto& bSurfaceRep = bSurface->surfaceRepresentation(); // intersect the surface - SurfaceIntersection bsIntersection - = bSurfaceRep.surfaceIntersectionEstimate( - gctx, position, direction, options, corrfnc); + SurfaceIntersection bsIntersection = + bSurfaceRep.surfaceIntersectionEstimate(gctx, position, direction, + options, corrfnc); // check if the intersection is valid, but exlude the on-surface case // when requested -- move to intersectionestimate if (bsIntersection) { bIntersections.push_back( - BoundaryIntersection(bsIntersection.intersection, - bSurface, - &bSurfaceRep, - options.navDir)); + BoundaryIntersection(bsIntersection.intersection, bSurface, + &bSurfaceRep, options.navDir)); } } // and now sort to get the closest - need custom sort here to respect sign @@ -97,8 +91,7 @@ struct DefaultBoundaryIntersectionSorter /// or curvature cases) /// 3) Order all surfaces in the opposite direction based on their path length /// (least probable) -struct BoundaryIntersectionSorter -{ +struct BoundaryIntersectionSorter { /// @brief Constructor BoundaryIntersectionSorter() = default; @@ -125,14 +118,11 @@ struct BoundaryIntersectionSorter /// @return Vector of intersections with the boundaries ordered by the /// intersection probability template <typename options_t, typename corrector_t> - std::vector<BoundaryIntersection> - operator()(const GeometryContext& gctx, - std::vector<const BoundarySurfaceT<TrackingVolume>*>& boundaries, - const Vector3D& position, - const Vector3D& direction, - const options_t& options, - const corrector_t& corrfnc) const - { + std::vector<BoundaryIntersection> operator()( + const GeometryContext& gctx, + std::vector<const BoundarySurfaceT<TrackingVolume>*>& boundaries, + const Vector3D& position, const Vector3D& direction, + const options_t& options, const corrector_t& corrfnc) const { // Resulting vector std::vector<BoundaryIntersection> bIntersections, bIntersectionsOtherNavDir; bIntersections.reserve(boundaries.size()); @@ -140,33 +130,33 @@ struct BoundaryIntersectionSorter // Set options for forward and backward direction options_t optionsOtherNavDir(options); switch (options.navDir) { - case forward: { - optionsOtherNavDir.navDir = backward; - break; - } - case backward: { - optionsOtherNavDir.navDir = forward; - break; - } - // anyDirection does not have any opposite direction so it will directly - // collected - case anyDirection: { - // Collect intersections - for (const auto& boundary : boundaries) { - bIntersections.push_back( - intersect(gctx, boundary, position, direction, options, corrfnc)); + case forward: { + optionsOtherNavDir.navDir = backward; + break; + } + case backward: { + optionsOtherNavDir.navDir = forward; + break; + } + // anyDirection does not have any opposite direction so it will directly + // collected + case anyDirection: { + // Collect intersections + for (const auto& boundary : boundaries) { + bIntersections.push_back( + intersect(gctx, boundary, position, direction, options, corrfnc)); + } + // Fast exit for that case + return bIntersections; } - // Fast exit for that case - return bIntersections; - } } // Collect the boundary surfaces both directions for (const auto& boundary : boundaries) { // If the intersection is valid it is pushed to the final vector otherwise // to a tmp storage - BoundaryIntersection intersection - = intersect(gctx, boundary, position, direction, options, corrfnc); + BoundaryIntersection intersection = + intersect(gctx, boundary, position, direction, options, corrfnc); if (intersection) { bIntersections.push_back(std::move(intersection)); } else { @@ -179,8 +169,7 @@ struct BoundaryIntersectionSorter if (options.navDir == forward) { std::sort(bIntersections.begin(), bIntersections.end()); std::sort(bIntersectionsOtherNavDir.begin(), - bIntersectionsOtherNavDir.end(), - std::greater<>()); + bIntersectionsOtherNavDir.end(), std::greater<>()); } else { std::sort(bIntersections.begin(), bIntersections.end(), std::greater<>()); std::sort(bIntersectionsOtherNavDir.begin(), @@ -198,7 +187,7 @@ struct BoundaryIntersectionSorter return bIntersections; } -private: + private: /// @brief This function constructs the intersection with a boundary surface /// and returns the intersection object /// @@ -214,20 +203,17 @@ private: /// /// @return Intersection object of the boundary surface template <typename options_t, typename corrector_t> - BoundaryIntersection - intersect(const GeometryContext& gctx, - const BoundarySurfaceT<TrackingVolume>* boundary, - const Vector3D& position, - const Vector3D& direction, - const options_t& options, - const corrector_t& corrfnc) const - { + BoundaryIntersection intersect( + const GeometryContext& gctx, + const BoundarySurfaceT<TrackingVolume>* boundary, + const Vector3D& position, const Vector3D& direction, + const options_t& options, const corrector_t& corrfnc) const { const Surface* surface = &(boundary->surfaceRepresentation()); // intersect the surface SurfaceIntersection bsIntersection = surface->surfaceIntersectionEstimate( gctx, position, direction, options, corrfnc); - return BoundaryIntersection( - bsIntersection.intersection, boundary, surface, options.navDir); + return BoundaryIntersection(bsIntersection.intersection, boundary, surface, + options.navDir); } }; -} // end of Acts namespace +} // namespace Acts diff --git a/Core/include/Acts/Geometry/detail/DefaultDetectorElementBase.hpp b/Core/include/Acts/Geometry/detail/DefaultDetectorElementBase.hpp index ff0dcbae2cea5804e80fdbdc0214ec599167043f..eb8b1dc5e67c886fbbda3f191c759c241a59240d 100644 --- a/Core/include/Acts/Geometry/detail/DefaultDetectorElementBase.hpp +++ b/Core/include/Acts/Geometry/detail/DefaultDetectorElementBase.hpp @@ -28,9 +28,8 @@ class Surface; /// for the Acts proxy mechanism for surfaces, i.e. surfaces in the /// Tracking geometry representing actual detection devices /// -class DetectorElementBase -{ -public: +class DetectorElementBase { + public: /// Constructor DetectorElementBase() = default; @@ -40,88 +39,75 @@ public: /// Return the transform for the Element proxy mechanism /// /// @param gctx The current geometry context object, e.g. alignment - virtual const Transform3D& - transform(const GeometryContext& gctx) const = 0; + virtual const Transform3D& transform(const GeometryContext& gctx) const = 0; /// Return surface association - virtual const Surface& - surface() const = 0; + virtual const Surface& surface() const = 0; /// Returns the thickness of the module /// @return double that indicates the thickness of the module - virtual double - thickness() const = 0; + virtual double thickness() const = 0; /// Fast access to bin members /// Bin members are elements that are in the same geometric binning cell, /// such, e.g. backside modules in a multiplet detector /// /// @return vector of DetectorElementBase pointers - const std::vector<const DetectorElementBase*>& - binmembers() const; + const std::vector<const DetectorElementBase*>& binmembers() const; /// Reigster the bin members /// Bin members are elements that are in the same geometric binning cell, /// such, e.g. backside modules in a doublet/triplet detector /// /// @param binmembers DetectorElementBase objects in the same cell - void - registerBinmembers(std::vector<const DetectorElementBase*>& binmembers); + void registerBinmembers(std::vector<const DetectorElementBase*>& binmembers); /// Fast access to neighbours /// Neighbours are elements that are in an neighbouring geometric binning /// cell, such, e.g. next in phi, next in eta modules /// /// @return vector of DetectorElementBase pointers - const std::vector<const DetectorElementBase*>& - neighbours() const; + const std::vector<const DetectorElementBase*>& neighbours() const; /// Reigster the neighbours /// Neighbours are elements that are in an neighbouring geometric binning /// cell, such, e.g. next in phi, next in eta modules /// /// @param neighbours are DetectorElementBase objects that are neighbours - void - registerNeighbours(std::vector<const DetectorElementBase*>& neighbours); + void registerNeighbours(std::vector<const DetectorElementBase*>& neighbours); -private: + private: std::vector<const DetectorElementBase*> m_binmembers; std::vector<const DetectorElementBase*> m_neighbours; }; inline const std::vector<const DetectorElementBase*>& -DetectorElementBase::binmembers() const -{ +DetectorElementBase::binmembers() const { return m_binmembers; } inline const std::vector<const DetectorElementBase*>& -DetectorElementBase::neighbours() const -{ +DetectorElementBase::neighbours() const { return m_neighbours; } -inline void -DetectorElementBase::registerBinmembers( - std::vector<const DetectorElementBase*>& binmembers) -{ +inline void DetectorElementBase::registerBinmembers( + std::vector<const DetectorElementBase*>& binmembers) { for (auto& bmember : binmembers) { // only fill if it's not yet registered - if (find(m_binmembers.begin(), m_binmembers.end(), bmember) - == m_binmembers.end()) { + if (find(m_binmembers.begin(), m_binmembers.end(), bmember) == + m_binmembers.end()) { m_binmembers.push_back(bmember); } } } -inline void -DetectorElementBase::registerNeighbours( - std::vector<const DetectorElementBase*>& neighbours) -{ +inline void DetectorElementBase::registerNeighbours( + std::vector<const DetectorElementBase*>& neighbours) { for (auto& neighbour : neighbours) { // only fill if it's not yet registered - if (find(m_neighbours.begin(), m_neighbours.end(), neighbour) - == m_neighbours.end()) { + if (find(m_neighbours.begin(), m_neighbours.end(), neighbour) == + m_neighbours.end()) { m_neighbours.push_back(neighbour); } } diff --git a/Core/include/Acts/Geometry/detail/Layer.ipp b/Core/include/Acts/Geometry/detail/Layer.ipp index 427b29386d0b837e4f54babf5c2c81c908365642..23c50d00eef85b947e692ad586a1e3d733e4daf9 100644 --- a/Core/include/Acts/Geometry/detail/Layer.ipp +++ b/Core/include/Acts/Geometry/detail/Layer.ipp @@ -10,53 +10,37 @@ namespace Acts { -inline const SurfaceArray* -Layer::surfaceArray() const -{ +inline const SurfaceArray* Layer::surfaceArray() const { return m_surfaceArray.get(); } -inline SurfaceArray* -Layer::surfaceArray() -{ +inline SurfaceArray* Layer::surfaceArray() { return const_cast<SurfaceArray*>(m_surfaceArray.get()); } -inline double -Layer::thickness() const -{ +inline double Layer::thickness() const { return m_layerThickness; } -inline LayerType -Layer::layerType() const -{ +inline LayerType Layer::layerType() const { return m_layerType; } -inline const TrackingVolume* -Layer::trackingVolume() const -{ +inline const TrackingVolume* Layer::trackingVolume() const { return m_trackingVolume; } -inline void -Layer::encloseTrackingVolume(const TrackingVolume& tvol) -{ +inline void Layer::encloseTrackingVolume(const TrackingVolume& tvol) { m_trackingVolume = &(tvol); } -inline const AbstractVolume* -Layer::representingVolume() const -{ +inline const AbstractVolume* Layer::representingVolume() const { return m_representingVolume.get(); } -inline const Layer* -Layer::nextLayer(const GeometryContext& /*gctx*/, - const Vector3D& gp, - const Vector3D& mom) const -{ +inline const Layer* Layer::nextLayer(const GeometryContext& /*gctx*/, + const Vector3D& gp, + const Vector3D& mom) const { // no binutility -> no chance to find out the direction if (m_nextLayerUtility == nullptr) { return nullptr; @@ -65,42 +49,33 @@ Layer::nextLayer(const GeometryContext& /*gctx*/, : m_nextLayers.second; } -inline bool -Layer::resolve(bool resolveSensitive, - bool resolveMaterial, - bool resolvePassive) const -{ +inline bool Layer::resolve(bool resolveSensitive, bool resolveMaterial, + bool resolvePassive) const { if (resolvePassive) { return true; } if (resolveSensitive && m_surfaceArray) { return true; } - if (resolveMaterial - && (m_ssSensitiveSurfaces > 1 || m_ssApproachSurfaces > 1 - || (surfaceRepresentation().surfaceMaterial() != nullptr))) { + if (resolveMaterial && + (m_ssSensitiveSurfaces > 1 || m_ssApproachSurfaces > 1 || + (surfaceRepresentation().surfaceMaterial() != nullptr))) { return true; } return false; } template <typename parameters_t> -bool -Layer::onLayer(const GeometryContext& gctx, - const parameters_t& pars, - const BoundaryCheck& bcheck) const -{ +bool Layer::onLayer(const GeometryContext& gctx, const parameters_t& pars, + const BoundaryCheck& bcheck) const { return isOnLayer(gctx, pars.position(), bcheck); } template <typename options_t, typename corrector_t> -std::vector<SurfaceIntersection> -Layer::compatibleSurfaces(const GeometryContext& gctx, - const Vector3D& position, - const Vector3D& momentum, - const options_t& options, - const corrector_t& corrfnc) const -{ +std::vector<SurfaceIntersection> Layer::compatibleSurfaces( + const GeometryContext& gctx, const Vector3D& position, + const Vector3D& momentum, const options_t& options, + const corrector_t& corrfnc) const { // the list of valid intersection std::vector<SurfaceIntersection> sIntersections; // remember the surfaces for duplicate removal @@ -121,8 +96,8 @@ Layer::compatibleSurfaces(const GeometryContext& gctx, if (options.endObject) { // intersect the end surface // - it is the final one don't use the bounday check at all - SurfaceIntersection endInter - = options.endObject->template surfaceIntersectionEstimate( + SurfaceIntersection endInter = + options.endObject->template surfaceIntersectionEstimate( gctx, position, momentum, options, corrfnc); // non-valid intersection with the end surface provided at this layer // indicates wrong direction or faulty setup @@ -139,8 +114,8 @@ Layer::compatibleSurfaces(const GeometryContext& gctx, // i.e. the maximum path limit is given by the layer thickness times // path correction, we take a safety factor of 1.5 // -> this avoids punch through for cylinders - double pCorrection - = surfaceRepresentation().pathCorrection(gctx, position, momentum); + double pCorrection = + surfaceRepresentation().pathCorrection(gctx, position, momentum); maxPath = 1.5 * thickness() * pCorrection * options.navDir; } @@ -192,11 +167,11 @@ Layer::compatibleSurfaces(const GeometryContext& gctx, // the approach surfaces are in principle always testSurfaces // - the surface on approach is excluded via the veto // - the surfaces are only collected if needed - if (m_approachDescriptor - && (options.resolveMaterial || options.resolvePassive)) { + if (m_approachDescriptor && + (options.resolveMaterial || options.resolvePassive)) { // the approach surfaces - const std::vector<const Surface*>& approachSurfaces - = m_approachDescriptor->containedSurfaces(); + const std::vector<const Surface*>& approachSurfaces = + m_approachDescriptor->containedSurfaces(); // we loop through and veto // - if the approach surface is the parameter surface // - if the surface is not compatible with the collect @@ -208,11 +183,11 @@ Layer::compatibleSurfaces(const GeometryContext& gctx, // (B) sensitive surface section // // check the sensitive surfaces if you have some - if (m_surfaceArray && (options.resolveMaterial || options.resolvePassive - || options.resolveSensitive)) { + if (m_surfaceArray && (options.resolveMaterial || options.resolvePassive || + options.resolveSensitive)) { // get the canditates - const std::vector<const Surface*>& sensitiveSurfaces - = m_surfaceArray->neighbors(position); + const std::vector<const Surface*>& sensitiveSurfaces = + m_surfaceArray->neighbors(position); // loop through and veto // - if the approach surface is the parameter surface // - if the surface is not compatible with the type(s) that are collected @@ -238,54 +213,44 @@ Layer::compatibleSurfaces(const GeometryContext& gctx, } template <typename parameters_t, typename options_t, typename corrector_t> -std::vector<SurfaceIntersection> -Layer::compatibleSurfaces(const GeometryContext& gctx, - const parameters_t& parameters, - const options_t& options, - const corrector_t& corrfnc) const -{ - return compatibleSurfaces( - gctx, parameters.position(), parameters.momentum(), options, corrfnc); +std::vector<SurfaceIntersection> Layer::compatibleSurfaces( + const GeometryContext& gctx, const parameters_t& parameters, + const options_t& options, const corrector_t& corrfnc) const { + return compatibleSurfaces(gctx, parameters.position(), parameters.momentum(), + options, corrfnc); } template <typename options_t, typename corrector_t> -const SurfaceIntersection -Layer::surfaceOnApproach(const GeometryContext& gctx, - const Vector3D& position, - const Vector3D& direction, - const options_t& options, - const corrector_t& corrfnc) const -{ +const SurfaceIntersection Layer::surfaceOnApproach( + const GeometryContext& gctx, const Vector3D& position, + const Vector3D& direction, const options_t& options, + const corrector_t& corrfnc) const { // resolve directive based by options // - options.resolvePassive is on -> always // - options.resolveSensitive is on -> always // - options.resolveMaterial is on // && either sensitive or approach surfaces have material bool resolvePS = options.resolveSensitive || options.resolvePassive; - bool resolveMS = options.resolveMaterial - && (m_ssSensitiveSurfaces > 1 || m_ssApproachSurfaces > 1 - || surfaceRepresentation().surfaceMaterial()); + bool resolveMS = options.resolveMaterial && + (m_ssSensitiveSurfaces > 1 || m_ssApproachSurfaces > 1 || + surfaceRepresentation().surfaceMaterial()); // now of course this only counts when you have an approach descriptor if (m_approachDescriptor && (resolvePS || resolveMS)) { // test if you are on an approach surface already, if so - provide it for (auto& asf : m_approachDescriptor->containedSurfaces()) { // in a connected geometry this is only a pointer comparison - if (options.startObject - && asf == &(options.startObject->surfaceRepresentation())) { + if (options.startObject && + asf == &(options.startObject->surfaceRepresentation())) { Intersection nIntersection(position, 0., true); return SurfaceIntersection(nIntersection, asf, options.navDir); } } // that's the collect trigger for always collecting // let's find the most suitable approach surface - SurfaceIntersection aSurface - = m_approachDescriptor->approachSurface(gctx, - position, - direction, - options.navDir, - options.boundaryCheck, - corrfnc); + SurfaceIntersection aSurface = m_approachDescriptor->approachSurface( + gctx, position, direction, options.navDir, options.boundaryCheck, + corrfnc); if (aSurface.intersection.valid) { return (aSurface); } @@ -300,26 +265,20 @@ Layer::surfaceOnApproach(const GeometryContext& gctx, } // create the intersection with the surface representation - return rSurface.surfaceIntersectionEstimate( - gctx, position, direction, options, corrfnc); + return rSurface.surfaceIntersectionEstimate(gctx, position, direction, + options, corrfnc); } template <typename parameters_t, typename options_t, typename corrector_t> -const SurfaceIntersection -Layer::surfaceOnApproach(const GeometryContext& gctx, - const parameters_t& parameters, - const options_t& options, - const corrector_t& corrfnc) const -{ - return surfaceOnApproach( - gctx, parameters.position(), parameters.direction(), options, corrfnc); +const SurfaceIntersection Layer::surfaceOnApproach( + const GeometryContext& gctx, const parameters_t& parameters, + const options_t& options, const corrector_t& corrfnc) const { + return surfaceOnApproach(gctx, parameters.position(), parameters.direction(), + options, corrfnc); } -inline bool -Layer::isOnLayer(const GeometryContext& gctx, - const Vector3D& gp, - const BoundaryCheck& bcheck) const -{ +inline bool Layer::isOnLayer(const GeometryContext& gctx, const Vector3D& gp, + const BoundaryCheck& bcheck) const { if (m_representingVolume != nullptr) { return m_representingVolume->inside(gp); } diff --git a/Core/include/Acts/Geometry/detail/TrackingVolume.ipp b/Core/include/Acts/Geometry/detail/TrackingVolume.ipp index bcd159b9fb8fc79729f52e838624bcf2bf662bd6..4106da98caa19a8653aec8b890f8504cfd0ebe9d 100644 --- a/Core/include/Acts/Geometry/detail/TrackingVolume.ipp +++ b/Core/include/Acts/Geometry/detail/TrackingVolume.ipp @@ -10,10 +10,8 @@ // TrackingVolume.ipp, Acts project /////////////////////////////////////////////////////////////////// -inline const Acts::Layer* -TrackingVolume::associatedLayer(const GeometryContext& /*gctx*/, - const Vector3D& gp) const -{ +inline const Acts::Layer* TrackingVolume::associatedLayer( + const GeometryContext& /*gctx*/, const Vector3D& gp) const { // confined static layers - highest hierarchy if (m_confinedLayers) { return (m_confinedLayers->object(gp).get()); @@ -24,14 +22,10 @@ TrackingVolume::associatedLayer(const GeometryContext& /*gctx*/, } template <typename options_t, typename corrector_t> -std::vector<LayerIntersection> -TrackingVolume::compatibleLayers(const GeometryContext& gctx, - const Vector3D& position, - const Vector3D& direction, - const options_t& options, - const corrector_t& corrfnc) const -{ - +std::vector<LayerIntersection> TrackingVolume::compatibleLayers( + const GeometryContext& gctx, const Vector3D& position, + const Vector3D& direction, const options_t& options, + const corrector_t& corrfnc) const { // the layer intersections which are valid std::vector<LayerIntersection> lIntersections; @@ -52,20 +46,21 @@ TrackingVolume::compatibleLayers(const GeometryContext& gctx, auto atIntersection = tLayer->surfaceOnApproach( gctx, position, direction, options, corrfnc); auto path = atIntersection.intersection.pathLength; - bool withinLimit - = (path * path <= options.pathLimit * options.pathLimit); + bool withinLimit = + (path * path <= options.pathLimit * options.pathLimit); // Intersection is ok - take it (move to surface on appraoch) - if (atIntersection && (atIntersection.object != options.targetSurface) - && withinLimit) { + if (atIntersection && + (atIntersection.object != options.targetSurface) && withinLimit) { // create a layer intersection lIntersections.push_back(LayerIntersection( atIntersection.intersection, tLayer, atIntersection.object)); } } // move to next one or break because you reached the end layer - tLayer = (tLayer == options.endObject) - ? nullptr - : tLayer->nextLayer(gctx, position, options.navDir * direction); + tLayer = + (tLayer == options.endObject) + ? nullptr + : tLayer->nextLayer(gctx, position, options.navDir * direction); } // sort them accordingly to the navigation direction if (options.navDir == forward) { @@ -79,29 +74,22 @@ TrackingVolume::compatibleLayers(const GeometryContext& gctx, } template <typename parameters_t, typename options_t, typename corrector_t> -std::vector<LayerIntersection> -TrackingVolume::compatibleLayers(const GeometryContext& gctx, - const parameters_t& parameters, - const options_t& options, - const corrector_t& corrfnc) const -{ - return compatibleLayers( - gctx, parameters.position(), parameters.direction(), options, corrfnc); +std::vector<LayerIntersection> TrackingVolume::compatibleLayers( + const GeometryContext& gctx, const parameters_t& parameters, + const options_t& options, const corrector_t& corrfnc) const { + return compatibleLayers(gctx, parameters.position(), parameters.direction(), + options, corrfnc); } // Returns the boundary surfaces ordered in probability to hit them based on template <typename options_t, typename corrector_t, typename sorter_t> -std::vector<BoundaryIntersection> -TrackingVolume::compatibleBoundaries(const GeometryContext& gctx, - const Vector3D& position, - const Vector3D& direction, - const options_t& options, - const corrector_t& corrfnc, - const sorter_t& sorter) const -{ +std::vector<BoundaryIntersection> TrackingVolume::compatibleBoundaries( + const GeometryContext& gctx, const Vector3D& position, + const Vector3D& direction, const options_t& options, + const corrector_t& corrfnc, const sorter_t& sorter) const { // Loop over boundarySurfaces and calculate the intersection - auto excludeObject = options.startObject; - auto& bSurfaces = boundarySurfaces(); + auto excludeObject = options.startObject; + auto& bSurfaces = boundarySurfaces(); std::vector<const BoundarySurfaceT<TrackingVolume>*> nonExcludedBoundaries; for (auto& bsIter : bSurfaces) { @@ -114,27 +102,18 @@ TrackingVolume::compatibleBoundaries(const GeometryContext& gctx, } nonExcludedBoundaries.push_back(bSurface); } - return sorter( - gctx, nonExcludedBoundaries, position, direction, options, corrfnc); + return sorter(gctx, nonExcludedBoundaries, position, direction, options, + corrfnc); } // Returns the boundary surfaces ordered in probability to hit them based on // straight line intersection @todo change hard-coded default -template <typename parameters_t, - typename options_t, - typename corrector_t, +template <typename parameters_t, typename options_t, typename corrector_t, typename sorter_t> -std::vector<BoundaryIntersection> -TrackingVolume::compatibleBoundaries(const GeometryContext& gctx, - const parameters_t& parameters, - const options_t& options, - const corrector_t& corrfnc, - const sorter_t& sorter) const -{ - return compatibleBoundaries(gctx, - parameters.position(), - parameters.direction(), - options, - corrfnc, - sorter); +std::vector<BoundaryIntersection> TrackingVolume::compatibleBoundaries( + const GeometryContext& gctx, const parameters_t& parameters, + const options_t& options, const corrector_t& corrfnc, + const sorter_t& sorter) const { + return compatibleBoundaries(gctx, parameters.position(), + parameters.direction(), options, corrfnc, sorter); } \ No newline at end of file diff --git a/Core/include/Acts/MagneticField/BFieldMapUtils.hpp b/Core/include/Acts/MagneticField/BFieldMapUtils.hpp index cdbbe13c94159a4ff8c653944f8f0b1b2fcd9446..b6794153ac118f99e09d8abd05971da9919a87cf 100644 --- a/Core/include/Acts/MagneticField/BFieldMapUtils.hpp +++ b/Core/include/Acts/MagneticField/BFieldMapUtils.hpp @@ -61,19 +61,16 @@ class SolenoidBField; /// e.g. we have the grid values r={0,1} with BFieldValues={2,3} on the r axis. /// If the flag is set to true the r-axis grid values will be set to {-1,0,1} /// and the BFieldValues will be set to {3,2,3}. -Acts:: - InterpolatedBFieldMapper<Acts::detail::Grid<Acts::Vector2D, - Acts::detail::EquidistantAxis, - Acts::detail::EquidistantAxis>> - fieldMapperRZ(const std::function<size_t(std::array<size_t, 2> binsRZ, - std::array<size_t, 2> nBinsRZ)>& - localToGlobalBin, - std::vector<double> rPos, - std::vector<double> zPos, - std::vector<Acts::Vector2D> bField, - double lengthUnit = Acts::units::_mm, - double BFieldUnit = Acts::units::_T, - bool firstQuadrant = false); +Acts::InterpolatedBFieldMapper< + Acts::detail::Grid<Acts::Vector2D, Acts::detail::EquidistantAxis, + Acts::detail::EquidistantAxis>> +fieldMapperRZ(const std::function<size_t(std::array<size_t, 2> binsRZ, + std::array<size_t, 2> nBinsRZ)>& + localToGlobalBin, + std::vector<double> rPos, std::vector<double> zPos, + std::vector<Acts::Vector2D> bField, + double lengthUnit = Acts::units::_mm, + double BFieldUnit = Acts::units::_T, bool firstQuadrant = false); /// Method to setup the FieldMapper /// @param localToGlobalBin Function mapping the local bins of x,y,z to the @@ -125,21 +122,16 @@ Acts:: /// e.g. we have the grid values z={0,1} with BFieldValues={2,3} on the r axis. /// If the flag is set to true the z-axis grid values will be set to {-1,0,1} /// and the BFieldValues will be set to {3,2,3}. -Acts:: - InterpolatedBFieldMapper<Acts::detail::Grid<Acts::Vector3D, - Acts::detail::EquidistantAxis, - Acts::detail::EquidistantAxis, - Acts::detail::EquidistantAxis>> - fieldMapperXYZ(const std::function<size_t(std::array<size_t, 3> binsXYZ, - std::array<size_t, 3> nBinsXYZ)>& - localToGlobalBin, - std::vector<double> xPos, - std::vector<double> yPos, - std::vector<double> zPos, - std::vector<Acts::Vector3D> bField, - double lengthUnit = Acts::units::_mm, - double BFieldUnit = Acts::units::_T, - bool firstOctant = false); +Acts::InterpolatedBFieldMapper<Acts::detail::Grid< + Acts::Vector3D, Acts::detail::EquidistantAxis, + Acts::detail::EquidistantAxis, Acts::detail::EquidistantAxis>> +fieldMapperXYZ(const std::function<size_t(std::array<size_t, 3> binsXYZ, + std::array<size_t, 3> nBinsXYZ)>& + localToGlobalBin, + std::vector<double> xPos, std::vector<double> yPos, + std::vector<double> zPos, std::vector<Acts::Vector3D> bField, + double lengthUnit = Acts::units::_mm, + double BFieldUnit = Acts::units::_T, bool firstOctant = false); /// Function which takes an existing SolenoidBField instance and /// creates a field mapper by sampling grid points from the analytical @@ -151,13 +143,12 @@ Acts:: /// @param field the solenoid field instance /// /// @return A field mapper instance for use in interpolation. -Acts:: - InterpolatedBFieldMapper<Acts::detail::Grid<Acts::Vector2D, - Acts::detail::EquidistantAxis, - Acts::detail::EquidistantAxis>> - solenoidFieldMapper(std::pair<double, double> rlim, - std::pair<double, double> zlim, - std::pair<size_t, size_t> nbins, - const SolenoidBField& field); +Acts::InterpolatedBFieldMapper< + Acts::detail::Grid<Acts::Vector2D, Acts::detail::EquidistantAxis, + Acts::detail::EquidistantAxis>> +solenoidFieldMapper(std::pair<double, double> rlim, + std::pair<double, double> zlim, + std::pair<size_t, size_t> nbins, + const SolenoidBField& field); } // namespace Acts diff --git a/Core/include/Acts/MagneticField/ConstantBField.hpp b/Core/include/Acts/MagneticField/ConstantBField.hpp index 58e40bca966e63cd50f32b8edf18939b700fe95a..7190a43f3984afdfc5a6b77d37587ec20cd3f0f9 100644 --- a/Core/include/Acts/MagneticField/ConstantBField.hpp +++ b/Core/include/Acts/MagneticField/ConstantBField.hpp @@ -18,11 +18,9 @@ namespace Acts { /// This class implements a simple constant magnetic field. The /// magnetic field value has to be set at creation time, but can /// be updated later on. -class ConstantBField final -{ -public: - struct Cache - { +class ConstantBField final { + public: + struct Cache { /// @brief constructor with context Cache(std::reference_wrapper<const MagneticFieldContext> /*mcfg*/) {} }; @@ -38,9 +36,7 @@ public: /// @param [in] By magnetic field component in global y-direction /// @param [in] Bz magnetic field component in global z-direction ConstantBField(double Bx = 0., double By = 0., double Bz = 0.) - : m_BField(Bx, By, Bz) - { - } + : m_BField(Bx, By, Bz) {} /// @brief retrieve magnetic field value /// @@ -49,11 +45,7 @@ public: /// /// @note The @p position is ignored and only kept as argument to provide /// a consistent interface with other magnetic field services. - Vector3D - getField(const Vector3D& /*position*/) const - { - return m_BField; - } + Vector3D getField(const Vector3D& /*position*/) const { return m_BField; } /// @brief retrieve magnetic field value /// @@ -63,9 +55,7 @@ public: /// /// @note The @p position is ignored and only kept as argument to provide /// a consistent interface with other magnetic field services. - Vector3D - getField(const Vector3D& /*position*/, Cache& /*cache*/) const - { + Vector3D getField(const Vector3D& /*position*/, Cache& /*cache*/) const { return m_BField; } @@ -79,10 +69,8 @@ public: /// a consistent interface with other magnetic field services. /// @note currently the derivative is not calculated /// @todo return derivative - Vector3D - getFieldGradient(const Vector3D& /*position*/, - ActsMatrixD<3, 3>& /*derivative*/) const - { + Vector3D getFieldGradient(const Vector3D& /*position*/, + ActsMatrixD<3, 3>& /*derivative*/) const { return m_BField; } @@ -97,11 +85,9 @@ public: /// a consistent interface with other magnetic field services. /// @note currently the derivative is not calculated /// @todo return derivative - Vector3D - getFieldGradient(const Vector3D& /*position*/, - ActsMatrixD<3, 3>& /*derivative*/, - Cache& /*cache*/) const - { + Vector3D getFieldGradient(const Vector3D& /*position*/, + ActsMatrixD<3, 3>& /*derivative*/, + Cache& /*cache*/) const { return m_BField; } @@ -111,33 +97,21 @@ public: /// @return @c true if position is inside the defined look-up grid, /// otherwise @c false /// @note The method will always return true for the constant B-Field - bool - isInside(const Vector3D& /*position*/) const - { - return true; - } + bool isInside(const Vector3D& /*position*/) const { return true; } /// @brief update magnetic field vector from components /// /// @param [in] Bx magnetic field component in global x-direction /// @param [in] By magnetic field component in global y-direction /// @param [in] Bz magnetic field component in global z-direction - void - setField(double Bx, double By, double Bz) - { - m_BField << Bx, By, Bz; - } + void setField(double Bx, double By, double Bz) { m_BField << Bx, By, Bz; } /// @brief update magnetic field vector /// /// @param [in] B magnetic field vector in global coordinate system - void - setField(const Vector3D& B) - { - m_BField = B; - } + void setField(const Vector3D& B) { m_BField = B; } -private: + private: /// magnetic field vector Vector3D m_BField; }; diff --git a/Core/include/Acts/MagneticField/InterpolatedBFieldMap.hpp b/Core/include/Acts/MagneticField/InterpolatedBFieldMap.hpp index e60129cdcd1bb23c3e90449ce6d6f4929ce38569..3775eeaaf375b940f1b0b56518228ab0d00513a1 100644 --- a/Core/include/Acts/MagneticField/InterpolatedBFieldMap.hpp +++ b/Core/include/Acts/MagneticField/InterpolatedBFieldMap.hpp @@ -26,11 +26,10 @@ namespace Acts { /// vector which /// is used to look up the magnetic field value in the underlying field map. template <typename G> -struct InterpolatedBFieldMapper -{ -public: - using Grid_t = G; - using FieldType = typename Grid_t::value_type; +struct InterpolatedBFieldMapper { + public: + using Grid_t = G; + using FieldType = typename Grid_t::value_type; static constexpr size_t DIM_POS = Grid_t::DIM; /// @brief struct representing smallest grid unit in magnetic field grid @@ -39,12 +38,11 @@ public: /// /// This type encapsulate all required information to perform linear /// interpolation of magnetic field values within a confined 3D volume. - struct FieldCell - { + struct FieldCell { /// number of corner points defining the confining hyper-box static constexpr unsigned int N = 1 << DIM_POS; - public: + public: /// @brief default constructor /// /// @param [in] transform mapping of global 3D coordinates onto grid space @@ -59,13 +57,11 @@ public: FieldCell(std::function<ActsVectorD<DIM_POS>(const Vector3D&)> transformPos, std::array<double, DIM_POS> lowerLeft, std::array<double, DIM_POS> upperRight, - std::array<Vector3D, N> fieldValues) - : m_transformPos(std::move(transformPos)) - , m_lowerLeft(std::move(lowerLeft)) - , m_upperRight(std::move(upperRight)) - , m_fieldValues(std::move(fieldValues)) - { - } + std::array<Vector3D, N> fieldValues) + : m_transformPos(std::move(transformPos)), + m_lowerLeft(std::move(lowerLeft)), + m_upperRight(std::move(upperRight)), + m_fieldValues(std::move(fieldValues)) {} /// @brief retrieve field at given position /// @@ -73,12 +69,10 @@ public: /// @return magnetic field value at the given position /// /// @pre The given @c position must lie within the current field cell. - Vector3D - getField(const Vector3D& position) const - { + Vector3D getField(const Vector3D& position) const { // defined in Interpolation.hpp - return interpolate( - m_transformPos(position), m_lowerLeft, m_upperRight, m_fieldValues); + return interpolate(m_transformPos(position), m_lowerLeft, m_upperRight, + m_fieldValues); } /// @brief check whether given 3D position is inside this field cell @@ -86,20 +80,18 @@ public: /// @param [in] position global 3D position /// @return @c true if position is inside the current field cell, /// otherwise @c false - bool - isInside(const Vector3D& position) const - { + bool isInside(const Vector3D& position) const { const auto& gridCoordinates = m_transformPos(position); for (unsigned int i = 0; i < DIM_POS; ++i) { - if (gridCoordinates[i] < m_lowerLeft.at(i) - || gridCoordinates[i] >= m_upperRight.at(i)) { + if (gridCoordinates[i] < m_lowerLeft.at(i) || + gridCoordinates[i] >= m_upperRight.at(i)) { return false; } } return true; } - private: + private: /// geometric transformation applied to global 3D positions std::function<ActsVectorD<DIM_POS>(const Vector3D&)> m_transformPos; @@ -127,13 +119,11 @@ public: InterpolatedBFieldMapper( std::function<ActsVectorD<DIM_POS>(const Vector3D&)> transformPos, std::function<Vector3D(const FieldType&, const Vector3D&)> - transformBField, + transformBField, Grid_t grid) - : m_transformPos(std::move(transformPos)) - , m_transformBField(std::move(transformBField)) - , m_grid(std::move(grid)) - { - } + : m_transformPos(std::move(transformPos)), + m_transformBField(std::move(transformBField)), + m_grid(std::move(grid)) {} /// @brief retrieve field at given position /// @@ -142,9 +132,7 @@ public: /// /// @pre The given @c position must lie within the range of the underlying /// magnetic field map. - Vector3D - getField(const Vector3D& position) const - { + Vector3D getField(const Vector3D& position) const { return m_transformBField(m_grid.interpolate(m_transformPos(position)), position); } @@ -156,13 +144,11 @@ public: /// /// @pre The given @c position must lie within the range of the underlying /// magnetic field map. - FieldCell - getFieldCell(const Vector3D& position) const - { + FieldCell getFieldCell(const Vector3D& position) const { const auto& gridPosition = m_transformPos(position); - const auto& indices = m_grid.localBinsFromPosition(gridPosition); - const auto& lowerLeft = m_grid.lowerLeftBinEdge(indices); - const auto& upperRight = m_grid.upperRightBinEdge(indices); + const auto& indices = m_grid.localBinsFromPosition(gridPosition); + const auto& lowerLeft = m_grid.lowerLeftBinEdge(indices); + const auto& upperRight = m_grid.upperRightBinEdge(indices); // loop through all corner points constexpr size_t nCorners = 1 << DIM_POS; @@ -174,16 +160,14 @@ public: neighbors.at(i++) = m_transformBField(m_grid.at(index), position); } - return FieldCell( - m_transformPos, lowerLeft, upperRight, std::move(neighbors)); + return FieldCell(m_transformPos, lowerLeft, upperRight, + std::move(neighbors)); } /// @brief get the number of bins for all axes of the field map /// /// @return vector returning number of bins for all field map axes - std::vector<size_t> - getNBins() const - { + std::vector<size_t> getNBins() const { auto nBinsArray = m_grid.numLocalBins(); return std::vector<size_t>(nBinsArray.begin(), nBinsArray.end()); } @@ -191,9 +175,7 @@ public: /// @brief get the minimum value of all axes of the field map /// /// @return vector returning the minima of all field map axes - std::vector<double> - getMin() const - { + std::vector<double> getMin() const { auto minArray = m_grid.minPosition(); return std::vector<double>(minArray.begin(), minArray.end()); } @@ -201,9 +183,7 @@ public: /// @brief get the maximum value of all axes of the field map /// /// @return vector returning the maxima of all field map axes - std::vector<double> - getMax() const - { + std::vector<double> getMax() const { auto maxArray = m_grid.maxPosition(); return std::vector<double>(maxArray.begin(), maxArray.end()); } @@ -213,22 +193,16 @@ public: /// @param [in] position global 3D position /// @return @c true if position is inside the defined look-up grid, /// otherwise @c false - bool - isInside(const Vector3D& position) const - { + bool isInside(const Vector3D& position) const { return m_grid.isInside(m_transformPos(position)); } /// @brief Get a const reference on the underlying grid structure /// /// @return grid reference - const Grid_t& - getGrid() const - { - return m_grid; - } + const Grid_t& getGrid() const { return m_grid; } -private: + private: /// geometric transformation applied to global 3D positions std::function<ActsVectorD<DIM_POS>(const Vector3D&)> m_transformPos; /// Transformation calculating the global 3D coordinates (cartesian) of the @@ -255,13 +229,10 @@ private: /// - looking up the magnetic field values on the closest grid points, /// - doing a linear interpolation of these magnetic field values. template <typename Mapper_t> -class InterpolatedBFieldMap final -{ - -public: +class InterpolatedBFieldMap final { + public: /// @brief configuration object for magnetic field interpolation - struct Config - { + struct Config { Config(Mapper_t m) : mapper(m) {} /// @brief global B-field scaling factor @@ -278,16 +249,14 @@ public: Mapper_t mapper; }; - struct Cache - { - + struct Cache { /// @brief Constructor with magnetic field context /// /// @param mcfg the magnetic field context Cache(std::reference_wrapper<const MagneticFieldContext> /*mcfg*/) {} std::optional<typename Mapper_t::FieldCell> fieldCell; - bool initialized = false; + bool initialized = false; }; /// @brief create interpolated magnetic field map @@ -298,20 +267,14 @@ public: /// @brief get configuration object /// /// @return copy of the internal configuration object - Config - getConfiguration() const - { - return m_config; - } + Config getConfiguration() const { return m_config; } /// @brief retrieve magnetic field value /// /// @param [in] position global 3D position /// /// @return magnetic field vector at given position - Vector3D - getField(const Vector3D& position) const - { + Vector3D getField(const Vector3D& position) const { return m_config.mapper.getField(position); } @@ -322,9 +285,7 @@ public: /// interpolation /// /// @return magnetic field vector at given position - Vector3D - getField(const Vector3D& position, Cache& cache) const - { + Vector3D getField(const Vector3D& position, Cache& cache) const { if (!cache.fieldCell || !(*cache.fieldCell).isInside(position)) { cache.fieldCell = getFieldCell(position); } @@ -339,10 +300,8 @@ public: /// /// @note currently the derivative is not calculated /// @todo return derivative - Vector3D - getFieldGradient(const Vector3D& position, - ActsMatrixD<3, 3>& /*derivative*/) const - { + Vector3D getFieldGradient(const Vector3D& position, + ActsMatrixD<3, 3>& /*derivative*/) const { return m_config.mapper.getField(position); } @@ -356,53 +315,37 @@ public: /// @note currently the derivative is not calculated /// @note Cache is not used currently /// @todo return derivative - Vector3D - getFieldGradient(const Vector3D& position, - ActsMatrixD<3, 3>& /*derivative*/, - Cache& /*cache*/) const - { + Vector3D getFieldGradient(const Vector3D& position, + ActsMatrixD<3, 3>& /*derivative*/, + Cache& /*cache*/) const { return m_config.mapper.getField(position); } /// @brief get global scaling factor for magnetic field /// /// @return global factor for scaling the magnetic field - double - getScale() const - { - return m_config.scale; - } + double getScale() const { return m_config.scale; } /// @brief convenience method to access underlying field mapper /// /// @return the field mapper - Mapper_t - getMapper() const - { - return m_config.mapper; - } + Mapper_t getMapper() const { return m_config.mapper; } /// @brief check whether given 3D position is inside look-up domain /// /// @param [in] position global 3D position /// @return @c true if position is inside the defined BField map, /// otherwise @c false - bool - isInside(const Vector3D& position) const - { + bool isInside(const Vector3D& position) const { return m_config.mapper.isInside(position); } /// @brief update configuration /// /// @param [in] config new configuration object - void - setConfiguration(const Config& config) - { - m_config = config; - } + void setConfiguration(const Config& config) { m_config = config; } -private: + private: /// @brief retrieve field cell for given position /// /// @param [in] position global 3D position @@ -410,9 +353,7 @@ private: /// /// @pre The given @c position must lie within the range of the underlying /// magnetic field map. - typename Mapper_t::FieldCell - getFieldCell(const Vector3D& position) const - { + typename Mapper_t::FieldCell getFieldCell(const Vector3D& position) const { return m_config.mapper.getFieldCell(position); } diff --git a/Core/include/Acts/MagneticField/SharedBField.hpp b/Core/include/Acts/MagneticField/SharedBField.hpp index 343ec8af9f9bd973b107738cc5b1dcf7d34bb4f8..49529c6f376251f2449358d8f19aea20aedffd1c 100644 --- a/Core/include/Acts/MagneticField/SharedBField.hpp +++ b/Core/include/Acts/MagneticField/SharedBField.hpp @@ -18,9 +18,8 @@ namespace Acts { /// in several places and with multiple steppers /// mainly targeted to save memory template <typename BField> -class SharedBField -{ -public: +class SharedBField { + public: // typedef wrapped BField's cache type using Cache = typename BField::Cache; @@ -34,9 +33,7 @@ public: /// @param [in] position global 3D position /// /// @return magnetic field vector at given position - Vector3D - getField(const Vector3D& position) const - { + Vector3D getField(const Vector3D& position) const { return m_bField->getField(position); } @@ -44,9 +41,7 @@ public: /// /// @param [in] position global 3D position /// @param [in,out] cache Cache object, passed through to wrapped BField - Vector3D - getField(const Vector3D& position, Cache& cache) const - { + Vector3D getField(const Vector3D& position, Cache& cache) const { return m_bField->getField(position, cache); } @@ -58,10 +53,8 @@ public: /// /// @note currently the derivative is not calculated /// @todo return derivative - Vector3D - getFieldGradient(const Vector3D& position, - ActsMatrixD<3, 3>& derivative) const - { + Vector3D getFieldGradient(const Vector3D& position, + ActsMatrixD<3, 3>& derivative) const { return m_bField->getFieldGradient(position, derivative); } @@ -74,15 +67,12 @@ public: /// /// @note currently the derivative is not calculated /// @todo return derivative - Vector3D - getFieldGradient(const Vector3D& position, - ActsMatrixD<3, 3>& derivative, - Cache& cache) const - { + Vector3D getFieldGradient(const Vector3D& position, + ActsMatrixD<3, 3>& derivative, Cache& cache) const { return m_bField->getFieldGradient(position, derivative, cache); } -private: + private: std::shared_ptr<const BField> m_bField; }; diff --git a/Core/include/Acts/MagneticField/SolenoidBField.hpp b/Core/include/Acts/MagneticField/SolenoidBField.hpp index f531a0486a84e5ce34d73e63e5dadb7f9a384431..a042521a8c36d6871196c4d80c7a16d42b213c61 100644 --- a/Core/include/Acts/MagneticField/SolenoidBField.hpp +++ b/Core/include/Acts/MagneticField/SolenoidBField.hpp @@ -62,11 +62,9 @@ namespace Acts { /// z 4pi __ | | 2 | 2 1 | /// |/Rr |_ \ 2r(1 - k ) / _| /// -class SolenoidBField -{ -public: - struct Cache - { +class SolenoidBField { + public: + struct Cache { /// @brief Constructor with magnetic field context /// /// @param mcfg the magnetic field context @@ -74,8 +72,7 @@ public: }; /// Config struct for the SolenoidBfield - struct Config - { + struct Config { /// Radius at which the coils are located double radius; /// Extent of the solenoid in z. It goes from @@ -98,21 +95,18 @@ public: /// @param [in] position global 3D position /// /// @return magnetic field vector at given position - Vector3D - getField(const Vector3D& position) const; + Vector3D getField(const Vector3D& position) const; /// @brief Retrieve magnetic field value /// /// @param [in] position global 3D position /// @param [in] cache Cache object, passed through to wrapped BField - Vector3D - getField(const Vector3D& position, Cache& /*cache*/) const; + Vector3D getField(const Vector3D& position, Cache& /*cache*/) const; /// @brief Retrieve magnetic field value in local (r,z) coordinates /// /// @param [in] position local 2D position - Vector2D - getField(const Vector2D& position) const; + Vector2D getField(const Vector2D& position) const; /// @brief retrieve magnetic field value & its gradient /// @@ -122,9 +116,8 @@ public: /// /// @note currently the derivative is not calculated /// @todo return derivative - Vector3D - getFieldGradient(const Vector3D& position, - ActsMatrixD<3, 3>& /*derivative*/) const; + Vector3D getFieldGradient(const Vector3D& position, + ActsMatrixD<3, 3>& /*derivative*/) const; /// @brief retrieve magnetic field value & its gradient /// @@ -135,31 +128,25 @@ public: /// /// @note currently the derivative is not calculated /// @todo return derivative - Vector3D - getFieldGradient(const Vector3D& position, - ActsMatrixD<3, 3>& /*derivative*/, - Cache& /*cache*/) const; + Vector3D getFieldGradient(const Vector3D& position, + ActsMatrixD<3, 3>& /*derivative*/, + Cache& /*cache*/) const; -private: + private: Config m_cfg; double m_scale; double m_dz; double m_R2; - Vector2D - multiCoilField(const Vector2D& pos, double scale) const; + Vector2D multiCoilField(const Vector2D& pos, double scale) const; - Vector2D - singleCoilField(const Vector2D& pos, double scale) const; + Vector2D singleCoilField(const Vector2D& pos, double scale) const; - double - B_r(const Vector2D& pos, double scale) const; + double B_r(const Vector2D& pos, double scale) const; - double - B_z(const Vector2D& pos, double scale) const; + double B_z(const Vector2D& pos, double scale) const; - double - k2(double r, double z) const; + double k2(double r, double z) const; }; } // namespace Acts diff --git a/Core/include/Acts/Material/AccumulatedMaterialProperties.hpp b/Core/include/Acts/Material/AccumulatedMaterialProperties.hpp index c1098aa91a9051a8569905dfa457ad32f23e0300..c713bd2aac052e267d417921ebdbca9401d48f4b 100644 --- a/Core/include/Acts/Material/AccumulatedMaterialProperties.hpp +++ b/Core/include/Acts/Material/AccumulatedMaterialProperties.hpp @@ -35,10 +35,8 @@ namespace Acts { /// information from all mapped events per bin is taken. /// /// The averaging is always done to unit thickness -class AccumulatedMaterialProperties -{ - -public: +class AccumulatedMaterialProperties { + public: /// Default constructor sets everything to zero AccumulatedMaterialProperties() = default; @@ -47,8 +45,8 @@ public: /// Default copy constructor /// @param amp the source Accumulated properties - AccumulatedMaterialProperties(const AccumulatedMaterialProperties& amp) - = default; + AccumulatedMaterialProperties(const AccumulatedMaterialProperties& amp) = + default; /// Default copy move constructor /// @param amp the source Accumulated properties @@ -56,15 +54,13 @@ public: /// Default assignment operator /// @param amp the source Accumulated properties - AccumulatedMaterialProperties& - operator=(const AccumulatedMaterialProperties& amp) - = default; + AccumulatedMaterialProperties& operator=( + const AccumulatedMaterialProperties& amp) = default; /// Default move assignment operator /// @param amp the source Accumulated properties - AccumulatedMaterialProperties& - operator=(AccumulatedMaterialProperties&& amp) - = default; + AccumulatedMaterialProperties& operator=( + AccumulatedMaterialProperties&& amp) = default; /// Accumulation operator /// @brief this adds the material properties to event store @@ -79,12 +75,10 @@ public: /// /// @param amp the source Accumulated properties /// @param pathCorreciton is the correction to nominal incident - void - accumulate(const MaterialProperties& amp, double pathCorrection = 1.); + void accumulate(const MaterialProperties& amp, double pathCorrection = 1.); /// Average the information accumulated for one track - void - trackAverage(); + void trackAverage(); /// Average the information accumulated during the entire /// mapping process @@ -96,10 +90,9 @@ public: /// The latter can be used when parallelising the mapping /// to several jobs /// - std::pair<MaterialProperties, unsigned int> - totalAverage(); + std::pair<MaterialProperties, unsigned int> totalAverage(); -private: + private: double m_eventPathInX0{0.}; //!< event: accumulate the thickness in X0 double m_eventPathInL0{0.}; //!< event: accumulate the thickness in L0 double m_eventA{0.}; //!< event: accumulate the contribution to A @@ -117,10 +110,8 @@ private: unsigned int m_totalEvents{0}; //!< the number of events }; -inline void -AccumulatedMaterialProperties::accumulate(const MaterialProperties& amp, - double pathCorrection) -{ +inline void AccumulatedMaterialProperties::accumulate( + const MaterialProperties& amp, double pathCorrection) { m_eventPathInX0 += amp.thicknessInX0(); m_eventPathInL0 += amp.thicknessInL0(); double t = amp.thickness(); @@ -134,9 +125,7 @@ AccumulatedMaterialProperties::accumulate(const MaterialProperties& amp, m_eventPathCorrection += pathCorrection * t; } -inline void -AccumulatedMaterialProperties::trackAverage() -{ +inline void AccumulatedMaterialProperties::trackAverage() { // Always count a hit if a path length is registered if (m_eventPath > 0.) { ++m_totalEvents; @@ -151,18 +140,17 @@ AccumulatedMaterialProperties::trackAverage() m_totalZ += (m_eventZ / m_eventRho); m_totalRho += (m_eventRho); } - m_eventPathInX0 = 0.; - m_eventPathInL0 = 0.; - m_eventA = 0.; - m_eventZ = 0.; - m_eventRho = 0.; - m_eventPath = 0.; + m_eventPathInX0 = 0.; + m_eventPathInL0 = 0.; + m_eventA = 0.; + m_eventZ = 0.; + m_eventRho = 0.; + m_eventPath = 0.; m_eventPathCorrection = 0.; } inline std::pair<MaterialProperties, unsigned int> -AccumulatedMaterialProperties::totalAverage() -{ +AccumulatedMaterialProperties::totalAverage() { if (m_totalEvents > 0 && m_totalPathInX0 > 0.) { double eventScalor = 1. / m_totalEvents; m_totalPathInX0 *= eventScalor; diff --git a/Core/include/Acts/Material/AccumulatedSurfaceMaterial.hpp b/Core/include/Acts/Material/AccumulatedSurfaceMaterial.hpp index ddf09709a2276d7e7fd412506c7e6a46f37d19a3..56df31bde0779bcc49d306f4d5e1d0610dc149d7 100644 --- a/Core/include/Acts/Material/AccumulatedSurfaceMaterial.hpp +++ b/Core/include/Acts/Material/AccumulatedSurfaceMaterial.hpp @@ -27,9 +27,8 @@ namespace Acts { /// /// It performs event- and run-average when called, and returns /// a new SurfaceMaterial object as a unique_ptr after finalisation -class AccumulatedSurfaceMaterial -{ -public: +class AccumulatedSurfaceMaterial { + public: using AccumulatedVector = std::vector<AccumulatedMaterialProperties>; using AccumulatedMatrix = std::vector<AccumulatedVector>; @@ -49,7 +48,7 @@ public: /// @param binUtility defines the binning structure on the surface /// @param splitFactor is the pre/post splitting directive AccumulatedSurfaceMaterial(const BinUtility& binUtility, - double splitFactor = 0.); + double splitFactor = 0.); /// Copy Constructor /// @@ -64,23 +63,20 @@ public: /// Assignment Move operator /// /// @param asma is the source object to be copied - AccumulatedSurfaceMaterial& - operator=(AccumulatedSurfaceMaterial&& asma) - = default; + AccumulatedSurfaceMaterial& operator=(AccumulatedSurfaceMaterial&& asma) = + default; /// Assignment operator /// /// @param asma is the source object to be copied - AccumulatedSurfaceMaterial& - operator=(const AccumulatedSurfaceMaterial& asma) - = default; + AccumulatedSurfaceMaterial& operator=( + const AccumulatedSurfaceMaterial& asma) = default; /// Destructor ~AccumulatedSurfaceMaterial() = default; /// Return the BinUtility - const BinUtility& - binUtility() const; + const BinUtility& binUtility() const; /// Assign a material properites object /// @@ -88,10 +84,9 @@ public: /// @param mp material properties to be assigned /// /// @return the bin triple to which the material was assigned - std::array<size_t, 3> - accumulate(const Vector2D& lp, - const MaterialProperties& mp, - double pathCorrection = 1.); + std::array<size_t, 3> accumulate(const Vector2D& lp, + const MaterialProperties& mp, + double pathCorrection = 1.); /// Assign a material properites object /// @@ -99,31 +94,26 @@ public: /// @param mp material properties to be assigned /// /// @return the bin triple to which the material was assigned - std::array<size_t, 3> - accumulate(const Vector3D& gp, - const MaterialProperties& mp, - double pathCorrection = 1.); + std::array<size_t, 3> accumulate(const Vector3D& gp, + const MaterialProperties& mp, + double pathCorrection = 1.); /// Average the information accumulated from one mapped track /// /// @param trackBins The bins that were touched by this event /// If none is given, the average runs over all bins in the surface map - void - trackAverage(const std::vector<std::array<size_t, 3>>& trackBins = {}); + void trackAverage(const std::vector<std::array<size_t, 3>>& trackBins = {}); /// Total average creates SurfaceMaterial - std::unique_ptr<const ISurfaceMaterial> - totalAverage(); + std::unique_ptr<const ISurfaceMaterial> totalAverage(); /// Access to the accumulated material - const AccumulatedMatrix& - accumulatedMaterial() const; + const AccumulatedMatrix& accumulatedMaterial() const; /// Access to the split factor - double - splitFactor() const; + double splitFactor() const; -private: + private: /// The helper for the bin finding BinUtility m_binUtility{}; @@ -134,21 +124,16 @@ private: AccumulatedMatrix m_accumulatedMaterial; }; -inline const BinUtility& -AccumulatedSurfaceMaterial::binUtility() const -{ +inline const BinUtility& AccumulatedSurfaceMaterial::binUtility() const { return (m_binUtility); } inline const AccumulatedSurfaceMaterial::AccumulatedMatrix& -AccumulatedSurfaceMaterial::accumulatedMaterial() const -{ +AccumulatedSurfaceMaterial::accumulatedMaterial() const { return (m_accumulatedMaterial); } -inline double -AccumulatedSurfaceMaterial::splitFactor() const -{ +inline double AccumulatedSurfaceMaterial::splitFactor() const { return m_splitFactor; } -} \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Material/AccumulatedVolumeMaterial.hpp b/Core/include/Acts/Material/AccumulatedVolumeMaterial.hpp index c5592aba36b2ada38f8c7474ec1c1ca6b27cb543..045aee72df301f406cc2a7e56d5f40562b702d6c 100644 --- a/Core/include/Acts/Material/AccumulatedVolumeMaterial.hpp +++ b/Core/include/Acts/Material/AccumulatedVolumeMaterial.hpp @@ -23,9 +23,8 @@ namespace Acts { /// /// It calculates the average of the material classification values when called, /// and returns a material with the averaged properties. -class AccumulatedVolumeMaterial -{ -public: +class AccumulatedVolumeMaterial { + public: /// @brief Default constructor AccumulatedVolumeMaterial() = default; @@ -36,17 +35,15 @@ public: /// the container /// /// @param [in] mat Material that will be collected - void - accumulate(const Material& mat); + void accumulate(const Material& mat); /// @brief Total average of each material classification value stored in the /// object independently /// /// @return Material consisting of the averaged values - Material - average(); + Material average(); -private: + private: /// Accumulate the contribution to X0 float m_totalX0{std::numeric_limits<float>::infinity()}; /// Accumulate the contribution to L0 diff --git a/Core/include/Acts/Material/BinnedSurfaceMaterial.hpp b/Core/include/Acts/Material/BinnedSurfaceMaterial.hpp index 8b8cf136e1c272ddd9b3fccc8ad26ea0cb7259fe..111a859f7b5e2cbdace6f001739a278c245b7ef5 100644 --- a/Core/include/Acts/Material/BinnedSurfaceMaterial.hpp +++ b/Core/include/Acts/Material/BinnedSurfaceMaterial.hpp @@ -24,9 +24,8 @@ namespace Acts { /// MaterialProperties. This is not memory optimised as every bin /// holds one material property object. -class BinnedSurfaceMaterial : public ISurfaceMaterial -{ -public: +class BinnedSurfaceMaterial : public ISurfaceMaterial { + public: /// Default Constructor - deleted BinnedSurfaceMaterial() = delete; @@ -41,9 +40,9 @@ public: /// @param binUtility defines the binning structure on the surface (copied) /// @param fullProperties is the vector of properties as recorded (moved) /// @param splitFactor is the pre/post splitting directive - BinnedSurfaceMaterial(const BinUtility& binUtility, + BinnedSurfaceMaterial(const BinUtility& binUtility, MaterialPropertiesVector fullProperties, - double splitFactor = 0.); + double splitFactor = 0.); /// Explicit constructor with only full MaterialProperties, /// for two-dimensional binning. @@ -56,9 +55,9 @@ public: /// @param binUtility defines the binning structure on the surface (copied) /// @param fullProperties is the vector of properties as recorded (moved) /// @param splitFactor is the pre/post splitting directive - BinnedSurfaceMaterial(const BinUtility& binUtility, + BinnedSurfaceMaterial(const BinUtility& binUtility, MaterialPropertiesMatrix fullProperties, - double splitFactor = 0.); + double splitFactor = 0.); /// Copy Move Constructor /// @@ -71,14 +70,10 @@ public: BinnedSurfaceMaterial(const BinnedSurfaceMaterial& bsm) = default; /// Assignment Move operator - BinnedSurfaceMaterial& - operator=(BinnedSurfaceMaterial&& bsm) - = default; + BinnedSurfaceMaterial& operator=(BinnedSurfaceMaterial&& bsm) = default; /// Assignment operator - BinnedSurfaceMaterial& - operator=(const BinnedSurfaceMaterial& bsm) - = default; + BinnedSurfaceMaterial& operator=(const BinnedSurfaceMaterial& bsm) = default; /// Destructor ~BinnedSurfaceMaterial() override = default; @@ -86,34 +81,28 @@ public: /// Scale operator /// /// @param scale is the scale factor for the full material - BinnedSurfaceMaterial& - operator*=(double scale) final; + BinnedSurfaceMaterial& operator*=(double scale) final; /// Return the BinUtility - const BinUtility& - binUtility() const; + const BinUtility& binUtility() const; /// @copydoc SurfaceMaterial::fullMaterial - const MaterialPropertiesMatrix& - fullMaterial() const; + const MaterialPropertiesMatrix& fullMaterial() const; /// @copydoc SurfaceMaterial::materialProperties(const Vector2D&) - const MaterialProperties& - materialProperties(const Vector2D& lp) const final; + const MaterialProperties& materialProperties(const Vector2D& lp) const final; /// @copydoc SurfaceMaterial::materialProperties(const Vector3D&) - const MaterialProperties& - materialProperties(const Vector3D& gp) const final; + const MaterialProperties& materialProperties(const Vector3D& gp) const final; /// @copydoc SurfaceMaterial::materialProperties(size_t, size_t) - const MaterialProperties& - materialProperties(size_t bin0, size_t bin1) const final; + const MaterialProperties& materialProperties(size_t bin0, + size_t bin1) const final; /// Output Method for std::ostream, to be overloaded by child classes - std::ostream& - toStream(std::ostream& sl) const final; + std::ostream& toStream(std::ostream& sl) const final; -private: + private: /// The helper for the bin finding BinUtility m_binUtility; @@ -121,21 +110,17 @@ private: MaterialPropertiesMatrix m_fullMaterial; }; -inline const BinUtility& -BinnedSurfaceMaterial::binUtility() const -{ +inline const BinUtility& BinnedSurfaceMaterial::binUtility() const { return (m_binUtility); } -inline const MaterialPropertiesMatrix& -BinnedSurfaceMaterial::fullMaterial() const -{ +inline const MaterialPropertiesMatrix& BinnedSurfaceMaterial::fullMaterial() + const { return m_fullMaterial; } -inline const MaterialProperties& -BinnedSurfaceMaterial::materialProperties(size_t bin0, size_t bin1) const -{ +inline const MaterialProperties& BinnedSurfaceMaterial::materialProperties( + size_t bin0, size_t bin1) const { return m_fullMaterial[bin1][bin0]; } -} \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Material/ElementFraction.hpp b/Core/include/Acts/Material/ElementFraction.hpp index e549eb699c39a746440bc22dac4e847b42edd4c3..55f13748d87f8e68d2cb4416197c9d3e1c103f94 100644 --- a/Core/include/Acts/Material/ElementFraction.hpp +++ b/Core/include/Acts/Material/ElementFraction.hpp @@ -40,9 +40,8 @@ namespace Acts { /// uint8_t gives you 256 Elements (more than we need), with an accuracy of /// 1./256, i.e. < 0.5 %. That's better than we can dream of parameterizing /// hadronic interactions. -class ElementFraction -{ -public: +class ElementFraction { + public: /// Default Constructor ElementFraction() = default; @@ -51,9 +50,7 @@ public: /// @param iz is the z value of the element as an unsigned int /// @param ifrac is the associated fraction of that element ElementFraction(unsigned int iz, float ifrac) - : m_data{{(uint8_t)iz, (uint8_t)(ifrac * double(UCHAR_MAX))}} - { - } + : m_data{{(uint8_t)iz, (uint8_t)(ifrac * double(UCHAR_MAX))}} {} /// Constructor direct data /// @@ -73,45 +70,29 @@ public: /// Assignment operator from base class /// /// @param ef is the element fraction source object - ElementFraction& - operator=(const ElementFraction& ef) - = default; + ElementFraction& operator=(const ElementFraction& ef) = default; /// Assigment Move Operator /// /// @param ef is the element fraction source object - ElementFraction& - operator=(ElementFraction&& ef) - = default; + ElementFraction& operator=(ElementFraction&& ef) = default; /// Access to the data itself - const std::array<uint8_t, 2>& - data() const - { - return m_data; - } + const std::array<uint8_t, 2>& data() const { return m_data; } /// Return in a nice format /// @return casts back to an unsigned integer - unsigned int - element() const - { - return static_cast<unsigned int>(m_data[0]); - } + unsigned int element() const { return static_cast<unsigned int>(m_data[0]); } /// Return in a nice format /// @return casts char to an unsigned int and then into double - double - fraction() const - { + double fraction() const { return (static_cast<unsigned int>(m_data[1]) * s_oneOverUcharMax); } /// Define the equality operator /// @param ef is the source ElementFraction for comparison - bool - operator==(const ElementFraction& ef) const - { + bool operator==(const ElementFraction& ef) const { return (m_data[0] == ef.m_data[0] && m_data[1] == ef.m_data[1]); } @@ -120,13 +101,11 @@ public: /// most probable fraction /// /// @param ef is the source ElementFraction for comparison - bool - operator<(const ElementFraction& ef) const - { + bool operator<(const ElementFraction& ef) const { return (m_data[1] < ef.m_data[1]); } -private: + private: std::array<uint8_t, 2> m_data = {{0, 0}}; //!< the data component }; -} \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Material/HomogeneousSurfaceMaterial.hpp b/Core/include/Acts/Material/HomogeneousSurfaceMaterial.hpp index 470e9bf1d400f0b66f3376e1c66723b89a27fa80..34fea17c61ecc4448234a7f9569d2d554f060128 100644 --- a/Core/include/Acts/Material/HomogeneousSurfaceMaterial.hpp +++ b/Core/include/Acts/Material/HomogeneousSurfaceMaterial.hpp @@ -22,9 +22,8 @@ namespace Acts { /// /// It extends the ISurfaceMaterial virutal base class to describe /// a simple homogeneous material on a surface -class HomogeneousSurfaceMaterial : public ISurfaceMaterial -{ -public: +class HomogeneousSurfaceMaterial : public ISurfaceMaterial { + public: /// Default Constructor - defaulted HomogeneousSurfaceMaterial() = default; @@ -33,7 +32,7 @@ public: /// @param full are the full material properties /// @param splitFactor is the split for pre/post update HomogeneousSurfaceMaterial(const MaterialProperties& full, - double splitFactor = 1.); + double splitFactor = 1.); /// Copy Constructor /// @@ -51,41 +50,35 @@ public: /// Assignment operator /// /// @param hsm is the source material - HomogeneousSurfaceMaterial& - operator=(const HomogeneousSurfaceMaterial& hsm) - = default; + HomogeneousSurfaceMaterial& operator=(const HomogeneousSurfaceMaterial& hsm) = + default; /// Assignment Move operator /// /// @param hsm is the source material - HomogeneousSurfaceMaterial& - operator=(HomogeneousSurfaceMaterial&& hsm) - = default; + HomogeneousSurfaceMaterial& operator=(HomogeneousSurfaceMaterial&& hsm) = + default; /// Scale operator /// - it is effectively a thickness scaling /// /// @param scale is the scale factor - HomogeneousSurfaceMaterial& - operator*=(double scale) final; + HomogeneousSurfaceMaterial& operator*=(double scale) final; /// Equality operator /// /// @param hsm is the source material - bool - operator==(const HomogeneousSurfaceMaterial& hsm) const; + bool operator==(const HomogeneousSurfaceMaterial& hsm) const; /// @copydoc SurfaceMaterial::materialProperties(const Vector2D&) /// /// @note the input parameter is ignored - const MaterialProperties& - materialProperties(const Vector2D& lp) const final; + const MaterialProperties& materialProperties(const Vector2D& lp) const final; /// @copydoc SurfaceMaterial::materialProperties(const Vector3D&) /// /// @note the input parameter is ignored - const MaterialProperties& - materialProperties(const Vector3D& gp) const final; + const MaterialProperties& materialProperties(const Vector3D& gp) const final; /// @copydoc SurfaceMaterial::materialProperties(size_t, size_t) /// @@ -93,8 +86,8 @@ public: /// @param ib1 The bin at local 1 for retrieving the material /// /// @note the input parameter is ignored - const MaterialProperties& - materialProperties(size_t ib0, size_t ib1) const final; + const MaterialProperties& materialProperties(size_t ib0, + size_t ib1) const final; /// The inherited methods - for materialProperties access using ISurfaceMaterial::materialProperties; @@ -105,38 +98,31 @@ public: /// Output Method for std::ostream /// /// @param sl The outoput stream - std::ostream& - toStream(std::ostream& sl) const final; + std::ostream& toStream(std::ostream& sl) const final; -private: + private: /// The five different MaterialProperties MaterialProperties m_fullMaterial = MaterialProperties(); }; -inline const MaterialProperties& -HomogeneousSurfaceMaterial::materialProperties(const Vector2D& /*lp*/) const -{ +inline const MaterialProperties& HomogeneousSurfaceMaterial::materialProperties( + const Vector2D& /*lp*/) const { return (m_fullMaterial); } -inline const MaterialProperties& -HomogeneousSurfaceMaterial::materialProperties(const Vector3D& /*gp*/) const -{ +inline const MaterialProperties& HomogeneousSurfaceMaterial::materialProperties( + const Vector3D& /*gp*/) const { return (m_fullMaterial); } -inline const MaterialProperties& - HomogeneousSurfaceMaterial::materialProperties(size_t /*ib0*/, - size_t /*ib1*/) const -{ +inline const MaterialProperties& HomogeneousSurfaceMaterial::materialProperties( + size_t /*ib0*/, size_t /*ib1*/) const { return (m_fullMaterial); } -inline bool -HomogeneousSurfaceMaterial:: -operator==(const HomogeneousSurfaceMaterial& hsm) const -{ +inline bool HomogeneousSurfaceMaterial::operator==( + const HomogeneousSurfaceMaterial& hsm) const { return (m_fullMaterial == hsm.m_fullMaterial); } -} // namespace \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Material/HomogeneousVolumeMaterial.hpp b/Core/include/Acts/Material/HomogeneousVolumeMaterial.hpp index 77523ff0a08ef69d7d986f9b3fe2fc615e51e737..4dde4cd8ca3e29af01d1fbe24d775aa9a4136a74 100644 --- a/Core/include/Acts/Material/HomogeneousVolumeMaterial.hpp +++ b/Core/include/Acts/Material/HomogeneousVolumeMaterial.hpp @@ -22,9 +22,8 @@ namespace Acts { /// /// It extends the IVolumeMaterial base class to describe a simple /// homogeneous material in a volume -class HomogeneousVolumeMaterial : public IVolumeMaterial -{ -public: +class HomogeneousVolumeMaterial : public IVolumeMaterial { + public: /// Default Constructor - defaulted HomogeneousVolumeMaterial() = default; @@ -37,14 +36,12 @@ public: /// /// @param position is the request position for the material call /// @todo interface to change including 'cell' - const Material& - material(const Vector3D& /*position*/) const final - { + const Material& material(const Vector3D& /*position*/) const final { return m_material; } -private: + private: Material m_material; }; -} // namespace +} // namespace Acts diff --git a/Core/include/Acts/Material/IMaterialDecorator.hpp b/Core/include/Acts/Material/IMaterialDecorator.hpp index 16578988838eaaee8aa358b48658797050a4417c..51c5c9f49a36c6ac84c2b1fbfd103b941ee296a6 100644 --- a/Core/include/Acts/Material/IMaterialDecorator.hpp +++ b/Core/include/Acts/Material/IMaterialDecorator.hpp @@ -24,23 +24,20 @@ class TrackingVolume; /// to be assigned either to surfaces or to volumes, hence there are /// two decorate interface methots. /// -class IMaterialDecorator -{ -public: +class IMaterialDecorator { + public: /// Virtual Destructor virtual ~IMaterialDecorator() = default; /// Decorate a surface /// /// @param surface the non-cost surface that is decorated - virtual void - decorate(Surface& surface) const = 0; + virtual void decorate(Surface& surface) const = 0; /// Decorate a TrackingVolume /// /// @param volume the non-cost volume that is decorated - virtual void - decorate(TrackingVolume& volume) const = 0; + virtual void decorate(TrackingVolume& volume) const = 0; }; -} // namespace \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Material/ISurfaceMaterial.hpp b/Core/include/Acts/Material/ISurfaceMaterial.hpp index 64752072c72729c01ca7af4267e42bf2bf1a60fe..2670034b81dd950348f67bc8c874c4db1eb0d28a 100644 --- a/Core/include/Acts/Material/ISurfaceMaterial.hpp +++ b/Core/include/Acts/Material/ISurfaceMaterial.hpp @@ -26,9 +26,8 @@ namespace Acts { /// MaterialProperties that are associated to a surface, /// extended by certain special representations (binned, homogenous) /// -class ISurfaceMaterial -{ -public: +class ISurfaceMaterial { + public: /// Constructor ISurfaceMaterial() = default; @@ -43,9 +42,7 @@ public: /// Scale operator /// /// @param scale is the scale factor applied - virtual ISurfaceMaterial& - operator*=(double scale) - = 0; + virtual ISurfaceMaterial& operator*=(double scale) = 0; /// Return method for full material description of the Surface /// - from local coordinate on the surface @@ -53,8 +50,8 @@ public: /// @param lp is the local position used for the (eventual) lookup /// /// @return const MaterialProperties - virtual const MaterialProperties& - materialProperties(const Vector2D& lp) const = 0; + virtual const MaterialProperties& materialProperties( + const Vector2D& lp) const = 0; /// Return method for full material description of the Surface /// - from the global coordinates @@ -62,22 +59,21 @@ public: /// @param gp is the global position used for the (eventual) lookup /// /// @return const MaterialProperties - virtual const MaterialProperties& - materialProperties(const Vector3D& gp) const = 0; + virtual const MaterialProperties& materialProperties( + const Vector3D& gp) const = 0; /// Direct access via bins to the MaterialProperties /// /// @param ib0 is the material bin in dimension 0 /// @param ib1 is the material bin in dimension 1 - virtual const MaterialProperties& - materialProperties(size_t ib0, size_t ib1) const = 0; + virtual const MaterialProperties& materialProperties(size_t ib0, + size_t ib1) const = 0; /// Update pre factor /// /// @param pDir is the navigation direction through the surface /// @param mStage is the material update directive (onapproach, full, onleave) - double - factor(NavigationDirection pDir, MaterialUpdateStage mStage) const; + double factor(NavigationDirection pDir, MaterialUpdateStage mStage) const; /// Return method for fully scaled material description of the Surface /// - from local coordinate on the surface @@ -87,10 +83,9 @@ public: /// @param mStage is the material update directive (onapproach, full, onleave) /// /// @return MaterialProperties - MaterialProperties - materialProperties(const Vector2D& lp, - NavigationDirection pDir, - MaterialUpdateStage mStage) const; + MaterialProperties materialProperties(const Vector2D& lp, + NavigationDirection pDir, + MaterialUpdateStage mStage) const; /// Return method for full material description of the Surface /// - from the global coordinates @@ -100,10 +95,9 @@ public: /// @param mStage is the material update directive (onapproach, full, onleave) /// /// @return MaterialProperties - MaterialProperties - materialProperties(const Vector3D& gp, - NavigationDirection pDir, - MaterialUpdateStage mStage) const; + MaterialProperties materialProperties(const Vector3D& gp, + NavigationDirection pDir, + MaterialUpdateStage mStage) const; /// @brief output stream operator /// @@ -111,36 +105,30 @@ public: /// virtual ISurfaceMaterial::toStream method /// /// @return modified output stream object - friend std::ostream& - operator<<(std::ostream& out, const ISurfaceMaterial& sm) - { + friend std::ostream& operator<<(std::ostream& out, + const ISurfaceMaterial& sm) { sm.toStream(out); return out; } /// Output Method for std::ostream, to be overloaded by child classes - virtual std::ostream& - toStream(std::ostream& sl) const = 0; + virtual std::ostream& toStream(std::ostream& sl) const = 0; -protected: + protected: double m_splitFactor{1.}; //!< the split factor in favour of oppositePre }; -inline double -ISurfaceMaterial::factor(NavigationDirection pDir, - MaterialUpdateStage mStage) const -{ +inline double ISurfaceMaterial::factor(NavigationDirection pDir, + MaterialUpdateStage mStage) const { if (mStage == Acts::fullUpdate) { return 1.; } return (pDir * mStage > 0 ? m_splitFactor : 1. - m_splitFactor); } -inline MaterialProperties -ISurfaceMaterial::materialProperties(const Vector2D& lp, - NavigationDirection pDir, - MaterialUpdateStage mStage) const -{ +inline MaterialProperties ISurfaceMaterial::materialProperties( + const Vector2D& lp, NavigationDirection pDir, + MaterialUpdateStage mStage) const { // The plain material properties associated to this bin MaterialProperties plainMatProp = materialProperties(lp); // Scale if you have material to scale @@ -154,11 +142,9 @@ ISurfaceMaterial::materialProperties(const Vector2D& lp, return plainMatProp; } -inline MaterialProperties -ISurfaceMaterial::materialProperties(const Vector3D& gp, - NavigationDirection pDir, - MaterialUpdateStage mStage) const -{ +inline MaterialProperties ISurfaceMaterial::materialProperties( + const Vector3D& gp, NavigationDirection pDir, + MaterialUpdateStage mStage) const { // The plain material properties associated to this bin MaterialProperties plainMatProp = materialProperties(gp); // Scale if you have material to scale @@ -172,4 +158,4 @@ ISurfaceMaterial::materialProperties(const Vector3D& gp, return plainMatProp; } -} // namespace +} // namespace Acts diff --git a/Core/include/Acts/Material/IVolumeMaterial.hpp b/Core/include/Acts/Material/IVolumeMaterial.hpp index e75594efa427abfa9244bad466753798c08fe311..70f2f85ef7801cfeb08b09287068b805ee1f4e08 100644 --- a/Core/include/Acts/Material/IVolumeMaterial.hpp +++ b/Core/include/Acts/Material/IVolumeMaterial.hpp @@ -21,9 +21,8 @@ class Material; /// Virtual base class of volume material description // /// Material associated with a Volume (homogenous, binned, interpolated) -class IVolumeMaterial -{ -public: +class IVolumeMaterial { + public: /// Virtual Destructor virtual ~IVolumeMaterial() = default; @@ -31,8 +30,7 @@ public: /// /// @param position is the request position for the material call /// @todo interface to change including 'cell' - virtual const Material& - material(const Vector3D& position) const = 0; + virtual const Material& material(const Vector3D& position) const = 0; }; -} // namespace +} // namespace Acts diff --git a/Core/include/Acts/Material/InterpolatedMaterialMap.hpp b/Core/include/Acts/Material/InterpolatedMaterialMap.hpp index d1b44eb51c8d1a1bc9be05bf0d997a2244101c5d..d218bbb8a22dd302e5f940407f9243039bc58407 100644 --- a/Core/include/Acts/Material/InterpolatedMaterialMap.hpp +++ b/Core/include/Acts/Material/InterpolatedMaterialMap.hpp @@ -22,18 +22,16 @@ namespace Acts { /// which is used to look up the material classification value in the /// underlying material map. template <typename G> -struct MaterialMapper -{ -public: - using Grid_t = G; +struct MaterialMapper { + public: + using Grid_t = G; static constexpr size_t DIM_POS = Grid_t::DIM; /// @brief Struct representing smallest grid unit in material grid /// /// This type encapsulate all required information to perform linear /// interpolation of material classification values within a 3D volume. - struct MaterialCell - { + struct MaterialCell { /// Number of corner points defining the confining hyper-box static constexpr unsigned int N = 1 << DIM_POS; @@ -51,15 +49,13 @@ public: /// box corners sorted in the canonical order defined in Acts::interpolate MaterialCell( std::function<ActsVectorD<DIM_POS>(const Vector3D&)> transformPos, - std::array<double, DIM_POS> lowerLeft, - std::array<double, DIM_POS> upperRight, + std::array<double, DIM_POS> lowerLeft, + std::array<double, DIM_POS> upperRight, std::array<ActsVectorF<5>, N> materialValues) - : m_transformPos(std::move(transformPos)) - , m_lowerLeft(std::move(lowerLeft)) - , m_upperRight(std::move(upperRight)) - , m_materialValues(std::move(materialValues)) - { - } + : m_transformPos(std::move(transformPos)), + m_lowerLeft(std::move(lowerLeft)), + m_upperRight(std::move(upperRight)), + m_materialValues(std::move(materialValues)) {} /// @brief Retrieve material at given position /// @@ -67,14 +63,10 @@ public: /// @return Material at the given position /// /// @pre The given @c position must lie within the current cell. - Material - getMaterial(const Vector3D& position) const - { + Material getMaterial(const Vector3D& position) const { // defined in Interpolation.hpp - return Material(interpolate(m_transformPos(position), - m_lowerLeft, - m_upperRight, - m_materialValues)); + return Material(interpolate(m_transformPos(position), m_lowerLeft, + m_upperRight, m_materialValues)); } /// @brief Check whether given 3D position is inside this cell @@ -82,20 +74,18 @@ public: /// @param [in] position Global 3D position /// @return @c true if position is inside the current cell, /// otherwise @c false - bool - isInside(const Vector3D& position) const - { + bool isInside(const Vector3D& position) const { const auto& gridCoordinates = m_transformPos(position); for (unsigned int i = 0; i < DIM_POS; ++i) { - if (gridCoordinates[i] < m_lowerLeft.at(i) - || gridCoordinates[i] >= m_upperRight.at(i)) { + if (gridCoordinates[i] < m_lowerLeft.at(i) || + gridCoordinates[i] >= m_upperRight.at(i)) { return false; } } return true; } - private: + private: /// Geometric transformation applied to global 3D positions std::function<ActsVectorD<DIM_POS>(const Vector3D&)> m_transformPos; @@ -119,10 +109,8 @@ public: /// @param [in] grid Grid storing material classification values MaterialMapper( std::function<ActsVectorD<DIM_POS>(const Vector3D&)> transformPos, - Grid_t grid) - : m_transformPos(std::move(transformPos)), m_grid(std::move(grid)) - { - } + Grid_t grid) + : m_transformPos(std::move(transformPos)), m_grid(std::move(grid)) {} /// @brief Retrieve material at given position /// @@ -131,9 +119,7 @@ public: /// /// @pre The given @c position must lie within the range of the underlying /// map. - Material - getMaterial(const Vector3D& position) const - { + Material getMaterial(const Vector3D& position) const { return Material(m_grid.interpolate(m_transformPos(position))); } @@ -144,14 +130,12 @@ public: /// /// @pre The given @c position must lie within the range of the underlying /// map. - MaterialCell - getMaterialCell(const Vector3D& position) const - { + MaterialCell getMaterialCell(const Vector3D& position) const { const auto& gridPosition = m_transformPos(position); - size_t bin = m_grid.globalBinFromPosition(gridPosition); - const auto& indices = m_grid.localBinsFromPosition(bin); - const auto& lowerLeft = m_grid.lowerLeftBinEdge(indices); - const auto& upperRight = m_grid.upperRightBinEdge(indices); + size_t bin = m_grid.globalBinFromPosition(gridPosition); + const auto& indices = m_grid.localBinsFromPosition(bin); + const auto& lowerLeft = m_grid.lowerLeftBinEdge(indices); + const auto& upperRight = m_grid.upperRightBinEdge(indices); // Loop through all corner points constexpr size_t nCorners = 1 << DIM_POS; @@ -163,16 +147,14 @@ public: neighbors.at(i++) = m_grid.at(index); } - return MaterialCell( - m_transformPos, lowerLeft, upperRight, std::move(neighbors)); + return MaterialCell(m_transformPos, lowerLeft, upperRight, + std::move(neighbors)); } /// @brief Get the number of bins for all axes of the map /// /// @return Vector returning number of bins for all map axes - std::vector<size_t> - getNBins() const - { + std::vector<size_t> getNBins() const { auto nBinsArray = m_grid.numLocalBins(); return std::vector<size_t>(nBinsArray.begin(), nBinsArray.end()); } @@ -180,9 +162,7 @@ public: /// @brief Get the minimum value of all axes of the map /// /// @return Vector returning the minima of all map axes - std::vector<double> - getMin() const - { + std::vector<double> getMin() const { auto minArray = m_grid.minPosition(); return std::vector<double>(minArray.begin(), minArray.end()); } @@ -190,9 +170,7 @@ public: /// @brief Get the maximum value of all axes of the map /// /// @return Vector returning the maxima of all map axes - std::vector<double> - getMax() const - { + std::vector<double> getMax() const { auto maxArray = m_grid.maxPosition(); return std::vector<double>(maxArray.begin(), maxArray.end()); } @@ -202,22 +180,16 @@ public: /// @param [in] position Global 3D position /// @return @c true if position is inside the defined look-up grid, /// otherwise @c false - bool - isInside(const Vector3D& position) const - { + bool isInside(const Vector3D& position) const { return m_grid.isInside(m_transformPos(position)); } /// @brief Get a const reference on the underlying grid structure /// /// @return Grid reference - const Grid_t& - getGrid() const - { - return m_grid; - } + const Grid_t& getGrid() const { return m_grid; } -private: + private: /// Geometric transformation applied to global 3D positions std::function<ActsVectorD<DIM_POS>(const Vector3D&)> m_transformPos; /// Grid storing material values @@ -247,12 +219,10 @@ private: /// collection of numbers. /// @tparam G Type of the grid template <typename Mapper_t> -class InterpolatedMaterialMap final -{ -public: +class InterpolatedMaterialMap final { + public: /// @brief Temporary storage of a certain cell to improve material access - struct Cache - { + struct Cache { /// Stored material cell std::optional<typename Mapper_t::MaterialCell> matCell; /// Boolean statement if the cell is initialized @@ -269,9 +239,7 @@ public: /// @param [in] position Global 3D position /// /// @return Material at given position - Material - getMaterial(const Vector3D& position) const - { + Material getMaterial(const Vector3D& position) const { return m_mapper.getMaterial(position); } @@ -282,11 +250,9 @@ public: /// interpolation /// /// @return material at given position - Material - getMaterial(const Vector3D& position, Cache& cache) const - { + Material getMaterial(const Vector3D& position, Cache& cache) const { if (!cache.initialized || !(*cache.matCell).isInside(position)) { - cache.matCell = getMaterialCell(position); + cache.matCell = getMaterialCell(position); cache.initialized = true; } return (*cache.matCell).getMaterial(position); @@ -300,10 +266,8 @@ public: /// /// @note Currently the derivative is not calculated /// @todo return derivative - Material - getMaterialGradient(const Vector3D& position, - ActsMatrixD<5, 5>& /*derivative*/) const - { + Material getMaterialGradient(const Vector3D& position, + ActsMatrixD<5, 5>& /*derivative*/) const { return m_mapper.getMaterial(position); } @@ -317,34 +281,26 @@ public: /// @note Currently the derivative is not calculated /// @note Cache is not used currently /// @todo return derivative - Material - getMaterialGradient(const Vector3D& position, - ActsMatrixD<5, 5>& /*derivative*/, - Cache& /*cache*/) const - { + Material getMaterialGradient(const Vector3D& position, + ActsMatrixD<5, 5>& /*derivative*/, + Cache& /*cache*/) const { return m_mapper.getMaterial(position); } /// @brief Convenience method to access underlying material mapper /// /// @return The material mapper - Mapper_t - getMapper() const - { - return m_mapper; - } + Mapper_t getMapper() const { return m_mapper; } /// @brief Check whether given 3D position is inside look-up domain /// /// @param [in] position Global 3D position /// @return @c true if position is inside the defined map, otherwise @c false - bool - isInside(const Vector3D& position) const - { + bool isInside(const Vector3D& position) const { return m_mapper.isInside(position); } -private: + private: /// @brief Retrieve cell for given position /// /// @param [in] position Global 3D position @@ -352,9 +308,8 @@ private: /// /// @pre The given @c position must lie within the range of the underlying /// map. - typename Mapper_t::MaterialCell - getMaterialCell(const Vector3D& position) const - { + typename Mapper_t::MaterialCell getMaterialCell( + const Vector3D& position) const { return m_mapper.getMaterialCell(position); } diff --git a/Core/include/Acts/Material/Material.hpp b/Core/include/Acts/Material/Material.hpp index 54f9d065767c5fd40b0006d90c0cdd928f108237..21f4bc1a7e6d2f1c167c3c10d4b86b5de03eae67 100644 --- a/Core/include/Acts/Material/Material.hpp +++ b/Core/include/Acts/Material/Material.hpp @@ -38,17 +38,16 @@ namespace Acts { /// Z - nuclear number /// rho - density /// Z/A*rho -class Material -{ -public: +class Material { + public: /// @brief Accessor enums enum Param { - matX0 = 0, ///< X0 - this is in mm - matL0 = 1, ///< L0 - this is in mm - matA = 2, ///< A - in au - matZ = 3, ///< Z - in e - matrho = 4, ///< rho - g/mm^3 - matZ_AR = 5 ///< Z/A*rho + matX0 = 0, ///< X0 - this is in mm + matL0 = 1, ///< L0 - this is in mm + matA = 2, ///< A - in au + matZ = 3, ///< Z - in e + matrho = 4, ///< rho - g/mm^3 + matZ_AR = 5 ///< Z/A*rho }; /// @brief Default Constructor - vacuum material @@ -62,29 +61,18 @@ public: /// @param iZ is the average atomic number /// @param iRho is the average density /// @param imc is the material composition - Material(float iX0, - float iL0, - float iA, - float iZ, - float iRho, + Material(float iX0, float iL0, float iA, float iZ, float iRho, MaterialComposition imc = {}) - : m_vacuum(false) - , m_store({iX0, iL0, iA, iZ, iRho, 0.}) - , m_composition(std::move(imc)) - { + : m_vacuum(false), + m_store({iX0, iL0, iA, iZ, iRho, 0.}), + m_composition(std::move(imc)) { float zOaTr = (iA > 0. ? iZ / iA * iRho : 0.); - m_store[5] = zOaTr; + m_store[5] = zOaTr; } Material(ActsVectorF<5> iMatData, MaterialComposition imc = {}) - : Material(iMatData[0], - iMatData[1], - iMatData[2], - iMatData[3], - iMatData[4], - std::move(imc)) - { - } + : Material(iMatData[0], iMatData[1], iMatData[2], iMatData[3], + iMatData[4], std::move(imc)) {} /// @brief Copy Constructor /// @@ -99,16 +87,12 @@ public: /// @brief Assignment operator /// /// @param mat is the source material - Material& - operator=(const Material& mat) - = default; + Material& operator=(const Material& mat) = default; /// @brief Assignment Move operator /// /// @param mat is the source material - Material& - operator=(Material&& mat) - = default; + Material& operator=(Material&& mat) = default; /// @brief Desctructor ~Material() = default; @@ -116,75 +100,45 @@ public: /// @brief Equality operator /// /// @param mat is the source material - bool - operator==(const Material& mat) const; + bool operator==(const Material& mat) const; /// @brief Inequality operator /// /// @param mat is the source material - bool - operator!=(const Material& mat) const; + bool operator!=(const Material& mat) const; /// @brief Boolean operator to check if this is vacuum operator bool() const { return (!m_vacuum); } /// @brief Access to X0 /// if it's vacuum, infinity - float - X0() const - { - return m_store[matX0]; - } + float X0() const { return m_store[matX0]; } /// @brief Access to L0 /// if it's vacuum, infinity - float - L0() const - { - return m_store[matL0]; - } + float L0() const { return m_store[matL0]; } /// @brief Access to A - float - A() const - { - return m_store[matA]; - } + float A() const { return m_store[matA]; } /// @brief Access to Z - float - Z() const - { - return m_store[matZ]; - } + float Z() const { return m_store[matZ]; } /// @brief Access to rho - float - rho() const - { - return m_store[matrho]; - } + float rho() const { return m_store[matrho]; } /// @brief Access to z/A*tho - float - zOverAtimesRho() const - { - return m_store[matZ_AR]; - } + float zOverAtimesRho() const { return m_store[matZ_AR]; } /// @brief Access to all classification numbers of the material - ActsVectorF<5> - classificationNumbers() - { + ActsVectorF<5> classificationNumbers() { ActsVectorF<5> numbers; numbers << X0(), L0(), A(), Z(), rho(); return numbers; } /// spit out as a string - std::string - toString() const - { + std::string toString() const { std::ostringstream sout; sout << std::setiosflags(std::ios::fixed) << std::setprecision(4); sout << " | "; @@ -198,7 +152,7 @@ public: return sout.str(); } -private: + private: /// define it is vacuum or not bool m_vacuum = true; @@ -214,15 +168,11 @@ private: MaterialComposition m_composition = MaterialComposition(); }; -inline bool -Material::operator==(const Material& mat) const -{ +inline bool Material::operator==(const Material& mat) const { return (m_store == mat.m_store && m_composition == mat.m_composition); } -inline bool -Material::operator!=(const Material& mat) const -{ +inline bool Material::operator!=(const Material& mat) const { return !operator==(mat); } } // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Material/MaterialCollector.hpp b/Core/include/Acts/Material/MaterialCollector.hpp index 518e758a8315aacd2d95c2ff2fc014e017ba5619..be739e497c56e5f6b08fca0ca3fb3c13d891ac09 100644 --- a/Core/include/Acts/Material/MaterialCollector.hpp +++ b/Core/include/Acts/Material/MaterialCollector.hpp @@ -17,19 +17,16 @@ namespace Acts { /// The information to be writtern out per hit surface -struct MaterialHit -{ +struct MaterialHit { const Surface* surface = nullptr; - Vector3D position; - Vector3D direction; - Material material; - double pathLength; + Vector3D position; + Vector3D direction; + Material material; + double pathLength; }; /// A Material Collector struct -struct MaterialCollector -{ - +struct MaterialCollector { /// In the detailed collection mode the material /// per surface is collected, otherwise only the total /// pathlength in X0 or L0 are recorded @@ -40,11 +37,10 @@ struct MaterialCollector /// Result of the material collection process /// It collects the overall X0 and L0 path lengths, /// and optionally a detailed per-material breakdown - struct this_result - { + struct this_result { std::vector<MaterialHit> collected; - double materialInX0 = 0.; - double materialInL0 = 0.; + double materialInX0 = 0.; + double materialInL0 = 0.; }; using result_type = this_result; @@ -61,16 +57,11 @@ struct MaterialCollector /// @param stepper The stepper in use /// @param result is the result object to be filled template <typename propagator_state_t, typename stepper_t> - void - operator()(propagator_state_t& state, - const stepper_t& stepper, - result_type& result) const - { - + void operator()(propagator_state_t& state, const stepper_t& stepper, + result_type& result) const { if (state.navigation.currentSurface) { - - if (state.navigation.currentSurface == state.navigation.targetSurface - and not state.navigation.targetReached) { + if (state.navigation.currentSurface == state.navigation.targetSurface and + not state.navigation.targetReached) { return; } @@ -83,27 +74,27 @@ struct MaterialCollector if (state.navigation.currentSurface->surfaceMaterial()) { // get the material propertices and only continue - const MaterialProperties* mProperties - = state.navigation.currentSurface->surfaceMaterial()->material( + const MaterialProperties* mProperties = + state.navigation.currentSurface->surfaceMaterial()->material( stepper.position(state.stepping)); if (mProperties) { // pre/post/full update double prepofu = 1.; - if (state.navigation.startSurface - == state.navigation.currentSurface) { + if (state.navigation.startSurface == + state.navigation.currentSurface) { debugLog(state, [&] { return std::string("Update on start surface: post-update mode."); }); - prepofu - = state.navigation.currentSurface->surfaceMaterial()->factor( + prepofu = + state.navigation.currentSurface->surfaceMaterial()->factor( state.stepping.navDir, postUpdate); - } else if (state.navigation.targetSurface - == state.navigation.currentSurface) { + } else if (state.navigation.targetSurface == + state.navigation.currentSurface) { debugLog(state, [&] { return std::string("Update on target surface: pre-update mode"); }); - prepofu - = state.navigation.currentSurface->surfaceMaterial()->factor( + prepofu = + state.navigation.currentSurface->surfaceMaterial()->factor( state.stepping.navDir, preUpdate); } else { debugLog(state, [&] { @@ -125,10 +116,10 @@ struct MaterialCollector }); // the path correction from the surface intersection - double pCorrection = prepofu - * state.navigation.currentSurface->pathCorrection( - stepper.position(state.stepping), - stepper.direction(state.stepping)); + double pCorrection = + prepofu * state.navigation.currentSurface->pathCorrection( + stepper.position(state.stepping), + stepper.direction(state.stepping)); // the full material result.materialInX0 += pCorrection * mProperties->thicknessInX0(); result.materialInL0 += pCorrection * mProperties->thicknessInL0(); @@ -145,11 +136,11 @@ struct MaterialCollector if (detailedCollection) { // create for recording MaterialHit mHit; - mHit.surface = state.navigation.currentSurface; - mHit.position = stepper.position(state.stepping); + mHit.surface = state.navigation.currentSurface; + mHit.position = stepper.position(state.stepping); mHit.direction = stepper.direction(state.stepping); // get the material & path length - mHit.material = mProperties->material(); + mHit.material = mProperties->material(); mHit.pathLength = pCorrection * mProperties->thickness(); // save if in the result result.collected.push_back(mHit); @@ -162,12 +153,9 @@ struct MaterialCollector /// Pure observer interface /// - this does not apply to the surface collector template <typename propagator_state_t> - void - operator()(propagator_state_t& /*state*/) const - { - } + void operator()(propagator_state_t& /*state*/) const {} -private: + private: /// The private propagation debug logging /// /// It needs to be fed by a lambda function that returns a string, @@ -180,10 +168,8 @@ private: /// length /// @param logAction is a callable function that returns a stremable object template <typename propagator_state_t> - void - debugLog(propagator_state_t& state, - const std::function<std::string()>& logAction) const - { + void debugLog(propagator_state_t& state, + const std::function<std::string()>& logAction) const { if (state.options.debug) { std::stringstream dstream; dstream << " " << std::setw(state.options.debugPfxWidth); @@ -194,4 +180,4 @@ private: } } }; -} +} // namespace Acts diff --git a/Core/include/Acts/Material/MaterialComposition.hpp b/Core/include/Acts/Material/MaterialComposition.hpp index 06194f369d1b236ddc65dfdaacbee98259302bdf..1b3ecbd9645d77224062e7f9da40b5147c6f20e0 100644 --- a/Core/include/Acts/Material/MaterialComposition.hpp +++ b/Core/include/Acts/Material/MaterialComposition.hpp @@ -21,9 +21,8 @@ namespace Acts { /// /// This helper struct allows to create a material composition /// as terms of element fraction objects -class MaterialComposition -{ -public: +class MaterialComposition { + public: /// Default constructor MaterialComposition() = default; @@ -36,8 +35,7 @@ public: /// to one within tolerance /// /// @param efracs are the element fractions - MaterialComposition(const std::vector<ElementFraction>& efracs) - { + MaterialComposition(const std::vector<ElementFraction>& efracs) { m_elements = efracs; std::sort(m_elements.begin(), m_elements.end()); } @@ -55,49 +53,31 @@ public: /// Assignment operator /// /// @param mc is the source object - MaterialComposition& - operator=(const MaterialComposition& mc) - = default; + MaterialComposition& operator=(const MaterialComposition& mc) = default; /// Assignment move operator /// /// @param mc is the source object - MaterialComposition& - operator=(MaterialComposition&& mc) - = default; + MaterialComposition& operator=(MaterialComposition&& mc) = default; /// Access to the elements themselves - const std::vector<ElementFraction>& - elements() const - { - return m_elements; - } + const std::vector<ElementFraction>& elements() const { return m_elements; } /// Boolean operator to indicate if this is empty operator bool() const { return !empty(); } /// How many elements you have - size_t - size() const - { - return m_elements.size(); - } + size_t size() const { return m_elements.size(); } /// Check if empty - bool - empty() const - { - return m_elements.empty(); - } + bool empty() const { return m_elements.empty(); } /// Euality operator - bool - operator==(const MaterialComposition& mc) const - { + bool operator==(const MaterialComposition& mc) const { return (mc.m_elements == m_elements); } -private: + private: std::vector<ElementFraction> m_elements = {}; }; -} +} // namespace Acts diff --git a/Core/include/Acts/Material/MaterialMapUtils.hpp b/Core/include/Acts/Material/MaterialMapUtils.hpp index a9abc451076416e493fa409bc917bdf1bb68e0b0..5ec152075cc14d61fbdbda1caa42de8d3aa3b69c 100644 --- a/Core/include/Acts/Material/MaterialMapUtils.hpp +++ b/Core/include/Acts/Material/MaterialMapUtils.hpp @@ -52,16 +52,14 @@ namespace Acts { /// @note The function localToGlobalBin determines how the material was /// stored in the vector in respect to the grid values /// @param [in] lengthUnit The unit of the grid points -MaterialMapper<detail::Grid<ActsVectorF<5>, - detail::EquidistantAxis, +MaterialMapper<detail::Grid<ActsVectorF<5>, detail::EquidistantAxis, detail::EquidistantAxis>> materialMapperRZ(const std::function<size_t(std::array<size_t, 2> binsRZ, std::array<size_t, 2> nBinsRZ)>& - materialVectorToGridMapper, - std::vector<double> rPos, - std::vector<double> zPos, + materialVectorToGridMapper, + std::vector<double> rPos, std::vector<double> zPos, std::vector<Material> material, - double lengthUnit = units::_mm); + double lengthUnit = units::_mm); /// Method to setup the MaterialMapper /// @param [in] materialVectorToGridMapper Function mapping the vector of @@ -104,16 +102,12 @@ materialMapperRZ(const std::function<size_t(std::array<size_t, 2> binsRZ, /// @note The function localToGlobalBin determines how the material was /// stored in the vector in respect to the grid values /// @param [in] lengthUnit The unit of the grid points -MaterialMapper<detail::Grid<ActsVectorF<5>, - detail::EquidistantAxis, - detail::EquidistantAxis, - detail::EquidistantAxis>> +MaterialMapper<detail::Grid<ActsVectorF<5>, detail::EquidistantAxis, + detail::EquidistantAxis, detail::EquidistantAxis>> materialMapperXYZ(const std::function<size_t(std::array<size_t, 3> binsXYZ, std::array<size_t, 3> nBinsXYZ)>& - materialVectorToGridMapper, - std::vector<double> xPos, - std::vector<double> yPos, - std::vector<double> zPos, - std::vector<Material> material, - double lengthUnit = units::_mm); + materialVectorToGridMapper, + std::vector<double> xPos, std::vector<double> yPos, + std::vector<double> zPos, std::vector<Material> material, + double lengthUnit = units::_mm); } // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Material/MaterialProperties.hpp b/Core/include/Acts/Material/MaterialProperties.hpp index 3f7c6867a8e9e7a0ced6c3f2ad3b5bf7f211bbcd..cfe3937eaf3222f06d1612cc81015a2492e00248 100644 --- a/Core/include/Acts/Material/MaterialProperties.hpp +++ b/Core/include/Acts/Material/MaterialProperties.hpp @@ -31,9 +31,8 @@ namespace Acts { /// - A [g/mole] /// - Z /// - rho [g/mm3] -class MaterialProperties -{ -public: +class MaterialProperties { + public: /// Default Constructor MaterialProperties() = default; @@ -49,12 +48,8 @@ public: /// @param averageZ is the average atomic number /// @param averageRho is the average density in g/mm3 /// @param thickness is the thickness of the material - MaterialProperties(float Xo, - float Lo, - float averageA, - float averageZ, - float averageRho, - float thickness); + MaterialProperties(float Xo, float Lo, float averageA, float averageZ, + float averageRho, float thickness); /// Constructor - for full Material class /// @@ -85,34 +80,27 @@ public: /// Assignment Operator /// /// @param mprop is the source material properties object - MaterialProperties& - operator=(const MaterialProperties& mprop) - = default; + MaterialProperties& operator=(const MaterialProperties& mprop) = default; /// Assignment Move Operator /// /// @param mprop is the source material properties object - MaterialProperties& - operator=(MaterialProperties&& mprop) - = default; + MaterialProperties& operator=(MaterialProperties&& mprop) = default; /// Scale operator - scales the material thickness /// /// @param scale is the material scaling parameter - MaterialProperties& - operator*=(float scale); + MaterialProperties& operator*=(float scale); /// Comparison operator /// /// @param mprop is the source material properties object - bool - operator==(const MaterialProperties& mprop) const; + bool operator==(const MaterialProperties& mprop) const; /// Comparison operator /// /// @param mprop is the source material properties object - bool - operator!=(const MaterialProperties& mprop) const; + bool operator!=(const MaterialProperties& mprop) const; /// Scale to unit thickness /// @@ -126,140 +114,106 @@ public: /// /// Leaves intact: /// - tInX0, tInL0, A, Z - void - scaleToUnitThickness(); + void scaleToUnitThickness(); /// Boolean operator /// false indicates it's vacuum operator bool() const { return bool(m_material); } /// Return the stored Material - const Material& - material() const; + const Material& material() const; /// Return the thickness in mm - float - thickness() const; + float thickness() const; /// Return the radiationlength fraction - float - thicknessInX0() const; + float thicknessInX0() const; /// Return the nuclear interaction length fraction - float - thicknessInL0() const; + float thicknessInL0() const; /// Returns the average X0 of the material - float - averageX0() const; + float averageX0() const; /// Return the average L0 of the material - float - averageL0() const; + float averageL0() const; /// Returns the average Z of the material - float - averageZ() const; + float averageZ() const; /// Return the average A of the material [gram/mole] - float - averageA() const; + float averageA() const; /// Return the average density of the material /// - in [g/mm^3] - float - averageRho() const; + float averageRho() const; /// Return the @f$ Z/A * rho @f$ - float - zOverAtimesRho() const; - -protected: - Material m_material{}; //!< the material description - float m_thickness{0.}; //!< the thickness of material - float m_dInX0{0.}; //!< thickness in units of radiation length - float m_dInL0{0.}; //!< thickness in units of nucl. interaction length + float zOverAtimesRho() const; + + protected: + Material m_material{}; //!< the material description + float m_thickness{0.}; //!< the thickness of material + float m_dInX0{0.}; //!< thickness in units of radiation length + float m_dInL0{0.}; //!< thickness in units of nucl. interaction length }; -inline const Material& -MaterialProperties::material() const -{ +inline const Material& MaterialProperties::material() const { return m_material; } -inline float -MaterialProperties::thicknessInX0() const -{ +inline float MaterialProperties::thicknessInX0() const { return m_dInX0; } -inline float -MaterialProperties::thicknessInL0() const -{ +inline float MaterialProperties::thicknessInL0() const { return m_dInL0; } -inline float -MaterialProperties::thickness() const -{ +inline float MaterialProperties::thickness() const { return m_thickness; } -inline float -MaterialProperties::zOverAtimesRho() const -{ +inline float MaterialProperties::zOverAtimesRho() const { return m_material.zOverAtimesRho(); } -inline float -MaterialProperties::averageX0() const -{ +inline float MaterialProperties::averageX0() const { return m_material.X0(); } -inline float -MaterialProperties::averageL0() const -{ +inline float MaterialProperties::averageL0() const { return m_material.L0(); } -inline float -MaterialProperties::averageA() const -{ +inline float MaterialProperties::averageA() const { return m_material.A(); } -inline float -MaterialProperties::averageZ() const -{ +inline float MaterialProperties::averageZ() const { return m_material.Z(); } -inline float -MaterialProperties::averageRho() const -{ +inline float MaterialProperties::averageRho() const { return m_material.rho(); } -inline bool -MaterialProperties::operator==(const MaterialProperties& mprop) const -{ - return (m_material == mprop.m_material && m_dInX0 == mprop.m_dInX0 - && m_dInL0 == mprop.m_dInL0); +inline bool MaterialProperties::operator==( + const MaterialProperties& mprop) const { + return (m_material == mprop.m_material && m_dInX0 == mprop.m_dInX0 && + m_dInL0 == mprop.m_dInL0); } -inline bool -MaterialProperties::operator!=(const MaterialProperties& mprop) const -{ +inline bool MaterialProperties::operator!=( + const MaterialProperties& mprop) const { return (!operator==(mprop)); } // Overload of << operator for std::ostream for debug output -std::ostream& -operator<<(std::ostream& sl, const MaterialProperties& mprop); +std::ostream& operator<<(std::ostream& sl, const MaterialProperties& mprop); // Useful typedefs using MaterialPropertiesVector = std::vector<MaterialProperties>; using MaterialPropertiesMatrix = std::vector<MaterialPropertiesVector>; -} // namespace +} // namespace Acts diff --git a/Core/include/Acts/Material/ProtoSurfaceMaterial.hpp b/Core/include/Acts/Material/ProtoSurfaceMaterial.hpp index 43242cf2e30640bb4addb678e473dc95b0d2d464..9ef427ae9eafdab162e6d52f1931523732364bc8 100644 --- a/Core/include/Acts/Material/ProtoSurfaceMaterial.hpp +++ b/Core/include/Acts/Material/ProtoSurfaceMaterial.hpp @@ -25,9 +25,8 @@ namespace Acts { /// at construction time of the geometry and to hand over the granularity of /// of the material map with the bin Utility. -class ProtoSurfaceMaterial : public ISurfaceMaterial -{ -public: +class ProtoSurfaceMaterial : public ISurfaceMaterial { + public: /// Constructor without BinUtility - homogenous material ProtoSurfaceMaterial() = default; @@ -55,26 +54,21 @@ public: /// Assignment operator /// /// @param smproxy The source proxy - ProtoSurfaceMaterial& - operator=(const ProtoSurfaceMaterial& smproxy) - = default; + ProtoSurfaceMaterial& operator=(const ProtoSurfaceMaterial& smproxy) = + default; /// Assigment move operator /// /// @param smproxy The source proxy - ProtoSurfaceMaterial& - operator=(ProtoSurfaceMaterial&& smproxy) - = default; + ProtoSurfaceMaterial& operator=(ProtoSurfaceMaterial&& smproxy) = default; /// Scale operator /// /// @param - ProtoSurfaceMaterial& - operator*=(double scale) final; + ProtoSurfaceMaterial& operator*=(double scale) final; /// Return the BinUtility - const BinUtility& - binUtility() const; + const BinUtility& binUtility() const; /// Return method for full material description of the Surface - from local /// coordinates @@ -82,8 +76,7 @@ public: /// @param lp is local positioning vector /// /// @return will return dummy material - const MaterialProperties& - materialProperties(const Vector2D& lp) const final; + const MaterialProperties& materialProperties(const Vector2D& lp) const final; /// Return method for full material description of the Surface - from the /// global coordinates @@ -91,8 +84,7 @@ public: /// @param gp is the global positioning vector /// /// @return will return dummy material - const MaterialProperties& - materialProperties(const Vector3D& gp) const final; + const MaterialProperties& materialProperties(const Vector3D& gp) const final; /// Direct access via bins to the MaterialProperties /// @@ -100,14 +92,13 @@ public: /// @param ib1 indicates the seconf bin /// /// @return will return dummy material - const MaterialProperties& - materialProperties(size_t ib0, size_t ib1) const final; + const MaterialProperties& materialProperties(size_t ib0, + size_t ib1) const final; /// Output Method for std::ostream, to be overloaded by child classes - std::ostream& - toStream(std::ostream& sl) const final; + std::ostream& toStream(std::ostream& sl) const final; -private: + private: /// two dimensional BinUtility determining /// the granularity and binning of the /// material on the surface/layer @@ -116,29 +107,24 @@ private: /// Dummy material properties MaterialProperties m_materialProperties; }; -} +} // namespace Acts inline const Acts::MaterialProperties& -Acts::ProtoSurfaceMaterial::materialProperties(const Vector2D& /*lp*/) const -{ +Acts::ProtoSurfaceMaterial::materialProperties(const Vector2D& /*lp*/) const { return (m_materialProperties); } inline const Acts::MaterialProperties& -Acts::ProtoSurfaceMaterial::materialProperties(const Vector3D& /*gp*/) const -{ +Acts::ProtoSurfaceMaterial::materialProperties(const Vector3D& /*gp*/) const { return (m_materialProperties); } inline const Acts::MaterialProperties& - Acts::ProtoSurfaceMaterial::materialProperties(size_t /*ib0*/, - size_t /*ib1*/) const -{ +Acts::ProtoSurfaceMaterial::materialProperties(size_t /*ib0*/, + size_t /*ib1*/) const { return (m_materialProperties); } -inline const Acts::BinUtility& -Acts::ProtoSurfaceMaterial::binUtility() const -{ +inline const Acts::BinUtility& Acts::ProtoSurfaceMaterial::binUtility() const { return m_binUtility; } \ No newline at end of file diff --git a/Core/include/Acts/Material/SurfaceMaterialMapper.hpp b/Core/include/Acts/Material/SurfaceMaterialMapper.hpp index 0be8a99dc514fe0f0c0a74d419169db48ddf0bee..03a03c756a34b2a6a3dae7902773253208f8471f 100644 --- a/Core/include/Acts/Material/SurfaceMaterialMapper.hpp +++ b/Core/include/Acts/Material/SurfaceMaterialMapper.hpp @@ -30,11 +30,8 @@ namespace Acts { class TrackingGeometry; /// @brief selector for finding -struct MaterialSurface -{ - bool - operator()(const Surface& sf) const - { +struct MaterialSurface { + bool operator()(const Surface& sf) const { return (sf.surfaceMaterial() != nullptr); } }; @@ -64,16 +61,14 @@ struct MaterialSurface /// /// 4) Each 'hit' bin per event is counted and averaged at the end of the run /// -class SurfaceMaterialMapper -{ -public: +class SurfaceMaterialMapper { + public: using StraightLinePropagator = Propagator<StraightLineStepper, Navigator>; /// @struct Config /// /// Nested Configuration struct for the material mapper - struct Config - { + struct Config { /// Mapping range std::array<double, 2> etaRange = {{-6., 6.}}; /// Mapping output to debug stream @@ -83,15 +78,11 @@ public: /// @struct State /// /// Nested State struct which is used for the mapping prococess - struct State - { - + struct State { /// Constructor of the Sate with contexts - State(std::reference_wrapper<const GeometryContext> gctx, + State(std::reference_wrapper<const GeometryContext> gctx, std::reference_wrapper<const MagneticFieldContext> mctx) - : geoContext(gctx), magFieldContext(mctx) - { - } + : geoContext(gctx), magFieldContext(mctx) {} /// The accumulated material per geometry ID std::map<GeometryID, AccumulatedSurfaceMaterial> accumulatedMaterial; @@ -115,11 +106,10 @@ public: /// @param cfg Configuration struct /// @param propagator The straight line propagator /// @param log The logger - SurfaceMaterialMapper(const Config& cfg, - StraightLinePropagator propagator, - std::unique_ptr<const Logger> slogger - = getDefaultLogger("SurfaceMaterialMapper", - Logging::INFO)); + SurfaceMaterialMapper(const Config& cfg, StraightLinePropagator propagator, + std::unique_ptr<const Logger> slogger = + getDefaultLogger("SurfaceMaterialMapper", + Logging::INFO)); /// @brief helper method that creates the cache for the mapping /// @@ -128,10 +118,9 @@ public: /// This method takes a TrackingGeometry, /// finds all surfaces with material proxis /// and returns you a Cache object tO be used - State - createState(const GeometryContext& gctx, - const MagneticFieldContext& mctx, - const TrackingGeometry& tGeometry) const; + State createState(const GeometryContext& gctx, + const MagneticFieldContext& mctx, + const TrackingGeometry& tGeometry) const; /// @brief Method to finalize the maps /// @@ -140,8 +129,7 @@ public: /// class type /// /// @param mState - void - finalizeMaps(State& mState) const; + void finalizeMaps(State& mState) const; /// Process/map a single track /// @@ -150,30 +138,25 @@ public: /// /// @note the RecordedMaterialProperties of the track are assumed /// to be ordered from the starting position along the starting direction - void - mapMaterialTrack(State& mState, const RecordedMaterialTrack& mTrack) const; + void mapMaterialTrack(State& mState, + const RecordedMaterialTrack& mTrack) const; -private: + private: /// @brief finds all surfaces with ProtoSurfaceMaterial of a volume /// /// @param mState The state to be filled /// @param tVolume is current TrackingVolume - void - resolveMaterialSurfaces(State& mState, const TrackingVolume& tVolume) const; + void resolveMaterialSurfaces(State& mState, + const TrackingVolume& tVolume) const; /// @brief check and insert /// /// @param mState is the map to be filled /// @param surface is the surface to be checked for a Proxy - void - checkAndInsert(State& /*mState*/, const Surface& surface) const; + void checkAndInsert(State& /*mState*/, const Surface& surface) const; /// Standard logger method - const Logger& - logger() const - { - return *m_logger; - } + const Logger& logger() const { return *m_logger; } /// The configuration object Config m_cfg; @@ -184,4 +167,4 @@ private: /// The logging instance std::unique_ptr<const Logger> m_logger; }; -} +} // namespace Acts diff --git a/Core/include/Acts/Material/VolumeMaterialMapper.hpp b/Core/include/Acts/Material/VolumeMaterialMapper.hpp index 86da1f3b771c44ecf8799301e0e8a43757df24c3..0ed00c40fa1ed2aca3559ad419dd7ec9504e6ac7 100644 --- a/Core/include/Acts/Material/VolumeMaterialMapper.hpp +++ b/Core/include/Acts/Material/VolumeMaterialMapper.hpp @@ -34,18 +34,15 @@ namespace Acts { /// @return The map detail::Grid<ActsVectorF<5>, detail::EquidistantAxis, detail::EquidistantAxis> createMaterialGrid( - std::array<double, 3> gridAxis1, - std::array<double, 3> gridAxis2, + std::array<double, 3> gridAxis1, std::array<double, 3> gridAxis2, const std::vector<std::pair<Material, Vector3D>>& mPoints, - const std::function<detail::Grid<ActsVectorF<5>, - detail::EquidistantAxis, - detail::EquidistantAxis>:: - index_t( - const Vector3D&, - const detail::Grid<AccumulatedVolumeMaterial, - detail::EquidistantAxis, - detail::EquidistantAxis>&)>& - matchToGridPoint); + const std::function< + detail::Grid<ActsVectorF<5>, detail::EquidistantAxis, + detail::EquidistantAxis>:: + index_t(const Vector3D&, + const detail::Grid< + AccumulatedVolumeMaterial, detail::EquidistantAxis, + detail::EquidistantAxis>&)>& matchToGridPoint); /// @brief This function creates a discrete material map /// @@ -59,24 +56,18 @@ createMaterialGrid( /// of @p mPoints to the grid points by its local index /// /// @return The map -detail::Grid<ActsVectorF<5>, - detail::EquidistantAxis, - detail::EquidistantAxis, +detail::Grid<ActsVectorF<5>, detail::EquidistantAxis, detail::EquidistantAxis, detail::EquidistantAxis> createMaterialGrid( - std::array<double, 3> gridAxis1, - std::array<double, 3> gridAxis2, - std::array<double, 3> gridAxis3, + std::array<double, 3> gridAxis1, std::array<double, 3> gridAxis2, + std::array<double, 3> gridAxis3, const std::vector<std::pair<Material, Vector3D>>& mPoints, - const std::function<detail::Grid<ActsVectorF<5>, - detail::EquidistantAxis, - detail::EquidistantAxis, - detail::EquidistantAxis>:: - index_t( - const Vector3D&, - const detail::Grid<AccumulatedVolumeMaterial, - detail::EquidistantAxis, - detail::EquidistantAxis, - detail::EquidistantAxis>&)>& + const std::function< + detail::Grid<ActsVectorF<5>, detail::EquidistantAxis, + detail::EquidistantAxis, detail::EquidistantAxis>:: + index_t(const Vector3D&, + const detail::Grid< + AccumulatedVolumeMaterial, detail::EquidistantAxis, + detail::EquidistantAxis, detail::EquidistantAxis>&)>& matchToGridPoint); } // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Propagator/AbortList.hpp b/Core/include/Acts/Propagator/AbortList.hpp index 154e8c6cc0031baca2e7be080d3ee81320fc70e4..b30e8d0fbee45b519c80a3ec7d723bcaa8b9664f 100644 --- a/Core/include/Acts/Propagator/AbortList.hpp +++ b/Core/include/Acts/Propagator/AbortList.hpp @@ -30,15 +30,14 @@ namespace Acts { /// It can (optionally) depend on a result of an Actor from /// the actor list. template <typename... aborters_t> -struct AbortList : public detail::Extendable<aborters_t...> -{ -private: +struct AbortList : public detail::Extendable<aborters_t...> { + private: static_assert(not detail::has_duplicates_v<aborters_t...>, "same aborter type specified several times"); using detail::Extendable<aborters_t...>::tuple; -public: + public: // This uses the type collector using result_type = typename decltype(hana::unpack( detail::type_collector_t<detail::action_type_extractor, aborters_t...>, @@ -62,40 +61,32 @@ public: /// Default move assignment operator /// /// @param aborters The source action list - AbortList<aborters_t...>& - operator=(const AbortList<aborters_t...>& aborters) - = default; + AbortList<aborters_t...>& operator=( + const AbortList<aborters_t...>& aborters) = default; /// Default move assignment operator /// /// @param aborters The source action list - AbortList<aborters_t...>& - operator=(AbortList<aborters_t...>&& aborters) - = default; + AbortList<aborters_t...>& operator=(AbortList<aborters_t...>&& aborters) = + default; /// Constructor from tuple /// /// @param extensions Source extensions tuple AbortList(const std::tuple<aborters_t...>& aborters) - : detail::Extendable<aborters_t...>(aborters) - { - } + : detail::Extendable<aborters_t...>(aborters) {} /// Constructor from tuple move /// /// @param extensions Source extensions tuple AbortList(std::tuple<aborters_t...>&& aborters) - : detail::Extendable<aborters_t...>(std::move(aborters)) - { - } + : detail::Extendable<aborters_t...>(std::move(aborters)) {} /// Append new entries and return a new condition template <typename... appendices_t> - AbortList<aborters_t..., appendices_t...> - append(appendices_t... aps) const - { - auto catTuple - = std::tuple_cat(tuple(), std::tuple<appendices_t...>(aps...)); + AbortList<aborters_t..., appendices_t...> append(appendices_t... aps) const { + auto catTuple = + std::tuple_cat(tuple(), std::tuple<appendices_t...>(aps...)); return AbortList<aborters_t..., appendices_t...>(std::move(catTuple)); } @@ -110,11 +101,8 @@ public: /// @param [in,out] state is the state object from the propagator /// @param [in] stepper Stepper used for the propagation template <typename result_t, typename propagator_state_t, typename stepper_t> - bool - operator()(const result_t& result, - propagator_state_t& state, - const stepper_t& stepper) const - { + bool operator()(const result_t& result, propagator_state_t& state, + const stepper_t& stepper) const { // clang-format off static_assert(detail::all_of_v<detail::abort_condition_signature_check_v< aborters_t, @@ -122,8 +110,8 @@ public: "not all aborters support the specified input"); // clang-format on - return detail::abort_list_impl<aborters_t...>::check( - tuple(), result, state, stepper); + return detail::abort_list_impl<aborters_t...>::check(tuple(), result, state, + stepper); } }; diff --git a/Core/include/Acts/Propagator/ActionList.hpp b/Core/include/Acts/Propagator/ActionList.hpp index b1019aa1666e775795cd668b689984ce46d1394a..d82c208559ef68ceea6d1607f97a85c87ae7fbd0 100644 --- a/Core/include/Acts/Propagator/ActionList.hpp +++ b/Core/include/Acts/Propagator/ActionList.hpp @@ -28,15 +28,14 @@ namespace Acts { /// to define a list of different actors_t that are eacch /// executed during the stepping procedure template <typename... actors_t> -struct ActionList : public detail::Extendable<actors_t...> -{ -private: +struct ActionList : public detail::Extendable<actors_t...> { + private: static_assert(not detail::has_duplicates_v<actors_t...>, "same action type specified several times"); using detail::Extendable<actors_t...>::tuple; -public: + public: // This uses the type collector and unpacks using the `R` meta funciton template <template <typename...> class R> using result_type = typename decltype(hana::unpack( @@ -61,16 +60,14 @@ public: /// Default move assignment operator /// /// @param actors The source action list - ActionList<actors_t...>& - operator=(const ActionList<actors_t...>& actors) - = default; + ActionList<actors_t...>& operator=(const ActionList<actors_t...>& actors) = + default; /// Default move assignment operator /// /// @param actors The source action list - ActionList<actors_t...>& - operator=(ActionList<actors_t...>&& actors) - = default; + ActionList<actors_t...>& operator=(ActionList<actors_t...>&& actors) = + default; /// Call operator that is that broadcasts the call to the tuple() /// members of the list @@ -85,11 +82,8 @@ public: /// /// @return bool type indiciating if the step size can be released template <typename propagator_state_t, typename stepper_t, typename result_t> - void - operator()(propagator_state_t& state, - const stepper_t& stepper, - result_t& result) const - { + void operator()(propagator_state_t& state, const stepper_t& stepper, + result_t& result) const { // clang-format off static_assert(detail::all_of_v<detail::action_signature_check_v<actors_t, propagator_state_t, stepper_t>...>, diff --git a/Core/include/Acts/Propagator/DefaultExtension.hpp b/Core/include/Acts/Propagator/DefaultExtension.hpp index 8a246ffdd123e7fdf61b6e1e22096b838890737e..0bddd3c8ac12eae658b37de942d1fc94b795023f 100644 --- a/Core/include/Acts/Propagator/DefaultExtension.hpp +++ b/Core/include/Acts/Propagator/DefaultExtension.hpp @@ -14,8 +14,7 @@ namespace Acts { /// @brief Default evaluater of the k_i's and elements of the transport matrix /// D of the RKN4 stepping. This is a pure implementation by textbook. -struct DefaultExtension -{ +struct DefaultExtension { /// @brief Default constructor DefaultExtension() = default; @@ -31,9 +30,8 @@ struct DefaultExtension /// @tparam stepper_t Type of the stepper /// @return Boolean flag if the step would be valid template <typename propagator_state_t, typename stepper_t> - int - bid(const propagator_state_t& /*unused*/, const stepper_t& /*unused*/) const - { + int bid(const propagator_state_t& /*unused*/, + const stepper_t& /*unused*/) const { return 1; } @@ -51,26 +49,20 @@ struct DefaultExtension /// @param [in] kprev Evaluated k_{i - 1} /// @return Boolean flag if the calculation is valid template <typename propagator_state_t, typename stepper_t> - bool - k(const propagator_state_t& state, - const stepper_t& stepper, - Vector3D& knew, - const Vector3D& bField, - const int i = 0, - const double h = 0., - const Vector3D& kprev = Vector3D()) - { + bool k(const propagator_state_t& state, const stepper_t& stepper, + Vector3D& knew, const Vector3D& bField, const int i = 0, + const double h = 0., const Vector3D& kprev = Vector3D()) { // First step does not rely on previous data if (i == 0) { // Store qop, it is always used if valid - qop = stepper.charge(state.stepping) - / units::Nat2SI<units::MOMENTUM>(stepper.momentum(state.stepping)); + qop = stepper.charge(state.stepping) / + units::Nat2SI<units::MOMENTUM>(stepper.momentum(state.stepping)); // Evaluate the k_i knew = qop * stepper.direction(state.stepping).cross(bField); } else { - knew - = qop * (stepper.direction(state.stepping) + h * kprev).cross(bField); + knew = + qop * (stepper.direction(state.stepping) + h * kprev).cross(bField); } return true; } @@ -83,11 +75,8 @@ struct DefaultExtension /// @tparam stepper_t Type of the stepper /// @return Boolean flag if the calculation is valid template <typename propagator_state_t, typename stepper_t> - bool - finalize(propagator_state_t& /*unused*/, - const stepper_t& /*unused*/, - const double /*unused*/) const - { + bool finalize(propagator_state_t& /*unused*/, const stepper_t& /*unused*/, + const double /*unused*/) const { return true; } @@ -103,16 +92,12 @@ struct DefaultExtension /// @param [out] D Transport matrix /// @return Boolean flag if the calculation is valid template <typename propagator_state_t, typename stepper_t> - bool - finalize(propagator_state_t& state, - const stepper_t& stepper, - const double h, - ActsMatrixD<7, 7>& D) const - { + bool finalize(propagator_state_t& state, const stepper_t& stepper, + const double h, ActsMatrixD<7, 7>& D) const { return transportMatrix(state, stepper, h, D); } -private: + private: /// @brief Calculates the transport matrix D for the jacobian /// /// @tparam propagator_state_t Type of the state of the propagator @@ -123,12 +108,8 @@ private: /// @param [out] D Transport matrix /// @return Boolean flag if evaluation is valid template <typename propagator_state_t, typename stepper_t> - bool - transportMatrix(propagator_state_t& state, - const stepper_t& stepper, - const double h, - ActsMatrixD<7, 7>& D) const - { + bool transportMatrix(propagator_state_t& state, const stepper_t& stepper, + const double h, ActsMatrixD<7, 7>& D) const { /// The calculations are based on ATL-SOFT-PUB-2009-002. The update of the /// Jacobian matrix is requires only the calculation of eq. 17 and 18. /// Since the terms of eq. 18 are currently 0, this matrix is not needed @@ -148,8 +129,8 @@ private: /// constant offset does not exist for rectangular matrix dGdu' (due to the /// missing Lambda part) and only exists for dFdu' in dlambda/dlambda. - auto& sd = state.stepping.stepData; - auto dir = stepper.direction(state.stepping); + auto& sd = state.stepping.stepData; + auto dir = stepper.direction(state.stepping); D = ActsMatrixD<7, 7>::Identity(); @@ -174,12 +155,12 @@ private: // For the case without energy loss dk1dL = dir.cross(sd.B_first); - dk2dL = (dir + half_h * sd.k1).cross(sd.B_middle) - + qop * half_h * dk1dL.cross(sd.B_middle); - dk3dL = (dir + half_h * sd.k2).cross(sd.B_middle) - + qop * half_h * dk2dL.cross(sd.B_middle); - dk4dL - = (dir + h * sd.k3).cross(sd.B_last) + qop * h * dk3dL.cross(sd.B_last); + dk2dL = (dir + half_h * sd.k1).cross(sd.B_middle) + + qop * half_h * dk1dL.cross(sd.B_middle); + dk3dL = (dir + half_h * sd.k2).cross(sd.B_middle) + + qop * half_h * dk2dL.cross(sd.B_middle); + dk4dL = + (dir + h * sd.k3).cross(sd.B_last) + qop * h * dk3dL.cross(sd.B_last); dk1dT(0, 1) = sd.B_first.z(); dk1dT(0, 2) = -sd.B_first.y(); diff --git a/Core/include/Acts/Propagator/DenseEnvironmentExtension.hpp b/Core/include/Acts/Propagator/DenseEnvironmentExtension.hpp index a99d20c5916895d99a62654190ee47a120f24dca..4cb2580b989f2a8229d5187badb0b0d9bc9231fc 100644 --- a/Core/include/Acts/Propagator/DenseEnvironmentExtension.hpp +++ b/Core/include/Acts/Propagator/DenseEnvironmentExtension.hpp @@ -22,9 +22,7 @@ namespace Acts { /// ioninisation, bremsstrahlung, pair production and photonuclear interaction /// in the propagation and the jacobian. These effects will only occur if the /// propagation is in a TrackingVolume with attached material. -struct DenseEnvironmentExtension -{ - +struct DenseEnvironmentExtension { /// Momentum at a certain point double currentMomentum = 0.; /// Particles momentum at k1 @@ -49,7 +47,7 @@ struct DenseEnvironmentExtension /// Energy loss calculator static const detail::IonisationLoss ionisationLoss; - static const detail::RadiationLoss radiationLoss; + static const detail::RadiationLoss radiationLoss; /// @brief Default constructor DenseEnvironmentExtension() = default; @@ -61,19 +59,17 @@ struct DenseEnvironmentExtension /// @param [in] state State of the propagator /// @return Boolean flag if the step would be valid template <typename propagator_state_t, typename stepper_t> - int - bid(const propagator_state_t& state, const stepper_t& stepper) const - { + int bid(const propagator_state_t& state, const stepper_t& stepper) const { // Check for valid particle properties - if (stepper.charge(state.stepping) == 0. || state.options.mass == 0. - || stepper.momentum(state.stepping) - < conv * state.options.momentumCutOff) { + if (stepper.charge(state.stepping) == 0. || state.options.mass == 0. || + stepper.momentum(state.stepping) < + conv * state.options.momentumCutOff) { return 0; } // Check existence of a volume with material - if (!state.navigation.currentVolume - || !state.navigation.currentVolume->volumeMaterial()) { + if (!state.navigation.currentVolume || + !state.navigation.currentVolume->volumeMaterial()) { return 0; } return 2; @@ -92,26 +88,20 @@ struct DenseEnvironmentExtension /// @param [in] kprev Evaluated k_{i - 1} /// @return Boolean flag if the calculation is valid template <typename propagator_state_t, typename stepper_t> - bool - k(const propagator_state_t& state, - const stepper_t& stepper, - Vector3D& knew, - const Vector3D& bField, - const int i = 0, - const double h = 0., - const Vector3D& kprev = Vector3D()) - { + bool k(const propagator_state_t& state, const stepper_t& stepper, + Vector3D& knew, const Vector3D& bField, const int i = 0, + const double h = 0., const Vector3D& kprev = Vector3D()) { // i = 0 is used for setup and evaluation of k if (i == 0) { // Set up container for energy loss auto volumeMaterial = state.navigation.currentVolume->volumeMaterial(); - Vector3D position = stepper.position(state.stepping); - massSI = units::Nat2SI<units::MASS>(state.options.mass); - material = &(volumeMaterial->material(position)); - initialMomentum - = units::Nat2SI<units::MOMENTUM>(stepper.momentum(state.stepping)); + Vector3D position = stepper.position(state.stepping); + massSI = units::Nat2SI<units::MASS>(state.options.mass); + material = &(volumeMaterial->material(position)); + initialMomentum = + units::Nat2SI<units::MOMENTUM>(stepper.momentum(state.stepping)); currentMomentum = initialMomentum; - qop[0] = stepper.charge(state.stepping) / initialMomentum; + qop[0] = stepper.charge(state.stepping) / initialMomentum; initializeEnergyLoss(state); // Evaluate k knew = qop[0] * stepper.direction(state.stepping).cross(bField); @@ -122,8 +112,8 @@ struct DenseEnvironmentExtension return false; } // Evaluate k - knew = qop[i] - * (stepper.direction(state.stepping) + h * kprev).cross(bField); + knew = qop[i] * + (stepper.direction(state.stepping) + h * kprev).cross(bField); } return true; } @@ -139,27 +129,25 @@ struct DenseEnvironmentExtension /// @param [in] h Step size /// @return Boolean flag if the calculation is valid template <typename propagator_state_t, typename stepper_t> - bool - finalize(propagator_state_t& state, - const stepper_t& stepper, - const double h) const - { + bool finalize(propagator_state_t& state, const stepper_t& stepper, + const double h) const { // Evaluate the new momentum - double newMomentum = stepper.momentum(state.stepping) - + conv * (h / 6.) * (dPds[0] + 2. * (dPds[1] + dPds[2]) + dPds[3]); + double newMomentum = + stepper.momentum(state.stepping) + + conv * (h / 6.) * (dPds[0] + 2. * (dPds[1] + dPds[2]) + dPds[3]); // Break propagation if momentum becomes below cut-off - if (units::Nat2SI<units::MOMENTUM>(newMomentum) - < state.options.momentumCutOff) { + if (units::Nat2SI<units::MOMENTUM>(newMomentum) < + state.options.momentumCutOff) { return false; } // Add derivative dlambda/ds = Lambda'' - state.stepping.derivative(6) - = -std::sqrt(state.options.mass * state.options.mass - + newMomentum * newMomentum) - * units::SI2Nat<units::ENERGY>(g) - / (newMomentum * newMomentum * newMomentum); + state.stepping.derivative(6) = + -std::sqrt(state.options.mass * state.options.mass + + newMomentum * newMomentum) * + units::SI2Nat<units::ENERGY>(g) / + (newMomentum * newMomentum * newMomentum); // Update momentum state.stepping.p = newMomentum; @@ -181,16 +169,12 @@ struct DenseEnvironmentExtension /// @param [out] D Transport matrix /// @return Boolean flag if the calculation is valid template <typename propagator_state_t, typename stepper_t> - bool - finalize(propagator_state_t& state, - const stepper_t& stepper, - const double h, - ActsMatrixD<7, 7>& D) const - { + bool finalize(propagator_state_t& state, const stepper_t& stepper, + const double h, ActsMatrixD<7, 7>& D) const { return finalize(state, stepper, h) && transportMatrix(state, stepper, h, D); } -private: + private: /// @brief Evaluates the transport matrix D for the jacobian /// /// @tparam propagator_state_t Type of the state of the propagator @@ -200,12 +184,8 @@ private: /// @param [out] D Transport matrix /// @return Boolean flag if evaluation is valid template <typename propagator_state_t, typename stepper_t> - bool - transportMatrix(propagator_state_t& state, - const stepper_t& stepper, - const double h, - ActsMatrixD<7, 7>& D) const - { + bool transportMatrix(propagator_state_t& state, const stepper_t& stepper, + const double h, ActsMatrixD<7, 7>& D) const { /// The calculations are based on ATL-SOFT-PUB-2009-002. The update of the /// Jacobian matrix is requires only the calculation of eq. 17 and 18. /// Since the terms of eq. 18 are currently 0, this matrix is not needed @@ -226,10 +206,10 @@ private: /// constant offset does not exist for rectangular matrix dFdu' (due to the /// missing Lambda part) and only exists for dGdu' in dlambda/dlambda. - auto& sd = state.stepping.stepData; - auto dir = stepper.direction(state.stepping); + auto& sd = state.stepping.stepData; + auto dir = stepper.direction(state.stepping); - D = ActsMatrixD<7, 7>::Identity(); + D = ActsMatrixD<7, 7>::Identity(); const double half_h = h * 0.5; // This sets the reference to the sub matrices @@ -255,16 +235,16 @@ private: // Evaluation of the rightmost column without the last term. jdL[0] = dLdl[0]; - dk1dL = dir.cross(sd.B_first); + dk1dL = dir.cross(sd.B_first); jdL[1] = dLdl[1] * (1. + half_h * jdL[0]); - dk2dL = (1. + half_h * jdL[0]) * (dir + half_h * sd.k1).cross(sd.B_middle) - + qop[1] * half_h * dk1dL.cross(sd.B_middle); + dk2dL = (1. + half_h * jdL[0]) * (dir + half_h * sd.k1).cross(sd.B_middle) + + qop[1] * half_h * dk1dL.cross(sd.B_middle); jdL[2] = dLdl[2] * (1. + half_h * jdL[1]); - dk3dL = (1. + half_h * jdL[1]) * (dir + half_h * sd.k2).cross(sd.B_middle) - + qop[2] * half_h * dk2dL.cross(sd.B_middle); + dk3dL = (1. + half_h * jdL[1]) * (dir + half_h * sd.k2).cross(sd.B_middle) + + qop[2] * half_h * dk2dL.cross(sd.B_middle); jdL[3] = dLdl[3] * (1. + h * jdL[2]); - dk4dL = (1. + h * jdL[2]) * (dir + h * sd.k3).cross(sd.B_last) - + qop[3] * h * dk3dL.cross(sd.B_last); + dk4dL = (1. + h * jdL[2]) * (dir + h * sd.k3).cross(sd.B_last) + + qop[3] * h * dk3dL.cross(sd.B_last); dk1dT(0, 1) = sd.B_first.z(); dk1dT(0, 2) = -sd.B_first.y(); @@ -311,12 +291,8 @@ private: /// @param [in] meanEnergyLoss Boolean indicator if mean or mode of the energy /// loss will be evaluated /// @return Infinitesimal energy loss - double - dEds(const double momentum, - const double energy, - const int pdg, - const bool meanEnergyLoss) const - { + double dEds(const double momentum, const double energy, const int pdg, + const bool meanEnergyLoss) const { // Easy exit if material is invalid if (material->X0() == 0 || material->Z() == 0) { return 0.; @@ -324,18 +300,15 @@ private: // Calculate energy loss by // a) ionisation - double ionisationEnergyLoss = ionisationLoss - .dEds(massSI, - momentum * units::_c / energy, - energy / (massSI * units::_c2), - *(material), - 1., - meanEnergyLoss, - true) - .first; + double ionisationEnergyLoss = + ionisationLoss + .dEds(massSI, momentum * units::_c / energy, + energy / (massSI * units::_c2), *(material), 1., + meanEnergyLoss, true) + .first; // b) radiation - double radiationEnergyLoss - = radiationLoss.dEds(energy, massSI, *(material), pdg, 1., true); + double radiationEnergyLoss = + radiationLoss.dEds(energy, massSI, *(material), pdg, 1., true); // Rescaling for mode evaluation. // C.f. ATL-SOFT-PUB-2008-003 section 3. The mode evaluation for the energy @@ -356,22 +329,21 @@ private: /// loss will be evaluated /// @return Derivative evaluated at the point defined by the /// function parameters - double - dgdqop(const double energy, const int pdg, const bool meanEnergyLoss) const - { + double dgdqop(const double energy, const int pdg, + const bool meanEnergyLoss) const { // Fast exit if material is invalid - if (material->X0() == 0. || material->Z() == 0. - || material->zOverAtimesRho() == 0.) { + if (material->X0() == 0. || material->Z() == 0. || + material->zOverAtimesRho() == 0.) { return 0.; } // Bethe-Bloch - const double betheBlochDerivative - = ionisationLoss.dqop(energy, qop[0], massSI, *(material), true, true); + const double betheBlochDerivative = + ionisationLoss.dqop(energy, qop[0], massSI, *(material), true, true); // Bethe-Heitler (+ pair production & photonuclear interaction for muons) - const double radiationDerivative - = radiationLoss.dqop(massSI, *(material), qop[0], energy, pdg, true); + const double radiationDerivative = + radiationLoss.dqop(massSI, *(material), qop[0], energy, pdg, true); // Return the total derivative if (meanEnergyLoss) { @@ -388,15 +360,11 @@ private: /// @tparam propagator_state_t Type of the state of the propagator /// @param [in] state Deliverer of configurations template <typename propagator_state_t> - void - initializeEnergyLoss(const propagator_state_t& state) - { - double E = std::sqrt(initialMomentum * initialMomentum * units::_c2 - + massSI * massSI * units::_c4); + void initializeEnergyLoss(const propagator_state_t& state) { + double E = std::sqrt(initialMomentum * initialMomentum * units::_c2 + + massSI * massSI * units::_c4); // Use the same energy loss throughout the step. - g = dEds(initialMomentum, - E, - state.options.absPdgCode, + g = dEds(initialMomentum, E, state.options.absPdgCode, state.options.meanEnergyLoss); // Change of the momentum per path length // dPds = dPdE * dEds @@ -405,19 +373,17 @@ private: // Calculate the change of the energy loss per path length and // inverse momentum if (state.options.includeGgradient) { - dgdqopValue = dgdqop( - E, - state.options.absPdgCode, - state.options - .meanEnergyLoss); // Use this value throughout the step. + dgdqopValue = + dgdqop(E, state.options.absPdgCode, + state.options + .meanEnergyLoss); // Use this value throughout the step. } // Calculate term for later error propagation - dLdl[0] = (-qop[0] * qop[0] * g * E - * (3. - - (initialMomentum * initialMomentum * units::_c2) - / (E * E)) - - qop[0] * qop[0] * qop[0] * E * dgdqopValue) - / units::_c2; + dLdl[0] = (-qop[0] * qop[0] * g * E * + (3. - (initialMomentum * initialMomentum * units::_c2) / + (E * E)) - + qop[0] * qop[0] * qop[0] * E * dgdqopValue) / + units::_c2; } } @@ -430,52 +396,43 @@ private: /// @param [in] state State of the stepper /// @param [in] i Index of the sub-step (1-3) template <typename stepper_state_t, typename stepper_t> - void - updateEnergyLoss(const double h, - const stepper_state_t& state, - const stepper_t& stepper, - const int i) - { + void updateEnergyLoss(const double h, const stepper_state_t& state, + const stepper_t& stepper, const int i) { // Update parameters related to a changed momentum currentMomentum = initialMomentum + h * dPds[i - 1]; - double E = std::sqrt(currentMomentum * currentMomentum * units::_c2 - + massSI * massSI * units::_c4); + double E = std::sqrt(currentMomentum * currentMomentum * units::_c2 + + massSI * massSI * units::_c4); dPds[i] = g * E / (currentMomentum * units::_c2); - qop[i] = stepper.charge(state) / currentMomentum; + qop[i] = stepper.charge(state) / currentMomentum; // Calculate term for later error propagation if (state.covTransport) { - dLdl[i] = (-qop[i] * qop[i] * g * E - * (3. - - (currentMomentum * currentMomentum * units::_c2) - / (E * E)) - - qop[i] * qop[i] * qop[i] * E * dgdqopValue) - / units::_c2; + dLdl[i] = (-qop[i] * qop[i] * g * E * + (3. - (currentMomentum * currentMomentum * units::_c2) / + (E * E)) - + qop[i] * qop[i] * qop[i] * E * dgdqopValue) / + units::_c2; } } }; -template <typename action_list_t = ActionList<>, +template <typename action_list_t = ActionList<>, typename aborter_list_t = AbortList<>> struct DenseStepperPropagatorOptions - : public PropagatorOptions<action_list_t, aborter_list_t> -{ - + : public PropagatorOptions<action_list_t, aborter_list_t> { /// Copy Constructor DenseStepperPropagatorOptions( - const DenseStepperPropagatorOptions<action_list_t, aborter_list_t>& dspo) - = default; + const DenseStepperPropagatorOptions<action_list_t, aborter_list_t>& + dspo) = default; /// Constructor with GeometryContext /// /// @param gctx The current geometry context object, e.g. alignment /// @param mctx The current magnetic fielc context object DenseStepperPropagatorOptions( - std::reference_wrapper<const GeometryContext> gctx, + std::reference_wrapper<const GeometryContext> gctx, std::reference_wrapper<const MagneticFieldContext> mctx) - : PropagatorOptions<action_list_t, aborter_list_t>(gctx, mctx) - { - } + : PropagatorOptions<action_list_t, aborter_list_t>(gctx, mctx) {} /// Toggle between mean and mode evaluation of energy loss bool meanEnergyLoss = true; @@ -492,33 +449,32 @@ struct DenseStepperPropagatorOptions /// /// @param aborters The new aborter list to be used (internally) template <typename extended_aborter_list_t> - DenseStepperPropagatorOptions<action_list_t, extended_aborter_list_t> - extend(extended_aborter_list_t aborters) const - { + DenseStepperPropagatorOptions<action_list_t, extended_aborter_list_t> extend( + extended_aborter_list_t aborters) const { DenseStepperPropagatorOptions<action_list_t, extended_aborter_list_t> eoptions(this->geoContext, this->magFieldContext); // Copy the options over - eoptions.direction = this->direction; - eoptions.absPdgCode = this->absPdgCode; - eoptions.mass = this->mass; - eoptions.maxSteps = this->maxSteps; - eoptions.maxStepSize = this->maxStepSize; + eoptions.direction = this->direction; + eoptions.absPdgCode = this->absPdgCode; + eoptions.mass = this->mass; + eoptions.maxSteps = this->maxSteps; + eoptions.maxStepSize = this->maxStepSize; eoptions.targetTolerance = this->targetTolerance; - eoptions.pathLimit = this->pathLimit; - eoptions.loopProtection = this->loopProtection; - eoptions.loopFraction = this->loopFraction; + eoptions.pathLimit = this->pathLimit; + eoptions.loopProtection = this->loopProtection; + eoptions.loopFraction = this->loopFraction; // Output option - eoptions.debug = this->debug; - eoptions.debugString = this->debugString; + eoptions.debug = this->debug; + eoptions.debugString = this->debugString; eoptions.debugPfxWidth = this->debugPfxWidth; eoptions.debugMsgWidth = this->debugMsgWidth; // Action / abort list eoptions.actionList = this->actionList; - eoptions.abortList = std::move(aborters); + eoptions.abortList = std::move(aborters); // Copy dense environment specific parameters - eoptions.meanEnergyLoss = meanEnergyLoss; + eoptions.meanEnergyLoss = meanEnergyLoss; eoptions.includeGgradient = includeGgradient; - eoptions.momentumCutOff = momentumCutOff; + eoptions.momentumCutOff = momentumCutOff; // And return the options return eoptions; } diff --git a/Core/include/Acts/Propagator/EigenStepper.hpp b/Core/include/Acts/Propagator/EigenStepper.hpp index 2081345fe56f486b845d1373987c2638056e4aa4..02f4b942bb64478b261dd0c2cea324a588795fe0 100644 --- a/Core/include/Acts/Propagator/EigenStepper.hpp +++ b/Core/include/Acts/Propagator/EigenStepper.hpp @@ -36,45 +36,38 @@ namespace Acts { /// with s being the arc length of the track, q the charge of the particle, /// p its momentum and B the magnetic field /// -template <typename BField, - typename corrector_t = VoidIntersectionCorrector, +template <typename BField, typename corrector_t = VoidIntersectionCorrector, typename extensionlist_t = StepperExtensionList<DefaultExtension>, - typename auctioneer_t = detail::VoidAuctioneer> -class EigenStepper -{ - -private: + typename auctioneer_t = detail::VoidAuctioneer> +class EigenStepper { + private: // This struct is a meta-function which normally maps to BoundParameters... template <typename T, typename S> - struct s - { + struct s { using type = BoundParameters; }; // ...unless type S is int, in which case it maps to Curvilinear parameters template <typename T> - struct s<T, int> - { + struct s<T, int> { using type = CurvilinearParameters; }; -public: - using cstep = detail::ConstrainedStep; + public: + using cstep = detail::ConstrainedStep; using Corrector = corrector_t; /// Jacobian, Covariance and State defintions - using Jacobian = ActsMatrixD<5, 5>; - using Covariance = ActsSymMatrixD<5>; - using BoundState = std::tuple<BoundParameters, Jacobian, double>; + using Jacobian = ActsMatrixD<5, 5>; + using Covariance = ActsSymMatrixD<5>; + using BoundState = std::tuple<BoundParameters, Jacobian, double>; using CurvilinearState = std::tuple<CurvilinearParameters, Jacobian, double>; /// @brief State for track parameter propagation /// /// It contains the stepping information and is provided thread local /// by the propagator - struct State - { - + struct State { /// Constructor from the initial track parameters /// /// @param [in] gctx is the context object for the geometry @@ -85,20 +78,18 @@ public: /// /// @note the covariance matrix is copied when needed template <typename parameters_t> - explicit State(std::reference_wrapper<const GeometryContext> gctx, + explicit State(std::reference_wrapper<const GeometryContext> gctx, std::reference_wrapper<const MagneticFieldContext> mctx, - const parameters_t& par, - NavigationDirection ndir = forward, + const parameters_t& par, NavigationDirection ndir = forward, double ssize = std::numeric_limits<double>::max()) - : pos(par.position()) - , dir(par.momentum().normalized()) - , p(par.momentum().norm()) - , q(par.charge()) - , navDir(ndir) - , stepSize(ndir * std::abs(ssize)) - , fieldCache(mctx) - , geoContext(gctx) - { + : pos(par.position()), + dir(par.momentum().normalized()), + p(par.momentum().norm()), + q(par.charge()), + navDir(ndir), + stepSize(ndir * std::abs(ssize)), + fieldCache(mctx), + geoContext(gctx) { // remember the start parameters startPos = pos; startDir = dir; @@ -108,9 +99,9 @@ public: const auto& surface = par.referenceSurface(); // set the covariance transport flag to true and copy covTransport = true; - cov = ActsSymMatrixD<5>(*par.covariance()); - surface.initJacobianToGlobal( - gctx, jacToGlobal, pos, dir, par.parameters()); + cov = ActsSymMatrixD<5>(*par.covariance()); + surface.initJacobianToGlobal(gctx, jacToGlobal, pos, dir, + par.parameters()); } } @@ -149,8 +140,8 @@ public: /// Covariance matrix (and indicator) //// associated with the initial error on track parameters - bool covTransport = false; - Covariance cov = Covariance::Zero(); + bool covTransport = false; + Covariance cov = Covariance::Zero(); /// accummulated path length state double pathAccumulated = 0.; @@ -173,8 +164,7 @@ public: auctioneer_t auctioneer; /// @brief Storage of magnetic field and the sub steps during a RKN4 step - struct - { + struct { /// Magnetic field evaulations Vector3D B_first, B_middle, B_last; /// k_i of the RKN4 algorithm @@ -197,40 +187,22 @@ public: /// @param [in,out] state is the propagation state associated with the track /// the magnetic field cell is used (and potentially updated) /// @param [in] pos is the field position - Vector3D - getField(State& state, const Vector3D& pos) const - { + Vector3D getField(State& state, const Vector3D& pos) const { // get the field from the cell return m_bField.getField(pos, state.fieldCache); } /// Global particle position accessor - Vector3D - position(const State& state) const - { - return state.pos; - } + Vector3D position(const State& state) const { return state.pos; } /// Momentum direction accessor - Vector3D - direction(const State& state) const - { - return state.dir; - } + Vector3D direction(const State& state) const { return state.dir; } /// Actual momentum accessor - double - momentum(const State& state) const - { - return state.p; - } + double momentum(const State& state) const { return state.p; } /// Charge access - double - charge(const State& state) const - { - return state.q; - } + double charge(const State& state) const { return state.q; } /// Tests if the state reached a surface /// @@ -238,11 +210,9 @@ public: /// @param [in] surface Surface that is tested /// /// @return Boolean statement if surface is reached by state - bool - surfaceReached(const State& state, const Surface* surface) const - { - return surface->isOnSurface( - state.geoContext, position(state), direction(state), true); + bool surfaceReached(const State& state, const Surface* surface) const { + return surface->isOnSurface(state.geoContext, position(state), + direction(state), true); } /// Create and return the bound state at the current position @@ -261,10 +231,8 @@ public: /// - the parameters at the surface /// - the stepwise jacobian towards it (from last bound) /// - and the path length (from start - for ordering) - BoundState - boundState(State& state, - const Surface& surface, - bool reinitialize = true) const; + BoundState boundState(State& state, const Surface& surface, + bool reinitialize = true) const; /// Create and return a curvilinear state at the current position /// @@ -279,15 +247,14 @@ public: /// - the curvilinear parameters at given position /// - the stepweise jacobian towards it (from last bound) /// - and the path length (from start - for ordering) - CurvilinearState - curvilinearState(State& state, bool reinitialize = true) const; + CurvilinearState curvilinearState(State& state, + bool reinitialize = true) const; /// Method to update a stepper state to the some parameters /// /// @param [in,out] state State object that will be updated /// @param [in] pars Parameters that will be written into @p state - void - update(State& state, const BoundParameters& pars) const; + void update(State& state, const BoundParameters& pars) const; /// Method to update momentum, direction and p /// @@ -295,16 +262,11 @@ public: /// @param [in] uposition the updated position /// @param [in] udirection the updated direction /// @param [in] up the updated momentum value - void - update(State& state, - const Vector3D& uposition, - const Vector3D& udirection, - double up) const; + void update(State& state, const Vector3D& uposition, + const Vector3D& udirection, double up) const; /// Return a corrector - corrector_t - corrector(State& state) const - { + corrector_t corrector(State& state) const { return corrector_t(state.startPos, state.startDir, state.pathAccumulated); } @@ -317,8 +279,7 @@ public: /// reinitialized at the new position /// /// @return the full transport jacobian - void - covarianceTransport(State& state, bool reinitialize = false) const; + void covarianceTransport(State& state, bool reinitialize = false) const; /// Method for on-demand transport of the covariance /// to a new curvilinear frame at current position, @@ -331,10 +292,8 @@ public: /// @param [in] reinitialize is a flag to steer whether the state should be /// reinitialized at the new position /// @note no check is done if the position is actually on the surface - void - covarianceTransport(State& state, - const Surface& surface, - bool reinitialize = true) const; + void covarianceTransport(State& state, const Surface& surface, + bool reinitialize = true) const; /// Perform a Runge-Kutta track parameter propagation step /// @@ -347,10 +306,9 @@ public: /// and since we're using an adaptive algorithm, it can /// be modified by the stepper class during propagation. template <typename propagator_state_t> - Result<double> - step(propagator_state_t& state) const; + Result<double> step(propagator_state_t& state) const; -private: + private: /// Magnetic field inside of the detector BField m_bField; }; diff --git a/Core/include/Acts/Propagator/EigenStepper.ipp b/Core/include/Acts/Propagator/EigenStepper.ipp index b6aa75497fe098512c29bbb5722f3454b78655b5..ba5491c9a1b8b5e9315a557fc7aa2a98c7c65435 100644 --- a/Core/include/Acts/Propagator/EigenStepper.ipp +++ b/Core/include/Acts/Propagator/EigenStepper.ipp @@ -8,17 +8,13 @@ template <typename B, typename C, typename E, typename A> Acts::EigenStepper<B, C, E, A>::EigenStepper(B bField) - : m_bField(std::move(bField)) -{ -} + : m_bField(std::move(bField)) {} template <typename B, typename C, typename E, typename A> -auto -Acts::EigenStepper<B, C, E, A>::boundState(State& state, - const Surface& surface, - bool reinitialize) const - -> BoundState -{ +auto Acts::EigenStepper<B, C, E, A>::boundState(State& state, + const Surface& surface, + bool reinitialize) const + -> BoundState { // Transport the covariance to here std::unique_ptr<const Covariance> covPtr = nullptr; if (state.covTransport) { @@ -26,15 +22,12 @@ Acts::EigenStepper<B, C, E, A>::boundState(State& state, covPtr = std::make_unique<const Covariance>(state.cov); } // Create the bound parameters - BoundParameters parameters(state.geoContext, - std::move(covPtr), - state.pos, - state.p * state.dir, - state.q, + BoundParameters parameters(state.geoContext, std::move(covPtr), state.pos, + state.p * state.dir, state.q, surface.getSharedPtr()); // Create the bound state - BoundState bState{ - std::move(parameters), state.jacobian, state.pathAccumulated}; + BoundState bState{std::move(parameters), state.jacobian, + state.pathAccumulated}; // Reset the jacobian to identity if (reinitialize) { state.jacobian = Jacobian::Identity(); @@ -44,11 +37,9 @@ Acts::EigenStepper<B, C, E, A>::boundState(State& state, } template <typename B, typename C, typename E, typename A> -auto -Acts::EigenStepper<B, C, E, A>::curvilinearState(State& state, - bool reinitialize) const - -> CurvilinearState -{ +auto Acts::EigenStepper<B, C, E, A>::curvilinearState(State& state, + bool reinitialize) const + -> CurvilinearState { // Transport the covariance to here std::unique_ptr<const Covariance> covPtr = nullptr; if (state.covTransport) { @@ -56,11 +47,11 @@ Acts::EigenStepper<B, C, E, A>::curvilinearState(State& state, covPtr = std::make_unique<const Covariance>(state.cov); } // Create the curvilinear parameters - CurvilinearParameters parameters( - std::move(covPtr), state.pos, state.p * state.dir, state.q); + CurvilinearParameters parameters(std::move(covPtr), state.pos, + state.p * state.dir, state.q); // Create the bound state - CurvilinearState curvState{ - std::move(parameters), state.jacobian, state.pathAccumulated}; + CurvilinearState curvState{std::move(parameters), state.jacobian, + state.pathAccumulated}; // Reset the jacobian to identity if (reinitialize) { state.jacobian = Jacobian::Identity(); @@ -70,46 +61,40 @@ Acts::EigenStepper<B, C, E, A>::curvilinearState(State& state, } template <typename B, typename C, typename E, typename A> -void -Acts::EigenStepper<B, C, E, A>::update(State& state, - const BoundParameters& pars) const -{ +void Acts::EigenStepper<B, C, E, A>::update(State& state, + const BoundParameters& pars) const { const auto& mom = pars.momentum(); - state.pos = pars.position(); - state.dir = mom.normalized(); - state.p = mom.norm(); + state.pos = pars.position(); + state.dir = mom.normalized(); + state.p = mom.norm(); if (pars.covariance() != nullptr) { state.cov = (*(pars.covariance())); } } template <typename B, typename C, typename E, typename A> -void -Acts::EigenStepper<B, C, E, A>::update(State& state, - const Vector3D& uposition, - const Vector3D& udirection, - double up) const -{ +void Acts::EigenStepper<B, C, E, A>::update(State& state, + const Vector3D& uposition, + const Vector3D& udirection, + double up) const { state.pos = uposition; state.dir = udirection; - state.p = up; + state.p = up; } template <typename B, typename C, typename E, typename A> -void -Acts::EigenStepper<B, C, E, A>::covarianceTransport(State& state, - bool reinitialize) const -{ +void Acts::EigenStepper<B, C, E, A>::covarianceTransport( + State& state, bool reinitialize) const { // Optimized trigonometry on the propagation direction const double x = state.dir(0); // == cos(phi) * sin(theta) const double y = state.dir(1); // == sin(phi) * sin(theta) const double z = state.dir(2); // == cos(theta) // can be turned into cosine/sine - const double cosTheta = z; - const double sinTheta = sqrt(x * x + y * y); + const double cosTheta = z; + const double sinTheta = sqrt(x * x + y * y); const double invSinTheta = 1. / sinTheta; - const double cosPhi = x * invSinTheta; - const double sinPhi = y * invSinTheta; + const double cosPhi = x * invSinTheta; + const double sinPhi = y * invSinTheta; // prepare the jacobian to curvilinear ActsMatrixD<5, 7> jacToCurv = ActsMatrixD<5, 7>::Zero(); if (std::abs(cosTheta) < s_curvilinearProjTolerance) { @@ -122,7 +107,7 @@ Acts::EigenStepper<B, C, E, A>::covarianceTransport(State& state, } else { // Under grazing incidence to z, the above coordinate system definition // becomes numerically unstable, and we need to switch to another one - const double c = sqrt(y * y + z * z); + const double c = sqrt(y * y + z * z); const double invC = 1. / c; jacToCurv(0, 1) = -z * invC; jacToCurv(0, 2) = y * invC; @@ -138,19 +123,19 @@ Acts::EigenStepper<B, C, E, A>::covarianceTransport(State& state, // Apply the transport from the steps on the jacobian state.jacToGlobal = state.jacTransport * state.jacToGlobal; // Transport the covariance - ActsRowVectorD<3> normVec(state.dir); - const ActsRowVectorD<5> sfactors - = normVec * state.jacToGlobal.template topLeftCorner<3, 5>(); + ActsRowVectorD<3> normVec(state.dir); + const ActsRowVectorD<5> sfactors = + normVec * state.jacToGlobal.template topLeftCorner<3, 5>(); // The full jacobian is ([to local] jacobian) * ([transport] jacobian) - const ActsMatrixD<5, 5> jacFull - = jacToCurv * (state.jacToGlobal - state.derivative * sfactors); + const ActsMatrixD<5, 5> jacFull = + jacToCurv * (state.jacToGlobal - state.derivative * sfactors); // Apply the actual covariance transport state.cov = (jacFull * state.cov * jacFull.transpose()); // Reinitialize if asked to do so // this is useful for interruption calls if (reinitialize) { // reset the jacobians - state.jacToGlobal = ActsMatrixD<7, 5>::Zero(); + state.jacToGlobal = ActsMatrixD<7, 5>::Zero(); state.jacTransport = ActsMatrixD<7, 7>::Identity(); // fill the jacobian to global for next transport state.jacToGlobal(0, eLOC_0) = -sinPhi; @@ -158,45 +143,42 @@ Acts::EigenStepper<B, C, E, A>::covarianceTransport(State& state, state.jacToGlobal(1, eLOC_0) = cosPhi; state.jacToGlobal(1, eLOC_1) = -sinPhi * cosTheta; state.jacToGlobal(2, eLOC_1) = sinTheta; - state.jacToGlobal(3, ePHI) = -sinTheta * sinPhi; + state.jacToGlobal(3, ePHI) = -sinTheta * sinPhi; state.jacToGlobal(3, eTHETA) = cosTheta * cosPhi; - state.jacToGlobal(4, ePHI) = sinTheta * cosPhi; + state.jacToGlobal(4, ePHI) = sinTheta * cosPhi; state.jacToGlobal(4, eTHETA) = cosTheta * sinPhi; state.jacToGlobal(5, eTHETA) = -sinTheta; - state.jacToGlobal(6, eQOP) = 1; + state.jacToGlobal(6, eQOP) = 1; } // Store The global and bound jacobian (duplication for the moment) state.jacobian = jacFull * state.jacobian; } template <typename B, typename C, typename E, typename A> -void -Acts::EigenStepper<B, C, E, A>::covarianceTransport(State& state, - const Surface& surface, - bool reinitialize) const -{ +void Acts::EigenStepper<B, C, E, A>::covarianceTransport( + State& state, const Surface& surface, bool reinitialize) const { using VectorHelpers::phi; using VectorHelpers::theta; // Initialize the transport final frame jacobian ActsMatrixD<5, 7> jacToLocal = ActsMatrixD<5, 7>::Zero(); // initalize the jacobian to local, returns the transposed ref frame - auto rframeT = surface.initJacobianToLocal( - state.geoContext, jacToLocal, state.pos, state.dir); + auto rframeT = surface.initJacobianToLocal(state.geoContext, jacToLocal, + state.pos, state.dir); // Update the jacobian with the transport from the steps state.jacToGlobal = state.jacTransport * state.jacToGlobal; // calculate the form factors for the derivatives const ActsRowVectorD<5> sVec = surface.derivativeFactors( state.geoContext, state.pos, state.dir, rframeT, state.jacToGlobal); // the full jacobian is ([to local] jacobian) * ([transport] jacobian) - const ActsMatrixD<5, 5> jacFull - = jacToLocal * (state.jacToGlobal - state.derivative * sVec); + const ActsMatrixD<5, 5> jacFull = + jacToLocal * (state.jacToGlobal - state.derivative * sVec); // Apply the actual covariance transport state.cov = (jacFull * state.cov * jacFull.transpose()); // Reinitialize if asked to do so // this is useful for interruption calls if (reinitialize) { // reset the jacobians - state.jacToGlobal = ActsMatrixD<7, 5>::Zero(); + state.jacToGlobal = ActsMatrixD<7, 5>::Zero(); state.jacTransport = ActsMatrixD<7, 7>::Identity(); // reset the derivative state.derivative = ActsVectorD<7>::Zero(); @@ -206,8 +188,8 @@ Acts::EigenStepper<B, C, E, A>::covarianceTransport(State& state, ActsVectorD<5> pars; pars << loc[eLOC_0], loc[eLOC_1], phi(state.dir), theta(state.dir), state.q / state.p; - surface.initJacobianToGlobal( - state.geoContext, state.jacToGlobal, state.pos, state.dir, pars); + surface.initJacobianToGlobal(state.geoContext, state.jacToGlobal, state.pos, + state.dir, pars); } // Store The global and bound jacobian (duplication for the moment) state.jacobian = jacFull * state.jacobian; @@ -215,18 +197,17 @@ Acts::EigenStepper<B, C, E, A>::covarianceTransport(State& state, template <typename B, typename C, typename E, typename A> template <typename propagator_state_t> -Acts::Result<double> -Acts::EigenStepper<B, C, E, A>::step(propagator_state_t& state) const -{ +Acts::Result<double> Acts::EigenStepper<B, C, E, A>::step( + propagator_state_t& state) const { // Runge-Kutta integrator state - auto& sd = state.stepping.stepData; + auto& sd = state.stepping.stepData; double error_estimate = 0.; double h2, half_h; // First Runge-Kutta point (at current position) sd.B_first = getField(state.stepping, state.stepping.pos); - if (!state.stepping.extension.validExtensionForStep(state, *this) - || !state.stepping.extension.k1(state, *this, sd.k1, sd.B_first)) { + if (!state.stepping.extension.validExtensionForStep(state, *this) || + !state.stepping.extension.k1(state, *this, sd.k1, sd.B_first)) { return 0.; } @@ -236,30 +217,30 @@ Acts::EigenStepper<B, C, E, A>::step(propagator_state_t& state) const // allowing integration to continue once the error is deemed satisfactory const auto tryRungeKuttaStep = [&](const double h) -> bool { // State the square and half of the step size - h2 = h * h; + h2 = h * h; half_h = h * 0.5; // Second Runge-Kutta point - const Vector3D pos1 - = state.stepping.pos + half_h * state.stepping.dir + h2 * 0.125 * sd.k1; + const Vector3D pos1 = + state.stepping.pos + half_h * state.stepping.dir + h2 * 0.125 * sd.k1; sd.B_middle = getField(state.stepping, pos1); - if (!state.stepping.extension.k2( - state, *this, sd.k2, sd.B_middle, half_h, sd.k1)) { + if (!state.stepping.extension.k2(state, *this, sd.k2, sd.B_middle, half_h, + sd.k1)) { return false; } // Third Runge-Kutta point - if (!state.stepping.extension.k3( - state, *this, sd.k3, sd.B_middle, half_h, sd.k2)) { + if (!state.stepping.extension.k3(state, *this, sd.k3, sd.B_middle, half_h, + sd.k2)) { return false; } // Last Runge-Kutta point - const Vector3D pos2 - = state.stepping.pos + h * state.stepping.dir + h2 * 0.5 * sd.k3; + const Vector3D pos2 = + state.stepping.pos + h * state.stepping.dir + h2 * 0.5 * sd.k3; sd.B_last = getField(state.stepping, pos2); - if (!state.stepping.extension.k4( - state, *this, sd.k4, sd.B_last, h, sd.k3)) { + if (!state.stepping.extension.k4(state, *this, sd.k4, sd.B_last, h, + sd.k3)) { return false; } @@ -274,12 +255,11 @@ Acts::EigenStepper<B, C, E, A>::step(propagator_state_t& state) const // Select and adjust the appropriate Runge-Kutta step size as given // ATL-SOFT-PUB-2009-001 while (!tryRungeKuttaStep(state.stepping.stepSize)) { - stepSizeScaling - = std::min(std::max(0.25, - std::pow((state.options.tolerance - / std::abs(2. * error_estimate)), - 0.25)), - 4.); + stepSizeScaling = + std::min(std::max(0.25, std::pow((state.options.tolerance / + std::abs(2. * error_estimate)), + 0.25)), + 4.); if (stepSizeScaling == 1.) { break; } @@ -287,8 +267,8 @@ Acts::EigenStepper<B, C, E, A>::step(propagator_state_t& state) const // If step size becomes too small the particle remains at the initial // place - if (state.stepping.stepSize * state.stepping.stepSize - < state.options.stepSizeCutOff * state.options.stepSizeCutOff) { + if (state.stepping.stepSize * state.stepping.stepSize < + state.options.stepSizeCutOff * state.options.stepSizeCutOff) { // Not moving due to too low momentum needs an aborter return EigenStepperError::StepSizeStalled; } @@ -314,11 +294,11 @@ Acts::EigenStepper<B, C, E, A>::step(propagator_state_t& state) const } // Update the track parameters according to the equations of motion - state.stepping.pos - += h * state.stepping.dir + h2 / 6. * (sd.k1 + sd.k2 + sd.k3); + state.stepping.pos += + h * state.stepping.dir + h2 / 6. * (sd.k1 + sd.k2 + sd.k3); state.stepping.dir += h / 6. * (sd.k1 + 2. * (sd.k2 + sd.k3) + sd.k4); state.stepping.dir /= state.stepping.dir.norm(); - state.stepping.derivative.template head<3>() = state.stepping.dir; + state.stepping.derivative.template head<3>() = state.stepping.dir; state.stepping.derivative.template segment<3>(3) = sd.k4; state.stepping.pathAccumulated += h; diff --git a/Core/include/Acts/Propagator/EigenStepperError.hpp b/Core/include/Acts/Propagator/EigenStepperError.hpp index 44a2fa94a42d50520843bef8e6f6479e8a0adb9f..2d18a3b7e3fd4dd90f8addd968076104cfb94807 100644 --- a/Core/include/Acts/Propagator/EigenStepperError.hpp +++ b/Core/include/Acts/Propagator/EigenStepperError.hpp @@ -17,51 +17,39 @@ namespace Acts { enum class EigenStepperError { StepSizeStalled = 1, StepInvalid = 2 }; namespace detail { - // Define a custom error code category derived from std::error_category - class EigenStepperErrorCategory : public std::error_category - { - public: - // Return a short descriptive name for the category - const char* - name() const noexcept final - { - return "EigenStepperError"; - } - // Return what each enum means in text - std::string - message(int c) const final - { - switch (static_cast<EigenStepperError>(c)) { +// Define a custom error code category derived from std::error_category +class EigenStepperErrorCategory : public std::error_category { + public: + // Return a short descriptive name for the category + const char* name() const noexcept final { return "EigenStepperError"; } + // Return what each enum means in text + std::string message(int c) const final { + switch (static_cast<EigenStepperError>(c)) { case EigenStepperError::StepSizeStalled: return "Step size fell below minimum threshold"; case EigenStepperError::StepInvalid: return "Step calculation was invalid"; default: return "unknown"; - } } - }; -} + } +}; +} // namespace detail // Declare a global function returning a static instance of the custom category extern inline const detail::EigenStepperErrorCategory& -EigenStepperErrorCategory() -{ +EigenStepperErrorCategory() { static detail::EigenStepperErrorCategory c; return c; } -inline std::error_code -make_error_code(Acts::EigenStepperError e) -{ +inline std::error_code make_error_code(Acts::EigenStepperError e) { return {static_cast<int>(e), Acts::EigenStepperErrorCategory()}; } -} +} // namespace Acts namespace std { // register with STL template <> -struct is_error_code_enum<Acts::EigenStepperError> : std::true_type -{ -}; -} +struct is_error_code_enum<Acts::EigenStepperError> : std::true_type {}; +} // namespace std diff --git a/Core/include/Acts/Propagator/MaterialInteractor.hpp b/Core/include/Acts/Propagator/MaterialInteractor.hpp index df3aa27a221064359022444e65a8fc31f5e5508c..69de7cf0617061ed479b717d2d3f9e4b44a8c162 100644 --- a/Core/include/Acts/Propagator/MaterialInteractor.hpp +++ b/Core/include/Acts/Propagator/MaterialInteractor.hpp @@ -23,15 +23,14 @@ namespace Acts { /// @brief The Material interaction struct /// It records the surface and the passed material /// This is only nessecary recorded when configured -struct MaterialInteraction -{ +struct MaterialInteraction { /// The material surface const Surface* surface = nullptr; - double sigmaPhi2 = 0.; ///< applied material effect: sigma(phi)^2 + double sigmaPhi2 = 0.; ///< applied material effect: sigma(phi)^2 double sigmaTheta2 = 0.; ///< applied material effect: sigma(theta)^2 - double deltaP = 0.; ///< applied material effect: dela(p) - double sigmaQoP2 = 0.; ///< applied material effect: sigma(qop)^2 + double deltaP = 0.; ///< applied material effect: dela(p) + double sigmaQoP2 = 0.; ///< applied material effect: sigma(qop)^2 /// The position information of the material hit Vector3D position = Vector3D(0., 0., 0); @@ -49,9 +48,7 @@ struct MaterialInteraction /// This is a plugin to the Propagator that /// performs material interaction on the currentSurface /// of the Propagagor state -struct MaterialInteractor -{ - +struct MaterialInteractor { // Configuration for this MaterialInteractor /// multiple scattering switch on/off @@ -70,8 +67,7 @@ struct MaterialInteractor /// Simple result struct to be returned /// It mainly acts as an internal state which is /// created for every propagation/extrapolation step - struct this_result - { + struct this_result { // The accumulated materialInX0 double materialInX0 = 0.; /// The accumulated materialInL0 @@ -97,12 +93,8 @@ struct MaterialInteractor /// @param stepper The stepper in use /// @param result is the mutable result state object template <typename propagator_state_t, typename stepper_t> - void - operator()(propagator_state_t& state, - const stepper_t& stepper, - result_type& result) const - { - + void operator()(propagator_state_t& state, const stepper_t& stepper, + result_type& result) const { // If we are on target, everything should have been done if (state.navigation.targetReached) { return; @@ -115,8 +107,8 @@ struct MaterialInteractor // A current surface has been already assigned by the navigator // check for material - if (state.navigation.currentSurface - && state.navigation.currentSurface->surfaceMaterial()) { + if (state.navigation.currentSurface && + state.navigation.currentSurface->surfaceMaterial()) { // Let's set the pre/full/post update stage MaterialUpdateStage mStage = fullUpdate; // We are at the start surface @@ -126,8 +118,8 @@ struct MaterialInteractor }); mStage = postUpdate; // Or is it the target surface ? - } else if (state.navigation.targetSurface - == state.navigation.currentSurface) { + } else if (state.navigation.targetSurface == + state.navigation.currentSurface) { debugLog(state, [&] { return std::string("Update on target surface: pre-update mode"); }); @@ -140,8 +132,8 @@ struct MaterialInteractor // Get the surface material & properties from them and continue if you // found some - const ISurfaceMaterial* sMaterial - = state.navigation.currentSurface->surfaceMaterial(); + const ISurfaceMaterial* sMaterial = + state.navigation.currentSurface->surfaceMaterial(); MaterialProperties mProperties = sMaterial->materialProperties( stepper.position(state.stepping), state.stepping.navDir, mStage); // Material properties (non-zero) have been found for this configuration @@ -164,17 +156,16 @@ struct MaterialInteractor // Calculate the path correction double pCorrection = state.navigation.currentSurface->pathCorrection( - state.geoContext, - stepper.position(state.stepping), + state.geoContext, stepper.position(state.stepping), stepper.direction(state.stepping)); // Scale the material properties mProperties *= pCorrection; // The momentum at current position - const double p = stepper.momentum(state.stepping); - const double m = state.options.mass; - const double E = std::sqrt(p * p + m * m); + const double p = stepper.momentum(state.stepping); + const double m = state.options.mass; + const double E = std::sqrt(p * p + m * m); const double lbeta = p / E; // Apply the multiple scattering @@ -184,24 +175,24 @@ struct MaterialInteractor double tInX0 = mProperties.thicknessInX0(); // Retrieve the scattering contribution double sigmaScat = scattering(p, lbeta, tInX0); - double sinTheta = std::sin( - VectorHelpers::theta(stepper.direction(state.stepping))); - double sigmaDeltaPhiSq - = sigmaScat * sigmaScat / (sinTheta * sinTheta); + double sinTheta = + std::sin(VectorHelpers::theta(stepper.direction(state.stepping))); + double sigmaDeltaPhiSq = + sigmaScat * sigmaScat / (sinTheta * sinTheta); double sigmaDeltaThetaSq = sigmaScat * sigmaScat; // Record the material interaction - mInteraction.sigmaPhi2 = sigmaDeltaPhiSq; + mInteraction.sigmaPhi2 = sigmaDeltaPhiSq; mInteraction.sigmaTheta2 = sigmaDeltaThetaSq; // Good in any case for positive direction if (state.stepping.navDir == forward) { // Just add the multiple scattering component - state.stepping.cov(ePHI, ePHI) - += state.stepping.navDir * sigmaDeltaPhiSq; - state.stepping.cov(eTHETA, eTHETA) - += state.stepping.navDir * sigmaDeltaThetaSq; + state.stepping.cov(ePHI, ePHI) += + state.stepping.navDir * sigmaDeltaPhiSq; + state.stepping.cov(eTHETA, eTHETA) += + state.stepping.navDir * sigmaDeltaThetaSq; } else { // We check if the covariance stays positive - double sEphi = state.stepping.cov(ePHI, ePHI); + double sEphi = state.stepping.cov(ePHI, ePHI); double sEtheta = state.stepping.cov(eTHETA, eTHETA); if (sEphi > sigmaDeltaPhiSq && sEtheta > sigmaDeltaThetaSq) { // Noise removal is not applied if covariance would fall below 0 @@ -218,11 +209,11 @@ struct MaterialInteractor // Calculate gamma const double lgamma = E / m; // Energy loss and straggling - per unit length - std::pair<double, double> eLoss - = ionisationloss.dEds(m, lbeta, lgamma, mat, 1. * units::_mm); + std::pair<double, double> eLoss = + ionisationloss.dEds(m, lbeta, lgamma, mat, 1. * units::_mm); // Apply the energy loss const double dEdl = state.stepping.navDir * eLoss.first; - const double dE = mProperties.thickness() * dEdl; + const double dE = mProperties.thickness() * dEdl; // Screen output debugLog(state, [&] { std::stringstream dstream; @@ -238,8 +229,7 @@ struct MaterialInteractor mInteraction.deltaP = p - newP; // Update the state/momentum stepper.update( - state.stepping, - stepper.position(state.stepping), + state.stepping, stepper.position(state.stepping), stepper.direction(state.stepping), std::copysign(newP, stepper.momentum(state.stepping))); } @@ -249,21 +239,21 @@ struct MaterialInteractor // the kineamtic limit to catch the cases of deltE < MOP/MPV if (state.stepping.covTransport) { // Calculate the straggling - const double sigmaQoverP - = mProperties.thickness() * eLoss.second / (lbeta * p * p); + const double sigmaQoverP = + mProperties.thickness() * eLoss.second / (lbeta * p * p); // Save the material interaction mInteraction.sigmaQoP2 = sigmaQoverP * sigmaQoverP; // Good in any case for positive direction if (state.stepping.navDir == forward) { - state.stepping.cov(eQOP, eQOP) - += state.stepping.navDir * sigmaQoverP * sigmaQoverP; + state.stepping.cov(eQOP, eQOP) += + state.stepping.navDir * sigmaQoverP * sigmaQoverP; } else { // Check that covariance entry doesn't become negative double sEqop = state.stepping.cov(eQOP, eQOP); if (sEqop > sigmaQoverP * sigmaQoverP) { - state.stepping.cov(eQOP, eQOP) - += state.stepping.navDir * mInteraction.sigmaQoP2; + state.stepping.cov(eQOP, eQOP) += + state.stepping.navDir * mInteraction.sigmaQoP2; } } } @@ -275,10 +265,10 @@ struct MaterialInteractor // Record the material interaction if configured to do so if (recordInteractions) { - mInteraction.position = stepper.position(state.stepping); - mInteraction.direction = stepper.direction(state.stepping); + mInteraction.position = stepper.position(state.stepping); + mInteraction.direction = stepper.direction(state.stepping); mInteraction.materialProperties = mProperties; - mInteraction.pathCorrection = pCorrection; + mInteraction.pathCorrection = pCorrection; result.materialInteractions.push_back(std::move(mInteraction)); } } @@ -288,12 +278,9 @@ struct MaterialInteractor /// Pure observer interface /// This does not apply to the surface collector template <typename propagator_state_t> - void - operator()(propagator_state_t& /*state*/) const - { - } + void operator()(propagator_state_t& /*state*/) const {} -private: + private: /// The private propagation debug logging /// /// It needs to be fed by a lambda function that returns a string, @@ -306,10 +293,8 @@ private: /// length /// @param logAction is a callable function that returns a stremable object template <typename propagator_state_t> - void - debugLog(propagator_state_t& state, - const std::function<std::string()>& logAction) const - { + void debugLog(propagator_state_t& state, + const std::function<std::string()>& logAction) const { if (state.options.debug) { std::stringstream dstream; dstream << " " << std::setw(state.options.debugPfxWidth); @@ -327,7 +312,7 @@ using RecordedMaterial = MaterialInteractor::result_type; /// And recorded material track /// - this is start: position, start momentum /// and the Recorded material -using RecordedMaterialTrack - = std::pair<std::pair<Acts::Vector3D, Acts::Vector3D>, RecordedMaterial>; +using RecordedMaterialTrack = + std::pair<std::pair<Acts::Vector3D, Acts::Vector3D>, RecordedMaterial>; } // end of namespace Acts diff --git a/Core/include/Acts/Propagator/Navigator.hpp b/Core/include/Acts/Propagator/Navigator.hpp index 50a70385d77c485daef3da05a93e2e7d6eaa7a3e..d1d37fa2f2467d65377f580b83e939a273417c71 100644 --- a/Core/include/Acts/Propagator/Navigator.hpp +++ b/Core/include/Acts/Propagator/Navigator.hpp @@ -31,9 +31,7 @@ using Cstep = detail::ConstrainedStep; /// @tparam propagator_state_t Type of the object for navigation state /// @tparam object_t Type of the object for navigation to check against template <typename object_t> -struct NavigationOptions -{ - +struct NavigationOptions { /// The navigation direction NavigationDirection navDir = forward; @@ -65,23 +63,18 @@ struct NavigationOptions /// @param sobject Start object to check against /// @param eobject End object to check against /// @param maxStepLength Maximal step length to check against - NavigationOptions(NavigationDirection ndir, - BoundaryCheck bcheck, - bool resolves = true, - bool resolvem = true, - bool resolvep = false, - const object_t* sobject = nullptr, - const object_t* eobject = nullptr) - : navDir(ndir) - , boundaryCheck(std::move(bcheck)) - , resolveSensitive(resolves) - , resolveMaterial(resolvem) - , resolvePassive(resolvep) - , startObject(sobject) - , endObject(eobject) - , pathLimit(ndir * std::numeric_limits<double>::max()) - { - } + NavigationOptions(NavigationDirection ndir, BoundaryCheck bcheck, + bool resolves = true, bool resolvem = true, + bool resolvep = false, const object_t* sobject = nullptr, + const object_t* eobject = nullptr) + : navDir(ndir), + boundaryCheck(std::move(bcheck)), + resolveSensitive(resolves), + resolveMaterial(resolvem), + resolvePassive(resolvep), + startObject(sobject), + endObject(eobject), + pathLimit(ndir * std::numeric_limits<double>::max()) {} }; /// Navigator class @@ -107,29 +100,27 @@ struct NavigationOptions /// the surfaceReached call fails, it also re-computes the step size, to make /// sure we end up at the desired surface. /// -class Navigator -{ - -public: - using Surfaces = std::vector<const Surface*>; +class Navigator { + public: + using Surfaces = std::vector<const Surface*>; using SurfaceIter = std::vector<const Surface*>::iterator; - using NavigationSurfaces = std::vector<SurfaceIntersection>; + using NavigationSurfaces = std::vector<SurfaceIntersection>; using NavigationSurfaceIter = NavigationSurfaces::iterator; - using NavigationLayers = std::vector<LayerIntersection>; + using NavigationLayers = std::vector<LayerIntersection>; using NavigationLayerIter = NavigationLayers::iterator; - using NavigationBoundaries = std::vector<BoundaryIntersection>; + using NavigationBoundaries = std::vector<BoundaryIntersection>; using NavigationBoundaryIter = NavigationBoundaries::iterator; using ExternalSurfaces = std::multimap<const Layer*, const Surface*>; /// The navigation stage enum struct Stage : int { - undefined = 0, - surfaceTarget = 1, - layerTarget = 2, + undefined = 0, + surfaceTarget = 1, + layerTarget = 2, boundaryTarget = 3 }; @@ -137,9 +128,7 @@ public: /// /// @param tGeometry The tracking geometry for the navigator Navigator(std::shared_ptr<const TrackingGeometry> tGeometry = nullptr) - : trackingGeometry(std::move(tGeometry)) - { - } + : trackingGeometry(std::move(tGeometry)) {} /// Tracking Geometry for this Navigator std::shared_ptr<const TrackingGeometry> trackingGeometry; @@ -160,8 +149,7 @@ public: /// It acts as an internal state which is /// created for every propagation/extrapolation step /// and keep thread-local navigation information - struct State - { + struct State { // Navigation on surface level /// the vector of navigation surfaces to work through NavigationSurfaces navSurfaces = {}; @@ -233,9 +221,7 @@ public: /// @param [in,out] state is the mutable propagator state object /// @param [in] stepper Stepper in use template <typename propagator_state_t, typename stepper_t> - void - status(propagator_state_t& state, const stepper_t& stepper) const - { + void status(propagator_state_t& state, const stepper_t& stepper) const { // Check if the navigator is inactive if (inactive(state, stepper)) { return; @@ -259,9 +245,7 @@ public: // (b) Status call within propagation loop // Try finding status of surfaces - if (status(state, - stepper, - state.navigation.navSurfaces, + if (status(state, stepper, state.navigation.navSurfaces, state.navigation.navSurfaceIter)) { debugLog(state, [&] { return std::string("Status: in surface handling."); }); @@ -269,17 +253,15 @@ public: debugLog(state, [&] { return std::string("On surface: switch forward or release."); }); - if (++state.navigation.navSurfaceIter - == state.navigation.navSurfaces.end()) { + if (++state.navigation.navSurfaceIter == + state.navigation.navSurfaces.end()) { ++state.navigation.navLayerIter; } } // Set the navigation stage to surface target state.navigation.navigationStage = Stage::surfaceTarget; // Try finding status of layer - } else if (status(state, - stepper, - state.navigation.navLayers, + } else if (status(state, stepper, state.navigation.navLayers, state.navigation.navLayerIter)) { debugLog(state, [&] { return std::string("Status: in layer handling."); }); @@ -299,9 +281,7 @@ public: state.navigation.navigationStage = Stage::layerTarget; } // Try finding status of boundaries - } else if (status(state, - stepper, - state.navigation.navBoundaries, + } else if (status(state, stepper, state.navigation.navBoundaries, state.navigation.navBoundaryIter)) { debugLog(state, [&] { return std::string("Stauts: in boundary handling."); }); @@ -320,11 +300,9 @@ public: // Update volume information // get the attached volume information auto boundary = state.navigation.navBoundaryIter->object; - state.navigation.currentVolume - = boundary->attachedVolume(state.geoContext, - stepper.position(state.stepping), - stepper.direction(state.stepping), - state.stepping.navDir); + state.navigation.currentVolume = boundary->attachedVolume( + state.geoContext, stepper.position(state.stepping), + stepper.direction(state.stepping), state.stepping.navDir); // No volume anymore : end of known world if (!state.navigation.currentVolume) { debugLog(state, [&] { @@ -339,15 +317,15 @@ public: debugLog(state, [&] { return std::string("Volume updated."); }); // Forget the bounday information state.navigation.navBoundaries.clear(); - state.navigation.navBoundaryIter - = state.navigation.navBoundaries.end(); + state.navigation.navBoundaryIter = + state.navigation.navBoundaries.end(); } } else { // Set the navigation stage back to boundary target state.navigation.navigationStage = Stage::boundaryTarget; } - } else if (state.navigation.currentVolume - == state.navigation.targetVolume) { + } else if (state.navigation.currentVolume == + state.navigation.targetVolume) { debugLog(state, [&] { return std::string("No further navigation action, proceed to target."); }); @@ -375,9 +353,7 @@ public: /// @param [in,out] state is the mutable propagator state object /// @param [in] stepper Stepper in use template <typename propagator_state_t, typename stepper_t> - void - target(propagator_state_t& state, const stepper_t& stepper) const - { + void target(propagator_state_t& state, const stepper_t& stepper) const { // Check if the navigator is inactive if (inactive(state, stepper)) { return; @@ -396,12 +372,12 @@ public: } // Try targeting the surfaces - then layers - then boundaries - if (state.navigation.navigationStage <= Stage::surfaceTarget - and targetSurfaces(state, stepper, navCorr)) { + if (state.navigation.navigationStage <= Stage::surfaceTarget and + targetSurfaces(state, stepper, navCorr)) { debugLog(state, [&] { return std::string("Target set to next surface."); }); - } else if (state.navigation.navigationStage <= Stage::layerTarget - and targetLayers(state, stepper, navCorr)) { + } else if (state.navigation.navigationStage <= Stage::layerTarget and + targetLayers(state, stepper, navCorr)) { debugLog(state, [&] { return std::string("Target set to next layer."); }); } else if (targetBoundaries(state, stepper, navCorr)) { debugLog(state, @@ -422,7 +398,7 @@ public: return; } -private: + private: /// -------------------------------------------------------------------- /// Initialize call - start of propagation /// @@ -434,9 +410,7 @@ private: /// /// @return boolean return triggers exit to stepper template <typename propagator_state_t, typename stepper_t> - void - initialize(propagator_state_t& state, const stepper_t& stepper) const - { + void initialize(propagator_state_t& state, const stepper_t& stepper) const { // Call the navigation helper prior to actual navigation debugLog(state, [&] { return std::string("Initialization."); }); @@ -461,16 +435,16 @@ private: // Fast Navigation initialization for start condition: // - short-cut through object association, saves navigation in the // - geometry and volume tree search for the lowest volume - if (state.navigation.startSurface - && state.navigation.startSurface->associatedLayer()) { + if (state.navigation.startSurface && + state.navigation.startSurface->associatedLayer()) { debugLog(state, [&] { return std::string("Fast start initialization through association."); }); // assign the current layer and volume by association - state.navigation.startLayer - = state.navigation.startSurface->associatedLayer(); - state.navigation.startVolume - = state.navigation.startLayer->trackingVolume(); + state.navigation.startLayer = + state.navigation.startSurface->associatedLayer(); + state.navigation.startVolume = + state.navigation.startLayer->trackingVolume(); // Set the start volume as current volume state.navigation.currentVolume = state.navigation.startVolume; } else { @@ -488,10 +462,11 @@ private: }); state.navigation.startVolume = trackingGeometry->lowestTrackingVolume( state.geoContext, stepper.position(state.stepping)); - state.navigation.startLayer = state.navigation.startVolume - ? state.navigation.startVolume->associatedLayer( - state.geoContext, stepper.position(state.stepping)) - : nullptr; + state.navigation.startLayer = + state.navigation.startVolume + ? state.navigation.startVolume->associatedLayer( + state.geoContext, stepper.position(state.stepping)) + : nullptr; // Set the start volume as current volume state.navigation.currentVolume = state.navigation.startVolume; if (state.navigation.startVolume) { @@ -518,16 +493,11 @@ private: /// @param [in] navIter test surface fore the status test /// /// @return boolean return triggers exit to stepper - template <typename propagator_state_t, - typename stepper_t, - typename navigation_surfaces_t, - typename navigation_iter_t> - bool - status(propagator_state_t& state, - const stepper_t& stepper, - navigation_surfaces_t& navSurfaces, - const navigation_iter_t& navIter) const - { + template <typename propagator_state_t, typename stepper_t, + typename navigation_surfaces_t, typename navigation_iter_t> + bool status(propagator_state_t& state, const stepper_t& stepper, + navigation_surfaces_t& navSurfaces, + const navigation_iter_t& navIter) const { // No surfaces, status check will be done on layer if (navSurfaces.empty() or navIter == navSurfaces.end()) { return false; @@ -570,30 +540,25 @@ private: /// @param [in] navCorr is the navigation path corrector /// /// boolean return triggers exit to stepper - template <typename propagator_state_t, - typename stepper_t, + template <typename propagator_state_t, typename stepper_t, typename corrector_t> - bool - targetSurfaces(propagator_state_t& state, - const stepper_t& stepper, - const corrector_t& navCorr) const - { - + bool targetSurfaces(propagator_state_t& state, const stepper_t& stepper, + const corrector_t& navCorr) const { if (state.navigation.navigationBreak) { return false; } // Make sure resolve Surfaces is called on the start layer - if (state.navigation.startLayer - and not state.navigation.startLayerResolved) { + if (state.navigation.startLayer and + not state.navigation.startLayerResolved) { debugLog(state, [&] { return std::string("Start layer to be resolved."); }); // We provide the layer to the resolve surface method in this case state.navigation.startLayerResolved = true; - bool startResolved = resolveSurfaces( - state, stepper, navCorr, state.navigation.startLayer); - if (not startResolved - and state.navigation.startLayer == state.navigation.targetLayer) { + bool startResolved = + resolveSurfaces(state, stepper, navCorr, state.navigation.startLayer); + if (not startResolved and + state.navigation.startLayer == state.navigation.targetLayer) { debugLog(state, [&] { return std::string("Start is target layer, nothing left to do."); }); @@ -606,9 +571,8 @@ private: // The call that we are on a layer and have not yet resolved the surfaces // No surfaces, do not return to stepper - if (state.navigation.navSurfaces.empty() - or state.navigation.navSurfaceIter - == state.navigation.navSurfaces.end()) { + if (state.navigation.navSurfaces.empty() or + state.navigation.navSurfaceIter == state.navigation.navSurfaces.end()) { debugLog(state, [&] { return std::string("No surfaces present, target at layer first."); }); @@ -621,8 +585,8 @@ private: navOpts.pathLimit = state.stepping.stepSize.value(Cstep::aborter); // Loop over the navigation surfaces - while (state.navigation.navSurfaceIter - != state.navigation.navSurfaces.end()) { + while (state.navigation.navSurfaceIter != + state.navigation.navSurfaces.end()) { // Screen output how much is left to try debugLog(state, [&] { std::stringstream dstream; @@ -643,11 +607,8 @@ private: }); // Now intersect (should exclude punch-through) auto surfaceIntersect = surface->surfaceIntersectionEstimate( - state.geoContext, - stepper.position(state.stepping), - stepper.direction(state.stepping), - navOpts, - navCorr); + state.geoContext, stepper.position(state.stepping), + stepper.direction(state.stepping), navOpts, navCorr); double surfaceDistance = surfaceIntersect.intersection.pathLength; if (!surfaceIntersect) { debugLog(state, [&] { @@ -701,15 +662,10 @@ private: /// @param [in] corrector_t navCorr is the navigation path corrector /// /// @return boolean return triggers exit to stepper - template <typename propagator_state_t, - typename stepper_t, + template <typename propagator_state_t, typename stepper_t, typename corrector_t> - bool - targetLayers(propagator_state_t& state, - const stepper_t& stepper, - const corrector_t& navCorr) const - { - + bool targetLayers(propagator_state_t& state, const stepper_t& stepper, + const corrector_t& navCorr) const { if (state.navigation.navigationBreak) { return false; } @@ -745,11 +701,8 @@ private: // Otherwise try to step towards it NavigationOptions<Surface> navOpts(state.stepping.navDir, true); auto layerIntersect = layerSurface->surfaceIntersectionEstimate( - state.geoContext, - stepper.position(state.stepping), - stepper.direction(state.stepping), - navOpts, - navCorr); + state.geoContext, stepper.position(state.stepping), + stepper.direction(state.stepping), navOpts, navCorr); // check if the intersect is invalid if (!layerIntersect) { debugLog(state, [&] { @@ -758,8 +711,8 @@ private: ++state.navigation.navLayerIter; } else { // update the navigation step size, release the former first - updateStep( - state, navCorr, layerIntersect.intersection.pathLength, true); + updateStep(state, navCorr, layerIntersect.intersection.pathLength, + true); return true; } } @@ -780,8 +733,8 @@ private: return dstream.str(); }); // Set the navigation break if necessary - state.navigation.navigationBreak - = (state.navigation.currentVolume == state.navigation.targetVolume); + state.navigation.navigationBreak = + (state.navigation.currentVolume == state.navigation.targetVolume); return false; } @@ -813,30 +766,28 @@ private: /// @param [in] navCorr is the navigation path corrector /// /// boolean return triggers exit to stepper - template <typename propagator_state_t, - typename stepper_t, + template <typename propagator_state_t, typename stepper_t, typename corrector_t> - bool - targetBoundaries(propagator_state_t& state, - const stepper_t& stepper, - const corrector_t& navCorr) const - { + bool targetBoundaries(propagator_state_t& state, const stepper_t& stepper, + const corrector_t& navCorr) const { if (state.navigation.navigationBreak) { return false; } if (!state.navigation.currentVolume) { debugLog(state, [&] { - return std::string("No sufficient information to resolve boundary, " - "stopping navigation."); + return std::string( + "No sufficient information to resolve boundary, " + "stopping navigation."); }); state.stepping.stepSize.release(Cstep::actor); return false; - } else if (state.navigation.currentVolume - == state.navigation.targetVolume) { + } else if (state.navigation.currentVolume == + state.navigation.targetVolume) { debugLog(state, [&] { - return std::string("In target volume: no need to resolve boundary, " - "stopping navigation."); + return std::string( + "In target volume: no need to resolve boundary, " + "stopping navigation."); state.navigation.navigationBreak = true; state.stepping.stepSize.release(Cstep::actor); }); @@ -863,13 +814,10 @@ private: return ss.str(); }); // Evaluate the boundary surfaces - state.navigation.navBoundaries - = state.navigation.currentVolume->compatibleBoundaries( - state.geoContext, - stepper.position(state.stepping), - stepper.direction(state.stepping), - navOpts, - navCorr, + state.navigation.navBoundaries = + state.navigation.currentVolume->compatibleBoundaries( + state.geoContext, stepper.position(state.stepping), + stepper.direction(state.stepping), navOpts, navCorr, BoundaryIntersectionSorter()); // The number of boundary candidates debugLog(state, [&] { @@ -886,23 +834,19 @@ private: } // Loop over the boundary surface - while (state.navigation.navBoundaryIter - != state.navigation.navBoundaries.end()) { + while (state.navigation.navBoundaryIter != + state.navigation.navBoundaries.end()) { // That is the current boundary surface auto boundarySurface = state.navigation.navBoundaryIter->representation; // Step towards the boundary surface auto boundaryIntersect = boundarySurface->surfaceIntersectionEstimate( - state.geoContext, - stepper.position(state.stepping), - stepper.direction(state.stepping), - navOpts, - navCorr); + state.geoContext, stepper.position(state.stepping), + stepper.direction(state.stepping), navOpts, navCorr); // Distance auto distance = boundaryIntersect.intersection.pathLength; // Check the boundary is properly intersected: we are in target mode - if (!boundaryIntersect - or distance * distance - < s_onSurfaceTolerance * s_onSurfaceTolerance) { + if (!boundaryIntersect or + distance * distance < s_onSurfaceTolerance * s_onSurfaceTolerance) { debugLog(state, [&] { std::stringstream ss; ss << "Boundary intersection with:\n"; @@ -953,14 +897,10 @@ private: /// @param [in] navCorr is the navigation path corrector /// /// boolean return triggers exit to stepper - template <typename propagator_state_t, - typename stepper_t, + template <typename propagator_state_t, typename stepper_t, typename corrector_t> - void - initializeTarget(propagator_state_t& state, - const stepper_t& stepper, - const corrector_t& navCorr) const - { + void initializeTarget(propagator_state_t& state, const stepper_t& stepper, + const corrector_t& navCorr) const { if (state.navigation.targetVolume && state.stepping.pathAccumulated == 0.) { debugLog(state, [&] { return std::string("Re-initialzing cancelled as it is the first step."); @@ -968,9 +908,9 @@ private: return; } // Fast Navigation initialization for target: - if (state.navigation.targetSurface - && state.navigation.targetSurface->associatedLayer() - && !state.navigation.targetVolume) { + if (state.navigation.targetSurface && + state.navigation.targetSurface->associatedLayer() && + !state.navigation.targetVolume) { debugLog(state, [&] { return std::string("Fast target initialization through association."); }); @@ -981,10 +921,10 @@ private: return dstream.str(); }); // assign the target volume and the target surface - state.navigation.targetLayer - = state.navigation.targetSurface->associatedLayer(); - state.navigation.targetVolume - = state.navigation.targetLayer->trackingVolume(); + state.navigation.targetLayer = + state.navigation.targetSurface->associatedLayer(); + state.navigation.targetVolume = + state.navigation.targetLayer->trackingVolume(); } else if (state.navigation.targetSurface) { // screen output that you do a re-initialization if (state.navigation.targetVolume) { @@ -994,19 +934,14 @@ private: } // Slow navigation initialization for target: // target volume and layer search through global search - NavigationOptions<Surface> navOpts(state.stepping.navDir, - false, - resolveSensitive, - resolveMaterial, + NavigationOptions<Surface> navOpts(state.stepping.navDir, false, + resolveSensitive, resolveMaterial, resolvePassive); // take the target intersection - auto targetIntersection - = state.navigation.targetSurface->surfaceIntersectionEstimate( - state.geoContext, - stepper.position(state.stepping), - stepper.direction(state.stepping), - navOpts, - navCorr); + auto targetIntersection = + state.navigation.targetSurface->surfaceIntersectionEstimate( + state.geoContext, stepper.position(state.stepping), + stepper.direction(state.stepping), navOpts, navCorr); debugLog(state, [&] { std::stringstream dstream; dstream << "Target estimate position ("; @@ -1017,12 +952,13 @@ private: }); /// get the target volume from the intersection auto tPosition = targetIntersection.intersection.position; - state.navigation.targetVolume - = trackingGeometry->lowestTrackingVolume(state.geoContext, tPosition); - state.navigation.targetLayer = state.navigation.targetVolume - ? state.navigation.targetVolume->associatedLayer(state.geoContext, - tPosition) - : nullptr; + state.navigation.targetVolume = + trackingGeometry->lowestTrackingVolume(state.geoContext, tPosition); + state.navigation.targetLayer = + state.navigation.targetVolume + ? state.navigation.targetVolume->associatedLayer(state.geoContext, + tPosition) + : nullptr; if (state.navigation.targetVolume) { debugLog(state, [&] { std::stringstream dstream; @@ -1046,38 +982,27 @@ private: /// @param [in] cLayer is the already assigned current layer, e.g. start layer /// /// boolean return triggers exit to stepper - template <typename propagator_state_t, - typename stepper_t, + template <typename propagator_state_t, typename stepper_t, typename corrector_t> - bool - resolveSurfaces(propagator_state_t& state, - const stepper_t& stepper, - const corrector_t& navCorr, - const Layer* cLayer = nullptr) const - { + bool resolveSurfaces(propagator_state_t& state, const stepper_t& stepper, + const corrector_t& navCorr, + const Layer* cLayer = nullptr) const { // get the layer and layer surface auto layerSurface = cLayer ? state.navigation.startSurface : state.navigation.navLayerIter->representation; auto navLayer = cLayer ? cLayer : state.navigation.navLayerIter->object; // are we on the start layer - bool onStart = (navLayer == state.navigation.startLayer); + bool onStart = (navLayer == state.navigation.startLayer); auto startSurface = onStart ? state.navigation.startSurface : layerSurface; - NavigationOptions<Surface> navOpts(state.stepping.navDir, - true, - resolveSensitive, - resolveMaterial, - resolvePassive, - startSurface, - state.navigation.targetSurface); + NavigationOptions<Surface> navOpts( + state.stepping.navDir, true, resolveSensitive, resolveMaterial, + resolvePassive, startSurface, state.navigation.targetSurface); // Check the limit navOpts.pathLimit = state.stepping.stepSize.value(Cstep::aborter); // get the surfaces - state.navigation.navSurfaces - = navLayer->compatibleSurfaces(state.geoContext, - stepper.position(state.stepping), - stepper.direction(state.stepping), - navOpts, - navCorr); + state.navigation.navSurfaces = navLayer->compatibleSurfaces( + state.geoContext, stepper.position(state.stepping), + stepper.direction(state.stepping), navOpts, navCorr); // the number of layer candidates if (!state.navigation.navSurfaces.empty()) { debugLog(state, [&] { @@ -1093,8 +1018,7 @@ private: state.navigation.navSurfaceIter = state.navigation.navSurfaces.begin(); // Update the navigation step size before you return to the stepper // This is a new navigation stream, release the former step size first - updateStep(state, - navCorr, + updateStep(state, navCorr, state.navigation.navSurfaceIter->intersection.pathLength, true); return true; @@ -1122,42 +1046,31 @@ private: /// @param [in] navCorr is the navigation path corrector /// /// @return boolean return triggers exit to stepper - template <typename propagator_state_t, - typename stepper_t, + template <typename propagator_state_t, typename stepper_t, typename corrector_t> - bool - resolveLayers(propagator_state_t& state, - const stepper_t& stepper, - const corrector_t& navCorr) const - { + bool resolveLayers(propagator_state_t& state, const stepper_t& stepper, + const corrector_t& navCorr) const { debugLog(state, [&] { return std::string("Searching for compatible layers."); }); // Check if we are in the start volume - auto startLayer - = (state.navigation.currentVolume == state.navigation.startVolume) - ? state.navigation.startLayer - : nullptr; + auto startLayer = + (state.navigation.currentVolume == state.navigation.startVolume) + ? state.navigation.startLayer + : nullptr; // Create the navigation options // - and get the compatible layers, start layer will be excluded - NavigationOptions<Layer> navOpts(state.stepping.navDir, - true, - resolveSensitive, - resolveMaterial, - resolvePassive, - startLayer, - nullptr); + NavigationOptions<Layer> navOpts(state.stepping.navDir, true, + resolveSensitive, resolveMaterial, + resolvePassive, startLayer, nullptr); // Set also the target surface navOpts.targetSurface = state.navigation.targetSurface; - navOpts.pathLimit = state.stepping.stepSize.value(Cstep::aborter); + navOpts.pathLimit = state.stepping.stepSize.value(Cstep::aborter); // Request the compatible layers - state.navigation.navLayers - = state.navigation.currentVolume->compatibleLayers( - state.geoContext, - stepper.position(state.stepping), - stepper.direction(state.stepping), - navOpts, - navCorr); + state.navigation.navLayers = + state.navigation.currentVolume->compatibleLayers( + state.geoContext, stepper.position(state.stepping), + stepper.direction(state.stepping), navOpts, navCorr); // Layer candidates have been found if (!state.navigation.navLayers.empty()) { @@ -1174,13 +1087,12 @@ private: // Set the iterator to the first state.navigation.navLayerIter = state.navigation.navLayers.begin(); // Setting the step size towards first - if (state.navigation.startLayer - && state.navigation.navLayerIter->object - != state.navigation.startLayer) { + if (state.navigation.startLayer && + state.navigation.navLayerIter->object != + state.navigation.startLayer) { debugLog(state, [&] { return std::string("Target at layer."); }); // update the navigation step size before you return - updateStep(state, - navCorr, + updateStep(state, navCorr, state.navigation.navLayerIter->intersection.pathLength, true); // Trigger the return to the propagator @@ -1210,23 +1122,20 @@ private: /// @param[in] step the step size /// @param[in] release flag steers if the step is released first template <typename propagator_state_t, typename corrector_t> - void - updateStep(propagator_state_t& state, - const corrector_t& navCorr, - double navigationStep, - bool release = false) const - { // update the step + void updateStep(propagator_state_t& state, const corrector_t& navCorr, + double navigationStep, + bool release = false) const { // update the step state.stepping.stepSize.update(navigationStep, Cstep::actor, release); debugLog(state, [&] { std::stringstream dstream; - std::string releaseFlag = release ? "released and " : ""; + std::string releaseFlag = release ? "released and " : ""; dstream << "Navigation stepSize " << releaseFlag << "updated to "; dstream << state.stepping.stepSize.toString(); return dstream.str(); }); /// If we have an initial step and are configured to modify it - if (state.stepping.pathAccumulated == 0. - and navCorr(state.stepping.stepSize)) { + if (state.stepping.pathAccumulated == 0. and + navCorr(state.stepping.stepSize)) { debugLog(state, [&] { std::stringstream dstream; dstream << "Initial navigation step modified to "; @@ -1250,9 +1159,7 @@ private: /// /// boolean return triggers exit to stepper template <typename propagator_state_t, typename stepper_t> - bool - inactive(propagator_state_t& state, const stepper_t& stepper) const - { + bool inactive(propagator_state_t& state, const stepper_t& stepper) const { // Void behavior in case no tracking geometry is present if (!trackingGeometry) { return true; @@ -1304,17 +1211,15 @@ private: /// prefix and length /// @param logAction is a callable function that returns a stremable object template <typename propagator_state_t> - void - debugLog(propagator_state_t& state, - const std::function<std::string()>& logAction) const - { + void debugLog(propagator_state_t& state, + const std::function<std::string()>& logAction) const { if (state.options.debug) { std::string vName = "No Volume"; if (state.navigation.currentVolume) { vName = state.navigation.currentVolume->volumeName(); } std::vector<std::string> lines; - std::string input = logAction(); + std::string input = logAction(); boost::split(lines, input, boost::is_any_of("\n")); for (const auto& line : lines) { std::stringstream dstream; diff --git a/Core/include/Acts/Propagator/Propagator.hpp b/Core/include/Acts/Propagator/Propagator.hpp index cb67ef188f13a2310db369f1c30000b34aabee05..0b8e5c6c1b55a16a6ef0bcb3684312da52e38fb5 100644 --- a/Core/include/Acts/Propagator/Propagator.hpp +++ b/Core/include/Acts/Propagator/Propagator.hpp @@ -36,9 +36,7 @@ namespace Acts { /// @tparam result_list Result pack for additional propagation /// quantities template <typename parameters_t, typename... result_list> -struct PropagatorResult : private detail::Extendable<result_list...> -{ - +struct PropagatorResult : private detail::Extendable<result_list...> { /// Accessor to additional propagation quantities using detail::Extendable<result_list...>::get; @@ -63,24 +61,20 @@ struct PropagatorResult : private detail::Extendable<result_list...> /// @tparam aborter_list_t List of abort conditions tested after each /// propagation step using the current propagation and stepper state /// -template <typename action_list_t = ActionList<>, +template <typename action_list_t = ActionList<>, typename aborter_list_t = AbortList<>> -struct PropagatorOptions -{ - +struct PropagatorOptions { /// Delete default contructor PropagatorOptions() = delete; /// PropagatorOptions copy constructor - PropagatorOptions(const PropagatorOptions<action_list_t, aborter_list_t>& po) - = default; + PropagatorOptions( + const PropagatorOptions<action_list_t, aborter_list_t>& po) = default; /// PropagatorOptions with context - PropagatorOptions(std::reference_wrapper<const GeometryContext> gctx, + PropagatorOptions(std::reference_wrapper<const GeometryContext> gctx, std::reference_wrapper<const MagneticFieldContext> mctx) - : geoContext(gctx), magFieldContext(mctx) - { - } + : geoContext(gctx), magFieldContext(mctx) {} /// @brief Expand the Options with extended aborters /// @@ -88,29 +82,28 @@ struct PropagatorOptions /// /// @param aborters The new aborter list to be used (internally) template <typename extended_aborter_list_t> - PropagatorOptions<action_list_t, extended_aborter_list_t> - extend(extended_aborter_list_t aborters) const - { + PropagatorOptions<action_list_t, extended_aborter_list_t> extend( + extended_aborter_list_t aborters) const { PropagatorOptions<action_list_t, extended_aborter_list_t> eoptions( geoContext, magFieldContext); // Copy the options over - eoptions.direction = direction; - eoptions.absPdgCode = absPdgCode; - eoptions.mass = mass; - eoptions.maxSteps = maxSteps; - eoptions.maxStepSize = maxStepSize; + eoptions.direction = direction; + eoptions.absPdgCode = absPdgCode; + eoptions.mass = mass; + eoptions.maxSteps = maxSteps; + eoptions.maxStepSize = maxStepSize; eoptions.targetTolerance = targetTolerance; - eoptions.pathLimit = pathLimit; - eoptions.loopProtection = loopProtection; - eoptions.loopFraction = loopFraction; + eoptions.pathLimit = pathLimit; + eoptions.loopProtection = loopProtection; + eoptions.loopFraction = loopFraction; // Output option - eoptions.debug = debug; - eoptions.debugString = debugString; + eoptions.debug = debug; + eoptions.debugString = debugString; eoptions.debugPfxWidth = debugPfxWidth; eoptions.debugMsgWidth = debugMsgWidth; // Action / abort list eoptions.actionList = std::move(actionList); - eoptions.abortList = std::move(aborters); + eoptions.abortList = std::move(aborters); // And return the options return eoptions; } @@ -137,17 +130,17 @@ struct PropagatorOptions double targetTolerance = s_onSurfaceTolerance; /// Loop protection step, it adapts the pathLimit - bool loopProtection = true; - double loopFraction = 0.5; ///< Allowed loop fraction, 1 is a full loop + bool loopProtection = true; + double loopFraction = 0.5; ///< Allowed loop fraction, 1 is a full loop /// Debug output steering: // -> @todo: move to a debug struct // - the string where debug messages are stored (optionally) // - it also has some formatting options - bool debug = false; ///< switch debug on - std::string debugString = ""; ///< the string to collect msgs - size_t debugPfxWidth = 30; ///< the prefix width - size_t debugMsgWidth = 50; ///< the mesage width + bool debug = false; ///< switch debug on + std::string debugString = ""; ///< the string to collect msgs + size_t debugPfxWidth = 30; ///< the prefix width + size_t debugMsgWidth = 50; ///< the mesage width // Configurations for Stepper /// Tolerance for the error of the integration @@ -195,10 +188,9 @@ struct PropagatorOptions /// surface type) -> type of internal state object /// template <typename stepper_t, typename navigator_t = detail::VoidNavigator> -class Propagator final -{ - using Jacobian = ActsMatrixD<5, 5>; - using BoundState = std::tuple<BoundParameters, Jacobian, double>; +class Propagator final { + using Jacobian = ActsMatrixD<5, 5>; + using BoundState = std::tuple<BoundParameters, Jacobian, double>; using CurvilinearState = std::tuple<CurvilinearParameters, Jacobian, double>; static_assert(StepperStateConcept<typename stepper_t::State>, @@ -206,7 +198,7 @@ class Propagator final static_assert(StepperConcept<stepper_t>, "Stepper does not fulfill stepper concept."); -public: + public: /// Type of the stepper in use for public scope using Stepper = stepper_t; @@ -221,9 +213,7 @@ public: /// @param stepper The stepper implementation is moved to a private member /// @param navigator The navigator implementation, moved to a private member explicit Propagator(stepper_t stepper, navigator_t navigator = navigator_t()) - : m_stepper(std::move(stepper)), m_navigator(std::move(navigator)) - { - } + : m_stepper(std::move(stepper)), m_navigator(std::move(navigator)) {} /// @brief private Propagator state for navigation and debugging /// @@ -233,9 +223,7 @@ public: /// This struct holds the common state information for propagating /// which is independent of the actual stepper implementation. template <typename propagator_options_t> - struct State - { - + struct State { /// Create the propagator state from the options /// /// @tparam parameters_t the type of the start parameters @@ -245,14 +233,10 @@ public: /// @param topts The options handed over by the propagate call template <typename parameters_t> State(const parameters_t& start, const propagator_options_t& topts) - : options(topts) - , stepping(topts.geoContext, - topts.magFieldContext, - start, - topts.direction, - topts.maxStepSize) - , geoContext(topts.geoContext) - { + : options(topts), + stepping(topts.geoContext, topts.magFieldContext, start, + topts.direction, topts.maxStepSize), + geoContext(topts.geoContext) { // Setting the start surface navigation.startSurface = &start.referenceSurface(); } @@ -270,7 +254,7 @@ public: std::reference_wrapper<const GeometryContext> geoContext; }; -private: + private: /// @brief Helper struct determining the result's type /// /// @tparam parameters_t Type of final track parameters @@ -281,8 +265,7 @@ private: /// ActionList. /// template <typename parameters_t, typename action_list_t> - struct result_type_helper - { + struct result_type_helper { /// @brief Propagation result type for an arbitrary list of additional /// propagation results /// @@ -323,10 +306,9 @@ private: /// /// @return Propagation PropagatorStatus template <typename result_t, typename propagator_state_t> - Result<result_t> - propagate_impl(propagator_state_t& state) const; + Result<result_t> propagate_impl(propagator_state_t& state) const; -public: + public: /// @brief Propagate track parameters /// /// This function performs the propagation of the track parameters using the @@ -345,8 +327,7 @@ public: /// @return Propagation result containing the propagation status, final /// track parameters, and output of actions (if they produce any) /// - template <typename parameters_t, - typename action_list_t, + template <typename parameters_t, typename action_list_t, typename aborter_list_t, template <typename, typename> class propagator_options_t, typename path_aborter_t = detail::PathLimitReached> @@ -376,23 +357,20 @@ public: /// /// @return Propagation result containing the propagation status, final /// track parameters, and output of actions (if they produce any) - template <typename parameters_t, - typename surface_t, - typename action_list_t, + template <typename parameters_t, typename surface_t, typename action_list_t, typename aborter_list_t, template <typename, typename> class propagator_options_t, typename target_aborter_t = detail::SurfaceReached, - typename path_aborter_t = detail::PathLimitReached> - Result<action_list_t_result_t< - typename stepper_t::template return_parameter_type<parameters_t, - surface_t>, - action_list_t>> + typename path_aborter_t = detail::PathLimitReached> + Result< + action_list_t_result_t<typename stepper_t::template return_parameter_type< + parameters_t, surface_t>, + action_list_t>> propagate( - const parameters_t& start, - const surface_t& target, + const parameters_t& start, const surface_t& target, const propagator_options_t<action_list_t, aborter_list_t>& options) const; -private: + private: /// Implementation of propagation algorithm stepper_t m_stepper; @@ -410,9 +388,8 @@ private: /// @param state the propagator state for the debug flag, prefix/length /// @param logAction is a callable function that returns a stremable object template <typename propagator_state_t> - void - debugLog(propagator_state_t& state, - const std::function<std::string()>& logAction) const; + void debugLog(propagator_state_t& state, + const std::function<std::string()>& logAction) const; }; } // namespace Acts diff --git a/Core/include/Acts/Propagator/Propagator.ipp b/Core/include/Acts/Propagator/Propagator.ipp index 4422820149eb58be670d85fc20be8ffc48b84f71..b66c5e5f9bb4a9678ab9800fb58129f9e08049d2 100644 --- a/Core/include/Acts/Propagator/Propagator.ipp +++ b/Core/include/Acts/Propagator/Propagator.ipp @@ -8,10 +8,8 @@ template <typename S, typename N> template <typename result_t, typename propagator_state_t> -auto -Acts::Propagator<S, N>::propagate_impl(propagator_state_t& state) const - -> Result<result_t> -{ +auto Acts::Propagator<S, N>::propagate_impl(propagator_state_t& state) const + -> Result<result_t> { result_t result; // Pre-stepping call to the navigator and action list @@ -83,20 +81,16 @@ Acts::Propagator<S, N>::propagate_impl(propagator_state_t& state) const } template <typename S, typename N> -template <typename parameters_t, - typename action_list_t, +template <typename parameters_t, typename action_list_t, typename aborter_list_t, template <typename, typename> class propagator_options_t, typename path_aborter_t> -auto -Acts::Propagator<S, N>::propagate( +auto Acts::Propagator<S, N>::propagate( const parameters_t& start, const propagator_options_t<action_list_t, aborter_list_t>& options) const -> Result<action_list_t_result_t< typename S::template return_parameter_type<parameters_t>, - action_list_t>> -{ - + action_list_t>> { // Type of track parameters produced by the propagation using ReturnParameterType = typename S::template return_parameter_type<parameters_t>; @@ -111,20 +105,18 @@ Acts::Propagator<S, N>::propagate( // Expand the abort list with a path aborter path_aborter_t pathAborter; - auto abortList = options.abortList.append(pathAborter); + auto abortList = options.abortList.append(pathAborter); // The expanded options (including path limit) - auto eOptions = options.extend(abortList); + auto eOptions = options.extend(abortList); using OptionsType = decltype(eOptions); // Initialize the internal propagator state using StateType = State<OptionsType>; StateType state(start, eOptions); static_assert( - concept::has_method<const S, - Result<double>, - concept::Stepper::step_t, - StateType&>, + concept ::has_method<const S, Result<double>, concept ::Stepper::step_t, + StateType&>, "Step method of the Stepper is not compatible with the propagator " "state"); @@ -140,7 +132,7 @@ Acts::Propagator<S, N>::propagate( if (result.ok()) { auto& propRes = *result; /// Convert into return type and fill the result object - auto curvState = m_stepper.curvilinearState(state.stepping, true); + auto curvState = m_stepper.curvilinearState(state.stepping, true); auto& curvParameters = std::get<CurvilinearParameters>(curvState); // Fill the end parameters propRes.endParameters = std::make_unique<const CurvilinearParameters>( @@ -148,8 +140,8 @@ Acts::Propagator<S, N>::propagate( // Only fill the transport jacobian when covariance transport was done if (state.stepping.covTransport) { auto& tJacobian = std::get<Jacobian>(curvState); - propRes.transportJacobian - = std::make_unique<const Jacobian>(std::move(tJacobian)); + propRes.transportJacobian = + std::make_unique<const Jacobian>(std::move(tJacobian)); } return result; } else { @@ -158,39 +150,32 @@ Acts::Propagator<S, N>::propagate( } template <typename S, typename N> -template <typename parameters_t, - typename surface_t, - typename action_list_t, +template <typename parameters_t, typename surface_t, typename action_list_t, typename aborter_list_t, template <typename, typename> class propagator_options_t, - typename target_aborter_t, - typename path_aborter_t> -auto -Acts::Propagator<S, N>::propagate( - const parameters_t& start, - const surface_t& target, + typename target_aborter_t, typename path_aborter_t> +auto Acts::Propagator<S, N>::propagate( + const parameters_t& start, const surface_t& target, const propagator_options_t<action_list_t, aborter_list_t>& options) const -> Result<action_list_t_result_t< typename S::template return_parameter_type<parameters_t, surface_t>, - action_list_t>> -{ - + action_list_t>> { // Type of track parameters produced at the end of the propagation using return_parameter_type = typename S::template return_parameter_type<parameters_t, surface_t>; // Type of provided options target_aborter_t targetAborter; - path_aborter_t pathAborter; + path_aborter_t pathAborter; auto abortList = options.abortList.append(targetAborter, pathAborter); // Create the extended options and declare their type - auto eOptions = options.extend(abortList); + auto eOptions = options.extend(abortList); using OptionsType = decltype(eOptions); // Type of the full propagation result, including output from actions - using ResultType - = action_list_t_result_t<return_parameter_type, action_list_t>; + using ResultType = + action_list_t_result_t<return_parameter_type, action_list_t>; // Initialize the internal propagator state using StateType = State<OptionsType>; @@ -198,10 +183,8 @@ Acts::Propagator<S, N>::propagate( state.navigation.targetSurface = ⌖ static_assert( - concept::has_method<const S, - Result<double>, - concept::Stepper::step_t, - StateType&>, + concept ::has_method<const S, Result<double>, concept ::Stepper::step_t, + StateType&>, "Step method of the Stepper is not compatible with the propagator " "state"); @@ -215,16 +198,16 @@ Acts::Propagator<S, N>::propagate( if (result.ok()) { auto& propRes = *result; // Compute the final results and mark the propagation as successful - auto bs = m_stepper.boundState(state.stepping, target, true); + auto bs = m_stepper.boundState(state.stepping, target, true); auto& boundParameters = std::get<BoundParameters>(bs); // Fill the end parameters - propRes.endParameters - = std::make_unique<const BoundParameters>(std::move(boundParameters)); + propRes.endParameters = + std::make_unique<const BoundParameters>(std::move(boundParameters)); // Only fill the transport jacobian when covariance transport was done if (state.stepping.covTransport) { auto& tJacobian = std::get<Jacobian>(bs); - propRes.transportJacobian - = std::make_unique<const Jacobian>(std::move(tJacobian)); + propRes.transportJacobian = + std::make_unique<const Jacobian>(std::move(tJacobian)); } return result; } else { @@ -234,14 +217,12 @@ Acts::Propagator<S, N>::propagate( template <typename S, typename N> template <typename propagator_state_t> -void -Acts::Propagator<S, N>::debugLog( - propagator_state_t& state, - const std::function<std::string()>& logAction) const -{ +void Acts::Propagator<S, N>::debugLog( + propagator_state_t& state, + const std::function<std::string()>& logAction) const { if (state.options.debug) { std::vector<std::string> lines; - std::string input = logAction(); + std::string input = logAction(); boost::split(lines, input, boost::is_any_of("\n")); for (const auto& line : lines) { std::stringstream dstream; diff --git a/Core/include/Acts/Propagator/PropagatorError.hpp b/Core/include/Acts/Propagator/PropagatorError.hpp index 72a04aeaea1d28ae384e26972922d163a71dd812..e135d08ae4dff5a6e770a2558a256a2f40a83ed6 100644 --- a/Core/include/Acts/Propagator/PropagatorError.hpp +++ b/Core/include/Acts/Propagator/PropagatorError.hpp @@ -17,51 +17,38 @@ namespace Acts { enum class PropagatorError { Failure = 1, WrongDirection = 2 }; namespace detail { - // Define a custom error code category derived from std::error_category - class PropagatorErrorCategory : public std::error_category - { - public: - // Return a short descriptive name for the category - const char* - name() const noexcept final - { - return "PropagatorError"; - } - // Return what each enum means in text - std::string - message(int c) const final - { - switch (static_cast<PropagatorError>(c)) { +// Define a custom error code category derived from std::error_category +class PropagatorErrorCategory : public std::error_category { + public: + // Return a short descriptive name for the category + const char* name() const noexcept final { return "PropagatorError"; } + // Return what each enum means in text + std::string message(int c) const final { + switch (static_cast<PropagatorError>(c)) { case PropagatorError::Failure: return "Propagation failed"; case PropagatorError::WrongDirection: return "Propagation occurred in the wrong direction"; default: return "unknown"; - } } - }; -} + } +}; +} // namespace detail // Declare a global function returning a static instance of the custom category -extern inline const detail::PropagatorErrorCategory& -PropagatorErrorCategory() -{ +extern inline const detail::PropagatorErrorCategory& PropagatorErrorCategory() { static detail::PropagatorErrorCategory c; return c; } -inline std::error_code -make_error_code(Acts::PropagatorError e) -{ +inline std::error_code make_error_code(Acts::PropagatorError e) { return {static_cast<int>(e), Acts::PropagatorErrorCategory()}; } -} +} // namespace Acts namespace std { // register with STL template <> -struct is_error_code_enum<Acts::PropagatorError> : std::true_type -{ -}; -} +struct is_error_code_enum<Acts::PropagatorError> : std::true_type {}; +} // namespace std diff --git a/Core/include/Acts/Propagator/StepperConcept.hpp b/Core/include/Acts/Propagator/StepperConcept.hpp index 5feedb794ff78e56fd7797f9a8cb6a06b50d66aa..73dcbfd9dc18b7d23c355ffadc1f531bcedc9f69 100644 --- a/Core/include/Acts/Propagator/StepperConcept.hpp +++ b/Core/include/Acts/Propagator/StepperConcept.hpp @@ -18,46 +18,46 @@ class Surface; namespace concept { namespace Stepper { - template <typename T> - using state_t = typename T::State; + template <typename T> + using state_t = typename T::State; - template <typename T> - using return_t = typename T::template return_parameter_type<void, void>; + template <typename T> + using return_t = typename T::template return_parameter_type<void, void>; - template <typename T> - using jacobian_t = typename T::Jacobian; - template <typename T> - using covariance_t = typename T::Covariance; - template <typename T> - using bound_state_t = typename T::BoundState; - template <typename T> - using curvilinear_state_t = typename T::CurvilinearState; + template <typename T> + using jacobian_t = typename T::Jacobian; + template <typename T> + using covariance_t = typename T::Covariance; + template <typename T> + using bound_state_t = typename T::BoundState; + template <typename T> + using curvilinear_state_t = typename T::CurvilinearState; - METHOD_TRAIT(get_field_t, getField); - METHOD_TRAIT(position_t, position); - METHOD_TRAIT(direction_t, direction); - METHOD_TRAIT(momentum_t, momentum); - METHOD_TRAIT(charge_t, charge); - METHOD_TRAIT(surface_reached_t, surfaceReached); - METHOD_TRAIT(bound_state_method_t, boundState); - METHOD_TRAIT(curvilinear_state_method_t, curvilinearState); - METHOD_TRAIT(update_t, update); - METHOD_TRAIT(covariance_transport_t, covarianceTransport); - METHOD_TRAIT(step_t, step); - METHOD_TRAIT(corrector_t, corrector); + METHOD_TRAIT(get_field_t, getField); + METHOD_TRAIT(position_t, position); + METHOD_TRAIT(direction_t, direction); + METHOD_TRAIT(momentum_t, momentum); + METHOD_TRAIT(charge_t, charge); + METHOD_TRAIT(surface_reached_t, surfaceReached); + METHOD_TRAIT(bound_state_method_t, boundState); + METHOD_TRAIT(curvilinear_state_method_t, curvilinearState); + METHOD_TRAIT(update_t, update); + METHOD_TRAIT(covariance_transport_t, covarianceTransport); + METHOD_TRAIT(step_t, step); + METHOD_TRAIT(corrector_t, corrector); - template <typename T> - using cov_transport_t = decltype(std::declval<T>().covTransport); - template <typename T> - using cov_t = decltype(std::declval<T>().cov); - template <typename T> - using nav_dir_t = decltype(std::declval<T>().navDir); - template <typename T> - using path_accumulated_t = decltype(std::declval<T>().pathAccumulated); - template <typename T> - using step_size_t = decltype(std::declval<T>().stepSize); + template <typename T> + using cov_transport_t = decltype(std::declval<T>().covTransport); + template <typename T> + using cov_t = decltype(std::declval<T>().cov); + template <typename T> + using nav_dir_t = decltype(std::declval<T>().navDir); + template <typename T> + using path_accumulated_t = decltype(std::declval<T>().pathAccumulated); + template <typename T> + using step_size_t = decltype(std::declval<T>().stepSize); - // clang-format off + // clang-format off template <typename S> constexpr bool StepperStateConcept = require<has_member<S, cov_transport_t, bool>, @@ -66,9 +66,9 @@ namespace concept { has_member<S, path_accumulated_t, double>, has_member<S, step_size_t, detail::ConstrainedStep> >; - // clang-format on + // clang-format on - // clang-format off + // clang-format off template <typename S, typename state = typename S::State> struct StepperConcept { constexpr static bool state_exists = exists<state_t, S>; @@ -126,14 +126,14 @@ namespace concept { corrector_exists, covariance_transport_exists>; }; - // clang-format on - } -} + // clang-format on + } // namespace Stepper +} // namespace concept template <typename stepper, typename state = typename stepper::State> -constexpr bool StepperConcept - = Acts::concept::Stepper::StepperConcept<stepper, state>::value; +constexpr bool StepperConcept = + Acts::concept ::Stepper::StepperConcept<stepper, state>::value; template <typename stepper> -constexpr bool StepperStateConcept - = Acts::concept::Stepper::StepperStateConcept<stepper>; -} +constexpr bool StepperStateConcept = + Acts::concept ::Stepper::StepperStateConcept<stepper>; +} // namespace Acts diff --git a/Core/include/Acts/Propagator/StepperExtensionList.hpp b/Core/include/Acts/Propagator/StepperExtensionList.hpp index d9a9b82d5112ec63b2a7f332231fb68bbd3d8b9a..c1fa8feedebda2a8fc1f0aaa80a9ac6def1d08a4 100644 --- a/Core/include/Acts/Propagator/StepperExtensionList.hpp +++ b/Core/include/Acts/Propagator/StepperExtensionList.hpp @@ -31,9 +31,8 @@ namespace Acts { /// much momentum during the step) /// @tparam extensions Types of the extensions template <typename... extensions> -struct StepperExtensionList : private detail::Extendable<extensions...> -{ -private: +struct StepperExtensionList : private detail::Extendable<extensions...> { + private: // Checkout for duplicates in the extensions static_assert(not detail::has_duplicates_v<extensions...>, "same extension type specified several times"); @@ -50,7 +49,7 @@ private: // Vector of valid extensions for a step std::array<bool, nExtensions> validExtensions; -public: + public: // Access to an extension using detail::Extendable<extensions...>::get; @@ -62,18 +61,16 @@ public: /// @param [in] state State of the propagator /// @param [in] stepper Stepper of the propagation template <typename propagator_state_t, typename stepper_t> - bool - validExtensionForStep(const propagator_state_t& state, - const stepper_t& stepper) - { + bool validExtensionForStep(const propagator_state_t& state, + const stepper_t& stepper) { std::array<int, nExtensions> bids; // Ask all extensions for a boolean statement of their validity impl::bid(tuple(), state, stepper, bids); // Post-process the vector in an auctioneer validExtensions = state.stepping.auctioneer(std::move(bids)); - return (std::find(validExtensions.begin(), validExtensions.end(), true) - != validExtensions.end()); + return (std::find(validExtensions.begin(), validExtensions.end(), true) != + validExtensions.end()); } /// @brief This functions broadcasts the call for evaluating k1. It collects @@ -81,12 +78,8 @@ public: /// passes them forward for evaluation and returns a boolean as indicator if /// the evaluation is valid. template <typename propagator_state_t, typename stepper_t> - bool - k1(const propagator_state_t& state, - const stepper_t& stepper, - Vector3D& knew, - const Vector3D& bField) - { + bool k1(const propagator_state_t& state, const stepper_t& stepper, + Vector3D& knew, const Vector3D& bField) { return impl::k(tuple(), state, stepper, knew, bField, validExtensions); } @@ -94,60 +87,41 @@ public: /// all arguments and extensions and passes them forward for evaluation and /// returns a boolean as indicator if the evaluation is valid. template <typename propagator_state_t, typename stepper_t> - bool - k2(const propagator_state_t& state, - const stepper_t& stepper, - Vector3D& knew, - const Vector3D& bField, - const double h, - const Vector3D& kprev) - { - return impl::k( - tuple(), state, stepper, knew, bField, validExtensions, 1, h, kprev); + bool k2(const propagator_state_t& state, const stepper_t& stepper, + Vector3D& knew, const Vector3D& bField, const double h, + const Vector3D& kprev) { + return impl::k(tuple(), state, stepper, knew, bField, validExtensions, 1, h, + kprev); } /// @brief This functions broadcasts the call for evaluating k3. It collects /// all arguments and extensions and passes them forward for evaluation and /// returns a boolean as indicator if the evaluation is valid. template <typename propagator_state_t, typename stepper_t> - bool - k3(const propagator_state_t& state, - const stepper_t& stepper, - Vector3D& knew, - const Vector3D& bField, - const double h, - const Vector3D& kprev) - { - return impl::k( - tuple(), state, stepper, knew, bField, validExtensions, 2, h, kprev); + bool k3(const propagator_state_t& state, const stepper_t& stepper, + Vector3D& knew, const Vector3D& bField, const double h, + const Vector3D& kprev) { + return impl::k(tuple(), state, stepper, knew, bField, validExtensions, 2, h, + kprev); } /// @brief This functions broadcasts the call for evaluating k4. It collects /// all arguments and extensions and passes them forward for evaluation and /// returns a boolean as indicator if the evaluation is valid. template <typename propagator_state_t, typename stepper_t> - bool - k4(const propagator_state_t& state, - const stepper_t& stepper, - Vector3D& knew, - const Vector3D& bField, - const double h, - const Vector3D& kprev) - { - return impl::k( - tuple(), state, stepper, knew, bField, validExtensions, 3, h, kprev); + bool k4(const propagator_state_t& state, const stepper_t& stepper, + Vector3D& knew, const Vector3D& bField, const double h, + const Vector3D& kprev) { + return impl::k(tuple(), state, stepper, knew, bField, validExtensions, 3, h, + kprev); } /// @brief This functions broadcasts the call of the method finalize(). It /// collects all extensions and arguments and passes them forward for /// evaluation and returns a boolean. template <typename propagator_state_t, typename stepper_t> - bool - finalize(propagator_state_t& state, - const stepper_t& stepper, - const double h, - ActsMatrixD<7, 7>& D) - { + bool finalize(propagator_state_t& state, const stepper_t& stepper, + const double h, ActsMatrixD<7, 7>& D) { return impl::finalize(tuple(), state, stepper, h, D, validExtensions); } @@ -155,9 +129,8 @@ public: /// collects all extensions and arguments and passes them forward for /// evaluation and returns a boolean. template <typename propagator_state_t, typename stepper_t> - bool - finalize(propagator_state_t& state, const stepper_t& stepper, const double h) - { + bool finalize(propagator_state_t& state, const stepper_t& stepper, + const double h) { return impl::finalize(tuple(), state, stepper, h, validExtensions); } }; diff --git a/Core/include/Acts/Propagator/StraightLineStepper.hpp b/Core/include/Acts/Propagator/StraightLineStepper.hpp index 3c08a5a1a013723adb84b6c2c6e0f2cfcbcda2b1..6f6158966717b4cdfeb36c2494e40ea5071cdba2 100644 --- a/Core/include/Acts/Propagator/StraightLineStepper.hpp +++ b/Core/include/Acts/Propagator/StraightLineStepper.hpp @@ -26,38 +26,32 @@ namespace Acts { /// The straight line stepper is a simple navigation stepper /// to be used to navigate through the tracking geometry. It can be /// used for simple material mapping, navigation validation -class StraightLineStepper -{ - -private: +class StraightLineStepper { + private: // This struct is a meta-function which normally maps to BoundParameters... template <typename T, typename S> - struct s - { + struct s { using type = BoundParameters; }; // ...unless type S is int, in which case it maps to Curvilinear parameters template <typename T> - struct s<T, int> - { + struct s<T, int> { using type = CurvilinearParameters; }; -public: + public: using cstep = detail::ConstrainedStep; - using Corrector = VoidIntersectionCorrector; - using Jacobian = ActsMatrixD<5, 5>; - using Covariance = ActsMatrixD<5, 5>; - using BoundState = std::tuple<BoundParameters, Jacobian, double>; + using Corrector = VoidIntersectionCorrector; + using Jacobian = ActsMatrixD<5, 5>; + using Covariance = ActsMatrixD<5, 5>; + using BoundState = std::tuple<BoundParameters, Jacobian, double>; using CurvilinearState = std::tuple<CurvilinearParameters, Jacobian, double>; /// State for track parameter propagation /// - struct State - { - + struct State { /// Delete the default constructor State() = delete; @@ -73,22 +67,19 @@ public: template <typename parameters_t> explicit State(std::reference_wrapper<const GeometryContext> gctx, std::reference_wrapper<const MagneticFieldContext> /*mctx*/, - const parameters_t& par, - NavigationDirection ndir = forward, + const parameters_t& par, NavigationDirection ndir = forward, double ssize = std::numeric_limits<double>::max()) - : pos(par.position()) - , dir(par.momentum().normalized()) - , p(par.momentum().norm()) - , q(par.charge()) - , navDir(ndir) - , stepSize(ssize) - , geoContext(gctx) - { - } + : pos(par.position()), + dir(par.momentum().normalized()), + p(par.momentum().norm()), + q(par.charge()), + navDir(ndir), + stepSize(ssize), + geoContext(gctx) {} /// Boolean to indiciate if you need covariance transport - bool covTransport = false; - ActsSymMatrixD<5> cov = ActsSymMatrixD<5>::Zero(); + bool covTransport = false; + ActsSymMatrixD<5> cov = ActsSymMatrixD<5>::Zero(); /// Global particle position Vector3D pos = Vector3D(0., 0., 0.); @@ -137,40 +128,22 @@ public: /// @param [in,out] state is the propagation state associated with the track /// the magnetic field cell is used (and potentially updated) /// @param [in] pos is the field position - Vector3D - getField(State& /*state*/, const Vector3D& /*pos*/) const - { + Vector3D getField(State& /*state*/, const Vector3D& /*pos*/) const { // get the field from the cell return Vector3D(0., 0., 0.); } /// Global particle position accessor - Vector3D - position(const State& state) const - { - return state.pos; - } + Vector3D position(const State& state) const { return state.pos; } /// Momentum direction accessor - Vector3D - direction(const State& state) const - { - return state.dir; - } + Vector3D direction(const State& state) const { return state.dir; } /// Momentum accessor - double - momentum(const State& state) const - { - return state.p; - } + double momentum(const State& state) const { return state.p; } /// Charge access - double - charge(const State& state) const - { - return state.q; - } + double charge(const State& state) const { return state.q; } /// Tests if the state reached a surface /// @@ -178,11 +151,9 @@ public: /// @param [in] surface Surface that is tested /// /// @return Boolean statement if surface is reached by state - bool - surfaceReached(const State& state, const Surface* surface) const - { - return surface->isOnSurface( - state.geoContext, position(state), direction(state), true); + bool surfaceReached(const State& state, const Surface* surface) const { + return surface->isOnSurface(state.geoContext, position(state), + direction(state), true); } /// Create and return the bound state at the current position @@ -197,19 +168,14 @@ public: /// - the parameters at the surface /// - the stepwise jacobian towards it (from last bound) /// - and the path length (from start - for ordering) - BoundState - boundState(State& state, const Surface& surface, bool /*unused*/) const - { + BoundState boundState(State& state, const Surface& surface, + bool /*unused*/) const { // Create the bound parameters - BoundParameters parameters(state.geoContext, - nullptr, - state.pos, - state.p * state.dir, - state.q, + BoundParameters parameters(state.geoContext, nullptr, state.pos, + state.p * state.dir, state.q, surface.getSharedPtr()); // Create the bound state - BoundState bState{std::move(parameters), - ActsMatrixD<5, 5>::Identity(), + BoundState bState{std::move(parameters), ActsMatrixD<5, 5>::Identity(), state.pathAccumulated}; /// Return the State return bState; @@ -225,12 +191,10 @@ public: /// - the curvilinear parameters at given position /// - the stepweise jacobian towards it (from last bound) /// - and the path length (from start - for ordering) - CurvilinearState - curvilinearState(State& state, bool /*unused*/) const - { + CurvilinearState curvilinearState(State& state, bool /*unused*/) const { // Create the curvilinear parameters - CurvilinearParameters parameters( - nullptr, state.pos, state.p * state.dir, state.q); + CurvilinearParameters parameters(nullptr, state.pos, state.p * state.dir, + state.q); // Create the bound state CurvilinearState curvState{std::move(parameters), ActsMatrixD<5, 5>::Identity(), @@ -243,13 +207,11 @@ public: /// /// @param [in,out] state State object that will be updated /// @param [in] pars Parameters that will be written into @p state - void - update(State& state, const BoundParameters& pars) const - { + void update(State& state, const BoundParameters& pars) const { const auto& mom = pars.momentum(); - state.pos = pars.position(); - state.dir = mom.normalized(); - state.p = mom.norm(); + state.pos = pars.position(); + state.dir = mom.normalized(); + state.p = mom.norm(); } /// Method to update momentum, direction and p @@ -258,21 +220,15 @@ public: /// @param [in] uposition the updated position /// @param [in] udirection the updated direction /// @param [in] up the updated momentum value - void - update(State& state, - const Vector3D& uposition, - const Vector3D& udirection, - double up) const - { + void update(State& state, const Vector3D& uposition, + const Vector3D& udirection, double up) const { state.pos = uposition; state.dir = udirection; - state.p = up; + state.p = up; } /// Return a corrector - VoidIntersectionCorrector - corrector(State& /*state*/) const - { + VoidIntersectionCorrector corrector(State& /*state*/) const { return VoidIntersectionCorrector(); } @@ -284,10 +240,8 @@ public: /// @param [in] reinitialize is a flag to steer whether the /// state should be reinitialized at the new /// position - void - covarianceTransport(State& /*state*/, bool /*reinitialize = false*/) const - { - } + void covarianceTransport(State& /*state*/, + bool /*reinitialize = false*/) const {} /// Method for on-demand transport of the covariance /// to a new curvilinear frame at current position, @@ -303,12 +257,8 @@ public: /// position /// @note no check is done if the position is actually on the surface /// - void - covarianceTransport(State& /*unused*/, - const Surface& /*surface*/, - bool /*reinitialize = false*/) const - { - } + void covarianceTransport(State& /*unused*/, const Surface& /*surface*/, + bool /*reinitialize = false*/) const {} /// Perform a straight line propagation step /// @@ -321,9 +271,7 @@ public: /// /// @return the step size taken template <typename propagator_state_t> - Result<double> - step(propagator_state_t& state) const - { + Result<double> step(propagator_state_t& state) const { // use the adjusted step size const double h = state.stepping.stepSize; // Update the track parameters according to the equations of motion diff --git a/Core/include/Acts/Propagator/SurfaceCollector.hpp b/Core/include/Acts/Propagator/SurfaceCollector.hpp index c42a5f0435d0c6d4eea0843081e364ceb2311c0f..7ea6f224d7d2a2a8f05982c844fb3ff95c0c30c5 100644 --- a/Core/include/Acts/Propagator/SurfaceCollector.hpp +++ b/Core/include/Acts/Propagator/SurfaceCollector.hpp @@ -14,11 +14,10 @@ namespace Acts { /// The information to be writtern out per hit surface -struct SurfaceHit -{ +struct SurfaceHit { const Surface* surface = nullptr; - Vector3D position; - Vector3D direction; + Vector3D position; + Vector3D direction; }; /// A Surface Collector struct @@ -28,17 +27,14 @@ struct SurfaceHit /// that satisfies the selector, it is recorded /// for further usage in the flow. template <typename Selector> -struct SurfaceCollector -{ - +struct SurfaceCollector { /// The selector used for this surface Selector selector; /// Simple result struct to be returned /// It has all the SurfaceHit objects that /// are collected (and thus have been selected) - struct this_result - { + struct this_result { std::vector<SurfaceHit> collected; }; @@ -56,19 +52,16 @@ struct SurfaceCollector /// @param [in] stepper The stepper in use /// @param [in,out] result is the mutable result object template <typename propagator_state_t, typename stepper_t> - void - operator()(propagator_state_t& state, - const stepper_t& stepper, - result_type& result) const - { + void operator()(propagator_state_t& state, const stepper_t& stepper, + result_type& result) const { // a current surface has been assigned by the navigator // - if (state.navigation.currentSurface - && selector(*state.navigation.currentSurface)) { + if (state.navigation.currentSurface && + selector(*state.navigation.currentSurface)) { // create for recording SurfaceHit surface_hit; - surface_hit.surface = state.navigation.currentSurface; - surface_hit.position = stepper.position(state.stepping); + surface_hit.surface = state.navigation.currentSurface; + surface_hit.position = stepper.position(state.stepping); surface_hit.direction = stepper.direction(state.stepping); // save if in the result result.collected.push_back(surface_hit); @@ -78,10 +71,8 @@ struct SurfaceCollector /// Pure observer interface /// - this does not apply to the surface collector template <typename propagator_state_t, typename stepper_t> - void - operator()(propagator_state_t& /*state*/, const stepper_t& /*unused*/) const - { - } + void operator()(propagator_state_t& /*state*/, + const stepper_t& /*unused*/) const {} }; } // namespace Acts diff --git a/Core/include/Acts/Propagator/detail/Auctioneer.hpp b/Core/include/Acts/Propagator/detail/Auctioneer.hpp index 2270f7f3ef3cf3c2026bddaa806929855548f56d..2671b2650ef6d1363e96e77135c909b45e71ea20 100644 --- a/Core/include/Acts/Propagator/detail/Auctioneer.hpp +++ b/Core/include/Acts/Propagator/detail/Auctioneer.hpp @@ -12,107 +12,98 @@ namespace Acts { namespace detail { - /// The StepperExtensionList allows to add an arbitrary number of step - /// evaluation algorithms for the RKN4 evaluation. These can be categorised in - /// two general types: - /// a) Step evaluation that should not be evaluated along with other - /// extensions, or at least would overwrite partial results. This means that - /// in the best case unnecessary/redundant calculation would be performed, in - /// the worst case the evaluation would go wrong. - /// b) The step evaluation remains untouched and only further calculations are - /// performed (like additional features or data gathering) that can be treated - /// as independent of the basic step evaluation in type a). These types can be - /// added but do not require special treatment in order to not ruin the step - /// evaluation. - /// The concept of the auctioneers aims in the first place to judge which - /// extension of category a) is the one to go. Although every extension can - /// judge if it is valid based on the data given from the state of stepper, - /// multiple extensions from type a) could fulfill their dependencies. Since - /// an extension does not know about other extensions, the decision for the - /// best extension for the step can only be estimated on a global scope. This - /// is the job of the auctioneers. - /// - /// TODO: An anticipation of an optimal concept of the input (and maybe also - /// the output) of the call operator of an auctioneer cannot be performed at - /// the current stage. At the current stage, a real bid-system would be pure - /// guessing. +/// The StepperExtensionList allows to add an arbitrary number of step +/// evaluation algorithms for the RKN4 evaluation. These can be categorised in +/// two general types: +/// a) Step evaluation that should not be evaluated along with other +/// extensions, or at least would overwrite partial results. This means that +/// in the best case unnecessary/redundant calculation would be performed, in +/// the worst case the evaluation would go wrong. +/// b) The step evaluation remains untouched and only further calculations are +/// performed (like additional features or data gathering) that can be treated +/// as independent of the basic step evaluation in type a). These types can be +/// added but do not require special treatment in order to not ruin the step +/// evaluation. +/// The concept of the auctioneers aims in the first place to judge which +/// extension of category a) is the one to go. Although every extension can +/// judge if it is valid based on the data given from the state of stepper, +/// multiple extensions from type a) could fulfill their dependencies. Since +/// an extension does not know about other extensions, the decision for the +/// best extension for the step can only be estimated on a global scope. This +/// is the job of the auctioneers. +/// +/// TODO: An anticipation of an optimal concept of the input (and maybe also +/// the output) of the call operator of an auctioneer cannot be performed at +/// the current stage. At the current stage, a real bid-system would be pure +/// guessing. - /// @brief Auctioneer that takes all extensions as valid that make a valid bid - struct VoidAuctioneer - { - /// @brief Default constructor - VoidAuctioneer() = default; +/// @brief Auctioneer that takes all extensions as valid that make a valid bid +struct VoidAuctioneer { + /// @brief Default constructor + VoidAuctioneer() = default; - /// @brief Call operator that returns the list of valid candidates as valids - /// - /// @param [in] vCandidates Candidates that are treated as valid extensions - /// @return The to vCandidates identical list of valid extensions - template <long unsigned int N> - std::array<bool, N> - operator()(std::array<int, N> vCandidates) const - { - std::array<bool, N> valids; + /// @brief Call operator that returns the list of valid candidates as valids + /// + /// @param [in] vCandidates Candidates that are treated as valid extensions + /// @return The to vCandidates identical list of valid extensions + template <long unsigned int N> + std::array<bool, N> operator()(std::array<int, N> vCandidates) const { + std::array<bool, N> valids; - for (unsigned int i = 0; i < vCandidates.size(); i++) { - valids[i] = (vCandidates[i] > 0) ? true : false; - } - return valids; + for (unsigned int i = 0; i < vCandidates.size(); i++) { + valids[i] = (vCandidates[i] > 0) ? true : false; } - }; + return valids; + } +}; - /// @brief Auctioneer that states only the first one that makes a valid bid - struct FirstValidAuctioneer - { - /// @brief Default constructor - FirstValidAuctioneer() = default; +/// @brief Auctioneer that states only the first one that makes a valid bid +struct FirstValidAuctioneer { + /// @brief Default constructor + FirstValidAuctioneer() = default; - /// @brief Call operator that states the first valid extension as the only - /// valid extension - /// - /// @param [in] vCandidates Candidates for a valid extension - /// @return List with at most one valid extension - template <long unsigned int N> - std::array<bool, N> - operator()(std::array<int, N> vCandidates) const - { - std::array<bool, N> valids = {}; + /// @brief Call operator that states the first valid extension as the only + /// valid extension + /// + /// @param [in] vCandidates Candidates for a valid extension + /// @return List with at most one valid extension + template <long unsigned int N> + std::array<bool, N> operator()(std::array<int, N> vCandidates) const { + std::array<bool, N> valids = {}; - for (unsigned int i = 0; i < vCandidates.size(); i++) { - if (vCandidates[i] > 0) { - valids[i] = true; - return valids; - } + for (unsigned int i = 0; i < vCandidates.size(); i++) { + if (vCandidates[i] > 0) { + valids[i] = true; + return valids; } - return valids; } - }; + return valids; + } +}; - /// @brief Auctioneer that makes only the highest bidding extension valid. If - /// multiple elements have the same int, the first one with this value is - /// picked. - struct HighestValidAuctioneer - { - /// @brief Default constructor - HighestValidAuctioneer() = default; +/// @brief Auctioneer that makes only the highest bidding extension valid. If +/// multiple elements have the same int, the first one with this value is +/// picked. +struct HighestValidAuctioneer { + /// @brief Default constructor + HighestValidAuctioneer() = default; - /// @brief Call operator that states the highest bidding extension as the - /// only - /// valid extension - /// - /// @param [in] vCandidates Candidates for a valid extension - /// @return List with at most one valid extension - template <long unsigned int N> - std::array<bool, N> - operator()(std::array<int, N> vCandidates) const - { - std::array<bool, N> valids = {}; + /// @brief Call operator that states the highest bidding extension as the + /// only + /// valid extension + /// + /// @param [in] vCandidates Candidates for a valid extension + /// @return List with at most one valid extension + template <long unsigned int N> + std::array<bool, N> operator()(std::array<int, N> vCandidates) const { + std::array<bool, N> valids = {}; - auto highscore = std::max_element(vCandidates.begin(), vCandidates.end()); - valids.at(std::distance(vCandidates.begin(), highscore)) = true; + auto highscore = std::max_element(vCandidates.begin(), vCandidates.end()); + valids.at(std::distance(vCandidates.begin(), highscore)) = true; - return valids; - } - }; + return valids; + } +}; } // namespace detail } // namespace Acts diff --git a/Core/include/Acts/Propagator/detail/Constants.hpp b/Core/include/Acts/Propagator/detail/Constants.hpp index 6b225eef8bf1d1f0aa783ae1d40312c7cc4c3d84..4027d0789c58dcdd6e3e262cf1596a58f0b6fba0 100644 --- a/Core/include/Acts/Propagator/detail/Constants.hpp +++ b/Core/include/Acts/Propagator/detail/Constants.hpp @@ -15,35 +15,35 @@ namespace Acts { namespace constants { - // See (1) table 32.1 - // K/A*Z = 0.5 * 30.7075MeV/(g/mm2) * Z/A * rho[g/mm3] - constexpr double ka_BetheBloch = 30.7075 * (units::_MeV * units::_mm2); +// See (1) table 32.1 +// K/A*Z = 0.5 * 30.7075MeV/(g/mm2) * Z/A * rho[g/mm3] +constexpr double ka_BetheBloch = 30.7075 * (units::_MeV * units::_mm2); - /// Ionisation potential - /// Ionization - Bethe-Bloch - /// See ATL-SOFT-PUB-2008-003 equation (4) - /// 16 eV * Z**0.9 - constexpr double eionisation = 16 * units::_eV; +/// Ionisation potential +/// Ionization - Bethe-Bloch +/// See ATL-SOFT-PUB-2008-003 equation (4) +/// 16 eV * Z**0.9 +constexpr double eionisation = 16 * units::_eV; - /// Plasma energy [ eV ] - constexpr double eplasma = 28.816 * units::_eV; +/// Plasma energy [ eV ] +constexpr double eplasma = 28.816 * units::_eV; - /// Fine structure constexprant - constexpr double alpha = 1. / 137.; +/// Fine structure constexprant +constexpr double alpha = 1. / 137.; - /// Multiple scattering parameters for MIPS [ in MeV] - constexpr double main_RutherfordScott = 13.6 * units::_MeV; - constexpr double log_RutherfordScott = 0.038; +/// Multiple scattering parameters for MIPS [ in MeV] +constexpr double main_RutherfordScott = 13.6 * units::_MeV; +constexpr double log_RutherfordScott = 0.038; - /// Multiple scattering parameters for electrons [ in MeV ] - constexpr double main_RossiGreisen = 17.5 * units::_MeV; - constexpr double log_RossiGreisen = 0.125; +/// Multiple scattering parameters for electrons [ in MeV ] +constexpr double main_RossiGreisen = 17.5 * units::_MeV; +constexpr double log_RossiGreisen = 0.125; - /// Electron mass [ in MeV ] - constexpr double me = 0.51099891 * units::_MeV; +/// Electron mass [ in MeV ] +constexpr double me = 0.51099891 * units::_MeV; - /// 4 * scaling factor for Landau FWHM to gaussian sigma - const double landau2gauss = 2. / (std::sqrt(2. * std::log(2.))); +/// 4 * scaling factor for Landau FWHM to gaussian sigma +const double landau2gauss = 2. / (std::sqrt(2. * std::log(2.))); } // end of namespace constants diff --git a/Core/include/Acts/Propagator/detail/ConstrainedStep.hpp b/Core/include/Acts/Propagator/detail/ConstrainedStep.hpp index 791f0b8d88f86b4ca1c619d2a5e06c09b9604b63..6f2eb7785cef76f028c4b47c3d453c1162c43176 100644 --- a/Core/include/Acts/Propagator/detail/ConstrainedStep.hpp +++ b/Core/include/Acts/Propagator/detail/ConstrainedStep.hpp @@ -19,128 +19,107 @@ namespace Acts { namespace detail { - /// A constrained step class for the steppers - struct ConstrainedStep - { - - /// the types of constraints - /// from accuracy - this can vary up and down given a good step estimator - /// form actor - this would be a typical navigation step - /// from aborter - this would be a target condition - /// from user - this is user given for what reason ever - enum Type : int { accuracy = 0, actor = 1, aborter = 2, user = 3 }; - - /// the step size tuple - std::array<double, 4> values = {{std::numeric_limits<double>::max(), - std::numeric_limits<double>::max(), - std::numeric_limits<double>::max(), - std::numeric_limits<double>::max()}}; - - /// The Navigation direction - NavigationDirection direction = forward; - - /// Update the step size of a certain type - /// - /// Only navigation and target abortion step size - /// updates may change the sign due to overstepping - /// - /// @param value is the new value to be updated - /// @param type is the constraint type - void - update(const double& value, Type type, bool releaseStep = false) - { - if (releaseStep) { - release(type); - } - // The check the current value and set it if appropriate - double cValue = values[type]; - values[type] = cValue * cValue < value * value ? cValue : value; - } - - /// release a certain constraint value - /// to the (signed) biggest value available, hence - /// it depends on the direction - /// - /// @param type is the constraint type to be released - void - release(Type type) - { - double mvalue = (direction == forward) - ? (*std::max_element(values.begin(), values.end())) - : (*std::min_element(values.begin(), values.end())); - values[type] = mvalue; - } - - /// constructor from double - /// @paramn value is the initial value for all steps - ConstrainedStep(double value) - : values({{value, value, value, value}}) - , direction(value > 0. ? forward : backward) - { +/// A constrained step class for the steppers +struct ConstrainedStep { + /// the types of constraints + /// from accuracy - this can vary up and down given a good step estimator + /// form actor - this would be a typical navigation step + /// from aborter - this would be a target condition + /// from user - this is user given for what reason ever + enum Type : int { accuracy = 0, actor = 1, aborter = 2, user = 3 }; + + /// the step size tuple + std::array<double, 4> values = { + {std::numeric_limits<double>::max(), std::numeric_limits<double>::max(), + std::numeric_limits<double>::max(), std::numeric_limits<double>::max()}}; + + /// The Navigation direction + NavigationDirection direction = forward; + + /// Update the step size of a certain type + /// + /// Only navigation and target abortion step size + /// updates may change the sign due to overstepping + /// + /// @param value is the new value to be updated + /// @param type is the constraint type + void update(const double& value, Type type, bool releaseStep = false) { + if (releaseStep) { + release(type); } + // The check the current value and set it if appropriate + double cValue = values[type]; + values[type] = cValue * cValue < value * value ? cValue : value; + } - /// The assignment operator from one double - /// @note this will set only the accuracy, as this is the most - /// exposed to the Propagator, this adapts also the direction - /// - /// @param value is the new accuracy value - ConstrainedStep& - operator=(const double& value) - { - /// set the accuracy value - values[accuracy] = value; - // set/update the direction - direction = value > 0. ? forward : backward; - return (*this); - } + /// release a certain constraint value + /// to the (signed) biggest value available, hence + /// it depends on the direction + /// + /// @param type is the constraint type to be released + void release(Type type) { + double mvalue = (direction == forward) + ? (*std::max_element(values.begin(), values.end())) + : (*std::min_element(values.begin(), values.end())); + values[type] = mvalue; + } - /// Cast operator to double, returning the min/max value - /// depending on the direction - operator double() const - { - if (direction == forward) { - return (*std::min_element(values.begin(), values.end())); - } - return (*std::max_element(values.begin(), values.end())); - } + /// constructor from double + /// @paramn value is the initial value for all steps + ConstrainedStep(double value) + : values({{value, value, value, value}}), + direction(value > 0. ? forward : backward) {} + + /// The assignment operator from one double + /// @note this will set only the accuracy, as this is the most + /// exposed to the Propagator, this adapts also the direction + /// + /// @param value is the new accuracy value + ConstrainedStep& operator=(const double& value) { + /// set the accuracy value + values[accuracy] = value; + // set/update the direction + direction = value > 0. ? forward : backward; + return (*this); + } - /// Access to a specific value - /// - /// @param type is the resquested parameter type - double - value(Type type) const - { - return values[type]; + /// Cast operator to double, returning the min/max value + /// depending on the direction + operator double() const { + if (direction == forward) { + return (*std::min_element(values.begin(), values.end())); } + return (*std::max_element(values.begin(), values.end())); + } - /// Access to currently leading min type - /// - Type - currentType() const - { - if (direction == forward) { - return Type(std::min_element(values.begin(), values.end()) - - values.begin()); - } - return Type(std::max_element(values.begin(), values.end()) - - values.begin()); + /// Access to a specific value + /// + /// @param type is the resquested parameter type + double value(Type type) const { return values[type]; } + + /// Access to currently leading min type + /// + Type currentType() const { + if (direction == forward) { + return Type(std::min_element(values.begin(), values.end()) - + values.begin()); } - - /// return the split value as string for debugging - std::string - toString() const; - }; - - inline std::string - ConstrainedStep::toString() const - { - std::stringstream dstream; - dstream << "(" << std::setw(5) << values[accuracy]; - dstream << ", " << std::setw(5) << values[actor]; - dstream << ", " << std::setw(5) << values[aborter]; - dstream << ", " << std::setw(5) << values[user] << " )"; - return dstream.str(); + return Type(std::max_element(values.begin(), values.end()) - + values.begin()); } + /// return the split value as string for debugging + std::string toString() const; +}; + +inline std::string ConstrainedStep::toString() const { + std::stringstream dstream; + dstream << "(" << std::setw(5) << values[accuracy]; + dstream << ", " << std::setw(5) << values[actor]; + dstream << ", " << std::setw(5) << values[aborter]; + dstream << ", " << std::setw(5) << values[user] << " )"; + return dstream.str(); +} + } // namespace detail } // namespace Acts diff --git a/Core/include/Acts/Propagator/detail/DebugOutputActor.hpp b/Core/include/Acts/Propagator/detail/DebugOutputActor.hpp index 5c162a3b0f6a87058ab5ecb02a268e3005690dfa..32b514f3dc7d166084120d89de37c0f2e7339cfc 100644 --- a/Core/include/Acts/Propagator/detail/DebugOutputActor.hpp +++ b/Core/include/Acts/Propagator/detail/DebugOutputActor.hpp @@ -12,58 +12,50 @@ namespace Acts { namespace detail { - /// This is an actor that deals with the output string - /// It is called upon targetReached and navigationBreak - /// of the state and then copies the debugString into - /// the final output object (result), which leaves the propagation - struct DebugOutputActor - { - - /// mute the thing if you don't want any action - bool mute = false; - - /// Simple result struct to be returned - /// It collects the debug output string from the state - /// into which all actors and aborters can write - struct this_result - { - std::string debugString = ""; - }; - - using result_type = this_result; - - /// Debug output action for the ActionList of the Propagator - /// - /// @tparam propagator_state_t is the type of the Propagator state - /// it is not used in this stepper - /// @tparam stepper_t Type of the stepper - /// - /// @param state is the mutable propagator state object - /// @param result is the mutable result state object - template <typename propagator_state_t, typename stepper_t> - void - operator()(propagator_state_t& state, - const stepper_t& /*unused*/, - result_type& result) const - { - // move the debug output from the state to - // to the output actor if it is not set to mute - // only when the target is reached (or later otherwise triggered) - if (!mute && (state.navigation.targetReached - || state.navigation.navigationBreak)) { - result.debugString += state.options.debugString; - state.options.debugString = ""; - } - } +/// This is an actor that deals with the output string +/// It is called upon targetReached and navigationBreak +/// of the state and then copies the debugString into +/// the final output object (result), which leaves the propagation +struct DebugOutputActor { + /// mute the thing if you don't want any action + bool mute = false; + + /// Simple result struct to be returned + /// It collects the debug output string from the state + /// into which all actors and aborters can write + struct this_result { + std::string debugString = ""; + }; - /// Pure observer interface - /// - this does not apply to the output collector - template <typename propagator_state_t, typename stepper_t> - void - operator()(propagator_state_t& /*state*/, const stepper_t& /*unused*/) const - { + using result_type = this_result; + + /// Debug output action for the ActionList of the Propagator + /// + /// @tparam propagator_state_t is the type of the Propagator state + /// it is not used in this stepper + /// @tparam stepper_t Type of the stepper + /// + /// @param state is the mutable propagator state object + /// @param result is the mutable result state object + template <typename propagator_state_t, typename stepper_t> + void operator()(propagator_state_t& state, const stepper_t& /*unused*/, + result_type& result) const { + // move the debug output from the state to + // to the output actor if it is not set to mute + // only when the target is reached (or later otherwise triggered) + if (!mute && + (state.navigation.targetReached || state.navigation.navigationBreak)) { + result.debugString += state.options.debugString; + state.options.debugString = ""; } - }; + } + + /// Pure observer interface + /// - this does not apply to the output collector + template <typename propagator_state_t, typename stepper_t> + void operator()(propagator_state_t& /*state*/, + const stepper_t& /*unused*/) const {} +}; } // namespace detail } // namespace Acts diff --git a/Core/include/Acts/Propagator/detail/InteractionFormulas.hpp b/Core/include/Acts/Propagator/detail/InteractionFormulas.hpp index da6a13b31d1006794f3e9a6543b06df3f5f651ab..c3839a12ceb696a5f883dee114f71a247329dffa 100644 --- a/Core/include/Acts/Propagator/detail/InteractionFormulas.hpp +++ b/Core/include/Acts/Propagator/detail/InteractionFormulas.hpp @@ -17,408 +17,371 @@ namespace Acts { namespace detail { - /// The ionization energy loss along a given path length. +/// The ionization energy loss along a given path length. +/// +/// The mean energy loss should be used for reconstruction, +/// the most probable energy loss is more suited for fast simulation +/// +/// The energy loss is calculated using the following paper +/// http://pdg.lbl.gov/2018/reviews/rpp2018-rev-passage-particles-matter.pdf +/// +/// Formula 33.5 is used to calculate the mean energy loss [reco mode] +/// Formula 33.11 is used to calculate the most probable energy loss [sim +/// mode] +/// Sigma is calculated using the Landau width (FHWM) times the conversion +/// factor 1. / (2. * &radic(2. * log2)) +/// +struct IonisationLoss { + /// @brief call operator for the Ionisation class /// - /// The mean energy loss should be used for reconstruction, - /// the most probable energy loss is more suited for fast simulation + /// @tparam material_t Type of the material class /// - /// The energy loss is calculated using the following paper - /// http://pdg.lbl.gov/2018/reviews/rpp2018-rev-passage-particles-matter.pdf + /// @param [in] m The masses of the different particles + /// @param [in] lbeta Beta factor of the particle + /// @param [in] lgamma Gamma factor of the particle + /// @param [in] mat The material that is traversed + /// @param [in] path The path length (optional) + /// @param [in] mean Toggle between calculation of mean (true) and mode + /// (false) + /// @param [in] siUnits Toggle for the unit system between SI and natural + /// units + /// @note The only conversion needed is for @p kazL if siUnits is true. /// - /// Formula 33.5 is used to calculate the mean energy loss [reco mode] - /// Formula 33.11 is used to calculate the most probable energy loss [sim - /// mode] - /// Sigma is calculated using the Landau width (FHWM) times the conversion - /// factor 1. / (2. * &radic(2. * log2)) - /// - struct IonisationLoss - { - - /// @brief call operator for the Ionisation class - /// - /// @tparam material_t Type of the material class - /// - /// @param [in] m The masses of the different particles - /// @param [in] lbeta Beta factor of the particle - /// @param [in] lgamma Gamma factor of the particle - /// @param [in] mat The material that is traversed - /// @param [in] path The path length (optional) - /// @param [in] mean Toggle between calculation of mean (true) and mode - /// (false) - /// @param [in] siUnits Toggle for the unit system between SI and natural - /// units - /// @note The only conversion needed is for @p kazL if siUnits is true. - /// - /// @return A std::pair. The first entry is the mean energy loss due to - /// ionization along a given path length or its mode. The second entry is - /// the sigma of the distribution. - template <typename material_t> - std::pair<double, double> - dEds(double m, - double lbeta, - double lgamma, - const material_t& mat, - double path = 1., - bool mean = true, - bool siUnits = false) const - { - - // the return value - double dE = 0.; + /// @return A std::pair. The first entry is the mean energy loss due to + /// ionization along a given path length or its mode. The second entry is + /// the sigma of the distribution. + template <typename material_t> + std::pair<double, double> dEds(double m, double lbeta, double lgamma, + const material_t& mat, double path = 1., + bool mean = true, bool siUnits = false) const { + // the return value + double dE = 0.; - // Ionization - Bethe-Bloch - // See ATL-SOFT-PUB-2008-003 equation (4) - // 16 eV * Z**0.9 - double I = constants::eionisation * std::pow(mat.Z(), 0.9); + // Ionization - Bethe-Bloch + // See ATL-SOFT-PUB-2008-003 equation (4) + // 16 eV * Z**0.9 + double I = constants::eionisation * std::pow(mat.Z(), 0.9); + // See (1) table 33.1 + // K/A*Z = 0.5 * 30.7075MeV/(g/mm2) * Z/A * rho[g/mm3] + // Convert energy if SI units are used + double kaz; + if (siUnits) { + kaz = 0.5 * units::Nat2SI<units::ENERGY>(30.7075 * units::_MeV) * + units::_mm * units::_mm / units::_g * mat.zOverAtimesRho(); + } else { + kaz = 0.5 * constants::ka_BetheBloch * mat.zOverAtimesRho(); + } + double eta2 = lbeta * lgamma; + eta2 *= eta2; + // density effect, only valid for high energies + // (lgamma > 10 -> p > 1 GeV for muons) + double delta = 0.; + if (lbeta * lgamma > 10.) { // See (1) table 33.1 - // K/A*Z = 0.5 * 30.7075MeV/(g/mm2) * Z/A * rho[g/mm3] - // Convert energy if SI units are used - double kaz; - if (siUnits) { - kaz = 0.5 * units::Nat2SI<units::ENERGY>(30.7075 * units::_MeV) - * units::_mm * units::_mm / units::_g * mat.zOverAtimesRho(); - } else { - kaz = 0.5 * constants::ka_BetheBloch * mat.zOverAtimesRho(); - } - double eta2 = lbeta * lgamma; - eta2 *= eta2; - // density effect, only valid for high energies - // (lgamma > 10 -> p > 1 GeV for muons) - double delta = 0.; - if (lbeta * lgamma > 10.) { - // See (1) table 33.1 - double eplasma - = constants::eplasma * sqrt(1000. * mat.zOverAtimesRho()); - // See (1) formula 33.6 - delta = 2. * std::log(eplasma / I) + std::log(eta2) - 1.; - } + double eplasma = constants::eplasma * sqrt(1000. * mat.zOverAtimesRho()); + // See (1) formula 33.6 + delta = 2. * std::log(eplasma / I) + std::log(eta2) - 1.; + } - // divide by lbeta^2 for non-electrons - kaz /= lbeta * lbeta; - double kazL = kaz * path; + // divide by lbeta^2 for non-electrons + kaz /= lbeta * lbeta; + double kazL = kaz * path; - // Multiply the charge for consistency - if (siUnits) { - kazL *= units::_e * units::_e; - } + // Multiply the charge for consistency + if (siUnits) { + kazL *= units::_e * units::_e; + } - // The landau width (FWHM) is 4.*kazL - // The factor is the conversion factor from FWHM to sigma for - // gaussian curve: 1. / (2. * sqrt(2. * log(2.))). - double sigma = kazL * constants::landau2gauss; - if (mean) { - // Calculate the fraction to the electron mass - double mfrac = siUnits ? (constants::me / units::SI2Nat<units::MASS>(m)) - : (constants::me / m); - // Calculate the mean value for reconstruction - // See ATL-SOFT-PUB-2008-003 equation (2) - double tMax = 2. * eta2 * constants::me - / (1. + 2. * lgamma * mfrac + mfrac * mfrac); - // See ATL-SOFT-PUB-2008-003 equation (1) - // or: - // http://pdg.lbl.gov/2018/reviews/rpp2018-rev-passage-particles-matter.pdf - // PDG formula 33.5 - dE = -kazL * 2.0 - * (0.5 * std::log(2. * constants::me * eta2 * tMax / (I * I)) - - (lbeta * lbeta) - - delta * 0.5); + // The landau width (FWHM) is 4.*kazL + // The factor is the conversion factor from FWHM to sigma for + // gaussian curve: 1. / (2. * sqrt(2. * log(2.))). + double sigma = kazL * constants::landau2gauss; + if (mean) { + // Calculate the fraction to the electron mass + double mfrac = siUnits ? (constants::me / units::SI2Nat<units::MASS>(m)) + : (constants::me / m); + // Calculate the mean value for reconstruction + // See ATL-SOFT-PUB-2008-003 equation (2) + double tMax = 2. * eta2 * constants::me / + (1. + 2. * lgamma * mfrac + mfrac * mfrac); + // See ATL-SOFT-PUB-2008-003 equation (1) + // or: + // http://pdg.lbl.gov/2018/reviews/rpp2018-rev-passage-particles-matter.pdf + // PDG formula 33.5 + dE = -kazL * 2.0 * + (0.5 * std::log(2. * constants::me * eta2 * tMax / (I * I)) - + (lbeta * lbeta) - delta * 0.5); + } else { + // Calculate the most probably value for simulation + // + // the landau sigmaL is path length dependent + // PDG formula 33.11 for MOP value from + // http://pdg.lbl.gov/2018/reviews/rpp2018-rev-passage-particles-matter.pdf + // + if (siUnits) { + dE = kazL * (std::log(2. * units::SI2Nat<units::MASS>(m) * eta2 / I) + + std::log(units::SI2Nat<units::ENERGY>(kazL) / I) + 0.2 - + (lbeta * lbeta) - delta); } else { - // Calculate the most probably value for simulation - // - // the landau sigmaL is path length dependent - // PDG formula 33.11 for MOP value from - // http://pdg.lbl.gov/2018/reviews/rpp2018-rev-passage-particles-matter.pdf - // - if (siUnits) { - dE = kazL * (std::log(2. * units::SI2Nat<units::MASS>(m) * eta2 / I) - + std::log(units::SI2Nat<units::ENERGY>(kazL) / I) - + 0.2 - - (lbeta * lbeta) - - delta); - } else { - dE = kazL * (std::log(2. * m * eta2 / I) + std::log(kazL / I) + 0.2 - - (lbeta * lbeta) - - delta); - } + dE = kazL * (std::log(2. * m * eta2 / I) + std::log(kazL / I) + 0.2 - + (lbeta * lbeta) - delta); } - // return the energy loss and stragling - return std::make_pair(dE, sigma); } + // return the energy loss and stragling + return std::make_pair(dE, sigma); + } - /// @brief Evaluation of the energy loss dEds by ionisation derived by q/p - /// (=d(dE/ds)/d(q/p)). The underlying equations for dE/ds are given by - /// Formula 33.5 (mean energy loss) and Formula 33.11 (most probable energy - /// loss). - /// - /// @tparam material_t Type of the material - /// @param [in] energy Energy of the particle - /// @param [in] qop Charge over momentum of the particle - /// @param [in] mass Mass of the particle - /// @param [in] material Material that is penetrated - /// @param [in] mean Boolean flag if mean or mode of dEds should be derived - /// @param [in] siUnits Boolean flag if SI or natural units should be used - /// - /// @note The strategy is to evaluate everything in natural units as long as - /// they are involved in terms that lead to canceling out of units. So, only - /// the terms that define the resulting unit are treated in the individual - /// unit system. Therewith the amount of calculations of constants and - /// conversions gets reduced. - /// @return The evaluated derivative - template <typename material_t> - double - dqop(const double energy, - const double qop, - const double mass, - const material_t& material, - const bool mean = true, - const bool siUnits = false) const - { - // Fast exit if material is invalid - if (material.Z() == 0 || material.zOverAtimesRho() == 0) { - return 0.; - } + /// @brief Evaluation of the energy loss dEds by ionisation derived by q/p + /// (=d(dE/ds)/d(q/p)). The underlying equations for dE/ds are given by + /// Formula 33.5 (mean energy loss) and Formula 33.11 (most probable energy + /// loss). + /// + /// @tparam material_t Type of the material + /// @param [in] energy Energy of the particle + /// @param [in] qop Charge over momentum of the particle + /// @param [in] mass Mass of the particle + /// @param [in] material Material that is penetrated + /// @param [in] mean Boolean flag if mean or mode of dEds should be derived + /// @param [in] siUnits Boolean flag if SI or natural units should be used + /// + /// @note The strategy is to evaluate everything in natural units as long as + /// they are involved in terms that lead to canceling out of units. So, only + /// the terms that define the resulting unit are treated in the individual + /// unit system. Therewith the amount of calculations of constants and + /// conversions gets reduced. + /// @return The evaluated derivative + template <typename material_t> + double dqop(const double energy, const double qop, const double mass, + const material_t& material, const bool mean = true, + const bool siUnits = false) const { + // Fast exit if material is invalid + if (material.Z() == 0 || material.zOverAtimesRho() == 0) { + return 0.; + } - // Constants for readability - const double qop1 - = siUnits ? qop / units::SI2Nat<units::MOMENTUM>(1.) : qop; - const double m = siUnits ? units::SI2Nat<units::MASS>(mass) : mass; - const double m2 = m * m; - const double I = constants::eionisation * std::pow(material.Z(), 0.9); - const double E = siUnits ? units::SI2Nat<units::ENERGY>(energy) : energy; - const double gamma = E / m; - const double beta = std::abs(1 / (E * qop1)); - const double beta2 = beta * beta; - const double kaz = siUnits - ? 0.5 * units::Nat2SI<units::ENERGY>(30.7075 * units::_MeV) - * units::_mm2 * units::_e2 / units::_g * material.zOverAtimesRho() - : 0.5 * constants::ka_BetheBloch * material.zOverAtimesRho(); - // Storage of the result - double betheBlochDerivative = 0.; - if (mean) { - // Constants related to the mean evaluation - const double me = constants::me; - const double me2 = me * me; - const double qop3 = qop1 * qop1 * qop1; - const double qop4 = qop3 * qop1; - const double m4 = m2 * m2; - const double I2 = I * I; + // Constants for readability + const double qop1 = + siUnits ? qop / units::SI2Nat<units::MOMENTUM>(1.) : qop; + const double m = siUnits ? units::SI2Nat<units::MASS>(mass) : mass; + const double m2 = m * m; + const double I = constants::eionisation * std::pow(material.Z(), 0.9); + const double E = siUnits ? units::SI2Nat<units::ENERGY>(energy) : energy; + const double gamma = E / m; + const double beta = std::abs(1 / (E * qop1)); + const double beta2 = beta * beta; + const double kaz = + siUnits ? 0.5 * units::Nat2SI<units::ENERGY>(30.7075 * units::_MeV) * + units::_mm2 * units::_e2 / units::_g * + material.zOverAtimesRho() + : 0.5 * constants::ka_BetheBloch * material.zOverAtimesRho(); + // Storage of the result + double betheBlochDerivative = 0.; + if (mean) { + // Constants related to the mean evaluation + const double me = constants::me; + const double me2 = me * me; + const double qop3 = qop1 * qop1 * qop1; + const double qop4 = qop3 * qop1; + const double m4 = m2 * m2; + const double I2 = I * I; - // Parts of the derivative - const double lnCore = 4. * me2 / (m4 * I2 * qop4) - / (1. + 2. * gamma * me / m + me2 / m2); - const double lnCoreDerivative = -4. * me2 / (m4 * I2) - * std::pow(qop4 + 2. * gamma * qop4 * me / m + qop4 * me2 / m2, -2.) - * (4. * qop3 + 8. * me * qop3 * gamma / m - - 2. * me * qop1 / (m2 * m * gamma) - + 4. * qop3 * me2 / m2); + // Parts of the derivative + const double lnCore = + 4. * me2 / (m4 * I2 * qop4) / (1. + 2. * gamma * me / m + me2 / m2); + const double lnCoreDerivative = + -4. * me2 / (m4 * I2) * + std::pow(qop4 + 2. * gamma * qop4 * me / m + qop4 * me2 / m2, -2.) * + (4. * qop3 + 8. * me * qop3 * gamma / m - + 2. * me * qop1 / (m2 * m * gamma) + 4. * qop3 * me2 / m2); - // Combine parts - const double lnDerivative = 2. * qop1 * m2 * std::log(lnCore) - + lnCoreDerivative / (lnCore * beta2); - betheBlochDerivative = -kaz * lnDerivative; - } else { - // Parts of the mode derivative - const double lnCore = std::log(2. * m * beta2 * gamma * gamma / I); - const double lnCoreXi = std::log(kaz / (beta2 * I)); - const double lnCoreDerivative = -2. * m * beta * gamma; - const double lnCoreXiDerivative = 2. * beta2 * m2; + // Combine parts + const double lnDerivative = 2. * qop1 * m2 * std::log(lnCore) + + lnCoreDerivative / (lnCore * beta2); + betheBlochDerivative = -kaz * lnDerivative; + } else { + // Parts of the mode derivative + const double lnCore = std::log(2. * m * beta2 * gamma * gamma / I); + const double lnCoreXi = std::log(kaz / (beta2 * I)); + const double lnCoreDerivative = -2. * m * beta * gamma; + const double lnCoreXiDerivative = 2. * beta2 * m2; - // Result evaluation (without the density effect) - betheBlochDerivative - = kaz * (2. * m2 * qop1 * (lnCore + lnCoreXi + 0.2) - + (lnCoreDerivative + lnCoreXiDerivative) / beta2); - } - // Density effect, only valid for high energies (gamma > 10 -> p > 1GeV - // for muons). The derivative includes the kinematic parts of the - // pre-factor - if (gamma > 10.) { - const double delta - = 2. * std::log(constants::eplasma - * std::sqrt(1000. * material.zOverAtimesRho()) - / I) - + 2. * std::log(beta * gamma) - 1.; - if (mean) { - const double deltaDerivative - = -2. / (qop1 * beta2) + 2. * delta * qop1 * m2; - betheBlochDerivative += kaz * deltaDerivative; - } else { - const double deltaDerivative - = -kaz * 2. / (qop1 * beta2) + kaz * 2. * m2 * qop1 * delta; - betheBlochDerivative -= deltaDerivative; - } - } - // Convert to right unit system and return - if (siUnits) { - return betheBlochDerivative * units::Nat2SI<units::MOMENTUM>(1.); + // Result evaluation (without the density effect) + betheBlochDerivative = + kaz * (2. * m2 * qop1 * (lnCore + lnCoreXi + 0.2) + + (lnCoreDerivative + lnCoreXiDerivative) / beta2); + } + // Density effect, only valid for high energies (gamma > 10 -> p > 1GeV + // for muons). The derivative includes the kinematic parts of the + // pre-factor + if (gamma > 10.) { + const double delta = + 2. * std::log(constants::eplasma * + std::sqrt(1000. * material.zOverAtimesRho()) / I) + + 2. * std::log(beta * gamma) - 1.; + if (mean) { + const double deltaDerivative = + -2. / (qop1 * beta2) + 2. * delta * qop1 * m2; + betheBlochDerivative += kaz * deltaDerivative; } else { - return betheBlochDerivative; + const double deltaDerivative = + -kaz * 2. / (qop1 * beta2) + kaz * 2. * m2 * qop1 * delta; + betheBlochDerivative -= deltaDerivative; } } - }; + // Convert to right unit system and return + if (siUnits) { + return betheBlochDerivative * units::Nat2SI<units::MOMENTUM>(1.); + } else { + return betheBlochDerivative; + } + } +}; - /// @brief Multiple scattering as function of dInX0 +/// @brief Multiple scattering as function of dInX0 +/// +/// It supports MIP and electron scattering and return +/// the space angle which has to be transformed into actual +/// scattering components for the azimuthal and polar angles, +/// respectively (for reconstruction). +struct HighlandScattering { + /// @brief call operator for the HighlandScattering formula /// - /// It supports MIP and electron scattering and return - /// the space angle which has to be transformed into actual - /// scattering components for the azimuthal and polar angles, - /// respectively (for reconstruction). - struct HighlandScattering - { - - /// @brief call operator for the HighlandScattering formula - /// - /// @param p is the momentum - /// @param lbeta is the Lorentz beta parameter - /// @param dInX0 is the passed thickness expressed in units of X0 - double - operator()(double p, - double lbeta, - double dInX0, - bool electron = false) const - { - if (dInX0 == 0. || p == 0. || lbeta == 0.) { - return 0.; - } - // Highland formula - projected sigma_s - // ATL-SOFT-PUB-2008-003 equation (15) - if (!electron) { - double sigmaSpace = constants::main_RutherfordScott * std::sqrt(dInX0) - / (lbeta * p) * (1. + 0.038 * std::log(dInX0 / (lbeta * lbeta))); - // return the space scattering angle - return sigmaSpace; - } - // Electron specification multiple scattering effects - // Source: Highland NIM 129 (1975) p497-499 - // (Highland extension to the Rossi-Greisen formulation) - // @note: The formula can be extended by replacing - // the momentum^2 term with pi * pf - double sigma2 = constants::main_RossiGreisen / (lbeta * p); - sigma2 *= (sigma2 * dInX0); - // logarithmic term - double factor - = 1. + constants::log_RossiGreisen * std::log10(10. * dInX0); - factor *= factor; - sigma2 *= factor; - return std::sqrt(sigma2); + /// @param p is the momentum + /// @param lbeta is the Lorentz beta parameter + /// @param dInX0 is the passed thickness expressed in units of X0 + double operator()(double p, double lbeta, double dInX0, + bool electron = false) const { + if (dInX0 == 0. || p == 0. || lbeta == 0.) { + return 0.; } - }; + // Highland formula - projected sigma_s + // ATL-SOFT-PUB-2008-003 equation (15) + if (!electron) { + double sigmaSpace = constants::main_RutherfordScott * std::sqrt(dInX0) / + (lbeta * p) * + (1. + 0.038 * std::log(dInX0 / (lbeta * lbeta))); + // return the space scattering angle + return sigmaSpace; + } + // Electron specification multiple scattering effects + // Source: Highland NIM 129 (1975) p497-499 + // (Highland extension to the Rossi-Greisen formulation) + // @note: The formula can be extended by replacing + // the momentum^2 term with pi * pf + double sigma2 = constants::main_RossiGreisen / (lbeta * p); + sigma2 *= (sigma2 * dInX0); + // logarithmic term + double factor = 1. + constants::log_RossiGreisen * std::log10(10. * dInX0); + factor *= factor; + sigma2 *= factor; + return std::sqrt(sigma2); + } +}; - /// @brief Structure for the energy loss of particles due to radiation in - /// dense material. It combines the effect of bremsstrahlung with direct e+e- - /// pair production and photonuclear interaction. The last two effects are - /// just included for muons. - struct RadiationLoss - { - /// @brief Main call operator for the energy loss. The following equations - /// are provided by ATL-SOFT-PUB-2008-003. - /// - /// @tparam material_t Type of the material - /// @param [in] E Energy of the particle - /// @param [in] m Mass of the particle - /// @param [in] mat Material that is penetrated - /// @param [in] pdg PDG code of the particle - /// @param [in] path Path length of the particle through the material - /// @param [in] siUnits Boolean flag if SI or natural units should be used - /// @return Radiation energy loss - template <typename material_t> - double - dEds(double E, - double m, - const material_t& mat, - int pdg, - double path = 1., - bool siUnits = false) const - { - // Easy exit - if (mat.X0() == 0.) { - return 0.; - } +/// @brief Structure for the energy loss of particles due to radiation in +/// dense material. It combines the effect of bremsstrahlung with direct e+e- +/// pair production and photonuclear interaction. The last two effects are +/// just included for muons. +struct RadiationLoss { + /// @brief Main call operator for the energy loss. The following equations + /// are provided by ATL-SOFT-PUB-2008-003. + /// + /// @tparam material_t Type of the material + /// @param [in] E Energy of the particle + /// @param [in] m Mass of the particle + /// @param [in] mat Material that is penetrated + /// @param [in] pdg PDG code of the particle + /// @param [in] path Path length of the particle through the material + /// @param [in] siUnits Boolean flag if SI or natural units should be used + /// @return Radiation energy loss + template <typename material_t> + double dEds(double E, double m, const material_t& mat, int pdg, + double path = 1., bool siUnits = false) const { + // Easy exit + if (mat.X0() == 0.) { + return 0.; + } - double energyLoss; - const double meOverm - = constants::me / (siUnits ? units::SI2Nat<units::MASS>(m) : m); + double energyLoss; + const double meOverm = + constants::me / (siUnits ? units::SI2Nat<units::MASS>(m) : m); - // Converting energy if needed - if (siUnits) { - E = units::SI2Nat<units::ENERGY>(E); - } + // Converting energy if needed + if (siUnits) { + E = units::SI2Nat<units::ENERGY>(E); + } - // Calculate the bremsstrahlung energy loss (eq. 6) - energyLoss = -E * (meOverm * meOverm); + // Calculate the bremsstrahlung energy loss (eq. 6) + energyLoss = -E * (meOverm * meOverm); - // Calculate the energy loss due to direct e+e- pair production and - // photonuclear interaction (eq. 7, 8) if the particle is a muon - if ((pdg == 13 || pdg == -13) && E > 8. * units::_GeV) { - if (E < 1. * units::_TeV) { - energyLoss += 0.5345 - 6.803e-5 * E - 2.278e-11 * E * E - + 9.899e-18 * E * E * E; - } else { - energyLoss += 2.986 - 9.253e-5 * E; - } + // Calculate the energy loss due to direct e+e- pair production and + // photonuclear interaction (eq. 7, 8) if the particle is a muon + if ((pdg == 13 || pdg == -13) && E > 8. * units::_GeV) { + if (E < 1. * units::_TeV) { + energyLoss += + 0.5345 - 6.803e-5 * E - 2.278e-11 * E * E + 9.899e-18 * E * E * E; + } else { + energyLoss += 2.986 - 9.253e-5 * E; } + } - // Return energy loss - if (siUnits) { - return units::Nat2SI<units::ENERGY>(energyLoss) * path / mat.X0(); - } - return energyLoss * path / mat.X0(); + // Return energy loss + if (siUnits) { + return units::Nat2SI<units::ENERGY>(energyLoss) * path / mat.X0(); } + return energyLoss * path / mat.X0(); + } - /// @brief Evaluation of the energy loss dEds by radiation, direct e+e- pair - /// production and photonuclear interaction derived by q/p - /// (=d(dE/ds)/d(q/p)). - /// - /// @tparam material_t Type of the material - /// @param [in] mass Mass of the particle - /// @param [in] material Material that is penetrated - /// @param [in] qop Charge over momentum of the particle - /// @param [in] energy Energy of the particle - /// @param [in] pdg PDG code of the particle - /// @param [in] siUnits Boolean flag if SI or natural units should be used - /// @return The evaluated derivative - template <typename material_t> - double - dqop(const double mass, - const material_t& material, - const double qop, - const double energy, - const int pdg, - const bool siUnits = false) const - { - // Fast exit if material is invalid - if (material.X0() == 0.) { - return 0.; - } + /// @brief Evaluation of the energy loss dEds by radiation, direct e+e- pair + /// production and photonuclear interaction derived by q/p + /// (=d(dE/ds)/d(q/p)). + /// + /// @tparam material_t Type of the material + /// @param [in] mass Mass of the particle + /// @param [in] material Material that is penetrated + /// @param [in] qop Charge over momentum of the particle + /// @param [in] energy Energy of the particle + /// @param [in] pdg PDG code of the particle + /// @param [in] siUnits Boolean flag if SI or natural units should be used + /// @return The evaluated derivative + template <typename material_t> + double dqop(const double mass, const material_t& material, const double qop, + const double energy, const int pdg, + const bool siUnits = false) const { + // Fast exit if material is invalid + if (material.X0() == 0.) { + return 0.; + } - const double invqop3X0 = 1. / (qop * qop * qop * material.X0()); + const double invqop3X0 = 1. / (qop * qop * qop * material.X0()); - double muonExpansion = 0.; - if ((pdg == 13 || pdg == -13) - && (siUnits ? units::SI2Nat<units::ENERGY>(energy) : energy) - > 8. * units::_GeV) { - if ((siUnits ? units::SI2Nat<units::ENERGY>(energy) : energy) - < 1. * units::_TeV) { - muonExpansion = 6.803e-5 * invqop3X0 / energy - + 2. * 2.278e-11 * invqop3X0 - - 3. * 9.899e-18 * invqop3X0 * energy; - } else { - muonExpansion = 9.253e-5 * invqop3X0 / energy; - } - } - if (siUnits) { - // Just rescale the mass to natural units, qop & energy are already - // given in the right system - const double scaling = units::SI2Nat<units::MASS>(1.); - return constants::me * constants::me * invqop3X0 - / (mass * mass * energy * scaling * scaling) - + muonExpansion; + double muonExpansion = 0.; + if ((pdg == 13 || pdg == -13) && + (siUnits ? units::SI2Nat<units::ENERGY>(energy) : energy) > + 8. * units::_GeV) { + if ((siUnits ? units::SI2Nat<units::ENERGY>(energy) : energy) < + 1. * units::_TeV) { + muonExpansion = 6.803e-5 * invqop3X0 / energy + + 2. * 2.278e-11 * invqop3X0 - + 3. * 9.899e-18 * invqop3X0 * energy; } else { - return constants::me * constants::me * invqop3X0 - / (mass * mass * energy) - + muonExpansion; + muonExpansion = 9.253e-5 * invqop3X0 / energy; } } - }; + if (siUnits) { + // Just rescale the mass to natural units, qop & energy are already + // given in the right system + const double scaling = units::SI2Nat<units::MASS>(1.); + return constants::me * constants::me * invqop3X0 / + (mass * mass * energy * scaling * scaling) + + muonExpansion; + } else { + return constants::me * constants::me * invqop3X0 / + (mass * mass * energy) + + muonExpansion; + } + } +}; } // namespace detail } // namespace Acts diff --git a/Core/include/Acts/Propagator/detail/LoopProtection.hpp b/Core/include/Acts/Propagator/detail/LoopProtection.hpp index 61c2fe934ffef352cca4a6260312729200917219..7d1ed31c02feb07d6e67487faf0be2a0b393288b 100644 --- a/Core/include/Acts/Propagator/detail/LoopProtection.hpp +++ b/Core/include/Acts/Propagator/detail/LoopProtection.hpp @@ -15,38 +15,34 @@ namespace Acts { namespace detail { - template <typename path_arborter_t> - struct LoopProtection - { - - /// @brief Call to dress the options with a loop protection - /// - /// @tparam state_t State type of the Propagation call - /// @tparam stepper_t Stepper type of the Propagator setup - /// - /// @param [in,out] state State object provided for the call - /// @param [in] stepper Stepper used - template <typename state_t, typename stepper_t> - void - operator()(state_t& state, const stepper_t& stepper) const - { - // Estimate the loop protection limit - if (state.options.loopProtection) { - // Get the field at the start position - Vector3D field = stepper.getField(state.stepping, - stepper.position(state.stepping)); - // Momentum in SI units and B field - const double p - = units::Nat2SI<units::MOMENTUM>(stepper.momentum(state.stepping)); - const double B = field.norm(); - const double helixPath = 2 * M_PI * p / B; - // now set the new loop limit - auto& pathAborter - = state.options.abortList.template get<path_arborter_t>(); - pathAborter.internalLimit = state.options.loopFraction * helixPath; - } +template <typename path_arborter_t> +struct LoopProtection { + /// @brief Call to dress the options with a loop protection + /// + /// @tparam state_t State type of the Propagation call + /// @tparam stepper_t Stepper type of the Propagator setup + /// + /// @param [in,out] state State object provided for the call + /// @param [in] stepper Stepper used + template <typename state_t, typename stepper_t> + void operator()(state_t& state, const stepper_t& stepper) const { + // Estimate the loop protection limit + if (state.options.loopProtection) { + // Get the field at the start position + Vector3D field = + stepper.getField(state.stepping, stepper.position(state.stepping)); + // Momentum in SI units and B field + const double p = + units::Nat2SI<units::MOMENTUM>(stepper.momentum(state.stepping)); + const double B = field.norm(); + const double helixPath = 2 * M_PI * p / B; + // now set the new loop limit + auto& pathAborter = + state.options.abortList.template get<path_arborter_t>(); + pathAborter.internalLimit = state.options.loopFraction * helixPath; } - }; + } +}; } // namespace detail } // namespace Acts diff --git a/Core/include/Acts/Propagator/detail/RelativePathCorrector.hpp b/Core/include/Acts/Propagator/detail/RelativePathCorrector.hpp index 69808f98203443e764fed0fa488048af1112cc40..2b4662f8952eee432a728297b49f145eb9639a39 100644 --- a/Core/include/Acts/Propagator/detail/RelativePathCorrector.hpp +++ b/Core/include/Acts/Propagator/detail/RelativePathCorrector.hpp @@ -19,83 +19,74 @@ namespace Acts { namespace detail { - using Cstep = ConstrainedStep; +using Cstep = ConstrainedStep; - /// @brief a struct that allows you to evaluate the intersection - /// - /// It actually modifies the position/direction of the intersection - /// attempt to allow for a potential better estimate when being - /// in a magnetic field setup - /// - /// This is acutally most relevant for a constant magnetic field where - /// the danger of overstepping is problematic - struct RelativePathCorrector - { - - /// Start position where this corrector is created - Vector3D startPos = Vector3D(0., 0., 0.); - /// Start direction with which this corrector is created - Vector3D startDir = Vector3D(0., 0., 0.); - /// Path length where this corrector is created - double pathLength = 0.; - /// Below here do only straight line estimate - double straightLineStep = 100 * units::_um; - /// Step modification factor - double stepModification = 0.5; +/// @brief a struct that allows you to evaluate the intersection +/// +/// It actually modifies the position/direction of the intersection +/// attempt to allow for a potential better estimate when being +/// in a magnetic field setup +/// +/// This is acutally most relevant for a constant magnetic field where +/// the danger of overstepping is problematic +struct RelativePathCorrector { + /// Start position where this corrector is created + Vector3D startPos = Vector3D(0., 0., 0.); + /// Start direction with which this corrector is created + Vector3D startDir = Vector3D(0., 0., 0.); + /// Path length where this corrector is created + double pathLength = 0.; + /// Below here do only straight line estimate + double straightLineStep = 100 * units::_um; + /// Step modification factor + double stepModification = 0.5; - /// Constructor from arguments - RelativePathCorrector(const Vector3D& spos = Vector3D(0., 0., 0.), - const Vector3D& sdir = Vector3D(0., 0., 0.), - double spath = 0.) - : startPos(spos), startDir(sdir), pathLength(spath) - { - } + /// Constructor from arguments + RelativePathCorrector(const Vector3D& spos = Vector3D(0., 0., 0.), + const Vector3D& sdir = Vector3D(0., 0., 0.), + double spath = 0.) + : startPos(spos), startDir(sdir), pathLength(spath) {} - /// Boolean() operator - returns false for void modifier - explicit operator bool() const { return true; } + /// Boolean() operator - returns false for void modifier + explicit operator bool() const { return true; } - /// A corrector for step estimation - /// - /// @param pos[in,out] the position for the path intersection - /// @param dir[in,out] the direction for the path intersection - /// @param path[in,out] path that as a first estimate - bool - operator()(Vector3D& pos, Vector3D& dir, double& path) const - { - // Approximation with straight line - if (path * path < straightLineStep * straightLineStep) { - return false; - } - // no correction at start positions - if (pathLength == 0. || pos.isApprox(startPos) - || dir.isApprox(startDir)) { - // can not correct: this is the initial step, no reference point - return false; - } - // change of direction per path length unit - Vector3D deltaDir = (dir - startDir) * 1. / pathLength; - dir = dir + 0.5 * path * deltaDir; - // return true - return true; + /// A corrector for step estimation + /// + /// @param pos[in,out] the position for the path intersection + /// @param dir[in,out] the direction for the path intersection + /// @param path[in,out] path that as a first estimate + bool operator()(Vector3D& pos, Vector3D& dir, double& path) const { + // Approximation with straight line + if (path * path < straightLineStep * straightLineStep) { + return false; + } + // no correction at start positions + if (pathLength == 0. || pos.isApprox(startPos) || dir.isApprox(startDir)) { + // can not correct: this is the initial step, no reference point + return false; } + // change of direction per path length unit + Vector3D deltaDir = (dir - startDir) * 1. / pathLength; + dir = dir + 0.5 * path * deltaDir; + // return true + return true; + } - /// Step size manipulation call - bool - operator()(ConstrainedStep& step) const - { - // Don't do anything if you are under accuracy or user control - auto stepType = step.currentType(); - if (stepType == Cstep::accuracy or stepType == Cstep::user) { - return false; - } - // Apply the step modification - // Update navigation and target step - double navStep = stepModification * step.value(Cstep::actor); - // We need also modify the target stepping for the moment - step.update(navStep, Cstep::actor, false); - return true; + /// Step size manipulation call + bool operator()(ConstrainedStep& step) const { + // Don't do anything if you are under accuracy or user control + auto stepType = step.currentType(); + if (stepType == Cstep::accuracy or stepType == Cstep::user) { + return false; } - }; + // Apply the step modification + // Update navigation and target step + double navStep = stepModification * step.value(Cstep::actor); + // We need also modify the target stepping for the moment + step.update(navStep, Cstep::actor, false); + return true; + } +}; } // namespace detail } // namespace Acts diff --git a/Core/include/Acts/Propagator/detail/StandardAborters.hpp b/Core/include/Acts/Propagator/detail/StandardAborters.hpp index b201e42dbde1aeca1a56ebc2c88f8a029a9ad31b..354b175892743d27e78ebee436771074a90e9dff 100644 --- a/Core/include/Acts/Propagator/detail/StandardAborters.hpp +++ b/Core/include/Acts/Propagator/detail/StandardAborters.hpp @@ -21,256 +21,222 @@ namespace Acts { namespace detail { - /// @brief TargetOptions struct for geometry interface - struct TargetOptions - { - - /// the navigation direction - NavigationDirection navDir = forward; - - /// the boundary check directive - always false here - BoundaryCheck boundaryCheck = false; - - /// object to check against - always nullptr here - const Surface* startObject = nullptr; - - /// The path limit - double pathLimit = std::numeric_limits<double>::max(); - - /// create target options - TargetOptions(NavigationDirection ndir) : navDir(ndir) {} - }; +/// @brief TargetOptions struct for geometry interface +struct TargetOptions { + /// the navigation direction + NavigationDirection navDir = forward; + + /// the boundary check directive - always false here + BoundaryCheck boundaryCheck = false; + + /// object to check against - always nullptr here + const Surface* startObject = nullptr; + + /// The path limit + double pathLimit = std::numeric_limits<double>::max(); + + /// create target options + TargetOptions(NavigationDirection ndir) : navDir(ndir) {} +}; + +/// The debug logging for standard aborters +/// +/// It needs to be fed by a lambda function that returns a string, +/// that guarantees that the lambda is only called in the +/// state.options.debug == true case in order not to spend time +/// when not needed. +/// +/// @param state the propagator cache for the debug flag, prefix/stream +/// @param logAction is a callable function that returns a stremable object +template <typename propagator_state_t> +void targetDebugLog(propagator_state_t& state, const std::string& status, + const std::function<std::string()>& logAction) { + if (state.options.debug) { + std::stringstream dstream; + dstream << " " << status << " "; + dstream << std::setw(state.options.debugPfxWidth); + dstream << " Target " + << " | "; + dstream << std::setw(state.options.debugMsgWidth); + dstream << logAction() << '\n'; + state.options.debugString += dstream.str(); + } +} + +/// This is the condition that the pathLimit has been reached +struct PathLimitReached { + /// Boolean switch for Loop protection + double internalLimit = std::numeric_limits<double>::max(); + + /// boolean operator for abort condition using the result + template <typename propagator_state_t, typename stepper_t, typename result_t> + bool operator()(const result_t& /*r*/, propagator_state_t& state, + const stepper_t& stepper) const { + return operator()(state, stepper); + } - /// The debug logging for standard aborters + /// boolean operator for abort condition without using the result /// - /// It needs to be fed by a lambda function that returns a string, - /// that guarantees that the lambda is only called in the - /// state.options.debug == true case in order not to spend time - /// when not needed. + /// @tparam propagator_state_t Type of the propagator state + /// @tparam stepper_t Type of the stepper /// - /// @param state the propagator cache for the debug flag, prefix/stream - /// @param logAction is a callable function that returns a stremable object - template <typename propagator_state_t> - void - targetDebugLog(propagator_state_t& state, - const std::string& status, - const std::function<std::string()>& logAction) - { - if (state.options.debug) { - std::stringstream dstream; - dstream << " " << status << " "; - dstream << std::setw(state.options.debugPfxWidth); - dstream << " Target " - << " | "; - dstream << std::setw(state.options.debugMsgWidth); - dstream << logAction() << '\n'; - state.options.debugString += dstream.str(); - } - } - - /// This is the condition that the pathLimit has been reached - struct PathLimitReached - { - - /// Boolean switch for Loop protection - double internalLimit = std::numeric_limits<double>::max(); - - /// boolean operator for abort condition using the result - template <typename propagator_state_t, - typename stepper_t, - typename result_t> - bool - operator()(const result_t& /*r*/, - propagator_state_t& state, - const stepper_t& stepper) const - { - return operator()(state, stepper); + /// @param [in,out] state The propagation state object + template <typename propagator_state_t, typename stepper_t> + bool operator()(propagator_state_t& state, + const stepper_t& /*unused*/) const { + if (state.navigation.targetReached) { + return true; } - /// boolean operator for abort condition without using the result - /// - /// @tparam propagator_state_t Type of the propagator state - /// @tparam stepper_t Type of the stepper - /// - /// @param [in,out] state The propagation state object - template <typename propagator_state_t, typename stepper_t> - bool - operator()(propagator_state_t& state, const stepper_t& /*unused*/) const - { - if (state.navigation.targetReached) { - return true; - } - - // Check if the maximum allowed step size has to be updated - double limit = std::min(internalLimit, state.options.pathLimit); - double distance = limit - state.stepping.pathAccumulated; - double tolerance = state.options.targetTolerance; - state.stepping.stepSize.update(distance, ConstrainedStep::aborter); - bool limitReached = (distance * distance < tolerance * tolerance); - if (limitReached) { - targetDebugLog(state, "x", [&] { - std::stringstream dstream; - dstream << "Path limit reached at distance " << distance; - return dstream.str(); - }); - // reaching the target means navigation break - state.navigation.targetReached = true; - } else { - targetDebugLog(state, "o", [&] { - std::stringstream dstream; - dstream << "Target stepSize (path limit) updated to "; - dstream << state.stepping.stepSize.toString(); - return dstream.str(); - }); - } - // path limit check - return limitReached; + // Check if the maximum allowed step size has to be updated + double limit = std::min(internalLimit, state.options.pathLimit); + double distance = limit - state.stepping.pathAccumulated; + double tolerance = state.options.targetTolerance; + state.stepping.stepSize.update(distance, ConstrainedStep::aborter); + bool limitReached = (distance * distance < tolerance * tolerance); + if (limitReached) { + targetDebugLog(state, "x", [&] { + std::stringstream dstream; + dstream << "Path limit reached at distance " << distance; + return dstream.str(); + }); + // reaching the target means navigation break + state.navigation.targetReached = true; + } else { + targetDebugLog(state, "o", [&] { + std::stringstream dstream; + dstream << "Target stepSize (path limit) updated to "; + dstream << state.stepping.stepSize.toString(); + return dstream.str(); + }); } - }; - - /// This is the condition that the Surface has been reached - /// it then triggers an propagation abort of the propagation - struct SurfaceReached - { - - /// Default Constructor - SurfaceReached() = default; + // path limit check + return limitReached; + } +}; + +/// This is the condition that the Surface has been reached +/// it then triggers an propagation abort of the propagation +struct SurfaceReached { + /// Default Constructor + SurfaceReached() = default; + + /// boolean operator for abort condition using the result (ignored) + template <typename propagator_state_t, typename stepper_t, typename result_t> + bool operator()(const result_t& /*result*/, propagator_state_t& state, + const stepper_t& stepper) const { + return operator()(state, stepper); + } - /// boolean operator for abort condition using the result (ignored) - template <typename propagator_state_t, - typename stepper_t, - typename result_t> - bool - operator()(const result_t& /*result*/, - propagator_state_t& state, - const stepper_t& stepper) const - { - return operator()(state, stepper); - } + /// boolean operator for abort condition without using the result + /// + /// @tparam propagator_state_t Type of the propagator state + /// @tparam stepper_t Type of the stepper + /// + /// @param [in,out] state The propagation state object + /// @param [in] stepper Stepper used for propagation + template <typename propagator_state_t, typename stepper_t> + bool operator()(propagator_state_t& state, const stepper_t& stepper) const { + return (*this)(state, stepper, *state.navigation.targetSurface); + } - /// boolean operator for abort condition without using the result - /// - /// @tparam propagator_state_t Type of the propagator state - /// @tparam stepper_t Type of the stepper - /// - /// @param [in,out] state The propagation state object - /// @param [in] stepper Stepper used for propagation - template <typename propagator_state_t, typename stepper_t> - bool - operator()(propagator_state_t& state, const stepper_t& stepper) const - { - return (*this)(state, stepper, *state.navigation.targetSurface); + /// boolean operator for abort condition without using the result + /// + /// @tparam propagator_state_t Type of the propagator state + /// @tparam stepper_t Type of the stepper + /// + /// @param [in,out] state The propagation state object + /// @param [in] stepper Stepper used for the progation + /// @param [in] targetSurface The target surface + template <typename propagator_state_t, typename stepper_t> + bool operator()(propagator_state_t& state, const stepper_t& stepper, + const Surface& targetSurface) const { + if (state.navigation.targetReached) { + return true; } - /// boolean operator for abort condition without using the result - /// - /// @tparam propagator_state_t Type of the propagator state - /// @tparam stepper_t Type of the stepper - /// - /// @param [in,out] state The propagation state object - /// @param [in] stepper Stepper used for the progation - /// @param [in] targetSurface The target surface - template <typename propagator_state_t, typename stepper_t> - bool - operator()(propagator_state_t& state, - const stepper_t& stepper, - const Surface& targetSurface) const - { - if (state.navigation.targetReached) { - return true; - } - - // Check if the cache filled the currentSurface - or if we are on the - // surface - // @todo - do not apply the isOnSurface check here, but handle by the - // intersectionEstimate - if ((state.navigation.currentSurface - && state.navigation.currentSurface == &targetSurface)) { - targetDebugLog(state, "x", [&] { - std::string ds("Target surface reached."); - return ds; - }); - // reaching the target calls a navigation break - state.navigation.targetReached = true; - return true; - } - // Calculate the distance to the surface - const double tolerance = state.options.targetTolerance; - const auto intersection = targetSurface.intersectionEstimate( - state.geoContext, - stepper.position(state.stepping), - stepper.direction(state.stepping), - anyDirection); - const double distance = intersection.pathLength; - // Adjust the step size so that we cannot cross the target surface - state.stepping.stepSize.update(distance, ConstrainedStep::aborter); - // return true if you fall below tolerance - bool targetReached = (distance * distance <= tolerance * tolerance); - if (targetReached) { - targetDebugLog(state, "x", [&] { - std::stringstream dstream; - dstream << "Target surface reached at distance (tolerance) "; - dstream << distance << " (" << tolerance << ")"; - return dstream.str(); - }); - // assigning the currentSurface - state.navigation.currentSurface = &targetSurface; - targetDebugLog(state, "x", [&] { - std::stringstream dstream; - dstream << "Current surface set to target surface "; - dstream << state.navigation.currentSurface->geoID().toString(); - return dstream.str(); - }); - // reaching the target calls a navigation break - state.navigation.targetReached = true; - } else { - targetDebugLog(state, "o", [&] { - std::stringstream dstream; - dstream << "Target stepSize (surface) updated to "; - dstream << state.stepping.stepSize.toString(); - return dstream.str(); - }); - } - // path limit check - return targetReached; + // Check if the cache filled the currentSurface - or if we are on the + // surface + // @todo - do not apply the isOnSurface check here, but handle by the + // intersectionEstimate + if ((state.navigation.currentSurface && + state.navigation.currentSurface == &targetSurface)) { + targetDebugLog(state, "x", [&] { + std::string ds("Target surface reached."); + return ds; + }); + // reaching the target calls a navigation break + state.navigation.targetReached = true; + return true; } - }; - - /// This is the condition that the end of World has been reached - /// it then triggers an propagation abort - struct EndOfWorldReached - { - /// Default Constructor - EndOfWorldReached() = default; - - /// boolean operator for abort condition using the result (ignored) - template <typename propagator_state_t, - typename stepper_t, - typename result_t> - bool - operator()(const result_t& /*result*/, - propagator_state_t& state, - const stepper_t& stepper) const - { - return operator()(state, stepper); + // Calculate the distance to the surface + const double tolerance = state.options.targetTolerance; + const auto intersection = targetSurface.intersectionEstimate( + state.geoContext, stepper.position(state.stepping), + stepper.direction(state.stepping), anyDirection); + const double distance = intersection.pathLength; + // Adjust the step size so that we cannot cross the target surface + state.stepping.stepSize.update(distance, ConstrainedStep::aborter); + // return true if you fall below tolerance + bool targetReached = (distance * distance <= tolerance * tolerance); + if (targetReached) { + targetDebugLog(state, "x", [&] { + std::stringstream dstream; + dstream << "Target surface reached at distance (tolerance) "; + dstream << distance << " (" << tolerance << ")"; + return dstream.str(); + }); + // assigning the currentSurface + state.navigation.currentSurface = &targetSurface; + targetDebugLog(state, "x", [&] { + std::stringstream dstream; + dstream << "Current surface set to target surface "; + dstream << state.navigation.currentSurface->geoID().toString(); + return dstream.str(); + }); + // reaching the target calls a navigation break + state.navigation.targetReached = true; + } else { + targetDebugLog(state, "o", [&] { + std::stringstream dstream; + dstream << "Target stepSize (surface) updated to "; + dstream << state.stepping.stepSize.toString(); + return dstream.str(); + }); } + // path limit check + return targetReached; + } +}; + +/// This is the condition that the end of World has been reached +/// it then triggers an propagation abort +struct EndOfWorldReached { + /// Default Constructor + EndOfWorldReached() = default; + + /// boolean operator for abort condition using the result (ignored) + template <typename propagator_state_t, typename stepper_t, typename result_t> + bool operator()(const result_t& /*result*/, propagator_state_t& state, + const stepper_t& stepper) const { + return operator()(state, stepper); + } - /// boolean operator for abort condition without using the result - /// - /// @tparam propagator_state_t Type of the propagator state - /// - /// @param[in,out] state The propagation state object - template <typename propagator_state_t, typename stepper_t> - bool - operator()(propagator_state_t& state, const stepper_t& /*unused*/) const - { - if (state.navigation.currentVolume != nullptr) { - return false; - } - state.navigation.targetReached = true; - return true; + /// boolean operator for abort condition without using the result + /// + /// @tparam propagator_state_t Type of the propagator state + /// + /// @param[in,out] state The propagation state object + template <typename propagator_state_t, typename stepper_t> + bool operator()(propagator_state_t& state, + const stepper_t& /*unused*/) const { + if (state.navigation.currentVolume != nullptr) { + return false; } - }; + state.navigation.targetReached = true; + return true; + } +}; } // namespace detail } // namespace Acts diff --git a/Core/include/Acts/Propagator/detail/SteppingLogger.hpp b/Core/include/Acts/Propagator/detail/SteppingLogger.hpp index 9ec097ecd14d68caad9456b621e82de1aee41b3c..ccaa3bd42754447da8f7d253fd992e1da4363753 100644 --- a/Core/include/Acts/Propagator/detail/SteppingLogger.hpp +++ b/Core/include/Acts/Propagator/detail/SteppingLogger.hpp @@ -20,71 +20,61 @@ class TrackingVolume; namespace detail { - /// @brief the step information for - struct Step - { +/// @brief the step information for +struct Step { + ConstrainedStep stepSize = 0.; + Vector3D position = Vector3D(0., 0., 0.); + Vector3D momentum = Vector3D(0., 0., 0.); + std::shared_ptr<const Surface> surface = nullptr; + const TrackingVolume* volume = nullptr; +}; - ConstrainedStep stepSize = 0.; - Vector3D position = Vector3D(0., 0., 0.); - Vector3D momentum = Vector3D(0., 0., 0.); - std::shared_ptr<const Surface> surface = nullptr; - const TrackingVolume* volume = nullptr; +/// @brief a step length logger for debugging the stepping +/// +/// It simply logs the constrained step length per step +struct SteppingLogger { + /// Simple result struct to be returned + struct this_result { + std::vector<Step> steps; }; - /// @brief a step length logger for debugging the stepping - /// - /// It simply logs the constrained step length per step - struct SteppingLogger - { - - /// Simple result struct to be returned - struct this_result - { - std::vector<Step> steps; - }; - - using result_type = this_result; + using result_type = this_result; - /// SteppingLogger action for the ActionList of the Propagator - /// - /// @tparam stepper_t is the type of the Stepper - /// @tparam propagator_state_t is the type of Propagator state - /// - /// @param [in,out] state is the mutable stepper state object - /// @param [in,out] result is the mutable result object - template <typename propagator_state_t, typename stepper_t> - void - operator()(propagator_state_t& state, - const stepper_t& stepper, - result_type& result) const - { - // don't log if you have reached the target - if (state.navigation.targetReached) return; - // record the propagation state - Step step; - step.stepSize = state.stepping.stepSize; - step.position = stepper.position(state.stepping); - step.momentum = stepper.momentum(state.stepping) - * stepper.direction(state.stepping); - - if (state.navigation.currentSurface != nullptr) { - // hang on to surface - step.surface = state.navigation.currentSurface->getSharedPtr(); - } + /// SteppingLogger action for the ActionList of the Propagator + /// + /// @tparam stepper_t is the type of the Stepper + /// @tparam propagator_state_t is the type of Propagator state + /// + /// @param [in,out] state is the mutable stepper state object + /// @param [in,out] result is the mutable result object + template <typename propagator_state_t, typename stepper_t> + void operator()(propagator_state_t& state, const stepper_t& stepper, + result_type& result) const { + // don't log if you have reached the target + if (state.navigation.targetReached) + return; + // record the propagation state + Step step; + step.stepSize = state.stepping.stepSize; + step.position = stepper.position(state.stepping); + step.momentum = + stepper.momentum(state.stepping) * stepper.direction(state.stepping); - step.volume = state.navigation.currentVolume; - result.steps.push_back(std::move(step)); + if (state.navigation.currentSurface != nullptr) { + // hang on to surface + step.surface = state.navigation.currentSurface->getSharedPtr(); } - /// Pure observer interface - /// - this does not apply to the logger - template <typename propagator_state_t, typename stepper_t> - void - operator()(propagator_state_t& /*unused*/, - const stepper_t& /*unused*/) const - { - } - }; + step.volume = state.navigation.currentVolume; + result.steps.push_back(std::move(step)); + } + + /// Pure observer interface + /// - this does not apply to the logger + template <typename propagator_state_t, typename stepper_t> + void operator()(propagator_state_t& /*unused*/, + const stepper_t& /*unused*/) const {} +}; } // namespace detail } // namespace Acts diff --git a/Core/include/Acts/Propagator/detail/VoidPropagatorComponents.hpp b/Core/include/Acts/Propagator/detail/VoidPropagatorComponents.hpp index a5a7e49b352711b5919f19229617f9704756df4e..cef74c14268db588021001a5b86f9814fedef3ab 100644 --- a/Core/include/Acts/Propagator/detail/VoidPropagatorComponents.hpp +++ b/Core/include/Acts/Propagator/detail/VoidPropagatorComponents.hpp @@ -11,71 +11,61 @@ namespace Acts { namespace detail { - /// @brief The void navigator struct as a default navigator - /// - /// It does not provide any navigation action, the compiler - /// should eventually optimise that the function call is not done - /// - struct VoidNavigator - { - - /// @brief Nested State struct, minimal requirement - struct State - { - /// Navigation state - external state: the start surface - const Surface* startSurface = nullptr; +/// @brief The void navigator struct as a default navigator +/// +/// It does not provide any navigation action, the compiler +/// should eventually optimise that the function call is not done +/// +struct VoidNavigator { + /// @brief Nested State struct, minimal requirement + struct State { + /// Navigation state - external state: the start surface + const Surface* startSurface = nullptr; - /// Navigation state - external state: the current surface - const Surface* currentSurface = nullptr; + /// Navigation state - external state: the current surface + const Surface* currentSurface = nullptr; - /// Navigation state - external state: the target surface - const Surface* targetSurface = nullptr; + /// Navigation state - external state: the target surface + const Surface* targetSurface = nullptr; - /// Indicator if the target is reached - bool targetReached = false; + /// Indicator if the target is reached + bool targetReached = false; - /// Navigation state : a break has been detected - bool navigationBreak = false; - }; + /// Navigation state : a break has been detected + bool navigationBreak = false; + }; - /// Unique typedef to publish to the Propagator - using state_type = State; + /// Unique typedef to publish to the Propagator + using state_type = State; - /// Navigation call - void - /// - /// @tparam propagator_state_t is the type of Propagatgor state - /// @tparam stepper_t Type of the Stepper - /// - /// Empty call, compiler should optimise that - template <typename propagator_state_t, typename stepper_t> - void - status(propagator_state_t& /*state*/, const stepper_t& /*unused*/) const - { - } + /// Navigation call - void + /// + /// @tparam propagator_state_t is the type of Propagatgor state + /// @tparam stepper_t Type of the Stepper + /// + /// Empty call, compiler should optimise that + template <typename propagator_state_t, typename stepper_t> + void status(propagator_state_t& /*state*/, + const stepper_t& /*unused*/) const {} - /// Navigation call - void - /// - /// @tparam propagator_state_t is the type of Propagatgor state - /// @tparam stepper_t Type of the Stepper - /// - /// Empty call, compiler should optimise that - template <typename propagator_state_t, typename stepper_t> - void - target(propagator_state_t& /*state*/, const stepper_t& /*unused*/) const - { - } + /// Navigation call - void + /// + /// @tparam propagator_state_t is the type of Propagatgor state + /// @tparam stepper_t Type of the Stepper + /// + /// Empty call, compiler should optimise that + template <typename propagator_state_t, typename stepper_t> + void target(propagator_state_t& /*state*/, + const stepper_t& /*unused*/) const {} - /// Navigation call - void - /// - /// @tparam propagator_state_t is the type of Propagatgor state - /// - /// Empty call, compiler should optimise that - template <typename propagator_state_t> - void - operator()(propagator_state_t& /*state*/) const - { - } - }; + /// Navigation call - void + /// + /// @tparam propagator_state_t is the type of Propagatgor state + /// + /// Empty call, compiler should optimise that + template <typename propagator_state_t> + void operator()(propagator_state_t& /*state*/) const {} +}; } // namespace detail } // namespace Acts diff --git a/Core/include/Acts/Propagator/detail/abort_condition_signature_check.hpp b/Core/include/Acts/Propagator/detail/abort_condition_signature_check.hpp index 5b74d9928559f87948029990ebb7abe6fffdcf7f..9c64b583730f22a315e2aa01fbf88824d73c96db 100644 --- a/Core/include/Acts/Propagator/detail/abort_condition_signature_check.hpp +++ b/Core/include/Acts/Propagator/detail/abort_condition_signature_check.hpp @@ -40,76 +40,50 @@ namespace Acts { /// clang-format off namespace detail { - namespace { - template <typename T, - typename propagator_state_t, - typename stepper_t, - typename result_t, - typename - = decltype(std::declval<const T>(). - operator()(std::declval<const result_t&>(), - std::declval<const propagator_state_t&>()), - std::declval<const stepper_t&>())> - std::true_type - test_condition_with_result(int); +namespace { +template <typename T, typename propagator_state_t, typename stepper_t, + typename result_t, + typename = decltype(std::declval<const T>().operator()( + std::declval<const result_t&>(), + std::declval<const propagator_state_t&>()), + std::declval<const stepper_t&>())> +std::true_type test_condition_with_result(int); - template <typename, typename, typename, typename> - std::false_type - test_condition_with_result(...); +template <typename, typename, typename, typename> +std::false_type test_condition_with_result(...); - template <typename T, - typename propagator_state_t, - typename stepper_t, - typename - = decltype(std::declval<const T>(). - operator()(std::declval<const propagator_state_t&>(), - std::declval<const stepper_t&>()))> - std::true_type - test_condition_without_result(int); +template <typename T, typename propagator_state_t, typename stepper_t, + typename = decltype(std::declval<const T>().operator()( + std::declval<const propagator_state_t&>(), + std::declval<const stepper_t&>()))> +std::true_type test_condition_without_result(int); - template <typename, typename> - std::false_type - test_condition_without_result(...); +template <typename, typename> +std::false_type test_condition_without_result(...); - template <typename T, - typename propagator_state_t, - typename stepper_t, - bool has_result = false> - struct condition_signature_check_impl - : decltype( - test_condition_without_result<T, propagator_state_t, stepper_t>( - 0)) - { - }; +template <typename T, typename propagator_state_t, typename stepper_t, + bool has_result = false> +struct condition_signature_check_impl + : decltype( + test_condition_without_result<T, propagator_state_t, stepper_t>(0)) { +}; - template <typename T, typename propagator_state_t, typename stepper_t> - struct condition_signature_check_impl<T, - propagator_state_t, - stepper_t, - true> - : decltype( - test_condition_with_result<T, - propagator_state_t, - stepper_t, - result_type_t<action_type_t<T>>>(0)) - { - }; +template <typename T, typename propagator_state_t, typename stepper_t> +struct condition_signature_check_impl<T, propagator_state_t, stepper_t, true> + : decltype(test_condition_with_result<T, propagator_state_t, stepper_t, + result_type_t<action_type_t<T>>>(0)) { +}; - template <typename T, typename propagator_state_t, typename stepper_t> - struct abort_condition_signature_check - : condition_signature_check_impl<T, - propagator_state_t, - stepper_t, - condition_uses_result_type<T>::value> - { - }; - // clang-format on - } // end of anonymous namespace +template <typename T, typename propagator_state_t, typename stepper_t> +struct abort_condition_signature_check + : condition_signature_check_impl<T, propagator_state_t, stepper_t, + condition_uses_result_type<T>::value> {}; +// clang-format on +} // end of anonymous namespace - template <typename T, typename propagator_state_t, typename stepper_t> - constexpr bool abort_condition_signature_check_v - = abort_condition_signature_check<T, propagator_state_t, stepper_t>:: - value; +template <typename T, typename propagator_state_t, typename stepper_t> +constexpr bool abort_condition_signature_check_v = + abort_condition_signature_check<T, propagator_state_t, stepper_t>::value; } // namespace detail } // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Propagator/detail/abort_list_implementation.hpp b/Core/include/Acts/Propagator/detail/abort_list_implementation.hpp index 32aa5ea522f038ab50486fd48f0beac46d0a131e..ef1e88e46220f590addbf700742b06953c70a559 100644 --- a/Core/include/Acts/Propagator/detail/abort_list_implementation.hpp +++ b/Core/include/Acts/Propagator/detail/abort_list_implementation.hpp @@ -16,127 +16,92 @@ namespace Acts { namespace detail { - namespace { - /// This is the caller used if the condition uses the result - /// and that result type exists - template <bool has_result = true> - struct condition_caller - { - template <typename condition, - typename result_t, - typename propagator_state_t, - typename stepper_t> - static bool - check(const condition& c, - const result_t& r, - propagator_state_t& state, - const stepper_t& stepper) - { - using action_type = action_type_t<condition>; - using result_type = result_type_t<action_type>; - - return c(r.template get<result_type>(), state, stepper); - } - }; - - /// This is the caller used if the condition only uses the cache - /// it has no access to the result - template <> - struct condition_caller<false> - { - template <typename condition, - typename result_t, - typename propagator_state_t, - typename stepper_t> - static bool - check(const condition& c, - const result_t& /*result*/, - propagator_state_t& state, - const stepper_t& stepper) - { - return c(state, stepper); - } - }; - } // end of anonymous namespace - - template <typename... conditions> - struct abort_list_impl; - - /// This is the check call on the a list of conditions - /// it calls the aparant condition and broadcasts - /// the call to the remaining ones - template <typename first, typename... others> - struct abort_list_impl<first, others...> - { - template <typename T, - typename result_t, - typename propagator_state_t, - typename stepper_t> - static bool - check(const T& conditions_tuple, - const result_t& result, - propagator_state_t& state, - const stepper_t& stepper) - { - - // get the right helper for calling the abort condition - constexpr bool has_result = condition_uses_result_type<first>::value; - using caller_type = condition_caller<has_result>; - - // get the cache abort condition - const auto& this_condition = std::get<first>(conditions_tuple); - - // - check abort conditions recursively - // - make use of short-circuit evaluation - // -> skip remaining conditions if this abort condition evaluates to true - bool abort = caller_type::check(this_condition, result, state, stepper) - || abort_list_impl<others...>::check( - conditions_tuple, result, state, stepper); - - return abort; - } - }; - - /// This is the check call on the a last of all conditions - template <typename last> - struct abort_list_impl<last> - { - template <typename T, - typename result_t, - typename propagator_state_t, - typename stepper_t> - static bool - check(const T& conditions_tuple, - const result_t& result, - propagator_state_t& state, - const stepper_t& stepper) - { - // get the right helper for calling the abort condition - constexpr bool has_result = condition_uses_result_type<last>::value; - const auto& this_condition = std::get<last>(conditions_tuple); - - return condition_caller<has_result>::check( - this_condition, result, state, stepper); - } - }; - - /// This is the empty call list - never abort - template <> - struct abort_list_impl<> - { - template <typename T, - typename result_t, - typename propagator_state_t, - typename stepper_t> - static bool - check(const T& /*unused*/, - const result_t& /*result*/, - propagator_state_t& /*state*/, - const stepper_t& /*unused*/) - { - return false; - } - }; +namespace { +/// This is the caller used if the condition uses the result +/// and that result type exists +template <bool has_result = true> +struct condition_caller { + template <typename condition, typename result_t, typename propagator_state_t, + typename stepper_t> + static bool check(const condition& c, const result_t& r, + propagator_state_t& state, const stepper_t& stepper) { + using action_type = action_type_t<condition>; + using result_type = result_type_t<action_type>; + + return c(r.template get<result_type>(), state, stepper); + } +}; + +/// This is the caller used if the condition only uses the cache +/// it has no access to the result +template <> +struct condition_caller<false> { + template <typename condition, typename result_t, typename propagator_state_t, + typename stepper_t> + static bool check(const condition& c, const result_t& /*result*/, + propagator_state_t& state, const stepper_t& stepper) { + return c(state, stepper); + } +}; +} // end of anonymous namespace + +template <typename... conditions> +struct abort_list_impl; + +/// This is the check call on the a list of conditions +/// it calls the aparant condition and broadcasts +/// the call to the remaining ones +template <typename first, typename... others> +struct abort_list_impl<first, others...> { + template <typename T, typename result_t, typename propagator_state_t, + typename stepper_t> + static bool check(const T& conditions_tuple, const result_t& result, + propagator_state_t& state, const stepper_t& stepper) { + // get the right helper for calling the abort condition + constexpr bool has_result = condition_uses_result_type<first>::value; + using caller_type = condition_caller<has_result>; + + // get the cache abort condition + const auto& this_condition = std::get<first>(conditions_tuple); + + // - check abort conditions recursively + // - make use of short-circuit evaluation + // -> skip remaining conditions if this abort condition evaluates to true + bool abort = caller_type::check(this_condition, result, state, stepper) || + abort_list_impl<others...>::check(conditions_tuple, result, + state, stepper); + + return abort; + } +}; + +/// This is the check call on the a last of all conditions +template <typename last> +struct abort_list_impl<last> { + template <typename T, typename result_t, typename propagator_state_t, + typename stepper_t> + static bool check(const T& conditions_tuple, const result_t& result, + propagator_state_t& state, const stepper_t& stepper) { + // get the right helper for calling the abort condition + constexpr bool has_result = condition_uses_result_type<last>::value; + const auto& this_condition = std::get<last>(conditions_tuple); + + return condition_caller<has_result>::check(this_condition, result, state, + stepper); + } +}; + +/// This is the empty call list - never abort +template <> +struct abort_list_impl<> { + template <typename T, typename result_t, typename propagator_state_t, + typename stepper_t> + static bool check(const T& /*unused*/, const result_t& /*result*/, + propagator_state_t& /*state*/, + const stepper_t& /*unused*/) { + return false; + } +}; } // namespace detail diff --git a/Core/include/Acts/Propagator/detail/action_list_implementation.hpp b/Core/include/Acts/Propagator/detail/action_list_implementation.hpp index b6717fccf0b01de8424724531c292a43fb265e1a..8f2fbc7d3d31593a68c2bf2cd6171225aebf7901 100644 --- a/Core/include/Acts/Propagator/detail/action_list_implementation.hpp +++ b/Core/include/Acts/Propagator/detail/action_list_implementation.hpp @@ -13,113 +13,75 @@ namespace Acts { namespace detail { - namespace { +namespace { - /// The action caller struct, it's called with the - /// the right result object, which is taken out - /// from the result tuple - template <bool has_result = true> - struct action_caller - { - template <typename actor, - typename result_t, - typename propagator_state_t, - typename stepper_t> - static void - action(const actor& act, - propagator_state_t& state, - const stepper_t& stepper, - result_t& result) - { - act(state, - stepper, - result.template get<detail::result_type_t<actor>>()); - } - }; +/// The action caller struct, it's called with the +/// the right result object, which is taken out +/// from the result tuple +template <bool has_result = true> +struct action_caller { + template <typename actor, typename result_t, typename propagator_state_t, + typename stepper_t> + static void action(const actor& act, propagator_state_t& state, + const stepper_t& stepper, result_t& result) { + act(state, stepper, result.template get<detail::result_type_t<actor>>()); + } +}; - /// The action caller struct, without result object - template <> - struct action_caller<false> - { - template <typename actor, - typename result_t, - typename propagator_state_t, - typename stepper_t> - static void - action(const actor& act, - propagator_state_t& state, - const stepper_t& stepper, - result_t& /*unused*/) - { - act(state, stepper); - } - }; - } // end of anonymous namespace +/// The action caller struct, without result object +template <> +struct action_caller<false> { + template <typename actor, typename result_t, typename propagator_state_t, + typename stepper_t> + static void action(const actor& act, propagator_state_t& state, + const stepper_t& stepper, result_t& /*unused*/) { + act(state, stepper); + } +}; +} // end of anonymous namespace - /// The dummy list call implementation - template <typename... actors> - struct action_list_impl; +/// The dummy list call implementation +template <typename... actors> +struct action_list_impl; - /// The action list call implementation - /// - it calls 'action' on the current entry of the tuple - /// - then broadcasts the action call to the remaining tuple - template <typename first, typename... others> - struct action_list_impl<first, others...> - { - template <typename T, - typename result_t, - typename propagator_state_t, - typename stepper_t> - static void - action(const T& obs_tuple, - propagator_state_t& state, - const stepper_t& stepper, - result_t& result) - { - constexpr bool has_result = has_result_type_v<first>; - const auto& this_action = std::get<first>(obs_tuple); - action_caller<has_result>::action(this_action, state, stepper, result); - action_list_impl<others...>::action(obs_tuple, state, stepper, result); - } - }; +/// The action list call implementation +/// - it calls 'action' on the current entry of the tuple +/// - then broadcasts the action call to the remaining tuple +template <typename first, typename... others> +struct action_list_impl<first, others...> { + template <typename T, typename result_t, typename propagator_state_t, + typename stepper_t> + static void action(const T& obs_tuple, propagator_state_t& state, + const stepper_t& stepper, result_t& result) { + constexpr bool has_result = has_result_type_v<first>; + const auto& this_action = std::get<first>(obs_tuple); + action_caller<has_result>::action(this_action, state, stepper, result); + action_list_impl<others...>::action(obs_tuple, state, stepper, result); + } +}; - /// The action list call implementation - /// - it calls 'action' on the last entry of the tuple - template <typename last> - struct action_list_impl<last> - { - template <typename T, - typename result_t, - typename propagator_state_t, - typename stepper_t> - static void - action(const T& obs_tuple, - propagator_state_t& state, - const stepper_t& stepper, - result_t& result) - { - constexpr bool has_result = has_result_type_v<last>; - const auto& this_action = std::get<last>(obs_tuple); - action_caller<has_result>::action(this_action, state, stepper, result); - } - }; +/// The action list call implementation +/// - it calls 'action' on the last entry of the tuple +template <typename last> +struct action_list_impl<last> { + template <typename T, typename result_t, typename propagator_state_t, + typename stepper_t> + static void action(const T& obs_tuple, propagator_state_t& state, + const stepper_t& stepper, result_t& result) { + constexpr bool has_result = has_result_type_v<last>; + const auto& this_action = std::get<last>(obs_tuple); + action_caller<has_result>::action(this_action, state, stepper, result); + } +}; - /// The empty action list call implementation - template <> - struct action_list_impl<> - { - template <typename T, - typename result_t, - typename propagator_state_t, - typename stepper_t> - static void - action(const T& /*unused*/, - propagator_state_t& /*unused*/, - const stepper_t& /*unused*/, - result_t& /*unused*/) - { - } - }; +/// The empty action list call implementation +template <> +struct action_list_impl<> { + template <typename T, typename result_t, typename propagator_state_t, + typename stepper_t> + static void action(const T& /*unused*/, propagator_state_t& /*unused*/, + const stepper_t& /*unused*/, result_t& /*unused*/) {} +}; } // namespace detail } // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Propagator/detail/action_signature_check.hpp b/Core/include/Acts/Propagator/detail/action_signature_check.hpp index 6e025f39af470819ce20f32b4d4c10285939ddcb..d303abbef6b4b0a314f68f261b3361feaba10f94 100644 --- a/Core/include/Acts/Propagator/detail/action_signature_check.hpp +++ b/Core/include/Acts/Propagator/detail/action_signature_check.hpp @@ -39,70 +39,46 @@ namespace Acts { /// clang-format off namespace detail { - namespace { +namespace { - template <typename T, - typename propagator_state_t, - typename stepper_t, - typename result_t, - typename - = decltype(std::declval<T>(). - operator()(std::declval<propagator_state_t&>(), - std::declval<stepper_t&>(), - std::declval<result_t&>()))> - std::true_type - test_action_with_result(int); +template <typename T, typename propagator_state_t, typename stepper_t, + typename result_t, + typename = decltype(std::declval<T>().operator()( + std::declval<propagator_state_t&>(), std::declval<stepper_t&>(), + std::declval<result_t&>()))> +std::true_type test_action_with_result(int); - template <typename, typename, typename, typename> - std::false_type - test_action_with_result(...); +template <typename, typename, typename, typename> +std::false_type test_action_with_result(...); - template <typename T, - typename propagator_state_t, - typename stepper_t, - typename - = decltype(std::declval<T>(). - operator()(std::declval<propagator_state_t&>(), - std::declval<stepper_t&>()))> - std::true_type - test_action_without_result(int); +template <typename T, typename propagator_state_t, typename stepper_t, + typename = decltype(std::declval<T>().operator()( + std::declval<propagator_state_t&>(), std::declval<stepper_t&>()))> +std::true_type test_action_without_result(int); - template <typename> - std::false_type - test_action_without_result(...); +template <typename> +std::false_type test_action_without_result(...); - template <typename T, - typename propagator_state_t, - typename stepper_t, - bool has_result = false> - struct action_signature_check_impl - : decltype( - test_action_without_result<T, propagator_state_t, stepper_t>(0)) - { - }; +template <typename T, typename propagator_state_t, typename stepper_t, + bool has_result = false> +struct action_signature_check_impl + : decltype( + test_action_without_result<T, propagator_state_t, stepper_t>(0)) {}; - template <typename T, typename propagator_state_t, typename stepper_t> - struct action_signature_check_impl<T, propagator_state_t, stepper_t, true> - : decltype(test_action_with_result<T, - propagator_state_t, - stepper_t, - detail::result_type_t<T>>(0)) - { - }; +template <typename T, typename propagator_state_t, typename stepper_t> +struct action_signature_check_impl<T, propagator_state_t, stepper_t, true> + : decltype(test_action_with_result<T, propagator_state_t, stepper_t, + detail::result_type_t<T>>(0)) {}; - template <typename T, typename propagator_state_t, typename stepper_t> - struct action_signature_check - : action_signature_check_impl<T, - propagator_state_t, - stepper_t, - detail::has_result_type_v<T>> - { - }; - } // end of anonymous namespace +template <typename T, typename propagator_state_t, typename stepper_t> +struct action_signature_check + : action_signature_check_impl<T, propagator_state_t, stepper_t, + detail::has_result_type_v<T>> {}; +} // end of anonymous namespace - template <typename T, typename propagator_state_t, typename stepper_t> - constexpr bool action_signature_check_v - = action_signature_check<T, propagator_state_t, stepper_t>::value; +template <typename T, typename propagator_state_t, typename stepper_t> +constexpr bool action_signature_check_v = + action_signature_check<T, propagator_state_t, stepper_t>::value; } // namespace detail } // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Propagator/detail/condition_uses_result_type.hpp b/Core/include/Acts/Propagator/detail/condition_uses_result_type.hpp index e6643c7984fd3a3a40fac020ea58c6dfac1c460f..445c7b5bdecc098dc051751c6bb382a99bcfc38b 100644 --- a/Core/include/Acts/Propagator/detail/condition_uses_result_type.hpp +++ b/Core/include/Acts/Propagator/detail/condition_uses_result_type.hpp @@ -14,22 +14,17 @@ namespace Acts { namespace detail { - template <typename T, bool has_action = true> - struct condition_uses_result_type_impl - { - static constexpr bool value = has_result_type_v<action_type_t<T>>; - }; - - template <typename T> - struct condition_uses_result_type_impl<T, false> : std::false_type - { - }; - - template <typename T> - struct condition_uses_result_type - : condition_uses_result_type_impl<T, has_action_type_v<T>> - { - }; +template <typename T, bool has_action = true> +struct condition_uses_result_type_impl { + static constexpr bool value = has_result_type_v<action_type_t<T>>; +}; + +template <typename T> +struct condition_uses_result_type_impl<T, false> : std::false_type {}; + +template <typename T> +struct condition_uses_result_type + : condition_uses_result_type_impl<T, has_action_type_v<T>> {}; } // namespace detail diff --git a/Core/include/Acts/Propagator/detail/stepper_extension_list_implementation.hpp b/Core/include/Acts/Propagator/detail/stepper_extension_list_implementation.hpp index bbb9b7bc80993a2b33dfb06adc742c7592357c68..fdffa2d5b349bff06c346fa2d90b19047461c7dd 100644 --- a/Core/include/Acts/Propagator/detail/stepper_extension_list_implementation.hpp +++ b/Core/include/Acts/Propagator/detail/stepper_extension_list_implementation.hpp @@ -31,185 +31,143 @@ namespace Acts { namespace detail { - /// The dummy list call implementation - template <unsigned int N> - struct stepper_extension_list_impl; +/// The dummy list call implementation +template <unsigned int N> +struct stepper_extension_list_impl; + +/// The extension list call implementation +/// - it calls 'validExtensionsForStep()' on the current entry of the tuple +/// - it stores the result in @p validExtensions +/// - then broadcasts the extension call to the remaining tuple +template <unsigned int N> +struct stepper_extension_list_impl { + template <typename propagator_state_t, typename stepper_t, typename... T> + static void bid(const std::tuple<T...>& obs_tuple, + const propagator_state_t& state, const stepper_t& stepper, + std::array<int, sizeof...(T)>& bids) { + std::get<N - 1>(bids) = std::get<N - 1>(obs_tuple).bid(state, stepper); + stepper_extension_list_impl<N - 1>::bid(obs_tuple, state, stepper, bids); + } /// The extension list call implementation - /// - it calls 'validExtensionsForStep()' on the current entry of the tuple - /// - it stores the result in @p validExtensions + /// - it calls 'k()' on the current entry of the tuple /// - then broadcasts the extension call to the remaining tuple - template <unsigned int N> - struct stepper_extension_list_impl - { - template <typename propagator_state_t, typename stepper_t, typename... T> - static void - bid(const std::tuple<T...>& obs_tuple, - const propagator_state_t& state, - const stepper_t& stepper, - std::array<int, sizeof...(T)>& bids) - { - std::get<N - 1>(bids) = std::get<N - 1>(obs_tuple).bid(state, stepper); - stepper_extension_list_impl<N - 1>::bid(obs_tuple, state, stepper, bids); + template <typename propagator_state_t, typename stepper_t, typename... T> + static bool k(std::tuple<T...>& obs_tuple, const propagator_state_t& state, + const stepper_t& stepper, Vector3D& knew, + const Vector3D& bField, + const std::array<bool, sizeof...(T)>& validExtensions, + const int i = 0, const double h = 0, + const Vector3D& kprev = Vector3D()) { + // If element is invalid: continue + if (!std::get<N - 1>(validExtensions)) { + return stepper_extension_list_impl<N - 1>::k( + obs_tuple, state, stepper, knew, bField, validExtensions, i, h, + kprev); } - /// The extension list call implementation - /// - it calls 'k()' on the current entry of the tuple - /// - then broadcasts the extension call to the remaining tuple - template <typename propagator_state_t, typename stepper_t, typename... T> - static bool - k(std::tuple<T...>& obs_tuple, - const propagator_state_t& state, - const stepper_t& stepper, - Vector3D& knew, - const Vector3D& bField, - const std::array<bool, sizeof...(T)>& validExtensions, - const int i = 0, - const double h = 0, - const Vector3D& kprev = Vector3D()) - { - // If element is invalid: continue - if (!std::get<N - 1>(validExtensions)) { - return stepper_extension_list_impl<N - 1>::k(obs_tuple, - state, - stepper, - knew, - bField, - validExtensions, - i, - h, - kprev); - } - - // Continue as long as evaluations are 'true' - if (std::get<N - 1>(obs_tuple).k( - state, stepper, knew, bField, i, h, kprev)) { - return stepper_extension_list_impl<N - 1>::k(obs_tuple, - state, - stepper, - knew, - bField, - validExtensions, - i, - h, - kprev); - } else { - // Break at false - return false; - } + // Continue as long as evaluations are 'true' + if (std::get<N - 1>(obs_tuple).k(state, stepper, knew, bField, i, h, + kprev)) { + return stepper_extension_list_impl<N - 1>::k( + obs_tuple, state, stepper, knew, bField, validExtensions, i, h, + kprev); + } else { + // Break at false + return false; } + } - /// The extension list call implementation - /// - it calls 'finalize()' on the current entry of the tuple - /// - then broadcasts the extension call to the remaining tuple - template <typename propagator_state_t, typename stepper_t, typename... T> - static bool - finalize(const std::tuple<T...>& obs_tuple, - propagator_state_t& state, - const stepper_t& stepper, - const double h, - ActsMatrixD<7, 7>& D, - const std::array<bool, sizeof...(T)>& validExtensions) - { - // If element is invalid: continue - if (!std::get<N - 1>(validExtensions)) { - return stepper_extension_list_impl<N - 1>::finalize( - obs_tuple, state, stepper, h, D, validExtensions); - } - - // Continue as long as evaluations are 'true' - if (std::get<N - 1>(obs_tuple).finalize(state, stepper, h, D)) { - return stepper_extension_list_impl<N - 1>::finalize( - obs_tuple, state, stepper, h, D, validExtensions); - } else { - // Break at false - return false; - } + /// The extension list call implementation + /// - it calls 'finalize()' on the current entry of the tuple + /// - then broadcasts the extension call to the remaining tuple + template <typename propagator_state_t, typename stepper_t, typename... T> + static bool finalize(const std::tuple<T...>& obs_tuple, + propagator_state_t& state, const stepper_t& stepper, + const double h, ActsMatrixD<7, 7>& D, + const std::array<bool, sizeof...(T)>& validExtensions) { + // If element is invalid: continue + if (!std::get<N - 1>(validExtensions)) { + return stepper_extension_list_impl<N - 1>::finalize( + obs_tuple, state, stepper, h, D, validExtensions); } - /// The extension list call implementation - /// - it calls 'finalize()' on the current entry of the tuple - /// - then broadcasts the extension call to the remaining tuple - template <typename propagator_state_t, typename stepper_t, typename... T> - static bool - finalize(const std::tuple<T...>& obs_tuple, - propagator_state_t& state, - const stepper_t& stepper, - const double h, - const std::array<bool, sizeof...(T)>& validExtensions) - { - // If element is invalid: continue - if (!std::get<N - 1>(validExtensions)) { - return stepper_extension_list_impl<N - 1>::finalize( - obs_tuple, state, stepper, h, validExtensions); - } - - // Continue as long as evaluations are 'true' - if (std::get<N - 1>(obs_tuple).finalize(state, stepper, h)) { - return stepper_extension_list_impl<N - 1>::finalize( - obs_tuple, state, stepper, h, validExtensions); - } else { - // Break at false - return false; - } + // Continue as long as evaluations are 'true' + if (std::get<N - 1>(obs_tuple).finalize(state, stepper, h, D)) { + return stepper_extension_list_impl<N - 1>::finalize( + obs_tuple, state, stepper, h, D, validExtensions); + } else { + // Break at false + return false; } - }; + } - /// Template specialized list call implementation - template <> - struct stepper_extension_list_impl<0u> - { - /// The empty extension list call implementation - template <typename propagator_state_t, typename stepper_t, typename... T> - static void - bid(const std::tuple<T...>& /*unused*/, - const propagator_state_t& /*unused*/, - const stepper_t& /*unused*/, - std::array<int, sizeof...(T)>& /*unused*/) - { + /// The extension list call implementation + /// - it calls 'finalize()' on the current entry of the tuple + /// - then broadcasts the extension call to the remaining tuple + template <typename propagator_state_t, typename stepper_t, typename... T> + static bool finalize(const std::tuple<T...>& obs_tuple, + propagator_state_t& state, const stepper_t& stepper, + const double h, + const std::array<bool, sizeof...(T)>& validExtensions) { + // If element is invalid: continue + if (!std::get<N - 1>(validExtensions)) { + return stepper_extension_list_impl<N - 1>::finalize( + obs_tuple, state, stepper, h, validExtensions); } - /// The empty extension list call implementation - template <typename propagator_state_t, typename stepper_t, typename... T> - static bool - k(std::tuple<T...>& /*unused*/, - const propagator_state_t& /*unused*/, - const stepper_t& /*unused*/, - Vector3D& /*unused*/, - const Vector3D& /*unused*/, - const std::array<bool, sizeof...(T)>& /*unused*/, - const int /*unused*/, - const double /*unused*/, - const Vector3D& /*unused*/) - { - return true; + // Continue as long as evaluations are 'true' + if (std::get<N - 1>(obs_tuple).finalize(state, stepper, h)) { + return stepper_extension_list_impl<N - 1>::finalize( + obs_tuple, state, stepper, h, validExtensions); + } else { + // Break at false + return false; } + } +}; - /// The empty extension list call implementation - template <typename propagator_state_t, typename stepper_t, typename... T> - static bool - finalize(const std::tuple<T...>& /*unused*/, - propagator_state_t& /*unused*/, - const stepper_t& /*unused*/, - const double /*unused*/, - ActsMatrixD<7, 7>& /*unused*/, - const std::array<bool, sizeof...(T)>& /*unused*/) - { - return true; - } +/// Template specialized list call implementation +template <> +struct stepper_extension_list_impl<0u> { + /// The empty extension list call implementation + template <typename propagator_state_t, typename stepper_t, typename... T> + static void bid(const std::tuple<T...>& /*unused*/, + const propagator_state_t& /*unused*/, + const stepper_t& /*unused*/, + std::array<int, sizeof...(T)>& /*unused*/) {} - /// The empty extension list call implementation - template <typename propagator_state_t, typename stepper_t, typename... T> - static bool - finalize(const std::tuple<T...>& /*unused*/, - propagator_state_t& /*unused*/, - const stepper_t& /*unused*/, - const double /*unused*/, - const std::array<bool, sizeof...(T)>& /*unused*/) - { - return true; - } - }; + /// The empty extension list call implementation + template <typename propagator_state_t, typename stepper_t, typename... T> + static bool k(std::tuple<T...>& /*unused*/, + const propagator_state_t& /*unused*/, + const stepper_t& /*unused*/, Vector3D& /*unused*/, + const Vector3D& /*unused*/, + const std::array<bool, sizeof...(T)>& /*unused*/, + const int /*unused*/, const double /*unused*/, + const Vector3D& /*unused*/) { + return true; + } + + /// The empty extension list call implementation + template <typename propagator_state_t, typename stepper_t, typename... T> + static bool finalize(const std::tuple<T...>& /*unused*/, + propagator_state_t& /*unused*/, + const stepper_t& /*unused*/, const double /*unused*/, + ActsMatrixD<7, 7>& /*unused*/, + const std::array<bool, sizeof...(T)>& /*unused*/) { + return true; + } + + /// The empty extension list call implementation + template <typename propagator_state_t, typename stepper_t, typename... T> + static bool finalize(const std::tuple<T...>& /*unused*/, + propagator_state_t& /*unused*/, + const stepper_t& /*unused*/, const double /*unused*/, + const std::array<bool, sizeof...(T)>& /*unused*/) { + return true; + } +}; } // namespace detail } // namespace Acts diff --git a/Core/include/Acts/Seeding/BinFinder.hpp b/Core/include/Acts/Seeding/BinFinder.hpp index e445022cd16ae7e4db3afc01f894e1f70240e304..cc74081303cf310ddde4903def604dbe47005789 100644 --- a/Core/include/Acts/Seeding/BinFinder.hpp +++ b/Core/include/Acts/Seeding/BinFinder.hpp @@ -20,9 +20,8 @@ namespace Acts { /// top bins, which are assumed to be the same bins. Does not take interaction /// region into account to limit z-bins. template <typename SpacePoint> -class BinFinder : public IBinFinder<SpacePoint> -{ -public: +class BinFinder : public IBinFinder<SpacePoint> { + public: /// destructor ~BinFinder() override = default; @@ -31,10 +30,9 @@ public: /// @param phiBin phi index of bin with middle space points /// @param zBin z index of bin with middle space points /// @param binnedSP phi-z grid containing all bins - std::vector<size_t> - findBins(size_t phiBin, - size_t zBin, - const SpacePointGrid<SpacePoint>* binnedSP) override; + std::vector<size_t> findBins( + size_t phiBin, size_t zBin, + const SpacePointGrid<SpacePoint>* binnedSP) override; }; -} +} // namespace Acts #include "Acts/Seeding/BinFinder.ipp" diff --git a/Core/include/Acts/Seeding/BinFinder.ipp b/Core/include/Acts/Seeding/BinFinder.ipp index 91d0ee9f6c5e7d35de3647e1c92fa830b3ca4bc3..cd16c9d49bf01f9b2f2d85da7bb0db31ac9435e2 100644 --- a/Core/include/Acts/Seeding/BinFinder.ipp +++ b/Core/include/Acts/Seeding/BinFinder.ipp @@ -6,11 +6,8 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. template <typename SpacePoint> -std::vector<size_t> -Acts::BinFinder<SpacePoint>::findBins( - size_t phiBin, - size_t zBin, - const Acts::SpacePointGrid<SpacePoint>* binnedSP) -{ +std::vector<size_t> Acts::BinFinder<SpacePoint>::findBins( + size_t phiBin, size_t zBin, + const Acts::SpacePointGrid<SpacePoint>* binnedSP) { return binnedSP->neighborHoodIndices({phiBin, zBin}).collect(); } diff --git a/Core/include/Acts/Seeding/IBinFinder.hpp b/Core/include/Acts/Seeding/IBinFinder.hpp index aa7617f6e0cd16640596e8def38bc51ef08c392e..48a62de5dc2a1c6c1a70f853fc30be6e622dcc5c 100644 --- a/Core/include/Acts/Seeding/IBinFinder.hpp +++ b/Core/include/Acts/Seeding/IBinFinder.hpp @@ -17,9 +17,8 @@ namespace Acts { /// finder. It only contains one function that takes the indices of the bin /// that contains all middle space points for the three space point seeds. template <typename SpacePoint> -class IBinFinder -{ -public: +class IBinFinder { + public: /// destructor virtual ~IBinFinder() = default; @@ -33,10 +32,8 @@ public: /// potentially /// containing bottom resp. top space points that can be combined with the /// middle space points from the provided bin - virtual std::vector<size_t> - findBins(size_t phiBin, - size_t zBin, - const SpacePointGrid<SpacePoint>* binnedSP) - = 0; + virtual std::vector<size_t> findBins( + size_t phiBin, size_t zBin, + const SpacePointGrid<SpacePoint>* binnedSP) = 0; }; -} +} // namespace Acts diff --git a/Core/include/Acts/Seeding/IExperimentCuts.hpp b/Core/include/Acts/Seeding/IExperimentCuts.hpp index 4fabaa70df8ab9008b80e2ff9cf5bd1f50ab999c..f823531099d006bba3112e3db3decfe31a8a33fc 100644 --- a/Core/include/Acts/Seeding/IExperimentCuts.hpp +++ b/Core/include/Acts/Seeding/IExperimentCuts.hpp @@ -18,41 +18,37 @@ namespace Acts { /// to decide if a seed passes a seed weight cut. As the weight is stored in /// seeds, there are two distinct methods. template <typename SpacePoint> -class IExperimentCuts -{ -public: +class IExperimentCuts { + public: virtual ~IExperimentCuts() = default; /// Returns seed weight bonus/malus depending on detector considerations. /// @param bottom bottom space point of the current seed /// @param middle middle space point of the current seed /// @param top top space point of the current seed /// @return seed weight to be added to the seed's weight - virtual float - seedWeight(const InternalSpacePoint<SpacePoint>& bottom, - const InternalSpacePoint<SpacePoint>& middle, - const InternalSpacePoint<SpacePoint>& top) const = 0; + virtual float seedWeight(const InternalSpacePoint<SpacePoint>& bottom, + const InternalSpacePoint<SpacePoint>& middle, + const InternalSpacePoint<SpacePoint>& top) const = 0; /// @param weight the current seed weight /// @param bottom bottom space point of the current seed /// @param middle middle space point of the current seed /// @param top top space point of the current seed /// @return true if the seed should be kept, false if the seed should be /// discarded - virtual bool - singleSeedCut(float weight, - const InternalSpacePoint<SpacePoint>& bottom, - const InternalSpacePoint<SpacePoint>& middle, - const InternalSpacePoint<SpacePoint>& top) const = 0; + virtual bool singleSeedCut( + float weight, const InternalSpacePoint<SpacePoint>& bottom, + const InternalSpacePoint<SpacePoint>& middle, + const InternalSpacePoint<SpacePoint>& top) const = 0; /// @param seeds contains pairs of weight and seed created for one middle /// space /// point /// @return vector of seeds that pass the cut - virtual std:: - vector<std::pair<float, std::unique_ptr<const InternalSeed<SpacePoint>>>> - cutPerMiddleSP( - std:: - vector<std::pair<float, - std::unique_ptr<const InternalSeed<SpacePoint>>>> - seeds) const = 0; + virtual std::vector< + std::pair<float, std::unique_ptr<const InternalSeed<SpacePoint>>>> + cutPerMiddleSP( + std::vector< + std::pair<float, std::unique_ptr<const InternalSeed<SpacePoint>>>> + seeds) const = 0; }; -} +} // namespace Acts diff --git a/Core/include/Acts/Seeding/InternalSeed.hpp b/Core/include/Acts/Seeding/InternalSeed.hpp index 44a1855e3ee6f82c12b971c103e8d5fa602644a4..bdb4ca6e1ea7d5ca058e271ee7c4f08fb60d18e5 100644 --- a/Core/include/Acts/Seeding/InternalSeed.hpp +++ b/Core/include/Acts/Seeding/InternalSeed.hpp @@ -15,29 +15,21 @@ namespace Acts { template <typename SpacePoint> -class InternalSeed -{ - +class InternalSeed { ///////////////////////////////////////////////////////////////////////////////// // Public methods: ///////////////////////////////////////////////////////////////////////////////// -public: + public: InternalSeed(const InternalSpacePoint<SpacePoint>& s0, const InternalSpacePoint<SpacePoint>& s1, - const InternalSpacePoint<SpacePoint>& s2, - float z); - InternalSeed& - operator=(const InternalSeed& seed); + const InternalSpacePoint<SpacePoint>& s2, float z); + InternalSeed& operator=(const InternalSeed& seed); const std::array<const InternalSpacePoint<SpacePoint>*, 3> sp; - float - z() const - { - return m_z; - } + float z() const { return m_z; } -protected: + protected: float m_z; }; @@ -46,11 +38,10 @@ protected: ///////////////////////////////////////////////////////////////////////////////// template <typename SpacePoint> -inline InternalSeed<SpacePoint>& -InternalSeed<SpacePoint>::operator=(const InternalSeed<SpacePoint>& seed) -{ +inline InternalSeed<SpacePoint>& InternalSeed<SpacePoint>::operator=( + const InternalSeed<SpacePoint>& seed) { m_z = seed.m_z; - sp = seed.sp; + sp = seed.sp; return (*this); } @@ -58,11 +49,9 @@ template <typename SpacePoint> inline InternalSeed<SpacePoint>::InternalSeed( const InternalSpacePoint<SpacePoint>& s0, const InternalSpacePoint<SpacePoint>& s1, - const InternalSpacePoint<SpacePoint>& s2, - float z) - : sp({&s0, &s1, &s2}) -{ + const InternalSpacePoint<SpacePoint>& s2, float z) + : sp({&s0, &s1, &s2}) { m_z = z; } -} // end of Acts namespace +} // namespace Acts diff --git a/Core/include/Acts/Seeding/InternalSpacePoint.hpp b/Core/include/Acts/Seeding/InternalSpacePoint.hpp index 50c69f34356c95e6a947b6a017fd84355c55563e..f079d8fc647aa09211a1f1b3d56571cae5d04e74 100644 --- a/Core/include/Acts/Seeding/InternalSpacePoint.hpp +++ b/Core/include/Acts/Seeding/InternalSpacePoint.hpp @@ -16,75 +16,39 @@ namespace Acts { template <typename SpacePoint> -class InternalSpacePoint -{ - +class InternalSpacePoint { ///////////////////////////////////////////////////////////////////////////////// // Public methods: ///////////////////////////////////////////////////////////////////////////////// -public: + public: InternalSpacePoint() = delete; - InternalSpacePoint(const SpacePoint& sp, - const Acts::Vector3D& globalPos, - const Acts::Vector2D& offsetXY, - const Acts::Vector2D& cov); + InternalSpacePoint(const SpacePoint& sp, const Acts::Vector3D& globalPos, + const Acts::Vector2D& offsetXY, const Acts::Vector2D& cov); InternalSpacePoint(const InternalSpacePoint<SpacePoint>& sp); ~InternalSpacePoint() = default; - InternalSpacePoint<SpacePoint>& - operator=(const InternalSpacePoint<SpacePoint>&); + InternalSpacePoint<SpacePoint>& operator=( + const InternalSpacePoint<SpacePoint>&); - const float& - x() const - { - return m_x; - } - const float& - y() const - { - return m_y; - } - const float& - z() const - { - return m_z; - } - const float& - radius() const - { - return m_r; - } - float - phi() const - { - return atan2f(m_y, m_x); - } - const float& - covr() const - { - return m_covr; - } - const float& - covz() const - { - return m_covz; - } - const SpacePoint& - sp() const - { - return m_sp; - } + const float& x() const { return m_x; } + const float& y() const { return m_y; } + const float& z() const { return m_z; } + const float& radius() const { return m_r; } + float phi() const { return atan2f(m_y, m_x); } + const float& covr() const { return m_covr; } + const float& covz() const { return m_covz; } + const SpacePoint& sp() const { return m_sp; } -protected: - float m_x; // x-coordinate in beam system coordinates - float m_y; // y-coordinate in beam system coordinates - float m_z; // z-coordinate in beam system coordinetes - float m_r; // radius in beam system coordinates - float m_covr; // - float m_covz; // - const SpacePoint& m_sp; // external space point + protected: + float m_x; // x-coordinate in beam system coordinates + float m_y; // y-coordinate in beam system coordinates + float m_z; // z-coordinate in beam system coordinetes + float m_r; // radius in beam system coordinates + float m_covr; // + float m_covz; // + const SpacePoint& m_sp; // external space point }; ///////////////////////////////////////////////////////////////////////////////// @@ -93,16 +57,13 @@ protected: template <typename SpacePoint> inline InternalSpacePoint<SpacePoint>::InternalSpacePoint( - const SpacePoint& sp, - const Acts::Vector3D& globalPos, - const Acts::Vector2D& offsetXY, - const Acts::Vector2D& cov) - : m_sp(sp) -{ - m_x = globalPos.x() - offsetXY.x(); - m_y = globalPos.y() - offsetXY.y(); - m_z = globalPos.z(); - m_r = std::sqrt(m_x * m_x + m_y * m_y); + const SpacePoint& sp, const Acts::Vector3D& globalPos, + const Acts::Vector2D& offsetXY, const Acts::Vector2D& cov) + : m_sp(sp) { + m_x = globalPos.x() - offsetXY.x(); + m_y = globalPos.y() - offsetXY.y(); + m_z = globalPos.z(); + m_r = std::sqrt(m_x * m_x + m_y * m_y); m_covr = cov.x(); m_covz = cov.y(); } @@ -114,12 +75,11 @@ inline InternalSpacePoint<SpacePoint>::InternalSpacePoint( template <typename SpacePoint> inline InternalSpacePoint<SpacePoint>::InternalSpacePoint( const InternalSpacePoint<SpacePoint>& sp) - : m_sp(sp.sp()) -{ - m_x = sp.m_x; - m_y = sp.m_y; - m_z = sp.m_z; - m_r = sp.m_r; + : m_sp(sp.sp()) { + m_x = sp.m_x; + m_y = sp.m_y; + m_z = sp.m_z; + m_r = sp.m_r; m_covr = sp.m_covr; m_covz = sp.m_covz; } diff --git a/Core/include/Acts/Seeding/Seed.hpp b/Core/include/Acts/Seeding/Seed.hpp index 41d5e6b0e7afbf17c58d7cad2474bde1a15fde72..27caac54b5f6d245e3dbff3dc8cc4c6a1df04d1a 100644 --- a/Core/include/Acts/Seeding/Seed.hpp +++ b/Core/include/Acts/Seeding/Seed.hpp @@ -12,36 +12,23 @@ namespace Acts { template <typename SpacePoint> -class Seed -{ - +class Seed { ///////////////////////////////////////////////////////////////////////////////// // Public methods: ///////////////////////////////////////////////////////////////////////////////// -public: - Seed(const SpacePoint& b, - const SpacePoint& m, - const SpacePoint& u, - float vertex); + public: + Seed(const SpacePoint& b, const SpacePoint& m, const SpacePoint& u, + float vertex); Seed(const Seed&) = default; - Seed& - operator=(const Seed&); - - const std::vector<const SpacePoint*>& - sp() const - { - return m_spacepoints; - } - double - z() const - { - return m_zvertex; - } - -private: + Seed& operator=(const Seed&); + + const std::vector<const SpacePoint*>& sp() const { return m_spacepoints; } + double z() const { return m_zvertex; } + + private: std::vector<const SpacePoint*> m_spacepoints; - float m_zvertex; + float m_zvertex; }; /////////////////////////////////////////////////////////////////////////////// @@ -49,15 +36,12 @@ private: /////////////////////////////////////////////////////////////////////////////// template <typename SpacePoint> -Seed<SpacePoint>::Seed(const SpacePoint& b, - const SpacePoint& m, - const SpacePoint& u, - float vertex) -{ +Seed<SpacePoint>::Seed(const SpacePoint& b, const SpacePoint& m, + const SpacePoint& u, float vertex) { m_zvertex = vertex; m_spacepoints.push_back(&b); m_spacepoints.push_back(&m); m_spacepoints.push_back(&u); } -} // end of Acts namespace +} // namespace Acts diff --git a/Core/include/Acts/Seeding/SeedFilter.hpp b/Core/include/Acts/Seeding/SeedFilter.hpp index fee6112b10cc2baa1ca635dd2b9fa0cc1a9276a8..59878cb07db61f6a0690f16c2332d2b93de7bc43 100644 --- a/Core/include/Acts/Seeding/SeedFilter.hpp +++ b/Core/include/Acts/Seeding/SeedFilter.hpp @@ -18,8 +18,7 @@ #include "Acts/Seeding/Seed.hpp" namespace Acts { -struct SeedFilterConfig -{ +struct SeedFilterConfig { // the allowed delta between two inverted seed radii for them to be considered // compatible. float deltaInvHelixDiameter = 0.00003; @@ -42,12 +41,11 @@ struct SeedFilterConfig /// @class Filter seeds at various stages with the currently /// available information. template <typename SpacePoint> -class SeedFilter -{ -public: +class SeedFilter { + public: SeedFilter(SeedFilterConfig config, IExperimentCuts<SpacePoint>* expCuts = 0); - SeedFilter() = delete; + SeedFilter() = delete; virtual ~SeedFilter() = default; /// Create InternalSeeds for the all seeds with the same bottom and middle @@ -59,30 +57,27 @@ public: /// @param origin on the z axis as defined by bottom and middle space point /// @return vector of pairs containing seed weight and seed for all valid /// created seeds - virtual std:: - vector<std::pair<float, std::unique_ptr<const InternalSeed<SpacePoint>>>> - filterSeeds_2SpFixed( - const InternalSpacePoint<SpacePoint>& bottomSP, - const InternalSpacePoint<SpacePoint>& middleSP, - std::vector<const InternalSpacePoint<SpacePoint>*>& topSpVec, - std::vector<float>& invHelixDiameterVec, - std::vector<float>& impactParametersVec, - float zOrigin) const; + virtual std::vector< + std::pair<float, std::unique_ptr<const InternalSeed<SpacePoint>>>> + filterSeeds_2SpFixed( + const InternalSpacePoint<SpacePoint>& bottomSP, + const InternalSpacePoint<SpacePoint>& middleSP, + std::vector<const InternalSpacePoint<SpacePoint>*>& topSpVec, + std::vector<float>& invHelixDiameterVec, + std::vector<float>& impactParametersVec, float zOrigin) const; /// Filter seeds once all seeds for one middle space point have been created /// @param seedsPerSpM vector of pairs containing weight and seed for all /// for all seeds with the same middle space point /// @return vector of all InternalSeeds that not filtered out - virtual void - filterSeeds_1SpFixed( - std::vector<std::pair<float, - std::unique_ptr<const InternalSeed<SpacePoint>>>>& - seedsPerSpM, + virtual void filterSeeds_1SpFixed( + std::vector<std::pair< + float, std::unique_ptr<const InternalSeed<SpacePoint>>>>& seedsPerSpM, std::vector<std::unique_ptr<Seed<SpacePoint>>>& outVec) const; -private: - const SeedFilterConfig m_cfg; + private: + const SeedFilterConfig m_cfg; const IExperimentCuts<SpacePoint>* m_experimentCuts; }; -} +} // namespace Acts #include "Acts/Seeding/SeedFilter.ipp" diff --git a/Core/include/Acts/Seeding/SeedFilter.ipp b/Core/include/Acts/Seeding/SeedFilter.ipp index 5fc0052f8b913f305da746e1486f0668f2aef597..19096ec2b0ed815eb170b090d649a38c12b33760 100644 --- a/Core/include/Acts/Seeding/SeedFilter.ipp +++ b/Core/include/Acts/Seeding/SeedFilter.ipp @@ -12,11 +12,8 @@ namespace Acts { // constructor template <typename SpacePoint> SeedFilter<SpacePoint>::SeedFilter( - SeedFilterConfig config, - IExperimentCuts<SpacePoint>* expCuts /* = 0*/) - : m_cfg(config), m_experimentCuts(expCuts) -{ -} + SeedFilterConfig config, IExperimentCuts<SpacePoint>* expCuts /* = 0*/) + : m_cfg(config), m_experimentCuts(expCuts) {} // function to filter seeds based on all seeds with same bottom- and // middle-spacepoint. @@ -24,29 +21,25 @@ SeedFilter<SpacePoint>::SeedFilter( template <typename SpacePoint> std::vector<std::pair<float, std::unique_ptr<const InternalSeed<SpacePoint>>>> SeedFilter<SpacePoint>::filterSeeds_2SpFixed( - const InternalSpacePoint<SpacePoint>& bottomSP, - const InternalSpacePoint<SpacePoint>& middleSP, + const InternalSpacePoint<SpacePoint>& bottomSP, + const InternalSpacePoint<SpacePoint>& middleSP, std::vector<const InternalSpacePoint<SpacePoint>*>& topSpVec, - std::vector<float>& invHelixDiameterVec, - std::vector<float>& impactParametersVec, - float zOrigin) const -{ - + std::vector<float>& invHelixDiameterVec, + std::vector<float>& impactParametersVec, float zOrigin) const { std::vector<std::pair<float, std::unique_ptr<const InternalSeed<SpacePoint>>>> selectedSeeds; for (size_t i = 0; i < topSpVec.size(); i++) { - // if two compatible seeds with high distance in r are found, compatible // seeds span 5 layers // -> very good seed std::vector<float> compatibleSeedR; float invHelixDiameter = invHelixDiameterVec[i]; - float lowerLimitCurv = invHelixDiameter - m_cfg.deltaInvHelixDiameter; - float upperLimitCurv = invHelixDiameter + m_cfg.deltaInvHelixDiameter; - float currentTop_r = topSpVec[i]->radius(); - float impact = impactParametersVec[i]; + float lowerLimitCurv = invHelixDiameter - m_cfg.deltaInvHelixDiameter; + float upperLimitCurv = invHelixDiameter + m_cfg.deltaInvHelixDiameter; + float currentTop_r = topSpVec[i]->radius(); + float impact = impactParametersVec[i]; float weight = -(impact * m_cfg.impactWeightFactor); for (size_t j = 0; j < topSpVec.size(); j++) { @@ -55,7 +48,7 @@ SeedFilter<SpacePoint>::filterSeeds_2SpFixed( } // compared top SP should have at least deltaRMin distance float otherTop_r = topSpVec[j]->radius(); - float deltaR = currentTop_r - otherTop_r; + float deltaR = currentTop_r - otherTop_r; if (std::abs(deltaR) < m_cfg.deltaRMin) { continue; } @@ -91,37 +84,30 @@ SeedFilter<SpacePoint>::filterSeeds_2SpFixed( // add detector specific considerations on the seed weight weight += m_experimentCuts->seedWeight(bottomSP, middleSP, *topSpVec[i]); // discard seeds according to detector specific cuts (e.g.: weight) - if (!m_experimentCuts->singleSeedCut( - weight, bottomSP, middleSP, *topSpVec[i])) { + if (!m_experimentCuts->singleSeedCut(weight, bottomSP, middleSP, + *topSpVec[i])) { continue; } } selectedSeeds.push_back( - std::make_pair(weight, - std::make_unique<const InternalSeed<SpacePoint>>( - bottomSP, middleSP, *topSpVec[i], zOrigin))); + std::make_pair(weight, std::make_unique<const InternalSeed<SpacePoint>>( + bottomSP, middleSP, *topSpVec[i], zOrigin))); } return selectedSeeds; } // after creating all seeds with a common middle space point, filter again template <typename SpacePoint> -void -SeedFilter<SpacePoint>::filterSeeds_1SpFixed( - std::vector<std::pair<float, - std::unique_ptr<const InternalSeed<SpacePoint>>>>& - seedsPerSpM, - std::vector<std::unique_ptr<Seed<SpacePoint>>>& outVec) const -{ - +void SeedFilter<SpacePoint>::filterSeeds_1SpFixed( + std::vector<std::pair< + float, std::unique_ptr<const InternalSeed<SpacePoint>>>>& seedsPerSpM, + std::vector<std::unique_ptr<Seed<SpacePoint>>>& outVec) const { // sort by weight and iterate only up to configured max number of seeds per // middle SP std::sort( - (seedsPerSpM.begin()), - (seedsPerSpM.end()), - [](const std::pair<float, - std::unique_ptr<const Acts::InternalSeed<SpacePoint>>>& - i1, + (seedsPerSpM.begin()), (seedsPerSpM.end()), + [](const std::pair< + float, std::unique_ptr<const Acts::InternalSeed<SpacePoint>>>& i1, const std::pair<float, std::unique_ptr<const Acts::InternalSeed<SpacePoint>>>& i2) { return i1.first > i2.first; }); @@ -133,16 +119,14 @@ SeedFilter<SpacePoint>::filterSeeds_1SpFixed( maxSeeds = m_cfg.maxSeedsPerSpM + 1; } auto itBegin = seedsPerSpM.begin(); - auto it = seedsPerSpM.begin(); + auto it = seedsPerSpM.begin(); // default filter removes the last seeds if maximum amount exceeded // ordering by weight by filterSeeds_2SpFixed means these are the lowest // weight seeds for (; it < itBegin + maxSeeds; ++it) { - outVec.push_back( - std::make_unique<Seed<SpacePoint>>((*it).second->sp[0]->sp(), - (*it).second->sp[1]->sp(), - (*it).second->sp[2]->sp(), - (*it).second->z())); + outVec.push_back(std::make_unique<Seed<SpacePoint>>( + (*it).second->sp[0]->sp(), (*it).second->sp[1]->sp(), + (*it).second->sp[2]->sp(), (*it).second->z())); } } diff --git a/Core/include/Acts/Seeding/Seedfinder.hpp b/Core/include/Acts/Seeding/Seedfinder.hpp index 5cc80c106511fc8ffaab725db4cf558e4652fd44..1dd6f06444cb43cd50f1682a0cd190c11c2d77ad 100644 --- a/Core/include/Acts/Seeding/Seedfinder.hpp +++ b/Core/include/Acts/Seeding/Seedfinder.hpp @@ -23,8 +23,7 @@ #include <vector> namespace Acts { -struct LinCircle -{ +struct LinCircle { float Zo; float cotTheta; float iDeltaR; @@ -33,24 +32,22 @@ struct LinCircle float V; }; template <typename external_spacepoint_t> -class Seedfinder -{ +class Seedfinder { /////////////////////////////////////////////////////////////////// // Public methods: /////////////////////////////////////////////////////////////////// -public: + public: /// The only constructor. Requires a config object. /// @param config the configuration for the Seedfinder Seedfinder(const Acts::SeedfinderConfig<external_spacepoint_t> config); ~Seedfinder() = default; /** @name Disallow default instantiation, copy, assignment */ //@{ - Seedfinder() = delete; + Seedfinder() = delete; Seedfinder(const Seedfinder<external_spacepoint_t>&) = delete; - Seedfinder<external_spacepoint_t>& - operator=(const Seedfinder<external_spacepoint_t>&) - = delete; + Seedfinder<external_spacepoint_t>& operator=( + const Seedfinder<external_spacepoint_t>&) = delete; //@} /// @brief Create a new space point grid, fill all space points from input @@ -64,14 +61,11 @@ public: /// @return the state object containing all space points and container for /// found seeds template <typename spacepoint_iterator_t> - Acts::SeedfinderState<external_spacepoint_t> - initState( - spacepoint_iterator_t spBegin, - spacepoint_iterator_t spEnd, - std::function<Acts::Vector2D(const external_spacepoint_t&, - float, - float, - float)> covTool, + Acts::SeedfinderState<external_spacepoint_t> initState( + spacepoint_iterator_t spBegin, spacepoint_iterator_t spEnd, + std::function<Acts::Vector2D(const external_spacepoint_t&, float, float, + float)> + covTool, std::shared_ptr<Acts::IBinFinder<external_spacepoint_t>> bottomBinFinder, std::shared_ptr<Acts::IBinFinder<external_spacepoint_t>> topBinFinder) const; @@ -82,22 +76,19 @@ public: /// neighbors. Iterator must be separate object for each parallel call. /// @param state the state object in which all found seeds are stored. /// state object can be shared between all parallel calls - void - createSeedsForRegion( + void createSeedsForRegion( SeedfinderStateIterator<external_spacepoint_t> it, - Acts::SeedfinderState<external_spacepoint_t>& state) const; + Acts::SeedfinderState<external_spacepoint_t>& state) const; -private: - void - transformCoordinates( + private: + void transformCoordinates( std::vector<const InternalSpacePoint<external_spacepoint_t>*>& vec, - const InternalSpacePoint<external_spacepoint_t>& spM, - bool bottom, + const InternalSpacePoint<external_spacepoint_t>& spM, bool bottom, std::vector<LinCircle>& linCircleVec) const; Acts::SeedfinderConfig<external_spacepoint_t> m_config; }; -} // end of Acts namespace +} // namespace Acts #include "Acts/Seeding/Seedfinder.ipp" diff --git a/Core/include/Acts/Seeding/Seedfinder.ipp b/Core/include/Acts/Seeding/Seedfinder.ipp index 48a86f02726554c712206c32c65856f257001dc5..9cdcbeea800199a7e3575055e7593498019cd456 100644 --- a/Core/include/Acts/Seeding/Seedfinder.ipp +++ b/Core/include/Acts/Seeding/Seedfinder.ipp @@ -18,38 +18,34 @@ namespace Acts { template <typename external_spacepoint_t> Seedfinder<external_spacepoint_t>::Seedfinder( const Acts::SeedfinderConfig<external_spacepoint_t> config) - : m_config(std::move(config)) -{ - + : m_config(std::move(config)) { // calculation of scattering using the highland formula // convert pT to p once theta angle is known - m_config.highland = 13.6 * std::sqrt(m_config.radLengthPerSeed) - * (1 + 0.038 * std::log(m_config.radLengthPerSeed)); - float maxScatteringAngle = m_config.highland / m_config.minPt; + m_config.highland = 13.6 * std::sqrt(m_config.radLengthPerSeed) * + (1 + 0.038 * std::log(m_config.radLengthPerSeed)); + float maxScatteringAngle = m_config.highland / m_config.minPt; m_config.maxScatteringAngle2 = maxScatteringAngle * maxScatteringAngle; // helix radius in homogeneous magnetic field. Units are Kilotesla, MeV and // millimeter // TODO: change using ACTS units m_config.pTPerHelixRadius = 300. * m_config.bFieldInZ; - m_config.minHelixDiameter2 - = std::pow(m_config.minPt * 2 / m_config.pTPerHelixRadius, 2); - m_config.pT2perRadius - = std::pow(m_config.highland / m_config.pTPerHelixRadius, 2); + m_config.minHelixDiameter2 = + std::pow(m_config.minPt * 2 / m_config.pTPerHelixRadius, 2); + m_config.pT2perRadius = + std::pow(m_config.highland / m_config.pTPerHelixRadius, 2); } template <typename external_spacepoint_t> template <typename spacepoint_iterator_t> Acts::SeedfinderState<external_spacepoint_t> Seedfinder<external_spacepoint_t>::initState( - spacepoint_iterator_t spBegin, - spacepoint_iterator_t spEnd, - std::function<Acts::Vector2D(const external_spacepoint_t&, - float, - float, - float)> covTool, + spacepoint_iterator_t spBegin, spacepoint_iterator_t spEnd, + std::function<Acts::Vector2D(const external_spacepoint_t&, float, float, + float)> + covTool, std::shared_ptr<Acts::IBinFinder<external_spacepoint_t>> bottomBinFinder, - std::shared_ptr<Acts::IBinFinder<external_spacepoint_t>> topBinFinder) const -{ + std::shared_ptr<Acts::IBinFinder<external_spacepoint_t>> topBinFinder) + const { static_assert( std::is_same< typename std::iterator_traits<spacepoint_iterator_t>::value_type, @@ -58,41 +54,39 @@ Seedfinder<external_spacepoint_t>::initState( auto state = Acts::SeedfinderState<external_spacepoint_t>(); // setup spacepoint grid config SpacePointGridConfig gridConf; - gridConf.bFieldInZ = m_config.bFieldInZ; - gridConf.minPt = m_config.minPt; - gridConf.rMax = m_config.rMax; - gridConf.zMax = m_config.zMax; - gridConf.zMin = m_config.zMin; - gridConf.deltaRMax = m_config.deltaRMax; + gridConf.bFieldInZ = m_config.bFieldInZ; + gridConf.minPt = m_config.minPt; + gridConf.rMax = m_config.rMax; + gridConf.zMax = m_config.zMax; + gridConf.zMin = m_config.zMin; + gridConf.deltaRMax = m_config.deltaRMax; gridConf.cotThetaMax = m_config.cotThetaMax; // create grid with bin sizes according to the configured geometry - std::unique_ptr<SpacePointGrid<external_spacepoint_t>> grid - = SpacePointGridCreator::createGrid<external_spacepoint_t>(gridConf); + std::unique_ptr<SpacePointGrid<external_spacepoint_t>> grid = + SpacePointGridCreator::createGrid<external_spacepoint_t>(gridConf); // get region of interest (or full detector if configured accordingly) float phiMin = m_config.phiMin; float phiMax = m_config.phiMax; - float zMin = m_config.zMin; - float zMax = m_config.zMax; + float zMin = m_config.zMin; + float zMax = m_config.zMax; // sort by radius // add magnitude of beamPos to rMax to avoid excluding measurements // create number of bins equal to number of millimeters rMax // (worst case minR: configured minR + 1mm) size_t numRBins = (m_config.rMax + m_config.beamPos.norm()); - std:: - vector<std:: - vector<std:: - unique_ptr<const InternalSpacePoint<external_spacepoint_t>>>> - rBins(numRBins); + std::vector<std::vector< + std::unique_ptr<const InternalSpacePoint<external_spacepoint_t>>>> + rBins(numRBins); for (spacepoint_iterator_t it = spBegin; it != spEnd; it++) { if (*it == nullptr) { continue; } - const external_spacepoint_t& sp = **it; - float spX = sp.x(); - float spY = sp.y(); - float spZ = sp.z(); + const external_spacepoint_t& sp = **it; + float spX = sp.x(); + float spY = sp.y(); + float spZ = sp.z(); if (spZ > zMax || spZ < zMin) { continue; @@ -103,11 +97,11 @@ Seedfinder<external_spacepoint_t>::initState( } // covariance tool provided by user - Acts::Vector2D cov - = covTool(sp, m_config.zAlign, m_config.rAlign, m_config.sigmaError); + Acts::Vector2D cov = + covTool(sp, m_config.zAlign, m_config.rAlign, m_config.sigmaError); Acts::Vector3D spPosition(spX, spY, spZ); - auto isp - = std::make_unique<const InternalSpacePoint<external_spacepoint_t>>( + auto isp = + std::make_unique<const InternalSpacePoint<external_spacepoint_t>>( sp, spPosition, m_config.beamPos, cov); // calculate r-Bin index and protect against overflow (underflow not // possible) @@ -123,17 +117,15 @@ Seedfinder<external_spacepoint_t>::initState( for (auto& rbin : rBins) { for (auto& isp : rbin) { Acts::Vector2D spLocation(isp->phi(), isp->z()); - std:: - vector<std:: - unique_ptr<const InternalSpacePoint<external_spacepoint_t>>>& - bin - = grid->atPosition(spLocation); + std::vector< + std::unique_ptr<const InternalSpacePoint<external_spacepoint_t>>>& + bin = grid->atPosition(spLocation); bin.push_back(std::move(isp)); } } - state.binnedSP = std::move(grid); + state.binnedSP = std::move(grid); state.bottomBinFinder = bottomBinFinder; - state.topBinFinder = topBinFinder; + state.topBinFinder = topBinFinder; std::array<size_t, 2> numBins = state.binnedSP->numLocalBins(); for (size_t i = 0; i < numBins[0] * numBins[1]; i++) { state.outputVec.push_back({}); @@ -142,22 +134,20 @@ Seedfinder<external_spacepoint_t>::initState( } template <typename external_spacepoint_t> -void -Seedfinder<external_spacepoint_t>::createSeedsForRegion( +void Seedfinder<external_spacepoint_t>::createSeedsForRegion( SeedfinderStateIterator<external_spacepoint_t> it, - Acts::SeedfinderState<external_spacepoint_t>& state) const -{ + Acts::SeedfinderState<external_spacepoint_t>& state) const { for (size_t spIndex = 0; spIndex < it.currentBin->size(); spIndex++) { - const InternalSpacePoint<external_spacepoint_t>* spM - = (*(it.currentBin))[spIndex].get(); + const InternalSpacePoint<external_spacepoint_t>* spM = + (*(it.currentBin))[spIndex].get(); - float rM = spM->radius(); - float zM = spM->z(); + float rM = spM->radius(); + float zM = spM->z(); float covrM = spM->covr(); float covzM = spM->covz(); std::vector<size_t>& bottomBinIndices = it.bottomBinIndices; - std::vector<size_t>& topBinIndices = it.topBinIndices; + std::vector<size_t>& topBinIndices = it.topBinIndices; std::vector<const InternalSpacePoint<external_spacepoint_t>*> compatBottomSP; @@ -165,7 +155,7 @@ Seedfinder<external_spacepoint_t>::createSeedsForRegion( for (auto bottomBinIndex : bottomBinIndices) { auto& bottomBin = it.grid->at(bottomBinIndex); for (auto& spB : bottomBin) { - float rB = spB->radius(); + float rB = spB->radius(); float deltaR = rM - rB; // if r-distance is too big, try next SP in r-sorted bin if (deltaR > m_config.deltaRMax) { @@ -182,8 +172,8 @@ Seedfinder<external_spacepoint_t>::createSeedsForRegion( } // check if duplet origin on z axis within collision region float zOrigin = zM - rM * cotTheta; - if (zOrigin < m_config.collisionRegionMin - || zOrigin > m_config.collisionRegionMax) { + if (zOrigin < m_config.collisionRegionMin || + zOrigin > m_config.collisionRegionMax) { continue; } compatBottomSP.push_back(spB.get()); @@ -199,7 +189,7 @@ Seedfinder<external_spacepoint_t>::createSeedsForRegion( for (auto topBinIndex : topBinIndices) { auto& topBin = it.grid->at(topBinIndex); for (auto& spT : topBin) { - float rT = spT->radius(); + float rT = spT->radius(); float deltaR = rT - rM; // this condition is the opposite of the condition for bottom SP if (deltaR < m_config.deltaRMin) { @@ -214,8 +204,8 @@ Seedfinder<external_spacepoint_t>::createSeedsForRegion( continue; } float zOrigin = zM - rM * cotTheta; - if (zOrigin < m_config.collisionRegionMin - || zOrigin > m_config.collisionRegionMax) { + if (zOrigin < m_config.collisionRegionMin || + zOrigin > m_config.collisionRegionMax) { continue; } compatTopSP.push_back(spT.get()); @@ -234,27 +224,23 @@ Seedfinder<external_spacepoint_t>::createSeedsForRegion( // create vectors here to avoid reallocation in each loop std::vector<const InternalSpacePoint<external_spacepoint_t>*> topSpVec; - std::vector<float> curvatures; + std::vector<float> curvatures; std::vector<float> impactParameters; - std:: - vector<std:: - pair<float, - std:: - unique_ptr<const InternalSeed<external_spacepoint_t>>>> - seedsPerSpM; - size_t numBotSP = compatBottomSP.size(); - size_t numTopSP = compatTopSP.size(); + std::vector<std::pair< + float, std::unique_ptr<const InternalSeed<external_spacepoint_t>>>> + seedsPerSpM; + size_t numBotSP = compatBottomSP.size(); + size_t numTopSP = compatTopSP.size(); for (size_t b = 0; b < numBotSP; b++) { - - auto lb = linCircleBottom[b]; - float Zob = lb.Zo; + auto lb = linCircleBottom[b]; + float Zob = lb.Zo; float cotThetaB = lb.cotTheta; - float Vb = lb.V; - float Ub = lb.U; - float ErB = lb.Er; - float iDeltaRB = lb.iDeltaR; + float Vb = lb.V; + float Ub = lb.U; + float ErB = lb.Er; + float iDeltaRB = lb.iDeltaR; // 1+(cot^2(theta)) = 1/sin^2(theta) float iSinTheta2 = (1. + cotThetaB * cotThetaB); @@ -269,24 +255,23 @@ Seedfinder<external_spacepoint_t>::createSeedsForRegion( // eta=infinity: ~8.5% float scatteringInRegion2 = m_config.maxScatteringAngle2 * iSinTheta2; // multiply the squared sigma onto the squared scattering - scatteringInRegion2 - *= m_config.sigmaScattering * m_config.sigmaScattering; + scatteringInRegion2 *= + m_config.sigmaScattering * m_config.sigmaScattering; // clear all vectors used in each inner for loop topSpVec.clear(); curvatures.clear(); impactParameters.clear(); for (size_t t = 0; t < numTopSP; t++) { - auto lt = linCircleTop[t]; // add errors of spB-spM and spM-spT pairs and add the correlation term // for errors on spM - float error2 = lt.Er + ErB - + 2 * (cotThetaB * lt.cotTheta * covrM + covzM) * iDeltaRB - * lt.iDeltaR; + float error2 = lt.Er + ErB + + 2 * (cotThetaB * lt.cotTheta * covrM + covzM) * + iDeltaRB * lt.iDeltaR; - float deltaCotTheta = cotThetaB - lt.cotTheta; + float deltaCotTheta = cotThetaB - lt.cotTheta; float deltaCotTheta2 = deltaCotTheta * deltaCotTheta; float error; float dCotThetaMinusError2; @@ -296,8 +281,8 @@ Seedfinder<external_spacepoint_t>::createSeedsForRegion( deltaCotTheta = std::abs(deltaCotTheta); // if deltaTheta larger than the scattering for the lower pT cut, skip error = std::sqrt(error2); - dCotThetaMinusError2 - = deltaCotTheta2 + error2 - 2 * deltaCotTheta * error; + dCotThetaMinusError2 = + deltaCotTheta2 + error2 - 2 * deltaCotTheta * error; // avoid taking root of scatteringInRegion // if left side of ">" is positive, both sides of unequality can be // squared @@ -315,9 +300,9 @@ Seedfinder<external_spacepoint_t>::createSeedsForRegion( } // A and B are evaluated as a function of the circumference parameters // x_0 and y_0 - float A = (lt.V - Vb) / dU; + float A = (lt.V - Vb) / dU; float S2 = 1. + A * A; - float B = Vb - A * Ub; + float B = Vb - A * Ub; float B2 = B * B; // sqrt(S2)/B = 2 * helixradius // calculated radius must not be smaller than minimum radius @@ -333,9 +318,9 @@ Seedfinder<external_spacepoint_t>::createSeedsForRegion( // from rad to deltaCotTheta float p2scatter = pT2scatter * iSinTheta2; // if deltaTheta larger than allowed scattering for calculated pT, skip - if (deltaCotTheta2 - error2 > 0 - && dCotThetaMinusError2 > p2scatter * m_config.sigmaScattering - * m_config.sigmaScattering) { + if (deltaCotTheta2 - error2 > 0 && + dCotThetaMinusError2 > p2scatter * m_config.sigmaScattering * + m_config.sigmaScattering) { continue; } // A and B allow calculation of impact params in U/V plane with linear @@ -352,19 +337,12 @@ Seedfinder<external_spacepoint_t>::createSeedsForRegion( } } if (!topSpVec.empty()) { - std:: - vector<std:: - pair<float, - std:: - unique_ptr<const InternalSeed<external_spacepoint_t>>>> - sameTrackSeeds; - sameTrackSeeds = std::move( - m_config.seedFilter->filterSeeds_2SpFixed(*compatBottomSP[b], - *spM, - topSpVec, - curvatures, - impactParameters, - Zob)); + std::vector<std::pair< + float, std::unique_ptr<const InternalSeed<external_spacepoint_t>>>> + sameTrackSeeds; + sameTrackSeeds = std::move(m_config.seedFilter->filterSeeds_2SpFixed( + *compatBottomSP[b], *spM, topSpVec, curvatures, impactParameters, + Zob)); seedsPerSpM.insert(seedsPerSpM.end(), std::make_move_iterator(sameTrackSeeds.begin()), std::make_move_iterator(sameTrackSeeds.end())); @@ -376,19 +354,16 @@ Seedfinder<external_spacepoint_t>::createSeedsForRegion( } template <typename external_spacepoint_t> -void -Seedfinder<external_spacepoint_t>::transformCoordinates( +void Seedfinder<external_spacepoint_t>::transformCoordinates( std::vector<const InternalSpacePoint<external_spacepoint_t>*>& vec, - const InternalSpacePoint<external_spacepoint_t>& spM, - bool bottom, - std::vector<LinCircle>& linCircleVec) const -{ - float xM = spM.x(); - float yM = spM.y(); - float zM = spM.z(); - float rM = spM.radius(); - float covzM = spM.covz(); - float covrM = spM.covr(); + const InternalSpacePoint<external_spacepoint_t>& spM, bool bottom, + std::vector<LinCircle>& linCircleVec) const { + float xM = spM.x(); + float yM = spM.y(); + float zM = spM.z(); + float rM = spM.radius(); + float covzM = spM.covz(); + float covrM = spM.covr(); float cosPhiM = xM / rM; float sinPhiM = yM / rM; for (auto sp : vec) { @@ -403,7 +378,7 @@ Seedfinder<external_spacepoint_t>::transformCoordinates( float y = deltaY * cosPhiM - deltaX * sinPhiM; // 1/(length of M -> SP) float iDeltaR2 = 1. / (deltaX * deltaX + deltaY * deltaY); - float iDeltaR = std::sqrt(iDeltaR2); + float iDeltaR = std::sqrt(iDeltaR2); // int bottomFactor = 1 * (int(!bottom)) - 1 * (int(bottom)); // cot_theta = (deltaZ/deltaR) @@ -412,7 +387,7 @@ Seedfinder<external_spacepoint_t>::transformCoordinates( LinCircle l; l.cotTheta = cot_theta; // location on z-axis of this SP-duplet - l.Zo = zM - rM * cot_theta; + l.Zo = zM - rM * cot_theta; l.iDeltaR = iDeltaR; // transformation of circle equation (x,y) into linear equation (u,v) // x^2 + y^2 - 2x_0*x - 2y_0*y = 0 @@ -423,10 +398,10 @@ Seedfinder<external_spacepoint_t>::transformCoordinates( l.U = x * iDeltaR2; l.V = y * iDeltaR2; // error term for sp-pair without correlation of middle space point - l.Er = ((covzM + sp->covz()) - + (cot_theta * cot_theta) * (covrM + sp->covr())) - * iDeltaR2; + l.Er = ((covzM + sp->covz()) + + (cot_theta * cot_theta) * (covrM + sp->covr())) * + iDeltaR2; linCircleVec.push_back(l); } } -} // Acts namespace +} // namespace Acts diff --git a/Core/include/Acts/Seeding/SeedfinderConfig.hpp b/Core/include/Acts/Seeding/SeedfinderConfig.hpp index ade50baa00b3ccf23feceb9c9a41818ace4a0830..b6be3db9f7e6f3896fc80c48e60db20b90030d60 100644 --- a/Core/include/Acts/Seeding/SeedfinderConfig.hpp +++ b/Core/include/Acts/Seeding/SeedfinderConfig.hpp @@ -16,9 +16,7 @@ template <typename T> class SeedFilter; template <typename SpacePoint> -struct SeedfinderConfig -{ - +struct SeedfinderConfig { std::shared_ptr<Acts::SeedFilter<SpacePoint>> seedFilter; // Algorithm settings @@ -60,8 +58,8 @@ struct SeedfinderConfig // limiting location of collision region in z float collisionRegionMin = -150; float collisionRegionMax = +150; - float phiMin = -M_PI; - float phiMax = M_PI; + float phiMin = -M_PI; + float phiMax = M_PI; // limiting location of measurements float zMin = -2800; float zMax = 2800; @@ -95,10 +93,10 @@ struct SeedfinderConfig float sigmaError = 5; // derived values, set on Seedfinder construction - float highland = 0; + float highland = 0; float maxScatteringAngle2 = 0; - float pTPerHelixRadius = 0; - float minHelixDiameter2 = 0; - float pT2perRadius = 0; + float pTPerHelixRadius = 0; + float minHelixDiameter2 = 0; + float pT2perRadius = 0; }; } // namespace Acts diff --git a/Core/include/Acts/Seeding/SeedfinderState.hpp b/Core/include/Acts/Seeding/SeedfinderState.hpp index 009cd10f740fe172d45720a8f2a3fa6b364cea8a..71e5621d246e0f8486eabbf663ef07f70e024e99 100644 --- a/Core/include/Acts/Seeding/SeedfinderState.hpp +++ b/Core/include/Acts/Seeding/SeedfinderState.hpp @@ -21,11 +21,9 @@ namespace Acts { template <typename SpacePoint> -class SeedfinderStateIterator -{ -public: - SeedfinderStateIterator& operator++() - { +class SeedfinderStateIterator { + public: + SeedfinderStateIterator& operator++() { if (zIndex < phiZbins[1]) { zIndex++; @@ -35,76 +33,70 @@ public: } // set current & neighbor bins only if bin indices valid if (phiIndex <= phiZbins[0] && zIndex <= phiZbins[1]) { - currentBin = &(grid->atLocalBins({phiIndex, zIndex})); + currentBin = &(grid->atLocalBins({phiIndex, zIndex})); bottomBinIndices = bottomBinFinder->findBins(phiIndex, zIndex, grid); - topBinIndices = topBinFinder->findBins(phiIndex, zIndex, grid); + topBinIndices = topBinFinder->findBins(phiIndex, zIndex, grid); outputIndex++; return *this; } phiIndex = phiZbins[0]; - zIndex = phiZbins[1] + 1; + zIndex = phiZbins[1] + 1; return *this; } - bool - operator==(const SeedfinderStateIterator& otherState) - { + bool operator==(const SeedfinderStateIterator& otherState) { return (zIndex == otherState.zIndex && phiIndex == otherState.phiIndex); } SeedfinderStateIterator(const SpacePointGrid<SpacePoint>* spgrid, - IBinFinder<SpacePoint>* botBinFinder, - IBinFinder<SpacePoint>* tBinFinder) - : currentBin(&(spgrid->atLocalBins({1, 1}))) - { - grid = spgrid; - bottomBinFinder = botBinFinder; - topBinFinder = tBinFinder; - phiZbins = grid->numLocalBins(); - phiIndex = 1; - zIndex = 1; - outputIndex = 0; + IBinFinder<SpacePoint>* botBinFinder, + IBinFinder<SpacePoint>* tBinFinder) + : currentBin(&(spgrid->atLocalBins({1, 1}))) { + grid = spgrid; + bottomBinFinder = botBinFinder; + topBinFinder = tBinFinder; + phiZbins = grid->numLocalBins(); + phiIndex = 1; + zIndex = 1; + outputIndex = 0; bottomBinIndices = bottomBinFinder->findBins(phiIndex, zIndex, grid); - topBinIndices = topBinFinder->findBins(phiIndex, zIndex, grid); + topBinIndices = topBinFinder->findBins(phiIndex, zIndex, grid); } SeedfinderStateIterator(const SpacePointGrid<SpacePoint>* spgrid, - IBinFinder<SpacePoint>* botBinFinder, - IBinFinder<SpacePoint>* tBinFinder, - size_t phiInd, - size_t zInd) - : currentBin(&(spgrid->atLocalBins({phiInd, zInd}))) - { + IBinFinder<SpacePoint>* botBinFinder, + IBinFinder<SpacePoint>* tBinFinder, size_t phiInd, + size_t zInd) + : currentBin(&(spgrid->atLocalBins({phiInd, zInd}))) { bottomBinFinder = botBinFinder; - topBinFinder = tBinFinder; - grid = spgrid; - phiIndex = phiInd; - zIndex = zInd; - phiZbins = grid->numLocalBins(); - outputIndex = (phiInd - 1) * phiZbins[1] + zInd - 1; + topBinFinder = tBinFinder; + grid = spgrid; + phiIndex = phiInd; + zIndex = zInd; + phiZbins = grid->numLocalBins(); + outputIndex = (phiInd - 1) * phiZbins[1] + zInd - 1; if (phiIndex <= phiZbins[0] && zIndex <= phiZbins[1]) { bottomBinIndices = bottomBinFinder->findBins(phiIndex, zIndex, grid); - topBinIndices = topBinFinder->findBins(phiIndex, zIndex, grid); + topBinIndices = topBinFinder->findBins(phiIndex, zIndex, grid); } } // middle spacepoint bin const std::vector<std::unique_ptr<const InternalSpacePoint<SpacePoint>>>* - currentBin; - std::vector<size_t> bottomBinIndices; - std::vector<size_t> topBinIndices; + currentBin; + std::vector<size_t> bottomBinIndices; + std::vector<size_t> topBinIndices; const SpacePointGrid<SpacePoint>* grid; - size_t phiIndex = 1; - size_t zIndex = 1; - size_t outputIndex = 0; + size_t phiIndex = 1; + size_t zIndex = 1; + size_t outputIndex = 0; std::array<long unsigned int, 2ul> phiZbins; IBinFinder<SpacePoint>* bottomBinFinder; IBinFinder<SpacePoint>* topBinFinder; }; template <typename SpacePoint> -struct SeedfinderState -{ +struct SeedfinderState { // grid with ownership of all InternalSpacePoint std::unique_ptr<Acts::SpacePointGrid<SpacePoint>> binnedSP; @@ -116,22 +108,16 @@ struct SeedfinderState // container with seeds created so far std::vector<std::vector<std::unique_ptr<Seed<SpacePoint>>>> outputVec; - SeedfinderStateIterator<SpacePoint> - begin() - { + SeedfinderStateIterator<SpacePoint> begin() { return SeedfinderStateIterator<SpacePoint>( binnedSP.get(), bottomBinFinder.get(), topBinFinder.get()); } - SeedfinderStateIterator<SpacePoint> - end() - { + SeedfinderStateIterator<SpacePoint> end() { auto phiZbins = binnedSP->numLocalBins(); - return SeedfinderStateIterator<SpacePoint>(binnedSP.get(), - bottomBinFinder.get(), - topBinFinder.get(), - phiZbins[0], - phiZbins[1] + 1); + return SeedfinderStateIterator<SpacePoint>( + binnedSP.get(), bottomBinFinder.get(), topBinFinder.get(), phiZbins[0], + phiZbins[1] + 1); } }; -} +} // namespace Acts diff --git a/Core/include/Acts/Seeding/SpacePointGrid.hpp b/Core/include/Acts/Seeding/SpacePointGrid.hpp index bd538175659cef7e92e4cfdc28ecb77521a312bb..c824e92c62f2d8edc811a4b9e86b1bd7442c463c 100644 --- a/Core/include/Acts/Seeding/SpacePointGrid.hpp +++ b/Core/include/Acts/Seeding/SpacePointGrid.hpp @@ -15,8 +15,7 @@ namespace Acts { -struct SpacePointGridConfig -{ +struct SpacePointGridConfig { // magnetic field in kTesla float bFieldInZ; // minimum pT to be found by seedfinder in MeV @@ -37,19 +36,18 @@ struct SpacePointGridConfig float cotThetaMax; }; template <typename SpacePoint> -using SpacePointGrid = detail:: - Grid<std::vector<std::unique_ptr<const InternalSpacePoint<SpacePoint>>>, - detail::Axis<detail::AxisType::Equidistant, - detail::AxisBoundaryType::Closed>, - detail::Axis<detail::AxisType::Equidistant, - detail::AxisBoundaryType::Bound>>; +using SpacePointGrid = detail::Grid< + std::vector<std::unique_ptr<const InternalSpacePoint<SpacePoint>>>, + detail::Axis<detail::AxisType::Equidistant, + detail::AxisBoundaryType::Closed>, + detail::Axis<detail::AxisType::Equidistant, + detail::AxisBoundaryType::Bound>>; -class SpacePointGridCreator -{ -public: +class SpacePointGridCreator { + public: template <typename SpacePoint> - static std::unique_ptr<SpacePointGrid<SpacePoint>> - createGrid(const Acts::SpacePointGridConfig& config); + static std::unique_ptr<SpacePointGrid<SpacePoint>> createGrid( + const Acts::SpacePointGridConfig& config); }; -} +} // namespace Acts #include "Acts/Seeding/SpacePointGrid.ipp" diff --git a/Core/include/Acts/Seeding/SpacePointGrid.ipp b/Core/include/Acts/Seeding/SpacePointGrid.ipp index 90bd1767fb799885259091ae4a139289c47ba8ac..6f4c3637d039dc7674997198246cb907a82492a9 100644 --- a/Core/include/Acts/Seeding/SpacePointGrid.ipp +++ b/Core/include/Acts/Seeding/SpacePointGrid.ipp @@ -13,23 +13,22 @@ template <typename SpacePoint> std::unique_ptr<Acts::SpacePointGrid<SpacePoint>> Acts::SpacePointGridCreator::createGrid( - const Acts::SpacePointGridConfig& config) -{ + const Acts::SpacePointGridConfig& config) { // calculate circle intersections of helix and max detector radius float minHelixRadius = config.minPt / (300. * config.bFieldInZ); // in mm - float maxR2 = config.rMax * config.rMax; - float xOuter = maxR2 / (2 * minHelixRadius); - float yOuter = std::sqrt(maxR2 - xOuter * xOuter); - float outerAngle = std::atan(xOuter / yOuter); + float maxR2 = config.rMax * config.rMax; + float xOuter = maxR2 / (2 * minHelixRadius); + float yOuter = std::sqrt(maxR2 - xOuter * xOuter); + float outerAngle = std::atan(xOuter / yOuter); // intersection of helix and max detector radius minus maximum R distance from // middle SP to top SP float innerAngle = 0; if (config.rMax > config.deltaRMax) { - float innerCircleR2 - = (config.rMax - config.deltaRMax) * (config.rMax - config.deltaRMax); + float innerCircleR2 = + (config.rMax - config.deltaRMax) * (config.rMax - config.deltaRMax); float xInner = innerCircleR2 / (2 * minHelixRadius); float yInner = std::sqrt(innerCircleR2 - xInner * xInner); - innerAngle = std::atan(xInner / yInner); + innerAngle = std::atan(xInner / yInner); } // FIXME: phibin size must include max impact parameters @@ -45,7 +44,7 @@ Acts::SpacePointGridCreator::createGrid( // seeds // FIXME: zBinSize must include scattering float zBinSize = config.cotThetaMax * config.deltaRMax; - int zBins = std::floor((config.zMax - config.zMin) / zBinSize); + int zBins = std::floor((config.zMax - config.zMin) / zBinSize); detail::Axis<detail::AxisType::Equidistant, detail::AxisBoundaryType::Bound> zAxis(config.zMin, config.zMax, zBins); return std::make_unique<Acts::SpacePointGrid<SpacePoint>>( diff --git a/Core/include/Acts/Surfaces/BoundaryCheck.hpp b/Core/include/Acts/Surfaces/BoundaryCheck.hpp index 202c5efde72be1f639c17aaf472b7afeebc791d4..3b53203bb85acbce678eb6b4f5525b4b73b78293 100644 --- a/Core/include/Acts/Surfaces/BoundaryCheck.hpp +++ b/Core/include/Acts/Surfaces/BoundaryCheck.hpp @@ -36,9 +36,8 @@ namespace Acts { /// With a defined covariance matrix, the closest point and the distance are /// not defined along the usual Euclidean metric, but by the Mahalanobis /// distance induced by the the covariance. -class BoundaryCheck -{ -public: +class BoundaryCheck { + public: /// Construct either hard cut in both dimensions or no cut at all. BoundaryCheck(bool check); @@ -48,9 +47,7 @@ public: /// @param checkLocal1 Boolean directive to check coordinate 1 /// @param tolerance0 Tolerance along coordinate 0 /// @param tolerance1 Tolerance along coordinate 1 - BoundaryCheck(bool checkLocal0, - bool checkLocal1, - double tolerance0 = 0, + BoundaryCheck(bool checkLocal0, bool checkLocal1, double tolerance0 = 0, double tolerance1 = 0); /// Construct a chi2-based check. @@ -73,8 +70,7 @@ public: /// The check takes into account whether tolerances or covariances are defined /// for the boundary check. template <typename Vector2DContainer> - bool - isInside(const Vector2D& point, const Vector2DContainer& vertices) const; + bool isInside(const Vector2D& point, const Vector2DContainer& vertices) const; /// Check if the point is inside a box aligned with the local axes. /// @@ -86,10 +82,8 @@ public: /// /// The check takes into account whether tolerances or covariances are defined /// for the boundary check. - bool - isInside(const Vector2D& point, - const Vector2D& lowerLeft, - const Vector2D& upperRight) const; + bool isInside(const Vector2D& point, const Vector2D& lowerLeft, + const Vector2D& upperRight) const; /// Calculate the signed, weighted, closest distance to a polygonal boundary. /// @@ -103,8 +97,8 @@ public: /// If a covariance is defined, the distance is the corresponding Mahalanobis /// distance. Otherwise, it is the Eucleadian distance. template <typename Vector2DContainer> - double - distance(const Vector2D& point, const Vector2DContainer& vertices) const; + double distance(const Vector2D& point, + const Vector2DContainer& vertices) const; /// Calculate the signed, weighted, closest distance to an aligned box. /// @@ -117,12 +111,10 @@ public: /// /// If a covariance is defined, the distance is the corresponding Mahalanobis /// distance. Otherwise, it is the Eucleadian distance. - double - distance(const Vector2D& point, - const Vector2D& lowerLeft, - const Vector2D& upperRight) const; + double distance(const Vector2D& point, const Vector2D& lowerLeft, + const Vector2D& upperRight) const; -private: + private: enum class Type { eNone, ///< disable boundary check eAbsolute, ///< absolute cut @@ -133,47 +125,39 @@ private: /// @param jacobian Tranform Jacobian for the covariance /// @warning This currently only transforms the covariance and does not work /// for the tolerance based check. - BoundaryCheck - transformed(const ActsMatrixD<2, 2>& jacobian) const; + BoundaryCheck transformed(const ActsMatrixD<2, 2>& jacobian) const; /// Check if the point is inside the polygon w/o any tolerances. template <typename Vector2DContainer> - bool - isInsidePolygon(const Vector2D& point, - const Vector2DContainer& vertices) const; + bool isInsidePolygon(const Vector2D& point, + const Vector2DContainer& vertices) const; /// Check if the point is inside the aligned box - bool - isInsideRectangle(const Vector2D& point, - const Vector2D& lowerLeft, - const Vector2D& upperRight) const; + bool isInsideRectangle(const Vector2D& point, const Vector2D& lowerLeft, + const Vector2D& upperRight) const; /// Check if the distance vector is within the absolute or relative limits. - bool - isTolerated(const Vector2D& delta) const; + bool isTolerated(const Vector2D& delta) const; /// Compute vector norm based on the covariance. - double - squaredNorm(const Vector2D& x) const; + double squaredNorm(const Vector2D& x) const; /// Calculate the closest point on the polygon. template <typename Vector2DContainer> - Vector2D - computeClosestPointOnPolygon(const Vector2D& point, - const Vector2DContainer& vertices) const; + Vector2D computeClosestPointOnPolygon( + const Vector2D& point, const Vector2DContainer& vertices) const; /// Calculate the closest point on the box - Vector2D - computeEuclideanClosestPointOnRectangle(const Vector2D& point, - const Vector2D& lowerLeft, - const Vector2D& upperRight) const; + Vector2D computeEuclideanClosestPointOnRectangle( + const Vector2D& point, const Vector2D& lowerLeft, + const Vector2D& upperRight) const; /// metric weight matrix: identity for absolute mode or inverse covariance ActsSymMatrixD<2> m_weight; /// dual use: absolute tolerances or relative chi2/ sigma cut. Vector2D m_tolerance; - Type m_type; + Type m_type; // To acces the m_type friend class CylinderBounds; @@ -188,52 +172,40 @@ private: } // namespace Acts inline Acts::BoundaryCheck::BoundaryCheck(bool check) - : m_weight(ActsSymMatrixD<2>::Identity()) - , m_tolerance(0, 0) - , m_type(check ? Type::eAbsolute : Type::eNone) -{ -} + : m_weight(ActsSymMatrixD<2>::Identity()), + m_tolerance(0, 0), + m_type(check ? Type::eAbsolute : Type::eNone) {} -inline Acts::BoundaryCheck::BoundaryCheck(bool checkLocal0, - bool checkLocal1, - double tolerance0, - double tolerance1) - : m_weight(ActsSymMatrixD<2>::Identity()) - , m_tolerance(checkLocal0 ? tolerance0 : DBL_MAX, - checkLocal1 ? tolerance1 : DBL_MAX) - , m_type(Type::eAbsolute) -{ -} +inline Acts::BoundaryCheck::BoundaryCheck(bool checkLocal0, bool checkLocal1, + double tolerance0, double tolerance1) + : m_weight(ActsSymMatrixD<2>::Identity()), + m_tolerance(checkLocal0 ? tolerance0 : DBL_MAX, + checkLocal1 ? tolerance1 : DBL_MAX), + m_type(Type::eAbsolute) {} inline Acts::BoundaryCheck::BoundaryCheck( - const ActsSymMatrixD<2>& localCovariance, - double sigmaMax) - : m_weight(localCovariance.inverse()) - , m_tolerance(sigmaMax, 0) - , m_type(Type::eChi2) -{ -} + const ActsSymMatrixD<2>& localCovariance, double sigmaMax) + : m_weight(localCovariance.inverse()), + m_tolerance(sigmaMax, 0), + m_type(Type::eChi2) {} -inline Acts::BoundaryCheck -Acts::BoundaryCheck::transformed(const ActsMatrixD<2, 2>& jacobian) const -{ +inline Acts::BoundaryCheck Acts::BoundaryCheck::transformed( + const ActsMatrixD<2, 2>& jacobian) const { BoundaryCheck bc = *this; if (m_type == Type::eAbsolute) { // project tolerances to the new system. depending on the jacobian we need // to check both tolerances, even when the initial check does not. bc.m_tolerance = (jacobian * m_tolerance).cwiseAbs(); } else /* Type::eChi2 */ { - bc.m_weight - = (jacobian * m_weight.inverse() * jacobian.transpose()).inverse(); + bc.m_weight = + (jacobian * m_weight.inverse() * jacobian.transpose()).inverse(); } return bc; } template <typename Vector2DContainer> -inline bool -Acts::BoundaryCheck::isInside(const Vector2D& point, - const Vector2DContainer& vertices) const -{ +inline bool Acts::BoundaryCheck::isInside( + const Vector2D& point, const Vector2DContainer& vertices) const { // a compatible point must be either completely in the polygon or on the // outside but within the defined tolerance relative to the closest point if (isInsidePolygon(point, vertices)) { @@ -245,10 +217,8 @@ Acts::BoundaryCheck::isInside(const Vector2D& point, } template <typename Vector2DContainer> -inline bool -Acts::BoundaryCheck::isInsidePolygon(const Vector2D& point, - const Vector2DContainer& vertices) const -{ +inline bool Acts::BoundaryCheck::isInsidePolygon( + const Vector2D& point, const Vector2DContainer& vertices) const { // when we move along the edges of a convex polygon, a point on the inside of // the polygon will always appear on the same side of each edge. // a point on the outside will switch sides at least once. @@ -258,11 +228,11 @@ Acts::BoundaryCheck::isInsidePolygon(const Vector2D& point, // between the line normal vector and the vector from `ll0` to `p`. auto lineSide = [&](auto&& ll0, auto&& ll1) { auto normal = ll1 - ll0; - auto delta = point - ll0; + auto delta = point - ll0; return std::signbit((normal[0] * delta[1]) - (normal[1] * delta[0])); }; - auto iv = std::begin(vertices); + auto iv = std::begin(vertices); Vector2D l0 = *iv; Vector2D l1 = *(++iv); // use vertex0 to vertex1 to define reference sign and compare w/ all edges @@ -282,30 +252,25 @@ Acts::BoundaryCheck::isInsidePolygon(const Vector2D& point, return true; } -inline bool -Acts::BoundaryCheck::isInsideRectangle(const Vector2D& point, - const Vector2D& lowerLeft, - const Vector2D& upperRight) const -{ - return (lowerLeft[0] <= point[0]) && (point[0] < upperRight[0]) - && (lowerLeft[1] <= point[1]) && (point[1] < upperRight[1]); +inline bool Acts::BoundaryCheck::isInsideRectangle( + const Vector2D& point, const Vector2D& lowerLeft, + const Vector2D& upperRight) const { + return (lowerLeft[0] <= point[0]) && (point[0] < upperRight[0]) && + (lowerLeft[1] <= point[1]) && (point[1] < upperRight[1]); } -inline bool -Acts::BoundaryCheck::isInside(const Vector2D& point, - const Vector2D& lowerLeft, - const Vector2D& upperRight) const -{ +inline bool Acts::BoundaryCheck::isInside(const Vector2D& point, + const Vector2D& lowerLeft, + const Vector2D& upperRight) const { if (isInsideRectangle(point, lowerLeft, upperRight)) { return true; } else { - Vector2D closestPoint; if (m_type == Type::eNone || m_type == Type::eAbsolute) { // absolute, can calculate directly - closestPoint = computeEuclideanClosestPointOnRectangle( - point, lowerLeft, upperRight); + closestPoint = + computeEuclideanClosestPointOnRectangle(point, lowerLeft, upperRight); } else /* Type::eChi2 */ { // need to calculate by projection and squarednorm @@ -321,23 +286,18 @@ Acts::BoundaryCheck::isInside(const Vector2D& point, } template <typename Vector2DContainer> -inline double -Acts::BoundaryCheck::distance(const Acts::Vector2D& point, - const Vector2DContainer& vertices) const -{ +inline double Acts::BoundaryCheck::distance( + const Acts::Vector2D& point, const Vector2DContainer& vertices) const { // TODO 2017-04-06 msmk: this should be calculable directly double d = squaredNorm(point - computeClosestPointOnPolygon(point, vertices)); - d = std::sqrt(d); + d = std::sqrt(d); return isInsidePolygon(point, vertices) ? -d : d; } -inline double -Acts::BoundaryCheck::distance(const Acts::Vector2D& point, - const Vector2D& lowerLeft, - const Vector2D& upperRight) const -{ +inline double Acts::BoundaryCheck::distance(const Acts::Vector2D& point, + const Vector2D& lowerLeft, + const Vector2D& upperRight) const { if (m_type == Type::eNone || m_type == Type::eAbsolute) { - // compute closest point on box double d = (point - computeEuclideanClosestPointOnRectangle( point, lowerLeft, upperRight)) @@ -353,32 +313,25 @@ Acts::BoundaryCheck::distance(const Acts::Vector2D& point, } } -inline bool -Acts::BoundaryCheck::isTolerated(const Vector2D& delta) const -{ +inline bool Acts::BoundaryCheck::isTolerated(const Vector2D& delta) const { if (m_type == Type::eNone) { return true; } else if (m_type == Type::eAbsolute) { - return (std::abs(delta[0]) <= m_tolerance[0]) - && (std::abs(delta[1]) <= m_tolerance[1]); + return (std::abs(delta[0]) <= m_tolerance[0]) && + (std::abs(delta[1]) <= m_tolerance[1]); } else /* Type::eChi2 */ { // Mahalanobis distances mean is 2 in 2-dim. cut is 1-d sigma. return (squaredNorm(delta) < (2 * m_tolerance[0])); } } -inline double -Acts::BoundaryCheck::squaredNorm(const Vector2D& x) const -{ +inline double Acts::BoundaryCheck::squaredNorm(const Vector2D& x) const { return (x.transpose() * m_weight * x).value(); } template <typename Vector2DContainer> -inline Acts::Vector2D -Acts::BoundaryCheck::computeClosestPointOnPolygon( - const Acts::Vector2D& point, - const Vector2DContainer& vertices) const -{ +inline Acts::Vector2D Acts::BoundaryCheck::computeClosestPointOnPolygon( + const Acts::Vector2D& point, const Vector2DContainer& vertices) const { // calculate the closest position on the segment between `ll0` and `ll1` to // the point as measured by the metric induced by the weight matrix auto closestOnSegment = [&](auto&& ll0, auto&& ll1) { @@ -386,20 +339,20 @@ Acts::BoundaryCheck::computeClosestPointOnPolygon( auto n = ll1 - ll0; auto f = (n.transpose() * m_weight * n).value(); auto u = std::isnormal(f) - ? -((ll0 - point).transpose() * m_weight * n).value() / f - : 0.5; // ll0 and ll1 are so close it doesn't matter + ? -((ll0 - point).transpose() * m_weight * n).value() / f + : 0.5; // ll0 and ll1 are so close it doesn't matter // u must be in [0, 1] to still be on the polygon segment return ll0 + std::min(std::max(u, 0.0), 1.0) * n; }; - auto iv = std::begin(vertices); - Vector2D l0 = *iv; - Vector2D l1 = *(++iv); + auto iv = std::begin(vertices); + Vector2D l0 = *iv; + Vector2D l1 = *(++iv); Vector2D closest = closestOnSegment(l0, l1); // Calculate the closest point on other connecting lines and compare distances for (++iv; iv != std::end(vertices); ++iv) { - l0 = l1; - l1 = *iv; + l0 = l1; + l1 = *iv; Vector2D current = closestOnSegment(l0, l1); if (squaredNorm(current - point) < squaredNorm(closest - point)) { closest = current; @@ -415,11 +368,8 @@ Acts::BoundaryCheck::computeClosestPointOnPolygon( inline Acts::Vector2D Acts::BoundaryCheck::computeEuclideanClosestPointOnRectangle( - const Vector2D& point, - const Vector2D& lowerLeft, - const Vector2D& upperRight) const -{ - + const Vector2D& point, const Vector2D& lowerLeft, + const Vector2D& upperRight) const { /* * * | | @@ -445,19 +395,19 @@ Acts::BoundaryCheck::computeEuclideanClosestPointOnRectangle( // check if inside if (loc0Min <= l0 && l0 < loc0Max && loc1Min <= l1 && l1 < loc1Max) { // INSIDE - double dist = std::abs(loc0Max - l0); + double dist = std::abs(loc0Max - l0); Vector2D cls(loc0Max, l1); double test = std::abs(loc0Min - l0); if (test <= dist) { dist = test; - cls = {loc0Min, l1}; + cls = {loc0Min, l1}; } test = std::abs(loc1Max - l1); if (test <= dist) { dist = test; - cls = {l0, loc1Max}; + cls = {l0, loc1Max}; } test = std::abs(loc1Min - l1); diff --git a/Core/include/Acts/Surfaces/ConeBounds.hpp b/Core/include/Acts/Surfaces/ConeBounds.hpp index f6901cdbbdd955218128a9069dec0a3cf344c533..2754a1e4e8cdbdfe10122c8ff30c54651087c8c2 100644 --- a/Core/include/Acts/Surfaces/ConeBounds.hpp +++ b/Core/include/Acts/Surfaces/ConeBounds.hpp @@ -29,17 +29,16 @@ namespace Acts { /// @image html ConeBounds.gif /// -class ConeBounds : public SurfaceBounds -{ -public: +class ConeBounds : public SurfaceBounds { + public: /// @enum BoundValues for readablility enum BoundValues { - bv_alpha = 0, - bv_minZ = 1, - bv_maxZ = 2, - bv_averagePhi = 3, + bv_alpha = 0, + bv_minZ = 1, + bv_maxZ = 2, + bv_averagePhi = 3, bv_halfPhiSector = 4, - bv_length = 5 + bv_length = 5 }; ConeBounds() = delete; @@ -63,148 +62,112 @@ public: /// @param halfphi is the half opening angle (default is pi) /// @param avphi is the phi value around which the bounds are opened /// (default=0) - ConeBounds(double alpha, - double zmin, - double zmax, - double halfphi = M_PI, - double avphi = 0.); + ConeBounds(double alpha, double zmin, double zmax, double halfphi = M_PI, + double avphi = 0.); ~ConeBounds() override; - ConeBounds* - clone() const final; + ConeBounds* clone() const final; - BoundsType - type() const final; + BoundsType type() const final; - std::vector<TDD_real_t> - valueStore() const final; + std::vector<TDD_real_t> valueStore() const final; /// inside method for local position /// /// @param lpos is the local position to be checked /// @param bcheck is the boundary check directive /// @return is a boolean indicating if the position is inside - bool - inside(const Vector2D& lpos, const BoundaryCheck& bcheck = true) const final; + bool inside(const Vector2D& lpos, + const BoundaryCheck& bcheck = true) const final; /// Minimal distance to boundary ( > 0 if outside and <=0 if inside) /// /// @param lpos is the local position to check for the distance /// @return is a signed distance parameter - double - distanceToBoundary(const Vector2D& lpos) const final; + double distanceToBoundary(const Vector2D& lpos) const final; /// Output Method for std::ostream /// /// @param sl is the ostrea into which the dump is done /// @return is the input obect - std::ostream& - toStream(std::ostream& sl) const final; + std::ostream& toStream(std::ostream& sl) const final; /// Return the radius at a specific z values /// /// @param z is the z value for which r is requested /// @return is the r value associated with z - double - r(double z) const; + double r(double z) const; /// Return the average values for the angles - double - tanAlpha() const; + double tanAlpha() const; /// Return the average values for the angles - double - sinAlpha() const; + double sinAlpha() const; /// Return the average values for the angles - double - cosAlpha() const; + double cosAlpha() const; /// Return the average values for the angles - double - alpha() const; + double alpha() const; /// This method returns the minimum z value in the local /// frame for an unbound symmetric cone, it returns -MAXBOUNDVALUE*/ - double - minZ() const; + double minZ() const; /// This method returns the maximum z value in the local /// frame for an unbound symmetric cone, it returns -MAXBOUNDVALUE*/ - double - maxZ() const; + double maxZ() const; /// This method returns the average phi value /// (i.e. the "middle" phi value for the conical sector we are describing) - double - averagePhi() const; + double averagePhi() const; /// This method returns the half-phi width of the sector /// (so that averagePhi +/- halfPhiSector gives the phi bounds of the cone) - double - halfPhiSector() const; + double halfPhiSector() const; -private: + private: double m_alpha, m_tanAlpha; double m_zMin, m_zMax; double m_avgPhi, m_halfPhi; - Vector2D - shifted(const Vector2D& lpos) const; + Vector2D shifted(const Vector2D& lpos) const; }; -inline double -ConeBounds::r(double z) const -{ +inline double ConeBounds::r(double z) const { return std::abs(z * m_tanAlpha); } -inline double -ConeBounds::tanAlpha() const -{ +inline double ConeBounds::tanAlpha() const { return m_tanAlpha; } -inline double -ConeBounds::sinAlpha() const -{ +inline double ConeBounds::sinAlpha() const { return std::sin(m_alpha); } -inline double -ConeBounds::cosAlpha() const -{ +inline double ConeBounds::cosAlpha() const { return std::cos(m_alpha); } -inline double -ConeBounds::alpha() const -{ +inline double ConeBounds::alpha() const { return m_alpha; } -inline double -ConeBounds::minZ() const -{ +inline double ConeBounds::minZ() const { return m_zMin; } -inline double -ConeBounds::maxZ() const -{ +inline double ConeBounds::maxZ() const { return m_zMax; } -inline double -ConeBounds::averagePhi() const -{ +inline double ConeBounds::averagePhi() const { return m_avgPhi; } -inline double -ConeBounds::halfPhiSector() const -{ +inline double ConeBounds::halfPhiSector() const { return m_halfPhi; } -} \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Surfaces/ConeSurface.hpp b/Core/include/Acts/Surfaces/ConeSurface.hpp index ab88b4b935ac4ff2f92870e7f06487d8b14cf057..8eff497f699a2a47659e9139e0c65ca3d2b1fb7e 100644 --- a/Core/include/Acts/Surfaces/ConeSurface.hpp +++ b/Core/include/Acts/Surfaces/ConeSurface.hpp @@ -32,21 +32,19 @@ namespace Acts { /// Propagations to a cone surface will be returned in /// curvilinear coordinates. -class ConeSurface : public Surface -{ +class ConeSurface : public Surface { friend Surface; ConeSurface() = delete; -protected: + protected: /// Constructor form HepTransform and an opening angle /// /// @param htrans is the transform to place to cone in a 3D frame /// @param alpha is the opening angle of the cone /// @param symmetric indicates if the cones are built to +/1 z - ConeSurface(std::shared_ptr<const Transform3D> htrans, - double alpha, - bool symmetric = false); + ConeSurface(std::shared_ptr<const Transform3D> htrans, double alpha, + bool symmetric = false); /// Constructor form HepTransform and an opening angle /// @@ -55,17 +53,14 @@ protected: /// @param zmin is the z range over which the cone spans /// @param zmax is the z range over which the cone spans /// @param halfPhi is the openen angle for cone ssectors - ConeSurface(std::shared_ptr<const Transform3D> htrans, - double alpha, - double zmin, - double zmax, - double halfPhi = M_PI); + ConeSurface(std::shared_ptr<const Transform3D> htrans, double alpha, + double zmin, double zmax, double halfPhi = M_PI); /// Constructor from HepTransform and ConeBounds /// /// @param htrans is the transform that places the cone in the global frame /// @param cbounds is the boundary class, the bounds must exit - ConeSurface(std::shared_ptr<const Transform3D> htrans, + ConeSurface(std::shared_ptr<const Transform3D> htrans, const std::shared_ptr<const ConeBounds>& cbounds); /// Copy constructor @@ -78,25 +73,23 @@ protected: /// @param gctx The current geometry context object, e.g. alignment /// @param other is the source cone surface /// @param transf is the additional transfrom applied after copying - ConeSurface(const GeometryContext& gctx, - const ConeSurface& other, - const Transform3D& transf); + ConeSurface(const GeometryContext& gctx, const ConeSurface& other, + const Transform3D& transf); -public: + public: /// Destructor - defaulted ~ConeSurface() override = default; /// Assignment operator /// /// @param other is the source surface for the assignment - ConeSurface& - operator=(const ConeSurface& other); + ConeSurface& operator=(const ConeSurface& other); /// Clone method into a concrete type of ConeSurface with shift /// @param gctx The current geometry context object, e.g. alignment /// @param shift applied to the surface - std::shared_ptr<ConeSurface> - clone(const GeometryContext& gctx, const Transform3D& shift) const; + std::shared_ptr<ConeSurface> clone(const GeometryContext& gctx, + const Transform3D& shift) const; /// The binning position method - is overloaded for r-type binning /// @@ -104,12 +97,11 @@ public: /// @param bValue defines the type of binning applied in the global frame /// /// @return The return type is a vector for positioning in the global frame - const Vector3D - binningPosition(const GeometryContext& gctx, BinningValue bValue) const final; + const Vector3D binningPosition(const GeometryContext& gctx, + BinningValue bValue) const final; /// Return the surface type - SurfaceType - type() const override; + SurfaceType type() const override; /// Return the measurement frame - this is needed for alignment, in particular /// for StraightLine and Perigee Surface @@ -120,10 +112,9 @@ public: /// constructed /// @param mom is the momentum used for the measurement frame construction /// @return matrix that indicates the measurement frame - const RotationMatrix3D - referenceFrame(const GeometryContext& gctx, - const Vector3D& pos, - const Vector3D& mom) const final; + const RotationMatrix3D referenceFrame(const GeometryContext& gctx, + const Vector3D& pos, + const Vector3D& mom) const final; /// Return method for surface normal information /// @@ -131,8 +122,8 @@ public: /// @param lp is the local position on the cone for which the normal vector /// is requested /// @return Vector3D normal vector in global frame - const Vector3D - normal(const GeometryContext& gctx, const Vector2D& lp) const final; + const Vector3D normal(const GeometryContext& gctx, + const Vector2D& lp) const final; /// Return method for surface normal information /// @@ -140,8 +131,8 @@ public: /// @param gpos is the global position on the cone for which the normal vector /// is requested /// @return Vector3D normal vector in global frame - const Vector3D - normal(const GeometryContext& gctx, const Vector3D& gpos) const final; + const Vector3D normal(const GeometryContext& gctx, + const Vector3D& gpos) const final; /// Normal vector return without argument using Surface::normal; @@ -151,12 +142,10 @@ public: /// @param gctx The current geometry context object, e.g. alignment /// // @return This returns the local z axis - virtual const Vector3D - rotSymmetryAxis(const GeometryContext& gctx) const; + virtual const Vector3D rotSymmetryAxis(const GeometryContext& gctx) const; /// This method returns the ConeBounds by reference - const ConeBounds& - bounds() const final; + const ConeBounds& bounds() const final; /// Local to global transformation /// @@ -164,11 +153,8 @@ public: /// @param lpos is the local position to be transformed /// @param mom is the global momentum (ignored in this operation) /// @param gpos is the global position shich is filled - void - localToGlobal(const GeometryContext& gctx, - const Vector2D& lpos, - const Vector3D& mom, - Vector3D& gpos) const final; + void localToGlobal(const GeometryContext& gctx, const Vector2D& lpos, + const Vector3D& mom, Vector3D& gpos) const final; /// Global to local transfomration /// @@ -177,11 +163,8 @@ public: /// @param mom is the global momentum (ignored in this operation) /// @param lpos is hte local position to be filled /// @return is a boolean indicating if the transformation succeeded - bool - globalToLocal(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& mom, - Vector2D& lpos) const final; + bool globalToLocal(const GeometryContext& gctx, const Vector3D& gpos, + const Vector3D& mom, Vector2D& lpos) const final; /// @brief Straight line intersection schema - provides closest intersection /// and (signed) path length @@ -226,13 +209,11 @@ public: /// to be unit length. /// /// @return is the Intersection object - Intersection - intersectionEstimate(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& gmom, - NavigationDirection navDir, - const BoundaryCheck& bcheck = false, - CorrFnc correct = nullptr) const final; + Intersection intersectionEstimate(const GeometryContext& gctx, + const Vector3D& gpos, const Vector3D& gmom, + NavigationDirection navDir, + const BoundaryCheck& bcheck = false, + CorrFnc correct = nullptr) const final; /// the pathCorrection for derived classes with thickness /// @@ -240,28 +221,24 @@ public: /// @param gpos is the global potion at the correction point /// @param mom is the momentum at the correction point /// @return is the path correction due to incident angle - double - pathCorrection(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& mom) const final; + double pathCorrection(const GeometryContext& gctx, const Vector3D& gpos, + const Vector3D& mom) const final; /// Return properly formatted class name for screen output - std::string - name() const override; + std::string name() const override; -protected: + protected: std::shared_ptr<const ConeBounds> m_bounds; ///< bounds (shared) -private: + private: /// Clone method implementation /// /// @param gctx The current geometry context object, e.g. alignment /// @param shift applied to the surface - ConeSurface* - clone_impl(const GeometryContext& gctx, - const Transform3D& shift) const override; + ConeSurface* clone_impl(const GeometryContext& gctx, + const Transform3D& shift) const override; }; #include "Acts/Surfaces/detail/ConeSurface.ipp" -} // namespace +} // namespace Acts diff --git a/Core/include/Acts/Surfaces/ConvexPolygonBounds.hpp b/Core/include/Acts/Surfaces/ConvexPolygonBounds.hpp index db77b011c9bbccc305602ddfecc241625c8e5f97..1d81b9bfc402edeb719332c0297762860131d48c 100644 --- a/Core/include/Acts/Surfaces/ConvexPolygonBounds.hpp +++ b/Core/include/Acts/Surfaces/ConvexPolygonBounds.hpp @@ -21,32 +21,28 @@ namespace Acts { * This class serves as a base class for the actual bounds class. * The only deriving type is the templated `ConvexPolygonBounds`. */ -class ConvexPolygonBoundsBase : public PlanarBounds -{ -public: +class ConvexPolygonBoundsBase : public PlanarBounds { + public: /** * Output Method for std::ostream * @param sl is the ostream to be written into */ - std::ostream& - toStream(std::ostream& sl) const final; + std::ostream& toStream(std::ostream& sl) const final; /** * Return vector containing defining parameters * @return the parameters */ - std::vector<TDD_real_t> - valueStore() const final; + std::vector<TDD_real_t> valueStore() const final; -protected: + protected: /** * Return a rectangle bounds instance that encloses a set of vertices. * @param vertices A collection of vertices to enclose. * @return Enclosing rectangle. */ template <typename coll_t> - static RectangleBounds - makeBoundingBox(const coll_t& vertices); + static RectangleBounds makeBoundingBox(const coll_t& vertices); /** * Calculates whether a set of vertices forms a convex polygon. This is @@ -56,8 +52,7 @@ protected: * @return Whether the vertices form a convex polygon. */ template <typename coll_t> - static bool - convex_impl(const coll_t& vertices); + static bool convex_impl(const coll_t& vertices); }; /** @@ -68,8 +63,7 @@ protected: * @tparam N Number of vertices */ template <int N> -class ConvexPolygonBounds : public ConvexPolygonBoundsBase -{ +class ConvexPolygonBounds : public ConvexPolygonBoundsBase { /** * Expose number of vertices given as template parameter. */ @@ -79,7 +73,7 @@ class ConvexPolygonBounds : public ConvexPolygonBoundsBase */ using vertex_array = std::array<Vector2D, num_vertices>; -public: + public: static_assert(N >= 3, "ConvexPolygonBounds needs at least 3 sides."); /** @@ -111,15 +105,13 @@ public: * Return a copy of this bounds object. * @return The cloned instance */ - ConvexPolygonBounds<N>* - clone() const final; + ConvexPolygonBounds<N>* clone() const final; /** * Return the bounds type of this bounds object. * @return The bounds type */ - BoundsType - type() const final; + BoundsType type() const final; /** * Return whether a local 2D point lies inside of the bounds defined by this @@ -128,8 +120,7 @@ public: * @param bcheck The `BoundaryCheck` object handling tolerances. * @return Whether the points is inside */ - bool - inside(const Vector2D& lpos, const BoundaryCheck& bcheck) const final; + bool inside(const Vector2D& lpos, const BoundaryCheck& bcheck) const final; /** * Return the smallest distance to any point on the boundary of this bounds @@ -137,32 +128,28 @@ public: * @param lpos The local position to get the distance to * @return The smallest distance to the boundary. */ - double - distanceToBoundary(const Vector2D& lpos) const final; + double distanceToBoundary(const Vector2D& lpos) const final; /** * Returns a vector containing the vertices making up the bounds. * @return Vector of vertices */ - std::vector<Vector2D> - vertices() const final; + std::vector<Vector2D> vertices() const final; /** * Return a rectangle bounds object that encloses this polygon. * @return The rectangular bounds */ - const RectangleBounds& - boundingBox() const final; + const RectangleBounds& boundingBox() const final; /** * Return whether this bounds class is in fact convex * @return Whether the bounds are convex. */ - bool - convex() const; + bool convex() const; -private: - vertex_array m_vertices; + private: + vertex_array m_vertices; RectangleBounds m_boundingBox; }; @@ -176,9 +163,8 @@ constexpr int PolygonDynamic = -1; * points. It can accept any number of points. */ template <> -class ConvexPolygonBounds<PolygonDynamic> : public ConvexPolygonBoundsBase -{ -public: +class ConvexPolygonBounds<PolygonDynamic> : public ConvexPolygonBoundsBase { + public: /** * Default constructor, deleted */ @@ -200,15 +186,13 @@ public: * Return a copy of this bounds object. * @return The cloned instance */ - ConvexPolygonBounds<PolygonDynamic>* - clone() const final; + ConvexPolygonBounds<PolygonDynamic>* clone() const final; /** * Return the bounds type of this bounds object. * @return The bounds type */ - BoundsType - type() const final; + BoundsType type() const final; /** * Return whether a local 2D point lies inside of the bounds defined by this @@ -217,8 +201,7 @@ public: * @param bcheck The `BoundaryCheck` object handling tolerances. * @return Whether the points is inside */ - bool - inside(const Vector2D& lpos, const BoundaryCheck& bcheck) const final; + bool inside(const Vector2D& lpos, const BoundaryCheck& bcheck) const final; /** * Return the smallest distance to any point on the boundary of this bounds @@ -226,35 +209,31 @@ public: * @param lpos The local position to get the distance to * @return The smallest distance to the boundary. */ - double - distanceToBoundary(const Vector2D& lpos) const final; + double distanceToBoundary(const Vector2D& lpos) const final; /** * Returns a vector containing the vertices making up the bounds. * @return Vector of vertices */ - std::vector<Vector2D> - vertices() const final; + std::vector<Vector2D> vertices() const final; /** * Return a rectangle bounds object that encloses this polygon. * @return The rectangular bounds */ - const RectangleBounds& - boundingBox() const final; + const RectangleBounds& boundingBox() const final; /** * Return whether this bounds class is in fact convex * @return Whether the bounds are convex. */ - bool - convex() const; + bool convex() const; -private: + private: boost::container::small_vector<Vector2D, 10> m_vertices; RectangleBounds m_boundingBox; }; -} // namespace +} // namespace Acts #include "Acts/Surfaces/ConvexPolygonBounds.ipp" diff --git a/Core/include/Acts/Surfaces/ConvexPolygonBounds.ipp b/Core/include/Acts/Surfaces/ConvexPolygonBounds.ipp index 09606e3a9ccafa0f1db12775c587739ea0147386..1dd7104a2090824a816fd2d13e0e3ccb7c27e273 100644 --- a/Core/include/Acts/Surfaces/ConvexPolygonBounds.ipp +++ b/Core/include/Acts/Surfaces/ConvexPolygonBounds.ipp @@ -8,9 +8,7 @@ #include "Acts/Utilities/ThrowAssert.hpp" -std::ostream& -Acts::ConvexPolygonBoundsBase::toStream(std::ostream& sl) const -{ +std::ostream& Acts::ConvexPolygonBoundsBase::toStream(std::ostream& sl) const { std::vector<Vector2D> vtxs = vertices(); sl << "Acts::ConvexPolygonBounds<" << vtxs.size() << ">: vertices: [x, y]\n"; for (size_t i = 0; i < vtxs.size(); i++) { @@ -25,9 +23,8 @@ Acts::ConvexPolygonBoundsBase::toStream(std::ostream& sl) const } template <typename coll_t> -Acts::RectangleBounds -Acts::ConvexPolygonBoundsBase::makeBoundingBox(const coll_t& vertices) -{ +Acts::RectangleBounds Acts::ConvexPolygonBoundsBase::makeBoundingBox( + const coll_t& vertices) { Vector2D vmax, vmin; vmax = vertices[0]; vmin = vertices[0]; @@ -40,9 +37,7 @@ Acts::ConvexPolygonBoundsBase::makeBoundingBox(const coll_t& vertices) return {vmin, vmax}; } -std::vector<TDD_real_t> -Acts::ConvexPolygonBoundsBase::valueStore() const -{ +std::vector<TDD_real_t> Acts::ConvexPolygonBoundsBase::valueStore() const { std::vector<TDD_real_t> values; for (const auto& vtx : vertices()) { values.push_back(vtx.x()); @@ -52,19 +47,17 @@ Acts::ConvexPolygonBoundsBase::valueStore() const } template <typename coll_t> -bool -Acts::ConvexPolygonBoundsBase::convex_impl(const coll_t& vertices) -{ +bool Acts::ConvexPolygonBoundsBase::convex_impl(const coll_t& vertices) { static_assert(std::is_same<typename coll_t::value_type, Vector2D>::value, "Must be collection of Vector2D"); const size_t N = vertices.size(); for (size_t i = 0; i < N; i++) { - size_t j = (i + 1) % N; + size_t j = (i + 1) % N; const Vector2D& a = vertices[i]; const Vector2D& b = vertices[j]; - const Vector2D ab = b - a; + const Vector2D ab = b - a; const Vector2D normal = Vector2D(ab.y(), -ab.x()).normalized(); bool first = true; @@ -75,11 +68,11 @@ Acts::ConvexPolygonBoundsBase::convex_impl(const coll_t& vertices) continue; } - const Vector2D& c = vertices[k]; - double dot = normal.dot(c - a); + const Vector2D& c = vertices[k]; + double dot = normal.dot(c - a); if (first) { - ref = std::signbit(dot); + ref = std::signbit(dot); first = false; continue; } @@ -95,8 +88,7 @@ Acts::ConvexPolygonBoundsBase::convex_impl(const coll_t& vertices) template <int N> Acts::ConvexPolygonBounds<N>::ConvexPolygonBounds( const std::vector<Acts::Vector2D>& vertices) - : m_vertices(), m_boundingBox(makeBoundingBox(vertices)) -{ + : m_vertices(), m_boundingBox(makeBoundingBox(vertices)) { throw_assert(vertices.size() == N, "Size and number of given vertices do not match."); for (size_t i = 0; i < N; i++) { @@ -107,109 +99,81 @@ Acts::ConvexPolygonBounds<N>::ConvexPolygonBounds( template <int N> Acts::ConvexPolygonBounds<N>::ConvexPolygonBounds(const vertex_array& vertices) - : m_vertices(vertices), m_boundingBox(makeBoundingBox(vertices)) -{ + : m_vertices(vertices), m_boundingBox(makeBoundingBox(vertices)) { throw_assert(convex(), "Given vertices do not form convex hull."); } template <int N> -Acts::ConvexPolygonBounds<N>* -Acts::ConvexPolygonBounds<N>::clone() const -{ +Acts::ConvexPolygonBounds<N>* Acts::ConvexPolygonBounds<N>::clone() const { return new ConvexPolygonBounds<N>(*this); } template <int N> -Acts::SurfaceBounds::BoundsType -Acts::ConvexPolygonBounds<N>::type() const -{ +Acts::SurfaceBounds::BoundsType Acts::ConvexPolygonBounds<N>::type() const { return SurfaceBounds::ConvexPolygon; } template <int N> -bool -Acts::ConvexPolygonBounds<N>::inside(const Acts::Vector2D& lpos, - const Acts::BoundaryCheck& bcheck) const -{ +bool Acts::ConvexPolygonBounds<N>::inside( + const Acts::Vector2D& lpos, const Acts::BoundaryCheck& bcheck) const { return bcheck.isInside(lpos, m_vertices); } template <int N> -double -Acts::ConvexPolygonBounds<N>::distanceToBoundary( - const Acts::Vector2D& lpos) const -{ +double Acts::ConvexPolygonBounds<N>::distanceToBoundary( + const Acts::Vector2D& lpos) const { return BoundaryCheck(true).distance(lpos, m_vertices); } template <int N> -std::vector<Acts::Vector2D> -Acts::ConvexPolygonBounds<N>::vertices() const -{ +std::vector<Acts::Vector2D> Acts::ConvexPolygonBounds<N>::vertices() const { return {m_vertices.begin(), m_vertices.end()}; } template <int N> -const Acts::RectangleBounds& -Acts::ConvexPolygonBounds<N>::boundingBox() const -{ +const Acts::RectangleBounds& Acts::ConvexPolygonBounds<N>::boundingBox() const { return m_boundingBox; } template <int N> -bool -Acts::ConvexPolygonBounds<N>::convex() const -{ +bool Acts::ConvexPolygonBounds<N>::convex() const { return convex_impl(m_vertices); } Acts::ConvexPolygonBounds<Acts::PolygonDynamic>::ConvexPolygonBounds( const std::vector<Vector2D>& vertices) - : m_vertices(vertices.begin(), vertices.end()) - , m_boundingBox(makeBoundingBox(vertices)) -{ -} + : m_vertices(vertices.begin(), vertices.end()), + m_boundingBox(makeBoundingBox(vertices)) {} Acts::ConvexPolygonBounds<Acts::PolygonDynamic>* -Acts::ConvexPolygonBounds<Acts::PolygonDynamic>::clone() const -{ +Acts::ConvexPolygonBounds<Acts::PolygonDynamic>::clone() const { return new Acts::ConvexPolygonBounds<Acts::PolygonDynamic>(*this); } Acts::SurfaceBounds::BoundsType -Acts::ConvexPolygonBounds<Acts::PolygonDynamic>::type() const -{ +Acts::ConvexPolygonBounds<Acts::PolygonDynamic>::type() const { return SurfaceBounds::ConvexPolygon; } -bool -Acts::ConvexPolygonBounds<Acts::PolygonDynamic>::inside( - const Acts::Vector2D& lpos, - const Acts::BoundaryCheck& bcheck) const -{ +bool Acts::ConvexPolygonBounds<Acts::PolygonDynamic>::inside( + const Acts::Vector2D& lpos, const Acts::BoundaryCheck& bcheck) const { return bcheck.isInside(lpos, m_vertices); } -double -Acts::ConvexPolygonBounds<Acts::PolygonDynamic>::distanceToBoundary( - const Acts::Vector2D& lpos) const -{ +double Acts::ConvexPolygonBounds<Acts::PolygonDynamic>::distanceToBoundary( + const Acts::Vector2D& lpos) const { return BoundaryCheck(true).distance(lpos, m_vertices); } std::vector<Acts::Vector2D> -Acts::ConvexPolygonBounds<Acts::PolygonDynamic>::vertices() const -{ +Acts::ConvexPolygonBounds<Acts::PolygonDynamic>::vertices() const { return {m_vertices.begin(), m_vertices.end()}; } const Acts::RectangleBounds& -Acts::ConvexPolygonBounds<Acts::PolygonDynamic>::boundingBox() const -{ +Acts::ConvexPolygonBounds<Acts::PolygonDynamic>::boundingBox() const { return m_boundingBox; } -bool -Acts::ConvexPolygonBounds<Acts::PolygonDynamic>::convex() const -{ +bool Acts::ConvexPolygonBounds<Acts::PolygonDynamic>::convex() const { return convex_impl(m_vertices); } diff --git a/Core/include/Acts/Surfaces/CylinderBounds.hpp b/Core/include/Acts/Surfaces/CylinderBounds.hpp index a9f4dcc6f91b8510290d1d7eb6d51c8f90c44ad4..240c2bab895bb31b9bacd299786b6df1d0b1217e 100644 --- a/Core/include/Acts/Surfaces/CylinderBounds.hpp +++ b/Core/include/Acts/Surfaces/CylinderBounds.hpp @@ -36,17 +36,16 @@ namespace Acts { /// /// @image html CylinderBounds.gif -class CylinderBounds : public SurfaceBounds -{ -public: +class CylinderBounds : public SurfaceBounds { + public: /// @enum BoundValues for readablility /// nested enumeration object enum BoundValues { - bv_radius = 0, - bv_averagePhi = 1, + bv_radius = 0, + bv_averagePhi = 1, bv_halfPhiSector = 2, - bv_halfZ = 3, - bv_length = 4 + bv_halfZ = 3, + bv_length = 4 }; CylinderBounds() = delete; @@ -70,21 +69,16 @@ public: /// @param avphi is the middle phi position of the segment /// @param halfphi is the half opening angle /// @param halez is the half length in z - CylinderBounds(double radius, - double averagePhi, - double halfPhi, + CylinderBounds(double radius, double averagePhi, double halfPhi, double halfZ); ~CylinderBounds() override; - CylinderBounds* - clone() const final; + CylinderBounds* clone() const final; - BoundsType - type() const final; + BoundsType type() const final; - std::vector<TDD_real_t> - valueStore() const final; + std::vector<TDD_real_t> valueStore() const final; /// Inside check for the bounds object driven by the boundary check directive /// Each Bounds has a method inside, which checks if a LocalPosition is inside @@ -93,8 +87,7 @@ public: /// @param lpos Local position (assumed to be in right surface frame) /// @param bcheck boundary check directive /// @return boolean indicator for the success of this operation - bool - inside(const Vector2D& lpos, const BoundaryCheck& bcheck) const final; + bool inside(const Vector2D& lpos, const BoundaryCheck& bcheck) const final; /// Specialized method for CylinderBounds that checks if a global position /// is within the the cylinder cover @@ -102,69 +95,52 @@ public: /// @param pos is the position in the cylinder frame /// @param bcheck is the boundary check directive /// @return boolean indicator for operation success - bool - inside3D(const Vector3D& pos, const BoundaryCheck& bcheck = true) const; + bool inside3D(const Vector3D& pos, const BoundaryCheck& bcheck = true) const; /// Minimal distance to boundary ( > 0 if outside and <=0 if inside) /// /// @param lpos is the local position to check for the distance /// @return is a signed distance parameter - double - distanceToBoundary(const Vector2D& lpos) const final; + double distanceToBoundary(const Vector2D& lpos) const final; /// Output Method for std::ostream - std::ostream& - toStream(std::ostream& sl) const final; + std::ostream& toStream(std::ostream& sl) const final; /// This method returns the radius - double - r() const; + double r() const; /// This method returns the average phi - double - averagePhi() const; + double averagePhi() const; /// This method returns the halfPhiSector angle - double - halfPhiSector() const; + double halfPhiSector() const; /// This method returns the halflengthZ - double - halflengthZ() const; + double halflengthZ() const; -private: + private: /// the bound radius, average, half phi and half Z double m_radius, m_avgPhi, m_halfPhi, m_halfZ; /// an indicator if the bounds are closed bool m_closed; - Vector2D - shifted(const Vector2D& lpos) const; - ActsSymMatrixD<2> - jacobian() const; + Vector2D shifted(const Vector2D& lpos) const; + ActsSymMatrixD<2> jacobian() const; }; -inline double -CylinderBounds::r() const -{ +inline double CylinderBounds::r() const { return m_radius; } -inline double -CylinderBounds::averagePhi() const -{ +inline double CylinderBounds::averagePhi() const { return m_avgPhi; } -inline double -CylinderBounds::halfPhiSector() const -{ +inline double CylinderBounds::halfPhiSector() const { return m_halfPhi; } -inline double -CylinderBounds::halflengthZ() const -{ +inline double CylinderBounds::halflengthZ() const { return m_halfZ; } -} \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Surfaces/CylinderSurface.hpp b/Core/include/Acts/Surfaces/CylinderSurface.hpp index 88bb3ea6aae7d87d9115b8ecff42caf61fc994ec..3812f09d1f9e3adea4cd143a8200ae5b81565f1a 100644 --- a/Core/include/Acts/Surfaces/CylinderSurface.hpp +++ b/Core/include/Acts/Surfaces/CylinderSurface.hpp @@ -35,11 +35,10 @@ namespace Acts { /// /// @image html CylinderSurface.png -class CylinderSurface : public Surface -{ +class CylinderSurface : public Surface { friend Surface; -protected: + protected: /// Deleted default constructor CylinderSurface() = delete; @@ -49,9 +48,8 @@ protected: /// @note if htrans == nullptr, the cylinder is positioned around (0.,0.,0.) /// @param radius is the radius of the cylinder /// @param hlength is the half length of the cylinder in z - CylinderSurface(std::shared_ptr<const Transform3D> htrans, - double radius, - double hlength); + CylinderSurface(std::shared_ptr<const Transform3D> htrans, double radius, + double hlength); /// Constructor from Transform3D, radius halfphi, and halflength /// @@ -60,17 +58,15 @@ protected: /// @param radius is the radius of the cylinder /// @param hphi is the half length in phi of the cylinder /// @param hlength is the half length of the cylinder in z - CylinderSurface(std::shared_ptr<const Transform3D> htrans, - double radius, - double hphi, - double hlength); + CylinderSurface(std::shared_ptr<const Transform3D> htrans, double radius, + double hphi, double hlength); /// Constructor from DetectorElementBase: Element proxy /// /// @param cbounds are the provided cylinder bounds (shared) /// @param detelement is the linked detector element to this surface CylinderSurface(std::shared_ptr<const CylinderBounds> cbounds, - const DetectorElementBase& detelement); + const DetectorElementBase& detelement); /// Constructor from Transform3D and CylinderBounds /// @@ -78,7 +74,7 @@ protected: /// @note if htrans == nullptr, the cylinder is positioned around (0.,0.,0.) /// @param cbounds is a shared pointer to a cylindeer bounds object, /// it must exist (assert test) - CylinderSurface(std::shared_ptr<const Transform3D> htrans, + CylinderSurface(std::shared_ptr<const Transform3D> htrans, const std::shared_ptr<const CylinderBounds>& cbounds); /// Copy constructor @@ -91,26 +87,24 @@ protected: /// @param gctx The current geometry context object, e.g. alignment /// @param other is the source cone surface /// @param transf is the additional transfrom applied after copying - CylinderSurface(const GeometryContext& gctx, - const CylinderSurface& other, - const Transform3D& transf); + CylinderSurface(const GeometryContext& gctx, const CylinderSurface& other, + const Transform3D& transf); -public: + public: /// Destructor - defaulted ~CylinderSurface() override = default; /// Assignment operator /// /// @param other is the source cylinder for the copy - CylinderSurface& - operator=(const CylinderSurface& other); + CylinderSurface& operator=(const CylinderSurface& other); /// Clone method into a concrete type of CylinderSurface with shift /// /// @param gctx The current geometry context object, e.g. alignment /// @param shift applied to the surface - std::shared_ptr<CylinderSurface> - clone(const GeometryContext& gctx, const Transform3D& shift) const; + std::shared_ptr<CylinderSurface> clone(const GeometryContext& gctx, + const Transform3D& shift) const; /// The binning position method - is overloaded for r-type binning /// @@ -118,8 +112,8 @@ public: /// @param bValue is the type of global binning to be done /// /// @return is the global position to be used for binning - const Vector3D - binningPosition(const GeometryContext& gctx, BinningValue bValue) const final; + const Vector3D binningPosition(const GeometryContext& gctx, + BinningValue bValue) const final; /// Return the measurement frame - this is needed for alignment, in particular /// The measurement frame of a cylinder is the tangential plane at a given @@ -129,14 +123,12 @@ public: /// @param gpos is the position where the measurement frame is defined /// @param mom is the momentum vector (ignored) /// @return rotation matrix that defines the measurement frame - const RotationMatrix3D - referenceFrame(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& mom) const final; + const RotationMatrix3D referenceFrame(const GeometryContext& gctx, + const Vector3D& gpos, + const Vector3D& mom) const final; /// Return the surface type - SurfaceType - type() const override; + SurfaceType type() const override; /// Return method for surface normal information /// @note for a Cylinder a local position is always required for the normal @@ -145,8 +137,8 @@ public: /// @param gctx The current geometry context object, e.g. alignment /// @param lpos is the local postion for which the normal vector is requested /// @return normal vector at the local position - const Vector3D - normal(const GeometryContext& gctx, const Vector2D& lpos) const final; + const Vector3D normal(const GeometryContext& gctx, + const Vector2D& lpos) const final; /// Return method for surface normal information /// @note for a Cylinder a local position is always required for the normal @@ -155,8 +147,8 @@ public: /// @param gctx The current geometry context object, e.g. alignment /// @param gpos is the global postion for which the normal vector is requested /// @return normal vector at the global position - const Vector3D - normal(const GeometryContext& gctx, const Vector3D& gpos) const final; + const Vector3D normal(const GeometryContext& gctx, + const Vector3D& gpos) const final; /// Normal vector return without argument using Surface::normal; @@ -166,12 +158,10 @@ public: /// @param gctx The current geometry context object, e.g. alignment /// /// @return the z-Axis of transform - virtual const Vector3D - rotSymmetryAxis(const GeometryContext& gctx) const; + virtual const Vector3D rotSymmetryAxis(const GeometryContext& gctx) const; /// This method returns the CylinderBounds by reference - const CylinderBounds& - bounds() const final; + const CylinderBounds& bounds() const final; /// Local to global transformation /// @@ -179,11 +169,8 @@ public: /// @param lpos is the local position to be transformed /// @param mom is the global momentum (ignored in this operation) /// @param gpos is the global position shich is filled - void - localToGlobal(const GeometryContext& gctx, - const Vector2D& lpos, - const Vector3D& mom, - Vector3D& gpos) const final; + void localToGlobal(const GeometryContext& gctx, const Vector2D& lpos, + const Vector3D& mom, Vector3D& gpos) const final; /// Global to local transfomration /// @@ -193,11 +180,8 @@ public: /// @param lpos is hte local position to be filled /// /// @return is a boolean indicating if the transformation succeeded - bool - globalToLocal(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& mom, - Vector2D& lpos) const final; + bool globalToLocal(const GeometryContext& gctx, const Vector3D& gpos, + const Vector3D& mom, Vector2D& lpos) const final; /// Straight line intersection schema - provides closest intersection /// and (signed) path length @@ -242,13 +226,11 @@ public: /// reinsertion into the line equation. /// /// @return is the intersection object - Intersection - intersectionEstimate(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& gdir, - NavigationDirection navDir = forward, - const BoundaryCheck& bcheck = false, - CorrFnc correct = nullptr) const final; + Intersection intersectionEstimate(const GeometryContext& gctx, + const Vector3D& gpos, const Vector3D& gdir, + NavigationDirection navDir = forward, + const BoundaryCheck& bcheck = false, + CorrFnc correct = nullptr) const final; /// Path correction due to incident of the track /// @@ -257,36 +239,30 @@ public: /// @param mom is the global momentum at the starting point /// /// @return is the correction factor due to incident - double - pathCorrection(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& mom) const final; + double pathCorrection(const GeometryContext& gctx, const Vector3D& gpos, + const Vector3D& mom) const final; /// Return method for properly formatted output string - std::string - name() const override; + std::string name() const override; /// Return a PolyhedronRepresentation for this object /// /// @param gctx The current geometry context object, e.g. alignment /// @param l0div Number of divisions along l0 (phi) /// @param l1div Number of divisions along l1 (z) - virtual PolyhedronRepresentation - polyhedronRepresentation(const GeometryContext& gctx, - size_t l0div = 10, - size_t l1div = 1) const; + virtual PolyhedronRepresentation polyhedronRepresentation( + const GeometryContext& gctx, size_t l0div = 10, size_t l1div = 1) const; -protected: + protected: std::shared_ptr<const CylinderBounds> m_bounds; //!< bounds (shared) -private: + private: /// Clone method implementation /// /// @param gctx The current geometry context object, e.g. alignment /// @param shift applied to the surface - CylinderSurface* - clone_impl(const GeometryContext& gctx, - const Transform3D& shift) const override; + CylinderSurface* clone_impl(const GeometryContext& gctx, + const Transform3D& shift) const override; }; #include "Acts/Surfaces/detail/CylinderSurface.ipp" diff --git a/Core/include/Acts/Surfaces/DiamondBounds.hpp b/Core/include/Acts/Surfaces/DiamondBounds.hpp index bad26a54113a94918d45f1035c18006ff86c89fc..3ed9855c20d16eec3163c3b7d62d63419bb025fa 100644 --- a/Core/include/Acts/Surfaces/DiamondBounds.hpp +++ b/Core/include/Acts/Surfaces/DiamondBounds.hpp @@ -25,17 +25,16 @@ namespace Acts { /// /// Bounds for a double trapezoidal ("diamond"), planar Surface. /// -class DiamondBounds : public PlanarBounds -{ -public: +class DiamondBounds : public PlanarBounds { + public: /// @enum BoundValues for better readability enum BoundValues { bv_minHalfX = 0, bv_medHalfX = 1, bv_maxHalfX = 2, - bv_halfY1 = 3, - bv_halfY2 = 4, - bv_length = 5 + bv_halfY1 = 3, + bv_halfY2 = 4, + bv_length = 5 }; /// Constructor for convex hexagon symmetric about the y axis @@ -45,22 +44,16 @@ public: /// @param maxhalex is the halflength in x at maximal y /// @param haley1 is the halflength into y < 0 /// @param haley2 is the halflength into y > 0 - DiamondBounds(double minhalex, - double medhalex, - double maxhalex, - double haley1, - double haley2); + DiamondBounds(double minhalex, double medhalex, double maxhalex, + double haley1, double haley2); ~DiamondBounds() override; - DiamondBounds* - clone() const final; + DiamondBounds* clone() const final; - BoundsType - type() const final; + BoundsType type() const final; - std::vector<TDD_real_t> - valueStore() const final; + std::vector<TDD_real_t> valueStore() const final; /// Inside check for the bounds object driven by the boundary check directive /// Each Bounds has a method inside, which checks if a LocalPosition is inside @@ -69,87 +62,67 @@ public: /// @param lpos Local position (assumed to be in right surface frame) /// @param bcheck boundary check directive /// @return boolean indicator for the success of this operation - bool - inside(const Vector2D& lpos, const BoundaryCheck& bcheck) const final; + bool inside(const Vector2D& lpos, const BoundaryCheck& bcheck) const final; /// Minimal distance to boundary ( > 0 if outside and <=0 if inside) /// /// @param lpos is the local position to check for the distance /// @return is a signed distance parameter - double - distanceToBoundary(const Vector2D& lpos) const final; + double distanceToBoundary(const Vector2D& lpos) const final; /// Return the vertices - or, the points of the extremas - std::vector<Vector2D> - vertices() const final; + std::vector<Vector2D> vertices() const final; // Bounding box representation - const RectangleBounds& - boundingBox() const final; + const RectangleBounds& boundingBox() const final; /// Output Method for std::ostream /// /// @param sl is the ostream in which it is dumped - std::ostream& - toStream(std::ostream& sl) const final; + std::ostream& toStream(std::ostream& sl) const final; /// This method returns the halflength in X at minimal Y /// (first coordinate of local surface frame) - double - minHalflengthX() const; + double minHalflengthX() const; /// This method returns the (maximal) halflength in X /// (first coordinate of local surface frame) - double - medHalflengthX() const; + double medHalflengthX() const; /// This method returns the halflength in X at maximal Y /// (first coordinate of local surface frame) - double - maxHalflengthX() const; + double maxHalflengthX() const; /// This method returns the halflength in Y of trapezoid at negative Y - double - halflengthY1() const; + double halflengthY1() const; /// This method returns the halflength in Y of trapezoid at positive Y - double - halflengthY2() const; + double halflengthY2() const; -private: - double m_minHalfX, m_medHalfX, m_maxHalfX; - double m_minY, m_maxY; + private: + double m_minHalfX, m_medHalfX, m_maxHalfX; + double m_minY, m_maxY; RectangleBounds m_boundingBox; ///< internal bounding box cache }; -inline double -DiamondBounds::minHalflengthX() const -{ +inline double DiamondBounds::minHalflengthX() const { return m_minHalfX; } -inline double -DiamondBounds::medHalflengthX() const -{ +inline double DiamondBounds::medHalflengthX() const { return m_medHalfX; } -inline double -DiamondBounds::maxHalflengthX() const -{ +inline double DiamondBounds::maxHalflengthX() const { return m_maxHalfX; } -inline double -DiamondBounds::halflengthY1() const -{ +inline double DiamondBounds::halflengthY1() const { return m_minY; } -inline double -DiamondBounds::halflengthY2() const -{ +inline double DiamondBounds::halflengthY2() const { return m_maxY; } -} // namespace \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Surfaces/DiscBounds.hpp b/Core/include/Acts/Surfaces/DiscBounds.hpp index 3eb5e18138de753683622ca6ffcf0609a65a8be2..496a2d6364c5fbc4e5ce2bcd87166c62f8e2dce9 100644 --- a/Core/include/Acts/Surfaces/DiscBounds.hpp +++ b/Core/include/Acts/Surfaces/DiscBounds.hpp @@ -20,8 +20,6 @@ namespace Acts { /// common base class for all bounds that are in a r/phi frame /// - simply introduced to avoid wrong bound assigments to surfaces -class DiscBounds : public SurfaceBounds -{ -}; +class DiscBounds : public SurfaceBounds {}; -} // namespace \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Surfaces/DiscSurface.hpp b/Core/include/Acts/Surfaces/DiscSurface.hpp index c68470dc32cc273da08b1dc8cd67c1ef40cc9721..82d0d1a62006c95ffdac9b3fee8c44d78299caab 100644 --- a/Core/include/Acts/Surfaces/DiscSurface.hpp +++ b/Core/include/Acts/Surfaces/DiscSurface.hpp @@ -44,13 +44,12 @@ class DetectorElementBase; /// /// @image html DiscSurface.png /// -class DiscSurface : public Surface -{ +class DiscSurface : public Surface { friend Surface; DiscSurface() = delete; -protected: + protected: /// Default Constructor is deleted /// Constructor for Discs from Transform3D, \f$ r_{min}, r_{max} \f$ @@ -61,10 +60,8 @@ protected: /// @param rmax The outer radius of the disc surface /// @param hphisec The opening angle of the disc surface and is optional /// the default is a full disc - DiscSurface(std::shared_ptr<const Transform3D> htrans, - double rmin, - double rmax, - double hphisec = M_PI); + DiscSurface(std::shared_ptr<const Transform3D> htrans, double rmin, + double rmax, double hphisec = M_PI); /// Constructor for Discs from Transform3D, \f$ r_{min}, r_{max}, hx_{min}, /// hx_{max} \f$ @@ -78,27 +75,23 @@ protected: /// @param minR The outer radius of the disc surface /// @param avephi The position in phi (default is 0.) /// @param stereo The optional stereo angle - DiscSurface(std::shared_ptr<const Transform3D> htrans, - double minhalfx, - double maxhalfx, - double maxR, - double minR, - double avephi = 0., - double stereo = 0.); + DiscSurface(std::shared_ptr<const Transform3D> htrans, double minhalfx, + double maxhalfx, double maxR, double minR, double avephi = 0., + double stereo = 0.); /// Constructor for Discs from Transform3D and shared DiscBounds /// /// @param htrans The transform that positions the disc in global 3D /// @param dbounds The disc bounds describing the surface coverage DiscSurface(std::shared_ptr<const Transform3D> htrans, - std::shared_ptr<const DiscBounds> dbounds = nullptr); + std::shared_ptr<const DiscBounds> dbounds = nullptr); /// Constructor from DetectorElementBase : Element proxy /// /// @param dbounds The disc bounds describing the surface coverage /// @param detelement The detector element represented by this surface DiscSurface(const std::shared_ptr<const DiscBounds>& dbounds, - const DetectorElementBase& detelement); + const DetectorElementBase& detelement); /// Copy Constructor /// @@ -110,30 +103,27 @@ protected: /// @param gctx The current geometry context object, e.g. alignment /// @param other is the source cone surface /// @param transf is the additional transfrom applied after copying - DiscSurface(const GeometryContext& gctx, - const DiscSurface& other, - const Transform3D& transf); + DiscSurface(const GeometryContext& gctx, const DiscSurface& other, + const Transform3D& transf); -public: + public: /// Destructor - defaulted ~DiscSurface() override = default; /// Assignement operator /// /// @param other The source sourface for the assignment - DiscSurface& - operator=(const DiscSurface& other); + DiscSurface& operator=(const DiscSurface& other); /// Clone method into a concrete type of DiscSurface with shift /// /// @param gctx The current geometry context object, e.g. alignment /// @param shift applied to the surface - std::shared_ptr<DiscSurface> - clone(const GeometryContext& gctx, const Transform3D& shift) const; + std::shared_ptr<DiscSurface> clone(const GeometryContext& gctx, + const Transform3D& shift) const; /// Return the surface type - SurfaceType - type() const override; + SurfaceType type() const override; /// Normal vector return /// @@ -141,8 +131,8 @@ public: /// @param lpos The local position is ignored /// /// @return a Vector3D by value - const Vector3D - normal(const GeometryContext& gctx, const Vector2D& lpos) const final; + const Vector3D normal(const GeometryContext& gctx, + const Vector2D& lpos) const final; /// Normal vector return without argument using Surface::normal; @@ -154,12 +144,11 @@ public: /// @param bValue The binning type to be used /// /// @return position that can beused for this binning - const Vector3D - binningPosition(const GeometryContext& gctx, BinningValue bValue) const final; + const Vector3D binningPosition(const GeometryContext& gctx, + BinningValue bValue) const final; /// This method returns the bounds by reference - const SurfaceBounds& - bounds() const final; + const SurfaceBounds& bounds() const final; /// Local to global transformation /// For planar surfaces the momentum is ignroed in the local to global @@ -172,11 +161,8 @@ public: /// symmetry) /// /// @note the momentum is ignored for Disc surfaces in this calculateion - void - localToGlobal(const GeometryContext& gctx, - const Vector2D& lpos, - const Vector3D& mom, - Vector3D& gpos) const final; + void localToGlobal(const GeometryContext& gctx, const Vector2D& lpos, + const Vector3D& mom, Vector3D& gpos) const final; /// Global to local transformation /// @note the momentum is ignored for Disc surfaces in this calculateion @@ -190,11 +176,8 @@ public: /// /// @return boolean indication if operation was successful (fail means global /// position was not on surface) - bool - globalToLocal(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& mom, - Vector2D& lpos) const final; + bool globalToLocal(const GeometryContext& gctx, const Vector3D& gpos, + const Vector3D& mom, Vector2D& lpos) const final; /// Special method for DiscSurface : local<->local transformations polar <-> /// cartesian @@ -202,8 +185,7 @@ public: /// @param lpolar is a local position in polar coordinates /// /// @return values is local 2D position in cartesian coordinates @todo check - const Vector2D - localPolarToCartesian(const Vector2D& lpolar) const; + const Vector2D localPolarToCartesian(const Vector2D& lpolar) const; /// Special method for Disc surface : local<->local transformations polar <-> /// cartesian @@ -211,8 +193,7 @@ public: /// @param lcart is local 2D position in cartesian coordinates /// /// @return value is a local position in polar coordinates - const Vector2D - localCartesianToPolar(const Vector2D& lcart) const; + const Vector2D localCartesianToPolar(const Vector2D& lcart) const; /// Special method for DiscSurface : local<->local transformations polar <-> /// cartesian @@ -221,8 +202,7 @@ public: /// @param locpol is a local position in polar coordinates /// /// @return values is local 2D position in cartesian coordinates - const Vector2D - localPolarToLocalCartesian(const Vector2D& locpol) const; + const Vector2D localPolarToLocalCartesian(const Vector2D& locpol) const; /// Special method for DiscSurface : local<->global transformation when /// provided cartesian coordinates @@ -231,9 +211,8 @@ public: /// @param lpos is local 2D position in cartesian coordinates /// /// @return value is a global cartesian 3D position - const Vector3D - localCartesianToGlobal(const GeometryContext& gctx, - const Vector2D& lpos) const; + const Vector3D localCartesianToGlobal(const GeometryContext& gctx, + const Vector2D& lpos) const; /// Special method for DiscSurface : global<->local from cartesian coordinates /// @@ -242,10 +221,9 @@ public: /// @param tol The absoltue tolerance parameter /// /// @return value is a local polar - const Vector2D - globalToLocalCartesian(const GeometryContext& gctx, - const Vector3D& gpos, - double tol = 0.) const; + const Vector2D globalToLocalCartesian(const GeometryContext& gctx, + const Vector3D& gpos, + double tol = 0.) const; /// Initialize the jacobian from local to global /// the surface knows best, hence the calculation is done here. @@ -258,12 +236,10 @@ public: /// @param dir The direction at of the parameters /// /// @param pars The paranmeters vector - void - initJacobianToGlobal(const GeometryContext& gctx, - ActsMatrixD<7, 5>& jacobian, - const Vector3D& gpos, - const Vector3D& dir, - const ActsVectorD<5>& pars) const final; + void initJacobianToGlobal(const GeometryContext& gctx, + ActsMatrixD<7, 5>& jacobian, const Vector3D& gpos, + const Vector3D& dir, + const ActsVectorD<5>& pars) const final; /// Initialize the jacobian from global to local /// the surface knows best, hence the calculation is done here. @@ -276,11 +252,10 @@ public: /// @param dir The direction at of the parameters /// /// @return the transposed reference frame (avoids recalculation) - const RotationMatrix3D - initJacobianToLocal(const GeometryContext& gctx, - ActsMatrixD<5, 7>& jacobian, - const Vector3D& gpos, - const Vector3D& dir) const final; + const RotationMatrix3D initJacobianToLocal(const GeometryContext& gctx, + ActsMatrixD<5, 7>& jacobian, + const Vector3D& gpos, + const Vector3D& dir) const final; /// Path correction due to incident of the track /// @@ -288,10 +263,8 @@ public: /// @param pos The global position as a starting point /// @param mom The global momentum at the starting point /// @return The correction factor due to incident - double - pathCorrection(const GeometryContext& gctx, - const Vector3D& pos, - const Vector3D& mom) const final; + double pathCorrection(const GeometryContext& gctx, const Vector3D& pos, + const Vector3D& mom) const final; /// @brief Straight line intersection schema /// @@ -322,38 +295,32 @@ public: /// - perpendicular to the normal of the plane /// /// @return is the surface intersection object - Intersection - intersectionEstimate(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& gdir, - NavigationDirection navDir = forward, - const BoundaryCheck& bcheck = false, - CorrFnc correct = nullptr) const final; + Intersection intersectionEstimate(const GeometryContext& gctx, + const Vector3D& gpos, const Vector3D& gdir, + NavigationDirection navDir = forward, + const BoundaryCheck& bcheck = false, + CorrFnc correct = nullptr) const final; /// Return properly formatted class name for screen output - std::string - name() const override; + std::string name() const override; /// Return a PolyhedronRepresentation for this object /// @param gctx The current geometry context object, e.g. alignment /// @param l0div Number of divisions along l0 (phi) /// @param l1div Number of divisions along l1 (r) - virtual PolyhedronRepresentation - polyhedronRepresentation(const GeometryContext& gctx, - size_t l0div = 10, - size_t l1div = 1) const; + virtual PolyhedronRepresentation polyhedronRepresentation( + const GeometryContext& gctx, size_t l0div = 10, size_t l1div = 1) const; -protected: + protected: std::shared_ptr<const DiscBounds> m_bounds; ///< bounds (shared) -private: + private: /// Clone method implementation /// /// @param gctx The current geometry context object, e.g. alignment /// @param shift applied to the surface - DiscSurface* - clone_impl(const GeometryContext& gctx, - const Transform3D& shift) const override; + DiscSurface* clone_impl(const GeometryContext& gctx, + const Transform3D& shift) const override; }; #include "Acts/Surfaces/detail/DiscSurface.ipp" diff --git a/Core/include/Acts/Surfaces/DiscTrapezoidalBounds.hpp b/Core/include/Acts/Surfaces/DiscTrapezoidalBounds.hpp index e86929d338ba02a1af4232957378f5068bb7325e..5eba7d3b51b8278ede824998345839450076f5d2 100644 --- a/Core/include/Acts/Surfaces/DiscTrapezoidalBounds.hpp +++ b/Core/include/Acts/Surfaces/DiscTrapezoidalBounds.hpp @@ -27,19 +27,18 @@ namespace Acts { /// be restricted to a phi-range around the center position. /// -class DiscTrapezoidalBounds : public DiscBounds -{ -public: +class DiscTrapezoidalBounds : public DiscBounds { + public: /// @enum BoundValues /// enumeration for readability enum BoundValues { - bv_rMin = 0, - bv_rMax = 1, - bv_minHalfX = 2, - bv_maxHalfX = 3, + bv_rMin = 0, + bv_rMax = 1, + bv_minHalfX = 2, + bv_maxHalfX = 3, bv_averagePhi = 4, - bv_stereo = 5, - bv_length = 6 + bv_stereo = 5, + bv_length = 6 }; DiscTrapezoidalBounds() = delete; @@ -52,143 +51,106 @@ public: /// @param minR inner radius /// @param avephi average phi value /// @param stereo optional stero angle applied - DiscTrapezoidalBounds(double minhalfx, - double maxhalfx, - double maxR, - double minR, - double avephi = M_PI_2, + DiscTrapezoidalBounds(double minhalfx, double maxhalfx, double maxR, + double minR, double avephi = M_PI_2, double stereo = 0.); ~DiscTrapezoidalBounds() override; - DiscTrapezoidalBounds* - clone() const final; + DiscTrapezoidalBounds* clone() const final; - SurfaceBounds::BoundsType - type() const final; + SurfaceBounds::BoundsType type() const final; - std::vector<TDD_real_t> - valueStore() const final; + std::vector<TDD_real_t> valueStore() const final; /// This method cheks if the radius given in the LocalPosition is inside /// [rMin,rMax] /// if only tol0 is given and additional in the phi sector is tol1 is given /// @param lpos is the local position to be checked (in polar coordinates) /// @param bcheck is the boundary check directive - bool - inside(const Vector2D& lpos, const BoundaryCheck& bcheck = true) const final; + bool inside(const Vector2D& lpos, + const BoundaryCheck& bcheck = true) const final; /// Minimal distance to boundary /// @param lpos is the local position to be checked (in polar coordinates) /// @return is the minimal distance ( > 0 if outside and <=0 if inside) - double - distanceToBoundary(const Vector2D& lpos) const final; + double distanceToBoundary(const Vector2D& lpos) const final; /// Output Method for std::ostream - std::ostream& - toStream(std::ostream& sl) const final; + std::ostream& toStream(std::ostream& sl) const final; /// This method returns inner radius - double - rMin() const; + double rMin() const; /// This method returns outer radius - double - rMax() const; + double rMax() const; /// This method returns the average phi - double - averagePhi() const; + double averagePhi() const; /// This method returns the center radius - double - rCenter() const; + double rCenter() const; /// This method returns the stereo angle - double - stereo() const; + double stereo() const; /// This method returns the halfPhiSector which is covered by the disc - double - halfPhiSector() const; + double halfPhiSector() const; /// This method returns the minimal halflength in X - double - minHalflengthX() const; + double minHalflengthX() const; /// This method returns the maximal halflength in X - double - maxHalflengthX() const; + double maxHalflengthX() const; /// This method returns the halflength in Y (this is Rmax -Rmin) - double - halflengthY() const; + double halflengthY() const; -private: + private: double m_rMin, m_rMax, m_minHalfX, m_maxHalfX, m_avgPhi; double m_stereo; // TODO 2017-04-09 msmk: what is this good for? - Vector2D - toLocalXY(const Vector2D& lpos) const; - ActsMatrixD<2, 2> - jacobianToLocalXY(const Vector2D& lpos) const; + Vector2D toLocalXY(const Vector2D& lpos) const; + ActsMatrixD<2, 2> jacobianToLocalXY(const Vector2D& lpos) const; }; -inline double -DiscTrapezoidalBounds::rMin() const -{ +inline double DiscTrapezoidalBounds::rMin() const { return m_rMin; } -inline double -DiscTrapezoidalBounds::rMax() const -{ +inline double DiscTrapezoidalBounds::rMax() const { return m_rMax; } -inline double -DiscTrapezoidalBounds::minHalflengthX() const -{ +inline double DiscTrapezoidalBounds::minHalflengthX() const { return m_minHalfX; } -inline double -DiscTrapezoidalBounds::maxHalflengthX() const -{ +inline double DiscTrapezoidalBounds::maxHalflengthX() const { return m_maxHalfX; } -inline double -DiscTrapezoidalBounds::averagePhi() const -{ +inline double DiscTrapezoidalBounds::averagePhi() const { return m_avgPhi; } -inline double -DiscTrapezoidalBounds::stereo() const -{ +inline double DiscTrapezoidalBounds::stereo() const { return m_stereo; } -inline double -DiscTrapezoidalBounds::halfPhiSector() const -{ +inline double DiscTrapezoidalBounds::halfPhiSector() const { auto minHalfPhi = std::asin(m_minHalfX / m_rMin); auto maxHalfPhi = std::asin(m_maxHalfX / m_rMax); return std::max(minHalfPhi, maxHalfPhi); } -inline double -DiscTrapezoidalBounds::rCenter() const -{ +inline double DiscTrapezoidalBounds::rCenter() const { auto hmin = std::sqrt(m_rMin * m_rMin - m_minHalfX * m_minHalfX); auto hmax = std::sqrt(m_rMax * m_rMax - m_maxHalfX * m_maxHalfX); return (hmin + hmax) / 2.0; } -inline double -DiscTrapezoidalBounds::halflengthY() const -{ +inline double DiscTrapezoidalBounds::halflengthY() const { auto hmin = std::sqrt(m_rMin * m_rMin - m_minHalfX * m_minHalfX); auto hmax = std::sqrt(m_rMax * m_rMax - m_maxHalfX * m_maxHalfX); return (hmax - hmin) / 2.0; diff --git a/Core/include/Acts/Surfaces/EllipseBounds.hpp b/Core/include/Acts/Surfaces/EllipseBounds.hpp index 468cf5631e853c48de0a0b4d5f6aa521c298b65d..a72d7ef461cc37be4ba47c2845116f6358bfeb98 100644 --- a/Core/include/Acts/Surfaces/EllipseBounds.hpp +++ b/Core/include/Acts/Surfaces/EllipseBounds.hpp @@ -29,18 +29,17 @@ namespace Acts { /// /// @image html EllipseBounds.png /// -class EllipseBounds : public PlanarBounds -{ -public: +class EllipseBounds : public PlanarBounds { + public: /// @brief constants for readability enum BoundValues { - bv_rMinX = 0, - bv_rMinY = 1, - bv_rMaxX = 2, - bv_rMaxY = 3, - bv_averagePhi = 4, + bv_rMinX = 0, + bv_rMinY = 1, + bv_rMaxX = 2, + bv_rMaxY = 3, + bv_averagePhi = 4, bv_halfPhiSector = 5, - bv_length = 6 + bv_length = 6 }; EllipseBounds() = delete; @@ -53,23 +52,17 @@ public: /// @param maxRadius1 is the minimum radius at coorindate 1 /// @param averagePhi average phi (is set to 0. as default) /// @param halfPhi spanning phi sector (is set to pi as default) - EllipseBounds(double minRadius0, - double minRadius1, - double maxRadius0, - double maxRadius1, - double averagePhi = 0., - double halfPhi = M_PI); + EllipseBounds(double minRadius0, double minRadius1, double maxRadius0, + double maxRadius1, double averagePhi = 0., + double halfPhi = M_PI); ~EllipseBounds() override; - EllipseBounds* - clone() const final; + EllipseBounds* clone() const final; - BoundsType - type() const final; + BoundsType type() const final; - std::vector<TDD_real_t> - valueStore() const final; + std::vector<TDD_real_t> valueStore() const final; /// This method checks if the point given in the local coordinates is between /// two ellipsoids if only tol0 is given and additional in the phi sector is @@ -78,91 +71,68 @@ public: /// @param lpos Local position (assumed to be in right surface frame) /// @param bcheck boundary check directive /// @return boolean indicator for the success of this operation - bool - inside(const Vector2D& lpos, const BoundaryCheck& bcheck) const final; + bool inside(const Vector2D& lpos, const BoundaryCheck& bcheck) const final; /// Minimal distance to boundary ( > 0 if outside and <=0 if inside) /// /// @param lpos is the local position to check for the distance /// @return is a signed distance parameter - double - distanceToBoundary(const Vector2D& lpos) const final; + double distanceToBoundary(const Vector2D& lpos) const final; /// Return the vertices - or, the points of the extremas - std::vector<Vector2D> - vertices() const final; + std::vector<Vector2D> vertices() const final; // Bounding box representation - const RectangleBounds& - boundingBox() const final; + const RectangleBounds& boundingBox() const final; /// Output Method for std::ostream - std::ostream& - toStream(std::ostream& sl) const final; + std::ostream& toStream(std::ostream& sl) const final; /// This method returns first inner radius - double - rMinX() const; + double rMinX() const; /// This method returns second inner radius - double - rMinY() const; + double rMinY() const; /// This method returns first outer radius - double - rMaxX() const; + double rMaxX() const; /// This method returns second outer radius - double - rMaxY() const; + double rMaxY() const; /// This method returns the average phi - double - averagePhi() const; + double averagePhi() const; /// This method returns the halfPhiSector which is covered by the disc - double - halfPhiSector() const; + double halfPhiSector() const; -private: - double m_rMinX, m_rMinY, m_rMaxX, m_rMaxY, m_avgPhi, m_halfPhi; + private: + double m_rMinX, m_rMinY, m_rMaxX, m_rMaxY, m_avgPhi, m_halfPhi; RectangleBounds m_boundingBox; }; -inline double -EllipseBounds::rMinX() const -{ +inline double EllipseBounds::rMinX() const { return m_rMinX; } -inline double -EllipseBounds::rMinY() const -{ +inline double EllipseBounds::rMinY() const { return m_rMinY; } -inline double -EllipseBounds::rMaxX() const -{ +inline double EllipseBounds::rMaxX() const { return m_rMaxX; } -inline double -EllipseBounds::rMaxY() const -{ +inline double EllipseBounds::rMaxY() const { return m_rMaxY; } -inline double -EllipseBounds::averagePhi() const -{ +inline double EllipseBounds::averagePhi() const { return m_avgPhi; } -inline double -EllipseBounds::halfPhiSector() const -{ +inline double EllipseBounds::halfPhiSector() const { return m_halfPhi; } -} // namespace \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Surfaces/InfiniteBounds.hpp b/Core/include/Acts/Surfaces/InfiniteBounds.hpp index 19323f8e68df2750defea3de7ed4a0d0e20faa46..94003792d17fd3e5f26c3319d0b0e2339091a958 100644 --- a/Core/include/Acts/Surfaces/InfiniteBounds.hpp +++ b/Core/include/Acts/Surfaces/InfiniteBounds.hpp @@ -21,54 +21,36 @@ namespace Acts { /// templated boundless extension to forward the interface /// Returns all inside checks to true and can templated for all bounds -class InfiniteBounds : public SurfaceBounds -{ -public: - InfiniteBounds() = default; +class InfiniteBounds : public SurfaceBounds { + public: + InfiniteBounds() = default; ~InfiniteBounds() override = default; - InfiniteBounds* - clone() const final - { - return new InfiniteBounds(); - } + InfiniteBounds* clone() const final { return new InfiniteBounds(); } - SurfaceBounds::BoundsType - type() const final - { + SurfaceBounds::BoundsType type() const final { return SurfaceBounds::Boundless; } - std::vector<TDD_real_t> - valueStore() const final - { - return {}; - } + std::vector<TDD_real_t> valueStore() const final { return {}; } /// Method inside() returns true for any case /// /// ignores input parameters /// /// @return always true - bool - inside(const Vector2D& /*lpos*/, const BoundaryCheck& /*bcheck*/) const final - { + bool inside(const Vector2D& /*lpos*/, + const BoundaryCheck& /*bcheck*/) const final { return true; } /// Minimal distance calculation /// ignores input parameter /// @return always 0. (should be -NaN) - double - distanceToBoundary(const Vector2D& /*pos*/) const final - { - return 0; - } + double distanceToBoundary(const Vector2D& /*pos*/) const final { return 0; } /// Output Method for std::ostream - std::ostream& - toStream(std::ostream& os) const final - { + std::ostream& toStream(std::ostream& os) const final { os << "Acts::InfiniteBounds ... boundless surface" << std::endl; return os; } diff --git a/Core/include/Acts/Surfaces/LineBounds.hpp b/Core/include/Acts/Surfaces/LineBounds.hpp index a9dfe928287f498d5a9c08ee908b9da0cd32dbb6..8f18034eebc9595273a31e37e322e89730a2e4ad 100644 --- a/Core/include/Acts/Surfaces/LineBounds.hpp +++ b/Core/include/Acts/Surfaces/LineBounds.hpp @@ -21,9 +21,8 @@ namespace Acts { /// Bounds for a LineSurface. /// -class LineBounds : public SurfaceBounds -{ -public: +class LineBounds : public SurfaceBounds { + public: /// @enum BoundValues for readablility /// nested enumeration object enum BoundValues { bv_radius = 0, bv_halfZ = 1, bv_length = 2 }; @@ -36,14 +35,11 @@ public: ~LineBounds() override; - LineBounds* - clone() const final; + LineBounds* clone() const final; - BoundsType - type() const final; + BoundsType type() const final; - std::vector<TDD_real_t> - valueStore() const final; + std::vector<TDD_real_t> valueStore() const final; /// Inside check for the bounds object driven by the boundary check directive /// Each Bounds has a method inside, which checks if a LocalPosition is inside @@ -53,45 +49,36 @@ public: /// @param bcheck boundary check directive /// /// @return boolean indicator for the success of this operation - bool - inside(const Vector2D& lpos, const BoundaryCheck& bcheck) const final; + bool inside(const Vector2D& lpos, const BoundaryCheck& bcheck) const final; /// Minimal distance to boundary ( > 0 if outside and <=0 if inside) /// /// @param lpos is the local position to check for the distance /// /// @return is a signed distance parameter - double - distanceToBoundary(const Vector2D& lpos) const final; + double distanceToBoundary(const Vector2D& lpos) const final; /// This method returns the radius - virtual double - r() const; + virtual double r() const; /// This method returns the halflengthZ - double - halflengthZ() const; + double halflengthZ() const; /// Output Method for std::ostream /// /// @param sl is the ostream to be dumped into - std::ostream& - toStream(std::ostream& sl) const final; + std::ostream& toStream(std::ostream& sl) const final; -private: + private: double m_radius, m_halfZ; }; -inline double -LineBounds::r() const -{ +inline double LineBounds::r() const { return m_radius; } -inline double -LineBounds::halflengthZ() const -{ +inline double LineBounds::halflengthZ() const { return m_halfZ; } -} // namespace \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Surfaces/LineSurface.hpp b/Core/include/Acts/Surfaces/LineSurface.hpp index 2fb00147280482ff2de0fc56928e5e8df275c272..8096ea9aacd52046c4fb7d29c049c70f759a9b78 100644 --- a/Core/include/Acts/Surfaces/LineSurface.hpp +++ b/Core/include/Acts/Surfaces/LineSurface.hpp @@ -31,21 +31,19 @@ class LineBounds; /// @note It leaves the type() method virtual, so it can not be instantiated /// /// @image html LineSurface.png -class LineSurface : public Surface -{ +class LineSurface : public Surface { friend Surface; LineSurface() = delete; -protected: + protected: /// Constructor from Transform3D and bounds /// /// @param htrans The transform that positions the surface in the global frame /// @param radius The straw radius /// @param halez The half length in z - LineSurface(std::shared_ptr<const Transform3D> htrans, - double radius, - double halez); + LineSurface(std::shared_ptr<const Transform3D> htrans, double radius, + double halez); /// Constructor from Transform3D and a shared bounds object /// @@ -53,14 +51,14 @@ protected: /// @param lbounds The bounds describing the straw dimensions, can be /// optionally nullptr LineSurface(std::shared_ptr<const Transform3D> htrans, - std::shared_ptr<const LineBounds> lbounds = nullptr); + std::shared_ptr<const LineBounds> lbounds = nullptr); /// Constructor from DetectorElementBase : Element proxy /// /// @param lbounds The bounds describing the straw dimensions /// @param detelement for which this surface is (at least) one representation LineSurface(const std::shared_ptr<const LineBounds>& lbounds, - const DetectorElementBase& detelement); + const DetectorElementBase& detelement); /// Copy constructor /// @@ -72,19 +70,17 @@ protected: /// @param gctx The current geometry context object, e.g. alignment /// @param other is the source cone surface /// @param transf is the additional transfrom applied after copying - LineSurface(const GeometryContext& gctx, - const LineSurface& other, - const Transform3D& transf); + LineSurface(const GeometryContext& gctx, const LineSurface& other, + const Transform3D& transf); -public: + public: /// Destructor - defaulted ~LineSurface() override = default; /// Assignment operator /// /// @param slsf is the source surface dor copying - LineSurface& - operator=(const LineSurface& other); + LineSurface& operator=(const LineSurface& other); /// Normal vector return /// @@ -92,8 +88,8 @@ public: /// @param lpos is the local position is ignored /// /// @return a Vector3D by value - const Vector3D - normal(const GeometryContext& gctx, const Vector2D& lpos) const final; + const Vector3D normal(const GeometryContext& gctx, + const Vector2D& lpos) const final; /// Normal vector return without argument using Surface::normal; @@ -105,8 +101,8 @@ public: /// @param bValue is the binning type to be used /// /// @return position that can beused for this binning - const Vector3D - binningPosition(const GeometryContext& gctx, BinningValue bValue) const final; + const Vector3D binningPosition(const GeometryContext& gctx, + BinningValue bValue) const final; /// Return the measurement frame - this is needed for alignment, in particular /// @@ -119,10 +115,9 @@ public: /// @param mom is the momentum used for the measurement frame construction /// /// @return is a rotation matrix that indicates the measurement frame - const RotationMatrix3D - referenceFrame(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& mom) const final; + const RotationMatrix3D referenceFrame(const GeometryContext& gctx, + const Vector3D& gpos, + const Vector3D& mom) const final; /// Initialize the jacobian from local to global /// the surface knows best, hence the calculation is done here. @@ -135,12 +130,10 @@ public: /// @param dir is the direction at of the parameters /// /// @param pars is the paranmeters vector - void - initJacobianToGlobal(const GeometryContext& gctx, - ActsMatrixD<7, 5>& jacobian, - const Vector3D& gpos, - const Vector3D& dir, - const ActsVectorD<5>& pars) const final; + void initJacobianToGlobal(const GeometryContext& gctx, + ActsMatrixD<7, 5>& jacobian, const Vector3D& gpos, + const Vector3D& dir, + const ActsVectorD<5>& pars) const final; /// Calculate the form factors for the derivatives /// the calculation is identical for all surfaces where the @@ -153,12 +146,9 @@ public: /// @param jac is the transport jacobian /// /// @return a five-dim vector - const ActsRowVectorD<5> - derivativeFactors(const GeometryContext& gctx, - const Vector3D& pos, - const Vector3D& dir, - const RotationMatrix3D& rft, - const ActsMatrixD<7, 5>& jac) const final; + const ActsRowVectorD<5> derivativeFactors( + const GeometryContext& gctx, const Vector3D& pos, const Vector3D& dir, + const RotationMatrix3D& rft, const ActsMatrixD<7, 5>& jac) const final; /// Local to global transformation /// for line surfaces the momentum is used in order to interpret the drift @@ -169,11 +159,8 @@ public: /// @param mom is the global momentum (used to sign the closest approach) /// /// @param gpos is the global position shich is filled - void - localToGlobal(const GeometryContext& gctx, - const Vector2D& lpos, - const Vector3D& mom, - Vector3D& gpos) const final; + void localToGlobal(const GeometryContext& gctx, const Vector2D& lpos, + const Vector3D& mom, Vector3D& gpos) const final; /// Specified for LineSurface: global to local method without dynamic /// memory allocation @@ -212,11 +199,8 @@ public: /// /// @return boolean indication if operation was successful (fail means global /// position was not on surface) - bool - globalToLocal(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& mom, - Vector2D& lpos) const final; + bool globalToLocal(const GeometryContext& gctx, const Vector3D& gpos, + const Vector3D& mom, Vector2D& lpos) const final; /// @brief Straight line intersection schema /// @@ -256,47 +240,38 @@ public: /// e_a)(\vec e_a \cdot \vec e_b)}{1-(\vec e_a \cdot \vec e_b)^2} @f$ <br> /// /// @return is the intersection object - Intersection - intersectionEstimate(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& gdir, - NavigationDirection navDir = forward, - const BoundaryCheck& bcheck = false, - CorrFnc correct = nullptr) const final; + Intersection intersectionEstimate(const GeometryContext& gctx, + const Vector3D& gpos, const Vector3D& gdir, + NavigationDirection navDir = forward, + const BoundaryCheck& bcheck = false, + CorrFnc correct = nullptr) const final; /// the pathCorrection for derived classes with thickness /// is by definition 1 for LineSurfaces /// /// @note input parameters are ignored /// @note there's no material associated to the line surface - double - pathCorrection(const GeometryContext& gctx, - const Vector3D& pos, - const Vector3D& mom) const override; + double pathCorrection(const GeometryContext& gctx, const Vector3D& pos, + const Vector3D& mom) const override; /// This method returns the bounds of the Surface by reference */ - const SurfaceBounds& - bounds() const final; + const SurfaceBounds& bounds() const final; /// Return properly formatted class name for screen output */ - std::string - name() const override; + std::string name() const override; -protected: + protected: std::shared_ptr<const LineBounds> m_bounds; ///< bounds (shared) -private: + private: /// helper function to apply the globalToLocal with out transform /// /// @param gctx The current geometry context object, e.g. alignment /// @param pos is the global position /// @param mom is the momentum /// @param lpos is the local position to be filled - bool - globalToLocalPlain(const GeometryContext& gctx, - const Vector3D& pos, - const Vector3D& mom, - Vector2D& lpos) const; + bool globalToLocalPlain(const GeometryContext& gctx, const Vector3D& pos, + const Vector3D& mom, Vector2D& lpos) const; }; #include "Acts/Surfaces/detail/LineSurface.ipp" diff --git a/Core/include/Acts/Surfaces/PerigeeSurface.hpp b/Core/include/Acts/Surfaces/PerigeeSurface.hpp index 220ebbf8bb44d63b99ead43e29f1dc529a31dfd0..7e6688b06079875e27299bac3e25f7932d45cbc0 100644 --- a/Core/include/Acts/Surfaces/PerigeeSurface.hpp +++ b/Core/include/Acts/Surfaces/PerigeeSurface.hpp @@ -25,13 +25,12 @@ namespace Acts { /// It inherits from StraingLineSurface. /// /// @image html LineSurface.png -class PerigeeSurface : public LineSurface -{ +class PerigeeSurface : public LineSurface { friend Surface; PerigeeSurface() = delete; -protected: + protected: /// Constructor from GlobalPosition /// /// @param gp position where the perigee is centered @@ -52,11 +51,10 @@ protected: /// @param gctx The current geometry context object, e.g. alignment /// @param other is the source cone surface /// @param transf is the additional transfrom applied after copying - PerigeeSurface(const GeometryContext& gctx, - const PerigeeSurface& other, - const Transform3D& transf); + PerigeeSurface(const GeometryContext& gctx, const PerigeeSurface& other, + const Transform3D& transf); -public: + public: /// Destructor - defaulted ~PerigeeSurface() override = default; @@ -64,22 +62,19 @@ public: /// /// @param gctx The current geometry context object, e.g. alignment /// @param shift applied to the surface - std::shared_ptr<PerigeeSurface> - clone(const GeometryContext& gctx, const Transform3D& shift) const; + std::shared_ptr<PerigeeSurface> clone(const GeometryContext& gctx, + const Transform3D& shift) const; /// Assignment operator /// /// @param other is the source surface to be assigned - PerigeeSurface& - operator=(const PerigeeSurface& other); + PerigeeSurface& operator=(const PerigeeSurface& other); /// Return the surface type - SurfaceType - type() const final; + SurfaceType type() const final; /// Return properly formatted class name for screen output */ - std::string - name() const final; + std::string name() const final; /// Output Method for std::ostream /// @@ -87,17 +82,16 @@ public: /// @param sl is the ostream to be dumped into /// /// @return ostreamn obect which was streamed into - std::ostream& - toStream(const GeometryContext& gctx, std::ostream& sl) const final; + std::ostream& toStream(const GeometryContext& gctx, + std::ostream& sl) const final; -private: + private: /// Clone method implementation /// /// @param gctx The current geometry context object, e.g. alignment /// @param shift applied to the surface - PerigeeSurface* - clone_impl(const GeometryContext& gctx, - const Transform3D& shift) const override; + PerigeeSurface* clone_impl(const GeometryContext& gctx, + const Transform3D& shift) const override; }; } // namespace Acts diff --git a/Core/include/Acts/Surfaces/PlanarBounds.hpp b/Core/include/Acts/Surfaces/PlanarBounds.hpp index 577fdf0f40567a392148c649d2fdfe27d79869ad..aeb693f4aec8467a03e4a43d14cd68a41ee5e265 100644 --- a/Core/include/Acts/Surfaces/PlanarBounds.hpp +++ b/Core/include/Acts/Surfaces/PlanarBounds.hpp @@ -25,16 +25,13 @@ class RectangleBounds; /// common base class for all bounds that are in a local x/y cartesian frame /// - simply introduced to avoid wrong bound assigments to surfaces /// -class PlanarBounds : public SurfaceBounds -{ -public: +class PlanarBounds : public SurfaceBounds { + public: /// Return the vertices - or, the points of the extremas - virtual std::vector<Vector2D> - vertices() const = 0; + virtual std::vector<Vector2D> vertices() const = 0; // Bounding box parameters - virtual const RectangleBounds& - boundingBox() const = 0; + virtual const RectangleBounds& boundingBox() const = 0; }; -} // namespace \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Surfaces/PlaneSurface.hpp b/Core/include/Acts/Surfaces/PlaneSurface.hpp index bda29eb35511d35229411714286b58172921b9e0..22b9a8f1571219c205b07523499c50a4a6ced751 100644 --- a/Core/include/Acts/Surfaces/PlaneSurface.hpp +++ b/Core/include/Acts/Surfaces/PlaneSurface.hpp @@ -33,11 +33,10 @@ class DetectorElementBase; /// /// @image html PlaneSurface.png /// -class PlaneSurface : public Surface -{ +class PlaneSurface : public Surface { friend Surface; -protected: + protected: /// Default Constructor - needed for persistency PlaneSurface(); @@ -51,9 +50,8 @@ protected: /// @param gctx The current geometry context object, e.g. alignment /// @param other is the source cone surface /// @param transf is the additional transfrom applied after copying - PlaneSurface(const GeometryContext& gctx, - const PlaneSurface& other, - const Transform3D& transf); + PlaneSurface(const GeometryContext& gctx, const PlaneSurface& other, + const Transform3D& transf); /// Dedicated Constructor with normal vector /// This is for curvilinear surfaces which are by definition boundless @@ -67,31 +65,30 @@ protected: /// @param pbounds are the provided planar bounds (shared) /// @param detelement is the linked detector element to this surface PlaneSurface(const std::shared_ptr<const PlanarBounds>& pbounds, - const DetectorElementBase& detelement); + const DetectorElementBase& detelement); /// Constructor for Planes with (optional) shared bounds object /// /// @param htrans transform in 3D that positions this surface /// @param pbounds bounds object to describe the actual surface area - PlaneSurface(std::shared_ptr<const Transform3D> htrans, + PlaneSurface(std::shared_ptr<const Transform3D> htrans, std::shared_ptr<const PlanarBounds> pbounds = nullptr); -public: + public: /// Destructor - defaulted ~PlaneSurface() override = default; /// Assignment operator /// /// @param other The source PlaneSurface for assignment - PlaneSurface& - operator=(const PlaneSurface& other); + PlaneSurface& operator=(const PlaneSurface& other); /// Clone method into a concrete type of PlaneSurface with shift /// /// @param gctx The current geometry context object, e.g. alignment /// @param shift applied to the surface - std::shared_ptr<PlaneSurface> - clone(const GeometryContext& gctx, const Transform3D& shift) const; + std::shared_ptr<PlaneSurface> clone(const GeometryContext& gctx, + const Transform3D& shift) const; /// Normal vector return /// @@ -99,8 +96,8 @@ public: /// @param lpos is the local position is ignored /// /// return a Vector3D by value - const Vector3D - normal(const GeometryContext& gctx, const Vector2D& lpos) const final; + const Vector3D normal(const GeometryContext& gctx, + const Vector2D& lpos) const final; /// Normal vector return without argument using Surface::normal; @@ -112,16 +109,14 @@ public: /// @param bValue is the binning type to be used /// /// @return position that can beused for this binning - const Vector3D - binningPosition(const GeometryContext& gctx, BinningValue bValue) const final; + const Vector3D binningPosition(const GeometryContext& gctx, + BinningValue bValue) const final; /// Return the surface type - SurfaceType - type() const override; + SurfaceType type() const override; /// Return method for bounds object of this surfrace - const SurfaceBounds& - bounds() const override; + const SurfaceBounds& bounds() const override; /// Local to global transformation /// For planar surfaces the momentum is ignroed in the local to global @@ -132,11 +127,8 @@ public: /// @param mom global 3D momentum representation (optionally ignored) /// @param gpos global 3D position to be filled (given by reference for method /// symmetry) - void - localToGlobal(const GeometryContext& gctx, - const Vector2D& lpos, - const Vector3D& mom, - Vector3D& gpos) const override; + void localToGlobal(const GeometryContext& gctx, const Vector2D& lpos, + const Vector3D& mom, Vector3D& gpos) const override; /// Global to local transformation /// For planar surfaces the momentum is ignroed in the global to local @@ -151,11 +143,8 @@ public: /// /// @return boolean indication if operation was successful (fail means global /// position was not on surface) - bool - globalToLocal(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& mom, - Vector2D& lpos) const override; + bool globalToLocal(const GeometryContext& gctx, const Vector3D& gpos, + const Vector3D& mom, Vector2D& lpos) const override; /// Method that calculates the correction due to incident angle /// @@ -166,10 +155,8 @@ public: /// @note this is the final implementation of the pathCorrection function /// /// @return a double representing the scaling factor - double - pathCorrection(const GeometryContext& gctx, - const Vector3D& pos, - const Vector3D& mom) const final; + double pathCorrection(const GeometryContext& gctx, const Vector3D& pos, + const Vector3D& mom) const final; /// @brief Straight line intersection schema /// @@ -199,30 +186,26 @@ public: /// - perpendicular to the normal of the plane /// /// @return the Intersection object - Intersection - intersectionEstimate(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& gdir, - NavigationDirection navDir = forward, - const BoundaryCheck& bcheck = false, - CorrFnc correct = nullptr) const final; + Intersection intersectionEstimate(const GeometryContext& gctx, + const Vector3D& gpos, const Vector3D& gdir, + NavigationDirection navDir = forward, + const BoundaryCheck& bcheck = false, + CorrFnc correct = nullptr) const final; /// Return properly formatted class name for screen output - std::string - name() const override; + std::string name() const override; -protected: + protected: /// the bounds of this surface std::shared_ptr<const PlanarBounds> m_bounds; -private: + private: /// Clone method implementation /// /// @param gctx The current geometry context object, e.g. alignment /// @param shift applied to the surface - PlaneSurface* - clone_impl(const GeometryContext& gctx, - const Transform3D& shift) const override; + PlaneSurface* clone_impl(const GeometryContext& gctx, + const Transform3D& shift) const override; }; #include "Acts/Surfaces/detail/PlaneSurface.ipp" diff --git a/Core/include/Acts/Surfaces/PolyhedronRepresentation.hpp b/Core/include/Acts/Surfaces/PolyhedronRepresentation.hpp index 38710e2608282a4ef44fc25bb11aafff95b5ee02..607ad7f573c8c94bec01158ea8c77139c3a9b647 100644 --- a/Core/include/Acts/Surfaces/PolyhedronRepresentation.hpp +++ b/Core/include/Acts/Surfaces/PolyhedronRepresentation.hpp @@ -23,18 +23,14 @@ namespace Acts { /// Each entry in @c faces is a face, which is in turn a list of vertices /// that need to be connected to form a face. /// This allows the @c objString method to produce a ready-to-go obj output. -struct PolyhedronRepresentation -{ - +struct PolyhedronRepresentation { /// Default constructor from a vector of vertices and a vector of faces /// @param verticesIn The 3D global vertices that make up the object /// @param facesIn List of lists of indices for faces. /// @note This creates copies of the input vectors - PolyhedronRepresentation(const std::vector<Vector3D>& verticesIn, + PolyhedronRepresentation(const std::vector<Vector3D>& verticesIn, const std::vector<std::vector<size_t>>& facesIn) - : vertices(verticesIn), faces(facesIn) - { - } + : vertices(verticesIn), faces(facesIn) {} /// list of 3D vertices as vectors std::vector<Vector3D> vertices; @@ -48,13 +44,10 @@ struct PolyhedronRepresentation /// @param vtxOffset Optional obj vertex enumeration offset /// @note Vertices in obj are enumerated globally. The offset is required /// to allow for multiple output objects in one obj file. - std::string - objString(size_t vtxOffset = 0) const; + std::string objString(size_t vtxOffset = 0) const; template <typename helper_t> - void - draw(helper_t& helper) const - { + void draw(helper_t& helper) const { for (const auto& face : faces) { std::vector<Vector3D> face_vtx; for (size_t i : face) { @@ -64,4 +57,4 @@ struct PolyhedronRepresentation } } }; -} +} // namespace Acts diff --git a/Core/include/Acts/Surfaces/RadialBounds.hpp b/Core/include/Acts/Surfaces/RadialBounds.hpp index 3bc3a8d8c635f8c4a816bbff86479d2e603c2a8f..83e2c7a9596f271cf4e57178589cb604def601bc 100644 --- a/Core/include/Acts/Surfaces/RadialBounds.hpp +++ b/Core/include/Acts/Surfaces/RadialBounds.hpp @@ -28,16 +28,15 @@ namespace Acts { /// /// @image html RadialBounds.gif -class RadialBounds : public DiscBounds -{ -public: +class RadialBounds : public DiscBounds { + public: /// enumeration for readability enum BoundValues { - bv_rMin = 0, - bv_rMax = 1, - bv_averagePhi = 2, + bv_rMin = 0, + bv_rMax = 1, + bv_averagePhi = 2, bv_halfPhiSector = 3, - bv_length = 4 + bv_length = 4 }; RadialBounds(); @@ -61,14 +60,11 @@ public: ~RadialBounds() override; - RadialBounds* - clone() const final; + RadialBounds* clone() const final; - SurfaceBounds::BoundsType - type() const final; + SurfaceBounds::BoundsType type() const final; - std::vector<TDD_real_t> - valueStore() const final; + std::vector<TDD_real_t> valueStore() const final; /// For disc surfaces the local position in (r,phi) is checked /// @@ -76,69 +72,53 @@ public: /// @param bcheck boundary check directive /// /// @return is a boolean indicating the operation success - bool - inside(const Vector2D& lpos, const BoundaryCheck& bcheck) const final; + bool inside(const Vector2D& lpos, const BoundaryCheck& bcheck) const final; /// Minimal distance to boundary calculation /// /// @param lpos local 2D position in surface coordinate frame /// /// @return distance to boundary ( > 0 if outside and <=0 if inside) - double - distanceToBoundary(const Vector2D& lpos) const final; + double distanceToBoundary(const Vector2D& lpos) const final; /// Outstream operator /// /// @param sl is the ostream to be dumped into - std::ostream& - toStream(std::ostream& sl) const final; + std::ostream& toStream(std::ostream& sl) const final; /// Return method for inner Radius - double - rMin() const; + double rMin() const; /// Return method for outer Radius - double - rMax() const; + double rMax() const; /// Return method for the central phi value ///(i.e. phi value of x-axis of local 3D frame) - double - averagePhi() const; + double averagePhi() const; /// Return method for the half phi span - double - halfPhiSector() const; + double halfPhiSector() const; -private: + private: double m_rMin, m_rMax, m_avgPhi, m_halfPhi; - Vector2D - shifted(const Vector2D& lpos) const; + Vector2D shifted(const Vector2D& lpos) const; }; -inline double -RadialBounds::rMin() const -{ +inline double RadialBounds::rMin() const { return m_rMin; } -inline double -RadialBounds::rMax() const -{ +inline double RadialBounds::rMax() const { return m_rMax; } -inline double -RadialBounds::averagePhi() const -{ +inline double RadialBounds::averagePhi() const { return m_avgPhi; } -inline double -RadialBounds::halfPhiSector() const -{ +inline double RadialBounds::halfPhiSector() const { return m_halfPhi; } -} // namespace \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Surfaces/RectangleBounds.hpp b/Core/include/Acts/Surfaces/RectangleBounds.hpp index 82073b610145ad2a01254d424157633aa8c68fc8..4b4fdf31f73b1f5c61dec29c007178b91b7531e0 100644 --- a/Core/include/Acts/Surfaces/RectangleBounds.hpp +++ b/Core/include/Acts/Surfaces/RectangleBounds.hpp @@ -26,9 +26,8 @@ namespace Acts { /// /// @image html RectangularBounds.gif -class RectangleBounds : public PlanarBounds -{ -public: +class RectangleBounds : public PlanarBounds { + public: /// @enum BoundValues for readability enum BoundValues { bv_halfX = 0, bv_halfY = 1, bv_length = 2 }; @@ -48,14 +47,11 @@ public: ~RectangleBounds() override = default; - RectangleBounds* - clone() const final; + RectangleBounds* clone() const final; - BoundsType - type() const final; + BoundsType type() const final; - std::vector<TDD_real_t> - valueStore() const final; + std::vector<TDD_real_t> valueStore() const final; /// Inside check for the bounds object driven by the boundary check directive /// Each Bounds has a method inside, which checks if a LocalPosition is inside @@ -64,80 +60,61 @@ public: /// @param lpos Local position (assumed to be in right surface frame) /// @param bcheck boundary check directive /// @return boolean indicator for the success of this operation - bool - inside(const Vector2D& lpos, const BoundaryCheck& bcheck) const final; + bool inside(const Vector2D& lpos, const BoundaryCheck& bcheck) const final; /// Minimal distance to boundary ( > 0 if outside and <=0 if inside) /// /// @param lpos is the local position to check for the distance /// @return is a signed distance parameter - double - distanceToBoundary(const Vector2D& lpos) const final; + double distanceToBoundary(const Vector2D& lpos) const final; /// Return the vertices - or, the points of the extremas - std::vector<Vector2D> - vertices() const final; + std::vector<Vector2D> vertices() const final; // Bounding box representation - const RectangleBounds& - boundingBox() const final; + const RectangleBounds& boundingBox() const final; /// Output Method for std::ostream /// /// @param sl is the ostream for the dump - std::ostream& - toStream(std::ostream& sl) const final; + std::ostream& toStream(std::ostream& sl) const final; /// Return method for the half length in X - double - halflengthX() const; + double halflengthX() const; /// Return method for the half length in Y - double - halflengthY() const; + double halflengthY() const; /// Get the min vertex defining the bounds /// @return The min vertex - const Vector2D& - min() const; + const Vector2D& min() const; /// Get the max vertex defining the bounds /// @return The max vertex - const Vector2D& - max() const; + const Vector2D& max() const; -private: + private: Vector2D m_min; Vector2D m_max; }; -inline double -RectangleBounds::halflengthX() const -{ +inline double RectangleBounds::halflengthX() const { return std::abs(m_max.x() - m_min.x()) * 0.5; } -inline double -RectangleBounds::halflengthY() const -{ +inline double RectangleBounds::halflengthY() const { return std::abs(m_max.y() - m_min.y()) * 0.5; } -inline SurfaceBounds::BoundsType -RectangleBounds::type() const -{ +inline SurfaceBounds::BoundsType RectangleBounds::type() const { return SurfaceBounds::Rectangle; } -inline const Vector2D& -RectangleBounds::min() const -{ +inline const Vector2D& RectangleBounds::min() const { return m_min; } -inline const Vector2D& -RectangleBounds::max() const -{ +inline const Vector2D& RectangleBounds::max() const { return m_max; } diff --git a/Core/include/Acts/Surfaces/StrawSurface.hpp b/Core/include/Acts/Surfaces/StrawSurface.hpp index 8055b590b078c74746b873e0d5ac1d7538b5f8dd..8c9272d5668bb72bad8a5102d6a2c02ccf46e2a2 100644 --- a/Core/include/Acts/Surfaces/StrawSurface.hpp +++ b/Core/include/Acts/Surfaces/StrawSurface.hpp @@ -29,23 +29,21 @@ struct PolyhedronRepresentation; /// /// @image html LineSurface.png /// -class StrawSurface : public LineSurface -{ +class StrawSurface : public LineSurface { friend Surface; /// Default Constructor - deleted StrawSurface() = delete; -protected: + protected: /// Constructor from Transform3D and bounds /// /// @param htrans is the transform that positions the surface in the global /// frame /// @param radius is the straw radius /// @param halez is the half length in z - StrawSurface(std::shared_ptr<const Transform3D> htrans, - double radius, - double halez); + StrawSurface(std::shared_ptr<const Transform3D> htrans, double radius, + double halez); /// Constructor from Transform3D and a shared bounds object /// @@ -54,7 +52,7 @@ protected: /// @param lbounds are the bounds describing the straw dimensions, can be /// optionally nullptr StrawSurface(std::shared_ptr<const Transform3D> htrans, - std::shared_ptr<const LineBounds> lbounds = nullptr); + std::shared_ptr<const LineBounds> lbounds = nullptr); /// Constructor from DetectorElementBase : Element proxy /// @@ -62,7 +60,7 @@ protected: /// not be nullptr /// @param detelement for which this surface is (at least) one representation StrawSurface(const std::shared_ptr<const LineBounds>& lbounds, - const DetectorElementBase& detelement); + const DetectorElementBase& detelement); /// Copy constructor /// @@ -74,63 +72,52 @@ protected: /// @param gctx The current geometry context object, e.g. alignment /// @param other is the source cone surface /// @param transf is the additional transfrom applied after copying - StrawSurface(const GeometryContext& gctx, - const StrawSurface& other, - const Transform3D& transf); + StrawSurface(const GeometryContext& gctx, const StrawSurface& other, + const Transform3D& transf); -public: + public: /// Destructor - defaulted ~StrawSurface() override = default; /// Assignment operator /// /// @param other is the source surface for copying - StrawSurface& - operator=(const StrawSurface& other); + StrawSurface& operator=(const StrawSurface& other); /// Clone method into a concrete type of StrawSurface with shift /// /// @param gctx The current geometry context object, e.g. alignment /// @param shift applied to the surface - std::shared_ptr<StrawSurface> - clone(const GeometryContext& gctx, const Transform3D& shift) const; + std::shared_ptr<StrawSurface> clone(const GeometryContext& gctx, + const Transform3D& shift) const; /// Return the surface type - SurfaceType - type() const final; + SurfaceType type() const final; /// Return properly formatted class name for screen output */ - std::string - name() const final; + std::string name() const final; /// Return a PolyhedronRepresentation for this object /// @param gctx The current geometry context object, e.g. alignment /// @param l0div Number of divisions along l0 (phi) /// @param l1div Number of divisions along l1 (z) - virtual PolyhedronRepresentation - polyhedronRepresentation(const GeometryContext& gctx, - size_t l0div = 10, - size_t l1div = 1) const; + virtual PolyhedronRepresentation polyhedronRepresentation( + const GeometryContext& gctx, size_t l0div = 10, size_t l1div = 1) const; -private: + private: /// Clone method implementation /// /// @param gctx The current geometry context object, e.g. alignment /// @param shift applied to the surface - StrawSurface* - clone_impl(const GeometryContext& gctx, - const Transform3D& shift) const override; + StrawSurface* clone_impl(const GeometryContext& gctx, + const Transform3D& shift) const override; }; -inline Surface::SurfaceType -StrawSurface::type() const -{ +inline Surface::SurfaceType StrawSurface::type() const { return Surface::Straw; } -inline std::string -Acts::StrawSurface::name() const -{ +inline std::string Acts::StrawSurface::name() const { return "Acts::StrawSurface"; } diff --git a/Core/include/Acts/Surfaces/Surface.hpp b/Core/include/Acts/Surfaces/Surface.hpp index 6df109b4979e92eddf2bde02363cb1941090631c..d4d5b3c0359432bab536d289f2de3716e3e647fb 100644 --- a/Core/include/Acts/Surfaces/Surface.hpp +++ b/Core/include/Acts/Surfaces/Surface.hpp @@ -45,28 +45,27 @@ class TrackingVolume; /// in which case they are not copied within the data model objects. /// class Surface : public virtual GeometryObject, - public std::enable_shared_from_this<Surface> -{ -public: + public std::enable_shared_from_this<Surface> { + public: /// @enum SurfaceType /// /// This enumerator simplifies the persistency & calculations, /// by saving a dynamic_cast, e.g. for persistency enum SurfaceType { - Cone = 0, - Cylinder = 1, - Disc = 2, - Perigee = 3, - Plane = 4, - Straw = 5, + Cone = 0, + Cylinder = 1, + Disc = 2, + Perigee = 3, + Plane = 4, + Straw = 5, Curvilinear = 6, - Other = 7 + Other = 7 }; /// Typedef of the surface intersection using SurfaceIntersection = ObjectIntersection<Surface>; -protected: + protected: /// Constructor with Transform3D as a shared object /// /// @param tform Transform3D positions the surface in 3D global space @@ -94,11 +93,10 @@ protected: /// @param gctx The current geometry context object, e.g. alignment /// @param other Source surface for copy /// @param shift Additional transform applied after copying from the source - Surface(const GeometryContext& gctx, - const Surface& other, - const Transform3D& shift); + Surface(const GeometryContext& gctx, const Surface& other, + const Transform3D& shift); -public: + public: /// Destructor virtual ~Surface(); @@ -106,9 +104,7 @@ public: /// Will forward all parameters and will attempt to find a suitable /// constructor. template <class T, typename... Args> - static std::shared_ptr<T> - makeShared(Args&&... args) - { + static std::shared_ptr<T> makeShared(Args&&... args) { return std::shared_ptr<T>(new T(std::forward<Args>(args)...)); } @@ -121,8 +117,7 @@ public: /// @note Only call this if you need shared ownership of this object. /// /// @return The shared pointer - std::shared_ptr<Surface> - getSharedPtr(); + std::shared_ptr<Surface> getSharedPtr(); /// Retrieve a @c std::shared_ptr for this surface (const version) /// @@ -133,16 +128,14 @@ public: /// @note Only call this if you need shared ownership of this object. /// /// @return The shared pointer - std::shared_ptr<const Surface> - getSharedPtr() const; + std::shared_ptr<const Surface> getSharedPtr() const; /// Assignment operator /// @note copy construction invalidates the association /// to detector element and layer /// /// @param other Source surface for the assignment - Surface& - operator=(const Surface& other); + Surface& operator=(const Surface& other); /// Comparison (equality) operator /// The strategy for comparison is @@ -152,39 +145,35 @@ public: /// (d) then transform comparison /// /// @param other source surface for the comparison - virtual bool - operator==(const Surface& other) const; + virtual bool operator==(const Surface& other) const; /// Comparison (non-equality) operator /// /// @param sf Source surface for the comparison - virtual bool - operator!=(const Surface& sf) const; + virtual bool operator!=(const Surface& sf) const; /// Clone method with shift - cloning without shift is not sensible /// /// @param gctx The current geometry context object, e.g. alignment /// @param shift applied to the surface - std::shared_ptr<Surface> - clone(const GeometryContext& gctx, const Transform3D& shift) const - { + std::shared_ptr<Surface> clone(const GeometryContext& gctx, + const Transform3D& shift) const { return std::shared_ptr<Surface>(this->clone_impl(gctx, shift)); } -private: + private: /// Implementation method for clone. Returns a bare pointer that is /// wrapped into a shared pointer by ::clone(). This is needed for /// covariant overload of this method. /// /// @param gctx The current geometry context object, e.g. alignment /// @param shift applied to the surface - virtual Surface* - clone_impl(const GeometryContext& gctx, const Transform3D& shift) const = 0; + virtual Surface* clone_impl(const GeometryContext& gctx, + const Transform3D& shift) const = 0; -public: + public: /// Return method for the Surface type to avoid dynamic casts - virtual SurfaceType - type() const = 0; + virtual SurfaceType type() const = 0; /// Return method for the surface Transform3D by reference /// In case a detector element is associated the surface transform @@ -194,8 +183,7 @@ public: /// @param gctx The current geometry context object, e.g. alignment /// /// @return the contextual transform - virtual const Transform3D& - transform(const GeometryContext& gctx) const; + virtual const Transform3D& transform(const GeometryContext& gctx) const; /// Return method for the surface center by reference /// @note the center is always recalculated in order to not keep a cache @@ -203,8 +191,7 @@ public: /// @param gctx The current geometry context object, e.g. alignment /// /// @return center position by value - virtual const Vector3D - center(const GeometryContext& gctx) const; + virtual const Vector3D center(const GeometryContext& gctx) const; /// Return method for the normal vector of the surface /// The normal vector can only be generally defined at a given local position @@ -214,8 +201,8 @@ public: /// @param lpos is the local position where the normal verctor is constructed /// /// @return normal vector by value - virtual const Vector3D - normal(const GeometryContext& gctx, const Vector2D& lpos) const = 0; + virtual const Vector3D normal(const GeometryContext& gctx, + const Vector2D& lpos) const = 0; /// Return method for the normal vector of the surface /// The normal vector can only be generally defined at a given local position @@ -226,8 +213,8 @@ public: /// /// @return normal vector by value - virtual const Vector3D - normal(const GeometryContext& gctx, const Vector3D& pos) const; + virtual const Vector3D normal(const GeometryContext& gctx, + const Vector3D& pos) const; /// Return method for the normal vector of the surface /// @@ -236,39 +223,32 @@ public: /// @param gctx The current geometry context object, e.g. alignment // /// @return normal vector by value - virtual const Vector3D - normal(const GeometryContext& gctx) const - { + virtual const Vector3D normal(const GeometryContext& gctx) const { return normal(gctx, center(gctx)); } /// Return method for SurfaceBounds /// @return SurfaceBounds by reference - virtual const SurfaceBounds& - bounds() const = 0; + virtual const SurfaceBounds& bounds() const = 0; /// Return method for the associated Detector Element /// @return plain pointer to the DetectorElement, can be nullptr - const DetectorElementBase* - associatedDetectorElement() const; + const DetectorElementBase* associatedDetectorElement() const; /// Return method for the associated Layer in which the surface is embedded /// @return Layer by plain pointer, can be nullptr - const Layer* - associatedLayer() const; + const Layer* associatedLayer() const; /// Set Associated Layer /// Many surfaces can be associated to a Layer, but it might not be known yet /// during construction of the layer, this can be set afterwards /// /// @param lay the assignment Layer by reference - void - associateLayer(const Layer& lay); + void associateLayer(const Layer& lay); /// Return method for the associated Material to this surface /// @return SurfaceMaterial as plain pointer, can be nullptr - const ISurfaceMaterial* - surfaceMaterial() const; + const ISurfaceMaterial* surfaceMaterial() const; /// Assign the surface material description /// @@ -277,8 +257,7 @@ public: /// this is provided by a shared pointer /// /// @param material Material description associated to this surface - void - assignSurfaceMaterial(std::shared_ptr<const ISurfaceMaterial> material); + void assignSurfaceMaterial(std::shared_ptr<const ISurfaceMaterial> material); /// The templated Parameters onSurface method /// In order to avoid unneccessary geometrical operations, it checks on the @@ -293,10 +272,8 @@ public: /// /// @return boolean indication if operation was successful template <typename parameters_t> - bool - isOnSurface(const GeometryContext& gctx, - const parameters_t& pars, - const BoundaryCheck& bcheck = true) const; + bool isOnSurface(const GeometryContext& gctx, const parameters_t& pars, + const BoundaryCheck& bcheck = true) const; /// The geometric onSurface method /// @@ -308,20 +285,17 @@ public: /// @param bcheck BoundaryCheck directive for this onSurface check /// /// @return boolean indication if operation was successful - bool - isOnSurface(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& gmom, - const BoundaryCheck& bcheck = true) const; + bool isOnSurface(const GeometryContext& gctx, const Vector3D& gpos, + const Vector3D& gmom, + const BoundaryCheck& bcheck = true) const; /// The insideBounds method for local positions /// /// @param locpos local position to check /// @param bcheck BoundaryCheck directive for this onSurface check /// @return boolean indication if operation was successful - virtual bool - insideBounds(const Vector2D& locpos, - const BoundaryCheck& bcheck = true) const; + virtual bool insideBounds(const Vector2D& locpos, + const BoundaryCheck& bcheck = true) const; /// Local to global transformation /// Generalized local to global transformation for the surface types. Since @@ -333,11 +307,8 @@ public: /// @param gmom global 3D momentum representation (optionally ignored) /// @param gpos global 3D position to be filled (given by reference for method /// symmetry) - virtual void - localToGlobal(const GeometryContext& gctx, - const Vector2D& lpos, - const Vector3D& gmom, - Vector3D& gpos) const = 0; + virtual void localToGlobal(const GeometryContext& gctx, const Vector2D& lpos, + const Vector3D& gmom, Vector3D& gpos) const = 0; /// Global to local transformation /// Generalized global to local transformation for the surface types. Since @@ -353,11 +324,8 @@ public: /// /// @return boolean indication if operation was successful (fail means global /// position was not on surface) - virtual bool - globalToLocal(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& gmom, - Vector2D& lpos) const = 0; + virtual bool globalToLocal(const GeometryContext& gctx, const Vector3D& gpos, + const Vector3D& gmom, Vector2D& lpos) const = 0; /// Return mehtod for the reference frame /// This is the frame in which the covariance matrix is defined (specialized @@ -370,10 +338,9 @@ public: /// /// @return RotationMatrix3D which defines the three axes of the measurement /// frame - virtual const Acts::RotationMatrix3D - referenceFrame(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& gmom) const; + virtual const Acts::RotationMatrix3D referenceFrame( + const GeometryContext& gctx, const Vector3D& gpos, + const Vector3D& gmom) const; /// Initialize the jacobian from local to global /// the surface knows best, hence the calculation is done here. @@ -389,12 +356,10 @@ public: /// @param gpos is the global position of the parameters /// @param dir is the direction at of the parameters /// @param pars is the parameter vector - virtual void - initJacobianToGlobal(const GeometryContext& gctx, - ActsMatrixD<7, 5>& jacobian, - const Vector3D& gpos, - const Vector3D& dir, - const ActsVectorD<5>& pars) const; + virtual void initJacobianToGlobal(const GeometryContext& gctx, + ActsMatrixD<7, 5>& jacobian, + const Vector3D& gpos, const Vector3D& dir, + const ActsVectorD<5>& pars) const; /// Initialize the jacobian from global to local /// the surface knows best, hence the calculation is done here. @@ -411,11 +376,9 @@ public: /// @param gctx The current geometry context object, e.g. alignment /// /// @return the transposed reference frame (avoids recalculation) - virtual const RotationMatrix3D - initJacobianToLocal(const GeometryContext& gctx, - ActsMatrixD<5, 7>& jacobian, - const Vector3D& gpos, - const Vector3D& dir) const; + virtual const RotationMatrix3D initJacobianToLocal( + const GeometryContext& gctx, ActsMatrixD<5, 7>& jacobian, + const Vector3D& gpos, const Vector3D& dir) const; /// Calculate the form factors for the derivatives /// the calculation is identical for all surfaces where the @@ -433,12 +396,9 @@ public: /// @param jac is the transport jacobian /// /// @return a five-dim vector - virtual const ActsRowVectorD<5> - derivativeFactors(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& dir, - const RotationMatrix3D& rft, - const ActsMatrixD<7, 5>& jac) const; + virtual const ActsRowVectorD<5> derivativeFactors( + const GeometryContext& gctx, const Vector3D& gpos, const Vector3D& dir, + const RotationMatrix3D& rft, const ActsMatrixD<7, 5>& jac) const; /// Calucation of the path correction for incident /// @@ -448,10 +408,9 @@ public: /// @param gmom global 3D momentum representation /// /// @return Path correction with respect to the nominal incident. - virtual double - pathCorrection(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& gmom) const = 0; + virtual double pathCorrection(const GeometryContext& gctx, + const Vector3D& gpos, + const Vector3D& gmom) const = 0; /// Straight line intersection schema from position/direction /// @@ -468,21 +427,16 @@ public: /// @return SurfaceIntersection object (contains intersection & surface) template <typename options_t, typename corrector_t = VoidIntersectionCorrector> - SurfaceIntersection - surfaceIntersectionEstimate(const GeometryContext& gctx, - const Vector3D& position, - const Vector3D& direction, - const options_t& options, - const corrector_t& correct = corrector_t()) const + SurfaceIntersection surfaceIntersectionEstimate( + const GeometryContext& gctx, const Vector3D& position, + const Vector3D& direction, const options_t& options, + const corrector_t& correct = corrector_t()) const { // get the intersection with the surface - auto sIntersection = intersectionEstimate(gctx, - position, - direction, - options.navDir, - options.boundaryCheck, - correct); + auto sIntersection = + intersectionEstimate(gctx, position, direction, options.navDir, + options.boundaryCheck, correct); // return a surface intersection with result direction return SurfaceIntersection(sIntersection, this); } @@ -500,15 +454,12 @@ public: /// @param correct Corrector struct that can be used to refine the solution /// /// @return SurfaceIntersection object (contains intersection & surface) - template <typename parameters_t, - typename options_t, + template <typename parameters_t, typename options_t, typename corrector_t = VoidIntersectionCorrector> - SurfaceIntersection - surfaceIntersectionEstimate(const GeometryContext& gctx, - const parameters_t& parameters, - const options_t& options, - const corrector_t& correct = corrector_t()) const - { + SurfaceIntersection surfaceIntersectionEstimate( + const GeometryContext& gctx, const parameters_t& parameters, + const options_t& options, + const corrector_t& correct = corrector_t()) const { return surfaceIntersectionEstimate( gctx, parameters.position(), parameters.direction(), options, correct); } @@ -527,27 +478,23 @@ public: /// a more appropriate intersection /// /// @return Intersection object - virtual Intersection - intersectionEstimate(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& gidr, - NavigationDirection navDir = forward, - const BoundaryCheck& bcheck = false, - CorrFnc corr = nullptr) const = 0; + virtual Intersection intersectionEstimate( + const GeometryContext& gctx, const Vector3D& gpos, const Vector3D& gidr, + NavigationDirection navDir = forward, const BoundaryCheck& bcheck = false, + CorrFnc corr = nullptr) const = 0; /// clang-format on /// Output Method for std::ostream, to be overloaded by child classes /// /// @param gctx The current geometry context object, e.g. alignment /// @param sl is the ostream to be dumped into - virtual std::ostream& - toStream(const GeometryContext& gctx, std::ostream& sl) const; + virtual std::ostream& toStream(const GeometryContext& gctx, + std::ostream& sl) const; /// Return properly formatted class name - virtual std::string - name() const = 0; + virtual std::string name() const = 0; -protected: + protected: /// Transform3D definition that positions /// (translation, rotation) the surface in global space std::shared_ptr<const Transform3D> m_transform; diff --git a/Core/include/Acts/Surfaces/SurfaceArray.hpp b/Core/include/Acts/Surfaces/SurfaceArray.hpp index d6bbdcf6cd02e688e476a0b93fb5ce98ebd074cb..39b28242fdb6abc48cc490c8d4e9973eb83637ef 100644 --- a/Core/include/Acts/Surfaces/SurfaceArray.hpp +++ b/Core/include/Acts/Surfaces/SurfaceArray.hpp @@ -28,20 +28,16 @@ using SurfaceVector = std::vector<const Surface*>; /// Contains a lookup struct which talks to the @c Grid /// and performs utility actions. This struct needs to be initialised /// externally and passed to @c SurfaceArray on construction. -class SurfaceArray -{ - -public: +class SurfaceArray { + public: /// @brief Base interface for all surface lookups. - struct ISurfaceGridLookup - { + struct ISurfaceGridLookup { /// @brief Fill provided surfaces into the contained @c Grid. /// @param gctx The current geometry context object, e.g. alignment /// @param surfaces Input surface pointers - virtual void - fill(const GeometryContext& gctx, const SurfaceVector& surfaces) - = 0; + virtual void fill(const GeometryContext& gctx, + const SurfaceVector& surfaces) = 0; /// @brief Attempts to fix sub-optimal binning by filling closest /// Surfaces into empty bin @@ -50,76 +46,63 @@ public: /// @param surfaces The surface pointers to fill /// @return number of bins that were filled - virtual size_t - completeBinning(const GeometryContext& gctx, const SurfaceVector& surfaces) - = 0; + virtual size_t completeBinning(const GeometryContext& gctx, + const SurfaceVector& surfaces) = 0; /// @brief Performs lookup at @c pos and returns bin content as reference /// @param pos Lookup position /// @return @c SurfaceVector at given bin - virtual SurfaceVector& - lookup(const Vector3D& pos) - = 0; + virtual SurfaceVector& lookup(const Vector3D& pos) = 0; /// @brief Performs lookup at @c pos and returns bin content as const /// reference /// @param pos Lookup position /// @return @c SurfaceVector at given bin - virtual const SurfaceVector& - lookup(const Vector3D& pos) const = 0; + virtual const SurfaceVector& lookup(const Vector3D& pos) const = 0; /// @brief Performs lookup at global bin and returns bin content as /// reference /// @param bin Global lookup bin /// @return @c SurfaceVector at given bin - virtual SurfaceVector& - lookup(size_t bin) - = 0; + virtual SurfaceVector& lookup(size_t bin) = 0; /// @brief Performs lookup at global bin and returns bin content as const /// reference /// @param bin Global lookup bin /// @return @c SurfaceVector at given bin - virtual const SurfaceVector& - lookup(size_t bin) const = 0; + virtual const SurfaceVector& lookup(size_t bin) const = 0; /// @brief Performs a lookup at @c pos, but returns neighbors as well /// /// @param pos Lookup position /// @return @c SurfaceVector at given bin. Copy of all bins selected - virtual const SurfaceVector& - neighbors(const Vector3D& pos) const = 0; + virtual const SurfaceVector& neighbors(const Vector3D& pos) const = 0; /// @brief Returns the total size of the grid (including under/overflow /// bins) /// @return Size of the grid data structure - virtual size_t - size() const = 0; + virtual size_t size() const = 0; /// @brief Gets the center position of bin @c bin in global coordinates /// @param bin the global bin index /// @return The bin center - virtual Vector3D - getBinCenter(size_t bin) const = 0; + virtual Vector3D getBinCenter(size_t bin) const = 0; /// @brief Returns copies of the axes used in the grid as @c AnyAxis /// @return The axes /// @note This returns copies. Use for introspection and querying. - virtual std::vector<const IAxis*> - getAxes() const = 0; + virtual std::vector<const IAxis*> getAxes() const = 0; /// @brief Get the number of dimensions of the grid. /// @return number of dimensions - virtual size_t - dimensions() const = 0; + virtual size_t dimensions() const = 0; /// @brief Checks if global bin is valid /// @param bin the global bin index /// @return bool if the bin is valid /// @note Valid means that the index points to a bin which is not a under /// or overflow bin or out of range in any axis. - virtual bool - isValidBin(size_t bin) const = 0; + virtual bool isValidBin(size_t bin) const = 0; /// Pure virtual destructor virtual ~ISurfaceGridLookup() = 0; @@ -128,16 +111,15 @@ public: /// @brief Lookup helper which encapsulates a @c Grid /// @tparam Axes The axes used for the grid template <class... Axes> - struct SurfaceGridLookup : ISurfaceGridLookup - { + struct SurfaceGridLookup : ISurfaceGridLookup { static constexpr size_t DIM = sizeof...(Axes); - public: + public: /// @brief Specifies the local coordinate type. /// This resolves to @c ActsVector<DIM> for DIM > 1, else @c /// std::array<double, 1> - using point_t - = std::conditional_t<DIM == 1, std::array<double, 1>, ActsVectorD<DIM>>; + using point_t = + std::conditional_t<DIM == 1, std::array<double, 1>, ActsVectorD<DIM>>; using Grid_t = detail::Grid<SurfaceVector, Axes...>; /// @brief Default constructor @@ -150,11 +132,10 @@ public: /// @c std::array<double, 1>. SurfaceGridLookup(std::function<point_t(const Vector3D&)> globalToLocal, std::function<Vector3D(const point_t&)> localToGlobal, - std::tuple<Axes...> axes) - : m_globalToLocal(std::move(globalToLocal)) - , m_localToGlobal(std::move(localToGlobal)) - , m_grid(std::move(axes)) - { + std::tuple<Axes...> axes) + : m_globalToLocal(std::move(globalToLocal)), + m_localToGlobal(std::move(localToGlobal)), + m_grid(std::move(axes)) { m_neighborMap.resize(m_grid.size()); } @@ -168,9 +149,8 @@ public: /// /// @param gctx The current geometry context object, e.g. alignment /// @param surfaces Input surface pointers - void - fill(const GeometryContext& gctx, const SurfaceVector& surfaces) override - { + void fill(const GeometryContext& gctx, + const SurfaceVector& surfaces) override { for (const auto& srf : surfaces) { Vector3D pos = srf->binningPosition(gctx, binR); lookup(pos).push_back(srf); @@ -186,13 +166,11 @@ public: /// @param gctx The current geometry context object, e.g. alignment /// @param surfaces The surface pointers to fill /// @return number of bins that were filled - size_t - completeBinning(const GeometryContext& gctx, - const SurfaceVector& surfaces) override - { - size_t binCompleted = 0; - size_t nBins = size(); - double minPath, curPath; + size_t completeBinning(const GeometryContext& gctx, + const SurfaceVector& surfaces) override { + size_t binCompleted = 0; + size_t nBins = size(); + double minPath, curPath; const Surface* minSrf; for (size_t b = 0; b < nBins; ++b) { @@ -206,13 +184,13 @@ public: } Vector3D binCtr = getBinCenter(b); - minPath = std::numeric_limits<double>::max(); + minPath = std::numeric_limits<double>::max(); for (const auto& srf : surfaces) { curPath = (binCtr - srf->binningPosition(gctx, binR)).norm(); if (curPath < minPath) { minPath = curPath; - minSrf = srf; + minSrf = srf; } } @@ -228,9 +206,7 @@ public: /// @brief Performs lookup at @c pos and returns bin content as reference /// @param pos Lookup position /// @return @c SurfaceVector at given bin - SurfaceVector& - lookup(const Vector3D& pos) override - { + SurfaceVector& lookup(const Vector3D& pos) override { return m_grid.atPosition(m_globalToLocal(pos)); } @@ -238,9 +214,7 @@ public: /// reference /// @param pos Lookup position /// @return @c SurfaceVector at given bin - const SurfaceVector& - lookup(const Vector3D& pos) const override - { + const SurfaceVector& lookup(const Vector3D& pos) const override { return m_grid.atPosition(m_globalToLocal(pos)); } @@ -248,19 +222,13 @@ public: /// reference /// @param bin Global lookup bin /// @return @c SurfaceVector at given bin - SurfaceVector& - lookup(size_t bin) override - { - return m_grid.at(bin); - } + SurfaceVector& lookup(size_t bin) override { return m_grid.at(bin); } /// @brief Performs lookup at global bin and returns bin content as const /// reference /// @param bin Global lookup bin /// @return @c SurfaceVector at given bin - const SurfaceVector& - lookup(size_t bin) const override - { + const SurfaceVector& lookup(size_t bin) const override { return m_grid.at(bin); } @@ -268,9 +236,7 @@ public: /// /// @param pos Lookup position /// @return @c SurfaceVector at given bin. Copy of all bins selected - const SurfaceVector& - neighbors(const Vector3D& pos) const override - { + const SurfaceVector& neighbors(const Vector3D& pos) const override { auto loc = m_globalToLocal(pos); return m_neighborMap.at(m_grid.globalBinFromPosition(loc)); } @@ -278,49 +244,35 @@ public: /// @brief Returns the total size of the grid (including under/overflow /// bins) /// @return Size of the grid data structure - size_t - size() const override - { - return m_grid.size(); - } + size_t size() const override { return m_grid.size(); } /// @brief Gets the center position of bin @c bin in global coordinates /// @param bin the global bin index /// @return The bin center - Vector3D - getBinCenter(size_t bin) const override - { + Vector3D getBinCenter(size_t bin) const override { return getBinCenterImpl(bin); } /// @brief Returns copies of the axes used in the grid as @c AnyAxis /// @return The axes /// @note This returns copies. Use for introspection and querying. - std::vector<const IAxis*> - getAxes() const override - { + std::vector<const IAxis*> getAxes() const override { auto arr = m_grid.axes(); return std::vector<const IAxis*>(arr.begin(), arr.end()); } /// @brief Get the number of dimensions of the grid. /// @return number of dimensions - size_t - dimensions() const override - { - return DIM; - } + size_t dimensions() const override { return DIM; } /// @brief Checks if global bin is valid /// @param bin the global bin index /// @return bool if the bin is valid /// @note Valid means that the index points to a bin which is not a under /// or overflow bin or out of range in any axis. - bool - isValidBin(size_t bin) const override - { + bool isValidBin(size_t bin) const override { std::array<size_t, DIM> indices = m_grid.localBinsFromGlobalBin(bin); - std::array<size_t, DIM> nBins = m_grid.numLocalBins(); + std::array<size_t, DIM> nBins = m_grid.numLocalBins(); for (size_t i = 0; i < indices.size(); ++i) { size_t idx = indices.at(i); if (idx <= 0 || idx >= nBins.at(i) + 1) { @@ -331,24 +283,21 @@ public: return true; } - private: - void - populateNeighborCache() - { + private: + void populateNeighborCache() { // calculate neighbors for every bin and store in map for (size_t i = 0; i < m_grid.size(); i++) { if (!isValidBin(i)) { continue; } typename Grid_t::index_t loc = m_grid.localBinsFromGlobalBin(i); - auto neighborIdxs = m_grid.neighborHoodIndices(loc, 1u); + auto neighborIdxs = m_grid.neighborHoodIndices(loc, 1u); std::vector<const Surface*>& neighbors = m_neighborMap.at(i); neighbors.clear(); for (const auto& idx : neighborIdxs) { const std::vector<const Surface*>& binContent = m_grid.at(idx); - std::copy(binContent.begin(), - binContent.end(), + std::copy(binContent.begin(), binContent.end(), std::back_inserter(neighbors)); } } @@ -365,9 +314,7 @@ public: /// here on the callers end /// This is the version for DIM>1 template <size_t D = DIM, std::enable_if_t<D != 1, int> = 0> - Vector3D - getBinCenterImpl(size_t bin) const - { + Vector3D getBinCenterImpl(size_t bin) const { return m_localToGlobal(ActsVectorD<DIM>( m_grid.binCenter(m_grid.localBinsFromGlobalBin(bin)).data())); } @@ -375,46 +322,36 @@ public: /// Internal method, see above. /// This is the version for DIM==1 template <size_t D = DIM, std::enable_if_t<D == 1, int> = 0> - Vector3D - getBinCenterImpl(size_t bin) const - { + Vector3D getBinCenterImpl(size_t bin) const { point_t pos = m_grid.binCenter(m_grid.localBinsFromGlobalBin(bin)); return m_localToGlobal(pos); } std::function<point_t(const Vector3D&)> m_globalToLocal; std::function<Vector3D(const point_t&)> m_localToGlobal; - Grid_t m_grid; - std::vector<SurfaceVector> m_neighborMap; + Grid_t m_grid; + std::vector<SurfaceVector> m_neighborMap; }; /// @brief Lookup implementation which wraps one element and always returns /// this element when lookup is called - struct SingleElementLookup : ISurfaceGridLookup - { - + struct SingleElementLookup : ISurfaceGridLookup { /// @brief Default constructor. /// @param element the one and only element. SingleElementLookup(SurfaceVector::value_type element) - : m_element({element}) - { - } + : m_element({element}) {} /// @brief Lookup, always returns @c element /// @param pos is ignored /// @return reference to vector containing only @c element - SurfaceVector& - lookup(const Vector3D& /*pos*/) override - { + SurfaceVector& lookup(const Vector3D& /*pos*/) override { return m_element; } /// @brief Lookup, always returns @c element /// @param pos is ignored /// @return reference to vector containing only @c element - const SurfaceVector& - lookup(const Vector3D& /*pos*/) const override - { + const SurfaceVector& lookup(const Vector3D& /*pos*/) const override { return m_element; } @@ -426,66 +363,45 @@ public: /// @brief Lookup, always returns @c element /// @param bin is ignored /// @return reference to vector containing only @c element - const SurfaceVector& lookup(size_t /*bin*/) const override - { + const SurfaceVector& lookup(size_t /*bin*/) const override { return m_element; } /// @brief Lookup, always returns @c element /// @param pos is ignored /// @return reference to vector containing only @c element - const SurfaceVector& - neighbors(const Vector3D& /*pos*/) const override - { + const SurfaceVector& neighbors(const Vector3D& /*pos*/) const override { return m_element; } /// @brief returns 1 /// @return 1 - size_t - size() const override - { - return 1; - } + size_t size() const override { return 1; } /// @brief Gets the bin center, but always returns (0, 0, 0) /// @param bin is ignored /// @return (0, 0, 0) - Vector3D getBinCenter(size_t /*bin*/) const override - { + Vector3D getBinCenter(size_t /*bin*/) const override { return Vector3D(0, 0, 0); } /// @brief Returns an empty vector of @c AnyAxis /// @return empty vector - std::vector<const IAxis*> - getAxes() const override - { - return {}; - } + std::vector<const IAxis*> getAxes() const override { return {}; } /// @brief Get the number of dimensions /// @return always 0 - size_t - dimensions() const override - { - return 0; - } + size_t dimensions() const override { return 0; } /// @brief Comply with concept and provide fill method /// @note Does nothing - void - fill(const GeometryContext& /*gctx*/, - const SurfaceVector& /*surfaces*/) override - { - } + void fill(const GeometryContext& /*gctx*/, + const SurfaceVector& /*surfaces*/) override {} /// @brief Comply with concept and provide completeBinning method /// @note Does nothing - size_t - completeBinning(const GeometryContext& /*gctx*/, - const SurfaceVector& /*surfaces*/) override - { + size_t completeBinning(const GeometryContext& /*gctx*/, + const SurfaceVector& /*surfaces*/) override { return 0; } @@ -494,7 +410,7 @@ public: /// @return always true bool isValidBin(size_t /*bin*/) const override { return true; } - private: + private: SurfaceVector m_element; }; @@ -505,9 +421,9 @@ public: /// @param surfaces The input vector of surfaces. This is only for /// bookkeeping, so we can ask /// @param transform Optional additional transform for this SurfaceArray - SurfaceArray(std::unique_ptr<ISurfaceGridLookup> gridLookup, + SurfaceArray(std::unique_ptr<ISurfaceGridLookup> gridLookup, std::vector<std::shared_ptr<const Surface>> surfaces, - std::shared_ptr<const Transform3D> transform = nullptr); + std::shared_ptr<const Transform3D> transform = nullptr); /// @brief Constructor which takes concrete type SurfaceGridLookup /// @param gridLookup The grid storage. Is static casted to ISurfaceGridLookup @@ -524,37 +440,25 @@ public: /// @brief Get all surfaces in bin given by position. /// @param pos the lookup position /// @return reference to @c SurfaceVector contained in bin at that position - SurfaceVector& - at(const Vector3D& pos) - { - return p_gridLookup->lookup(pos); - } + SurfaceVector& at(const Vector3D& pos) { return p_gridLookup->lookup(pos); } /// @brief Get all surfaces in bin given by position @p pos. /// @param pos the lookup position /// @return const reference to @c SurfaceVector contained in bin at that /// position - const SurfaceVector& - at(const Vector3D& pos) const - { + const SurfaceVector& at(const Vector3D& pos) const { return p_gridLookup->lookup(pos); } /// @brief Get all surfaces in bin given by global bin index @p bin. /// @param bin the global bin index /// @return reference to @c SurfaceVector contained in bin - SurfaceVector& - at(size_t bin) - { - return p_gridLookup->lookup(bin); - } + SurfaceVector& at(size_t bin) { return p_gridLookup->lookup(bin); } /// @brief Get all surfaces in bin given by global bin index. /// @param bin the global bin index /// @return const reference to @c SurfaceVector contained in bin - const SurfaceVector& - at(size_t bin) const - { + const SurfaceVector& at(size_t bin) const { return p_gridLookup->lookup(bin); } @@ -565,76 +469,49 @@ public: /// @note The @c SurfaceVector will be combined. For technical reasons, the /// different bin content vectors have to be copied, so the resulting /// vector contains copies. - SurfaceVector - neighbors(const Vector3D& pos) const - { + SurfaceVector neighbors(const Vector3D& pos) const { return p_gridLookup->neighbors(pos); } /// @brief Get the size of the underlying grid structure including /// under/overflow bins /// @return the size - size_t - size() const - { - return p_gridLookup->size(); - } + size_t size() const { return p_gridLookup->size(); } /// @brief Get the center of the bin identified by global bin index @p bin /// @param bin the global bin index /// @return Center position of the bin in global coordinates - Vector3D - getBinCenter(size_t bin) - { - return p_gridLookup->getBinCenter(bin); - } + Vector3D getBinCenter(size_t bin) { return p_gridLookup->getBinCenter(bin); } /// @brief Get all surfaces attached to this @c SurfaceArray /// @return Reference to @c SurfaceVector containing all surfaces /// @note This does not reflect the actual state of the grid. It only /// returns what was given in the constructor, without any checks /// if that is actually whats in the grid. - const SurfaceVector& - surfaces() const - { - return m_surfacesRawPointers; - } + const SurfaceVector& surfaces() const { return m_surfacesRawPointers; } /// @brief Get vector of axes spanning the grid as @c AnyAxis /// @return vector of @c AnyAxis /// @note The axes in the vector are copies. Only use for introspection and /// querying. - std::vector<const IAxis*> - getAxes() const - { - return p_gridLookup->getAxes(); - } + std::vector<const IAxis*> getAxes() const { return p_gridLookup->getAxes(); } /// @brief Checks if global bin is valid /// @param bin the global bin index /// @return bool if the bin is valid /// @note Valid means that the index points to a bin which is not a under /// or overflow bin or out of range in any axis. - bool - isValidBin(size_t bin) const - { - return p_gridLookup->isValidBin(bin); - } + bool isValidBin(size_t bin) const { return p_gridLookup->isValidBin(bin); } - const Transform3D& - transform() const - { - return *m_transform; - } + const Transform3D& transform() const { return *m_transform; } /// @brief String representation of this @c SurfaceArray /// @param gctx The current geometry context object, e.g. alignment /// @param sl Output stream to write to /// @return the output stream given as @p sl - std::ostream& - toStream(const GeometryContext& gctx, std::ostream& sl) const; + std::ostream& toStream(const GeometryContext& gctx, std::ostream& sl) const; -private: + private: std::unique_ptr<ISurfaceGridLookup> p_gridLookup; // this vector makes sure we have shared ownership over the surfaces std::vector<std::shared_ptr<const Surface>> m_surfaces; diff --git a/Core/include/Acts/Surfaces/SurfaceBounds.hpp b/Core/include/Acts/Surfaces/SurfaceBounds.hpp index a5226ba4e7c80b18cb336fe6e48a5b8b9c5a7dc8..c7a8fba4b433ec15168fa15578b03ee72bc28912 100644 --- a/Core/include/Acts/Surfaces/SurfaceBounds.hpp +++ b/Core/include/Acts/Surfaces/SurfaceBounds.hpp @@ -27,29 +27,28 @@ namespace Acts { /// - distance to boundary calculations /// - the BoundsType and a set of parameters to simplify persistency /// -class SurfaceBounds -{ -public: +class SurfaceBounds { + public: /// @enum BoundsType /// /// This enumerator simplifies the persistency, /// by saving a dynamic_cast to happen. /// enum BoundsType { - Cone = 0, - Cylinder = 1, - Diamond = 2, - Disc = 3, - Ellipse = 5, - Line = 6, - Rectangle = 7, + Cone = 0, + Cylinder = 1, + Diamond = 2, + Disc = 3, + Ellipse = 5, + Line = 6, + Rectangle = 7, RotatedTrapezoid = 8, - Trapezoid = 9, - Triangle = 10, - DiscTrapezoidal = 11, - ConvexPolygon = 12, - Boundless = 13, - Other = 14 + Trapezoid = 9, + Triangle = 10, + DiscTrapezoidal = 11, + ConvexPolygon = 12, + Boundless = 13, + Other = 14 }; virtual ~SurfaceBounds() = default; @@ -58,20 +57,17 @@ public: /// assigment operator of the Surface class /// /// @return is a newly created object - virtual SurfaceBounds* - clone() const = 0; + virtual SurfaceBounds* clone() const = 0; /// Return the bounds type - for persistency optimization /// /// @return is a BoundsType enum - virtual BoundsType - type() const = 0; + virtual BoundsType type() const = 0; /// Access method for bound variable store /// /// @return of the stored values for the boundary object - virtual std::vector<TDD_real_t> - valueStore() const = 0; + virtual std::vector<TDD_real_t> valueStore() const = 0; /// Inside check for the bounds object driven by the boundary check directive /// Each Bounds has a method inside, which checks if a LocalPosition is inside @@ -80,41 +76,33 @@ public: /// @param lpos Local position (assumed to be in right surface frame) /// @param bcheck boundary check directive /// @return boolean indicator for the success of this operation - virtual bool - inside(const Vector2D& lpos, const BoundaryCheck& bcheck) const = 0; + virtual bool inside(const Vector2D& lpos, + const BoundaryCheck& bcheck) const = 0; /// Minimal distance to boundary ( > 0 if outside and <=0 if inside) /// /// @param lpos is the local position to check for the distance /// @return is a signed distance parameter - virtual double - distanceToBoundary(const Vector2D& lpos) const = 0; + virtual double distanceToBoundary(const Vector2D& lpos) const = 0; /// Output Method for std::ostream, to be overloaded by child classes /// /// @param sl is the outstream in which the string dump is done - virtual std::ostream& - toStream(std::ostream& os) const = 0; + virtual std::ostream& toStream(std::ostream& os) const = 0; }; -inline bool -operator==(const SurfaceBounds& lhs, const SurfaceBounds& rhs) -{ +inline bool operator==(const SurfaceBounds& lhs, const SurfaceBounds& rhs) { if (&lhs == &rhs) { return true; } return (lhs.type() == rhs.type()) && (lhs.valueStore() == rhs.valueStore()); } -inline bool -operator!=(const SurfaceBounds& lhs, const SurfaceBounds& rhs) -{ +inline bool operator!=(const SurfaceBounds& lhs, const SurfaceBounds& rhs) { return !(lhs == rhs); } -inline std::ostream& -operator<<(std::ostream& os, const SurfaceBounds& sb) -{ +inline std::ostream& operator<<(std::ostream& os, const SurfaceBounds& sb) { return sb.toStream(os); } diff --git a/Core/include/Acts/Surfaces/TrapezoidBounds.hpp b/Core/include/Acts/Surfaces/TrapezoidBounds.hpp index ed5b925b507537cf1cde8f5c33774dce3ec289e5..bdb744921d22fc28d4c0c9e456423e9b71f3a19d 100644 --- a/Core/include/Acts/Surfaces/TrapezoidBounds.hpp +++ b/Core/include/Acts/Surfaces/TrapezoidBounds.hpp @@ -28,15 +28,14 @@ namespace Acts { /// /// @todo can be speed optimized by calculating kappa/delta and caching it -class TrapezoidBounds : public PlanarBounds -{ -public: +class TrapezoidBounds : public PlanarBounds { + public: /// @enum BoundValues - for readability enum BoundValues { bv_minHalfX = 0, bv_maxHalfX = 1, - bv_halfY = 2, - bv_length = 3 + bv_halfY = 2, + bv_length = 3 }; /// Trapezoid bounds default constructor is forbidden @@ -51,14 +50,11 @@ public: ~TrapezoidBounds() override; - TrapezoidBounds* - clone() const final; + TrapezoidBounds* clone() const final; - BoundsType - type() const final; + BoundsType type() const final; - std::vector<TDD_real_t> - valueStore() const final; + std::vector<TDD_real_t> valueStore() const final; /// The orientation of the Trapezoid is according to the figure above, /// in words: the shorter of the two parallel sides of the trapezoid @@ -104,68 +100,54 @@ public: /// @param lpos Local position (assumed to be in right surface frame) /// @param bcheck boundary check directive /// @return boolean indicator for the success of this operation - bool - inside(const Vector2D& lpos, const BoundaryCheck& bcheck) const final; + bool inside(const Vector2D& lpos, const BoundaryCheck& bcheck) const final; /// Minimal distance to boundary ( > 0 if outside and <=0 if inside) /// /// @param lpos is the local position to check for the distance /// @return is a signed distance parameter - double - distanceToBoundary(const Vector2D& lpos) const final; + double distanceToBoundary(const Vector2D& lpos) const final; /// Return the vertices - or, the points of the extremas - std::vector<Vector2D> - vertices() const final; + std::vector<Vector2D> vertices() const final; // Bounding box representation - const RectangleBounds& - boundingBox() const final; + const RectangleBounds& boundingBox() const final; /// Output Method for std::ostream /// /// @param sl is the ostream to be dumped into - std::ostream& - toStream(std::ostream& sl) const final; + std::ostream& toStream(std::ostream& sl) const final; /// This method returns the minimal halflength in X /// (first coordinate of local surface frame) - double - minHalflengthX() const; + double minHalflengthX() const; /// This method returns the maximal halflength in X /// (first coordinate of local surface frame) - double - maxHalflengthX() const; + double maxHalflengthX() const; /// This method returns the halflength in Y /// (second coordinate of local surface frame) - double - halflengthY() const; + double halflengthY() const; -private: - double m_minHalfX; - double m_maxHalfX; - double m_halfY; + private: + double m_minHalfX; + double m_maxHalfX; + double m_halfY; RectangleBounds m_boundingBox; }; -inline double -TrapezoidBounds::minHalflengthX() const -{ +inline double TrapezoidBounds::minHalflengthX() const { return m_minHalfX; } -inline double -TrapezoidBounds::maxHalflengthX() const -{ +inline double TrapezoidBounds::maxHalflengthX() const { return m_maxHalfX; } -inline double -TrapezoidBounds::halflengthY() const -{ +inline double TrapezoidBounds::halflengthY() const { return m_halfY; } -} // namespace \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Surfaces/TriangleBounds.hpp b/Core/include/Acts/Surfaces/TriangleBounds.hpp index 777623d4a8a41b267ce1072cd9ee6dba6e0cdd95..beeec220284efcb2148ba00ce087e23f18dc4062 100644 --- a/Core/include/Acts/Surfaces/TriangleBounds.hpp +++ b/Core/include/Acts/Surfaces/TriangleBounds.hpp @@ -27,17 +27,16 @@ namespace Acts { /// /// @image html TriangularBounds.gif -class TriangleBounds : public PlanarBounds -{ -public: +class TriangleBounds : public PlanarBounds { + public: // @enum BoundValues for readability enum BoundValues { - bv_x1 = 0, - bv_y1 = 1, - bv_x2 = 2, - bv_y2 = 3, - bv_x3 = 4, - bv_y3 = 5, + bv_x1 = 0, + bv_y1 = 1, + bv_x2 = 2, + bv_y2 = 3, + bv_x3 = 4, + bv_y3 = 5, bv_length = 6 }; @@ -50,14 +49,11 @@ public: ~TriangleBounds() override; - TriangleBounds* - clone() const final; + TriangleBounds* clone() const final; - BoundsType - type() const final; + BoundsType type() const final; - std::vector<TDD_real_t> - valueStore() const final; + std::vector<TDD_real_t> valueStore() const final; /// This method checks if the provided local coordinates are inside the /// surface bounds @@ -65,33 +61,28 @@ public: /// @param lpos local position in 2D local carthesian frame /// @param bcheck is the boundary check directive /// @return boolean indicator for the success of this operation - bool - inside(const Vector2D& lpos, const BoundaryCheck& bcheck) const final; + bool inside(const Vector2D& lpos, const BoundaryCheck& bcheck) const final; /// Minimal distance to boundary ( > 0 if outside and <=0 if inside) /// /// @param lpos is the local position to check for the distance /// @return is a signed distance parameter - double - distanceToBoundary(const Vector2D& lpos) const final; + double distanceToBoundary(const Vector2D& lpos) const final; /// This method returns the coordinates of vertices - std::vector<Vector2D> - vertices() const final; + std::vector<Vector2D> vertices() const final; // Bounding box representation - const RectangleBounds& - boundingBox() const final; + const RectangleBounds& boundingBox() const final; /// Output Method for std::ostream /// /// @param sl is the ostream to be dumped into - std::ostream& - toStream(std::ostream& sl) const final; + std::ostream& toStream(std::ostream& sl) const final; -private: + private: std::array<Vector2D, 3> m_vertices; RectangleBounds m_boundingBox; ///< internal bounding box cache }; -} // namespace \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Surfaces/detail/ConeSurface.ipp b/Core/include/Acts/Surfaces/detail/ConeSurface.ipp index dcb25de1709d18fdaf46e641524a87f8f7c122b1..0f71ec6e926a60f26804da7d4cc4d0666035f5d2 100644 --- a/Core/include/Acts/Surfaces/detail/ConeSurface.ipp +++ b/Core/include/Acts/Surfaces/detail/ConeSurface.ipp @@ -10,48 +10,42 @@ // ConeSurface.ipp, Acts project /////////////////////////////////////////////////////////////////// -inline Intersection -ConeSurface::intersectionEstimate(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& gmom, - NavigationDirection navDir, - const BoundaryCheck& bcheck, - CorrFnc correct) const -{ - +inline Intersection ConeSurface::intersectionEstimate( + const GeometryContext& gctx, const Vector3D& gpos, const Vector3D& gmom, + NavigationDirection navDir, const BoundaryCheck& bcheck, + CorrFnc correct) const { // check if you need bool needsTransform = (Surface::m_transform) ? true : false; // create the points - Vector3D point1 = gpos; + Vector3D point1 = gpos; Vector3D initialdir = gmom.normalized(); - Vector3D direction = initialdir; + Vector3D direction = initialdir; // what you need at the and Vector3D solution(0, 0, 0); - double path = 0.; - bool valid = false; + double path = 0.; + bool valid = false; // break condition for the loop bool correctionDone = false; // make the loop including the potential correction do { - if (needsTransform) { Transform3D invTrans = transform(gctx).inverse(); - point1 = invTrans * gpos; - direction = invTrans.linear() * direction; + point1 = invTrans * gpos; + direction = invTrans.linear() * direction; } // see the header for the formula derivation double tan2Alpha = bounds().tanAlpha() * bounds().tanAlpha(), - A = direction.x() * direction.x() + direction.y() * direction.y() - - tan2Alpha * direction.z() * direction.z(), - B = 2 * (direction.x() * point1.x() + direction.y() * point1.y() - - tan2Alpha * direction.z() * point1.z()), - C = point1.x() * point1.x() + point1.y() * point1.y() - - tan2Alpha * point1.z() * point1.z(); + A = direction.x() * direction.x() + direction.y() * direction.y() - + tan2Alpha * direction.z() * direction.z(), + B = 2 * (direction.x() * point1.x() + direction.y() * point1.y() - + tan2Alpha * direction.z() * point1.z()), + C = point1.x() * point1.x() + point1.y() * point1.y() - + tan2Alpha * point1.z() * point1.z(); if (A == 0.) { A += 1e-16; // avoid division by zero } @@ -60,38 +54,38 @@ ConeSurface::intersectionEstimate(const GeometryContext& gctx, detail::RealQuadraticEquation solns(A, B, C); if (solns.solutions != 0) { - double t1 = solns.first; + double t1 = solns.first; Vector3D soln1Loc(point1 + t1 * direction); // there's only one solution for this if (solns.solutions == 1) { // set the solution solution = soln1Loc; - path = t1; + path = t1; // check the validity given the navigation direction valid = (t1 * navDir >= 0.); // there's two solutions } else if (solns.solutions == 2) { // get the second solution - double t2 = solns.second; + double t2 = solns.second; Vector3D soln2Loc(point1 + t2 * direction); // both solutions have the same sign - or you don't care // then take the closer one if (t1 * t2 > 0. || (navDir == 0)) { if (t1 * t1 < t2 * t2) { solution = soln1Loc; - path = t1; + path = t1; } else { solution = soln2Loc; - path = t2; + path = t2; } } else { if (navDir * t1 > 0.) { solution = soln1Loc; - path = t1; + path = t1; } else { solution = soln2Loc; - path = t2; + path = t2; } } } @@ -102,7 +96,7 @@ ConeSurface::intersectionEstimate(const GeometryContext& gctx, // break if there's nothing to correct if (correct && !correctionDone) { // reset to initial position and direction - point1 = gpos; + point1 = gpos; direction = initialdir; if (correct(point1, direction, path)) { correctionDone = true; diff --git a/Core/include/Acts/Surfaces/detail/CylinderSurface.ipp b/Core/include/Acts/Surfaces/detail/CylinderSurface.ipp index 8d9aaca414331b03286fc7c3669afd2241711f32..41a9183af1ffd6ca60f32b641e0ff5d40573901a 100644 --- a/Core/include/Acts/Surfaces/detail/CylinderSurface.ipp +++ b/Core/include/Acts/Surfaces/detail/CylinderSurface.ipp @@ -10,43 +10,37 @@ // CylinderSurface.ipp, Acts project /////////////////////////////////////////////////////////////////// -inline const Vector3D -CylinderSurface::rotSymmetryAxis(const GeometryContext& gctx) const -{ +inline const Vector3D CylinderSurface::rotSymmetryAxis( + const GeometryContext& gctx) const { // fast access via tranform matrix (and not rotation()) return transform(gctx).matrix().block<3, 1>(0, 2); } -inline Intersection -CylinderSurface::intersectionEstimate(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& gdir, - NavigationDirection navDir, - const BoundaryCheck& bcheck, - CorrFnc correct) const -{ - +inline Intersection CylinderSurface::intersectionEstimate( + const GeometryContext& gctx, const Vector3D& gpos, const Vector3D& gdir, + NavigationDirection navDir, const BoundaryCheck& bcheck, + CorrFnc correct) const { // create line parameters Vector3D lpos = gpos; Vector3D ldir = gdir; // minimize the call to transform() const auto& tMatrix = transform(gctx).matrix(); - Vector3D caxis = tMatrix.block<3, 1>(0, 2).transpose(); - Vector3D ccenter = tMatrix.block<3, 1>(0, 3).transpose(); + Vector3D caxis = tMatrix.block<3, 1>(0, 2).transpose(); + Vector3D ccenter = tMatrix.block<3, 1>(0, 3).transpose(); // what you need at the and Vector3D solution(0, 0, 0); - double path = 0.; + double path = 0.; // lemma : the solver -> should catch current values - auto solve = [&solution, &path, &lpos, &ldir, &ccenter, &caxis, &navDir]( - double R) -> bool { + auto solve = [&solution, &path, &lpos, &ldir, &ccenter, &caxis, + &navDir](double R) -> bool { // check documentation for explanation - Vector3D pc = lpos - ccenter; + Vector3D pc = lpos - ccenter; Vector3D pcXcd = pc.cross(caxis); Vector3D ldXcd = ldir.cross(caxis); - double a = ldXcd.dot(ldXcd); - double b = 2. * (ldXcd.dot(pcXcd)); - double c = pcXcd.dot(pcXcd) - (R * R); + double a = ldXcd.dot(ldXcd); + double b = 2. * (ldXcd.dot(pcXcd)); + double c = pcXcd.dot(pcXcd) - (R * R); // and solve the qaudratic equation - todo, validity check detail::RealQuadraticEquation qe(a, b, c); // check how many solution you have @@ -55,8 +49,9 @@ CylinderSurface::intersectionEstimate(const GeometryContext& gctx, } // chose the solution path = ((navDir == 0) || qe.first * qe.second > 0.) - ? (qe.first * qe.first < qe.second * qe.second ? qe.first : qe.second) - : (navDir * qe.first >= 0. ? qe.first : qe.second); + ? (qe.first * qe.first < qe.second * qe.second ? qe.first + : qe.second) + : (navDir * qe.first >= 0. ? qe.first : qe.second); // return the solution solution = lpos + path * ldir; // is valid if it goes into the right direction @@ -64,8 +59,8 @@ CylinderSurface::intersectionEstimate(const GeometryContext& gctx, }; // solve for radius R - double R = bounds().r(); - bool valid = solve(R); + double R = bounds().r(); + bool valid = solve(R); // if configured, correct and solve again if (correct && correct(lpos, ldir, path)) { valid = solve(R); diff --git a/Core/include/Acts/Surfaces/detail/DiscSurface.ipp b/Core/include/Acts/Surfaces/detail/DiscSurface.ipp index d720eb04905cff306dcf3d884fe0713955638322..bb4917689a7e7da170b516bddf01faca7a8488cb 100644 --- a/Core/include/Acts/Surfaces/detail/DiscSurface.ipp +++ b/Core/include/Acts/Surfaces/detail/DiscSurface.ipp @@ -10,28 +10,23 @@ // DiscSurface.ipp, Acts project /////////////////////////////////////////////////////////////////// -inline const Vector2D -DiscSurface::localPolarToCartesian(const Vector2D& lpolar) const -{ +inline const Vector2D DiscSurface::localPolarToCartesian( + const Vector2D& lpolar) const { return Vector2D(lpolar[eLOC_R] * cos(lpolar[eLOC_PHI]), lpolar[eLOC_R] * sin(lpolar[eLOC_PHI])); } -inline const Vector2D -DiscSurface::localCartesianToPolar(const Vector2D& lcart) const -{ +inline const Vector2D DiscSurface::localCartesianToPolar( + const Vector2D& lcart) const { return Vector2D( sqrt(lcart[eLOC_X] * lcart[eLOC_X] + lcart[eLOC_Y] * lcart[eLOC_Y]), atan2(lcart[eLOC_Y], lcart[eLOC_X])); } -inline void -DiscSurface::initJacobianToGlobal(const GeometryContext& gctx, - ActsMatrixD<7, 5>& jacobian, - const Vector3D& gpos, - const Vector3D& dir, - const ActsVectorD<5>& pars) const -{ +inline void DiscSurface::initJacobianToGlobal( + const GeometryContext& gctx, ActsMatrixD<7, 5>& jacobian, + const Vector3D& gpos, const Vector3D& dir, + const ActsVectorD<5>& pars) const { // The trigonometry required to convert the direction to spherical // coordinates and then compute the sines and cosines again can be // surprisingly expensive from a performance point of view. @@ -43,93 +38,86 @@ DiscSurface::initJacobianToGlobal(const GeometryContext& gctx, const double z = dir(2); // == cos(theta) // ...which we can invert to directly get the sines and cosines: - const double cos_theta = z; - const double sin_theta = sqrt(x * x + y * y); + const double cos_theta = z; + const double sin_theta = sqrt(x * x + y * y); const double inv_sin_theta = 1. / sin_theta; - const double cos_phi = x * inv_sin_theta; - const double sin_phi = y * inv_sin_theta; + const double cos_phi = x * inv_sin_theta; + const double sin_phi = y * inv_sin_theta; // retrieve the reference frame const auto rframe = referenceFrame(gctx, gpos, dir); // special polar coordinates for the Disc - double lrad = pars[eLOC_0]; - double lphi = pars[eLOC_1]; + double lrad = pars[eLOC_0]; + double lphi = pars[eLOC_1]; double lcos_phi = cos(lphi); double lsin_phi = sin(lphi); // the local error components - rotated from reference frame - jacobian.block<3, 1>(0, eLOC_0) = lcos_phi * rframe.block<3, 1>(0, 0) - + lsin_phi * rframe.block<3, 1>(0, 1); - jacobian.block<3, 1>(0, eLOC_1) - = lrad * (lcos_phi * rframe.block<3, 1>(0, 1) - - lsin_phi * rframe.block<3, 1>(0, 0)); + jacobian.block<3, 1>(0, eLOC_0) = + lcos_phi * rframe.block<3, 1>(0, 0) + lsin_phi * rframe.block<3, 1>(0, 1); + jacobian.block<3, 1>(0, eLOC_1) = + lrad * (lcos_phi * rframe.block<3, 1>(0, 1) - + lsin_phi * rframe.block<3, 1>(0, 0)); // the momentum components - jacobian(3, ePHI) = (-sin_theta) * sin_phi; + jacobian(3, ePHI) = (-sin_theta) * sin_phi; jacobian(3, eTHETA) = cos_theta * cos_phi; - jacobian(4, ePHI) = sin_theta * cos_phi; + jacobian(4, ePHI) = sin_theta * cos_phi; jacobian(4, eTHETA) = cos_theta * sin_phi; jacobian(5, eTHETA) = (-sin_theta); - jacobian(6, eQOP) = 1; + jacobian(6, eQOP) = 1; } -inline const RotationMatrix3D -DiscSurface::initJacobianToLocal(const GeometryContext& gctx, - ActsMatrixD<5, 7>& jacobian, - const Vector3D& gpos, - const Vector3D& dir) const -{ - using VectorHelpers::phi; +inline const RotationMatrix3D DiscSurface::initJacobianToLocal( + const GeometryContext& gctx, ActsMatrixD<5, 7>& jacobian, + const Vector3D& gpos, const Vector3D& dir) const { using VectorHelpers::perp; + using VectorHelpers::phi; // Optimized trigonometry on the propagation direction const double x = dir(0); // == cos(phi) * sin(theta) const double y = dir(1); // == sin(phi) * sin(theta) // component expressions - global - const double inv_sin_theta_2 = 1. / (x * x + y * y); + const double inv_sin_theta_2 = 1. / (x * x + y * y); const double cos_phi_over_sin_theta = x * inv_sin_theta_2; const double sin_phi_over_sin_theta = y * inv_sin_theta_2; - const double inv_sin_theta = sqrt(inv_sin_theta_2); + const double inv_sin_theta = sqrt(inv_sin_theta_2); // The measurement frame of the surface RotationMatrix3D rframeT = referenceFrame(gctx, gpos, dir).transpose(); // calculate the transformation to local coorinates const Vector3D pos_loc = transform(gctx).inverse() * gpos; - const double lr = perp(pos_loc); - const double lphi = phi(pos_loc); - const double lcphi = cos(lphi); - const double lsphi = sin(lphi); + const double lr = perp(pos_loc); + const double lphi = phi(pos_loc); + const double lcphi = cos(lphi); + const double lsphi = sin(lphi); // rotate into the polar coorindates auto lx = rframeT.block<1, 3>(0, 0); auto ly = rframeT.block<1, 3>(1, 0); jacobian.block<1, 3>(0, 0) = lcphi * lx + lsphi * ly; jacobian.block<1, 3>(1, 0) = (lcphi * ly - lsphi * lx) / lr; // Directional and momentum elements for reference frame surface - jacobian(ePHI, 3) = -sin_phi_over_sin_theta; - jacobian(ePHI, 4) = cos_phi_over_sin_theta; + jacobian(ePHI, 3) = -sin_phi_over_sin_theta; + jacobian(ePHI, 4) = cos_phi_over_sin_theta; jacobian(eTHETA, 5) = -inv_sin_theta; - jacobian(eQOP, 6) = 1; + jacobian(eQOP, 6) = 1; // return the transposed reference frame return rframeT; } -inline Intersection -DiscSurface::intersectionEstimate(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& gdir, - NavigationDirection navDir, - const BoundaryCheck& bcheck, - CorrFnc correct) const -{ +inline Intersection DiscSurface::intersectionEstimate( + const GeometryContext& gctx, const Vector3D& gpos, const Vector3D& gdir, + NavigationDirection navDir, const BoundaryCheck& bcheck, + CorrFnc correct) const { // minimize the call to transform() - const auto& tMatrix = transform(gctx).matrix(); + const auto& tMatrix = transform(gctx).matrix(); const Vector3D pnormal = tMatrix.block<3, 1>(0, 2).transpose(); const Vector3D pcenter = tMatrix.block<3, 1>(0, 3).transpose(); // return solution and path Vector3D solution(0., 0., 0.); - double path = std::numeric_limits<double>::infinity(); + double path = std::numeric_limits<double>::infinity(); // lemma : the solver -> should catch current values auto solve = [&solution, &path, &pnormal, &pcenter, &navDir]( - const Vector3D& lpos, const Vector3D& ldir) -> bool { + const Vector3D& lpos, const Vector3D& ldir) -> bool { double denom = ldir.dot(pnormal); if (denom != 0.0) { - path = (pnormal.dot((pcenter - lpos))) / (denom); + path = (pnormal.dot((pcenter - lpos))) / (denom); solution = (lpos + path * ldir); } // is valid if it goes into the right direction @@ -154,27 +142,21 @@ DiscSurface::intersectionEstimate(const GeometryContext& gctx, return Intersection(solution, path, valid); } -inline const Vector3D -DiscSurface::normal(const GeometryContext& gctx, - const Vector2D& /*unused*/) const -{ +inline const Vector3D DiscSurface::normal(const GeometryContext& gctx, + const Vector2D& /*unused*/) const { // fast access via tranform matrix (and not rotation()) const auto& tMatrix = transform(gctx).matrix(); return Vector3D(tMatrix(0, 2), tMatrix(1, 2), tMatrix(2, 2)); } -inline const Vector3D -DiscSurface::binningPosition(const GeometryContext& gctx, - BinningValue /*unused*/) const -{ +inline const Vector3D DiscSurface::binningPosition( + const GeometryContext& gctx, BinningValue /*unused*/) const { return center(gctx); } -inline double -DiscSurface::pathCorrection(const GeometryContext& gctx, - const Vector3D& pos, - const Vector3D& mom) const -{ +inline double DiscSurface::pathCorrection(const GeometryContext& gctx, + const Vector3D& pos, + const Vector3D& mom) const { /// we can ignore the global position here return 1. / std::abs(Surface::normal(gctx, pos).dot(mom.normalized())); } diff --git a/Core/include/Acts/Surfaces/detail/LineSurface.ipp b/Core/include/Acts/Surfaces/detail/LineSurface.ipp index 3b018fa0123458dd9b09bb9575df58afa21f0a35..807eefaca9d43e7c8d45d2b8da30a083fe82ff22 100644 --- a/Core/include/Acts/Surfaces/detail/LineSurface.ipp +++ b/Core/include/Acts/Surfaces/detail/LineSurface.ipp @@ -10,16 +10,13 @@ // LineSurface.ipp, Acts project /////////////////////////////////////////////////////////////////// -inline void -LineSurface::localToGlobal(const GeometryContext& gctx, - const Vector2D& lpos, - const Vector3D& mom, - Vector3D& gpos) const -{ - +inline void LineSurface::localToGlobal(const GeometryContext& gctx, + const Vector2D& lpos, + const Vector3D& mom, + Vector3D& gpos) const { const auto& sTransform = transform(gctx); - const auto& tMatrix = sTransform.matrix(); - Vector3D lineDirection(tMatrix(0, 2), tMatrix(1, 2), tMatrix(2, 2)); + const auto& tMatrix = sTransform.matrix(); + Vector3D lineDirection(tMatrix(0, 2), tMatrix(1, 2), tMatrix(2, 2)); // get the vector perpendicular to the momentum and the straw axis Vector3D radiusAxisGlobal(lineDirection.cross(mom)); @@ -28,17 +25,15 @@ LineSurface::localToGlobal(const GeometryContext& gctx, gpos = Vector3D(locZinGlobal + lpos[eLOC_R] * radiusAxisGlobal.normalized()); } -inline bool -LineSurface::globalToLocal(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& mom, - Vector2D& lpos) const -{ +inline bool LineSurface::globalToLocal(const GeometryContext& gctx, + const Vector3D& gpos, + const Vector3D& mom, + Vector2D& lpos) const { using VectorHelpers::perp; const auto& sTransform = transform(gctx); - const auto& tMatrix = sTransform.matrix(); - Vector3D lineDirection(tMatrix(0, 2), tMatrix(1, 2), tMatrix(2, 2)); + const auto& tMatrix = sTransform.matrix(); + Vector3D lineDirection(tMatrix(0, 2), tMatrix(1, 2), tMatrix(2, 2)); // Bring the global position into the local frame Vector3D loc3Dframe = sTransform.inverse() * gpos; // construct localPosition with sign*perp(candidate) and z.() @@ -51,22 +46,18 @@ LineSurface::globalToLocal(const GeometryContext& gctx, return true; } -inline std::string -LineSurface::name() const -{ +inline std::string LineSurface::name() const { return "Acts::LineSurface"; } -inline const RotationMatrix3D -LineSurface::referenceFrame(const GeometryContext& gctx, - const Vector3D& /*unused*/, - const Vector3D& mom) const -{ +inline const RotationMatrix3D LineSurface::referenceFrame( + const GeometryContext& gctx, const Vector3D& /*unused*/, + const Vector3D& mom) const { RotationMatrix3D mFrame; - const auto& tMatrix = transform(gctx).matrix(); - Vector3D measY(tMatrix(0, 2), tMatrix(1, 2), tMatrix(2, 2)); - Vector3D measX(measY.cross(mom).normalized()); - Vector3D measDepth(measX.cross(measY)); + const auto& tMatrix = transform(gctx).matrix(); + Vector3D measY(tMatrix(0, 2), tMatrix(1, 2), tMatrix(2, 2)); + Vector3D measX(measY.cross(mom).normalized()); + Vector3D measDepth(measX.cross(measY)); // assign the columnes mFrame.col(0) = measX; mFrame.col(1) = measY; @@ -75,57 +66,46 @@ LineSurface::referenceFrame(const GeometryContext& gctx, return mFrame; } -inline double -LineSurface::pathCorrection(const GeometryContext& /*unused*/, - const Vector3D& /*pos*/, - const Vector3D& /*mom*/) const -{ +inline double LineSurface::pathCorrection(const GeometryContext& /*unused*/, + const Vector3D& /*pos*/, + const Vector3D& /*mom*/) const { return 1.; } -inline const Vector3D -LineSurface::binningPosition(const GeometryContext& gctx, - BinningValue /*bValue*/) const -{ +inline const Vector3D LineSurface::binningPosition( + const GeometryContext& gctx, BinningValue /*bValue*/) const { return center(gctx); } -inline const Vector3D -LineSurface::normal(const GeometryContext& gctx, const Vector2D& /*lpos*/) const -{ +inline const Vector3D LineSurface::normal(const GeometryContext& gctx, + const Vector2D& /*lpos*/) const { const auto& tMatrix = transform(gctx).matrix(); return Vector3D(tMatrix(0, 2), tMatrix(1, 2), tMatrix(2, 2)); } -inline const SurfaceBounds& -LineSurface::bounds() const -{ +inline const SurfaceBounds& LineSurface::bounds() const { if (m_bounds) { return (*m_bounds.get()); } return s_noBounds; } -inline Intersection -LineSurface::intersectionEstimate(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& gdir, - NavigationDirection navDir, - const BoundaryCheck& bcheck, - CorrFnc correct) const -{ +inline Intersection LineSurface::intersectionEstimate( + const GeometryContext& gctx, const Vector3D& gpos, const Vector3D& gdir, + NavigationDirection navDir, const BoundaryCheck& bcheck, + CorrFnc correct) const { // following nominclature found in header file and doxygen documentation // line one is the straight track Vector3D ma = gpos; Vector3D ea = gdir; // line two is the line surface const auto& tMatrix = transform(gctx).matrix(); - Vector3D mb = tMatrix.block<3, 1>(0, 3).transpose(); - Vector3D eb = tMatrix.block<3, 1>(0, 2).transpose(); + Vector3D mb = tMatrix.block<3, 1>(0, 3).transpose(); + Vector3D eb = tMatrix.block<3, 1>(0, 2).transpose(); // now go ahead and solve for the closest approach Vector3D mab(mb - ma); - double eaTeb = ea.dot(eb); - double denom = 1 - eaTeb * eaTeb; + double eaTeb = ea.dot(eb); + double denom = 1 - eaTeb * eaTeb; // validity parameter bool valid = false; if (denom * denom > s_onSurfaceTolerance * s_onSurfaceTolerance) { @@ -140,7 +120,7 @@ LineSurface::intersectionEstimate(const GeometryContext& gctx, eaTeb = ea.dot(eb); denom = 1 - eaTeb * eaTeb; if (denom * denom > s_onSurfaceTolerance * s_onSurfaceTolerance) { - u = (mab.dot(ea) - mab.dot(eb) * eaTeb) / denom; + u = (mab.dot(ea) - mab.dot(eb) * eaTeb) / denom; result = (ma + u * ea); // if you have specified a navigation direction, valid mean path > 0. valid = (navDir * u >= 0); @@ -158,13 +138,10 @@ LineSurface::intersectionEstimate(const GeometryContext& gctx, return Intersection(gpos, std::numeric_limits<double>::max(), false); } -inline void -LineSurface::initJacobianToGlobal(const GeometryContext& gctx, - ActsMatrixD<7, 5>& jacobian, - const Vector3D& gpos, - const Vector3D& dir, - const ActsVectorD<5>& pars) const -{ +inline void LineSurface::initJacobianToGlobal( + const GeometryContext& gctx, ActsMatrixD<7, 5>& jacobian, + const Vector3D& gpos, const Vector3D& dir, + const ActsVectorD<5>& pars) const { // The trigonometry required to convert the direction to spherical // coordinates and then compute the sines and cosines again can be // surprisingly expensive from a performance point of view. @@ -176,52 +153,48 @@ LineSurface::initJacobianToGlobal(const GeometryContext& gctx, const double z = dir(2); // == cos(theta) // ...which we can invert to directly get the sines and cosines: - const double cos_theta = z; - const double sin_theta = sqrt(x * x + y * y); + const double cos_theta = z; + const double sin_theta = sqrt(x * x + y * y); const double inv_sin_theta = 1. / sin_theta; - const double cos_phi = x * inv_sin_theta; - const double sin_phi = y * inv_sin_theta; + const double cos_phi = x * inv_sin_theta; + const double sin_phi = y * inv_sin_theta; // retrieve the reference frame const auto rframe = referenceFrame(gctx, gpos, dir); // the local error components - given by the reference frame jacobian.topLeftCorner<3, 2>() = rframe.topLeftCorner<3, 2>(); // the momentum components - jacobian(3, ePHI) = (-sin_theta) * sin_phi; + jacobian(3, ePHI) = (-sin_theta) * sin_phi; jacobian(3, eTHETA) = cos_theta * cos_phi; - jacobian(4, ePHI) = sin_theta * cos_phi; + jacobian(4, ePHI) = sin_theta * cos_phi; jacobian(4, eTHETA) = cos_theta * sin_phi; jacobian(5, eTHETA) = (-sin_theta); - jacobian(6, eQOP) = 1; + jacobian(6, eQOP) = 1; // the projection of direction onto ref frame normal double ipdn = 1. / dir.dot(rframe.col(2)); // build the cross product of d(D)/d(ePHI) components with y axis auto dDPhiY = rframe.block<3, 1>(0, 1).cross(jacobian.block<3, 1>(3, ePHI)); // and the same for the d(D)/d(eTheta) components - auto dDThetaY - = rframe.block<3, 1>(0, 1).cross(jacobian.block<3, 1>(3, eTHETA)); + auto dDThetaY = + rframe.block<3, 1>(0, 1).cross(jacobian.block<3, 1>(3, eTHETA)); // and correct for the x axis components dDPhiY -= rframe.block<3, 1>(0, 0) * (rframe.block<3, 1>(0, 0).dot(dDPhiY)); - dDThetaY - -= rframe.block<3, 1>(0, 0) * (rframe.block<3, 1>(0, 0).dot(dDThetaY)); + dDThetaY -= + rframe.block<3, 1>(0, 0) * (rframe.block<3, 1>(0, 0).dot(dDThetaY)); // set the jacobian components for global d/ phi/Theta - jacobian.block<3, 1>(0, ePHI) = dDPhiY * pars[eLOC_0] * ipdn; + jacobian.block<3, 1>(0, ePHI) = dDPhiY * pars[eLOC_0] * ipdn; jacobian.block<3, 1>(0, eTHETA) = dDThetaY * pars[eLOC_0] * ipdn; } -inline const ActsRowVectorD<5> -LineSurface::derivativeFactors(const GeometryContext& gctx, - const Vector3D& pos, - const Vector3D& dir, - const RotationMatrix3D& rft, - const ActsMatrixD<7, 5>& jac) const -{ +inline const ActsRowVectorD<5> LineSurface::derivativeFactors( + const GeometryContext& gctx, const Vector3D& pos, const Vector3D& dir, + const RotationMatrix3D& rft, const ActsMatrixD<7, 5>& jac) const { // the vector between position and center ActsRowVectorD<3> pc = (pos - center(gctx)).transpose(); // the longitudinal component vector (alogn local z) ActsRowVectorD<3> locz = rft.block<1, 3>(1, 0); // build the norm vector comonent by subtracting the longitudinal one - double long_c = locz * dir; + double long_c = locz * dir; ActsRowVectorD<3> norm_vec = dir.transpose() - long_c * locz; // calculate the s factors for the dependency on X const ActsRowVectorD<5> s_vec = norm_vec * jac.topLeftCorner<3, 5>(); @@ -233,7 +206,6 @@ LineSurface::derivativeFactors(const GeometryContext& gctx, ActsMatrixD<3, 5> long_mat = ActsMatrixD<3, 5>::Zero(); long_mat.colwise() += locz.transpose(); // build the combined normal & longitudinal components - return ( - norm - * (s_vec - pc * (long_mat * d_vec.asDiagonal() - jac.block<3, 5>(3, 0)))); + return (norm * (s_vec - pc * (long_mat * d_vec.asDiagonal() - + jac.block<3, 5>(3, 0)))); } diff --git a/Core/include/Acts/Surfaces/detail/PlaneSurface.ipp b/Core/include/Acts/Surfaces/detail/PlaneSurface.ipp index 1244e7adc9abc94de0376e80cdf85b31962ebb14..5a06a68f37c0204f841ce2ddc680768ba322c868 100644 --- a/Core/include/Acts/Surfaces/detail/PlaneSurface.ipp +++ b/Core/include/Acts/Surfaces/detail/PlaneSurface.ipp @@ -10,52 +10,42 @@ // PlaneSurface.ipp, Acts project /////////////////////////////////////////////////////////////////// -inline const Vector3D -PlaneSurface::normal(const GeometryContext& gctx, - const Vector2D& /*lpos*/) const -{ +inline const Vector3D PlaneSurface::normal(const GeometryContext& gctx, + const Vector2D& /*lpos*/) const { // fast access via tranform matrix (and not rotation()) const auto& tMatrix = transform(gctx).matrix(); return Vector3D(tMatrix(0, 2), tMatrix(1, 2), tMatrix(2, 2)); } -inline const Vector3D -PlaneSurface::binningPosition(const GeometryContext& gctx, - BinningValue /*bValue*/) const -{ +inline const Vector3D PlaneSurface::binningPosition( + const GeometryContext& gctx, BinningValue /*bValue*/) const { return center(gctx); } -inline double -PlaneSurface::pathCorrection(const GeometryContext& gctx, - const Vector3D& pos, - const Vector3D& mom) const -{ +inline double PlaneSurface::pathCorrection(const GeometryContext& gctx, + const Vector3D& pos, + const Vector3D& mom) const { /// we can ignore the global position here return 1. / std::abs(Surface::normal(gctx, pos).dot(mom.normalized())); } -inline Intersection -PlaneSurface::intersectionEstimate(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& gdir, - NavigationDirection navDir, - const BoundaryCheck& bcheck, - CorrFnc correct) const -{ +inline Intersection PlaneSurface::intersectionEstimate( + const GeometryContext& gctx, const Vector3D& gpos, const Vector3D& gdir, + NavigationDirection navDir, const BoundaryCheck& bcheck, + CorrFnc correct) const { // minimize the call to transform() - const auto& tMatrix = transform(gctx).matrix(); + const auto& tMatrix = transform(gctx).matrix(); const Vector3D pnormal = tMatrix.block<3, 1>(0, 2).transpose(); const Vector3D pcenter = tMatrix.block<3, 1>(0, 3).transpose(); // return solution and path Vector3D solution(0., 0., 0.); - double path = std::numeric_limits<double>::infinity(); + double path = std::numeric_limits<double>::infinity(); // lemma : the solver -> should catch current values auto solve = [&solution, &path, &pnormal, &pcenter, &navDir]( - const Vector3D& lpos, const Vector3D& ldir) -> bool { + const Vector3D& lpos, const Vector3D& ldir) -> bool { double denom = ldir.dot(pnormal); if (denom != 0.0) { - path = (pnormal.dot((pcenter - lpos))) / (denom); + path = (pnormal.dot((pcenter - lpos))) / (denom); solution = (lpos + path * ldir); } // is valid if it goes into the right direction diff --git a/Core/include/Acts/Surfaces/detail/Surface.ipp b/Core/include/Acts/Surfaces/detail/Surface.ipp index bfc851e3912ae41b63d9a7ee54c97e99640f2ba1..7f3bbd5875aa7099973fa5721165fcf4813da21a 100644 --- a/Core/include/Acts/Surfaces/detail/Surface.ipp +++ b/Core/include/Acts/Surfaces/detail/Surface.ipp @@ -10,23 +10,19 @@ // Surface.ipp, Acts project /////////////////////////////////////////////////////////////////// -inline const Vector3D -Surface::center(const GeometryContext& gctx) const -{ +inline const Vector3D Surface::center(const GeometryContext& gctx) const { // fast access via tranform matrix (and not translation()) auto tMatrix = transform(gctx).matrix(); return Vector3D(tMatrix(0, 3), tMatrix(1, 3), tMatrix(2, 3)); } -inline const Acts::Vector3D -Surface::normal(const GeometryContext& gctx, const Vector3D& /*unused*/) const -{ +inline const Acts::Vector3D Surface::normal(const GeometryContext& gctx, + const Vector3D& /*unused*/) const { return normal(gctx, s_origin2D); } -inline const Transform3D& -Surface::transform(const GeometryContext& gctx) const -{ +inline const Transform3D& Surface::transform( + const GeometryContext& gctx) const { if (m_transform != nullptr) { return (*(m_transform.get())); } @@ -36,27 +32,21 @@ Surface::transform(const GeometryContext& gctx) const return s_idTransform; } -inline bool -Surface::insideBounds(const Vector2D& locpos, const BoundaryCheck& bcheck) const -{ +inline bool Surface::insideBounds(const Vector2D& locpos, + const BoundaryCheck& bcheck) const { return bounds().inside(locpos, bcheck); } -inline const RotationMatrix3D -Surface::referenceFrame(const GeometryContext& gctx, - const Vector3D& /*unused*/, - const Vector3D& /*unused*/) const -{ +inline const RotationMatrix3D Surface::referenceFrame( + const GeometryContext& gctx, const Vector3D& /*unused*/, + const Vector3D& /*unused*/) const { return transform(gctx).matrix().block<3, 3>(0, 0); } -inline void -Surface::initJacobianToGlobal(const GeometryContext& gctx, - ActsMatrixD<7, 5>& jacobian, - const Vector3D& gpos, - const Vector3D& dir, - const ActsVectorD<5>& /*pars*/) const -{ +inline void Surface::initJacobianToGlobal( + const GeometryContext& gctx, ActsMatrixD<7, 5>& jacobian, + const Vector3D& gpos, const Vector3D& dir, + const ActsVectorD<5>& /*pars*/) const { // The trigonometry required to convert the direction to spherical // coordinates and then compute the sines and cosines again can be // surprisingly expensive from a performance point of view. @@ -68,58 +58,52 @@ Surface::initJacobianToGlobal(const GeometryContext& gctx, const double z = dir(2); // == cos(theta) // ...which we can invert to directly get the sines and cosines: - const double cos_theta = z; - const double sin_theta = sqrt(x * x + y * y); + const double cos_theta = z; + const double sin_theta = sqrt(x * x + y * y); const double inv_sin_theta = 1. / sin_theta; - const double cos_phi = x * inv_sin_theta; - const double sin_phi = y * inv_sin_theta; + const double cos_phi = x * inv_sin_theta; + const double sin_phi = y * inv_sin_theta; // retrieve the reference frame const auto rframe = referenceFrame(gctx, gpos, dir); // the local error components - given by reference frame jacobian.topLeftCorner<3, 2>() = rframe.topLeftCorner<3, 2>(); // the momentum components - jacobian(3, ePHI) = (-sin_theta) * sin_phi; + jacobian(3, ePHI) = (-sin_theta) * sin_phi; jacobian(3, eTHETA) = cos_theta * cos_phi; - jacobian(4, ePHI) = sin_theta * cos_phi; + jacobian(4, ePHI) = sin_theta * cos_phi; jacobian(4, eTHETA) = cos_theta * sin_phi; jacobian(5, eTHETA) = (-sin_theta); - jacobian(6, eQOP) = 1; + jacobian(6, eQOP) = 1; } -inline const RotationMatrix3D -Surface::initJacobianToLocal(const GeometryContext& gctx, - ActsMatrixD<5, 7>& jacobian, - const Vector3D& gpos, - const Vector3D& dir) const -{ +inline const RotationMatrix3D Surface::initJacobianToLocal( + const GeometryContext& gctx, ActsMatrixD<5, 7>& jacobian, + const Vector3D& gpos, const Vector3D& dir) const { // Optimized trigonometry on the propagation direction const double x = dir(0); // == cos(phi) * sin(theta) const double y = dir(1); // == sin(phi) * sin(theta) // component expressions - const double inv_sin_theta_2 = 1. / (x * x + y * y); + const double inv_sin_theta_2 = 1. / (x * x + y * y); const double cos_phi_over_sin_theta = x * inv_sin_theta_2; const double sin_phi_over_sin_theta = y * inv_sin_theta_2; - const double inv_sin_theta = sqrt(inv_sin_theta_2); + const double inv_sin_theta = sqrt(inv_sin_theta_2); // The measurement frame of the surface RotationMatrix3D rframeT = referenceFrame(gctx, gpos, dir).transpose(); // given by the refernece frame jacobian.block<2, 3>(0, 0) = rframeT.block<2, 3>(0, 0); // Directional and momentum elements for reference frame surface - jacobian(ePHI, 3) = -sin_phi_over_sin_theta; - jacobian(ePHI, 4) = cos_phi_over_sin_theta; + jacobian(ePHI, 3) = -sin_phi_over_sin_theta; + jacobian(ePHI, 4) = cos_phi_over_sin_theta; jacobian(eTHETA, 5) = -inv_sin_theta; - jacobian(eQOP, 6) = 1; + jacobian(eQOP, 6) = 1; // return the frame where this happened return rframeT; } -inline const ActsRowVectorD<5> -Surface::derivativeFactors(const GeometryContext& /*unused*/, - const Vector3D& /*unused*/, - const Vector3D& dir, - const RotationMatrix3D& rft, - const ActsMatrixD<7, 5>& jac) const -{ +inline const ActsRowVectorD<5> Surface::derivativeFactors( + const GeometryContext& /*unused*/, const Vector3D& /*unused*/, + const Vector3D& dir, const RotationMatrix3D& rft, + const ActsMatrixD<7, 5>& jac) const { // Create the normal and scale it with the projection onto the direction ActsRowVectorD<3> norm_vec = rft.template block<1, 3>(2, 0); norm_vec /= (norm_vec * dir); @@ -128,11 +112,8 @@ Surface::derivativeFactors(const GeometryContext& /*unused*/, } template <typename parameters_t> -bool -Surface::isOnSurface(const GeometryContext& gctx, - const parameters_t& pars, - const BoundaryCheck& bcheck) const -{ +bool Surface::isOnSurface(const GeometryContext& gctx, const parameters_t& pars, + const BoundaryCheck& bcheck) const { // surface pointer comparison as a first fast check (w/o transform) // @todo check if we can find a fast way that works for stepper state and // parameters @@ -140,32 +121,23 @@ Surface::isOnSurface(const GeometryContext& gctx, return isOnSurface(gctx, pars.position(), pars.momentum(), bcheck); } -inline const DetectorElementBase* -Surface::associatedDetectorElement() const -{ +inline const DetectorElementBase* Surface::associatedDetectorElement() const { return m_associatedDetElement; } -inline const Layer* -Surface::associatedLayer() const -{ +inline const Layer* Surface::associatedLayer() const { return (m_associatedLayer); } -inline const ISurfaceMaterial* -Surface::surfaceMaterial() const -{ +inline const ISurfaceMaterial* Surface::surfaceMaterial() const { return m_surfaceMaterial.get(); } -inline void -Surface::assignSurfaceMaterial(std::shared_ptr<const ISurfaceMaterial> material) -{ +inline void Surface::assignSurfaceMaterial( + std::shared_ptr<const ISurfaceMaterial> material) { m_surfaceMaterial = std::move(material); } -inline void -Surface::associateLayer(const Layer& lay) -{ +inline void Surface::associateLayer(const Layer& lay) { m_associatedLayer = (&lay); } diff --git a/Core/include/Acts/Utilities/BinAdjustment.hpp b/Core/include/Acts/Utilities/BinAdjustment.hpp index 6422fa0d7ccd05ef495e7e1707a3a72bdab1f971..011620157598ea31be5ea5f6fe1d986c19716e3c 100644 --- a/Core/include/Acts/Utilities/BinAdjustment.hpp +++ b/Core/include/Acts/Utilities/BinAdjustment.hpp @@ -27,14 +27,12 @@ namespace Acts { /// @param rBounds the Radial bounds to adjust to /// /// @return new updated BinUtiltiy -BinUtility -adjustBinUtility(const BinUtility& bu, const RadialBounds& rBounds) -{ +BinUtility adjustBinUtility(const BinUtility& bu, const RadialBounds& rBounds) { // Default constructor BinUtility uBinUtil; // The parameters from the cylinder bounds - double minR = rBounds.rMin(); - double maxR = rBounds.rMax(); + double minR = rBounds.rMin(); + double maxR = rBounds.rMax(); double minPhi = rBounds.averagePhi() - rBounds.halfPhiSector(); double maxPhi = rBounds.averagePhi() + rBounds.halfPhiSector(); // Retrieve the binning data @@ -73,14 +71,13 @@ adjustBinUtility(const BinUtility& bu, const RadialBounds& rBounds) /// @param cBounds the Cylinder bounds to adjust to /// /// @return new updated BinUtiltiy -BinUtility -adjustBinUtility(const BinUtility& bu, const CylinderBounds& cBounds) -{ +BinUtility adjustBinUtility(const BinUtility& bu, + const CylinderBounds& cBounds) { // Default constructor BinUtility uBinUtil; // The parameters from the cylinder bounds - double cR = cBounds.r(); - double cHz = cBounds.halflengthZ(); + double cR = cBounds.r(); + double cHz = cBounds.halflengthZ(); double minPhi = cBounds.averagePhi() - cBounds.halfPhiSector(); double maxPhi = cBounds.averagePhi() + cBounds.halfPhiSector(); // Retrieve the binning data @@ -122,9 +119,7 @@ adjustBinUtility(const BinUtility& bu, const CylinderBounds& cBounds) /// @param Surface to which the adjustment is being done /// /// @return new updated BinUtiltiy -BinUtility -adjustBinUtility(const BinUtility& bu, const Surface& surface) -{ +BinUtility adjustBinUtility(const BinUtility& bu, const Surface& surface) { // The surface type is a cylinder if (surface.type() == Surface::Cylinder) { // Cast to Cylinder bounds and return diff --git a/Core/include/Acts/Utilities/BinUtility.hpp b/Core/include/Acts/Utilities/BinUtility.hpp index 086a5c6e393bec5246dd31b58e0868dee79effaa..e93d4b19cfe7a59099986e49725bb73bed47b243 100644 --- a/Core/include/Acts/Utilities/BinUtility.hpp +++ b/Core/include/Acts/Utilities/BinUtility.hpp @@ -31,12 +31,10 @@ namespace Acts { /// is /// defined on, for performance reasons, also the inverse transform is stored. /// -class BinUtility -{ -public: +class BinUtility { + public: /// Constructor for equidistant - BinUtility() : m_binningData(), m_transform(nullptr), m_itransform(nullptr) - { + BinUtility() : m_binningData(), m_transform(nullptr), m_itransform(nullptr) { m_binningData.reserve(3); } @@ -44,12 +42,11 @@ public: /// /// @param bData is the provided binning data /// @param tForm is the (optional) transform - BinUtility(const BinningData& bData, + BinUtility(const BinningData& bData, const std::shared_ptr<const Transform3D>& tForm = nullptr) - : m_binningData() - , m_transform(tForm) - , m_itransform(tForm ? new Transform3D(tForm->inverse()) : nullptr) - { + : m_binningData(), + m_transform(tForm), + m_itransform(tForm ? new Transform3D(tForm->inverse()) : nullptr) { m_binningData.reserve(3); m_binningData.push_back(bData); } @@ -62,16 +59,12 @@ public: /// @param opt is the binning option : open, closed /// @param value is the binninb value : binX, binY, binZ, etc. /// @param tForm is the (optional) transform - BinUtility(size_t bins, - float min, - float max, - BinningOption opt = open, - BinningValue value = binX, + BinUtility(size_t bins, float min, float max, BinningOption opt = open, + BinningValue value = binX, const std::shared_ptr<const Transform3D>& tForm = nullptr) - : m_binningData() - , m_transform(tForm) - , m_itransform(tForm ? new Transform3D(tForm->inverse()) : nullptr) - { + : m_binningData(), + m_transform(tForm), + m_itransform(tForm ? new Transform3D(tForm->inverse()) : nullptr) { m_binningData.reserve(3); m_binningData.push_back(BinningData(opt, value, bins, min, max)); } @@ -82,14 +75,12 @@ public: /// @param opt is the binning option : open, closed /// @param value is the binninb value : binX, binY, binZ, etc. /// @param tForm is the (optional) transform - BinUtility(std::vector<float>& bValues, - BinningOption opt = open, - BinningValue value = binPhi, + BinUtility(std::vector<float>& bValues, BinningOption opt = open, + BinningValue value = binPhi, const std::shared_ptr<const Transform3D>& tForm = nullptr) - : m_binningData() - , m_transform(tForm) - , m_itransform(tForm ? new Transform3D(tForm->inverse()) : nullptr) - { + : m_binningData(), + m_transform(tForm), + m_itransform(tForm ? new Transform3D(tForm->inverse()) : nullptr) { m_binningData.reserve(3); m_binningData.push_back(BinningData(opt, value, bValues)); } @@ -98,26 +89,23 @@ public: /// /// @param sbu is the source bin utility BinUtility(const BinUtility& sbu) - : m_binningData(sbu.m_binningData) - , m_transform(sbu.m_transform) - , m_itransform(sbu.m_transform ? new Transform3D(sbu.m_transform->inverse()) - : nullptr) - { - } + : m_binningData(sbu.m_binningData), + m_transform(sbu.m_transform), + m_itransform(sbu.m_transform + ? new Transform3D(sbu.m_transform->inverse()) + : nullptr) {} /// Assignment operator /// /// @param sbu is the source bin utility - BinUtility& - operator=(const BinUtility& sbu) - { + BinUtility& operator=(const BinUtility& sbu) { if (this != &sbu) { m_binningData = sbu.m_binningData; - m_transform = sbu.m_transform; - m_itransform = sbu.m_transform - ? std::unique_ptr<const Transform3D>( - new Transform3D(sbu.m_transform->inverse())) - : nullptr; + m_transform = sbu.m_transform; + m_itransform = sbu.m_transform + ? std::unique_ptr<const Transform3D>( + new Transform3D(sbu.m_transform->inverse())) + : nullptr; } return (*this); } @@ -125,24 +113,22 @@ public: /// Operator++ to make multidimensional BinUtility /// /// @param gbu is the additional BinUtility to be chosen - BinUtility& - operator+=(const BinUtility& gbu) - { + BinUtility& operator+=(const BinUtility& gbu) { const std::vector<BinningData>& bData = gbu.binningData(); if (m_transform == nullptr && gbu.transform() != nullptr) { // use other transform m_transform = gbu.transform(); - m_itransform - = std::make_unique<const Transform3D>(m_transform->inverse()); + m_itransform = + std::make_unique<const Transform3D>(m_transform->inverse()); } else if (m_transform != nullptr && gbu.transform() != nullptr) { // combine two existing transform // note that this might lead to undesired behaviour of the combined // BinUtility - m_transform = std::make_shared<const Transform3D>((*m_transform) - * (*gbu.transform())); - m_itransform - = std::make_unique<const Transform3D>(m_transform->inverse()); + m_transform = std::make_shared<const Transform3D>((*m_transform) * + (*gbu.transform())); + m_itransform = + std::make_unique<const Transform3D>(m_transform->inverse()); } // else { // only this BU has transform, just keep it. //} @@ -157,25 +143,13 @@ public: /// Virtual Destructor ~BinUtility() = default; /// Implizit Constructor - BinUtility* - clone() const - { - return new BinUtility(*this); - } + BinUtility* clone() const { return new BinUtility(*this); } /// return the binning data vector - const std::vector<BinningData>& - binningData() const - { - return m_binningData; - } + const std::vector<BinningData>& binningData() const { return m_binningData; } /// Return the total number of bins - size_t - bins() const - { - return bins(0) * bins(1) * bins(2); - } + size_t bins() const { return bins(0) * bins(1) * bins(2); } /// Bin-triple fast access /// @@ -184,12 +158,10 @@ public: /// @param position is the 3D position to be evaluated /// /// @return is the bin value in 3D - std::array<size_t, 3> - binTriple(const Vector3D& position) const - { + std::array<size_t, 3> binTriple(const Vector3D& position) const { /// transform or not - const Vector3D& bPosition - = m_itransform ? Vector3D((*m_itransform) * position) : position; + const Vector3D& bPosition = + m_itransform ? Vector3D((*m_itransform) * position) : position; // get the dimension size_t mdim = m_binningData.size(); /// now get the bins @@ -207,15 +179,14 @@ public: /// @param ba is the bin dimension /// /// @return is the bin value - size_t - bin(const Vector3D& position, size_t ba = 0) const - { + size_t bin(const Vector3D& position, size_t ba = 0) const { if (ba >= m_binningData.size()) { return 0; } - size_t bEval = m_itransform - ? m_binningData[ba].searchGlobal((*m_itransform) * position) - : m_binningData[ba].searchGlobal(position); + size_t bEval = + m_itransform + ? m_binningData[ba].searchGlobal((*m_itransform) * position) + : m_binningData[ba].searchGlobal(position); return bEval; } @@ -229,16 +200,15 @@ public: /// @param ba is the binning accessor /// /// @return a vector of neighbour sizes - std::vector<size_t> - neighbourRange(const Vector3D& position, size_t ba = 0) const - { + std::vector<size_t> neighbourRange(const Vector3D& position, + size_t ba = 0) const { if (ba >= m_binningData.size()) { return {0}; } std::vector<size_t> neighbourRange; - size_t cbin = bin(position, ba); - size_t pbin = cbin; - size_t nbin = cbin; + size_t cbin = bin(position, ba); + size_t pbin = cbin; + size_t nbin = cbin; if (m_binningData[ba].decrement(pbin)) { neighbourRange.push_back(pbin); } @@ -258,11 +228,8 @@ public: /// @todo the /// /// @return the next bin - int - nextDirection(const Vector3D& position, - const Vector3D& direction, - size_t ba = 0) const - { + int nextDirection(const Vector3D& position, const Vector3D& direction, + size_t ba = 0) const { if (ba >= m_binningData.size()) { return 0; } @@ -280,9 +247,7 @@ public: /// @param ba is the bin dimension /// /// @return bin calculated from local - size_t - bin(const Vector2D& lposition, size_t ba = 0) const - { + size_t bin(const Vector2D& lposition, size_t ba = 0) const { if (ba >= m_binningData.size()) { return 0; } @@ -292,12 +257,10 @@ public: /// /// @param position is the global position to be evaluated /// @return is a boolean check - bool - inside(const Vector3D& position) const - { + bool inside(const Vector3D& position) const { /// transform or not - const Vector3D& bPosition - = m_itransform ? Vector3D((*m_itransform) * position) : position; + const Vector3D& bPosition = + m_itransform ? Vector3D((*m_itransform) * position) : position; // loop and break for (auto& bData : m_binningData) { if (!(bData.inside(bPosition))) { @@ -312,9 +275,7 @@ public: /// /// @param lposition is the local position to be evaluated /// @return is a boolean check - bool - inside(const Vector2D& lposition) const - { + bool inside(const Vector2D& lposition) const { return true; std::vector<BinningData>::const_iterator bdIter = m_binningData.begin(); for (; bdIter != m_binningData.end(); ++bdIter) { @@ -327,20 +288,14 @@ public: /// First bin maximal value /// @return the dimenstion of the binning data - size_t - dimensions() const - { - return m_binningData.size(); - } + size_t dimensions() const { return m_binningData.size(); } /// First bin maximal value /// /// @param ba is the binaccessor /// /// @return size_t is the maximal bin of the accessor entry - size_t - max(size_t ba = 0) const - { + size_t max(size_t ba = 0) const { if (ba >= m_binningData.size()) { return 0; } @@ -352,9 +307,7 @@ public: /// @param ba is the binaccessor /// /// @return size_t is the bins of the accessor entry - size_t - bins(size_t ba) const - { + size_t bins(size_t ba) const { if (ba >= m_binningData.size()) { return 1; } @@ -364,20 +317,14 @@ public: /// Transform applied to global positions before lookup /// /// @return Shared pointer to transform - std::shared_ptr<const Transform3D> - transform() const - { - return m_transform; - } + std::shared_ptr<const Transform3D> transform() const { return m_transform; } /// The type/value of the binning /// /// @param ba is the binaccessor /// /// @return the binning value of the accessor entry - BinningValue - binningValue(size_t ba = 0) const - { + BinningValue binningValue(size_t ba = 0) const { if (ba >= m_binningData.size()) { throw "dimension out of bounds"; } @@ -388,15 +335,13 @@ public: /// - this creates a simple size_t from a triple object /// /// @param bin is the bin to be serialized - size_t - serialize(const std::array<size_t, 3>& bin) const - { + size_t serialize(const std::array<size_t, 3>& bin) const { size_t serializedBin = bin[0]; if (m_binningData.size() == 2) { serializedBin += bin[1] * m_binningData[0].bins(); } else if (m_binningData.size() == 3) { - serializedBin += (bin[1] * m_binningData[0].bins() * bin[2] - * m_binningData[1].bins()); + serializedBin += + (bin[1] * m_binningData[0].bins() * bin[2] * m_binningData[1].bins()); } return serializedBin; } @@ -404,9 +349,7 @@ public: /// Output Method for std::ostream, to be overloaded by child classes /// /// @param sl is the ostream to be dumped into - std::ostream& - toStream(std::ostream& sl) const - { + std::ostream& toStream(std::ostream& sl) const { sl << "BinUtility for " << m_binningData.size() << "- dimensional array:" << std::endl; std::vector<BinningData>::const_iterator bdIter = m_binningData.begin(); @@ -431,14 +374,13 @@ public: return sl; } -private: - std::vector<BinningData> m_binningData; /// vector of BinningData - std::shared_ptr<const Transform3D> m_transform; /// shared transform + private: + std::vector<BinningData> m_binningData; /// vector of BinningData + std::shared_ptr<const Transform3D> m_transform; /// shared transform std::unique_ptr<const Transform3D> m_itransform; /// unique inverse transform }; /// Overload of << operator for std::ostream for debug output -std::ostream& -operator<<(std::ostream& sl, const BinUtility& bgen); +std::ostream& operator<<(std::ostream& sl, const BinUtility& bgen); } // namespace Acts diff --git a/Core/include/Acts/Utilities/BinnedArray.hpp b/Core/include/Acts/Utilities/BinnedArray.hpp index a6c170ac86b60a26d5cb9daa9ee8e7fb43ba2266..ed8e2906abaa26332132c94afa2558597abc14a8 100644 --- a/Core/include/Acts/Utilities/BinnedArray.hpp +++ b/Core/include/Acts/Utilities/BinnedArray.hpp @@ -27,9 +27,8 @@ namespace Acts { /// /// - the BinnedArray is designed for 0D, 1D, 2D, and 3D binning template <class T> -class BinnedArray -{ -public: +class BinnedArray { + public: /// Default Constructor - needed for inherited classes BinnedArray() = default; /// Virtual Destructor @@ -40,17 +39,15 @@ public: /// @param bins is the bin triple to filled /// /// @return the object according to the estimated bin - virtual T - object(const Vector2D& lposition, std::array<size_t, 3>& bins) const = 0; + virtual T object(const Vector2D& lposition, + std::array<size_t, 3>& bins) const = 0; /// Same method without bins for backward compatibility /// /// @param lposition is the local position for finding the obect /// /// @return the object according to the estimated bin - virtual T - object(const Vector2D& lposition) const - { + virtual T object(const Vector2D& lposition) const { std::array<size_t, 3> bins; return object(lposition, bins); } @@ -61,17 +58,15 @@ public: /// @param bin is the bin triple filled /// /// @return the object according to the estimated bin - virtual T - object(const Vector3D& position, std::array<size_t, 3>& bin) const = 0; + virtual T object(const Vector3D& position, + std::array<size_t, 3>& bin) const = 0; /// Same method without bins for backward compatibility /// /// @param position is the global position for the object finding /// /// @return the object according to the estimated bin - virtual T - object(const Vector3D& position) const - { + virtual T object(const Vector3D& position) const { std::array<size_t, 3> bins; return object(position, bins); } @@ -84,25 +79,23 @@ public: /// @param bin is the binning /// /// @return a vector of unique objects - virtual std::vector<T> - objectCluster(const std::array<size_t, 3>& bin) const = 0; + virtual std::vector<T> objectCluster( + const std::array<size_t, 3>& bin) const = 0; /// Return all unqiue object /// @note this is the accessor to the /// @return the vector of all array objects - virtual const std::vector<T>& - arrayObjects() const = 0; + virtual const std::vector<T>& arrayObjects() const = 0; /// Return the object grid multiple entries are allowed /// @return the object grid - virtual const std::vector<std::vector<std::vector<T>>>& - objectGrid() const = 0; + virtual const std::vector<std::vector<std::vector<T>>>& objectGrid() + const = 0; /// Return the BinUtility /// - if returned 0 it is a 0D array /// @return plain pointer to the bin utility - virtual const BinUtility* - binUtility() const = 0; + virtual const BinUtility* binUtility() const = 0; }; } // namespace Acts diff --git a/Core/include/Acts/Utilities/BinnedArrayXD.hpp b/Core/include/Acts/Utilities/BinnedArrayXD.hpp index 66b8c7185410d0744c9aa99f047b764d41fc44b2..f713914e5392a5aee5ab4729e83d3d4b76b329ff 100644 --- a/Core/include/Acts/Utilities/BinnedArrayXD.hpp +++ b/Core/include/Acts/Utilities/BinnedArrayXD.hpp @@ -30,22 +30,20 @@ namespace Acts { /// /// the type of Binning is given defined through the BinUtility template <class T> -class BinnedArrayXD : public BinnedArray<T> -{ +class BinnedArrayXD : public BinnedArray<T> { /// typedef the object and position for readability using TAP = std::pair<T, Vector3D>; -public: + public: /// Constructor for single object /// /// @tparam object is the single object BinnedArrayXD(T object) - : BinnedArray<T>() - , m_objectGrid(1, - std::vector<std::vector<T>>(1, std::vector<T>(1, nullptr))) - , m_arrayObjects({object}) - , m_binUtility(nullptr) - { + : BinnedArray<T>(), + m_objectGrid( + 1, std::vector<std::vector<T>>(1, std::vector<T>(1, nullptr))), + m_arrayObjects({object}), + m_binUtility(nullptr) { /// fill the single object into the object grid m_objectGrid[0][0][0] = object; } @@ -55,16 +53,14 @@ public: /// /// @param tapvector is a vector of object and binning position /// @param bu is the unique bin utility for this binned array - BinnedArrayXD(const std::vector<TAP>& tapvector, + BinnedArrayXD(const std::vector<TAP>& tapvector, std::unique_ptr<const BinUtility> bu) - : BinnedArray<T>() - , m_objectGrid( - bu->bins(2), - std::vector<std::vector<T>>(bu->bins(1), - std::vector<T>(bu->bins(0), nullptr))) - , m_arrayObjects() - , m_binUtility(std::move(bu)) - { + : BinnedArray<T>(), + m_objectGrid(bu->bins(2), + std::vector<std::vector<T>>( + bu->bins(1), std::vector<T>(bu->bins(0), nullptr))), + m_arrayObjects(), + m_binUtility(std::move(bu)) { /// reserve the right amount of data m_arrayObjects.reserve(tapvector.size()); /// loop over the object & position for ordering @@ -77,8 +73,8 @@ public: /// fill the data m_objectGrid[bins[2]][bins[1]][bins[0]] = tap.first; /// fill the unique m_arrayObjects - if (std::find(m_arrayObjects.begin(), m_arrayObjects.end(), tap.first) - == m_arrayObjects.end()) { + if (std::find(m_arrayObjects.begin(), m_arrayObjects.end(), + tap.first) == m_arrayObjects.end()) { m_arrayObjects.push_back(tap.first); } } @@ -90,15 +86,14 @@ public: /// @param grid is the prepared object grid /// @param bu is the unique bin utility for this binned array BinnedArrayXD(const std::vector<std::vector<std::vector<T>>>& grid, - std::unique_ptr<const BinUtility> bu) - : BinnedArray<T>() - , m_objectGrid(grid) - , m_arrayObjects() - , m_binUtility(std::move(bu)) - { + std::unique_ptr<const BinUtility> bu) + : BinnedArray<T>(), + m_objectGrid(grid), + m_arrayObjects(), + m_binUtility(std::move(bu)) { // get the total dimension - size_t objects - = m_binUtility->bins(0) * m_binUtility->bins(1) * m_binUtility->bins(2); + size_t objects = + m_binUtility->bins(0) * m_binUtility->bins(1) * m_binUtility->bins(2); /// reserve the right amount of data m_arrayObjects.reserve(objects); /// loop over the object & position for ordering @@ -107,8 +102,8 @@ public: for (auto& o0 : o1) { if (o0) { /// fill the unique m_arrayObjects - if (std::find(m_arrayObjects.begin(), m_arrayObjects.end(), o0) - == m_arrayObjects.end()) { + if (std::find(m_arrayObjects.begin(), m_arrayObjects.end(), o0) == + m_arrayObjects.end()) { m_arrayObjects.push_back(o0); } } @@ -123,9 +118,7 @@ public: /// Assignment operator /// - not allowed, use the same array - BinnedArrayXD& - operator=(const BinnedArrayXD<T>& barr) - = delete; + BinnedArrayXD& operator=(const BinnedArrayXD<T>& barr) = delete; /// Destructor ~BinnedArrayXD() override = default; @@ -137,23 +130,19 @@ public: /// @param bins is the bin triple filled during this access /// /// @return is the object in that bin - T - object(const Vector2D& lposition, std::array<size_t, 3>& bins) const final - { + T object(const Vector2D& lposition, std::array<size_t, 3>& bins) const final { if (m_binUtility) { size_t bdim = m_binUtility->dimensions(); - bins[2] = bdim > 2 ? m_binUtility->bin(lposition, 2) : 0; - bins[1] = bdim > 1 ? m_binUtility->bin(lposition, 1) : 0; - bins[0] = m_binUtility->bin(lposition, 0); + bins[2] = bdim > 2 ? m_binUtility->bin(lposition, 2) : 0; + bins[1] = bdim > 1 ? m_binUtility->bin(lposition, 1) : 0; + bins[0] = m_binUtility->bin(lposition, 0); return m_objectGrid[bins[2]][bins[1]][bins[0]]; } return m_objectGrid[0][0][0]; } // satisfy overload / override - T - object(const Vector2D& lposition) const override - { + T object(const Vector2D& lposition) const override { std::array<size_t, 3> bins; return object(lposition, bins); } @@ -164,41 +153,31 @@ public: /// @param bins is the bins triple filled during access /// /// @return is the object in that bin - T - object(const Vector3D& position, std::array<size_t, 3>& bins) const final - { + T object(const Vector3D& position, std::array<size_t, 3>& bins) const final { if (m_binUtility) { size_t bdim = m_binUtility->dimensions(); - bins[2] = bdim > 2 ? m_binUtility->bin(position, 2) : 0; - bins[1] = bdim > 1 ? m_binUtility->bin(position, 1) : 0; - bins[0] = m_binUtility->bin(position, 0); + bins[2] = bdim > 2 ? m_binUtility->bin(position, 2) : 0; + bins[1] = bdim > 1 ? m_binUtility->bin(position, 1) : 0; + bins[0] = m_binUtility->bin(position, 0); return m_objectGrid[bins[2]][bins[1]][bins[0]]; } return m_objectGrid[0][0][0]; } // satisfy overload / override - T - object(const Vector3D& position) const override - { + T object(const Vector3D& position) const override { std::array<size_t, 3> bins; return object(position, bins); } /// Return all unqiue object /// @return vector of unique array objects - const std::vector<T>& - arrayObjects() const final - { - return m_arrayObjects; - } + const std::vector<T>& arrayObjects() const final { return m_arrayObjects; } /// Return the object grid /// multiple entries are allowed and wanted /// @return internal object grid - const std::vector<std::vector<std::vector<T>>>& - objectGrid() const final - { + const std::vector<std::vector<std::vector<T>>>& objectGrid() const final { return m_objectGrid; } @@ -208,9 +187,8 @@ public: /// @param binTriple is the binning /// /// @return a vector of unique objects - std::vector<T> - objectCluster(const std::array<size_t, 3>& binTriple) const override - { + std::vector<T> objectCluster( + const std::array<size_t, 3>& binTriple) const override { // prepare the return vector std::vector<T> rvector; // reference bin object to be excluded @@ -220,16 +198,16 @@ public: // avoiding code duplication std::vector<size_t> zerorange = {0}; // 2D bin - std::vector<size_t> bin2values = (bdim > 2) - ? m_binUtility->binningData()[2].neighbourRange(binTriple[2]) - : zerorange; + std::vector<size_t> bin2values = + (bdim > 2) ? m_binUtility->binningData()[2].neighbourRange(binTriple[2]) + : zerorange; // 1D bin - std::vector<size_t> bin1values = (bdim > 1) - ? m_binUtility->binningData()[1].neighbourRange(binTriple[1]) - : zerorange; + std::vector<size_t> bin1values = + (bdim > 1) ? m_binUtility->binningData()[1].neighbourRange(binTriple[1]) + : zerorange; // 0D bin - std::vector<size_t> bin0values - = m_binUtility->binningData()[0].neighbourRange(binTriple[0]); + std::vector<size_t> bin0values = + m_binUtility->binningData()[0].neighbourRange(binTriple[0]); // do the loop for (auto b2 : bin2values) { @@ -237,9 +215,9 @@ public: for (auto b0 : bin0values) { // get the object T object = m_objectGrid[b2][b1][b0]; - if (object && object != bObject - && std::find(rvector.begin(), rvector.end(), object) - == rvector.end()) { + if (object && object != bObject && + std::find(rvector.begin(), rvector.end(), object) == + rvector.end()) { rvector.push_back(object); } } @@ -251,13 +229,9 @@ public: /// Return the BinUtility /// @return plain pointer to the bin utility of this array - const BinUtility* - binUtility() const final - { - return (m_binUtility.get()); - } + const BinUtility* binUtility() const final { return (m_binUtility.get()); } -private: + private: /// the data store - a 3D array at default std::vector<std::vector<std::vector<T>>> m_objectGrid; /// Vector of unique Array objects diff --git a/Core/include/Acts/Utilities/BinningData.hpp b/Core/include/Acts/Utilities/BinningData.hpp index d2b215cfa7caaeb0307774d1fe3f5d9057e350a9..64694acc44540338030d9b2f746841cd61f39a77 100644 --- a/Core/include/Acts/Utilities/BinningData.hpp +++ b/Core/include/Acts/Utilities/BinningData.hpp @@ -37,16 +37,15 @@ namespace Acts { /// additive : sub structure replaces one bin (and one bin only) /// /// -class BinningData -{ -public: - BinningType type; ///< binning type: equidistant, arbitrary - BinningOption option; ///< binning option: open, closed - BinningValue binvalue; ///< binning value: binX, binY, binZ, binR ... - float min; ///< minimum value - float max; ///< maximum value - float step; ///< binning step - bool zdim; ///< zero dimensional binning : direct access +class BinningData { + public: + BinningType type; ///< binning type: equidistant, arbitrary + BinningOption option; ///< binning option: open, closed + BinningValue binvalue; ///< binning value: binX, binY, binZ, binR ... + float min; ///< minimum value + float max; ///< maximum value + float step; ///< binning step + bool zdim; ///< zero dimensional binning : direct access /// sub structure: describe some sub binning std::unique_ptr<const BinningData> subBinningData; @@ -59,22 +58,20 @@ public: /// @param bMin is the minum value /// @param bMax is the maxmimum value BinningData(BinningValue bValue, float bMin, float bMax) - : type(equidistant) - , option(open) - , binvalue(bValue) - , min(bMin) - , max(bMax) - , step((bMax - bMin)) - , zdim(true) - , subBinningData(nullptr) - , subBinningAdditive(false) - , m_bins(1) - , m_boundaries({{min, max}}) - , m_totalBins(1) - , m_totalBoundaries(std::vector<float>()) - , m_functionPtr(&searchEquidistantWithBoundary) - { - } + : type(equidistant), + option(open), + binvalue(bValue), + min(bMin), + max(bMax), + step((bMax - bMin)), + zdim(true), + subBinningData(nullptr), + subBinningAdditive(false), + m_bins(1), + m_boundaries({{min, max}}), + m_totalBins(1), + m_totalBoundaries(std::vector<float>()), + m_functionPtr(&searchEquidistantWithBoundary) {} /// Constructor for equidistant binning /// and optional sub structure can be @@ -87,28 +84,24 @@ public: /// @param bMax is the maxmimum value /// @param sBinData is (optional) sub structure /// @param sBinAdditive is the prescription for the sub structure - BinningData(BinningOption bOption, - BinningValue bValue, - size_t bBins, - float bMin, - float bMax, - std::unique_ptr<const BinningData> sBinData = nullptr, - bool sBinAdditive = false) - : type(equidistant) - , option(bOption) - , binvalue(bValue) - , min(bMin) - , max(bMax) - , step((bMax - bMin) / bBins) - , zdim(bBins == 1 ? true : false) - , subBinningData(std::move(sBinData)) - , subBinningAdditive(sBinAdditive) - , m_bins(bBins) - , m_boundaries(std::vector<float>()) - , m_totalBins(bBins) - , m_totalBoundaries(std::vector<float>()) - , m_functionPtr(nullptr) - { + BinningData(BinningOption bOption, BinningValue bValue, size_t bBins, + float bMin, float bMax, + std::unique_ptr<const BinningData> sBinData = nullptr, + bool sBinAdditive = false) + : type(equidistant), + option(bOption), + binvalue(bValue), + min(bMin), + max(bMax), + step((bMax - bMin) / bBins), + zdim(bBins == 1 ? true : false), + subBinningData(std::move(sBinData)), + subBinningAdditive(sBinAdditive), + m_bins(bBins), + m_boundaries(std::vector<float>()), + m_totalBins(bBins), + m_totalBoundaries(std::vector<float>()), + m_functionPtr(nullptr) { // set to equidistant search m_functionPtr = &searchEquidistantWithBoundary; // fill the boundary vector for fast access to center & boundaries @@ -126,32 +119,30 @@ public: /// @param bValue is the binning value : binX, binY, etc. /// @param bBoundaries are the bin boundaries /// @param sBinData is (optional) sub structure - BinningData(BinningOption bOption, - BinningValue bValue, - const std::vector<float>& bBoundaries, + BinningData(BinningOption bOption, BinningValue bValue, + const std::vector<float>& bBoundaries, std::unique_ptr<const BinningData> sBinData = nullptr) - : type(arbitrary) - , option(bOption) - , binvalue(bValue) - , min(0.) - , max(0.) - , step(0.) - , zdim(bBoundaries.size() == 2 ? true : false) - , subBinningData(std::move(sBinData)) - , subBinningAdditive(true) - , m_bins(bBoundaries.size() - 1) - , m_boundaries(bBoundaries) - , m_totalBins(bBoundaries.size() - 1) - , m_totalBoundaries(bBoundaries) - , m_functionPtr(nullptr) - { + : type(arbitrary), + option(bOption), + binvalue(bValue), + min(0.), + max(0.), + step(0.), + zdim(bBoundaries.size() == 2 ? true : false), + subBinningData(std::move(sBinData)), + subBinningAdditive(true), + m_bins(bBoundaries.size() - 1), + m_boundaries(bBoundaries), + m_totalBins(bBoundaries.size() - 1), + m_totalBoundaries(bBoundaries), + m_functionPtr(nullptr) { // assert a no-size case throw_assert(m_boundaries.size() > 1, "Must have more than one boundary"); min = m_boundaries[0]; max = m_boundaries[m_boundaries.size() - 1]; // set to equidistant search - m_functionPtr - = m_bins < 50 ? &searchInVectorWithBoundary : &binarySearchWithBoundary; + m_functionPtr = + m_bins < 50 ? &searchInVectorWithBoundary : &binarySearchWithBoundary; // the binning data has sub structure - multiplicative checkSubStructure(); } @@ -160,56 +151,55 @@ public: /// /// @param bdata is the source object BinningData(const BinningData& bdata) - : type(bdata.type) - , option(bdata.option) - , binvalue(bdata.binvalue) - , min(bdata.min) - , max(bdata.max) - , step(bdata.step) - , zdim(bdata.zdim) - , subBinningData(nullptr) - , subBinningAdditive(bdata.subBinningAdditive) - , m_bins(bdata.m_bins) - , m_boundaries(bdata.m_boundaries) - , m_totalBins(bdata.m_totalBins) - , m_totalBoundaries(bdata.m_totalBoundaries) - , m_functionPtr(nullptr) - { + : type(bdata.type), + option(bdata.option), + binvalue(bdata.binvalue), + min(bdata.min), + max(bdata.max), + step(bdata.step), + zdim(bdata.zdim), + subBinningData(nullptr), + subBinningAdditive(bdata.subBinningAdditive), + m_bins(bdata.m_bins), + m_boundaries(bdata.m_boundaries), + m_totalBins(bdata.m_totalBins), + m_totalBoundaries(bdata.m_totalBoundaries), + m_functionPtr(nullptr) { // get the binning data - subBinningData = bdata.subBinningData - ? std::make_unique<const BinningData>(*bdata.subBinningData) - : nullptr; + subBinningData = + bdata.subBinningData + ? std::make_unique<const BinningData>(*bdata.subBinningData) + : nullptr; // set the pointer depending on the type // set the correct function pointer if (type == equidistant) { m_functionPtr = &searchEquidistantWithBoundary; } else { - m_functionPtr = m_bins < 50 ? &searchInVectorWithBoundary - : &binarySearchWithBoundary; + m_functionPtr = + m_bins < 50 ? &searchInVectorWithBoundary : &binarySearchWithBoundary; } } /// Assignment operator /// /// @param bdata is the source object - BinningData& - operator=(const BinningData& bdata) - { + BinningData& operator=(const BinningData& bdata) { if (this != &bdata) { - type = bdata.type; - option = bdata.option; - binvalue = bdata.binvalue; - min = bdata.min; - max = bdata.max; - step = bdata.step; - zdim = bdata.zdim; + type = bdata.type; + option = bdata.option; + binvalue = bdata.binvalue; + min = bdata.min; + max = bdata.max; + step = bdata.step; + zdim = bdata.zdim; subBinningAdditive = bdata.subBinningAdditive; - subBinningData = bdata.subBinningData - ? std::make_unique<const BinningData>(*bdata.subBinningData) - : nullptr; - m_bins = bdata.m_bins; - m_boundaries = bdata.m_boundaries; - m_totalBins = bdata.m_totalBins; + subBinningData = + bdata.subBinningData + ? std::make_unique<const BinningData>(*bdata.subBinningData) + : nullptr; + m_bins = bdata.m_bins; + m_boundaries = bdata.m_boundaries; + m_totalBins = bdata.m_totalBins; m_totalBoundaries = bdata.m_totalBoundaries; // set the correct function pointer if (type == equidistant) { @@ -226,21 +216,15 @@ public: ~BinningData() = default; /// Return the number of bins - including sub bins - size_t - bins() const - { - return m_totalBins; - } + size_t bins() const { return m_totalBins; } /// Decrement the bin /// - boolean indicates if decrement actually worked /// /// @param bin is the bin to be decremented - bool - decrement(size_t& bin) const - { + bool decrement(size_t& bin) const { size_t sbin = bin; - bin = bin > 0 ? bin - 1 : (option == open ? bin : m_bins - 1); + bin = bin > 0 ? bin - 1 : (option == open ? bin : m_bins - 1); return (sbin != bin); } @@ -248,19 +232,15 @@ public: /// - boolean indicates if decrement actually worked /// /// @param bin the bin to be incremented - bool - increment(size_t& bin) const - { + bool increment(size_t& bin) const { size_t sbin = bin; - bin = bin + 1 < m_bins ? bin + 1 : (option == open ? bin : 0); + bin = bin + 1 < m_bins ? bin + 1 : (option == open ? bin : 0); return (sbin != bin); } /// Return the boundaries - including sub boundaries /// @return vector of floats indicating the boundary values - const std::vector<float>& - boundaries() const - { + const std::vector<float>& boundaries() const { if (subBinningData) { return m_totalBoundaries; } @@ -272,12 +252,10 @@ public: /// @param lposition assumes the correct local position expression /// /// @return float value according to the binning setup - float - value(const Vector2D& lposition) const - { + float value(const Vector2D& lposition) const { // ordered after occurence - if (binvalue == binR || binvalue == binRPhi || binvalue == binX - || binvalue == binH) { + if (binvalue == binR || binvalue == binRPhi || binvalue == binX || + binvalue == binH) { return lposition[0]; } if (binvalue == binPhi) { @@ -291,12 +269,10 @@ public: /// @param position is the global position /// /// @return float value according to the binning setup - float - value(const Vector3D& position) const - { - using VectorHelpers::phi; - using VectorHelpers::perp; + float value(const Vector3D& position) const { using VectorHelpers::eta; + using VectorHelpers::perp; + using VectorHelpers::phi; // ordered after occurence if (binvalue == binR || binvalue == binH) { return (perp(position)); @@ -319,9 +295,7 @@ public: /// @param bin is the bin for which the center value is requested /// /// @return float value according to the bin center - float - center(size_t bin) const - { + float center(size_t bin) const { const std::vector<float>& bvals = boundaries(); // take the center between bin boundaries float value = bin < bvals.size() ? 0.5 * (bvals[bin] + bvals[bin + 1]) : 0.; @@ -333,9 +307,7 @@ public: /// @param position is the search position in global coordinated /// /// @return boolen if this is inside() method is true - bool - inside(const Vector3D& position) const - { + bool inside(const Vector3D& position) const { // closed one is always inside if (option == closed) { return true; @@ -351,9 +323,7 @@ public: /// @param lposition is the search position in global coordinated /// /// @return boolen if this is inside() method is true - bool - inside(const Vector2D& lposition) const - { + bool inside(const Vector2D& lposition) const { // closed one is always inside if (option == closed) { return true; @@ -369,9 +339,7 @@ public: /// @param lposition is the search position in local coordinated /// /// @return bin according tot this - size_t - searchLocal(const Vector2D& lposition) const - { + size_t searchLocal(const Vector2D& lposition) const { if (zdim) { return 0; } @@ -383,9 +351,7 @@ public: /// @param position is the search position in global coordinated /// /// @return bin according tot this - size_t - searchGlobal(const Vector3D& position) const - { + size_t searchGlobal(const Vector3D& position) const { if (zdim) { return 0; } @@ -397,9 +363,7 @@ public: /// @param value is the searchvalue as float /// /// @return bin according tot this - size_t - search(float value) const - { + size_t search(float value) const { if (zdim) { return 0; } @@ -414,9 +378,7 @@ public: /// @param value is the searchvalue as float /// /// @return bin according tot this - size_t - searchWithSubStructure(float value) const - { + size_t searchWithSubStructure(float value) const { // find the masterbin with the correct function pointer size_t masterbin = (*m_functionPtr)(value, *this); // additive sub binning - @@ -425,8 +387,8 @@ public: return masterbin + subBinningData->search(value); } // gauge the value to the subBinData - float gvalue - = value - masterbin * (subBinningData->max - subBinningData->min); + float gvalue = + value - masterbin * (subBinningData->max - subBinningData->min); // now go / additive or multiplicative size_t subbin = subBinningData->search(gvalue); // now return @@ -440,15 +402,13 @@ public: /// @todo check if this can be changed /// /// @return integer that indicates which direction to move - int - nextDirection(const Vector3D& position, const Vector3D& dir) const - { + int nextDirection(const Vector3D& position, const Vector3D& dir) const { if (zdim) { return 0; } - float val = value(position); - Vector3D probe = position + dir.normalized(); - float nextval = value(probe); + float val = value(position); + Vector3D probe = position + dir.normalized(); + float nextval = value(probe); return (nextval > val) ? 1 : -1; } @@ -459,9 +419,7 @@ public: /// it is set to max /// /// @return the center value of the bin is given - float - centerValue(size_t bin) const - { + float centerValue(size_t bin) const { if (zdim) { return 0.5 * (min + max); } @@ -475,10 +433,8 @@ public: /// takes a bin entry and returns the lower/higher bound /// respecting open/closed /// @return low/high bounds - std::vector<size_t> - neighbourRange(size_t bin) const - { - size_t low = bin; + std::vector<size_t> neighbourRange(size_t bin) const { + size_t low = bin; size_t high = bin; // decrement and increment bool dsucc = decrement(low); @@ -495,18 +451,16 @@ public: return {bin}; } -private: - size_t m_bins; ///< number of bins + private: + size_t m_bins; ///< number of bins std::vector<float> m_boundaries; ///< vector of holding the bin boundaries - size_t m_totalBins; ///< including potential substructure + size_t m_totalBins; ///< including potential substructure std::vector<float> m_totalBoundaries; ///< including potential substructure size_t (*m_functionPtr)(float, const BinningData&); /// function pointer /// helper method to set the sub structure - void - checkSubStructure() - { + void checkSubStructure() { // sub structure is only checked when sBinData is defined if (subBinningData) { m_totalBoundaries.clear(); @@ -517,8 +471,8 @@ private: // the tricky one - exchange one bin by many others m_totalBoundaries.reserve(m_totalBins + 1); // get the sub bin boundaries - const std::vector<float>& subBinBoundaries - = subBinningData->boundaries(); + const std::vector<float>& subBinBoundaries = + subBinningData->boundaries(); float sBinMin = subBinBoundaries[0]; // get the min value of the sub bin boundaries std::vector<float>::const_iterator mbvalue = m_boundaries.begin(); @@ -539,8 +493,8 @@ private: m_totalBins = m_bins * subBinningData->bins(); m_totalBoundaries.reserve(m_totalBins + 1); // get the sub bin boundaries if there are any - const std::vector<float>& subBinBoundaries - = subBinningData->boundaries(); + const std::vector<float>& subBinBoundaries = + subBinningData->boundaries(); // create the boundary vector m_totalBoundaries.push_back(min); for (size_t ib = 0; ib < m_bins; ++ib) { @@ -557,10 +511,8 @@ private: // Equidistant search // - fastest method - static size_t - searchEquidistantWithBoundary(float value, const BinningData& bData) - { - + static size_t searchEquidistantWithBoundary(float value, + const BinningData& bData) { // vanilla int bin = ((value - bData.min) / bData.step); @@ -582,9 +534,8 @@ private: // Linear search in arbitrary vector // - superior in O(10) searches - static size_t - searchInVectorWithBoundary(float value, const BinningData& bData) - { + static size_t searchInVectorWithBoundary(float value, + const BinningData& bData) { // lower boundary if (value <= bData.m_boundaries[0]) { return (bData.option == closed) ? (bData.m_bins - 1) : 0; @@ -594,8 +545,8 @@ private: return (bData.option == closed) ? 0 : (bData.m_bins - 1); } // search - auto vIter = bData.m_boundaries.begin(); - size_t bin = 0; + auto vIter = bData.m_boundaries.begin(); + size_t bin = 0; for (; vIter != bData.m_boundaries.end(); ++vIter, ++bin) { if ((*vIter) > value) { break; @@ -606,9 +557,8 @@ private: // A binary search with in an arbitrary vector // - faster than vector search for O(50) objects - static size_t - binarySearchWithBoundary(float value, const BinningData& bData) - { + static size_t binarySearchWithBoundary(float value, + const BinningData& bData) { // Binary search in an array of n values to locate value if (value <= bData.m_boundaries[0]) { return (bData.option == closed) ? (bData.m_bins - 1) : 0; @@ -635,4 +585,4 @@ private: return nbelow - 1; } }; -} +} // namespace Acts diff --git a/Core/include/Acts/Utilities/BinningType.hpp b/Core/include/Acts/Utilities/BinningType.hpp index 18a13ea4dd4fb3eed732586c069cd91ef683e112..3014f05e7ab39791ada53509a6e2dae88794a09b 100644 --- a/Core/include/Acts/Utilities/BinningType.hpp +++ b/Core/include/Acts/Utilities/BinningType.hpp @@ -49,13 +49,7 @@ enum BinningValue { }; /// @brief screen output option -static const std::vector<std::string> binningValueNames = {"binX", - "binY", - "binZ", - "binR", - "binPhi", - "binRPhi", - "binH", - "binEta", - "binMag"}; -} \ No newline at end of file +static const std::vector<std::string> binningValueNames = { + "binX", "binY", "binZ", "binR", "binPhi", + "binRPhi", "binH", "binEta", "binMag"}; +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Utilities/Definitions.hpp b/Core/include/Acts/Utilities/Definitions.hpp index a94b20cbc4f8191edb274674450f8896fff4d13c..a68a7734aeeb7d16b15d8093ac32f185b48aa069 100644 --- a/Core/include/Acts/Utilities/Definitions.hpp +++ b/Core/include/Acts/Utilities/Definitions.hpp @@ -48,7 +48,7 @@ enum NavigationDirection : int { backward = -1, anyDirection = 0, forward = 1 }; /// - fullUpdate : update when passing a surface /// - postUpdate : update when leaving a surface enum MaterialUpdateStage : int { - preUpdate = -1, + preUpdate = -1, fullUpdate = 0, postUpdate = 1 }; @@ -108,20 +108,20 @@ using ActsRowVectorX = Eigen::Matrix<T, 1, Eigen::Dynamic>; using ActsRowVectorXd = ActsRowVectorX<double>; using ActsRowVectorXf = ActsRowVectorX<float>; -using Rotation3D = Eigen::Quaternion<double>; -using Translation3D = Eigen::Translation<double, 3>; -using AngleAxis3D = Eigen::AngleAxisd; -using Transform3D = Eigen::Affine3d; -using Vector3D = Eigen::Matrix<double, 3, 1>; -using Vector2D = Eigen::Matrix<double, 2, 1>; +using Rotation3D = Eigen::Quaternion<double>; +using Translation3D = Eigen::Translation<double, 3>; +using AngleAxis3D = Eigen::AngleAxisd; +using Transform3D = Eigen::Affine3d; +using Vector3D = Eigen::Matrix<double, 3, 1>; +using Vector2D = Eigen::Matrix<double, 2, 1>; using RotationMatrix3D = Eigen::Matrix<double, 3, 3>; -using Rotation3F = Eigen::Quaternion<float>; -using Translation3F = Eigen::Translation<float, 3>; -using AngleAxis3F = Eigen::AngleAxisf; -using Transform3F = Eigen::Affine3f; -using Vector3F = Eigen::Matrix<float, 3, 1>; -using Vector2F = Eigen::Matrix<float, 2, 1>; +using Rotation3F = Eigen::Quaternion<float>; +using Translation3F = Eigen::Translation<float, 3>; +using AngleAxis3F = Eigen::AngleAxisf; +using Transform3F = Eigen::Affine3f; +using Vector3F = Eigen::Matrix<float, 3, 1>; +using Vector2F = Eigen::Matrix<float, 2, 1>; using RotationMatrix3F = Eigen::Matrix<float, 3, 3>; /// axis defintion element for code readability diff --git a/Core/include/Acts/Utilities/Helpers.hpp b/Core/include/Acts/Utilities/Helpers.hpp index b3faaea7b188bd8da9f1effaa2a1af7aecf8398b..5b26f33029c0697c7f9fc58217ba5a321ea96070 100644 --- a/Core/include/Acts/Utilities/Helpers.hpp +++ b/Core/include/Acts/Utilities/Helpers.hpp @@ -57,185 +57,154 @@ namespace Acts { */ namespace VectorHelpers { - namespace detail { - template <class T> - using phi_method_t = decltype(std::declval<const T>().phi()); - - template <class T> - using has_phi_method = concept::is_detected<phi_method_t, T>; - - } // namespace detail - - /// Calculate phi (transverse plane angle) from compatible Eigen types - /// @tparam Derived Eigen derived concrete type - /// @param v Any vector like Eigen type, static or dynamic - /// @note Will static assert that the number of rows of @p v is at least 2, or - /// in case of dynamic size, will abort execution if that is not the case. - /// @return The value of the angle in the transverse plane. - template <typename Derived> - double - phi(const Eigen::MatrixBase<Derived>& v) noexcept - { - constexpr int rows = Eigen::MatrixBase<Derived>::RowsAtCompileTime; - if - constexpr(rows != -1) - { - // static size, do compile time check - static_assert(rows >= 2, - "Phi function not valid for vectors not at least 2D"); - } - else { - // dynamic size - if (v.rows() < 2) { - std::cerr << "Phi function not valid for vectors not at least 2D" - << std::endl; - std::abort(); - } +namespace detail { +template <class T> +using phi_method_t = decltype(std::declval<const T>().phi()); + +template <class T> +using has_phi_method = concept ::is_detected<phi_method_t, T>; + +} // namespace detail + +/// Calculate phi (transverse plane angle) from compatible Eigen types +/// @tparam Derived Eigen derived concrete type +/// @param v Any vector like Eigen type, static or dynamic +/// @note Will static assert that the number of rows of @p v is at least 2, or +/// in case of dynamic size, will abort execution if that is not the case. +/// @return The value of the angle in the transverse plane. +template <typename Derived> +double phi(const Eigen::MatrixBase<Derived>& v) noexcept { + constexpr int rows = Eigen::MatrixBase<Derived>::RowsAtCompileTime; + if constexpr (rows != -1) { + // static size, do compile time check + static_assert(rows >= 2, + "Phi function not valid for vectors not at least 2D"); + } else { + // dynamic size + if (v.rows() < 2) { + std::cerr << "Phi function not valid for vectors not at least 2D" + << std::endl; + std::abort(); } - - return std::atan2(v[1], v[0]); } - /// Calculate phi (transverse plane angle) from anything implementing a method - /// like `phi()` returing anything convertible to `double`. - /// @tparam T anything that has a phi method - /// @param v Any type that implements a phi method - /// @return The phi value - template <typename T, - std::enable_if_t<detail::has_phi_method<T>::value, int> = 0> - double - phi(const T& v) noexcept - { - return v.phi(); - } + return std::atan2(v[1], v[0]); +} - /// Calculate radius in the transverse (xy) plane of a vector - /// @tparam Derived Eigen derived concrete type - /// @param v Any vector like Eigen type, static or dynamic - /// @note Will static assert that the number of rows of @p v is at least 2, or - /// in case of dynamic size, will abort execution if that is not the case. - /// @return The transverse radius value. - template <typename Derived> - double - perp(const Eigen::MatrixBase<Derived>& v) noexcept - { - constexpr int rows = Eigen::MatrixBase<Derived>::RowsAtCompileTime; - if - constexpr(rows != -1) - { - // static size, do compile time check - static_assert(rows >= 2, - "Perp function not valid for vectors not at least 2D"); - } - else { - // dynamic size - if (v.rows() < 2) { - std::cerr << "Perp function not valid for vectors not at least 2D" - << std::endl; - std::abort(); - } +/// Calculate phi (transverse plane angle) from anything implementing a method +/// like `phi()` returing anything convertible to `double`. +/// @tparam T anything that has a phi method +/// @param v Any type that implements a phi method +/// @return The phi value +template <typename T, + std::enable_if_t<detail::has_phi_method<T>::value, int> = 0> +double phi(const T& v) noexcept { + return v.phi(); +} + +/// Calculate radius in the transverse (xy) plane of a vector +/// @tparam Derived Eigen derived concrete type +/// @param v Any vector like Eigen type, static or dynamic +/// @note Will static assert that the number of rows of @p v is at least 2, or +/// in case of dynamic size, will abort execution if that is not the case. +/// @return The transverse radius value. +template <typename Derived> +double perp(const Eigen::MatrixBase<Derived>& v) noexcept { + constexpr int rows = Eigen::MatrixBase<Derived>::RowsAtCompileTime; + if constexpr (rows != -1) { + // static size, do compile time check + static_assert(rows >= 2, + "Perp function not valid for vectors not at least 2D"); + } else { + // dynamic size + if (v.rows() < 2) { + std::cerr << "Perp function not valid for vectors not at least 2D" + << std::endl; + std::abort(); } - return std::sqrt(v[0] * v[0] + v[1] * v[1]); } + return std::sqrt(v[0] * v[0] + v[1] * v[1]); +} - /// Calculate the theta angle (longitudinal w.r.t. z axis) of a vector - /// @tparam Derived Eigen derived concrete type - /// @param v Any vector like Eigen type, static or dynamic - /// @note Will static assert that the number of rows of @p v is at least 3, or - /// in case of dynamic size, will abort execution if that is not the case. - /// @return The theta value - template <typename Derived> - double - theta(const Eigen::MatrixBase<Derived>& v) noexcept - { - constexpr int rows = Eigen::MatrixBase<Derived>::RowsAtCompileTime; - if - constexpr(rows != -1) - { - // static size, do compile time check - static_assert(rows >= 3, - "Theta function not valid for non-3D vectors."); - } - else { - // dynamic size - if (v.rows() < 3) { - std::cerr << "Theta function not valid for non-3D vectors." - << std::endl; - std::abort(); - } +/// Calculate the theta angle (longitudinal w.r.t. z axis) of a vector +/// @tparam Derived Eigen derived concrete type +/// @param v Any vector like Eigen type, static or dynamic +/// @note Will static assert that the number of rows of @p v is at least 3, or +/// in case of dynamic size, will abort execution if that is not the case. +/// @return The theta value +template <typename Derived> +double theta(const Eigen::MatrixBase<Derived>& v) noexcept { + constexpr int rows = Eigen::MatrixBase<Derived>::RowsAtCompileTime; + if constexpr (rows != -1) { + // static size, do compile time check + static_assert(rows >= 3, "Theta function not valid for non-3D vectors."); + } else { + // dynamic size + if (v.rows() < 3) { + std::cerr << "Theta function not valid for non-3D vectors." << std::endl; + std::abort(); } - - return std::atan2(std::sqrt(v[0] * v[0] + v[1] * v[1]), v[2]); } - /// Calculate the pseudorapidity for a vector. - /// @tparam Derived Eigen derived concrete type - /// @param v Any vector like Eigen type, static or dynamic - /// @note Will static assert that the number of rows of @p v is at least 3, or - /// in case of dynamic size, will abort execution if that is not the case. - /// @return The pseudorapidity value - template <typename Derived> - double - eta(const Eigen::MatrixBase<Derived>& v) noexcept - { - constexpr int rows = Eigen::MatrixBase<Derived>::RowsAtCompileTime; - if - constexpr(rows != -1) - { - // static size, do compile time check - static_assert(rows >= 3, "Eta function not valid for non-3D vectors."); - } - else { - // dynamic size - if (v.rows() < 3) { - std::cerr << "Eta function not valid for non-3D vectors." << std::endl; - std::abort(); - } - } + return std::atan2(std::sqrt(v[0] * v[0] + v[1] * v[1]), v[2]); +} - return std::atanh(v[2] / v.norm()); +/// Calculate the pseudorapidity for a vector. +/// @tparam Derived Eigen derived concrete type +/// @param v Any vector like Eigen type, static or dynamic +/// @note Will static assert that the number of rows of @p v is at least 3, or +/// in case of dynamic size, will abort execution if that is not the case. +/// @return The pseudorapidity value +template <typename Derived> +double eta(const Eigen::MatrixBase<Derived>& v) noexcept { + constexpr int rows = Eigen::MatrixBase<Derived>::RowsAtCompileTime; + if constexpr (rows != -1) { + // static size, do compile time check + static_assert(rows >= 3, "Eta function not valid for non-3D vectors."); + } else { + // dynamic size + if (v.rows() < 3) { + std::cerr << "Eta function not valid for non-3D vectors." << std::endl; + std::abort(); + } } - /// @brief Calculates column-wise cross products of a matrix and a vector and - /// stores the result column-wise in a matrix. - /// - /// @param [in] m Matrix that will be used for cross products - /// @param [in] v Vector for cross products - /// @return Constructed matrix - inline ActsMatrixD<3, 3> - cross(const ActsMatrixD<3, 3>& m, const Vector3D& v) - { - ActsMatrixD<3, 3> r; - r.col(0) = m.col(0).cross(v); - r.col(1) = m.col(1).cross(v); - r.col(2) = m.col(2).cross(v); - - return r; - } + return std::atanh(v[2] / v.norm()); } +/// @brief Calculates column-wise cross products of a matrix and a vector and +/// stores the result column-wise in a matrix. +/// +/// @param [in] m Matrix that will be used for cross products +/// @param [in] v Vector for cross products +/// @return Constructed matrix +inline ActsMatrixD<3, 3> cross(const ActsMatrixD<3, 3>& m, const Vector3D& v) { + ActsMatrixD<3, 3> r; + r.col(0) = m.col(0).cross(v); + r.col(1) = m.col(1).cross(v); + r.col(2) = m.col(2).cross(v); + + return r; +} +} // namespace VectorHelpers + namespace detail { - inline double - roundWithPrecision(double val, int precision) - { - if (val < 0 && std::abs(val) * std::pow(10, precision) < 1.) { - return -val; - } - return val; +inline double roundWithPrecision(double val, int precision) { + if (val < 0 && std::abs(val) * std::pow(10, precision) < 1.) { + return -val; } + return val; } +} // namespace detail /// Print out a matrix in a structured way. /// @param matrix The matrix to print /// @param precision Numeric output precision /// @param offset Offset in front of matrix lines /// @return The printed string -inline std::string -toString(const ActsMatrixXd& matrix, - int precision = 4, - const std::string& offset = "") -{ +inline std::string toString(const ActsMatrixXd& matrix, int precision = 4, + const std::string& offset = "") { std::ostringstream sout; sout << std::setiosflags(std::ios::fixed) << std::setprecision(precision); @@ -263,9 +232,8 @@ toString(const ActsMatrixXd& matrix, sout << ", "; } } - if (i - != matrix.rows() - - 1) { // make the end line and the offset in the next line + if (i != matrix.rows() - + 1) { // make the end line and the offset in the next line sout << std::endl; sout << offset; } @@ -278,9 +246,8 @@ toString(const ActsMatrixXd& matrix, /// @param matrix The translation to print /// @param precision Numeric output precision /// @return The printed string -inline std::string -toString(const Acts::Translation3D& translation, int precision = 4) -{ +inline std::string toString(const Acts::Translation3D& translation, + int precision = 4) { Acts::Vector3D trans; trans[0] = translation.x(); trans[1] = translation.y(); @@ -293,11 +260,8 @@ toString(const Acts::Translation3D& translation, int precision = 4) /// @param precision Numeric output precision /// @param offset Offset in front of matrix lines /// @return The printed string -inline std::string -toString(const Acts::Transform3D& transform, - int precision = 4, - const std::string& offset = "") -{ +inline std::string toString(const Acts::Transform3D& transform, + int precision = 4, const std::string& offset = "") { std::ostringstream sout; sout << "Translation : " << toString(transform.translation(), precision) << std::endl; @@ -313,9 +277,8 @@ toString(const Acts::Transform3D& transform, /// @param items The vector of @c shared_ptr /// @return The unpacked vector template <typename T> -std::vector<T*> -unpack_shared_vector(const std::vector<std::shared_ptr<T>>& items) -{ +std::vector<T*> unpack_shared_vector( + const std::vector<std::shared_ptr<T>>& items) { std::vector<T*> rawPtrs; rawPtrs.reserve(items.size()); for (const std::shared_ptr<T>& item : items) { @@ -330,9 +293,8 @@ unpack_shared_vector(const std::vector<std::shared_ptr<T>>& items) /// @param items The vector of @c shared_ptr /// @return The unpacked vector template <typename T> -std::vector<const T*> -unpack_shared_vector(const std::vector<std::shared_ptr<const T>>& items) -{ +std::vector<const T*> unpack_shared_vector( + const std::vector<std::shared_ptr<const T>>& items) { std::vector<const T*> rawPtrs; rawPtrs.reserve(items.size()); for (const std::shared_ptr<const T>& item : items) { @@ -341,4 +303,4 @@ unpack_shared_vector(const std::vector<std::shared_ptr<const T>>& items) return rawPtrs; } -} // end of Acts namespace +} // namespace Acts diff --git a/Core/include/Acts/Utilities/IAxis.hpp b/Core/include/Acts/Utilities/IAxis.hpp index 3729638a101b0080e0ab30d4ecf38b0b1a470d3e..e3961899948bf9da9d948bb4fcff11c82606092f 100644 --- a/Core/include/Acts/Utilities/IAxis.hpp +++ b/Core/include/Acts/Utilities/IAxis.hpp @@ -12,54 +12,45 @@ namespace Acts { namespace detail { - enum class AxisBoundaryType; +enum class AxisBoundaryType; } /// Common base class for all Axis instance. This allows generice handling /// such as for inspection. -class IAxis -{ - -public: +class IAxis { + public: /// @brief returns whether the axis is equidistant /// /// @return bool is equidistant - virtual bool - isEquidistant() const = 0; + virtual bool isEquidistant() const = 0; /// @brief returns whether the axis is variable /// /// @return bool is variable - virtual bool - isVariable() const = 0; + virtual bool isVariable() const = 0; /// @brief returns the boundary type set in the template param /// /// @return @c AxisBoundaryType of this axis - virtual detail::AxisBoundaryType - getBoundaryType() const = 0; + virtual detail::AxisBoundaryType getBoundaryType() const = 0; /// @brief Return a vector of bin edges /// @return Vector which contains the bin edges - virtual std::vector<double> - getBinEdges() const = 0; + virtual std::vector<double> getBinEdges() const = 0; /// @brief get minimum of binning range /// /// @return minimum of binning range - virtual double - getMin() const = 0; + virtual double getMin() const = 0; /// @brief get maximum of binning range /// /// @return maximum of binning range - virtual double - getMax() const = 0; + virtual double getMax() const = 0; /// @brief get total number of bins /// /// @return total number of bins (excluding under-/overflow bins) - virtual size_t - getNBins() const = 0; + virtual size_t getNBins() const = 0; }; -} \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Utilities/IVisualization.hpp b/Core/include/Acts/Utilities/IVisualization.hpp index 0d4e33484ed407ebbb09e265165faf984ca80473..68b0bc3a8162b6370d5738ed291944723f6dc628 100644 --- a/Core/include/Acts/Utilities/IVisualization.hpp +++ b/Core/include/Acts/Utilities/IVisualization.hpp @@ -19,9 +19,8 @@ namespace Acts { * conform to. It also provides a `color_type` typedef, but not all of the * helpers actually support that. */ -class IVisualization -{ -public: +class IVisualization { + public: /** * The color typedef. It's an array of three numbers [0, 255] indicating RGB * color values. @@ -33,9 +32,8 @@ public: * @param vtx The vertex position * @param color The color */ - virtual void - vertex(const Vector3D& vtx, color_type color = {120, 120, 120}) - = 0; + virtual void vertex(const Vector3D& vtx, + color_type color = {120, 120, 120}) = 0; /** * Draw a face that connects a list of vertices. @@ -44,9 +42,8 @@ public: * @param vtxs The vertices that make up the face * @param color The color of the face */ - virtual void - face(const std::vector<Vector3D>& vtxs, color_type color = {120, 120, 120}) - = 0; + virtual void face(const std::vector<Vector3D>& vtxs, + color_type color = {120, 120, 120}) = 0; /** * Draw a line from a vertex to another @@ -54,23 +51,19 @@ public: * @param b The end vertex * @param color The color of the line */ - virtual void - line(const Vector3D& a, const Vector3D& b, color_type color = {120, 120, 120}) - = 0; + virtual void line(const Vector3D& a, const Vector3D& b, + color_type color = {120, 120, 120}) = 0; /** * Write the content of the helper to an outstream. * @param os The output stream */ - virtual void - write(std::ostream& os) const = 0; + virtual void write(std::ostream& os) const = 0; /** * Remove all contents of this helper */ - virtual void - clear() - = 0; + virtual void clear() = 0; /** * Below are helper functions, which share the same interface as the ones @@ -81,9 +74,7 @@ public: /** * @copydoc Acts::IVisualization::vertex(const Vector3D&, color_type) */ - void - vertex(const Vector3F& vtx, color_type color = {120, 120, 120}) - { + void vertex(const Vector3F& vtx, color_type color = {120, 120, 120}) { Vector3D vtxd = vtx.template cast<double>(); vertex(vtxd, color); } @@ -91,13 +82,10 @@ public: /** * @copydoc Acts::IVisualization::face(std::vector<Vector3F>&, color_type) */ - void - face(const std::vector<Vector3F>& vtxs, color_type color = {120, 120, 120}) - { + void face(const std::vector<Vector3F>& vtxs, + color_type color = {120, 120, 120}) { std::vector<Vector3D> vtxsd; - std::transform(vtxs.begin(), - vtxs.end(), - std::back_inserter(vtxsd), + std::transform(vtxs.begin(), vtxs.end(), std::back_inserter(vtxsd), [](auto& v) { return v.template cast<double>(); }); face(vtxsd, color); } @@ -106,9 +94,8 @@ public: * @copydoc Acts::IVisualization::line(const Vector3F&, const Vector3F&, * color_type) */ - void - line(const Vector3F& a, const Vector3F& b, color_type color = {120, 120, 120}) - { + void line(const Vector3F& a, const Vector3F& b, + color_type color = {120, 120, 120}) { Vector3D ad = a.template cast<double>(); Vector3D bd = b.template cast<double>(); line(ad, bd, color); @@ -120,10 +107,8 @@ public: * @param os The output stream * @param hlp The helper instance */ -inline std::ostream& -operator<<(std::ostream& os, const IVisualization& hlp) -{ +inline std::ostream& operator<<(std::ostream& os, const IVisualization& hlp) { hlp.write(os); return os; } -} +} // namespace Acts diff --git a/Core/include/Acts/Utilities/Interpolation.hpp b/Core/include/Acts/Utilities/Interpolation.hpp index f937e80b7c805191d6d38c98dc1e9e9758a2cec5..a70cbe1b06e098b57834861eb56424f33340b0a4 100644 --- a/Core/include/Acts/Utilities/Interpolation.hpp +++ b/Core/include/Acts/Utilities/Interpolation.hpp @@ -70,28 +70,16 @@ namespace Acts { /// - (4,2,6): 101 = 5 /// - (4,5,3): 110 = 6 /// - (4,5,6): 111 = 7 -template < - typename T, - size_t N, - class Point1, - class Point2 = Point1, - class Point3 = Point2, - typename = std:: - enable_if_t<detail::can_interpolate<Point1, Point2, Point3, T>::value>> -inline T -interpolate(const Point1& position, - const Point2& lowerCorner, - const Point3& upperCorner, - const std::array<T, N>& values) -{ - return detail::interpolate_impl<T, - Point1, - Point2, - Point3, +template <typename T, size_t N, class Point1, class Point2 = Point1, + class Point3 = Point2, + typename = std::enable_if_t< + detail::can_interpolate<Point1, Point2, Point3, T>::value>> +inline T interpolate(const Point1& position, const Point2& lowerCorner, + const Point3& upperCorner, + const std::array<T, N>& values) { + return detail::interpolate_impl<T, Point1, Point2, Point3, detail::get_dimension<N>::value - 1, - N>::run(position, - lowerCorner, - upperCorner, + N>::run(position, lowerCorner, upperCorner, values); } diff --git a/Core/include/Acts/Utilities/Intersection.hpp b/Core/include/Acts/Utilities/Intersection.hpp index 8b9dc46defb37a6045661101a6ef4d8d7098802a..749580139d964449166f128d8ebbc5b89ae13eaa 100644 --- a/Core/include/Acts/Utilities/Intersection.hpp +++ b/Core/include/Acts/Utilities/Intersection.hpp @@ -22,12 +22,11 @@ using CorrFnc = std::function<bool(Vector3D&, Vector3D&, double&)>; /// @struct Intersection /// /// intersection struct used for position -struct Intersection -{ - Vector3D position; ///< position of the intersection - double pathLength; ///< path length to the intersection (if valid) - double distance{0.}; ///< remaining distance (if not valid) - bool valid{false}; ///< validiaty boolean +struct Intersection { + Vector3D position; ///< position of the intersection + double pathLength; ///< path length to the intersection (if valid) + double distance{0.}; ///< remaining distance (if not valid) + bool valid{false}; ///< validiaty boolean /// Constructor with arguments /// @@ -35,20 +34,14 @@ struct Intersection /// @param slength is the path length to the intersection /// @param svalid is a boolean indicating if intersection is valid /// @param dist is the distance to the closes surface boundary - Intersection(const Vector3D& sinter, - double slength, - bool svalid, - double dist = 0.) - : position(sinter), pathLength(slength), distance(dist), valid(svalid) - { - } + Intersection(const Vector3D& sinter, double slength, bool svalid, + double dist = 0.) + : position(sinter), pathLength(slength), distance(dist), valid(svalid) {} /// Default constructor Intersection() - : position(Vector3D(0., 0., 0.)) - , pathLength(std::numeric_limits<double>::infinity()) - { - } + : position(Vector3D(0., 0., 0.)), + pathLength(std::numeric_limits<double>::infinity()) {} /// Bool() operator for validity checking explicit operator bool() const { return valid; } @@ -56,9 +49,7 @@ struct Intersection /// Smaller operator for sorting, /// - it respects the validity of the intersection /// @param si is the intersection for testing - bool - operator<(const Intersection& si) const - { + bool operator<(const Intersection& si) const { if (!valid) { return false; } @@ -73,9 +64,7 @@ struct Intersection /// Greater operator for sorting, /// - it respects the validity of the intersection /// @param si is the intersection for testing - bool - operator>(const Intersection& si) const - { + bool operator>(const Intersection& si) const { if (!valid) { return false; } @@ -91,10 +80,9 @@ struct Intersection /// class extensions to return also the object - can be merged with /// FullIntersection template <typename object_t> -class ObjectIntersection -{ -public: - Intersection intersection{}; ///< the intersection iself +class ObjectIntersection { + public: + Intersection intersection{}; ///< the intersection iself const object_t* object{nullptr}; ///< the object that was intersected const object_t* representation{ nullptr}; ///< the representation of the object @@ -109,15 +97,12 @@ public: /// @param sInter is the intersection /// @param sObject is the object to be instersected /// @param dir is the direction of the intersection - ObjectIntersection(const Intersection& sInter, - const object_t* sObject, + ObjectIntersection(const Intersection& sInter, const object_t* sObject, NavigationDirection dir = forward) - : intersection(sInter) - , object(sObject) - , representation(sObject) - , pDirection(dir) - { - } + : intersection(sInter), + object(sObject), + representation(sObject), + pDirection(dir) {} /// Bool() operator for validity checking explicit operator bool() const { return intersection.valid; } @@ -125,18 +110,14 @@ public: /// @brief smaller operator for ordering & sorting /// /// @param oi is the source intersection for comparison - bool - operator<(const ObjectIntersection<object_t>& oi) const - { + bool operator<(const ObjectIntersection<object_t>& oi) const { return (intersection < oi.intersection); } /// @brief greater operator for ordering & sorting /// /// @param oi is the source intersection for comparison - bool - operator>(const ObjectIntersection<object_t>& oi) const - { + bool operator>(const ObjectIntersection<object_t>& oi) const { return (intersection > oi.intersection); } }; @@ -149,13 +130,12 @@ public: /// @tparam object_t Type of the object to be intersected /// @tparam representation_t Type of the representation template <typename object_t, typename representation_t> -class FullIntersection -{ -public: - Intersection intersection; ///< the intersection iself - const object_t* object; ///< the object that was intersected +class FullIntersection { + public: + Intersection intersection; ///< the intersection iself + const object_t* object; ///< the object that was intersected const representation_t* representation; ///< the represenation of the object - NavigationDirection pDirection; ///< the direction in which it was taken + NavigationDirection pDirection; ///< the direction in which it was taken /// Full intersection constructor /// @@ -164,16 +144,13 @@ public: /// @param sRepresentation is the surface representation of the object /// @param dir is the direction /// - FullIntersection(const Intersection& sInter, - const object_t* sObject, + FullIntersection(const Intersection& sInter, const object_t* sObject, const representation_t* sRepresentation, - NavigationDirection dir = forward) - : intersection(sInter) - , object(sObject) - , representation(sRepresentation) - , pDirection(dir) - { - } + NavigationDirection dir = forward) + : intersection(sInter), + object(sObject), + representation(sRepresentation), + pDirection(dir) {} /// Bool() operator for validity checking explicit operator bool() const { return intersection.valid; } @@ -181,24 +158,19 @@ public: /// @brief smaller operator for ordering & sorting /// /// @param fi is the full intersection to be tested - bool - operator<(const FullIntersection<object_t, representation_t>& fi) const - { + bool operator<(const FullIntersection<object_t, representation_t>& fi) const { return (intersection < fi.intersection); } /// @brief greater operator for ordering & sorting /// /// @param fi is the full intersection to be tested - bool - operator>(const FullIntersection<object_t, representation_t>& fi) const - { + bool operator>(const FullIntersection<object_t, representation_t>& fi) const { return (intersection > fi.intersection); } }; -struct SameSurfaceIntersection -{ +struct SameSurfaceIntersection { /// @brief comparison operator /// /// This is a struct to pick out intersection with identical surfaces @@ -207,9 +179,7 @@ struct SameSurfaceIntersection /// @param i1 First intersection to test /// @param i2 Second intersection to test template <typename intersection_t> - bool - operator()(const intersection_t& i1, const intersection_t& i2) const - { + bool operator()(const intersection_t& i1, const intersection_t& i2) const { return (i1.object == i2.object); } }; @@ -218,26 +188,20 @@ struct SameSurfaceIntersection /// /// This is used to evaluate a modified /// intersection (e.g. curvature updated) -struct VoidIntersectionCorrector -{ - +struct VoidIntersectionCorrector { // Void Corrector default constructor VoidIntersectionCorrector() = default; // Void Corrector parameter constructor VoidIntersectionCorrector(const Vector3D& /*unused*/, - const Vector3D& /*unused*/, - double /*unused*/) - { - } + const Vector3D& /*unused*/, double /*unused*/) {} /// Boolean() operator - returns false for void modifier explicit operator bool() const { return false; } /// empty correction interface - bool - operator()(Vector3D& /*unused*/, Vector3D& /*unused*/, double /*unused*/) - { + bool operator()(Vector3D& /*unused*/, Vector3D& /*unused*/, + double /*unused*/) { return false; } @@ -245,10 +209,8 @@ struct VoidIntersectionCorrector /// /// @stay put and don't do antyhing template <typename step_t> - bool - operator()(step_t& /*unused*/) const - { + bool operator()(step_t& /*unused*/) const { return false; } }; -} +} // namespace Acts diff --git a/Core/include/Acts/Utilities/Logger.hpp b/Core/include/Acts/Utilities/Logger.hpp index 925a1416265628933db08174be2c8342902cf20b..72315d5c270f937aae8fcc0189aab94bbe9aab2e 100644 --- a/Core/include/Acts/Utilities/Logger.hpp +++ b/Core/include/Acts/Utilities/Logger.hpp @@ -146,387 +146,338 @@ namespace Acts { /// @brief debug output related helper classes and functions /// @ingroup Logging namespace Logging { - /// @brief constants steering the debug output - /// - /// All messages with a debug level equal or higher than the currently set - /// debug output level will be printed. - enum Level { - VERBOSE = 0, ///< VERBOSE level - DEBUG, ///< DEBUG level - INFO, ///< INFO level - WARNING, ///< WARNING level - ERROR, ///< ERROR level - FATAL ///< FATAL level - }; - - /// @brief abstract base class for printing debug output - /// - /// Implementations of this interface need to define how and where to @a print - /// debug messages (e.g. to a file, to a stream into a database etc). - class OutputPrintPolicy - { - public: - /// virtual default destructor - virtual ~OutputPrintPolicy() = default; - - /// @brief handle output of debug message - /// - /// @param [in] lvl debug output level of message - /// @param [in] input text of debug message - virtual void - flush(const Level& lvl, const std::ostringstream& input) - = 0; - }; - - /// @brief abstract base class for filtering debug output - /// - /// Implementations of this interface need to define whether a debug message - /// with a certain debug level is processed or filtered out. - class OutputFilterPolicy - { - public: - /// virtual default destructor - virtual ~OutputFilterPolicy() = default; - - /// @brief decide whether a debug message should be processed - /// - /// @param [in] lvl debug level of debug message - /// - /// @return @c true of debug message should be processed, @c false if debug - /// message should be skipped - virtual bool - doPrint(const Level& lvl) const = 0; - }; - - /// @brief thread-safe output stream - /// - /// This classes caches the output internally and only flushes it to the - /// destination stream once it is destroyed. Using local instances of this - /// class therefore provides a thread-safe way for printing debug messages. - class OutStream final - { - /// function type for output flushing - using OutputFunc = std::function<void(const std::ostringstream&)>; - - public: - /// @brief construct stream object - /// - /// @param [in] output function object called for flushing the internal - /// cache - explicit OutStream(OutputFunc output) - : m_stream(), m_outputFunctor(std::move(output)) - { - } - - /// @brief copy constructor - /// - /// @param [in] copy stream object to copy - OutStream(const OutStream& copy) - : m_stream(), m_outputFunctor(copy.m_outputFunctor) - { - m_stream << copy.m_stream.str(); - } - - /// @brief destructor - /// - /// When calling the destructor, the internal cache is flushed using the - /// function provided during construction. - ~OutStream() { m_outputFunctor(m_stream); } - - /// @brief stream input operator forwarded to internal cache - /// - /// @tparam T input type - /// - /// @param [in] input content added to the stream - template <typename T> - OutStream& - operator<<(T&& input) - { - m_stream << std::forward<T>(input); - return *this; - } - - /// @brief forward stream modifiers to internal cache - /// - /// @tparam T stream type - /// - /// @param [in] f stream modifier - template <typename T> - OutStream& - operator<<(T& (*f)(T&)) - { - f(m_stream); - return *this; - } - - private: - /// internal cache of stream - std::ostringstream m_stream; - - /// output function called for flushing cache upon destruction - OutputFunc m_outputFunctor; - }; - - /// @brief default filter policy for debug messages - /// - /// All debug messages with a debug level equal or larger to the specified - /// threshold level are processed. - class DefaultFilterPolicy final : public OutputFilterPolicy - { - public: - /// @brief constructor - /// - /// @param [in] lvl threshold debug level - explicit DefaultFilterPolicy(const Level& lvl) : m_level(lvl) {} - - /// virtual default destructor - ~DefaultFilterPolicy() override = default; - - /// @brief decide whether a debug message should be processed - /// - /// @param [in] lvl debug level of debug message - /// - /// @return @c true if @p lvl >= #m_level, otherwise @c false - bool - doPrint(const Level& lvl) const override - { - return m_level <= lvl; - } - - private: - /// threshold debug level for messages to be processed - Level m_level; - }; - - /// @brief base class for decorating the debug output - /// - /// Derived classes may augment the debug message with additional information. - /// Chaining different decorators is possible to customize the output to your - /// needs. - class OutputDecorator : public OutputPrintPolicy - { - public: - /// @brief constructor wrapping actual output print policy - /// - /// @param [in] wrappee output print policy object which is wrapped by this - /// decorator object - explicit OutputDecorator(std::unique_ptr<OutputPrintPolicy> wrappee) - : m_wrappee(std::move(wrappee)) - { - } - - /// @brief flush the debug message to the destination stream - /// - /// @param [in] lvl debug level of debug message - /// @param [in] input text of debug message - /// - /// This function delegates the flushing of the debug message to its wrapped - /// object. - void - flush(const Level& lvl, const std::ostringstream& input) override - { - m_wrappee->flush(lvl, input); - } - - private: - /// wrapped object for printing the debug message - std::unique_ptr<OutputPrintPolicy> m_wrappee; - }; - - /// @brief decorate debug message with a name - /// - /// The debug message is complemented with a name. - class NamedOutputDecorator final : public OutputDecorator - { - public: - /// @brief constructor - /// - /// @param [in] wrappee output print policy object to be wrapped - /// @param [in] name name to be added to debug message - /// @param [in] maxWidth maximum width of field used for name - NamedOutputDecorator(std::unique_ptr<OutputPrintPolicy> wrappee, - const std::string& name, - unsigned int maxWidth = 15) - : OutputDecorator(std::move(wrappee)), m_name(name), m_maxWidth(maxWidth) - { - } - - /// @brief flush the debug message to the destination stream - /// - /// @param [in] lvl debug level of debug message - /// @param [in] input text of debug message - /// - /// This function prepends the given name to the debug message and then - /// delegates the flushing of the whole message to its wrapped object. - void - flush(const Level& lvl, const std::ostringstream& input) override - { - std::ostringstream os; - os << std::left << std::setw(m_maxWidth) - << m_name.substr(0, m_maxWidth - 3) << input.str(); - OutputDecorator::flush(lvl, os); - } - - private: - /// name to be prepended - std::string m_name; - - /// maximum width of field for printing the name - unsigned int m_maxWidth; - }; - - /// @brief decorate debug message with a time stamp - /// - /// The debug message is complemented with a time stamp. - class TimedOutputDecorator final : public OutputDecorator - { - public: - /// @brief constructor - /// - /// @param [in] wrappee output print policy object to be wrapped - /// @param [in] format format of time stamp (see std::strftime) - TimedOutputDecorator(std::unique_ptr<OutputPrintPolicy> wrappee, - const std::string& format = "%X") - : OutputDecorator(std::move(wrappee)), m_format(format) - { - } - - /// @brief flush the debug message to the destination stream - /// - /// @param [in] lvl debug level of debug message - /// @param [in] input text of debug message - /// - /// This function prepends a time stamp to the debug message and then - /// delegates the flushing of the whole message to its wrapped object. - void - flush(const Level& lvl, const std::ostringstream& input) override - { - std::ostringstream os; - os << std::left << std::setw(12) << now() << input.str(); - OutputDecorator::flush(lvl, os); - } - - private: - /// @brief get current time stamp - /// - /// @return current time stamp as string - std::string - now() const - { - char buffer[20]; - time_t t; - std::time(&t); - std::strftime(buffer, sizeof(buffer), m_format.c_str(), localtime(&t)); - return buffer; - } - - /// format of the time stamp (see std::strftime for details) - std::string m_format; - }; - - /// @brief decorate debug message with a thread ID - /// - /// The debug message is complemented with a thread ID. - class ThreadOutputDecorator final : public OutputDecorator - { - public: - /// @brief constructor - /// - /// @param [in] wrappee output print policy object to be wrapped - explicit ThreadOutputDecorator(std::unique_ptr<OutputPrintPolicy> wrappee) - : OutputDecorator(std::move(wrappee)) - { - } - - /// @brief flush the debug message to the destination stream - /// - /// @param [in] lvl debug level of debug message - /// @param [in] input text of debug message - /// - /// This function prepends the thread ID to the debug message and then - /// delegates the flushing of the whole message to its wrapped object. - void - flush(const Level& lvl, const std::ostringstream& input) override - { - std::ostringstream os; - os << std::left << std::setw(20) << std::this_thread::get_id() - << input.str(); - OutputDecorator::flush(lvl, os); - } - }; - - /// @brief decorate debug message with its debug level - /// - /// The debug message is complemented with its debug level. - class LevelOutputDecorator final : public OutputDecorator - { - public: - /// @brief constructor - /// - /// @param [in] wrappee output print policy object to be wrapped - explicit LevelOutputDecorator(std::unique_ptr<OutputPrintPolicy> wrappee) - : OutputDecorator(std::move(wrappee)) - { - } - - /// @brief flush the debug message to the destination stream - /// - /// @param [in] lvl debug level of debug message - /// @param [in] input text of debug message - /// - /// This function prepends the debug level to the debug message and then - /// delegates the flushing of the whole message to its wrapped object. - void - flush(const Level& lvl, const std::ostringstream& input) override - { - std::ostringstream os; - os << std::left << std::setw(10) << toString(lvl) << input.str(); - OutputDecorator::flush(lvl, os); - } - - private: - /// @brief convert debug level to string - /// - /// @param [in] lvl debug level - /// - /// @return string representation of debug level - std::string - toString(const Level& lvl) const - { - static const char* const buffer[] - = {"VERBOSE", "DEBUG", "INFO", "WARNING", "ERROR", "FATAL"}; - return buffer[lvl]; - } - }; - - /// @brief default print policy for debug messages - /// - /// This class allows to print debug messages without further modifications to - /// a specified output stream. - class DefaultPrintPolicy final : public OutputPrintPolicy - { - public: - /// @brief constructor - /// - /// @param [in] out pointer to output stream object - /// - /// @pre @p out is non-zero - explicit DefaultPrintPolicy(std::ostream* out = &std::cout) : m_out(out) {} - - /// @brief flush the debug message to the destination stream - /// - /// @param [in] lvl debug level of debug message - /// @param [in] input text of debug message - void - flush(const Level& /*lvl*/, const std::ostringstream& input) final - { - (*m_out) << input.str() << std::endl; - } - - private: - /// pointer to destination output stream - std::ostream* m_out; - }; +/// @brief constants steering the debug output +/// +/// All messages with a debug level equal or higher than the currently set +/// debug output level will be printed. +enum Level { + VERBOSE = 0, ///< VERBOSE level + DEBUG, ///< DEBUG level + INFO, ///< INFO level + WARNING, ///< WARNING level + ERROR, ///< ERROR level + FATAL ///< FATAL level +}; + +/// @brief abstract base class for printing debug output +/// +/// Implementations of this interface need to define how and where to @a print +/// debug messages (e.g. to a file, to a stream into a database etc). +class OutputPrintPolicy { + public: + /// virtual default destructor + virtual ~OutputPrintPolicy() = default; + + /// @brief handle output of debug message + /// + /// @param [in] lvl debug output level of message + /// @param [in] input text of debug message + virtual void flush(const Level& lvl, const std::ostringstream& input) = 0; +}; + +/// @brief abstract base class for filtering debug output +/// +/// Implementations of this interface need to define whether a debug message +/// with a certain debug level is processed or filtered out. +class OutputFilterPolicy { + public: + /// virtual default destructor + virtual ~OutputFilterPolicy() = default; + + /// @brief decide whether a debug message should be processed + /// + /// @param [in] lvl debug level of debug message + /// + /// @return @c true of debug message should be processed, @c false if debug + /// message should be skipped + virtual bool doPrint(const Level& lvl) const = 0; +}; + +/// @brief thread-safe output stream +/// +/// This classes caches the output internally and only flushes it to the +/// destination stream once it is destroyed. Using local instances of this +/// class therefore provides a thread-safe way for printing debug messages. +class OutStream final { + /// function type for output flushing + using OutputFunc = std::function<void(const std::ostringstream&)>; + + public: + /// @brief construct stream object + /// + /// @param [in] output function object called for flushing the internal + /// cache + explicit OutStream(OutputFunc output) + : m_stream(), m_outputFunctor(std::move(output)) {} + + /// @brief copy constructor + /// + /// @param [in] copy stream object to copy + OutStream(const OutStream& copy) + : m_stream(), m_outputFunctor(copy.m_outputFunctor) { + m_stream << copy.m_stream.str(); + } + + /// @brief destructor + /// + /// When calling the destructor, the internal cache is flushed using the + /// function provided during construction. + ~OutStream() { m_outputFunctor(m_stream); } + + /// @brief stream input operator forwarded to internal cache + /// + /// @tparam T input type + /// + /// @param [in] input content added to the stream + template <typename T> + OutStream& operator<<(T&& input) { + m_stream << std::forward<T>(input); + return *this; + } + + /// @brief forward stream modifiers to internal cache + /// + /// @tparam T stream type + /// + /// @param [in] f stream modifier + template <typename T> + OutStream& operator<<(T& (*f)(T&)) { + f(m_stream); + return *this; + } + + private: + /// internal cache of stream + std::ostringstream m_stream; + + /// output function called for flushing cache upon destruction + OutputFunc m_outputFunctor; +}; + +/// @brief default filter policy for debug messages +/// +/// All debug messages with a debug level equal or larger to the specified +/// threshold level are processed. +class DefaultFilterPolicy final : public OutputFilterPolicy { + public: + /// @brief constructor + /// + /// @param [in] lvl threshold debug level + explicit DefaultFilterPolicy(const Level& lvl) : m_level(lvl) {} + + /// virtual default destructor + ~DefaultFilterPolicy() override = default; + + /// @brief decide whether a debug message should be processed + /// + /// @param [in] lvl debug level of debug message + /// + /// @return @c true if @p lvl >= #m_level, otherwise @c false + bool doPrint(const Level& lvl) const override { return m_level <= lvl; } + + private: + /// threshold debug level for messages to be processed + Level m_level; +}; + +/// @brief base class for decorating the debug output +/// +/// Derived classes may augment the debug message with additional information. +/// Chaining different decorators is possible to customize the output to your +/// needs. +class OutputDecorator : public OutputPrintPolicy { + public: + /// @brief constructor wrapping actual output print policy + /// + /// @param [in] wrappee output print policy object which is wrapped by this + /// decorator object + explicit OutputDecorator(std::unique_ptr<OutputPrintPolicy> wrappee) + : m_wrappee(std::move(wrappee)) {} + + /// @brief flush the debug message to the destination stream + /// + /// @param [in] lvl debug level of debug message + /// @param [in] input text of debug message + /// + /// This function delegates the flushing of the debug message to its wrapped + /// object. + void flush(const Level& lvl, const std::ostringstream& input) override { + m_wrappee->flush(lvl, input); + } + + private: + /// wrapped object for printing the debug message + std::unique_ptr<OutputPrintPolicy> m_wrappee; +}; + +/// @brief decorate debug message with a name +/// +/// The debug message is complemented with a name. +class NamedOutputDecorator final : public OutputDecorator { + public: + /// @brief constructor + /// + /// @param [in] wrappee output print policy object to be wrapped + /// @param [in] name name to be added to debug message + /// @param [in] maxWidth maximum width of field used for name + NamedOutputDecorator(std::unique_ptr<OutputPrintPolicy> wrappee, + const std::string& name, unsigned int maxWidth = 15) + : OutputDecorator(std::move(wrappee)), + m_name(name), + m_maxWidth(maxWidth) {} + + /// @brief flush the debug message to the destination stream + /// + /// @param [in] lvl debug level of debug message + /// @param [in] input text of debug message + /// + /// This function prepends the given name to the debug message and then + /// delegates the flushing of the whole message to its wrapped object. + void flush(const Level& lvl, const std::ostringstream& input) override { + std::ostringstream os; + os << std::left << std::setw(m_maxWidth) << m_name.substr(0, m_maxWidth - 3) + << input.str(); + OutputDecorator::flush(lvl, os); + } + + private: + /// name to be prepended + std::string m_name; + + /// maximum width of field for printing the name + unsigned int m_maxWidth; +}; + +/// @brief decorate debug message with a time stamp +/// +/// The debug message is complemented with a time stamp. +class TimedOutputDecorator final : public OutputDecorator { + public: + /// @brief constructor + /// + /// @param [in] wrappee output print policy object to be wrapped + /// @param [in] format format of time stamp (see std::strftime) + TimedOutputDecorator(std::unique_ptr<OutputPrintPolicy> wrappee, + const std::string& format = "%X") + : OutputDecorator(std::move(wrappee)), m_format(format) {} + + /// @brief flush the debug message to the destination stream + /// + /// @param [in] lvl debug level of debug message + /// @param [in] input text of debug message + /// + /// This function prepends a time stamp to the debug message and then + /// delegates the flushing of the whole message to its wrapped object. + void flush(const Level& lvl, const std::ostringstream& input) override { + std::ostringstream os; + os << std::left << std::setw(12) << now() << input.str(); + OutputDecorator::flush(lvl, os); + } + + private: + /// @brief get current time stamp + /// + /// @return current time stamp as string + std::string now() const { + char buffer[20]; + time_t t; + std::time(&t); + std::strftime(buffer, sizeof(buffer), m_format.c_str(), localtime(&t)); + return buffer; + } + + /// format of the time stamp (see std::strftime for details) + std::string m_format; +}; + +/// @brief decorate debug message with a thread ID +/// +/// The debug message is complemented with a thread ID. +class ThreadOutputDecorator final : public OutputDecorator { + public: + /// @brief constructor + /// + /// @param [in] wrappee output print policy object to be wrapped + explicit ThreadOutputDecorator(std::unique_ptr<OutputPrintPolicy> wrappee) + : OutputDecorator(std::move(wrappee)) {} + + /// @brief flush the debug message to the destination stream + /// + /// @param [in] lvl debug level of debug message + /// @param [in] input text of debug message + /// + /// This function prepends the thread ID to the debug message and then + /// delegates the flushing of the whole message to its wrapped object. + void flush(const Level& lvl, const std::ostringstream& input) override { + std::ostringstream os; + os << std::left << std::setw(20) << std::this_thread::get_id() + << input.str(); + OutputDecorator::flush(lvl, os); + } +}; + +/// @brief decorate debug message with its debug level +/// +/// The debug message is complemented with its debug level. +class LevelOutputDecorator final : public OutputDecorator { + public: + /// @brief constructor + /// + /// @param [in] wrappee output print policy object to be wrapped + explicit LevelOutputDecorator(std::unique_ptr<OutputPrintPolicy> wrappee) + : OutputDecorator(std::move(wrappee)) {} + + /// @brief flush the debug message to the destination stream + /// + /// @param [in] lvl debug level of debug message + /// @param [in] input text of debug message + /// + /// This function prepends the debug level to the debug message and then + /// delegates the flushing of the whole message to its wrapped object. + void flush(const Level& lvl, const std::ostringstream& input) override { + std::ostringstream os; + os << std::left << std::setw(10) << toString(lvl) << input.str(); + OutputDecorator::flush(lvl, os); + } + + private: + /// @brief convert debug level to string + /// + /// @param [in] lvl debug level + /// + /// @return string representation of debug level + std::string toString(const Level& lvl) const { + static const char* const buffer[] = {"VERBOSE", "DEBUG", "INFO", + "WARNING", "ERROR", "FATAL"}; + return buffer[lvl]; + } +}; + +/// @brief default print policy for debug messages +/// +/// This class allows to print debug messages without further modifications to +/// a specified output stream. +class DefaultPrintPolicy final : public OutputPrintPolicy { + public: + /// @brief constructor + /// + /// @param [in] out pointer to output stream object + /// + /// @pre @p out is non-zero + explicit DefaultPrintPolicy(std::ostream* out = &std::cout) : m_out(out) {} + + /// @brief flush the debug message to the destination stream + /// + /// @param [in] lvl debug level of debug message + /// @param [in] input text of debug message + void flush(const Level& /*lvl*/, const std::ostringstream& input) final { + (*m_out) << input.str() << std::endl; + } + + private: + /// pointer to destination output stream + std::ostream* m_out; +}; } // namespace Logging /// @brief class for printing debug output @@ -535,27 +486,22 @@ namespace Logging { /// different levels of severity. /// /// @ingroup Logging -class Logger -{ -public: +class Logger { + public: /// @brief construct from output print and filter policy /// /// @param [in] pPrint policy for printing debug messages /// @param [in] pFilter policy for filtering debug messages - Logger(std::unique_ptr<Logging::OutputPrintPolicy> pPrint, + Logger(std::unique_ptr<Logging::OutputPrintPolicy> pPrint, std::unique_ptr<Logging::OutputFilterPolicy> pFilter) - : m_printPolicy(std::move(pPrint)), m_filterPolicy(std::move(pFilter)) - { - } + : m_printPolicy(std::move(pPrint)), m_filterPolicy(std::move(pFilter)) {} /// @brief decide whether a message with a given debug level has to be printed /// /// @param [in] lvl debug level of debug message /// /// @return @c true if debug message should be printed, otherwise @c false - bool - doPrint(const Logging::Level& lvl) const - { + bool doPrint(const Logging::Level& lvl) const { return m_filterPolicy->doPrint(lvl); } @@ -569,16 +515,13 @@ public: /// of scope. /// /// @return output stream object with internal cache for debug message - Logging::OutStream - log(const Logging::Level& lvl) const - { + Logging::OutStream log(const Logging::Level& lvl) const { return Logging::OutStream(std::bind(&Logging::OutputPrintPolicy::flush, - m_printPolicy.get(), - lvl, + m_printPolicy.get(), lvl, std::placeholders::_1)); } -private: + private: /// policy object for printing debug messages std::unique_ptr<Logging::OutputPrintPolicy> m_printPolicy; @@ -599,9 +542,8 @@ private: /// - debug level /// /// @return pointer to logging instance -std::unique_ptr<const Logger> -getDefaultLogger(const std::string& name, - const Logging::Level& lvl, - std::ostream* log_stream = &std::cout); +std::unique_ptr<const Logger> getDefaultLogger( + const std::string& name, const Logging::Level& lvl, + std::ostream* log_stream = &std::cout); } // namespace Acts diff --git a/Core/include/Acts/Utilities/ObjHelper.hpp b/Core/include/Acts/Utilities/ObjHelper.hpp index 115bd2088277a2893360324d002fda7985ffde88..c45abf648472720953eb13b9a1352ba8c7f8be7a 100644 --- a/Core/include/Acts/Utilities/ObjHelper.hpp +++ b/Core/include/Acts/Utilities/ObjHelper.hpp @@ -18,9 +18,8 @@ namespace Acts { * supported in this implementation. */ template <typename T = double> -class ObjHelper : public IVisualization -{ -public: +class ObjHelper : public IVisualization { + public: static_assert(std::is_same_v<T, double> || std::is_same_v<T, float>, "Use either double or float"); @@ -42,10 +41,8 @@ public: /** * @copydoc Acts::IVisualization::vertex() */ - void - vertex(const Vector3D& vtx, - IVisualization::color_type color = {0, 0, 0}) override - { + void vertex(const Vector3D& vtx, + IVisualization::color_type color = {0, 0, 0}) override { (void)color; // suppress unused warning m_vertices.push_back(vtx.template cast<value_type>()); } @@ -54,11 +51,8 @@ public: * @copydoc Acts::IVisualization::line() * @note This function ist not implemented for the OBJ format. */ - void - line(const Vector3D& /*a*/, - const Vector3D& /*b*/, - IVisualization::color_type color = {0, 0, 0}) override - { + void line(const Vector3D& /*a*/, const Vector3D& /*b*/, + IVisualization::color_type color = {0, 0, 0}) override { (void)color; // suppress unused warning // not implemented throw std::runtime_error("Line not implemented for OBJ"); @@ -67,10 +61,8 @@ public: /** * @copydoc Acts::IVisualization::face() */ - void - face(const std::vector<Vector3D>& vtxs, - IVisualization::color_type color = {0, 0, 0}) override - { + void face(const std::vector<Vector3D>& vtxs, + IVisualization::color_type color = {0, 0, 0}) override { (void)color; // suppress unused warning face_type idxs; idxs.reserve(vtxs.size()); @@ -84,9 +76,7 @@ public: /** * @copydoc Acts::IVisualization::write() */ - void - write(std::ostream& os) const override - { + void write(std::ostream& os) const override { for (const vertex_type& vtx : m_vertices) { os << "v " << vtx.x() << " " << vtx.y() << " " << vtx.z() << "\n"; } @@ -103,15 +93,13 @@ public: /** * @copydoc Acts::IVisualization::clear() */ - void - clear() override - { + void clear() override { m_vertices.clear(); m_faces.clear(); } -private: + private: std::vector<vertex_type> m_vertices; - std::vector<face_type> m_faces; + std::vector<face_type> m_faces; }; -} +} // namespace Acts diff --git a/Core/include/Acts/Utilities/ParameterDefinitions.hpp b/Core/include/Acts/Utilities/ParameterDefinitions.hpp index 1587d690103875aff710b90890a6873d4350c038..643737152bf798d87e2f3bda40b2ce4deea391e8 100644 --- a/Core/include/Acts/Utilities/ParameterDefinitions.hpp +++ b/Core/include/Acts/Utilities/ParameterDefinitions.hpp @@ -35,8 +35,8 @@ static_assert(Acts::eLOC_R == Acts::eLOC_0 or Acts::eLOC_R == Acts::eLOC_1, "local radius must be a local parameter"); static_assert(Acts::eLOC_PHI == Acts::eLOC_0 or Acts::eLOC_PHI == Acts::eLOC_1, "local phi must be a local parameter"); -static_assert(Acts::eLOC_RPHI == Acts::eLOC_0 - or Acts::eLOC_RPHI == Acts::eLOC_1, +static_assert(Acts::eLOC_RPHI == Acts::eLOC_0 or + Acts::eLOC_RPHI == Acts::eLOC_1, "local r x phi must be a local parameter"); static_assert(Acts::eLOC_Z == Acts::eLOC_0 or Acts::eLOC_Z == Acts::eLOC_1, "local z must be a local parameter"); diff --git a/Core/include/Acts/Utilities/ParameterTypes.hpp b/Core/include/Acts/Utilities/ParameterTypes.hpp index e54f80ec347b05223bbb9063c691435d85cd4b4b..e97d52563158b6125b7130b9a3d25ed69a75ac40 100644 --- a/Core/include/Acts/Utilities/ParameterTypes.hpp +++ b/Core/include/Acts/Utilities/ParameterTypes.hpp @@ -14,8 +14,7 @@ namespace Acts { /// /// @brief type for parameters with unrestricted value range /// -struct unbound_parameter -{ +struct unbound_parameter { static constexpr bool may_modify_value{ false}; ///< parameter values need no adjustment @@ -28,16 +27,12 @@ struct unbound_parameter /// @return identical input parameter value /// template <typename T> - static T - getValue(const T& input) - { + static T getValue(const T& input) { return input; } template <typename T> - static T - getDifference(const T& first, const T& second) - { + static T getDifference(const T& first, const T& second) { return first - second; } }; @@ -45,9 +40,7 @@ struct unbound_parameter /// /// @brief type for local parameters bound to a surface /// -struct local_parameter : public unbound_parameter -{ -}; +struct local_parameter : public unbound_parameter {}; /// /// @brief type for parameter with restricted value range @@ -62,8 +55,7 @@ struct local_parameter : public unbound_parameter /// the value range /// template <typename T, T (*MIN)(), T (*MAX)()> -struct bound_parameter -{ +struct bound_parameter { static constexpr bool may_modify_value{ true}; ///< parameter values may need adjustment static constexpr T min{MIN()}; ///< lower bound of range @@ -80,16 +72,12 @@ struct bound_parameter /// @c bound_parameter<U,MIN,MAX>::max. /// template <typename U> - static U - getValue(const U& input) - { + static U getValue(const U& input) { return (input > max) ? max : ((input < min) ? min : input); } template <typename U> - static U - getDifference(const U& first, const U& second) - { + static U getDifference(const U& first, const U& second) { return getValue(first) - getValue(second); } }; @@ -106,8 +94,7 @@ struct bound_parameter /// the value range /// template <typename T, T (*MIN)(), T (*MAX)()> -struct cyclic_parameter -{ +struct cyclic_parameter { static constexpr bool may_modify_value{ true}; ///< parameter values may need adjustment static constexpr T min{MIN()}; ///< lower bound of range @@ -125,9 +112,7 @@ struct cyclic_parameter /// parameter type. /// template <typename U> - static U - getValue(const U& input) - { + static U getValue(const U& input) { if (min <= input && input < max) { return input; } else { @@ -136,11 +121,9 @@ struct cyclic_parameter } template <typename U> - static U - getDifference(const U& first, const U& second) - { + static U getDifference(const U& first, const U& second) { static constexpr U half_period = (max - min) / 2; - U tmp = getValue(first) - getValue(second); + U tmp = getValue(first) - getValue(second); return (tmp < -half_period ? tmp + 2 * half_period : (tmp > half_period ? tmp - 2 * half_period : tmp)); diff --git a/Core/include/Acts/Utilities/PlyHelper.hpp b/Core/include/Acts/Utilities/PlyHelper.hpp index 88ce36450ed50cb17b8ad33d8c23568f5415873c..2b75bb687ccae82144c2eb2b6eb31da51974c717 100644 --- a/Core/include/Acts/Utilities/PlyHelper.hpp +++ b/Core/include/Acts/Utilities/PlyHelper.hpp @@ -14,9 +14,8 @@ namespace Acts { template <typename T = double> -class PlyHelper : public IVisualization -{ -public: +class PlyHelper : public IVisualization { + public: static_assert(std::is_same_v<T, double> || std::is_same_v<T, float>, "Use either double or float"); @@ -38,20 +37,16 @@ public: /** * @copydoc Acts::IVisualization::vertex() */ - void - vertex(const Vector3D& vtx, - IVisualization::color_type color = {120, 120, 120}) override - { + void vertex(const Vector3D& vtx, + IVisualization::color_type color = {120, 120, 120}) override { m_vertices.emplace_back(vtx.template cast<value_type>(), color); } /** * @copydoc Acts::IVisualization::line() */ - void - face(const std::vector<Vector3D>& vtxs, - IVisualization::color_type color = {120, 120, 120}) override - { + void face(const std::vector<Vector3D>& vtxs, + IVisualization::color_type color = {120, 120, 120}) override { face_type idxs; idxs.reserve(vtxs.size()); for (const auto& vtx : vtxs) { @@ -64,11 +59,8 @@ public: /** * @copydoc Acts::IVisualization::face() */ - void - line(const Vector3D& a, - const Vector3D& b, - IVisualization::color_type color = {120, 120, 120}) override - { + void line(const Vector3D& a, const Vector3D& b, + IVisualization::color_type color = {120, 120, 120}) override { vertex(a, color); size_t idx_a = m_vertices.size() - 1; vertex(b, color); @@ -79,9 +71,7 @@ public: /** * @copydoc Acts::IVisualization::write() */ - void - write(std::ostream& os) const override - { + void write(std::ostream& os) const override { os << "ply\n"; os << "format ascii 1.0\n"; os << "element vertex " << m_vertices.size() << "\n"; @@ -129,18 +119,16 @@ public: /** * @copydoc Acts::IVisualization::clear() */ - void - clear() override - { + void clear() override { m_vertices.clear(); m_faces.clear(); m_edges.clear(); } -private: + private: std::vector<std::pair<vertex_type, IVisualization::color_type>> m_vertices; std::vector<face_type> m_faces; std::vector<std::pair<std::pair<size_t, size_t>, IVisualization::color_type>> m_edges; }; -} +} // namespace Acts diff --git a/Core/include/Acts/Utilities/Result.hpp b/Core/include/Acts/Utilities/Result.hpp index 0bfc9eaf144831979358d3e0a2a67e29189c546b..e18937b8661b3a68221bddcf5426673068f8b5e0 100644 --- a/Core/include/Acts/Utilities/Result.hpp +++ b/Core/include/Acts/Utilities/Result.hpp @@ -22,8 +22,7 @@ namespace Acts { * @tparam E The error, defaults to `std::error_code` */ template <typename T, typename E = std::error_code> -class Result -{ +class Result { /** * Private constructor which accepts an external variant. * This is used by the factory static methods to set up @@ -31,7 +30,7 @@ class Result */ Result(std::variant<T, E>&& var) : m_var(var) {} -public: + public: /** * Default construction is disallowed. */ @@ -45,9 +44,7 @@ public: /** * Assignment is disallowed */ - Result<T, E>& - operator=(const Result<T, E>& other) - = delete; + Result<T, E>& operator=(const Result<T, E>& other) = delete; /** * Move construction is allowed @@ -59,9 +56,7 @@ public: * @param other The other result instance, rvalue reference * @return The assigned instance */ - Result<T, E>& - operator=(Result<T, E>&& other) - { + Result<T, E>& operator=(Result<T, E>&& other) { m_var = std::move(other.m_var); return *this; } @@ -80,17 +75,11 @@ public: * @param value The potential value, could be an actual valid value or an * error. */ - template < - typename T2, - typename _E = E, - typename _T = T, - typename = std:: - enable_if_t<!std:: - is_same_v<_T, - _E> && !std::is_constructible_v<_T, _E> && !std::is_constructible_v<_E, _T>>> - Result(T2 value) noexcept : m_var(std::move(value)) - { - } + template <typename T2, typename _E = E, typename _T = T, + typename = std::enable_if_t<!std::is_same_v<_T, _E> && + !std::is_constructible_v<_T, _E> && + !std::is_constructible_v<_E, _T>>> + Result(T2 value) noexcept : m_var(std::move(value)) {} /** * @brief Assignment operator from arbitrary value @@ -101,17 +90,11 @@ public: * error. * @return The assigned instance */ - template < - typename T2, - typename _E = E, - typename _T = T, - typename = std:: - enable_if_t<!std:: - is_same_v<_T, - _E> && !std::is_constructible_v<_T, _E> && !std::is_constructible_v<_E, _T>>> - Result<T, E>& - operator=(T2 value) noexcept - { + template <typename T2, typename _E = E, typename _T = T, + typename = std::enable_if_t<!std::is_same_v<_T, _E> && + !std::is_constructible_v<_T, _E> && + !std::is_constructible_v<_E, _T>>> + Result<T, E>& operator=(T2 value) noexcept { m_var = std::move(value); return *this; } @@ -121,9 +104,7 @@ public: * @param value The valid value to assign. Will not be converted to E. * @return Initialized result object */ - static Result<T, E> - success(T value) - { + static Result<T, E> success(T value) { return Result<T, E>( std::variant<T, E>{std::in_place_index<0>, std::move(value)}); } @@ -133,9 +114,7 @@ public: * @param value The error to assign. Will not be converted to T. * @return Initialized result object */ - static Result<T, E> - failure(E error) - { + static Result<T, E> failure(E error) { return Result<T, E>( std::variant<T, E>{std::in_place_index<1>, std::move(error)}); } @@ -144,11 +123,7 @@ public: * Checks whether this result contains a valid value, and no error. * @return bool Whether result contains an error or not. */ - bool - ok() const noexcept - { - return m_var.index() == 0; - } + bool ok() const noexcept { return m_var.index() == 0; } /** * Returns a reference into the variant to the valid value. @@ -162,44 +137,29 @@ public: * @note If `res.ok()` this method will abort (noexcept) * @return Reference to the error */ - E& - error() - & noexcept - { - return std::get<E>(m_var); - } + E& error() & noexcept { return std::get<E>(m_var); } /** * Returns the error by-value. * @note If `res.ok()` this method will abort (noexcept) * @return The error */ - E - error() - && noexcept - { - return std::move(std::get<E>(m_var)); - } + E error() && noexcept { return std::move(std::get<E>(m_var)); } /** * Retrieves the valid value from the result object. * @note This is the lvalue version, returns a reference to the value * @return The valid value as a reference */ - T& - value() & - { + T& value() & { if (m_var.index() != 0) { - if - constexpr(std::is_same_v<E, std::error_code>) - { - std::stringstream ss; - const auto& e = std::get<E>(m_var); - ss << "Value called on error value: " << e.category().name() << ": " - << e.message() << " [" << e.value() << "]"; - throw std::runtime_error(ss.str()); - } - else { + if constexpr (std::is_same_v<E, std::error_code>) { + std::stringstream ss; + const auto& e = std::get<E>(m_var); + ss << "Value called on error value: " << e.category().name() << ": " + << e.message() << " [" << e.value() << "]"; + throw std::runtime_error(ss.str()); + } else { throw std::runtime_error("Value called on error value"); } } @@ -213,20 +173,15 @@ public: * by-value and moves out of the variant. * @return The valid value by value, moved out of the variant. */ - T - value() && - { + T value() && { if (m_var.index() != 0) { - if - constexpr(std::is_same_v<E, std::error_code>) - { - std::stringstream ss; - const auto& e = std::get<E>(m_var); - ss << "Value called on error value: " << e.category().name() << ": " - << e.message() << " [" << e.value() << "]"; - throw std::runtime_error(ss.str()); - } - else { + if constexpr (std::is_same_v<E, std::error_code>) { + std::stringstream ss; + const auto& e = std::get<E>(m_var); + ss << "Value called on error value: " << e.category().name() << ": " + << e.message() << " [" << e.value() << "]"; + throw std::runtime_error(ss.str()); + } else { throw std::runtime_error("Value called on error value"); } } @@ -234,7 +189,7 @@ public: return std::move(std::get<T>(m_var)); } -private: + private: std::variant<T, E> m_var; }; @@ -252,9 +207,8 @@ private: * @tparam E The type of the error */ template <typename E> -class Result<void, E> -{ -public: +class Result<void, E> { + public: /** * Default constructor which initializes the result in the ok state. */ @@ -268,9 +222,7 @@ public: /** * The (self) assignment operator is deleted. */ - Result<void, E>& - operator=(const Result<void, E>& other) - = delete; + Result<void, E>& operator=(const Result<void, E>& other) = delete; /** * Move constructor @@ -282,9 +234,7 @@ public: * Move assignment operator * @param other The other result object, rvalue ref */ - Result<void, E>& - operator=(Result<void, E>&& other) noexcept - { + Result<void, E>& operator=(Result<void, E>&& other) noexcept { m_opt = std::move(other.m_opt); return *this; } @@ -295,9 +245,7 @@ public: * @param error The instance of the actual error */ template <typename E2> - Result(E2 error) noexcept : m_opt(std::move(error)) - { - } + Result(E2 error) noexcept : m_opt(std::move(error)) {} /** * Assignment operator from an error. @@ -306,9 +254,7 @@ public: * @return The assigned instance */ template <typename E2> - Result<void, E>& - operator=(E2 error) - { + Result<void, E>& operator=(E2 error) { m_opt = std::move(error); return *this; } @@ -317,20 +263,14 @@ public: * Static factory function to initialize the result in the ok state. * @return Result object, in ok state */ - static Result<void, E> - success() - { - return Result<void, E>(); - } + static Result<void, E> success() { return Result<void, E>(); } /** * Static factory function to initialize the result in the error state. * @param error The errorr to initialize with. * @return Result object, in error state. */ - static Result<void, E> - failure(E error) - { + static Result<void, E> failure(E error) { return Result<void, E>(std::move(error)); } @@ -338,37 +278,23 @@ public: * Checks whether this result is in the ok state, and no error. * @return bool Whether result contains an error or not. */ - bool - ok() const noexcept - { - return !m_opt; - } + bool ok() const noexcept { return !m_opt; } /** * Returns a reference to the error stored in the result. * @note If `res.ok()` this method will abort (noexcept) * @return Reference to the error */ - E& - error() - & noexcept - { - return *m_opt; - } + E& error() & noexcept { return *m_opt; } /** * Returns the error by-value. * @note If `res.ok()` this method will abort (noexcept) * @return Reference to the error */ - E - error() - && noexcept - { - return std::move(*m_opt); - } + E error() && noexcept { return std::move(*m_opt); } -private: + private: std::optional<E> m_opt; }; diff --git a/Core/include/Acts/Utilities/ThrowAssert.hpp b/Core/include/Acts/Utilities/ThrowAssert.hpp index eb3227ad067c8ec6ce43d49966d5a144a1cf6833..419dc11f31c69bcc401c0195b910abe63a2816eb 100644 --- a/Core/include/Acts/Utilities/ThrowAssert.hpp +++ b/Core/include/Acts/Utilities/ThrowAssert.hpp @@ -15,16 +15,14 @@ namespace Acts { /// @brief Exception type for assertion failures /// This class captures the information available to the throw_assert macro -class AssertionFailureException : public std::exception -{ -public: +class AssertionFailureException : public std::exception { + public: /// @brief Class which allows to use the << operator to assemble a string - class StreamFormatter - { - private: + class StreamFormatter { + private: std::ostringstream stream; - public: + public: /// @brief Converts to string operator std::string() const { return stream.str(); } @@ -33,9 +31,7 @@ public: /// @tparam T type of anything /// @param value const ref to anything template <typename T> - StreamFormatter& - operator<<(const T& value) - { + StreamFormatter& operator<<(const T& value) { stream << value; return *this; } @@ -47,10 +43,8 @@ public: /// @param line The current line /// @param msg The message to print if assertion fails AssertionFailureException(const std::string& expression, - const std::string& file, - int line, - const std::string& msg) - { + const std::string& file, int line, + const std::string& msg) { std::ostringstream os; if (!msg.empty()) { @@ -64,23 +58,17 @@ public: } /// The assertion message - const char* - what() const throw() override - { - return report.c_str(); - } + const char* what() const throw() override { return report.c_str(); } -private: + private: std::string report; }; } // namespace Acts -#define throw_assert(EXPRESSION, MESSAGE) \ - if (!(EXPRESSION)) { \ - throw Acts::AssertionFailureException( \ - #EXPRESSION, \ - __FILE__, \ - __LINE__, \ - (Acts::AssertionFailureException::StreamFormatter() << MESSAGE)); \ +#define throw_assert(EXPRESSION, MESSAGE) \ + if (!(EXPRESSION)) { \ + throw Acts::AssertionFailureException( \ + #EXPRESSION, __FILE__, __LINE__, \ + (Acts::AssertionFailureException::StreamFormatter() << MESSAGE)); \ } diff --git a/Core/include/Acts/Utilities/TypeTraits.hpp b/Core/include/Acts/Utilities/TypeTraits.hpp index 573a776dd6acfb6b7870fdabc844b1e50f6221db..d7ff645497048a0064f70dc05cc98586c724de9a 100644 --- a/Core/include/Acts/Utilities/TypeTraits.hpp +++ b/Core/include/Acts/Utilities/TypeTraits.hpp @@ -16,77 +16,70 @@ namespace Acts { namespace detail { - /** - * This file contains an implementation of the detection idiom in C++. - * It's not currently in the standard, but can be implemented using - * standard features. This implementation is largely taken from the C++ - * [technical specifications, library fundamentals - * v2](https://en.cppreference.com/w/cpp/experimental/is_detected) - * - * The detector pattern works like this: there is a default type, that - * accepts an "operation" that can be basically anything. It also accepts - * variadic arguments for that operation. The default type - * has a member type that is std::false_type to indicate success or - * failure. It also has a member type "type" which captures a type result. - * Then there is a specialization which attempts to instantiate the operation - * with the given parameters, and tries to assign it into std::void_t. If the - * operation fails to instantiate (say, the checked for type does not exist), - * the specialization will not be instantiated, and the compiler falls back to - * the default type which contains std::false_type. Since it happens inside - * while the compiler tries to find a better matching template specialization - * than the default one (so basically overload resolution), a compile error - * inside the operation is handled as a substitution failure, and is not an - * error. If the instantiation succeeds, the specialization contains a - * std::true_type, and an alias to the result of the operation. - * - * Essentially, it provides a convenient way to "lift" operations into this - * overload resolution, allowing testing expressions and evaluating them into - * compile time booleans (instead of compilation failures). - */ +/** + * This file contains an implementation of the detection idiom in C++. + * It's not currently in the standard, but can be implemented using + * standard features. This implementation is largely taken from the C++ + * [technical specifications, library fundamentals + * v2](https://en.cppreference.com/w/cpp/experimental/is_detected) + * + * The detector pattern works like this: there is a default type, that + * accepts an "operation" that can be basically anything. It also accepts + * variadic arguments for that operation. The default type + * has a member type that is std::false_type to indicate success or + * failure. It also has a member type "type" which captures a type result. + * Then there is a specialization which attempts to instantiate the operation + * with the given parameters, and tries to assign it into std::void_t. If the + * operation fails to instantiate (say, the checked for type does not exist), + * the specialization will not be instantiated, and the compiler falls back to + * the default type which contains std::false_type. Since it happens inside + * while the compiler tries to find a better matching template specialization + * than the default one (so basically overload resolution), a compile error + * inside the operation is handled as a substitution failure, and is not an + * error. If the instantiation succeeds, the specialization contains a + * std::true_type, and an alias to the result of the operation. + * + * Essentially, it provides a convenient way to "lift" operations into this + * overload resolution, allowing testing expressions and evaluating them into + * compile time booleans (instead of compilation failures). + */ - /** - * Helper struct which cannot be constructe (or destroyes)d at all. - */ - struct nonesuch - { - ~nonesuch() = delete; - nonesuch(nonesuch const&) = delete; - void - operator=(nonesuch const&) - = delete; - }; +/** + * Helper struct which cannot be constructe (or destroyes)d at all. + */ +struct nonesuch { + ~nonesuch() = delete; + nonesuch(nonesuch const&) = delete; + void operator=(nonesuch const&) = delete; +}; - /** - * This is the default specialization. - * It does not attempt to instantiate `Op<Args...>` at all. - * @tparam Default The default type to set - * @tparam AlwaysVoid Helper type that accepts the void instantiation - * @tparam Op The operation to test - * @tparam Args Arguments to the operation - */ - template <class Default, - class AlwaysVoid, - template <class...> class Op, - class... Args> - struct detector - { - using value_t = std::false_type; - using type = Default; - }; +/** + * This is the default specialization. + * It does not attempt to instantiate `Op<Args...>` at all. + * @tparam Default The default type to set + * @tparam AlwaysVoid Helper type that accepts the void instantiation + * @tparam Op The operation to test + * @tparam Args Arguments to the operation + */ +template <class Default, class AlwaysVoid, template <class...> class Op, + class... Args> +struct detector { + using value_t = std::false_type; + using type = Default; +}; - /** - * This is the specialization which attempts to instantiate `Op<Args...`. - * @tparam Default Default type to set if substitution fails - * @tparam Op The operation to test - * @tparam Args Arguments to the operation - */ - template <class Default, template <class...> class Op, class... Args> - struct detector<Default, std::void_t<Op<Args...>>, Op, Args...> - { - // Note that std::void_t is a C++17 feature - using value_t = std::true_type; - using type = Op<Args...>; - }; +/** + * This is the specialization which attempts to instantiate `Op<Args...`. + * @tparam Default Default type to set if substitution fails + * @tparam Op The operation to test + * @tparam Args Arguments to the operation + */ +template <class Default, template <class...> class Op, class... Args> +struct detector<Default, std::void_t<Op<Args...>>, Op, Args...> { + // Note that std::void_t is a C++17 feature + using value_t = std::true_type; + using type = Op<Args...>; +}; } // namespace detail @@ -133,8 +126,8 @@ namespace concept { * @tparam Args The arguments to the operation */ template <class To, template <class...> class Op, class... Args> - using is_detected_convertible - = std::is_convertible<detected_t<Op, Args...>, To>; + using is_detected_convertible = + std::is_convertible<detected_t<Op, Args...>, To>; /** * Helper which invokes the detector with a default type, and resolves to the @@ -209,9 +202,7 @@ namespace concept { * @tparam M The method trait, as generated by METHOD_TRAIT * @tparam Arguments The argument types that make up the signature. */ - template <typename T, - typename R, - template <class...> class M, + template <typename T, typename R, template <class...> class M, typename... Arguments> constexpr bool has_method = M<T, R, Arguments...>::template tv<T>::value; @@ -228,8 +219,8 @@ namespace concept { /** * Have a look at `TypeTraitsTest.cpp` to see most of this in action. */ -} -} +} // namespace concept +} // namespace Acts /** * These helpers allow writing checks. The missing piece is something that you @@ -348,13 +339,12 @@ namespace concept { */ #define METHOD_TRAIT(trait_name, method_name) \ template <class T, typename R, typename... Arguments> \ - struct trait_name \ - { \ + struct trait_name { \ /* Meta function to check if a type has a const qualifier*/ \ /* (by stripping it and seeing if something changed */ \ template <typename T_> \ - static constexpr bool is_const \ - = not std::is_same_v<std::remove_const_t<T_>, T_>; \ + static constexpr bool is_const = \ + not std::is_same_v<std::remove_const_t<T_>, T_>; \ \ /*These following meta-functions basically to this: they check whether or \ * not the actual function pointer extracted through `&T::method_name` can \ @@ -365,14 +355,12 @@ namespace concept { /* Meta function which constructs the right type to check a function \ * pointer, non-const version*/ \ template <typename T_, typename = int> \ - struct fptr_meta \ - { \ + struct fptr_meta { \ template <typename... Arguments_> \ - using type = typename std:: \ - integral_constant<decltype(std::declval<T_>().method_name( \ - std::declval<Arguments_>()...)) (T_::*)( \ - Arguments_...), \ - &T_::method_name>::value_type; \ + using type = typename std::integral_constant< \ + decltype(std::declval<T_>().method_name( \ + std::declval<Arguments_>()...)) (T_::*)(Arguments_...), \ + &T_::method_name>::value_type; \ }; \ \ /* Meta function which constructs the right type to check a function \ @@ -380,14 +368,12 @@ namespace concept { /* The `const` needs to be put in there in one specific spot, that's why \ * the metafunction is needed*/ \ template <typename T_> \ - struct fptr_meta<T_, std::enable_if_t<is_const<T_>, int>> \ - { \ + struct fptr_meta<T_, std::enable_if_t<is_const<T_>, int>> { \ template <typename... Arguments_> \ - using type = typename std:: \ - integral_constant<decltype(std::declval<T_>().method_name( \ - std::declval<Arguments_>()...)) (T_::*)( \ - Arguments_...) const, \ - &T_::method_name>::value_type; \ + using type = typename std::integral_constant< \ + decltype(std::declval<T_>().method_name( \ + std::declval<Arguments_>()...)) (T_::*)(Arguments_...) const, \ + &T_::method_name>::value_type; \ }; \ \ /* Helper on top of the function pointer metafunction */ \ @@ -409,20 +395,15 @@ namespace concept { * based signature check. That way, there is no hard failures, only \ * substitution failures and we're happy. */ \ template <typename T_, typename = int> \ - struct tv \ - { \ + struct tv { \ static constexpr bool value = false; \ }; \ template <typename T_> \ - struct tv<T_, \ - std::enable_if_t<is_detected_exact<R, \ - qual_ret, \ - T_, \ - Arguments...>::value, \ - int>> \ - { \ + struct tv<T_, std::enable_if_t< \ + is_detected_exact<R, qual_ret, T_, Arguments...>::value, \ + int>> { \ /* This is only ever evaluate if the method exists!*/ \ - static constexpr bool value \ - = is_detected<fptr_meta_t, T, Arguments...>::value; \ + static constexpr bool value = \ + is_detected<fptr_meta_t, T, Arguments...>::value; \ }; \ } diff --git a/Core/include/Acts/Utilities/Units.hpp b/Core/include/Acts/Utilities/Units.hpp index 8518b1fd2caa80a98a4f9484c695559c9eea42cf..ddbc1a0b8da51b14a43b286fa71aa9df68e04b26 100644 --- a/Core/include/Acts/Utilities/Units.hpp +++ b/Core/include/Acts/Utilities/Units.hpp @@ -41,253 +41,243 @@ namespace units { /// @name length units /// @{ #ifdef DOXYGEN - constexpr double _m = unspecified; +constexpr double _m = unspecified; #else - constexpr double _m = 1e3; +constexpr double _m = 1e3; #endif // DOXYGEN - constexpr double _km = 1e3 * _m; - constexpr double _cm = 1e-2 * _m; - constexpr double _mm = 1e-3 * _m; - constexpr double _um = 1e-6 * _m; - constexpr double _nm = 1e-9 * _m; - constexpr double _pm = 1e-12 * _m; - constexpr double _fm = 1e-15 * _m; - /// Higher orders - constexpr double _mm2 = _mm * _mm; +constexpr double _km = 1e3 * _m; +constexpr double _cm = 1e-2 * _m; +constexpr double _mm = 1e-3 * _m; +constexpr double _um = 1e-6 * _m; +constexpr double _nm = 1e-9 * _m; +constexpr double _pm = 1e-12 * _m; +constexpr double _fm = 1e-15 * _m; +/// Higher orders +constexpr double _mm2 = _mm * _mm; /// @} /// @name mass units /// @{ #ifdef DOXYGEN - constexpr double _kg = unspecified; +constexpr double _kg = unspecified; #else - constexpr double _kg = 1e3; +constexpr double _kg = 1e3; #endif // DOXYGEN - constexpr double _g = 1e-3 * _kg; - constexpr double _mg = 1e-6 * _kg; - /// atomic mass unit - constexpr double _u = 1.660539040e-27 * _kg; +constexpr double _g = 1e-3 * _kg; +constexpr double _mg = 1e-6 * _kg; +/// atomic mass unit +constexpr double _u = 1.660539040e-27 * _kg; /// @} /// @name time units /// @{ #ifdef DOXYGEN - constexpr double _s = unspecified; +constexpr double _s = unspecified; #else - constexpr double _s = 1; +constexpr double _s = 1; #endif // DOXYGEN - constexpr double _ms = 1e-3 * _s; - constexpr double _h = 3600 * _s; +constexpr double _ms = 1e-3 * _s; +constexpr double _h = 3600 * _s; /// @} /// @name energy units /// @{ #ifdef DOXYGEN - constexpr double _MeV = unspecified; +constexpr double _MeV = unspecified; #else - constexpr double _MeV = 1e-3; +constexpr double _MeV = 1e-3; #endif // DOXYGEN - constexpr double _GeV = 1e3 * _MeV; - constexpr double _TeV = 1e6 * _MeV; - constexpr double _keV = 1e-3 * _MeV; - constexpr double _eV = 1e-6 * _MeV; +constexpr double _GeV = 1e3 * _MeV; +constexpr double _TeV = 1e6 * _MeV; +constexpr double _keV = 1e-3 * _MeV; +constexpr double _eV = 1e-6 * _MeV; /// @} /// @name charge units /// @{ #ifdef DOXYGEN - constexpr double _C = unspecified; +constexpr double _C = unspecified; #else - constexpr double _C = 1. / 1.60217733e-19; +constexpr double _C = 1. / 1.60217733e-19; #endif // DOXYGEN - constexpr double _e = 1.60217733e-19 * _C; - /// Higher orders - constexpr double _e2 = _e * _e; - /// @} +constexpr double _e = 1.60217733e-19 * _C; +/// Higher orders +constexpr double _e2 = _e * _e; +/// @} - /// @name derived units - /// @{ - constexpr double _N = _kg * _m / (_s * _s); - constexpr double _J = _N * _m; - constexpr double _T = _kg / (_C * _s); - constexpr double _Gauss = 1e-4 * _T; - constexpr double _kGauss = 1e-1 * _T; - /// @} +/// @name derived units +/// @{ +constexpr double _N = _kg * _m / (_s * _s); +constexpr double _J = _N * _m; +constexpr double _T = _kg / (_C * _s); +constexpr double _Gauss = 1e-4 * _T; +constexpr double _kGauss = 1e-1 * _T; +/// @} - /// @name fundamental physical constants in SI units - /// @{ - /// speed of light in vacuum - constexpr double _c = 2.99792458e8 * _m / _s; - /// reduced Planck constant - constexpr double _hbar = 1.05457266e-34 * _J * _s; - /// value of elementary charge in Coulomb - constexpr double _el_charge = _e / _C; - /// Higher orders - constexpr double _c2 = _c * _c; - constexpr double _c3 = _c * _c * _c; - constexpr double _c4 = _c2 * _c2; - /// @} +/// @name fundamental physical constants in SI units +/// @{ +/// speed of light in vacuum +constexpr double _c = 2.99792458e8 * _m / _s; +/// reduced Planck constant +constexpr double _hbar = 1.05457266e-34 * _J * _s; +/// value of elementary charge in Coulomb +constexpr double _el_charge = _e / _C; +/// Higher orders +constexpr double _c2 = _c * _c; +constexpr double _c3 = _c * _c * _c; +constexpr double _c4 = _c2 * _c2; +/// @} - /// @cond - /// @brief internally used conversion constants - namespace { - // 1 GeV = 1e9 * e * 1 V = 1.60217733e-10 As * 1 V = 1.60217733e-10 J - // ==> 1 J = 1 / 1.60217733e-10 GeV - constexpr double _GeV_per_J = _GeV / (_el_charge * 1e9 * _J); - // hbar * c = 3.161529298809983e-26 J * m - // ==> hbar * c * _GeV_per_J = 1.973270523563071e-16 GeV * m - constexpr double _mm_times_GeV = _c * _hbar * _GeV_per_J; - } - /// @endcond +/// @cond +/// @brief internally used conversion constants +namespace { +// 1 GeV = 1e9 * e * 1 V = 1.60217733e-10 As * 1 V = 1.60217733e-10 J +// ==> 1 J = 1 / 1.60217733e-10 GeV +constexpr double _GeV_per_J = _GeV / (_el_charge * 1e9 * _J); +// hbar * c = 3.161529298809983e-26 J * m +// ==> hbar * c * _GeV_per_J = 1.973270523563071e-16 GeV * m +constexpr double _mm_times_GeV = _c * _hbar * _GeV_per_J; +} // namespace +/// @endcond - /// @brief physical quantities for selecting right conversion function - enum Quantity { MOMENTUM, ENERGY, LENGTH, MASS }; +/// @brief physical quantities for selecting right conversion function +enum Quantity { MOMENTUM, ENERGY, LENGTH, MASS }; - /// @cond - template <Quantity> - double - SI2Nat(const double); +/// @cond +template <Quantity> +double SI2Nat(const double); - template <Quantity> - double - Nat2SI(const double); - /// @endcond +template <Quantity> +double Nat2SI(const double); +/// @endcond - /// @brief convert energy from SI to natural units - /// - /// This function converts the given energy value from SI units to natural - /// units. Example: - /// @code - /// #include "Acts/include/Utilities/Units.hpp" - /// using namespace Acts::units; - /// - /// double E_in_TeV = SI2Nat<ENERGY>(2.3 * _J) / _TeV; - /// @endcode - /// - /// @param[in] E numeric value of energy in SI units - /// @result numeric value of energy in natural units - template <> - double - SI2Nat<ENERGY>(const double E); +/// @brief convert energy from SI to natural units +/// +/// This function converts the given energy value from SI units to natural +/// units. Example: +/// @code +/// #include "Acts/include/Utilities/Units.hpp" +/// using namespace Acts::units; +/// +/// double E_in_TeV = SI2Nat<ENERGY>(2.3 * _J) / _TeV; +/// @endcode +/// +/// @param[in] E numeric value of energy in SI units +/// @result numeric value of energy in natural units +template <> +double SI2Nat<ENERGY>(const double E); - /// @brief convert energy from natural to SI units - /// - /// This function converts the given energy value from natural units to SI - /// units. Example: - /// @code - /// #include "Acts/include/Utilities/Units.hpp" - /// using namespace Acts::units; - /// - /// double E_in_Joule = Nat2SI<ENERGY>(2.3 * _TeV) / _J; - /// @endcode - /// - /// @param[in] E numeric value of energy in natural units - /// @result numeric value of energy in SI units - template <> - double - Nat2SI<ENERGY>(const double E); +/// @brief convert energy from natural to SI units +/// +/// This function converts the given energy value from natural units to SI +/// units. Example: +/// @code +/// #include "Acts/include/Utilities/Units.hpp" +/// using namespace Acts::units; +/// +/// double E_in_Joule = Nat2SI<ENERGY>(2.3 * _TeV) / _J; +/// @endcode +/// +/// @param[in] E numeric value of energy in natural units +/// @result numeric value of energy in SI units +template <> +double Nat2SI<ENERGY>(const double E); - /// @brief convert length from SI to natural units - /// - /// This function converts the given length value from SI units to natural - /// units. Example: - /// @code - /// #include "Acts/include/Utilities/Units.hpp" - /// using namespace Acts::units; - /// - /// double l_per_MeV = SI2Nat<LENGTH>(3 * _um) * _MeV; - /// @endcode - /// - /// @param[in] l numeric value of length in SI units - /// @result numeric value of length in natural units - template <> - double - SI2Nat<LENGTH>(const double l); +/// @brief convert length from SI to natural units +/// +/// This function converts the given length value from SI units to natural +/// units. Example: +/// @code +/// #include "Acts/include/Utilities/Units.hpp" +/// using namespace Acts::units; +/// +/// double l_per_MeV = SI2Nat<LENGTH>(3 * _um) * _MeV; +/// @endcode +/// +/// @param[in] l numeric value of length in SI units +/// @result numeric value of length in natural units +template <> +double SI2Nat<LENGTH>(const double l); - /// @brief convert length from natural to SI units - /// - /// This function converts the given length value from natural units to SI - /// units. Example: - /// @code - /// #include "Acts/include/Utilities/Units.hpp" - /// using namespace Acts::units; - /// - /// double l_in_m = Nat2SI<LENGTH>(1. / (2 * _TeV)) / _m; - /// @endcode - /// - /// @param[in] l numeric value of length in natural units - /// @result numeric value of length in SI units - template <> - double - Nat2SI<LENGTH>(const double l); +/// @brief convert length from natural to SI units +/// +/// This function converts the given length value from natural units to SI +/// units. Example: +/// @code +/// #include "Acts/include/Utilities/Units.hpp" +/// using namespace Acts::units; +/// +/// double l_in_m = Nat2SI<LENGTH>(1. / (2 * _TeV)) / _m; +/// @endcode +/// +/// @param[in] l numeric value of length in natural units +/// @result numeric value of length in SI units +template <> +double Nat2SI<LENGTH>(const double l); - /// @brief convert momentum from SI to natural units - /// - /// This function converts the given momentum value from SI units to natural - /// units. Example: - /// @code - /// #include "Acts/include/Utilities/Units.hpp" - /// using namespace Acts::units; - /// - /// double p_in_GeV = SI2Nat<MOMENTUM>(2 * _N * _s) / _GeV; - /// @endcode - /// - /// @param[in] p numeric value of momentum in SI units - /// @result numeric value of momentum in natural units - template <> - double - SI2Nat<MOMENTUM>(const double p); +/// @brief convert momentum from SI to natural units +/// +/// This function converts the given momentum value from SI units to natural +/// units. Example: +/// @code +/// #include "Acts/include/Utilities/Units.hpp" +/// using namespace Acts::units; +/// +/// double p_in_GeV = SI2Nat<MOMENTUM>(2 * _N * _s) / _GeV; +/// @endcode +/// +/// @param[in] p numeric value of momentum in SI units +/// @result numeric value of momentum in natural units +template <> +double SI2Nat<MOMENTUM>(const double p); - /// @brief convert momentum from natural to SI units - /// - /// This function converts the given momentum value from natural units to SI - /// units. Example: - /// @code - /// #include "Acts/include/Utilities/Units.hpp" - /// using namespace Acts::units; - /// - /// double p_in_Ns = Nat2SI<MOMENTUM>(132 * _GeV) / (_N * _s); - /// @endcode - /// - /// @param[in] p numeric value of momentum in natural units - /// @result numeric value of momentum in SI units - template <> - double - Nat2SI<MOMENTUM>(const double p); +/// @brief convert momentum from natural to SI units +/// +/// This function converts the given momentum value from natural units to SI +/// units. Example: +/// @code +/// #include "Acts/include/Utilities/Units.hpp" +/// using namespace Acts::units; +/// +/// double p_in_Ns = Nat2SI<MOMENTUM>(132 * _GeV) / (_N * _s); +/// @endcode +/// +/// @param[in] p numeric value of momentum in natural units +/// @result numeric value of momentum in SI units +template <> +double Nat2SI<MOMENTUM>(const double p); - /// @brief convert mass from SI to natural units - /// - /// This function converts the given mass value from SI units to natural - /// units. Example: - /// @code - /// #include "Acts/include/Utilities/Units.hpp" - /// using namespace Acts::units; - /// - /// double m_in_keV = SI2Nat<MASS>(2 * _g) / _keV; - /// @endcode - /// - /// @param[in] m numeric value of mass in SI units - /// @result numeric value of mass in natural units - template <> - double - SI2Nat<MASS>(const double m); +/// @brief convert mass from SI to natural units +/// +/// This function converts the given mass value from SI units to natural +/// units. Example: +/// @code +/// #include "Acts/include/Utilities/Units.hpp" +/// using namespace Acts::units; +/// +/// double m_in_keV = SI2Nat<MASS>(2 * _g) / _keV; +/// @endcode +/// +/// @param[in] m numeric value of mass in SI units +/// @result numeric value of mass in natural units +template <> +double SI2Nat<MASS>(const double m); - /// @brief convert mass from natural to SI units - /// - /// This function converts the given mass value from natural units to SI - /// units. Example: - /// @code - /// #include "Acts/include/Utilities/Units.hpp" - /// using namespace Acts::units; - /// - /// double higgs_in_kg= Nat2SI<MASS>(125 * _GeV) / _kg; - /// @endcode - /// - /// @param[in] m numeric value of mass in natural units - /// @result numeric value of mass in SI units - template <> - double - Nat2SI<MASS>(const double m); +/// @brief convert mass from natural to SI units +/// +/// This function converts the given mass value from natural units to SI +/// units. Example: +/// @code +/// #include "Acts/include/Utilities/Units.hpp" +/// using namespace Acts::units; +/// +/// double higgs_in_kg= Nat2SI<MASS>(125 * _GeV) / _kg; +/// @endcode +/// +/// @param[in] m numeric value of mass in natural units +/// @result numeric value of mass in SI units +template <> +double Nat2SI<MASS>(const double m); } // namespace units } // namespace Acts diff --git a/Core/include/Acts/Utilities/detail/Axis.hpp b/Core/include/Acts/Utilities/detail/Axis.hpp index b312b53ce98bffbdb14de034aba1a477c9445f1a..d418d3369ba3a247e924a317db51ef9aa2ea221c 100644 --- a/Core/include/Acts/Utilities/detail/Axis.hpp +++ b/Core/include/Acts/Utilities/detail/Axis.hpp @@ -17,795 +17,661 @@ namespace Acts { namespace detail { - /// Enum which determines how the axis handle its outer boundaries - /// possible values values - /// - Open is the default behaviour: out of bounds - /// positions are filled into the over or underflow bins - /// - Bound: out-of-bounds positions resolve to first/last bin - /// respectively - /// - Closed: out-of-bounds positions resolve to the outermost - /// bin on the oppsite side - enum class AxisBoundaryType { Open, Bound, Closed }; - - /// Enum which determines the binning type of the axis - enum class AxisType { Equidistant, Variable }; - - // This object can be iterated to produce up to two sequences of integer - // indices, corresponding to the half-open integer ranges [begin1, end1[ and - // [begin2, end2[. - // - // The goal is to emulate the effect of enumerating a range of neighbor - // indices on an axis (which may go out of bounds and wrap around since we - // have AxisBoundaryType::Closed), inserting them into an std::vector, and - // discarding duplicates, without paying the price of duplicate removal - // and dynamic memory allocation in hot magnetic field interpolation code. - // - class NeighborHoodIndices - { - public: - NeighborHoodIndices() = default; - - NeighborHoodIndices(size_t begin, size_t end) - : m_begin1(begin), m_end1(end), m_begin2(end), m_end2(end) - { - } - - NeighborHoodIndices(size_t begin1, size_t end1, size_t begin2, size_t end2) - : m_begin1(begin1), m_end1(end1), m_begin2(begin2), m_end2(end2) - { - } - - class iterator - { - public: - iterator() = default; - - // Specialized constructor for end() iterator - iterator(size_t current) : m_current(current), m_wrapped(true) {} - - iterator(size_t begin1, size_t end1, size_t begin2) - : m_current(begin1) - , m_end1(end1) - , m_begin2(begin2) - , m_wrapped(begin1 == begin2) - { - } - - size_t operator*() const { return m_current; } - - iterator& operator++() - { - ++m_current; - if (m_current == m_end1) { - m_current = m_begin2; - m_wrapped = true; - } - return *this; - } - - bool - operator==(const iterator& it) const - { - return (m_current == it.m_current) && (m_wrapped == it.m_wrapped); - } - - bool - operator!=(const iterator& it) const - { - return !(*this == it); - } - - private: - size_t m_current, m_end1, m_begin2; - bool m_wrapped; - }; - - iterator - begin() const - { - return iterator(m_begin1, m_end1, m_begin2); - } - - iterator - end() const - { - return iterator(m_end2); - } - - // Number of indices that will be produced if this sequence is iterated - size_t - size() const - { - return (m_end1 - m_begin1) + (m_end2 - m_begin2); - } - - // Collect the sequence of indices into an std::vector - std::vector<size_t> - collect() const - { - std::vector<size_t> result; - result.reserve(this->size()); - for (size_t idx : *this) { - result.push_back(idx); - } - return result; - } - - private: - size_t m_begin1 = 0, m_end1 = 0, m_begin2 = 0, m_end2 = 0; - }; - - /// @brief calculate bin indices from a given binning structure - /// - /// This class provides some basic functionality for calculating bin indices - /// for a given binning configuration. Both equidistant as well as variable - /// binning structures are supported. - /// - /// Bin intervals are defined such that the lower bound is closed and the - /// uper bound is open. - /// - /// @tparam equidistant flag whether binning is equidistant (@c true) - /// or not (@c false) - template <AxisType type, AxisBoundaryType bdt = AxisBoundaryType::Open> - class Axis; - - using EquidistantAxis = Axis<AxisType::Equidistant>; - using VariableAxis = Axis<AxisType::Variable>; - - /// @brief calculate bin indices for an equidistant binning - /// - /// This class provides some basic functionality for calculating bin indices - /// for a given equidistant binning. - template <AxisBoundaryType bdt> - class Axis<AxisType::Equidistant, bdt> final : public IAxis - { - public: - /// @brief default constructor - /// - /// @param [in] xmin lower boundary of axis range - /// @param [in] xmax upper boundary of axis range - /// @param [in] nBins number of bins to divide the axis range into - /// - /// Divide the range \f$[\text{xmin},\text{xmax})\f$ into \f$\text{nBins}\f$ - /// equidistant bins. - Axis(double xmin, double xmax, size_t nBins) - : m_min(xmin), m_max(xmax), m_width((xmax - xmin) / nBins), m_bins(nBins) - { - } - - /// @brief returns whether the axis is equidistant - /// - /// @return bool is equidistant - bool - isEquidistant() const override - { - return true; - } - - /// @brief returns whether the axis is variable - /// - /// @return bool is variable - bool - isVariable() const override - { - return false; - } +/// Enum which determines how the axis handle its outer boundaries +/// possible values values +/// - Open is the default behaviour: out of bounds +/// positions are filled into the over or underflow bins +/// - Bound: out-of-bounds positions resolve to first/last bin +/// respectively +/// - Closed: out-of-bounds positions resolve to the outermost +/// bin on the oppsite side +enum class AxisBoundaryType { Open, Bound, Closed }; + +/// Enum which determines the binning type of the axis +enum class AxisType { Equidistant, Variable }; + +// This object can be iterated to produce up to two sequences of integer +// indices, corresponding to the half-open integer ranges [begin1, end1[ and +// [begin2, end2[. +// +// The goal is to emulate the effect of enumerating a range of neighbor +// indices on an axis (which may go out of bounds and wrap around since we +// have AxisBoundaryType::Closed), inserting them into an std::vector, and +// discarding duplicates, without paying the price of duplicate removal +// and dynamic memory allocation in hot magnetic field interpolation code. +// +class NeighborHoodIndices { + public: + NeighborHoodIndices() = default; - /// @brief returns the boundary type set in the template param - /// - /// @return @c AxisBoundaryType of this axis - AxisBoundaryType - getBoundaryType() const override - { - return bdt; - } + NeighborHoodIndices(size_t begin, size_t end) + : m_begin1(begin), m_end1(end), m_begin2(end), m_end2(end) {} - /// @brief Get #size bins which neighbor the one given - /// - /// Generic overload with symmetric size - /// - /// @param [in] idx requested bin index - /// @param [in] sizes how many neighboring bins (up/down) - /// @return Set of neighboring bin indices (global) - NeighborHoodIndices - neighborHoodIndices(size_t idx, size_t size = 1) const - { - return neighborHoodIndices(idx, std::make_pair(size, size)); - } + NeighborHoodIndices(size_t begin1, size_t end1, size_t begin2, size_t end2) + : m_begin1(begin1), m_end1(end1), m_begin2(begin2), m_end2(end2) {} - /// @brief Get #size bins which neighbor the one given - /// - /// This is the version for Open - /// - /// @param [in] idx requested bin index - /// @param [in] sizes how many neighboring bins (up/down) - /// @return Set of neighboring bin indices (global) - /// @note Open varies given bin and allows 0 and NBins+1 (underflow, - /// overflow) - /// as neighbors - template <AxisBoundaryType T = bdt, - std::enable_if_t<T == AxisBoundaryType::Open, int> = 0> - NeighborHoodIndices - neighborHoodIndices(size_t idx, - std::pair<size_t, size_t> sizes = {1, 1}) const - { - constexpr int min = 0; - const int max = getNBins() + 1; - const int itmin = std::max(min, int(idx - sizes.first)); - const int itmax = std::min(max, int(idx + sizes.second)); - return NeighborHoodIndices(itmin, itmax + 1); - } + class iterator { + public: + iterator() = default; - /// @brief Get #size bins which neighbor the one given - /// - /// This is the version for Bound - /// - /// @param [in] idx requested bin index - /// @param [in] sizes how many neighboring bins (up/down) - /// @return Set of neighboring bin indices (global) - /// @note Bound varies given bin and allows 1 and NBins (regular bins) - /// as neighbors - template <AxisBoundaryType T = bdt, - std::enable_if_t<T == AxisBoundaryType::Bound, int> = 0> - NeighborHoodIndices - neighborHoodIndices(size_t idx, - std::pair<size_t, size_t> sizes = {1, 1}) const - { - if (idx <= 0 || idx >= (getNBins() + 1)) { - return NeighborHoodIndices(); - } - constexpr int min = 1; - const int max = getNBins(); - const int itmin = std::max(min, int(idx - sizes.first)); - const int itmax = std::min(max, int(idx + sizes.second)); - return NeighborHoodIndices(itmin, itmax + 1); - } + // Specialized constructor for end() iterator + iterator(size_t current) : m_current(current), m_wrapped(true) {} - /// @brief Get #size bins which neighbor the one given - /// - /// This is the version for Closed - /// - /// @param [in] idx requested bin index - /// @param [in] sizes how many neighboring bins (up/down) - /// @return Set of neighboring bin indices (global) - /// @note Closed varies given bin and allows bins on the opposite - /// side of the axis as neighbors. (excludes underflow / overflow) - template <AxisBoundaryType T = bdt, - std::enable_if_t<T == AxisBoundaryType::Closed, int> = 0> - NeighborHoodIndices - neighborHoodIndices(size_t idx, - std::pair<size_t, size_t> sizes = {1, 1}) const - { - // Handle invalid indices - if (idx <= 0 || idx >= (getNBins() + 1)) { - return NeighborHoodIndices(); - } + iterator(size_t begin1, size_t end1, size_t begin2) + : m_current(begin1), + m_end1(end1), + m_begin2(begin2), + m_wrapped(begin1 == begin2) {} - // Handle corner case where user requests more neighbours than the number - // of bins on the axis. We do not want to double-count bins in that case. - sizes.first %= getNBins(); - sizes.second %= getNBins(); - if (sizes.first + sizes.second + 1 > getNBins()) { - sizes.second -= (sizes.first + sizes.second + 1) - getNBins(); - } + size_t operator*() const { return m_current; } - // If the entire index range is not covered, we must wrap the range of - // targeted neighbor indices into the range of valid bin indices. This may - // split the range of neighbor indices in two parts: - // - // Before wraparound - [ XXXXX]XXX - // After wraparound - [ XXXX XXXX ] - // - const int itmin = idx - sizes.first; - const int itmax = idx + sizes.second; - const size_t itfirst = wrapBin(itmin); - const size_t itlast = wrapBin(itmax); - if (itfirst <= itlast) { - return NeighborHoodIndices(itfirst, itlast + 1); - } else { - return NeighborHoodIndices(itfirst, getNBins() + 1, 1, itlast + 1); + iterator& operator++() { + ++m_current; + if (m_current == m_end1) { + m_current = m_begin2; + m_wrapped = true; } + return *this; } - /// @brief Converts bin index into a valid one for this axis. - /// - /// @note Open: bin index is clamped to [0, nBins+1] - /// - /// @param [in] bin The bin to wrap - /// @return valid bin index - template <AxisBoundaryType T = bdt, - std::enable_if_t<T == AxisBoundaryType::Open, int> = 0> - size_t - wrapBin(int bin) const - { - return std::max(std::min(bin, static_cast<int>(getNBins()) + 1), 0); - } - - /// @brief Converts bin index into a valid one for this axis. - /// - /// @note Bound: bin index is clamped to [1, nBins] - /// - /// @param [in] bin The bin to wrap - /// @return valid bin index - template <AxisBoundaryType T = bdt, - std::enable_if_t<T == AxisBoundaryType::Bound, int> = 0> - size_t - wrapBin(int bin) const - { - return std::max(std::min(bin, static_cast<int>(getNBins())), 1); - } - - /// @brief Converts bin index into a valid one for this axis. - /// - /// @note Closed: bin index wraps around to other side - /// - /// @param [in] bin The bin to wrap - /// @return valid bin index - template <AxisBoundaryType T = bdt, - std::enable_if_t<T == AxisBoundaryType::Closed, int> = 0> - size_t - wrapBin(int bin) const - { - const int w = getNBins(); - return 1 + (w + ((bin - 1) % w)) % w; - // return int(bin<1)*w - int(bin>w)*w + bin; - } - - /// @brief get corresponding bin index for given coordinate - /// - /// @param [in] x input coordinate - /// @return index of bin containing the given value - /// - /// @note Bin intervals are defined with closed lower bounds and open upper - /// bounds, that is \f$l <= x < u\f$ if the value @c x lies within a - /// bin with lower bound @c l and upper bound @c u. - /// @note Bin indices start at @c 1. The underflow bin has the index @c 0 - /// while the index <tt>nBins + 1</tt> indicates the overflow bin . - size_t - getBin(double x) const - { - return wrapBin(std::floor((x - getMin()) / getBinWidth()) + 1); - } - - /// @brief get bin width - /// - /// @return constant width for all bins - double getBinWidth(size_t /*bin*/ = 0) const { return m_width; } - - /// @brief get lower bound of bin - /// - /// @param [in] bin index of bin - /// @return lower bin boundary - /// - /// @pre @c bin must be a valid bin index (excluding the underflow bin), - /// i.e. \f$1 \le \text{bin} \le \text{nBins} + 1\f$ - /// - /// @note Bin intervals have a closed lower bound, i.e. the lower boundary - /// belongs to the bin with the given bin index. - double - getBinLowerBound(size_t bin) const - { - return getMin() + (bin - 1) * getBinWidth(); - } - - /// @brief get upper bound of bin - /// - /// @param [in] bin index of bin - /// @return upper bin boundary - /// - /// @pre @c bin must be a valid bin index (excluding the overflow bin), - /// i.e. \f$0 \le \text{bin} \le \text{nBins}\f$ - /// - /// @note Bin intervals have an open upper bound, i.e. the upper boundary - /// does @b not belong to the bin with the given bin index. - double - getBinUpperBound(size_t bin) const - { - return getMin() + bin * getBinWidth(); - } - - /// @brief get bin center - /// - /// @param [in] bin index of bin - /// @return bin center position - /// - /// @pre @c bin must be a valid bin index (excluding under-/overflow bins), - /// i.e. \f$1 \le \text{bin} \le \text{nBins}\f$ - double - getBinCenter(size_t bin) const - { - return getMin() + (bin - 0.5) * getBinWidth(); - } - - /// @brief get maximum of binning range - /// - /// @return maximum of binning range - double - getMax() const override - { - return m_max; - } - - /// @brief get minimum of binning range - /// - /// @return minimum of binning range - double - getMin() const override - { - return m_min; - } - - /// @brief get total number of bins - /// - /// @return total number of bins (excluding under-/overflow bins) - size_t - getNBins() const override - { - return m_bins; - } - - /// @brief check whether value is inside axis limits - /// - /// @return @c true if \f$\text{xmin} \le x < \text{xmax}\f$, otherwise - /// @c false - /// - /// @post If @c true is returned, the bin containing the given value is a - /// valid bin, i.e. it is neither the underflow nor the overflow bin. - bool - isInside(double x) const - { - return (m_min <= x) && (x < m_max); + bool operator==(const iterator& it) const { + return (m_current == it.m_current) && (m_wrapped == it.m_wrapped); } - /// @brief Return a vector of bin edges - /// @return Vector which contains the bin edges - std::vector<double> - getBinEdges() const override - { - std::vector<double> binEdges; - for (size_t i = 1; i <= m_bins; i++) { - binEdges.push_back(getBinLowerBound(i)); - } - binEdges.push_back(getBinUpperBound(m_bins)); - return binEdges; - } + bool operator!=(const iterator& it) const { return !(*this == it); } - private: - /// minimum of binning range - double m_min; - /// maximum of binning range - double m_max; - /// constant bin width - double m_width; - /// number of bins (excluding under-/overflow bins) - size_t m_bins; + private: + size_t m_current, m_end1, m_begin2; + bool m_wrapped; }; - /// @brief calculate bin indices for a variable binning - /// - /// This class provides some basic functionality for calculating bin indices - /// for a given binning with variable bin sizes. - template <AxisBoundaryType bdt> - class Axis<AxisType::Variable, bdt> final : public IAxis - { - public: - /// @brief default constructor - /// - /// @param [in] binEdges vector of bin edges - /// @pre @c binEdges must be strictly sorted in ascending order. - /// @pre @c binEdges must contain at least two entries. - /// - /// Create a binning structure with @c nBins variable-sized bins from the - /// given bin boundaries. @c nBins is given by the number of bin edges - /// reduced by one. - Axis(std::vector<double> binEdges) : m_binEdges(std::move(binEdges)) {} - - /// @brief returns whether the axis is equidistante - /// - /// @return bool is equidistant - bool - isEquidistant() const override - { - return false; - } - - /// @brief returns whether the axis is variable - /// - /// @return bool is variable - bool - isVariable() const override - { - return true; - } + iterator begin() const { return iterator(m_begin1, m_end1, m_begin2); } + + iterator end() const { return iterator(m_end2); } + + // Number of indices that will be produced if this sequence is iterated + size_t size() const { return (m_end1 - m_begin1) + (m_end2 - m_begin2); } + + // Collect the sequence of indices into an std::vector + std::vector<size_t> collect() const { + std::vector<size_t> result; + result.reserve(this->size()); + for (size_t idx : *this) { + result.push_back(idx); + } + return result; + } + + private: + size_t m_begin1 = 0, m_end1 = 0, m_begin2 = 0, m_end2 = 0; +}; + +/// @brief calculate bin indices from a given binning structure +/// +/// This class provides some basic functionality for calculating bin indices +/// for a given binning configuration. Both equidistant as well as variable +/// binning structures are supported. +/// +/// Bin intervals are defined such that the lower bound is closed and the +/// uper bound is open. +/// +/// @tparam equidistant flag whether binning is equidistant (@c true) +/// or not (@c false) +template <AxisType type, AxisBoundaryType bdt = AxisBoundaryType::Open> +class Axis; + +using EquidistantAxis = Axis<AxisType::Equidistant>; +using VariableAxis = Axis<AxisType::Variable>; + +/// @brief calculate bin indices for an equidistant binning +/// +/// This class provides some basic functionality for calculating bin indices +/// for a given equidistant binning. +template <AxisBoundaryType bdt> +class Axis<AxisType::Equidistant, bdt> final : public IAxis { + public: + /// @brief default constructor + /// + /// @param [in] xmin lower boundary of axis range + /// @param [in] xmax upper boundary of axis range + /// @param [in] nBins number of bins to divide the axis range into + /// + /// Divide the range \f$[\text{xmin},\text{xmax})\f$ into \f$\text{nBins}\f$ + /// equidistant bins. + Axis(double xmin, double xmax, size_t nBins) + : m_min(xmin), + m_max(xmax), + m_width((xmax - xmin) / nBins), + m_bins(nBins) {} + + /// @brief returns whether the axis is equidistant + /// + /// @return bool is equidistant + bool isEquidistant() const override { return true; } - /// @brief returns the boundary type set in the template param - /// - /// @return @c AxisBoundaryType of this axis - AxisBoundaryType - getBoundaryType() const override - { - return bdt; - } + /// @brief returns whether the axis is variable + /// + /// @return bool is variable + bool isVariable() const override { return false; } - /// @brief Get #size bins which neighbor the one given - /// - /// Generic overload with symmetric size - /// - /// @param [in] idx requested bin index - /// @param [in] size how many neighboring bins - /// @return Set of neighboring bin indices (global) - NeighborHoodIndices - neighborHoodIndices(size_t idx, size_t size = 1) const - { - return neighborHoodIndices(idx, std::make_pair(size, size)); - } + /// @brief returns the boundary type set in the template param + /// + /// @return @c AxisBoundaryType of this axis + AxisBoundaryType getBoundaryType() const override { return bdt; } - /// @brief Get #size bins which neighbor the one given - /// - /// This is the version for Open - /// - /// @param [in] idx requested bin index - /// @param [in] sizes how many neighboring bins (up/down) - /// @return Set of neighboring bin indices (global) - /// @note Open varies given bin and allows 0 and NBins+1 (underflow, - /// overflow) - /// as neighbors - template <AxisBoundaryType T = bdt, - std::enable_if_t<T == AxisBoundaryType::Open, int> = 0> - NeighborHoodIndices - neighborHoodIndices(size_t idx, - std::pair<size_t, size_t> sizes = {1, 1}) const - { - constexpr int min = 0; - const int max = getNBins() + 1; - const int itmin = std::max(min, int(idx - sizes.first)); - const int itmax = std::min(max, int(idx + sizes.second)); - return NeighborHoodIndices(itmin, itmax + 1); - } + /// @brief Get #size bins which neighbor the one given + /// + /// Generic overload with symmetric size + /// + /// @param [in] idx requested bin index + /// @param [in] sizes how many neighboring bins (up/down) + /// @return Set of neighboring bin indices (global) + NeighborHoodIndices neighborHoodIndices(size_t idx, size_t size = 1) const { + return neighborHoodIndices(idx, std::make_pair(size, size)); + } + + /// @brief Get #size bins which neighbor the one given + /// + /// This is the version for Open + /// + /// @param [in] idx requested bin index + /// @param [in] sizes how many neighboring bins (up/down) + /// @return Set of neighboring bin indices (global) + /// @note Open varies given bin and allows 0 and NBins+1 (underflow, + /// overflow) + /// as neighbors + template <AxisBoundaryType T = bdt, + std::enable_if_t<T == AxisBoundaryType::Open, int> = 0> + NeighborHoodIndices neighborHoodIndices(size_t idx, + std::pair<size_t, size_t> sizes = { + 1, 1}) const { + constexpr int min = 0; + const int max = getNBins() + 1; + const int itmin = std::max(min, int(idx - sizes.first)); + const int itmax = std::min(max, int(idx + sizes.second)); + return NeighborHoodIndices(itmin, itmax + 1); + } + + /// @brief Get #size bins which neighbor the one given + /// + /// This is the version for Bound + /// + /// @param [in] idx requested bin index + /// @param [in] sizes how many neighboring bins (up/down) + /// @return Set of neighboring bin indices (global) + /// @note Bound varies given bin and allows 1 and NBins (regular bins) + /// as neighbors + template <AxisBoundaryType T = bdt, + std::enable_if_t<T == AxisBoundaryType::Bound, int> = 0> + NeighborHoodIndices neighborHoodIndices(size_t idx, + std::pair<size_t, size_t> sizes = { + 1, 1}) const { + if (idx <= 0 || idx >= (getNBins() + 1)) { + return NeighborHoodIndices(); + } + constexpr int min = 1; + const int max = getNBins(); + const int itmin = std::max(min, int(idx - sizes.first)); + const int itmax = std::min(max, int(idx + sizes.second)); + return NeighborHoodIndices(itmin, itmax + 1); + } + + /// @brief Get #size bins which neighbor the one given + /// + /// This is the version for Closed + /// + /// @param [in] idx requested bin index + /// @param [in] sizes how many neighboring bins (up/down) + /// @return Set of neighboring bin indices (global) + /// @note Closed varies given bin and allows bins on the opposite + /// side of the axis as neighbors. (excludes underflow / overflow) + template <AxisBoundaryType T = bdt, + std::enable_if_t<T == AxisBoundaryType::Closed, int> = 0> + NeighborHoodIndices neighborHoodIndices(size_t idx, + std::pair<size_t, size_t> sizes = { + 1, 1}) const { + // Handle invalid indices + if (idx <= 0 || idx >= (getNBins() + 1)) { + return NeighborHoodIndices(); + } + + // Handle corner case where user requests more neighbours than the number + // of bins on the axis. We do not want to double-count bins in that case. + sizes.first %= getNBins(); + sizes.second %= getNBins(); + if (sizes.first + sizes.second + 1 > getNBins()) { + sizes.second -= (sizes.first + sizes.second + 1) - getNBins(); + } + + // If the entire index range is not covered, we must wrap the range of + // targeted neighbor indices into the range of valid bin indices. This may + // split the range of neighbor indices in two parts: + // + // Before wraparound - [ XXXXX]XXX + // After wraparound - [ XXXX XXXX ] + // + const int itmin = idx - sizes.first; + const int itmax = idx + sizes.second; + const size_t itfirst = wrapBin(itmin); + const size_t itlast = wrapBin(itmax); + if (itfirst <= itlast) { + return NeighborHoodIndices(itfirst, itlast + 1); + } else { + return NeighborHoodIndices(itfirst, getNBins() + 1, 1, itlast + 1); + } + } + + /// @brief Converts bin index into a valid one for this axis. + /// + /// @note Open: bin index is clamped to [0, nBins+1] + /// + /// @param [in] bin The bin to wrap + /// @return valid bin index + template <AxisBoundaryType T = bdt, + std::enable_if_t<T == AxisBoundaryType::Open, int> = 0> + size_t wrapBin(int bin) const { + return std::max(std::min(bin, static_cast<int>(getNBins()) + 1), 0); + } + + /// @brief Converts bin index into a valid one for this axis. + /// + /// @note Bound: bin index is clamped to [1, nBins] + /// + /// @param [in] bin The bin to wrap + /// @return valid bin index + template <AxisBoundaryType T = bdt, + std::enable_if_t<T == AxisBoundaryType::Bound, int> = 0> + size_t wrapBin(int bin) const { + return std::max(std::min(bin, static_cast<int>(getNBins())), 1); + } + + /// @brief Converts bin index into a valid one for this axis. + /// + /// @note Closed: bin index wraps around to other side + /// + /// @param [in] bin The bin to wrap + /// @return valid bin index + template <AxisBoundaryType T = bdt, + std::enable_if_t<T == AxisBoundaryType::Closed, int> = 0> + size_t wrapBin(int bin) const { + const int w = getNBins(); + return 1 + (w + ((bin - 1) % w)) % w; + // return int(bin<1)*w - int(bin>w)*w + bin; + } + + /// @brief get corresponding bin index for given coordinate + /// + /// @param [in] x input coordinate + /// @return index of bin containing the given value + /// + /// @note Bin intervals are defined with closed lower bounds and open upper + /// bounds, that is \f$l <= x < u\f$ if the value @c x lies within a + /// bin with lower bound @c l and upper bound @c u. + /// @note Bin indices start at @c 1. The underflow bin has the index @c 0 + /// while the index <tt>nBins + 1</tt> indicates the overflow bin . + size_t getBin(double x) const { + return wrapBin(std::floor((x - getMin()) / getBinWidth()) + 1); + } + + /// @brief get bin width + /// + /// @return constant width for all bins + double getBinWidth(size_t /*bin*/ = 0) const { return m_width; } - /// @brief Get #size bins which neighbor the one given - /// - /// This is the version for Bound - /// - /// @param [in] idx requested bin index - /// @param [in] sizes how many neighboring bins (up/down) - /// @return Set of neighboring bin indices (global) - /// @note Bound varies given bin and allows 1 and NBins (regular bins) - /// as neighbors - template <AxisBoundaryType T = bdt, - std::enable_if_t<T == AxisBoundaryType::Bound, int> = 0> - NeighborHoodIndices - neighborHoodIndices(size_t idx, - std::pair<size_t, size_t> sizes = {1, 1}) const - { - if (idx <= 0 || idx >= (getNBins() + 1)) { - return NeighborHoodIndices(); - } - constexpr int min = 1; - const int max = getNBins(); - const int itmin = std::max(min, int(idx - sizes.first)); - const int itmax = std::min(max, int(idx + sizes.second)); - return NeighborHoodIndices(itmin, itmax + 1); - } + /// @brief get lower bound of bin + /// + /// @param [in] bin index of bin + /// @return lower bin boundary + /// + /// @pre @c bin must be a valid bin index (excluding the underflow bin), + /// i.e. \f$1 \le \text{bin} \le \text{nBins} + 1\f$ + /// + /// @note Bin intervals have a closed lower bound, i.e. the lower boundary + /// belongs to the bin with the given bin index. + double getBinLowerBound(size_t bin) const { + return getMin() + (bin - 1) * getBinWidth(); + } - /// @brief Get #size bins which neighbor the one given - /// - /// This is the version for Closed - /// - /// @param [in] idx requested bin index - /// @param [in] sizes how many neighboring bins (up/down) - /// @return Set of neighboring bin indices (global) - /// @note Closed varies given bin and allows bins on the opposite - /// side of the axis as neighbors. (excludes underflow / overflow) - template <AxisBoundaryType T = bdt, - std::enable_if_t<T == AxisBoundaryType::Closed, int> = 0> - NeighborHoodIndices - neighborHoodIndices(size_t idx, - std::pair<size_t, size_t> sizes = {1, 1}) const - { - // Handle invalid indices - if (idx <= 0 || idx >= (getNBins() + 1)) { - return NeighborHoodIndices(); - } + /// @brief get upper bound of bin + /// + /// @param [in] bin index of bin + /// @return upper bin boundary + /// + /// @pre @c bin must be a valid bin index (excluding the overflow bin), + /// i.e. \f$0 \le \text{bin} \le \text{nBins}\f$ + /// + /// @note Bin intervals have an open upper bound, i.e. the upper boundary + /// does @b not belong to the bin with the given bin index. + double getBinUpperBound(size_t bin) const { + return getMin() + bin * getBinWidth(); + } - // Handle corner case where user requests more neighbours than the number - // of bins on the axis. We do not want to double-count bins in that case. - sizes.first %= getNBins(); - sizes.second %= getNBins(); - if (sizes.first + sizes.second + 1 > getNBins()) { - sizes.second -= (sizes.first + sizes.second + 1) - getNBins(); - } + /// @brief get bin center + /// + /// @param [in] bin index of bin + /// @return bin center position + /// + /// @pre @c bin must be a valid bin index (excluding under-/overflow bins), + /// i.e. \f$1 \le \text{bin} \le \text{nBins}\f$ + double getBinCenter(size_t bin) const { + return getMin() + (bin - 0.5) * getBinWidth(); + } - // If the entire index range is not covered, we must wrap the range of - // targeted neighbor indices into the range of valid bin indices. This may - // split the range of neighbor indices in two parts: - // - // Before wraparound - [ XXXXX]XXX - // After wraparound - [ XXXX XXXX ] - // - const int itmin = idx - sizes.first; - const int itmax = idx + sizes.second; - const size_t itfirst = wrapBin(itmin); - const size_t itlast = wrapBin(itmax); - if (itfirst <= itlast) { - return NeighborHoodIndices(itfirst, itlast + 1); - } else { - return NeighborHoodIndices(itfirst, getNBins() + 1, 1, itlast + 1); - } - } + /// @brief get maximum of binning range + /// + /// @return maximum of binning range + double getMax() const override { return m_max; } - /// @brief Converts bin index into a valid one for this axis. - /// - /// @note Open: bin index is clamped to [0, nBins+1] - /// - /// @param [in] bin The bin to wrap - /// @return valid bin index - template <AxisBoundaryType T = bdt, - std::enable_if_t<T == AxisBoundaryType::Open, int> = 0> - size_t - wrapBin(int bin) const - { - return std::max(std::min(bin, static_cast<int>(getNBins()) + 1), 0); - } + /// @brief get minimum of binning range + /// + /// @return minimum of binning range + double getMin() const override { return m_min; } - /// @brief Converts bin index into a valid one for this axis. - /// - /// @note Bound: bin index is clamped to [1, nBins] - /// - /// @param [in] bin The bin to wrap - /// @return valid bin index - template <AxisBoundaryType T = bdt, - std::enable_if_t<T == AxisBoundaryType::Bound, int> = 0> - size_t - wrapBin(int bin) const - { - return std::max(std::min(bin, static_cast<int>(getNBins())), 1); - } + /// @brief get total number of bins + /// + /// @return total number of bins (excluding under-/overflow bins) + size_t getNBins() const override { return m_bins; } - /// @brief Converts bin index into a valid one for this axis. - /// - /// @note Closed: bin index wraps around to other side - /// - /// @param [in] bin The bin to wrap - /// @return valid bin index - template <AxisBoundaryType T = bdt, - std::enable_if_t<T == AxisBoundaryType::Closed, int> = 0> - size_t - wrapBin(int bin) const - { - const int w = getNBins(); - return 1 + (w + ((bin - 1) % w)) % w; - // return int(bin<1)*w - int(bin>w)*w + bin; - } + /// @brief check whether value is inside axis limits + /// + /// @return @c true if \f$\text{xmin} \le x < \text{xmax}\f$, otherwise + /// @c false + /// + /// @post If @c true is returned, the bin containing the given value is a + /// valid bin, i.e. it is neither the underflow nor the overflow bin. + bool isInside(double x) const { return (m_min <= x) && (x < m_max); } + + /// @brief Return a vector of bin edges + /// @return Vector which contains the bin edges + std::vector<double> getBinEdges() const override { + std::vector<double> binEdges; + for (size_t i = 1; i <= m_bins; i++) { + binEdges.push_back(getBinLowerBound(i)); + } + binEdges.push_back(getBinUpperBound(m_bins)); + return binEdges; + } + + private: + /// minimum of binning range + double m_min; + /// maximum of binning range + double m_max; + /// constant bin width + double m_width; + /// number of bins (excluding under-/overflow bins) + size_t m_bins; +}; + +/// @brief calculate bin indices for a variable binning +/// +/// This class provides some basic functionality for calculating bin indices +/// for a given binning with variable bin sizes. +template <AxisBoundaryType bdt> +class Axis<AxisType::Variable, bdt> final : public IAxis { + public: + /// @brief default constructor + /// + /// @param [in] binEdges vector of bin edges + /// @pre @c binEdges must be strictly sorted in ascending order. + /// @pre @c binEdges must contain at least two entries. + /// + /// Create a binning structure with @c nBins variable-sized bins from the + /// given bin boundaries. @c nBins is given by the number of bin edges + /// reduced by one. + Axis(std::vector<double> binEdges) : m_binEdges(std::move(binEdges)) {} - /// @brief get corresponding bin index for given coordinate - /// - /// @param [in] x input coordinate - /// @return index of bin containing the given value - /// - /// @note Bin intervals are defined with closed lower bounds and open upper - /// bounds, that is \f$l <= x < u\f$ if the value @c x lies within a - /// bin with lower bound @c l and upper bound @c u. - /// @note Bin indices start at @c 1. The underflow bin has the index @c 0 - /// while the index <tt>nBins + 1</tt> indicates the overflow bin . - size_t - getBin(double x) const - { - const auto it - = std::upper_bound(std::begin(m_binEdges), std::end(m_binEdges), x); - return wrapBin(std::distance(std::begin(m_binEdges), it)); - } + /// @brief returns whether the axis is equidistante + /// + /// @return bool is equidistant + bool isEquidistant() const override { return false; } - /// @brief get bin width - /// - /// @param [in] bin index of bin - /// @return width of given bin - /// - /// @pre @c bin must be a valid bin index (excluding under-/overflow bins), - /// i.e. \f$1 \le \text{bin} \le \text{nBins}\f$ - double - getBinWidth(size_t bin) const - { - return m_binEdges.at(bin) - m_binEdges.at(bin - 1); - } + /// @brief returns whether the axis is variable + /// + /// @return bool is variable + bool isVariable() const override { return true; } - /// @brief get lower bound of bin - /// - /// @param [in] bin index of bin - /// @return lower bin boundary - /// - /// @pre @c bin must be a valid bin index (excluding the underflow bin), - /// i.e. \f$1 \le \text{bin} \le \text{nBins} + 1\f$ - /// - /// @note Bin intervals have a closed lower bound, i.e. the lower boundary - /// belongs to the bin with the given bin index. - double - getBinLowerBound(size_t bin) const - { - return m_binEdges.at(bin - 1); - } + /// @brief returns the boundary type set in the template param + /// + /// @return @c AxisBoundaryType of this axis + AxisBoundaryType getBoundaryType() const override { return bdt; } - /// @brief get upper bound of bin - /// - /// @param [in] bin index of bin - /// @return upper bin boundary - /// - /// @pre @c bin must be a valid bin index (excluding the overflow bin), - /// i.e. \f$0 \le \text{bin} \le \text{nBins}\f$ - /// - /// @note Bin intervals have an open upper bound, i.e. the upper boundary - /// does @b not belong to the bin with the given bin index. - double - getBinUpperBound(size_t bin) const - { - return m_binEdges.at(bin); - } + /// @brief Get #size bins which neighbor the one given + /// + /// Generic overload with symmetric size + /// + /// @param [in] idx requested bin index + /// @param [in] size how many neighboring bins + /// @return Set of neighboring bin indices (global) + NeighborHoodIndices neighborHoodIndices(size_t idx, size_t size = 1) const { + return neighborHoodIndices(idx, std::make_pair(size, size)); + } + + /// @brief Get #size bins which neighbor the one given + /// + /// This is the version for Open + /// + /// @param [in] idx requested bin index + /// @param [in] sizes how many neighboring bins (up/down) + /// @return Set of neighboring bin indices (global) + /// @note Open varies given bin and allows 0 and NBins+1 (underflow, + /// overflow) + /// as neighbors + template <AxisBoundaryType T = bdt, + std::enable_if_t<T == AxisBoundaryType::Open, int> = 0> + NeighborHoodIndices neighborHoodIndices(size_t idx, + std::pair<size_t, size_t> sizes = { + 1, 1}) const { + constexpr int min = 0; + const int max = getNBins() + 1; + const int itmin = std::max(min, int(idx - sizes.first)); + const int itmax = std::min(max, int(idx + sizes.second)); + return NeighborHoodIndices(itmin, itmax + 1); + } + + /// @brief Get #size bins which neighbor the one given + /// + /// This is the version for Bound + /// + /// @param [in] idx requested bin index + /// @param [in] sizes how many neighboring bins (up/down) + /// @return Set of neighboring bin indices (global) + /// @note Bound varies given bin and allows 1 and NBins (regular bins) + /// as neighbors + template <AxisBoundaryType T = bdt, + std::enable_if_t<T == AxisBoundaryType::Bound, int> = 0> + NeighborHoodIndices neighborHoodIndices(size_t idx, + std::pair<size_t, size_t> sizes = { + 1, 1}) const { + if (idx <= 0 || idx >= (getNBins() + 1)) { + return NeighborHoodIndices(); + } + constexpr int min = 1; + const int max = getNBins(); + const int itmin = std::max(min, int(idx - sizes.first)); + const int itmax = std::min(max, int(idx + sizes.second)); + return NeighborHoodIndices(itmin, itmax + 1); + } + + /// @brief Get #size bins which neighbor the one given + /// + /// This is the version for Closed + /// + /// @param [in] idx requested bin index + /// @param [in] sizes how many neighboring bins (up/down) + /// @return Set of neighboring bin indices (global) + /// @note Closed varies given bin and allows bins on the opposite + /// side of the axis as neighbors. (excludes underflow / overflow) + template <AxisBoundaryType T = bdt, + std::enable_if_t<T == AxisBoundaryType::Closed, int> = 0> + NeighborHoodIndices neighborHoodIndices(size_t idx, + std::pair<size_t, size_t> sizes = { + 1, 1}) const { + // Handle invalid indices + if (idx <= 0 || idx >= (getNBins() + 1)) { + return NeighborHoodIndices(); + } + + // Handle corner case where user requests more neighbours than the number + // of bins on the axis. We do not want to double-count bins in that case. + sizes.first %= getNBins(); + sizes.second %= getNBins(); + if (sizes.first + sizes.second + 1 > getNBins()) { + sizes.second -= (sizes.first + sizes.second + 1) - getNBins(); + } + + // If the entire index range is not covered, we must wrap the range of + // targeted neighbor indices into the range of valid bin indices. This may + // split the range of neighbor indices in two parts: + // + // Before wraparound - [ XXXXX]XXX + // After wraparound - [ XXXX XXXX ] + // + const int itmin = idx - sizes.first; + const int itmax = idx + sizes.second; + const size_t itfirst = wrapBin(itmin); + const size_t itlast = wrapBin(itmax); + if (itfirst <= itlast) { + return NeighborHoodIndices(itfirst, itlast + 1); + } else { + return NeighborHoodIndices(itfirst, getNBins() + 1, 1, itlast + 1); + } + } + + /// @brief Converts bin index into a valid one for this axis. + /// + /// @note Open: bin index is clamped to [0, nBins+1] + /// + /// @param [in] bin The bin to wrap + /// @return valid bin index + template <AxisBoundaryType T = bdt, + std::enable_if_t<T == AxisBoundaryType::Open, int> = 0> + size_t wrapBin(int bin) const { + return std::max(std::min(bin, static_cast<int>(getNBins()) + 1), 0); + } + + /// @brief Converts bin index into a valid one for this axis. + /// + /// @note Bound: bin index is clamped to [1, nBins] + /// + /// @param [in] bin The bin to wrap + /// @return valid bin index + template <AxisBoundaryType T = bdt, + std::enable_if_t<T == AxisBoundaryType::Bound, int> = 0> + size_t wrapBin(int bin) const { + return std::max(std::min(bin, static_cast<int>(getNBins())), 1); + } + + /// @brief Converts bin index into a valid one for this axis. + /// + /// @note Closed: bin index wraps around to other side + /// + /// @param [in] bin The bin to wrap + /// @return valid bin index + template <AxisBoundaryType T = bdt, + std::enable_if_t<T == AxisBoundaryType::Closed, int> = 0> + size_t wrapBin(int bin) const { + const int w = getNBins(); + return 1 + (w + ((bin - 1) % w)) % w; + // return int(bin<1)*w - int(bin>w)*w + bin; + } + + /// @brief get corresponding bin index for given coordinate + /// + /// @param [in] x input coordinate + /// @return index of bin containing the given value + /// + /// @note Bin intervals are defined with closed lower bounds and open upper + /// bounds, that is \f$l <= x < u\f$ if the value @c x lies within a + /// bin with lower bound @c l and upper bound @c u. + /// @note Bin indices start at @c 1. The underflow bin has the index @c 0 + /// while the index <tt>nBins + 1</tt> indicates the overflow bin . + size_t getBin(double x) const { + const auto it = + std::upper_bound(std::begin(m_binEdges), std::end(m_binEdges), x); + return wrapBin(std::distance(std::begin(m_binEdges), it)); + } + + /// @brief get bin width + /// + /// @param [in] bin index of bin + /// @return width of given bin + /// + /// @pre @c bin must be a valid bin index (excluding under-/overflow bins), + /// i.e. \f$1 \le \text{bin} \le \text{nBins}\f$ + double getBinWidth(size_t bin) const { + return m_binEdges.at(bin) - m_binEdges.at(bin - 1); + } - /// @brief get bin center - /// - /// @param [in] bin index of bin - /// @return bin center position - /// - /// @pre @c bin must be a valid bin index (excluding under-/overflow bins), - /// i.e. \f$1 \le \text{bin} \le \text{nBins}\f$ - double - getBinCenter(size_t bin) const - { - return 0.5 * (getBinLowerBound(bin) + getBinUpperBound(bin)); - } + /// @brief get lower bound of bin + /// + /// @param [in] bin index of bin + /// @return lower bin boundary + /// + /// @pre @c bin must be a valid bin index (excluding the underflow bin), + /// i.e. \f$1 \le \text{bin} \le \text{nBins} + 1\f$ + /// + /// @note Bin intervals have a closed lower bound, i.e. the lower boundary + /// belongs to the bin with the given bin index. + double getBinLowerBound(size_t bin) const { return m_binEdges.at(bin - 1); } - /// @brief get maximum of binning range - /// - /// @return maximum of binning range - double - getMax() const override - { - return m_binEdges.back(); - } + /// @brief get upper bound of bin + /// + /// @param [in] bin index of bin + /// @return upper bin boundary + /// + /// @pre @c bin must be a valid bin index (excluding the overflow bin), + /// i.e. \f$0 \le \text{bin} \le \text{nBins}\f$ + /// + /// @note Bin intervals have an open upper bound, i.e. the upper boundary + /// does @b not belong to the bin with the given bin index. + double getBinUpperBound(size_t bin) const { return m_binEdges.at(bin); } - /// @brief get minimum of binning range - /// - /// @return minimum of binning range - double - getMin() const override - { - return m_binEdges.front(); - } + /// @brief get bin center + /// + /// @param [in] bin index of bin + /// @return bin center position + /// + /// @pre @c bin must be a valid bin index (excluding under-/overflow bins), + /// i.e. \f$1 \le \text{bin} \le \text{nBins}\f$ + double getBinCenter(size_t bin) const { + return 0.5 * (getBinLowerBound(bin) + getBinUpperBound(bin)); + } - /// @brief get total number of bins - /// - /// @return total number of bins (excluding under-/overflow bins) - size_t - getNBins() const override - { - return m_binEdges.size() - 1; - } + /// @brief get maximum of binning range + /// + /// @return maximum of binning range + double getMax() const override { return m_binEdges.back(); } - /// @brief check whether value is inside axis limits - /// - /// @return @c true if \f$\text{xmin} \le x < \text{xmax}\f$, otherwise - /// @c false - /// - /// @post If @c true is returned, the bin containing the given value is a - /// valid bin, i.e. it is neither the underflow nor the overflow bin. - bool - isInside(double x) const - { - return (m_binEdges.front() <= x) && (x < m_binEdges.back()); - } + /// @brief get minimum of binning range + /// + /// @return minimum of binning range + double getMin() const override { return m_binEdges.front(); } - /// @brief Return a vector of bin edges - /// @return Vector which contains the bin edges - std::vector<double> - getBinEdges() const override - { - return m_binEdges; - } + /// @brief get total number of bins + /// + /// @return total number of bins (excluding under-/overflow bins) + size_t getNBins() const override { return m_binEdges.size() - 1; } - private: - /// vector of bin edges (sorted in ascending order) - std::vector<double> m_binEdges; - }; + /// @brief check whether value is inside axis limits + /// + /// @return @c true if \f$\text{xmin} \le x < \text{xmax}\f$, otherwise + /// @c false + /// + /// @post If @c true is returned, the bin containing the given value is a + /// valid bin, i.e. it is neither the underflow nor the overflow bin. + bool isInside(double x) const { + return (m_binEdges.front() <= x) && (x < m_binEdges.back()); + } + + /// @brief Return a vector of bin edges + /// @return Vector which contains the bin edges + std::vector<double> getBinEdges() const override { return m_binEdges; } + + private: + /// vector of bin edges (sorted in ascending order) + std::vector<double> m_binEdges; +}; } // namespace detail } // namespace Acts diff --git a/Core/include/Acts/Utilities/detail/DefaultParameterDefinitions.hpp b/Core/include/Acts/Utilities/detail/DefaultParameterDefinitions.hpp index df9cbb6b5f43731e910636e01f38ab6ba965f67b..302516ed35f9bf4b3f4bd45453342610783b2984 100644 --- a/Core/include/Acts/Utilities/detail/DefaultParameterDefinitions.hpp +++ b/Core/include/Acts/Utilities/detail/DefaultParameterDefinitions.hpp @@ -15,24 +15,24 @@ namespace Acts { enum ParDef : unsigned int { - eLOC_0 = 0, ///< first coordinate in local surface frame - eLOC_1 = 1, ///< second coordinate in local surface frame - eLOC_R = eLOC_0, - eLOC_PHI = eLOC_1, + eLOC_0 = 0, ///< first coordinate in local surface frame + eLOC_1 = 1, ///< second coordinate in local surface frame + eLOC_R = eLOC_0, + eLOC_PHI = eLOC_1, eLOC_RPHI = eLOC_0, - eLOC_Z = eLOC_1, - eLOC_X = eLOC_0, - eLOC_Y = eLOC_1, - eLOC_D0 = eLOC_0, - eLOC_Z0 = eLOC_1, - ePHI = 2, ///< phi direction of momentum in global frame - eTHETA = 3, ///< theta direction of momentum in global frame - eQOP = 4, ///< charge/momentum for charged tracks, for neutral tracks it is - /// 1/momentum + eLOC_Z = eLOC_1, + eLOC_X = eLOC_0, + eLOC_Y = eLOC_1, + eLOC_D0 = eLOC_0, + eLOC_Z0 = eLOC_1, + ePHI = 2, ///< phi direction of momentum in global frame + eTHETA = 3, ///< theta direction of momentum in global frame + eQOP = 4, ///< charge/momentum for charged tracks, for neutral tracks it is + /// 1/momentum NGlobalPars }; -using ParID_t = ParDef; +using ParID_t = ParDef; using ParValue_t = double; template <ParID_t> @@ -42,52 +42,31 @@ template <ParID_t par> using par_type_t = typename par_type<par>::type; template <> -struct par_type<ParDef::eLOC_0> -{ +struct par_type<ParDef::eLOC_0> { using type = local_parameter; }; template <> -struct par_type<ParDef::eLOC_1> -{ +struct par_type<ParDef::eLOC_1> { using type = local_parameter; }; template <> -struct par_type<ParDef::ePHI> -{ - static constexpr double - pMin() - { - return -M_PI; - } - static constexpr double - pMax() - { - return M_PI; - } +struct par_type<ParDef::ePHI> { + static constexpr double pMin() { return -M_PI; } + static constexpr double pMax() { return M_PI; } using type = cyclic_parameter<double, pMin, pMax>; }; template <> -struct par_type<ParDef::eTHETA> -{ - static constexpr double - pMin() - { - return 0; - } - static constexpr double - pMax() - { - return M_PI; - } +struct par_type<ParDef::eTHETA> { + static constexpr double pMin() { return 0; } + static constexpr double pMax() { return M_PI; } using type = bound_parameter<double, pMin, pMax>; }; template <> -struct par_type<ParDef::eQOP> -{ +struct par_type<ParDef::eQOP> { using type = unbound_parameter; }; } // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Utilities/detail/Extendable.hpp b/Core/include/Acts/Utilities/detail/Extendable.hpp index ad0ac6fd7b7c8ed747adf77146d99415fa67888e..6598d6ad361dcf71e8ad965371292a7cba4601ae 100644 --- a/Core/include/Acts/Utilities/detail/Extendable.hpp +++ b/Core/include/Acts/Utilities/detail/Extendable.hpp @@ -16,120 +16,100 @@ namespace Acts { namespace detail { - /// This sctruct defines an extendable std::tuple - /// - /// all Extensions have to : - /// - default constructible - /// - copy constructible - /// - move constructible - /// - /// This is needed in order to allow custom construction of objects - template <typename... extensions_t> - struct Extendable - { - // clang-format off +/// This sctruct defines an extendable std::tuple +/// +/// all Extensions have to : +/// - default constructible +/// - copy constructible +/// - move constructible +/// +/// This is needed in order to allow custom construction of objects +template <typename... extensions_t> +struct Extendable { + // clang-format off static_assert(detail::all_of_v<std::is_default_constructible<extensions_t>::value...>, "all extensions must be default constructible"); static_assert(detail::all_of_v<std::is_copy_constructible<extensions_t>::value...>, "all extensions must be copy constructible"); static_assert(detail::all_of_v<std::is_move_constructible<extensions_t>::value...>, "all extensions must be move constructible"); - // clang-format on - - /// Default constructor - Extendable() = default; - - /// Default copy constructor - Extendable(const Extendable<extensions_t...>& extendable) = default; - - // Default move constructor - Extendable(Extendable<extensions_t...>&& extendable) = default; - - /// Constructor from tuple - /// - /// @param extensions Source extensions tuple - Extendable(const std::tuple<extensions_t...>& extensions) - : m_extensions(extensions) - { - } - - /// Constructor from tuple move - /// - /// @param extensions source extensions tuple - Extendable(std::tuple<extensions_t...>&& extensions) - : m_extensions(std::move(extensions)) - { - } - - /// Default move assignment operator - /// - /// @param extendable The source Extendable list - Extendable<extensions_t...>& - operator=(const Extendable<extensions_t...>& extendable) - = default; - - /// Default move assignment operator - /// - /// @param extendable The source Extendable list - Extendable<extensions_t...>& - operator=(Extendable<extensions_t...>&& extendable) - = default; - - /// Append new entries and return a new condition - /// - /// @tparam appendices_t Types of appended entries to the tuple - /// - /// @param aps The extensions to be appended to the new Extendable - template <typename... appendices_t> - Extendable<extensions_t..., appendices_t...> - append(appendices_t... aps) const - { - auto catTuple - = std::tuple_cat(m_extensions, std::tuple<appendices_t...>(aps...)); - return Extendable<extensions_t..., appendices_t...>(std::move(catTuple)); - } - - /// Const retrieval of an extension of a specific type - /// - /// @tparam extension_t Type of the Extension to be retrieved - template <typename extension_t> - const extension_t& - get() const - { - return std::get<extension_t>(m_extensions); - } - - /// Non-const retrieval of an extension of a specific type - /// - /// @tparam extension_t Type of the Extension to be retrieved - template <typename extension_t> - extension_t& - get() - { - return std::get<extension_t>(m_extensions); - } - - /// Const retrieval of the extension tuype - /// - /// @tparam extension_t Type of the Extension to be retrieved - const std::tuple<extensions_t...>& - tuple() const - { - return m_extensions; - } - - /// Non-Const retrieval of the extendsion tuype - /// - /// @tparam extension_t Type of the Extension to be retrieved - std::tuple<extensions_t...>& - tuple() - { - return m_extensions; - } - - private: - std::tuple<extensions_t...> m_extensions; - }; + // clang-format on + + /// Default constructor + Extendable() = default; + + /// Default copy constructor + Extendable(const Extendable<extensions_t...>& extendable) = default; + + // Default move constructor + Extendable(Extendable<extensions_t...>&& extendable) = default; + + /// Constructor from tuple + /// + /// @param extensions Source extensions tuple + Extendable(const std::tuple<extensions_t...>& extensions) + : m_extensions(extensions) {} + + /// Constructor from tuple move + /// + /// @param extensions source extensions tuple + Extendable(std::tuple<extensions_t...>&& extensions) + : m_extensions(std::move(extensions)) {} + + /// Default move assignment operator + /// + /// @param extendable The source Extendable list + Extendable<extensions_t...>& operator=( + const Extendable<extensions_t...>& extendable) = default; + + /// Default move assignment operator + /// + /// @param extendable The source Extendable list + Extendable<extensions_t...>& operator=( + Extendable<extensions_t...>&& extendable) = default; + + /// Append new entries and return a new condition + /// + /// @tparam appendices_t Types of appended entries to the tuple + /// + /// @param aps The extensions to be appended to the new Extendable + template <typename... appendices_t> + Extendable<extensions_t..., appendices_t...> append( + appendices_t... aps) const { + auto catTuple = + std::tuple_cat(m_extensions, std::tuple<appendices_t...>(aps...)); + return Extendable<extensions_t..., appendices_t...>(std::move(catTuple)); + } + + /// Const retrieval of an extension of a specific type + /// + /// @tparam extension_t Type of the Extension to be retrieved + template <typename extension_t> + const extension_t& get() const { + return std::get<extension_t>(m_extensions); + } + + /// Non-const retrieval of an extension of a specific type + /// + /// @tparam extension_t Type of the Extension to be retrieved + template <typename extension_t> + extension_t& get() { + return std::get<extension_t>(m_extensions); + } + + /// Const retrieval of the extension tuype + /// + /// @tparam extension_t Type of the Extension to be retrieved + const std::tuple<extensions_t...>& tuple() const { return m_extensions; } + + /// Non-Const retrieval of the extendsion tuype + /// + /// @tparam extension_t Type of the Extension to be retrieved + std::tuple<extensions_t...>& tuple() { return m_extensions; } + + private: + std::tuple<extensions_t...> m_extensions; +}; } // namespace detail } // namespace Acts diff --git a/Core/include/Acts/Utilities/detail/Grid.hpp b/Core/include/Acts/Utilities/detail/Grid.hpp index d8eabeca9a5b2314e496ab941b072bd8cc59f6dd..bb1437a80d6d0fd1e08ecd089e66cabf53e4269a 100644 --- a/Core/include/Acts/Utilities/detail/Grid.hpp +++ b/Core/include/Acts/Utilities/detail/Grid.hpp @@ -22,444 +22,376 @@ namespace Acts { namespace detail { - /// @brief class for describing a regular multi-dimensional grid - /// - /// @tparam T type of values stored inside the bins of the grid - /// @tparam Axes parameter pack of axis types defining the grid - /// - /// Class describing a multi-dimensional, regular grid which can store objects - /// in its multi-dimensional bins. Bins are hyper-boxes and can be accessed - /// either by global bin index, local bin indices or position. - /// - /// @note @c T must be default-constructible. - template <typename T, class... Axes> - class Grid final - { - public: - /// number of dimensions of the grid - static constexpr size_t DIM = sizeof...(Axes); - - /// type of values stored - using value_type = T; - /// reference type to values stored - using reference = value_type&; - /// constant reference type to values stored - using const_reference = const value_type&; - /// type for points in d-dimensional grid space - using point_t = std::array<double, DIM>; - /// index type using local bin indices along each axis - using index_t = std::array<size_t, DIM>; - - /// @brief default constructor - /// - /// @param [in] axes actual axis objects spanning the grid - Grid(std::tuple<Axes...> axes) : m_axes(std::move(axes)) - { - m_values.resize(size()); - } - - /// @brief access value stored in bin for a given point - /// - /// @tparam Point any type with point semantics supporting component access - /// through @c operator[] - /// @param [in] point point used to look up the corresponding bin in the - /// grid - /// @return reference to value stored in bin containing the given point - /// - /// @pre The given @c Point type must represent a point in d (or higher) - /// dimensions where d is dimensionality of the grid. - /// - /// @note The look-up considers under-/overflow bins along each axis. - /// Therefore, the look-up will never fail. - // - template <class Point> - reference - atPosition(const Point& point) - { - return m_values.at(globalBinFromPosition(point)); - } - - /// @brief access value stored in bin for a given point - /// - /// @tparam Point any type with point semantics supporting component access - /// through @c operator[] - /// @param [in] point point used to look up the corresponding bin in the - /// grid - /// @return const-reference to value stored in bin containing the given - /// point - /// - /// @pre The given @c Point type must represent a point in d (or higher) - /// dimensions where d is dimensionality of the grid. - /// - /// @note The look-up considers under-/overflow bins along each axis. - /// Therefore, the look-up will never fail. - template <class Point> - const_reference - atPosition(const Point& point) const - { - return m_values.at(globalBinFromPosition(point)); - } - - /// @brief access value stored in bin with given global bin number - /// - /// @param [in] bin global bin number - /// @return reference to value stored in bin containing the given - /// point - reference - at(size_t bin) - { - return m_values.at(bin); - } - - /// @brief access value stored in bin with given global bin number - /// - /// @param [in] bin global bin number - /// @return const-reference to value stored in bin containing the given - /// point - const_reference - at(size_t bin) const - { - return m_values.at(bin); - } - - /// @brief access value stored in bin with given local bin numbers - /// - /// @param [in] localBins local bin indices along each axis - /// @return reference to value stored in bin containing the given - /// point - /// - /// @pre All local bin indices must be a valid index for the corresponding - /// axis (including the under-/overflow bin for this axis). - reference - atLocalBins(const index_t& localBins) - { - return m_values.at(globalBinFromLocalBins(localBins)); - } - - /// @brief access value stored in bin with given local bin numbers - /// - /// @param [in] localBins local bin indices along each axis - /// @return const-reference to value stored in bin containing the given - /// point - /// - /// @pre All local bin indices must be a valid index for the corresponding - /// axis (including the under-/overflow bin for this axis). - const_reference - atLocalBins(const index_t& localBins) const - { - return m_values.at(globalBinFromLocalBins(localBins)); - } - - /// @brief get global bin indices for closest points on grid - /// - /// @tparam Point any type with point semantics supporting component access - /// through @c operator[] - /// @param [in] position point of interest - /// @return Iterable thatemits the indices of bins whose lower-left corners - /// are the closest points on the grid to the input. - /// - /// @pre The given @c Point type must represent a point in d (or higher) - /// dimensions where d is dimensionality of the grid. It must lie - /// within the grid range (i.e. not within a under-/overflow bin). - template <class Point> - detail::GlobalNeighborHoodIndices<DIM> - closestPointsIndices(const Point& position) const - { - return rawClosestPointsIndices(localBinsFromPosition(position)); - } - - /// @brief dimensionality of grid - /// - /// @return number of axes spanning the grid - static constexpr size_t - dimensions() - { - return DIM; - } +/// @brief class for describing a regular multi-dimensional grid +/// +/// @tparam T type of values stored inside the bins of the grid +/// @tparam Axes parameter pack of axis types defining the grid +/// +/// Class describing a multi-dimensional, regular grid which can store objects +/// in its multi-dimensional bins. Bins are hyper-boxes and can be accessed +/// either by global bin index, local bin indices or position. +/// +/// @note @c T must be default-constructible. +template <typename T, class... Axes> +class Grid final { + public: + /// number of dimensions of the grid + static constexpr size_t DIM = sizeof...(Axes); + + /// type of values stored + using value_type = T; + /// reference type to values stored + using reference = value_type&; + /// constant reference type to values stored + using const_reference = const value_type&; + /// type for points in d-dimensional grid space + using point_t = std::array<double, DIM>; + /// index type using local bin indices along each axis + using index_t = std::array<size_t, DIM>; + + /// @brief default constructor + /// + /// @param [in] axes actual axis objects spanning the grid + Grid(std::tuple<Axes...> axes) : m_axes(std::move(axes)) { + m_values.resize(size()); + } - /// @brief get center position of bin with given local bin numbers - /// - /// @param [in] localBins local bin indices along each axis - /// @return center position of bin - /// - /// @pre All local bin indices must be a valid index for the corresponding - /// axis (excluding the under-/overflow bins for each axis). - std::array<double, DIM> - binCenter(const index_t& localBins) const - { - return grid_helper::getBinCenter(localBins, m_axes); - } + /// @brief access value stored in bin for a given point + /// + /// @tparam Point any type with point semantics supporting component access + /// through @c operator[] + /// @param [in] point point used to look up the corresponding bin in the + /// grid + /// @return reference to value stored in bin containing the given point + /// + /// @pre The given @c Point type must represent a point in d (or higher) + /// dimensions where d is dimensionality of the grid. + /// + /// @note The look-up considers under-/overflow bins along each axis. + /// Therefore, the look-up will never fail. + // + template <class Point> + reference atPosition(const Point& point) { + return m_values.at(globalBinFromPosition(point)); + } + + /// @brief access value stored in bin for a given point + /// + /// @tparam Point any type with point semantics supporting component access + /// through @c operator[] + /// @param [in] point point used to look up the corresponding bin in the + /// grid + /// @return const-reference to value stored in bin containing the given + /// point + /// + /// @pre The given @c Point type must represent a point in d (or higher) + /// dimensions where d is dimensionality of the grid. + /// + /// @note The look-up considers under-/overflow bins along each axis. + /// Therefore, the look-up will never fail. + template <class Point> + const_reference atPosition(const Point& point) const { + return m_values.at(globalBinFromPosition(point)); + } + + /// @brief access value stored in bin with given global bin number + /// + /// @param [in] bin global bin number + /// @return reference to value stored in bin containing the given + /// point + reference at(size_t bin) { return m_values.at(bin); } - /// @brief determine global index for bin containing the given point - /// - /// @tparam Point any type with point semantics supporting component access - /// through @c operator[] - /// - /// @param [in] point point to look up in the grid - /// @return global index for bin containing the given point - /// - /// @pre The given @c Point type must represent a point in d (or higher) - /// dimensions where d is dimensionality of the grid. - /// @note This could be a under-/overflow bin along one or more axes. - template <class Point> - size_t - globalBinFromPosition(const Point& point) const - { - return globalBinFromLocalBins(localBinsFromPosition(point)); - } + /// @brief access value stored in bin with given global bin number + /// + /// @param [in] bin global bin number + /// @return const-reference to value stored in bin containing the given + /// point + const_reference at(size_t bin) const { return m_values.at(bin); } - /// @brief determine global bin index from local bin indices along each axis - /// - /// @param [in] localBins local bin indices along each axis - /// @return global index for bin defined by the local bin indices - /// - /// @pre All local bin indices must be a valid index for the corresponding - /// axis (including the under-/overflow bin for this axis). - size_t - globalBinFromLocalBins(const index_t& localBins) const - { - return grid_helper::getGlobalBin(localBins, m_axes); - } + /// @brief access value stored in bin with given local bin numbers + /// + /// @param [in] localBins local bin indices along each axis + /// @return reference to value stored in bin containing the given + /// point + /// + /// @pre All local bin indices must be a valid index for the corresponding + /// axis (including the under-/overflow bin for this axis). + reference atLocalBins(const index_t& localBins) { + return m_values.at(globalBinFromLocalBins(localBins)); + } - /// @brief determine local bin index for each axis from the given point - /// - /// @tparam Point any type with point semantics supporting component access - /// through @c operator[] - /// - /// @param [in] point point to look up in the grid - /// @return array with local bin indices along each axis (in same order as - /// given @c axes object) - /// - /// @pre The given @c Point type must represent a point in d (or higher) - /// dimensions where d is dimensionality of the grid. - /// @note This could be a under-/overflow bin along one or more axes. - template <class Point> - index_t - localBinsFromPosition(const Point& point) const - { - return grid_helper::getLocalBinIndices(point, m_axes); - } + /// @brief access value stored in bin with given local bin numbers + /// + /// @param [in] localBins local bin indices along each axis + /// @return const-reference to value stored in bin containing the given + /// point + /// + /// @pre All local bin indices must be a valid index for the corresponding + /// axis (including the under-/overflow bin for this axis). + const_reference atLocalBins(const index_t& localBins) const { + return m_values.at(globalBinFromLocalBins(localBins)); + } - /// @brief determine local bin index for each axis from global bin index - /// - /// @param [in] bin global bin index - /// @return array with local bin indices along each axis (in same order as - /// given @c axes object) - /// - /// @note Local bin indices can contain under-/overflow bins along the - /// corresponding axis. - index_t - localBinsFromGlobalBin(size_t bin) const - { - return grid_helper::getLocalBinIndices(bin, m_axes); - } + /// @brief get global bin indices for closest points on grid + /// + /// @tparam Point any type with point semantics supporting component access + /// through @c operator[] + /// @param [in] position point of interest + /// @return Iterable thatemits the indices of bins whose lower-left corners + /// are the closest points on the grid to the input. + /// + /// @pre The given @c Point type must represent a point in d (or higher) + /// dimensions where d is dimensionality of the grid. It must lie + /// within the grid range (i.e. not within a under-/overflow bin). + template <class Point> + detail::GlobalNeighborHoodIndices<DIM> closestPointsIndices( + const Point& position) const { + return rawClosestPointsIndices(localBinsFromPosition(position)); + } + + /// @brief dimensionality of grid + /// + /// @return number of axes spanning the grid + static constexpr size_t dimensions() { return DIM; } - /// @brief retrieve lower-left bin edge from set of local bin indices - /// - /// @param [in] localBins local bin indices along each axis - /// @return generalized lower-left bin edge position - /// - /// @pre @c localBins must only contain valid bin indices (excluding - /// underflow bins). - point_t - lowerLeftBinEdge(const index_t& localBins) const - { - return grid_helper::getLowerLeftBinEdge(localBins, m_axes); - } + /// @brief get center position of bin with given local bin numbers + /// + /// @param [in] localBins local bin indices along each axis + /// @return center position of bin + /// + /// @pre All local bin indices must be a valid index for the corresponding + /// axis (excluding the under-/overflow bins for each axis). + std::array<double, DIM> binCenter(const index_t& localBins) const { + return grid_helper::getBinCenter(localBins, m_axes); + } - /// @brief retrieve upper-right bin edge from set of local bin indices - /// - /// @param [in] localBins local bin indices along each axis - /// @return generalized upper-right bin edge position - /// - /// @pre @c localBins must only contain valid bin indices (excluding - /// overflow bins). - point_t - upperRightBinEdge(const index_t& localBins) const - { - return grid_helper::getUpperRightBinEdge(localBins, m_axes); - } + /// @brief determine global index for bin containing the given point + /// + /// @tparam Point any type with point semantics supporting component access + /// through @c operator[] + /// + /// @param [in] point point to look up in the grid + /// @return global index for bin containing the given point + /// + /// @pre The given @c Point type must represent a point in d (or higher) + /// dimensions where d is dimensionality of the grid. + /// @note This could be a under-/overflow bin along one or more axes. + template <class Point> + size_t globalBinFromPosition(const Point& point) const { + return globalBinFromLocalBins(localBinsFromPosition(point)); + } + + /// @brief determine global bin index from local bin indices along each axis + /// + /// @param [in] localBins local bin indices along each axis + /// @return global index for bin defined by the local bin indices + /// + /// @pre All local bin indices must be a valid index for the corresponding + /// axis (including the under-/overflow bin for this axis). + size_t globalBinFromLocalBins(const index_t& localBins) const { + return grid_helper::getGlobalBin(localBins, m_axes); + } - /// @brief get number of bins along each specific axis - /// - /// @return array giving the number of bins along all axes - /// - /// @note Not including under- and overflow bins - index_t - numLocalBins() const - { - return grid_helper::getNBins(m_axes); - } + /// @brief determine local bin index for each axis from the given point + /// + /// @tparam Point any type with point semantics supporting component access + /// through @c operator[] + /// + /// @param [in] point point to look up in the grid + /// @return array with local bin indices along each axis (in same order as + /// given @c axes object) + /// + /// @pre The given @c Point type must represent a point in d (or higher) + /// dimensions where d is dimensionality of the grid. + /// @note This could be a under-/overflow bin along one or more axes. + template <class Point> + index_t localBinsFromPosition(const Point& point) const { + return grid_helper::getLocalBinIndices(point, m_axes); + } + + /// @brief determine local bin index for each axis from global bin index + /// + /// @param [in] bin global bin index + /// @return array with local bin indices along each axis (in same order as + /// given @c axes object) + /// + /// @note Local bin indices can contain under-/overflow bins along the + /// corresponding axis. + index_t localBinsFromGlobalBin(size_t bin) const { + return grid_helper::getLocalBinIndices(bin, m_axes); + } - /// @brief get the minimum value of all axes of one grid - /// - /// @return array returning the minima of all given axes - point_t - minPosition() const - { - return grid_helper::getMin(m_axes); - } + /// @brief retrieve lower-left bin edge from set of local bin indices + /// + /// @param [in] localBins local bin indices along each axis + /// @return generalized lower-left bin edge position + /// + /// @pre @c localBins must only contain valid bin indices (excluding + /// underflow bins). + point_t lowerLeftBinEdge(const index_t& localBins) const { + return grid_helper::getLowerLeftBinEdge(localBins, m_axes); + } - /// @brief get the maximum value of all axes of one grid - /// - /// @return array returning the maxima of all given axes - point_t - maxPosition() const - { - return grid_helper::getMax(m_axes); - } + /// @brief retrieve upper-right bin edge from set of local bin indices + /// + /// @param [in] localBins local bin indices along each axis + /// @return generalized upper-right bin edge position + /// + /// @pre @c localBins must only contain valid bin indices (excluding + /// overflow bins). + point_t upperRightBinEdge(const index_t& localBins) const { + return grid_helper::getUpperRightBinEdge(localBins, m_axes); + } - /// @brief set all overflow and underflow bins to a certain value - /// - /// @param [in] value value to be inserted in every overflow and underflow - /// bin of the grid. - /// - void - setExteriorBins(const value_type& value) - { - for (size_t index : grid_helper::exteriorBinIndices(m_axes)) { - at(index) = value; - } - } + /// @brief get number of bins along each specific axis + /// + /// @return array giving the number of bins along all axes + /// + /// @note Not including under- and overflow bins + index_t numLocalBins() const { return grid_helper::getNBins(m_axes); } - /// @brief interpolate grid values to given position - /// - /// @tparam Point type specifying geometric positions - /// @tparam U dummy template parameter identical to @c T - /// - /// @param [in] point location to which to interpolate grid values. The - /// position must be within the grid dimensions and not - /// lie in an under-/overflow bin along any axis. - /// - /// @return interpolated value at given position - /// - /// @pre The given @c Point type must represent a point in d (or higher) - /// dimensions where d is dimensionality of the grid. - /// - /// @note This function is available only if the following conditions are - /// fulfilled: - /// - Given @c U and @c V of value type @c T as well as two @c double @c a - /// and @c b, then the following must be a valid expression <tt>a * U + b * - /// V</tt> yielding an object which is (implicitly) convertible to @c T. - /// - @c Point must represent a d-dimensional position and support - /// coordinate access using @c operator[] which should return a @c double - /// (or a value which is implicitly convertible). Coordinate indices must - /// start at 0. - /// @note Bin values are interpreted as being the field values at the - /// lower-left corner of the corresponding hyper-box. - template <class Point, - typename U = T, - typename - = std::enable_if_t<can_interpolate<Point, - std::array<double, DIM>, - std::array<double, DIM>, - U>::value>> - T - interpolate(const Point& point) const - { - // there are 2^DIM corner points used during the interpolation - constexpr size_t nCorners = 1 << DIM; - - // construct vector of pairs of adjacent bin centers and values - std::array<value_type, nCorners> neighbors; - - // get local indices for current bin - // value of bin is interpreted as being the field value at its lower left - // corner - const auto& llIndices = localBinsFromPosition(point); - - // get global indices for all surrounding corner points - const auto& closestIndices = rawClosestPointsIndices(llIndices); - - // get values on grid points - size_t i = 0; - for (size_t index : closestIndices) { - neighbors.at(i++) = at(index); - } - - return Acts::interpolate(point, - lowerLeftBinEdge(llIndices), - upperRightBinEdge(llIndices), - neighbors); - } + /// @brief get the minimum value of all axes of one grid + /// + /// @return array returning the minima of all given axes + point_t minPosition() const { return grid_helper::getMin(m_axes); } - /// @brief check whether given point is inside grid limits - /// - /// @return @c true if \f$\text{xmin_i} \le x_i < \text{xmax}_i \forall i=0, - /// \dots, d-1\f$, otherwise @c false - /// - /// @pre The given @c Point type must represent a point in d (or higher) - /// dimensions where d is dimensionality of the grid. - /// - /// @post If @c true is returned, the global bin containing the given point - /// is a valid bin, i.e. it is neither a underflow nor an overflow bin - /// along any axis. - template <class Point> - bool - isInside(const Point& position) const - { - return grid_helper::isInside(position, m_axes); - } + /// @brief get the maximum value of all axes of one grid + /// + /// @return array returning the maxima of all given axes + point_t maxPosition() const { return grid_helper::getMax(m_axes); } - /// @brief get global bin indices for neighborhood - /// - /// @param [in] localBins center bin defined by local bin indices along each - /// axis - /// @param [in] size size of neighborhood determining how many adjacent - /// bins along each axis are considered - /// @return set of global bin indices for all bins in neighborhood - /// - /// @note Over-/underflow bins are included in the neighborhood. - /// @note The @c size parameter sets the range by how many units each local - /// bin index is allowed to be varied. All local bin indices are - /// varied independently, that is diagonal neighbors are included. - /// Ignoring the truncation of the neighborhood size reaching beyond - /// over-/underflow bins, the neighborhood is of size \f$2 \times - /// \text{size}+1\f$ along each dimension. - detail::GlobalNeighborHoodIndices<DIM> - neighborHoodIndices(const index_t& localBins, size_t size = 1u) const - { - return grid_helper::neighborHoodIndices(localBins, size, m_axes); + /// @brief set all overflow and underflow bins to a certain value + /// + /// @param [in] value value to be inserted in every overflow and underflow + /// bin of the grid. + /// + void setExteriorBins(const value_type& value) { + for (size_t index : grid_helper::exteriorBinIndices(m_axes)) { + at(index) = value; } + } - /// @brief total number of bins - /// - /// @return total number of bins in the grid - /// - /// @note This number contains under-and overflow bins along all axes. - size_t - size() const - { - index_t nBinsArray = numLocalBins(); - // add under-and overflow bins for each axis and multiply all bins - return std::accumulate( - nBinsArray.begin(), - nBinsArray.end(), - 1, - [](const size_t& a, const size_t& b) { return a * (b + 2); }); + /// @brief interpolate grid values to given position + /// + /// @tparam Point type specifying geometric positions + /// @tparam U dummy template parameter identical to @c T + /// + /// @param [in] point location to which to interpolate grid values. The + /// position must be within the grid dimensions and not + /// lie in an under-/overflow bin along any axis. + /// + /// @return interpolated value at given position + /// + /// @pre The given @c Point type must represent a point in d (or higher) + /// dimensions where d is dimensionality of the grid. + /// + /// @note This function is available only if the following conditions are + /// fulfilled: + /// - Given @c U and @c V of value type @c T as well as two @c double @c a + /// and @c b, then the following must be a valid expression <tt>a * U + b * + /// V</tt> yielding an object which is (implicitly) convertible to @c T. + /// - @c Point must represent a d-dimensional position and support + /// coordinate access using @c operator[] which should return a @c double + /// (or a value which is implicitly convertible). Coordinate indices must + /// start at 0. + /// @note Bin values are interpreted as being the field values at the + /// lower-left corner of the corresponding hyper-box. + template < + class Point, typename U = T, + typename = std::enable_if_t<can_interpolate< + Point, std::array<double, DIM>, std::array<double, DIM>, U>::value>> + T interpolate(const Point& point) const { + // there are 2^DIM corner points used during the interpolation + constexpr size_t nCorners = 1 << DIM; + + // construct vector of pairs of adjacent bin centers and values + std::array<value_type, nCorners> neighbors; + + // get local indices for current bin + // value of bin is interpreted as being the field value at its lower left + // corner + const auto& llIndices = localBinsFromPosition(point); + + // get global indices for all surrounding corner points + const auto& closestIndices = rawClosestPointsIndices(llIndices); + + // get values on grid points + size_t i = 0; + for (size_t index : closestIndices) { + neighbors.at(i++) = at(index); } - std::array<const IAxis*, DIM> - axes() const - { - return grid_helper::getAxes(m_axes); - } + return Acts::interpolate(point, lowerLeftBinEdge(llIndices), + upperRightBinEdge(llIndices), neighbors); + } - private: - /// set of axis defining the multi-dimensional grid - std::tuple<Axes...> m_axes; - /// linear value store for each bin - std::vector<T> m_values; - - // Part of closestPointsIndices that goes after local bins resolution. - // Used as an interpolation performance optimization, but not exposed as it - // doesn't make that much sense from an API design standpoint. - detail::GlobalNeighborHoodIndices<DIM> - rawClosestPointsIndices(const index_t& localBins) const - { - return grid_helper::closestPointsIndices(localBins, m_axes); - } - }; + /// @brief check whether given point is inside grid limits + /// + /// @return @c true if \f$\text{xmin_i} \le x_i < \text{xmax}_i \forall i=0, + /// \dots, d-1\f$, otherwise @c false + /// + /// @pre The given @c Point type must represent a point in d (or higher) + /// dimensions where d is dimensionality of the grid. + /// + /// @post If @c true is returned, the global bin containing the given point + /// is a valid bin, i.e. it is neither a underflow nor an overflow bin + /// along any axis. + template <class Point> + bool isInside(const Point& position) const { + return grid_helper::isInside(position, m_axes); + } + + /// @brief get global bin indices for neighborhood + /// + /// @param [in] localBins center bin defined by local bin indices along each + /// axis + /// @param [in] size size of neighborhood determining how many adjacent + /// bins along each axis are considered + /// @return set of global bin indices for all bins in neighborhood + /// + /// @note Over-/underflow bins are included in the neighborhood. + /// @note The @c size parameter sets the range by how many units each local + /// bin index is allowed to be varied. All local bin indices are + /// varied independently, that is diagonal neighbors are included. + /// Ignoring the truncation of the neighborhood size reaching beyond + /// over-/underflow bins, the neighborhood is of size \f$2 \times + /// \text{size}+1\f$ along each dimension. + detail::GlobalNeighborHoodIndices<DIM> neighborHoodIndices( + const index_t& localBins, size_t size = 1u) const { + return grid_helper::neighborHoodIndices(localBins, size, m_axes); + } + + /// @brief total number of bins + /// + /// @return total number of bins in the grid + /// + /// @note This number contains under-and overflow bins along all axes. + size_t size() const { + index_t nBinsArray = numLocalBins(); + // add under-and overflow bins for each axis and multiply all bins + return std::accumulate( + nBinsArray.begin(), nBinsArray.end(), 1, + [](const size_t& a, const size_t& b) { return a * (b + 2); }); + } + + std::array<const IAxis*, DIM> axes() const { + return grid_helper::getAxes(m_axes); + } + + private: + /// set of axis defining the multi-dimensional grid + std::tuple<Axes...> m_axes; + /// linear value store for each bin + std::vector<T> m_values; + + // Part of closestPointsIndices that goes after local bins resolution. + // Used as an interpolation performance optimization, but not exposed as it + // doesn't make that much sense from an API design standpoint. + detail::GlobalNeighborHoodIndices<DIM> rawClosestPointsIndices( + const index_t& localBins) const { + return grid_helper::closestPointsIndices(localBins, m_axes); + } +}; } // namespace detail } // namespace Acts diff --git a/Core/include/Acts/Utilities/detail/MPL/all_of.hpp b/Core/include/Acts/Utilities/detail/MPL/all_of.hpp index 7b2ee9478ff8cce2b926c3632c098fb6c5ce191f..c4037a763975e38485f288a401b717abf9ba55f1 100644 --- a/Core/include/Acts/Utilities/detail/MPL/all_of.hpp +++ b/Core/include/Acts/Utilities/detail/MPL/all_of.hpp @@ -13,8 +13,8 @@ namespace Acts { namespace detail { - namespace { - // clang-format off +namespace { +// clang-format off template <bool... values> struct all_of : std::true_type {}; @@ -23,11 +23,11 @@ namespace detail { template <bool... others> struct all_of<true, others...> : public all_of<others...> {}; - // clang-format on - } // end of anonymous namespace +// clang-format on +} // end of anonymous namespace - template <bool... values> - constexpr bool all_of_v = all_of<values...>::value; +template <bool... values> +constexpr bool all_of_v = all_of<values...>::value; } // namespace detail } // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Utilities/detail/MPL/any_of.hpp b/Core/include/Acts/Utilities/detail/MPL/any_of.hpp index 6c4ee003806e17fc3c83703806332ff3db7d5272..2a1ecbb1a206d951fff16ac87028f11a70f020f1 100644 --- a/Core/include/Acts/Utilities/detail/MPL/any_of.hpp +++ b/Core/include/Acts/Utilities/detail/MPL/any_of.hpp @@ -13,8 +13,8 @@ namespace Acts { namespace detail { - namespace { - // clang-format off +namespace { +// clang-format off template <bool... values> struct any_of : std::false_type {}; @@ -23,11 +23,11 @@ namespace detail { template <bool... others> struct any_of<false, others...> : public any_of<others...> {}; - // clang-format on - } +// clang-format on +} // namespace - template <bool... values> - constexpr bool any_of_v = any_of<values...>::value; +template <bool... values> +constexpr bool any_of_v = any_of<values...>::value; } // namespace detail } // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Utilities/detail/MPL/are_sorted.hpp b/Core/include/Acts/Utilities/detail/MPL/are_sorted.hpp index aff7689c577aa634c8920de234fd565238110fc9..a0623c251f00912270e18f5d20fafa6b5aee8947 100644 --- a/Core/include/Acts/Utilities/detail/MPL/are_sorted.hpp +++ b/Core/include/Acts/Utilities/detail/MPL/are_sorted.hpp @@ -10,61 +10,56 @@ namespace Acts { /// @cond detail namespace detail { - /** - * @brief check whether integral values are sorted - * - * @tparam ascending boolean flag to check for ascending order (@c true) or - * descending order (@c false) - * @tparam strict boolean flag whether strict ordering is required - * @tparam T integral type of values whose order should be checked - * @tparam values template parameter pack containing the list of values - * - * @test Unit tests are implemented \link - * Acts::Test::BOOST_AUTO_TEST_CASE(are_sorted_helper_tests) here\endlink. - * - * @return `are_sorted<asc,strict,T,values...>::value` is @c true if the given - * values are properly sorted, - * otherwise @c false - */ - template <bool ascending, bool strict, typename T, T... values> - struct are_sorted; +/** + * @brief check whether integral values are sorted + * + * @tparam ascending boolean flag to check for ascending order (@c true) or + * descending order (@c false) + * @tparam strict boolean flag whether strict ordering is required + * @tparam T integral type of values whose order should be checked + * @tparam values template parameter pack containing the list of values + * + * @test Unit tests are implemented \link + * Acts::Test::BOOST_AUTO_TEST_CASE(are_sorted_helper_tests) here\endlink. + * + * @return `are_sorted<asc,strict,T,values...>::value` is @c true if the given + * values are properly sorted, + * otherwise @c false + */ +template <bool ascending, bool strict, typename T, T... values> +struct are_sorted; - /// @cond - // one value is always sorted - template <bool ascending, bool strict, typename T, T v> - struct are_sorted<ascending, strict, T, v> - { - enum { value = true }; - }; +/// @cond +// one value is always sorted +template <bool ascending, bool strict, typename T, T v> +struct are_sorted<ascending, strict, T, v> { + enum { value = true }; +}; - // strict, ascending ordering - template <typename T, T a, T b, T... N> - struct are_sorted<true, true, T, a, b, N...> - { - enum { value = ((a < b) && are_sorted<true, true, T, b, N...>::value) }; - }; +// strict, ascending ordering +template <typename T, T a, T b, T... N> +struct are_sorted<true, true, T, a, b, N...> { + enum { value = ((a < b) && are_sorted<true, true, T, b, N...>::value) }; +}; - // weak, ascending ordering - template <typename T, T a, T b, T... N> - struct are_sorted<true, false, T, a, b, N...> - { - enum { value = (a <= b && are_sorted<true, false, T, b, N...>::value) }; - }; +// weak, ascending ordering +template <typename T, T a, T b, T... N> +struct are_sorted<true, false, T, a, b, N...> { + enum { value = (a <= b && are_sorted<true, false, T, b, N...>::value) }; +}; - // strict, descending ordering - template <typename T, T a, T b, T... N> - struct are_sorted<false, true, T, a, b, N...> - { - enum { value = (a > b && are_sorted<false, true, T, b, N...>::value) }; - }; +// strict, descending ordering +template <typename T, T a, T b, T... N> +struct are_sorted<false, true, T, a, b, N...> { + enum { value = (a > b && are_sorted<false, true, T, b, N...>::value) }; +}; - // weak, descending ordering - template <typename T, T a, T b, T... N> - struct are_sorted<false, false, T, a, b, N...> - { - enum { value = (a >= b && are_sorted<false, false, T, b, N...>::value) }; - }; - /// @endcond +// weak, descending ordering +template <typename T, T a, T b, T... N> +struct are_sorted<false, false, T, a, b, N...> { + enum { value = (a >= b && are_sorted<false, false, T, b, N...>::value) }; +}; +/// @endcond } // namespace detail /// @endcond } // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Utilities/detail/MPL/are_within.hpp b/Core/include/Acts/Utilities/detail/MPL/are_within.hpp index eafdc4f725b9b7387d264bd0ca439e5872d0dde6..8dcfcf428e574f4c2c7774e1c78c503dd6e718ca 100644 --- a/Core/include/Acts/Utilities/detail/MPL/are_within.hpp +++ b/Core/include/Acts/Utilities/detail/MPL/are_within.hpp @@ -10,42 +10,40 @@ namespace Acts { /// @cond detail namespace detail { - /** - * @brief check whether integral values are within a given range - * - * @tparam T integral type of values whose range should be checked - * @tparam MIN lower accepted bound of values (inclusive) - * @tparam MAX upper accepted bound of values (exclusive) - * @tparam values template parameter pack containing the list of values - * - * @test Unit tests are implemented \link - * Acts::Test::BOOST_AUTO_TEST_CASE(are_within_helper_tests) here\endlink. - * - * @return `are_within<T,MIN,MAX,values...>::value` is @c true if all given - * values are within the - * interval [MIN,MAX), otherwise @c false - */ - template <typename T, T MIN, T MAX, T... values> - struct are_within; +/** + * @brief check whether integral values are within a given range + * + * @tparam T integral type of values whose range should be checked + * @tparam MIN lower accepted bound of values (inclusive) + * @tparam MAX upper accepted bound of values (exclusive) + * @tparam values template parameter pack containing the list of values + * + * @test Unit tests are implemented \link + * Acts::Test::BOOST_AUTO_TEST_CASE(are_within_helper_tests) here\endlink. + * + * @return `are_within<T,MIN,MAX,values...>::value` is @c true if all given + * values are within the + * interval [MIN,MAX), otherwise @c false + */ +template <typename T, T MIN, T MAX, T... values> +struct are_within; - /// @cond - // check last parameter - template <typename T, T MIN, T MAX, T a> - struct are_within<T, MIN, MAX, a> - { - enum { value = (a >= MIN && a < MAX) }; - }; +/// @cond +// check last parameter +template <typename T, T MIN, T MAX, T a> +struct are_within<T, MIN, MAX, a> { + enum { value = (a >= MIN && a < MAX) }; +}; - // recursive check - template <typename T, T MIN, T MAX, T a, T... others> - struct are_within<T, MIN, MAX, a, others...> - { - enum { - value - = ((a >= MIN) && (a < MAX) && are_within<T, MIN, MAX, others...>::value) - }; +// recursive check +template <typename T, T MIN, T MAX, T a, T... others> +struct are_within<T, MIN, MAX, a, others...> { + enum { + value = + ((a >= MIN) && (a < MAX) && are_within<T, MIN, MAX, others...>::value) }; - /// @endcond +}; +/// @endcond } // namespace detail /// @endcond } // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Utilities/detail/MPL/at_index.hpp b/Core/include/Acts/Utilities/detail/MPL/at_index.hpp index 2425f086099eae2ab114681df6edd52ff5694485..0758f9c00d0088f9916d6932cb56e9b13a53c7b7 100644 --- a/Core/include/Acts/Utilities/detail/MPL/at_index.hpp +++ b/Core/include/Acts/Utilities/detail/MPL/at_index.hpp @@ -10,33 +10,31 @@ namespace Acts { /// @cond detail namespace detail { - /** - * @brief return integral constant at position in template parameter pack - * - * @tparam T integral type of the values to be investigated - * @tparam index position in the template parameter pack - * @tparam values template parameter pack containing the list of values - * - * @return `at_index<T,index,values...>::type` yields the integral constant - * at the given position in `values` if 0 ≤ `index` < - * sizeof...(values). Otherwise, a compile-time error is generated. - */ - template <typename T, size_t index, T... values> - struct at_index; +/** + * @brief return integral constant at position in template parameter pack + * + * @tparam T integral type of the values to be investigated + * @tparam index position in the template parameter pack + * @tparam values template parameter pack containing the list of values + * + * @return `at_index<T,index,values...>::type` yields the integral constant + * at the given position in `values` if 0 ≤ `index` < + * sizeof...(values). Otherwise, a compile-time error is generated. + */ +template <typename T, size_t index, T... values> +struct at_index; - /// @cond - template <typename T, size_t index, T next, T... others> - struct at_index<T, index, next, others...> - { - static constexpr T value = at_index<T, index - 1, others...>::value; - }; +/// @cond +template <typename T, size_t index, T next, T... others> +struct at_index<T, index, next, others...> { + static constexpr T value = at_index<T, index - 1, others...>::value; +}; - template <typename T, T next, T... others> - struct at_index<T, 0, next, others...> - { - static constexpr T value = next; - }; - /// @endcond +template <typename T, T next, T... others> +struct at_index<T, 0, next, others...> { + static constexpr T value = next; +}; +/// @endcond } // namespace detail /// @endcond } // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Utilities/detail/MPL/get_position.hpp b/Core/include/Acts/Utilities/detail/MPL/get_position.hpp index e56d3415e3a3b48cb58c9883637f97f36f13866d..c1b34d038cb44484a7aeafb6145efac144d4504b 100644 --- a/Core/include/Acts/Utilities/detail/MPL/get_position.hpp +++ b/Core/include/Acts/Utilities/detail/MPL/get_position.hpp @@ -10,35 +10,33 @@ namespace Acts { /// @cond detail namespace detail { - /** - * @brief get position of integral constant in template parameter pack - * - * @tparam T integral type of the values to be investigated - * @tparam target target value whose position in the template parameter pack - * should be determined - * @tparam values template parameter pack containing the list of values - * - * @return `get_position<T,target,values...>::value` yields the position of - * `target` inside `values`. - * If `target` is not in the list of `values`, a compile-time error is - * generated. - */ - template <typename T, T target, T... values> - struct get_position; +/** + * @brief get position of integral constant in template parameter pack + * + * @tparam T integral type of the values to be investigated + * @tparam target target value whose position in the template parameter pack + * should be determined + * @tparam values template parameter pack containing the list of values + * + * @return `get_position<T,target,values...>::value` yields the position of + * `target` inside `values`. + * If `target` is not in the list of `values`, a compile-time error is + * generated. + */ +template <typename T, T target, T... values> +struct get_position; - /// @cond - template <typename T, T target, T... others> - struct get_position<T, target, target, others...> - { - enum { value = 0 }; - }; +/// @cond +template <typename T, T target, T... others> +struct get_position<T, target, target, others...> { + enum { value = 0 }; +}; - template <typename T, T target, T next, T... others> - struct get_position<T, target, next, others...> - { - enum { value = get_position<T, target, others...>::value + 1 }; - }; - /// @endcond +template <typename T, T target, T next, T... others> +struct get_position<T, target, next, others...> { + enum { value = get_position<T, target, others...>::value + 1 }; +}; +/// @endcond } // namespace detail /// @endcond } // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Utilities/detail/MPL/has_duplicates.hpp b/Core/include/Acts/Utilities/detail/MPL/has_duplicates.hpp index 8877b19bc6c8d0bf5dc5bb77f17082713beb8eb3..9fc1c87bedc85574c8dcfbac09190146245a8080 100644 --- a/Core/include/Acts/Utilities/detail/MPL/has_duplicates.hpp +++ b/Core/include/Acts/Utilities/detail/MPL/has_duplicates.hpp @@ -11,42 +11,38 @@ namespace Acts { namespace detail { - namespace { - template <typename... Args> - struct has_duplicates; - - template <> - struct has_duplicates<> - { - static constexpr bool value = false; - }; - - template <typename last> - struct has_duplicates<last> - { - static constexpr bool value = false; - }; - - template <typename first, typename second, typename... others> - struct has_duplicates<first, second, others...> - { - private: - static constexpr bool _first = has_duplicates<first, others...>::value; - static constexpr bool _second = has_duplicates<second, others...>::value; - - public: - static constexpr bool value = _first or _second; - }; - - template <typename first, typename... others> - struct has_duplicates<first, first, others...> - { - static constexpr bool value = true; - }; - } - - template <typename... Args> - constexpr bool has_duplicates_v = has_duplicates<Args...>::value; +namespace { +template <typename... Args> +struct has_duplicates; + +template <> +struct has_duplicates<> { + static constexpr bool value = false; +}; + +template <typename last> +struct has_duplicates<last> { + static constexpr bool value = false; +}; + +template <typename first, typename second, typename... others> +struct has_duplicates<first, second, others...> { + private: + static constexpr bool _first = has_duplicates<first, others...>::value; + static constexpr bool _second = has_duplicates<second, others...>::value; + + public: + static constexpr bool value = _first or _second; +}; + +template <typename first, typename... others> +struct has_duplicates<first, first, others...> { + static constexpr bool value = true; +}; +} // namespace + +template <typename... Args> +constexpr bool has_duplicates_v = has_duplicates<Args...>::value; } // namespace detail } // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Utilities/detail/MPL/is_contained.hpp b/Core/include/Acts/Utilities/detail/MPL/is_contained.hpp index 38a1950bd0b39c48edf627402f0f53737f5df7df..1b760dbe90dc2bc5f55b6e39aa52a61aba5333e8 100644 --- a/Core/include/Acts/Utilities/detail/MPL/is_contained.hpp +++ b/Core/include/Acts/Utilities/detail/MPL/is_contained.hpp @@ -10,45 +10,41 @@ namespace Acts { /// @cond detail namespace detail { - /** - * @brief check whether given integral constant is contained in a template - * parameter pack - * - * @tparam T integral type of the values to be checked - * @tparam target target value to be looked for - * @tparam values template parameter pack containing the list of values - * - * @return `is_contained<T,target,values...>::value` is @c true if `target` is - * among `values`, otherwise @c false - */ - template <typename T, T target, T... values> - struct is_contained; +/** + * @brief check whether given integral constant is contained in a template + * parameter pack + * + * @tparam T integral type of the values to be checked + * @tparam target target value to be looked for + * @tparam values template parameter pack containing the list of values + * + * @return `is_contained<T,target,values...>::value` is @c true if `target` is + * among `values`, otherwise @c false + */ +template <typename T, T target, T... values> +struct is_contained; - /// @cond - template <typename T, T target, T... others> - struct is_contained<T, target, target, others...> - { - enum { value = true }; - }; +/// @cond +template <typename T, T target, T... others> +struct is_contained<T, target, target, others...> { + enum { value = true }; +}; - template <typename T, T target> - struct is_contained<T, target, target> - { - enum { value = true }; - }; +template <typename T, T target> +struct is_contained<T, target, target> { + enum { value = true }; +}; - template <typename T, T target, T next, T... others> - struct is_contained<T, target, next, others...> - { - enum { value = is_contained<T, target, others...>::value }; - }; +template <typename T, T target, T next, T... others> +struct is_contained<T, target, next, others...> { + enum { value = is_contained<T, target, others...>::value }; +}; - template <typename T, T target, T next> - struct is_contained<T, target, next> - { - enum { value = false }; - }; - /// @endcond +template <typename T, T target, T next> +struct is_contained<T, target, next> { + enum { value = false }; +}; +/// @endcond } // namespace detail /// @endcond } // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Utilities/detail/MPL/type_collector.hpp b/Core/include/Acts/Utilities/detail/MPL/type_collector.hpp index c911605e365ca37a5db2c37226fef1584c121a75..528a25fd21bb0a6be104015751cb250f617e5c3a 100644 --- a/Core/include/Acts/Utilities/detail/MPL/type_collector.hpp +++ b/Core/include/Acts/Utilities/detail/MPL/type_collector.hpp @@ -17,99 +17,95 @@ namespace Acts { namespace detail { - /** - * Struct which extracts the result type from an actor. - * This is used as an argument to `type_collector`. - */ - struct result_type_extractor - { - // Checks whether the type even has a result type - static constexpr auto predicate - = hana::is_valid([](auto t) -> hana::type<typename decltype( - t)::type::result_type>{}); - // meta function to extract the result type - template <typename T> - using extractor_impl = typename T::result_type; - // embed meta function in hana - static constexpr auto extractor = hana::template_<extractor_impl>; - }; +/** + * Struct which extracts the result type from an actor. + * This is used as an argument to `type_collector`. + */ +struct result_type_extractor { + // Checks whether the type even has a result type + static constexpr auto predicate = hana::is_valid( + [](auto t) -> hana::type<typename decltype(t)::type::result_type>{}); + // meta function to extract the result type + template <typename T> + using extractor_impl = typename T::result_type; + // embed meta function in hana + static constexpr auto extractor = hana::template_<extractor_impl>; +}; - /** - * Struct which extracts the action type from an aborter. - * This is used as an argument to `type_collector`. - */ - struct action_type_extractor - { - // Checks if aborter even has action type - static constexpr auto predicate - = hana::is_valid([](auto t) -> hana::type<typename decltype( - t)::type::action_type>{}); - // meta function to extract the action type - template <typename T> - using extractor_impl = typename T::action_type; - // converted to hana - static constexpr auto extractor = hana::template_<extractor_impl>; - }; +/** + * Struct which extracts the action type from an aborter. + * This is used as an argument to `type_collector`. + */ +struct action_type_extractor { + // Checks if aborter even has action type + static constexpr auto predicate = hana::is_valid( + [](auto t) -> hana::type<typename decltype(t)::type::action_type>{}); + // meta function to extract the action type + template <typename T> + using extractor_impl = typename T::action_type; + // converted to hana + static constexpr auto extractor = hana::template_<extractor_impl>; +}; - /** - * The main type collector. This loops over the given tuple of actions or - * aborters, - * filters by predicate and uses extracter to construct a resulting output - * set. - */ - constexpr auto type_collector = [](auto t_, auto predicate, auto extractor) { - // filtered list using predicate - constexpr auto have_result - = hana::filter(t_, [&](auto t) { return predicate(t); }); - // convert to set to remove duplicates, and transform to unpacked type - // using extractor. - constexpr auto result_types - = hana::to_set(hana::transform(have_result, extractor)); - return result_types; - }; +/** + * The main type collector. This loops over the given tuple of actions or + * aborters, + * filters by predicate and uses extracter to construct a resulting output + * set. + */ +constexpr auto type_collector = [](auto t_, auto predicate, auto extractor) { + // filtered list using predicate + constexpr auto have_result = + hana::filter(t_, [&](auto t) { return predicate(t); }); + // convert to set to remove duplicates, and transform to unpacked type + // using extractor. + constexpr auto result_types = + hana::to_set(hana::transform(have_result, extractor)); + return result_types; +}; - /** - * Helper around type_collector which constructrs a hana tuple input from - * variadic - * template args, and pre-unpacks the predicate and extractor from the helper - * type - * @tparam helper Either result_type_extractor or action_type_extractor - * @tparam items The items to filter / collect from. - */ - template <typename helper, typename... items> - constexpr auto type_collector_t = type_collector(hana::tuple_t<items...>, - helper::predicate, - helper::extractor); +/** + * Helper around type_collector which constructrs a hana tuple input from + * variadic + * template args, and pre-unpacks the predicate and extractor from the helper + * type + * @tparam helper Either result_type_extractor or action_type_extractor + * @tparam items The items to filter / collect from. + */ +template <typename helper, typename... items> +constexpr auto type_collector_t = type_collector(hana::tuple_t<items...>, + helper::predicate, + helper::extractor); - /** - * Meta function which returns a compile time bool - * @tparam T the type to check - */ - template <typename T> - constexpr bool has_result_type_v - = decltype(result_type_extractor::predicate(hana::type_c<T>))::value; +/** + * Meta function which returns a compile time bool + * @tparam T the type to check + */ +template <typename T> +constexpr bool has_result_type_v = + decltype(result_type_extractor::predicate(hana::type_c<T>))::value; - /** - * Meta function which gets the result type from an action - * @tparam T The type to extract from - */ - template <typename T> - using result_type_t = typename result_type_extractor::extractor_impl<T>; +/** + * Meta function which gets the result type from an action + * @tparam T The type to extract from + */ +template <typename T> +using result_type_t = typename result_type_extractor::extractor_impl<T>; - /** - * Meta function which returns a compile time bool - * @tparam T the type to check - */ - template <typename T> - constexpr bool has_action_type_v - = decltype(action_type_extractor::predicate(hana::type_c<T>))::value; +/** + * Meta function which returns a compile time bool + * @tparam T the type to check + */ +template <typename T> +constexpr bool has_action_type_v = + decltype(action_type_extractor::predicate(hana::type_c<T>))::value; - /** - * Meta function which gets the action for an aborter - * @tparam T The type to extract from - */ - template <typename T> - using action_type_t = typename action_type_extractor::extractor_impl<T>; +/** + * Meta function which gets the action for an aborter + * @tparam T The type to extract from + */ +template <typename T> +using action_type_t = typename action_type_extractor::extractor_impl<T>; } // namespace detail } // namespace Acts diff --git a/Core/include/Acts/Utilities/detail/RealQuadraticEquation.hpp b/Core/include/Acts/Utilities/detail/RealQuadraticEquation.hpp index 68dad994f459ddd5ac3c7ff5c978199b809a1b7a..82b3a9dcfb11a718148c3ac57cb7cbae2e22175c 100644 --- a/Core/include/Acts/Utilities/detail/RealQuadraticEquation.hpp +++ b/Core/include/Acts/Utilities/detail/RealQuadraticEquation.hpp @@ -17,59 +17,57 @@ namespace Acts { namespace detail { - /// @struct RealQuadradicEquation - /// Mathematic struct for solving real quadratic equations - /// - /// <b>Mathematical motivation</b>:<br> - /// The equation is given by:<br> - /// @f$ \alpha x^{2} + \beta x + \gamma = 0 @f$ - /// and has therefore the analytical solution:<br> - /// @f$ x_{1, 2} = - \frac{\beta \pm - /// \sqrt{\beta^{2}-4\alpha\gamma}}{2\alpha}@f$ - /// <br> - /// <br> - /// - case @f$ \beta > 0 @f$:<br> - /// @f$ x_{1} = - \frac{\beta + \sqrt{\beta^{2}-4\alpha\gamma}}{2\alpha} := - /// \frac{q}{\alpha}@f$, <br> - /// so that @f$ q= -\frac{1}{2}(\beta+sqrt{\beta^{2}-4\alpha\gamma})@f$. - /// @f$ x_{2} @f$ can now be written as: @f$ x_{2} = \frac{\gamma}{q} = - /// -\frac{2\gamma}{\beta+sqrt{\beta^{2}-4\alpha\gamma}}@f$, since: <br> - /// @f$ -\frac{2\gamma}{\beta+sqrt{\beta^{2}-4\alpha\gamma}} = - /// -\frac{2\gamma}{\beta}\frac{1}{1+\sqrt{1-4\alpha\gamma/\beta^{2}}}@f$, and - /// <br> - /// @f$ x_{2}\frac{1}{1-\sqrt{1-4\alpha\gamma/\beta^{2}}} = - /// -\frac{2\gamma}{\beta}\frac{1}{1-1+4\alpha\gamma/\beta^{2}}=-\frac{\beta}{2\alpha}.@f$<br> - /// Hence,@f$ -\frac{\beta(1-\sqrt{1-4\alpha\gamma/\beta^{2}}}{2\alpha} = - - /// \frac{\beta - \sqrt{\beta^{2}-4\alpha\gamma}}{2\alpha} @f$.<br> - /// - case @f$ \beta > 0 @f$ is similar. - /// +/// @struct RealQuadradicEquation +/// Mathematic struct for solving real quadratic equations +/// +/// <b>Mathematical motivation</b>:<br> +/// The equation is given by:<br> +/// @f$ \alpha x^{2} + \beta x + \gamma = 0 @f$ +/// and has therefore the analytical solution:<br> +/// @f$ x_{1, 2} = - \frac{\beta \pm +/// \sqrt{\beta^{2}-4\alpha\gamma}}{2\alpha}@f$ +/// <br> +/// <br> +/// - case @f$ \beta > 0 @f$:<br> +/// @f$ x_{1} = - \frac{\beta + \sqrt{\beta^{2}-4\alpha\gamma}}{2\alpha} := +/// \frac{q}{\alpha}@f$, <br> +/// so that @f$ q= -\frac{1}{2}(\beta+sqrt{\beta^{2}-4\alpha\gamma})@f$. +/// @f$ x_{2} @f$ can now be written as: @f$ x_{2} = \frac{\gamma}{q} = +/// -\frac{2\gamma}{\beta+sqrt{\beta^{2}-4\alpha\gamma}}@f$, since: <br> +/// @f$ -\frac{2\gamma}{\beta+sqrt{\beta^{2}-4\alpha\gamma}} = +/// -\frac{2\gamma}{\beta}\frac{1}{1+\sqrt{1-4\alpha\gamma/\beta^{2}}}@f$, and +/// <br> +/// @f$ x_{2}\frac{1}{1-\sqrt{1-4\alpha\gamma/\beta^{2}}} = +/// -\frac{2\gamma}{\beta}\frac{1}{1-1+4\alpha\gamma/\beta^{2}}=-\frac{\beta}{2\alpha}.@f$<br> +/// Hence,@f$ -\frac{\beta(1-\sqrt{1-4\alpha\gamma/\beta^{2}}}{2\alpha} = - +/// \frac{\beta - \sqrt{\beta^{2}-4\alpha\gamma}}{2\alpha} @f$.<br> +/// - case @f$ \beta > 0 @f$ is similar. +/// - struct RealQuadraticEquation - { - double first; - double second; - int solutions; +struct RealQuadraticEquation { + double first; + double second; + int solutions; - /// Constructor - /// - /// @param alpha is the first parameter of the quad equation - /// @param beta is the second parameter of the quad equation - /// @param gamma is the third parameter of the quad equation - RealQuadraticEquation(double alpha, double beta, double gamma) - : first(0.), second(0.) - { - double discriminant = beta * beta - 4 * alpha * gamma; - if (discriminant < 0) { - solutions = 0; - } else { - solutions = (discriminant == 0) ? 1 : 2; - double q = -0.5 * (beta + (beta > 0 ? std::sqrt(discriminant) - : -std::sqrt(discriminant))); - first = q / alpha; - second = gamma / q; - } + /// Constructor + /// + /// @param alpha is the first parameter of the quad equation + /// @param beta is the second parameter of the quad equation + /// @param gamma is the third parameter of the quad equation + RealQuadraticEquation(double alpha, double beta, double gamma) + : first(0.), second(0.) { + double discriminant = beta * beta - 4 * alpha * gamma; + if (discriminant < 0) { + solutions = 0; + } else { + solutions = (discriminant == 0) ? 1 : 2; + double q = -0.5 * (beta + (beta > 0 ? std::sqrt(discriminant) + : -std::sqrt(discriminant))); + first = q / alpha; + second = gamma / q; } - }; + } +}; } // namespace detail } // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Utilities/detail/grid_helper.hpp b/Core/include/Acts/Utilities/detail/grid_helper.hpp index d1910f592844f34dfc8d927e1168f275aae10e9d..5cdba9215d58a79ff17c8ebfe67894c21dfb5517 100644 --- a/Core/include/Acts/Utilities/detail/grid_helper.hpp +++ b/Core/include/Acts/Utilities/detail/grid_helper.hpp @@ -17,867 +17,754 @@ namespace Acts { namespace detail { - // This object can be iterated to produce the (ordered) set of global indices - // associated with a neighborhood around a certain point on a grid. - // - // The goal is to emulate the effect of enumerating the global indices into - // an std::set (or into an std::vector that gets subsequently sorted), without - // paying the price of dynamic memory allocation in hot magnetic field - // interpolation code. - // - template <size_t DIM> - class GlobalNeighborHoodIndices - { - public: - // You can get the local neighbor indices from - // grid_helper_impl<DIM>::neighborHoodIndices and the number of bins in - // each direction from grid_helper_impl<DIM>::getNBins. - GlobalNeighborHoodIndices( - std::array<NeighborHoodIndices, DIM>& neighborIndices, - const std::array<size_t, DIM>& nBinsArray) - : m_localIndices(neighborIndices) - { - if (DIM == 1) return; - size_t globalStride = 1; - for (long i = DIM - 2; i >= 0; --i) { - globalStride *= (nBinsArray[i + 1] + 2); - m_globalStrides[i] = globalStride; - } - } - - class iterator - { - public: - iterator() = default; - - iterator( - const GlobalNeighborHoodIndices& parent, - std::array<NeighborHoodIndices::iterator, DIM>&& localIndicesIter) - : m_localIndicesIter(std::move(localIndicesIter)), m_parent(&parent) - { - } - - size_t operator*() const - { - size_t globalIndex = *m_localIndicesIter[DIM - 1]; - if (DIM == 1) return globalIndex; - for (size_t i = 0; i < DIM - 1; ++i) { - globalIndex - += m_parent->m_globalStrides[i] * (*m_localIndicesIter[i]); - } +// This object can be iterated to produce the (ordered) set of global indices +// associated with a neighborhood around a certain point on a grid. +// +// The goal is to emulate the effect of enumerating the global indices into +// an std::set (or into an std::vector that gets subsequently sorted), without +// paying the price of dynamic memory allocation in hot magnetic field +// interpolation code. +// +template <size_t DIM> +class GlobalNeighborHoodIndices { + public: + // You can get the local neighbor indices from + // grid_helper_impl<DIM>::neighborHoodIndices and the number of bins in + // each direction from grid_helper_impl<DIM>::getNBins. + GlobalNeighborHoodIndices( + std::array<NeighborHoodIndices, DIM>& neighborIndices, + const std::array<size_t, DIM>& nBinsArray) + : m_localIndices(neighborIndices) { + if (DIM == 1) + return; + size_t globalStride = 1; + for (long i = DIM - 2; i >= 0; --i) { + globalStride *= (nBinsArray[i + 1] + 2); + m_globalStrides[i] = globalStride; + } + } + + class iterator { + public: + iterator() = default; + + iterator(const GlobalNeighborHoodIndices& parent, + std::array<NeighborHoodIndices::iterator, DIM>&& localIndicesIter) + : m_localIndicesIter(std::move(localIndicesIter)), m_parent(&parent) {} + + size_t operator*() const { + size_t globalIndex = *m_localIndicesIter[DIM - 1]; + if (DIM == 1) return globalIndex; + for (size_t i = 0; i < DIM - 1; ++i) { + globalIndex += m_parent->m_globalStrides[i] * (*m_localIndicesIter[i]); } - - iterator& operator++() - { - const auto& localIndices = m_parent->m_localIndices; - - // Go to the next global index via a lexicographic increment: - // - Start by incrementing the last local index - // - If it reaches the end, reset it and increment the previous one... - for (long i = DIM - 1; i > 0; --i) { - ++m_localIndicesIter[i]; - if (m_localIndicesIter[i] != localIndices[i].end()) return *this; - m_localIndicesIter[i] = localIndices[i].begin(); - } - - // The first index should stay at the end value when it reaches it, so - // that we know when we've reached the end of iteration. - ++m_localIndicesIter[0]; - return *this; - } - - bool - operator==(const iterator& it) - { - // We know when we've reached the end, so we don't need an end-iterator. - // Sadly, in C++, there has to be one. Therefore, we special-case it - // heavily so that it's super-efficient to create and compare to. - if (it.m_parent == nullptr) { - return m_localIndicesIter[0] == m_parent->m_localIndices[0].end(); - } else { - return m_localIndicesIter == it.m_localIndicesIter; - } - } - - bool - operator!=(const iterator& it) - { - return !(*this == it); - } - - private: - std::array<NeighborHoodIndices::iterator, DIM> m_localIndicesIter; - const GlobalNeighborHoodIndices* m_parent = nullptr; - }; - - iterator - begin() const - { - std::array<NeighborHoodIndices::iterator, DIM> localIndicesIter; - for (size_t i = 0; i < DIM; ++i) { - localIndicesIter[i] = m_localIndices[i].begin(); - } - return iterator(*this, std::move(localIndicesIter)); + return globalIndex; } - iterator - end() const - { - return iterator(); - } + iterator& operator++() { + const auto& localIndices = m_parent->m_localIndices; - // Number of indices that will be produced if this sequence is iterated - size_t - size() const - { - size_t result = m_localIndices[0].size(); - for (size_t i = 1; i < DIM; ++i) { - result *= m_localIndices[i].size(); + // Go to the next global index via a lexicographic increment: + // - Start by incrementing the last local index + // - If it reaches the end, reset it and increment the previous one... + for (long i = DIM - 1; i > 0; --i) { + ++m_localIndicesIter[i]; + if (m_localIndicesIter[i] != localIndices[i].end()) + return *this; + m_localIndicesIter[i] = localIndices[i].begin(); } - return result; - } - - // Collect the sequence of indices into an std::vector - std::vector<size_t> - collect() const - { - std::vector<size_t> result; - result.reserve(this->size()); - for (size_t idx : *this) { - result.push_back(idx); - } - return result; - } - - private: - std::array<NeighborHoodIndices, DIM> m_localIndices; - std::array<size_t, DIM - 1> m_globalStrides; - }; - - /// @cond - /// @brief helper struct to calculate number of bins inside a grid - /// - /// @tparam N number of axes to consider - template <size_t N> - struct grid_helper_impl; - - template <size_t N> - struct grid_helper_impl - { - template <class... Axes> - static void - getBinCenter(std::array<double, sizeof...(Axes)>& center, - const std::array<size_t, sizeof...(Axes)>& localIndices, - const std::tuple<Axes...>& axes) - { - center.at(N) = std::get<N>(axes).getBinCenter(localIndices.at(N)); - grid_helper_impl<N - 1>::getBinCenter(center, localIndices, axes); - } - template <class... Axes> - static void - getGlobalBin(const std::array<size_t, sizeof...(Axes)>& localBins, - const std::tuple<Axes...>& axes, - size_t& bin, - size_t& area) - { - const auto& thisAxis = std::get<N>(axes); - bin += area * localBins.at(N); - // make sure to account for under-/overflow bins - area *= (thisAxis.getNBins() + 2); - grid_helper_impl<N - 1>::getGlobalBin(localBins, axes, bin, area); + // The first index should stay at the end value when it reaches it, so + // that we know when we've reached the end of iteration. + ++m_localIndicesIter[0]; + return *this; } - template <class Point, class... Axes> - static void - getLocalBinIndices(const Point& point, - const std::tuple<Axes...>& axes, - std::array<size_t, sizeof...(Axes)>& indices) - { - const auto& thisAxis = std::get<N>(axes); - indices.at(N) = thisAxis.getBin(point[N]); - grid_helper_impl<N - 1>::getLocalBinIndices(point, axes, indices); - } - - template <class... Axes> - static void - getLocalBinIndices(size_t& bin, - const std::tuple<Axes...>& axes, - size_t& area, - std::array<size_t, sizeof...(Axes)>& indices) - { - const auto& thisAxis = std::get<N>(axes); - // make sure to account for under-/overflow bins - size_t new_area = area * (thisAxis.getNBins() + 2); - grid_helper_impl<N - 1>::getLocalBinIndices(bin, axes, new_area, indices); - indices.at(N) = bin / area; - bin %= area; - } - - template <class... Axes> - static void - getLowerLeftBinEdge(std::array<double, sizeof...(Axes)>& llEdge, - const std::array<size_t, sizeof...(Axes)>& localIndices, - const std::tuple<Axes...>& axes) - { - llEdge.at(N) = std::get<N>(axes).getBinLowerBound(localIndices.at(N)); - grid_helper_impl<N - 1>::getLowerLeftBinEdge(llEdge, localIndices, axes); - } - - template <class... Axes> - static void - getLowerLeftBinIndices(std::array<size_t, sizeof...(Axes)>& localIndices, - const std::tuple<Axes...>& axes) - { - localIndices.at(N) = std::get<N>(axes).wrapBin(localIndices.at(N) - 1); - grid_helper_impl<N - 1>::getLowerLeftBinIndices(localIndices, axes); - } - - template <class... Axes> - static void - getNBins(const std::tuple<Axes...>& axes, - std::array<size_t, sizeof...(Axes)>& nBinsArray) - { - // by convention getNBins does not include under-/overflow bins - nBinsArray[N] = std::get<N>(axes).getNBins(); - grid_helper_impl<N - 1>::getNBins(axes, nBinsArray); - } - - template <class... Axes> - static void - getAxes(const std::tuple<Axes...>& axes, - std::array<const IAxis*, sizeof...(Axes)>& axesArr) - { - axesArr[N] = static_cast<const IAxis*>(&std::get<N>(axes)); - grid_helper_impl<N - 1>::getAxes(axes, axesArr); - } - - template <class... Axes> - static void - getUpperRightBinEdge( - std::array<double, sizeof...(Axes)>& urEdge, - const std::array<size_t, sizeof...(Axes)>& localIndices, - const std::tuple<Axes...>& axes) - { - urEdge.at(N) = std::get<N>(axes).getBinUpperBound(localIndices.at(N)); - grid_helper_impl<N - 1>::getUpperRightBinEdge(urEdge, localIndices, axes); - } - - template <class... Axes> - static void - getUpperRightBinIndices(std::array<size_t, sizeof...(Axes)>& localIndices, - const std::tuple<Axes...>& axes) - { - localIndices.at(N) = std::get<N>(axes).wrapBin(localIndices.at(N) + 1); - grid_helper_impl<N - 1>::getUpperRightBinIndices(localIndices, axes); - } - - template <class... Axes> - static void - getMin(const std::tuple<Axes...>& axes, - std::array<double, sizeof...(Axes)>& minArray) - { - minArray[N] = std::get<N>(axes).getMin(); - grid_helper_impl<N - 1>::getMin(axes, minArray); - } - - template <class... Axes> - static void - getMax(const std::tuple<Axes...>& axes, - std::array<double, sizeof...(Axes)>& maxArray) - { - maxArray[N] = std::get<N>(axes).getMax(); - grid_helper_impl<N - 1>::getMax(axes, maxArray); - } - - template <class Point, class... Axes> - static bool - isInside(const Point& position, const std::tuple<Axes...>& axes) - { - bool insideThisAxis = std::get<N>(axes).isInside(position[N]); - return insideThisAxis - && grid_helper_impl<N - 1>::isInside(position, axes); - } - - template <class... Axes> - static void - neighborHoodIndices( - const std::array<size_t, sizeof...(Axes)>& localIndices, - std::pair<size_t, size_t> sizes, - const std::tuple<Axes...>& axes, - std::array<NeighborHoodIndices, sizeof...(Axes)>& neighborIndices) - { - - // ask n-th axis - size_t locIdx = localIndices.at(N); - NeighborHoodIndices locNeighbors - = std::get<N>(axes).neighborHoodIndices(locIdx, sizes); - neighborIndices.at(N) = locNeighbors; - - grid_helper_impl<N - 1>::neighborHoodIndices( - localIndices, sizes, axes, neighborIndices); - } - - template <class... Axes> - static void - exteriorBinIndices(std::array<size_t, sizeof...(Axes)>& idx, - std::array<bool, sizeof...(Axes)> isExterior, - std::set<size_t>& combinations, - const std::tuple<Axes...>& axes) - { - // iterate over this axis' bins, remembering which bins are exterior - for (size_t i = 0; i < std::get<N>(axes).getNBins() + 2; ++i) { - idx.at(N) = i; - isExterior.at(N) = (i == 0) || (i == std::get<N>(axes).getNBins() + 1); - // vary other axes recursively - grid_helper_impl<N - 1>::exteriorBinIndices( - idx, isExterior, combinations, axes); + bool operator==(const iterator& it) { + // We know when we've reached the end, so we don't need an end-iterator. + // Sadly, in C++, there has to be one. Therefore, we special-case it + // heavily so that it's super-efficient to create and compare to. + if (it.m_parent == nullptr) { + return m_localIndicesIter[0] == m_parent->m_localIndices[0].end(); + } else { + return m_localIndicesIter == it.m_localIndicesIter; } } - }; - - template <> - struct grid_helper_impl<0u> - { - - template <class... Axes> - static void - getBinCenter(std::array<double, sizeof...(Axes)>& center, - const std::array<size_t, sizeof...(Axes)>& localIndices, - const std::tuple<Axes...>& axes) - { - center.at(0u) = std::get<0u>(axes).getBinCenter(localIndices.at(0u)); - } - template <class... Axes> - static void - getGlobalBin(const std::array<size_t, sizeof...(Axes)>& localBins, - const std::tuple<Axes...>& /*axes*/, - size_t& bin, - size_t& area) - { - bin += area * localBins.at(0u); - } - - template <class Point, class... Axes> - static void - getLocalBinIndices(const Point& point, - const std::tuple<Axes...>& axes, - std::array<size_t, sizeof...(Axes)>& indices) - { - const auto& thisAxis = std::get<0u>(axes); - indices.at(0u) = thisAxis.getBin(point[0u]); - } - - template <class... Axes> - static void - getLocalBinIndices(size_t& bin, - const std::tuple<Axes...>& /*axes*/, - size_t& area, - std::array<size_t, sizeof...(Axes)>& indices) - { - // make sure to account for under-/overflow bins - indices.at(0u) = bin / area; - bin %= area; - } - - template <class... Axes> - static void - getLowerLeftBinEdge(std::array<double, sizeof...(Axes)>& llEdge, - const std::array<size_t, sizeof...(Axes)>& localIndices, - const std::tuple<Axes...>& axes) - { - llEdge.at(0u) = std::get<0u>(axes).getBinLowerBound(localIndices.at(0u)); - } - - template <class... Axes> - static void - getLowerLeftBinIndices(std::array<size_t, sizeof...(Axes)>& localIndices, - const std::tuple<Axes...>& axes) - { - localIndices.at(0u) = std::get<0u>(axes).wrapBin(localIndices.at(0u) - 1); - } - - template <class... Axes> - static void - getNBins(const std::tuple<Axes...>& axes, - std::array<size_t, sizeof...(Axes)>& nBinsArray) - { - // by convention getNBins does not include under-/overflow bins - nBinsArray[0u] = std::get<0u>(axes).getNBins(); - } - - template <class... Axes> - static void - getAxes(const std::tuple<Axes...>& axes, - std::array<const IAxis*, sizeof...(Axes)>& axesArr) - { - axesArr[0u] = static_cast<const IAxis*>(&std::get<0u>(axes)); - } - - template <class... Axes> - static void - getUpperRightBinEdge( - std::array<double, sizeof...(Axes)>& urEdge, - const std::array<size_t, sizeof...(Axes)>& localIndices, - const std::tuple<Axes...>& axes) - { - urEdge.at(0u) = std::get<0u>(axes).getBinUpperBound(localIndices.at(0u)); - } - - template <class... Axes> - static void - getUpperRightBinIndices(std::array<size_t, sizeof...(Axes)>& localIndices, - const std::tuple<Axes...>& axes) - { - localIndices.at(0u) = std::get<0u>(axes).wrapBin(localIndices.at(0u) + 1); - } + bool operator!=(const iterator& it) { return !(*this == it); } - template <class... Axes> - static void - getMin(const std::tuple<Axes...>& axes, - std::array<double, sizeof...(Axes)>& minArray) - { - minArray[0u] = std::get<0u>(axes).getMin(); - } - - template <class... Axes> - static void - getMax(const std::tuple<Axes...>& axes, - std::array<double, sizeof...(Axes)>& maxArray) - { - maxArray[0u] = std::get<0u>(axes).getMax(); - } - - template <class Point, class... Axes> - static bool - isInside(const Point& position, const std::tuple<Axes...>& axes) - { - return std::get<0u>(axes).isInside(position[0u]); - } - - template <class... Axes> - static void - neighborHoodIndices( - const std::array<size_t, sizeof...(Axes)>& localIndices, - std::pair<size_t, size_t> sizes, - const std::tuple<Axes...>& axes, - std::array<NeighborHoodIndices, sizeof...(Axes)>& neighborIndices) - { - - // ask 0-th axis - size_t locIdx = localIndices.at(0u); - NeighborHoodIndices locNeighbors - = std::get<0u>(axes).neighborHoodIndices(locIdx, sizes); - neighborIndices.at(0u) = locNeighbors; - } - - template <class... Axes> - static void - exteriorBinIndices(std::array<size_t, sizeof...(Axes)>& idx, - std::array<bool, sizeof...(Axes)> isExterior, - std::set<size_t>& combinations, - const std::tuple<Axes...>& axes) - { - // For each exterior bin on this axis, we will do this - auto recordExteriorBin = [&](size_t i) { - idx.at(0u) = i; - // at this point, combinations are complete: save the global bin - size_t bin = 0, area = 1; - grid_helper_impl<sizeof...(Axes) - 1>::getGlobalBin( - idx, axes, bin, area); - combinations.insert(bin); - }; - - // The first and last bins on this axis are exterior by definition - for (size_t i : - {static_cast<size_t>(0), std::get<0u>(axes).getNBins() + 1}) { - recordExteriorBin(i); - } - - // If no other axis is on an exterior index, stop here - bool otherAxisExterior = false; - for (size_t N = 1; N < sizeof...(Axes); ++N) { - otherAxisExterior = otherAxisExterior | isExterior[N]; - } - if (!otherAxisExterior) { - return; - } - - // Otherwise, we're on a grid border: iterate over all the other indices - for (size_t i = 1; i <= std::get<0u>(axes).getNBins(); ++i) { - recordExteriorBin(i); - } - } + private: + std::array<NeighborHoodIndices::iterator, DIM> m_localIndicesIter; + const GlobalNeighborHoodIndices* m_parent = nullptr; }; - /// @endcond - - /// @brief helper functions for grid-related operations - struct grid_helper - { - /// @brief get the global indices for closest points on grid - /// - /// @tparam Axes parameter pack of axis types defining the grid - /// @param [in] bin global bin index for bin of interest - /// @param [in] axes actual axis objects spanning the grid - /// @return Sorted collection of global bin indices for bins whose - /// lower-left corners are the closest points on the grid to every - /// point in the given bin - /// - /// @note @c bin must be a valid bin index (excluding under-/overflow bins - /// along any axis). - template <class... Axes> - static GlobalNeighborHoodIndices<sizeof...(Axes)> - closestPointsIndices( - const std::array<size_t, sizeof...(Axes)>& localIndices, - const std::tuple<Axes...>& axes) - { - // get neighboring bins, but only increment. - return neighborHoodIndices(localIndices, std::make_pair(0, 1), axes); - } - - /// @brief retrieve bin center from set of local bin indices - /// - /// @tparam Axes parameter pack of axis types defining the grid - /// @param [in] localIndices local bin indices along each axis - /// @param [in] axes actual axis objects spanning the grid - /// @return center position of bin - /// - /// @pre @c localIndices must only contain valid bin indices (i.e. excluding - /// under-/overflow bins). - template <class... Axes> - static std::array<double, sizeof...(Axes)> - getBinCenter(const std::array<size_t, sizeof...(Axes)>& localIndices, - const std::tuple<Axes...>& axes) - { - std::array<double, sizeof...(Axes)> center; - constexpr size_t MAX = sizeof...(Axes) - 1; - grid_helper_impl<MAX>::getBinCenter(center, localIndices, axes); - - return center; - } - /// @brief determine global bin index from local indices along each axis - /// - /// @tparam Axes parameter pack of axis types defining the grid - /// - /// @param [in] localBins local bin indices along each axis - /// @param [in] axes actual axis objects spanning the grid - /// @return global index for bin defined by the local bin indices - /// - /// @pre All local bin indices must be a valid index for the corresponding - /// axis (including the under-/overflow bin for this axis). - template <class... Axes> - static size_t - getGlobalBin(const std::array<size_t, sizeof...(Axes)>& localBins, - const std::tuple<Axes...>& axes) - { - constexpr size_t MAX = sizeof...(Axes) - 1; - size_t area = 1; - size_t bin = 0; - - grid_helper_impl<MAX>::getGlobalBin(localBins, axes, bin, area); - - return bin; - } - - /// @brief determine local bin index for each axis from point - /// - /// @tparam Point any type with point semantics supporting component access - /// through @c operator[] - /// @tparam Axes parameter pack of axis types defining the grid - /// - /// @param [in] point point to look up in the grid - /// @param [in] axes actual axis objects spanning the grid - /// @return array with local bin indices along each axis (in same order as - /// given @c axes object) - /// - /// @pre The given @c Point type must represent a point in d (or higher) - /// dimensions where d is the number of axis objects in the tuple. - /// @note This could be a under-/overflow bin along one or more axes. - template <class Point, class... Axes> - static std::array<size_t, sizeof...(Axes)> - getLocalBinIndices(const Point& point, const std::tuple<Axes...>& axes) - { - constexpr size_t MAX = sizeof...(Axes) - 1; - std::array<size_t, sizeof...(Axes)> indices; - - grid_helper_impl<MAX>::getLocalBinIndices(point, axes, indices); - - return indices; - } - - /// @brief determine local bin index for each axis from global bin index - /// - /// @tparam Axes parameter pack of axis types defining the grid - /// - /// @param [in] bin global bin index - /// @param [in] axes actual axis objects spanning the grid - /// @return array with local bin indices along each axis (in same order as - /// given @c axes object) - /// - /// @note Local bin indices can contain under-/overflow bins along any axis. - template <class... Axes> - static std::array<size_t, sizeof...(Axes)> - getLocalBinIndices(size_t bin, const std::tuple<Axes...>& axes) - { - constexpr size_t MAX = sizeof...(Axes) - 1; - size_t area = 1; - std::array<size_t, sizeof...(Axes)> indices; - - grid_helper_impl<MAX>::getLocalBinIndices(bin, axes, area, indices); - - return indices; - } - - /// @brief retrieve lower-left bin edge from set of local bin indices - /// - /// @tparam Axes parameter pack of axis types defining the grid - /// @param [in] localIndices local bin indices along each axis - /// @param [in] axes actual axis objects spanning the grid - /// @return generalized lower-left bin edge - /// - /// @pre @c localIndices must only contain valid bin indices (excluding - /// underflow bins). - template <class... Axes> - static std::array<double, sizeof...(Axes)> - getLowerLeftBinEdge(const std::array<size_t, sizeof...(Axes)>& localIndices, - const std::tuple<Axes...>& axes) - { - std::array<double, sizeof...(Axes)> llEdge; - constexpr size_t MAX = sizeof...(Axes) - 1; - grid_helper_impl<MAX>::getLowerLeftBinEdge(llEdge, localIndices, axes); - - return llEdge; - } + iterator begin() const { + std::array<NeighborHoodIndices::iterator, DIM> localIndicesIter; + for (size_t i = 0; i < DIM; ++i) { + localIndicesIter[i] = m_localIndices[i].begin(); + } + return iterator(*this, std::move(localIndicesIter)); + } + + iterator end() const { return iterator(); } + + // Number of indices that will be produced if this sequence is iterated + size_t size() const { + size_t result = m_localIndices[0].size(); + for (size_t i = 1; i < DIM; ++i) { + result *= m_localIndices[i].size(); + } + return result; + } + + // Collect the sequence of indices into an std::vector + std::vector<size_t> collect() const { + std::vector<size_t> result; + result.reserve(this->size()); + for (size_t idx : *this) { + result.push_back(idx); + } + return result; + } + + private: + std::array<NeighborHoodIndices, DIM> m_localIndices; + std::array<size_t, DIM - 1> m_globalStrides; +}; + +/// @cond +/// @brief helper struct to calculate number of bins inside a grid +/// +/// @tparam N number of axes to consider +template <size_t N> +struct grid_helper_impl; + +template <size_t N> +struct grid_helper_impl { + template <class... Axes> + static void getBinCenter( + std::array<double, sizeof...(Axes)>& center, + const std::array<size_t, sizeof...(Axes)>& localIndices, + const std::tuple<Axes...>& axes) { + center.at(N) = std::get<N>(axes).getBinCenter(localIndices.at(N)); + grid_helper_impl<N - 1>::getBinCenter(center, localIndices, axes); + } + + template <class... Axes> + static void getGlobalBin(const std::array<size_t, sizeof...(Axes)>& localBins, + const std::tuple<Axes...>& axes, size_t& bin, + size_t& area) { + const auto& thisAxis = std::get<N>(axes); + bin += area * localBins.at(N); + // make sure to account for under-/overflow bins + area *= (thisAxis.getNBins() + 2); + grid_helper_impl<N - 1>::getGlobalBin(localBins, axes, bin, area); + } + + template <class Point, class... Axes> + static void getLocalBinIndices(const Point& point, + const std::tuple<Axes...>& axes, + std::array<size_t, sizeof...(Axes)>& indices) { + const auto& thisAxis = std::get<N>(axes); + indices.at(N) = thisAxis.getBin(point[N]); + grid_helper_impl<N - 1>::getLocalBinIndices(point, axes, indices); + } + + template <class... Axes> + static void getLocalBinIndices(size_t& bin, const std::tuple<Axes...>& axes, + size_t& area, + std::array<size_t, sizeof...(Axes)>& indices) { + const auto& thisAxis = std::get<N>(axes); + // make sure to account for under-/overflow bins + size_t new_area = area * (thisAxis.getNBins() + 2); + grid_helper_impl<N - 1>::getLocalBinIndices(bin, axes, new_area, indices); + indices.at(N) = bin / area; + bin %= area; + } + + template <class... Axes> + static void getLowerLeftBinEdge( + std::array<double, sizeof...(Axes)>& llEdge, + const std::array<size_t, sizeof...(Axes)>& localIndices, + const std::tuple<Axes...>& axes) { + llEdge.at(N) = std::get<N>(axes).getBinLowerBound(localIndices.at(N)); + grid_helper_impl<N - 1>::getLowerLeftBinEdge(llEdge, localIndices, axes); + } + + template <class... Axes> + static void getLowerLeftBinIndices( + std::array<size_t, sizeof...(Axes)>& localIndices, + const std::tuple<Axes...>& axes) { + localIndices.at(N) = std::get<N>(axes).wrapBin(localIndices.at(N) - 1); + grid_helper_impl<N - 1>::getLowerLeftBinIndices(localIndices, axes); + } + + template <class... Axes> + static void getNBins(const std::tuple<Axes...>& axes, + std::array<size_t, sizeof...(Axes)>& nBinsArray) { + // by convention getNBins does not include under-/overflow bins + nBinsArray[N] = std::get<N>(axes).getNBins(); + grid_helper_impl<N - 1>::getNBins(axes, nBinsArray); + } + + template <class... Axes> + static void getAxes(const std::tuple<Axes...>& axes, + std::array<const IAxis*, sizeof...(Axes)>& axesArr) { + axesArr[N] = static_cast<const IAxis*>(&std::get<N>(axes)); + grid_helper_impl<N - 1>::getAxes(axes, axesArr); + } + + template <class... Axes> + static void getUpperRightBinEdge( + std::array<double, sizeof...(Axes)>& urEdge, + const std::array<size_t, sizeof...(Axes)>& localIndices, + const std::tuple<Axes...>& axes) { + urEdge.at(N) = std::get<N>(axes).getBinUpperBound(localIndices.at(N)); + grid_helper_impl<N - 1>::getUpperRightBinEdge(urEdge, localIndices, axes); + } + + template <class... Axes> + static void getUpperRightBinIndices( + std::array<size_t, sizeof...(Axes)>& localIndices, + const std::tuple<Axes...>& axes) { + localIndices.at(N) = std::get<N>(axes).wrapBin(localIndices.at(N) + 1); + grid_helper_impl<N - 1>::getUpperRightBinIndices(localIndices, axes); + } + + template <class... Axes> + static void getMin(const std::tuple<Axes...>& axes, + std::array<double, sizeof...(Axes)>& minArray) { + minArray[N] = std::get<N>(axes).getMin(); + grid_helper_impl<N - 1>::getMin(axes, minArray); + } + + template <class... Axes> + static void getMax(const std::tuple<Axes...>& axes, + std::array<double, sizeof...(Axes)>& maxArray) { + maxArray[N] = std::get<N>(axes).getMax(); + grid_helper_impl<N - 1>::getMax(axes, maxArray); + } + + template <class Point, class... Axes> + static bool isInside(const Point& position, const std::tuple<Axes...>& axes) { + bool insideThisAxis = std::get<N>(axes).isInside(position[N]); + return insideThisAxis && grid_helper_impl<N - 1>::isInside(position, axes); + } + + template <class... Axes> + static void neighborHoodIndices( + const std::array<size_t, sizeof...(Axes)>& localIndices, + std::pair<size_t, size_t> sizes, const std::tuple<Axes...>& axes, + std::array<NeighborHoodIndices, sizeof...(Axes)>& neighborIndices) { + // ask n-th axis + size_t locIdx = localIndices.at(N); + NeighborHoodIndices locNeighbors = + std::get<N>(axes).neighborHoodIndices(locIdx, sizes); + neighborIndices.at(N) = locNeighbors; + + grid_helper_impl<N - 1>::neighborHoodIndices(localIndices, sizes, axes, + neighborIndices); + } + + template <class... Axes> + static void exteriorBinIndices(std::array<size_t, sizeof...(Axes)>& idx, + std::array<bool, sizeof...(Axes)> isExterior, + std::set<size_t>& combinations, + const std::tuple<Axes...>& axes) { + // iterate over this axis' bins, remembering which bins are exterior + for (size_t i = 0; i < std::get<N>(axes).getNBins() + 2; ++i) { + idx.at(N) = i; + isExterior.at(N) = (i == 0) || (i == std::get<N>(axes).getNBins() + 1); + // vary other axes recursively + grid_helper_impl<N - 1>::exteriorBinIndices(idx, isExterior, combinations, + axes); + } + } +}; + +template <> +struct grid_helper_impl<0u> { + template <class... Axes> + static void getBinCenter( + std::array<double, sizeof...(Axes)>& center, + const std::array<size_t, sizeof...(Axes)>& localIndices, + const std::tuple<Axes...>& axes) { + center.at(0u) = std::get<0u>(axes).getBinCenter(localIndices.at(0u)); + } + + template <class... Axes> + static void getGlobalBin(const std::array<size_t, sizeof...(Axes)>& localBins, + const std::tuple<Axes...>& /*axes*/, size_t& bin, + size_t& area) { + bin += area * localBins.at(0u); + } + + template <class Point, class... Axes> + static void getLocalBinIndices(const Point& point, + const std::tuple<Axes...>& axes, + std::array<size_t, sizeof...(Axes)>& indices) { + const auto& thisAxis = std::get<0u>(axes); + indices.at(0u) = thisAxis.getBin(point[0u]); + } + + template <class... Axes> + static void getLocalBinIndices(size_t& bin, + const std::tuple<Axes...>& /*axes*/, + size_t& area, + std::array<size_t, sizeof...(Axes)>& indices) { + // make sure to account for under-/overflow bins + indices.at(0u) = bin / area; + bin %= area; + } + + template <class... Axes> + static void getLowerLeftBinEdge( + std::array<double, sizeof...(Axes)>& llEdge, + const std::array<size_t, sizeof...(Axes)>& localIndices, + const std::tuple<Axes...>& axes) { + llEdge.at(0u) = std::get<0u>(axes).getBinLowerBound(localIndices.at(0u)); + } + + template <class... Axes> + static void getLowerLeftBinIndices( + std::array<size_t, sizeof...(Axes)>& localIndices, + const std::tuple<Axes...>& axes) { + localIndices.at(0u) = std::get<0u>(axes).wrapBin(localIndices.at(0u) - 1); + } + + template <class... Axes> + static void getNBins(const std::tuple<Axes...>& axes, + std::array<size_t, sizeof...(Axes)>& nBinsArray) { + // by convention getNBins does not include under-/overflow bins + nBinsArray[0u] = std::get<0u>(axes).getNBins(); + } + + template <class... Axes> + static void getAxes(const std::tuple<Axes...>& axes, + std::array<const IAxis*, sizeof...(Axes)>& axesArr) { + axesArr[0u] = static_cast<const IAxis*>(&std::get<0u>(axes)); + } + + template <class... Axes> + static void getUpperRightBinEdge( + std::array<double, sizeof...(Axes)>& urEdge, + const std::array<size_t, sizeof...(Axes)>& localIndices, + const std::tuple<Axes...>& axes) { + urEdge.at(0u) = std::get<0u>(axes).getBinUpperBound(localIndices.at(0u)); + } + + template <class... Axes> + static void getUpperRightBinIndices( + std::array<size_t, sizeof...(Axes)>& localIndices, + const std::tuple<Axes...>& axes) { + localIndices.at(0u) = std::get<0u>(axes).wrapBin(localIndices.at(0u) + 1); + } + + template <class... Axes> + static void getMin(const std::tuple<Axes...>& axes, + std::array<double, sizeof...(Axes)>& minArray) { + minArray[0u] = std::get<0u>(axes).getMin(); + } + + template <class... Axes> + static void getMax(const std::tuple<Axes...>& axes, + std::array<double, sizeof...(Axes)>& maxArray) { + maxArray[0u] = std::get<0u>(axes).getMax(); + } + + template <class Point, class... Axes> + static bool isInside(const Point& position, const std::tuple<Axes...>& axes) { + return std::get<0u>(axes).isInside(position[0u]); + } + + template <class... Axes> + static void neighborHoodIndices( + const std::array<size_t, sizeof...(Axes)>& localIndices, + std::pair<size_t, size_t> sizes, const std::tuple<Axes...>& axes, + std::array<NeighborHoodIndices, sizeof...(Axes)>& neighborIndices) { + // ask 0-th axis + size_t locIdx = localIndices.at(0u); + NeighborHoodIndices locNeighbors = + std::get<0u>(axes).neighborHoodIndices(locIdx, sizes); + neighborIndices.at(0u) = locNeighbors; + } + + template <class... Axes> + static void exteriorBinIndices(std::array<size_t, sizeof...(Axes)>& idx, + std::array<bool, sizeof...(Axes)> isExterior, + std::set<size_t>& combinations, + const std::tuple<Axes...>& axes) { + // For each exterior bin on this axis, we will do this + auto recordExteriorBin = [&](size_t i) { + idx.at(0u) = i; + // at this point, combinations are complete: save the global bin + size_t bin = 0, area = 1; + grid_helper_impl<sizeof...(Axes) - 1>::getGlobalBin(idx, axes, bin, area); + combinations.insert(bin); + }; - /// @brief get local bin indices for lower-left neighboring bin - /// - /// @tparam Axes parameter pack of axis types defining the grid - /// @param [in] localIndices local bin indices along each axis - /// @param [in] axes actual axis objects spanning the grid - /// @return array with local bin indices of lower-left neighbor bin - /// - /// @pre @c localIndices must only contain valid bin indices (excluding - /// underflow bins). - /// - /// This function returns the local bin indices for the generalized - /// lower-left neighbor which simply means that all local bin indices are - /// decremented by one. - template <class... Axes> - static std::array<size_t, sizeof...(Axes)> - getLowerLeftBinIndices( - const std::array<size_t, sizeof...(Axes)>& localIndices, - const std::tuple<Axes...>& axes) - { - constexpr size_t MAX = sizeof...(Axes) - 1; - auto llIndices = localIndices; - grid_helper_impl<MAX>::getLowerLeftBinIndices(llIndices, axes); - - return llIndices; + // The first and last bins on this axis are exterior by definition + for (size_t i : + {static_cast<size_t>(0), std::get<0u>(axes).getNBins() + 1}) { + recordExteriorBin(i); } - /// @brief calculate number of bins in a grid defined by a set of - /// axes for each axis - /// - /// @tparam Axes parameter pack of axis types defining the grid - /// @param [in] axes actual axis objects spanning the grid - /// @return array of number of bins for each axis of the grid - /// - /// @note This does not include under-/overflow bins along each axis. - template <class... Axes> - static std::array<size_t, sizeof...(Axes)> - getNBins(const std::tuple<Axes...>& axes) - { - std::array<size_t, sizeof...(Axes)> nBinsArray; - grid_helper_impl<sizeof...(Axes) - 1>::getNBins(axes, nBinsArray); - return nBinsArray; + // If no other axis is on an exterior index, stop here + bool otherAxisExterior = false; + for (size_t N = 1; N < sizeof...(Axes); ++N) { + otherAxisExterior = otherAxisExterior | isExterior[N]; } - - /// @brief return an array with copies of the axes, converted - /// to type AnyAxis - /// - /// @tparam Axes parameter pack of axis types defining the grid - /// @param [in] axes actual axis objects spanning the grid - /// @return array with copies of the axis - template <class... Axes> - static std::array<const IAxis*, sizeof...(Axes)> - getAxes(const std::tuple<Axes...>& axes) - { - std::array<const IAxis*, sizeof...(Axes)> arr; - grid_helper_impl<sizeof...(Axes) - 1>::getAxes(axes, arr); - return arr; + if (!otherAxisExterior) { + return; } - /// @brief retrieve upper-right bin edge from set of local bin indices - /// - /// @tparam Axes parameter pack of axis types defining the grid - /// @param [in] localIndices local bin indices along each axis - /// @param [in] axes actual axis objects spanning the grid - /// @return generalized upper-right bin edge - /// - /// @pre @c localIndices must only contain valid bin indices (excluding - /// overflow bins). - template <class... Axes> - static std::array<double, sizeof...(Axes)> - getUpperRightBinEdge( - const std::array<size_t, sizeof...(Axes)>& localIndices, - const std::tuple<Axes...>& axes) - { - std::array<double, sizeof...(Axes)> urEdge; - constexpr size_t MAX = sizeof...(Axes) - 1; - grid_helper_impl<MAX>::getUpperRightBinEdge(urEdge, localIndices, axes); - - return urEdge; + // Otherwise, we're on a grid border: iterate over all the other indices + for (size_t i = 1; i <= std::get<0u>(axes).getNBins(); ++i) { + recordExteriorBin(i); } + } +}; +/// @endcond - /// @brief get local bin indices for upper-right neighboring bin - /// - /// @tparam Axes parameter pack of axis types defining the grid - /// @param [in] localIndices local bin indices along each axis - /// @param [in] axes actual axis objects spanning the grid - /// @return array with local bin indices of upper-right neighbor bin - /// - /// @pre @c localIndices must only contain valid bin indices (excluding - /// overflow bins). - /// - /// This function returns the local bin indices for the generalized - /// upper-right neighbor which simply means that all local bin indices are - /// incremented by one. - template <class... Axes> - static std::array<size_t, sizeof...(Axes)> - getUpperRightBinIndices( - const std::array<size_t, sizeof...(Axes)>& localIndices, - const std::tuple<Axes...>& axes) - { - constexpr size_t MAX = sizeof...(Axes) - 1; - auto urIndices = localIndices; - grid_helper_impl<MAX>::getUpperRightBinIndices(urIndices, axes); - - return urIndices; - } +/// @brief helper functions for grid-related operations +struct grid_helper { + /// @brief get the global indices for closest points on grid + /// + /// @tparam Axes parameter pack of axis types defining the grid + /// @param [in] bin global bin index for bin of interest + /// @param [in] axes actual axis objects spanning the grid + /// @return Sorted collection of global bin indices for bins whose + /// lower-left corners are the closest points on the grid to every + /// point in the given bin + /// + /// @note @c bin must be a valid bin index (excluding under-/overflow bins + /// along any axis). + template <class... Axes> + static GlobalNeighborHoodIndices<sizeof...(Axes)> closestPointsIndices( + const std::array<size_t, sizeof...(Axes)>& localIndices, + const std::tuple<Axes...>& axes) { + // get neighboring bins, but only increment. + return neighborHoodIndices(localIndices, std::make_pair(0, 1), axes); + } + + /// @brief retrieve bin center from set of local bin indices + /// + /// @tparam Axes parameter pack of axis types defining the grid + /// @param [in] localIndices local bin indices along each axis + /// @param [in] axes actual axis objects spanning the grid + /// @return center position of bin + /// + /// @pre @c localIndices must only contain valid bin indices (i.e. excluding + /// under-/overflow bins). + template <class... Axes> + static std::array<double, sizeof...(Axes)> getBinCenter( + const std::array<size_t, sizeof...(Axes)>& localIndices, + const std::tuple<Axes...>& axes) { + std::array<double, sizeof...(Axes)> center; + constexpr size_t MAX = sizeof...(Axes) - 1; + grid_helper_impl<MAX>::getBinCenter(center, localIndices, axes); + + return center; + } + + /// @brief determine global bin index from local indices along each axis + /// + /// @tparam Axes parameter pack of axis types defining the grid + /// + /// @param [in] localBins local bin indices along each axis + /// @param [in] axes actual axis objects spanning the grid + /// @return global index for bin defined by the local bin indices + /// + /// @pre All local bin indices must be a valid index for the corresponding + /// axis (including the under-/overflow bin for this axis). + template <class... Axes> + static size_t getGlobalBin( + const std::array<size_t, sizeof...(Axes)>& localBins, + const std::tuple<Axes...>& axes) { + constexpr size_t MAX = sizeof...(Axes) - 1; + size_t area = 1; + size_t bin = 0; + + grid_helper_impl<MAX>::getGlobalBin(localBins, axes, bin, area); + + return bin; + } + + /// @brief determine local bin index for each axis from point + /// + /// @tparam Point any type with point semantics supporting component access + /// through @c operator[] + /// @tparam Axes parameter pack of axis types defining the grid + /// + /// @param [in] point point to look up in the grid + /// @param [in] axes actual axis objects spanning the grid + /// @return array with local bin indices along each axis (in same order as + /// given @c axes object) + /// + /// @pre The given @c Point type must represent a point in d (or higher) + /// dimensions where d is the number of axis objects in the tuple. + /// @note This could be a under-/overflow bin along one or more axes. + template <class Point, class... Axes> + static std::array<size_t, sizeof...(Axes)> getLocalBinIndices( + const Point& point, const std::tuple<Axes...>& axes) { + constexpr size_t MAX = sizeof...(Axes) - 1; + std::array<size_t, sizeof...(Axes)> indices; - /// @brief get the minimum value of all axes of one grid - /// - /// @tparam Axes parameter pack of axis types defining the grid - /// @param [in] axes actual axis objects spanning the grid - /// @return array returning the minima of all given axes - template <class... Axes> - static std::array<double, sizeof...(Axes)> - getMin(const std::tuple<Axes...>& axes) - { - std::array<double, sizeof...(Axes)> minArray; - grid_helper_impl<sizeof...(Axes) - 1>::getMin(axes, minArray); - return minArray; - } + grid_helper_impl<MAX>::getLocalBinIndices(point, axes, indices); - /// @brief get the maximum value of all axes of one grid - /// - /// @tparam Axes parameter pack of axis types defining the grid - /// @param [in] axes actual axis objects spanning the grid - /// @return array returning the maxima of all given axes - template <class... Axes> - static std::array<double, sizeof...(Axes)> - getMax(const std::tuple<Axes...>& axes) - { - std::array<double, sizeof...(Axes)> maxArray; - grid_helper_impl<sizeof...(Axes) - 1>::getMax(axes, maxArray); - return maxArray; - } + return indices; + } - /// @brief get global bin indices for bins in specified neighborhood - /// - /// @tparam Axes parameter pack of axis types defining the grid - /// @param [in] localIndices local bin indices along each axis - /// @param [in] size size of neighborhood determining how many - /// adjacent bins along each axis are considered - /// @param [in] axes actual axis objects spanning the grid - /// @return Sorted collection of global bin indices for all bins in - /// the neighborhood - /// - /// @note Over-/underflow bins are included in the neighborhood. - /// @note The @c size parameter sets the range by how many units each local - /// bin index is allowed to be varied. All local bin indices are - /// varied independently, that is diagonal neighbors are included. - /// Ignoring the truncation of the neighborhood size reaching beyond - /// over-/underflow bins, the neighborhood is of size \f$2 \times - /// \text{size}+1\f$ along each dimension. - /// @note The concrete bins which are returned depend on the WrappingTypes - /// of the contained axes - /// - template <class... Axes> - static GlobalNeighborHoodIndices<sizeof...(Axes)> - neighborHoodIndices(const std::array<size_t, sizeof...(Axes)>& localIndices, - std::pair<size_t, size_t> sizes, - const std::tuple<Axes...>& axes) - { - constexpr size_t MAX = sizeof...(Axes) - 1; - - // length N array which contains local neighbors based on size par - std::array<NeighborHoodIndices, sizeof...(Axes)> neighborIndices; - // get local bin indices for neighboring bins - grid_helper_impl<MAX>::neighborHoodIndices( - localIndices, sizes, axes, neighborIndices); - - // Query the number of bins - std::array<size_t, sizeof...(Axes)> nBinsArray = getNBins(axes); - - // Produce iterator of global indices - return GlobalNeighborHoodIndices(neighborIndices, nBinsArray); - } + /// @brief determine local bin index for each axis from global bin index + /// + /// @tparam Axes parameter pack of axis types defining the grid + /// + /// @param [in] bin global bin index + /// @param [in] axes actual axis objects spanning the grid + /// @return array with local bin indices along each axis (in same order as + /// given @c axes object) + /// + /// @note Local bin indices can contain under-/overflow bins along any axis. + template <class... Axes> + static std::array<size_t, sizeof...(Axes)> getLocalBinIndices( + size_t bin, const std::tuple<Axes...>& axes) { + constexpr size_t MAX = sizeof...(Axes) - 1; + size_t area = 1; + std::array<size_t, sizeof...(Axes)> indices; - template <class... Axes> - static GlobalNeighborHoodIndices<sizeof...(Axes)> - neighborHoodIndices(const std::array<size_t, sizeof...(Axes)>& localIndices, - size_t size, - const std::tuple<Axes...>& axes) - { - return neighborHoodIndices( - localIndices, std::make_pair(size, size), axes); - } + grid_helper_impl<MAX>::getLocalBinIndices(bin, axes, area, indices); - /// @brief get bin indices of all overflow and underflow bins - /// - /// @tparam Axes parameter pack of axis types defining the grid - /// @param [in] axes actual axis objects spanning the grid - /// @return set of global bin indices for all over- and underflow bins - template <class... Axes> - static std::set<size_t> - exteriorBinIndices(const std::tuple<Axes...>& axes) - { - constexpr size_t MAX = sizeof...(Axes) - 1; - - std::array<size_t, sizeof...(Axes)> idx; - std::array<bool, sizeof...(Axes)> isExterior; - std::set<size_t> combinations; - grid_helper_impl<MAX>::exteriorBinIndices( - idx, isExterior, combinations, axes); - - return combinations; - } + return indices; + } - /// @brief check whether given point is inside axes limits - /// - /// @tparam Point any type with point semantics supporting component access - /// through @c operator[] - /// @tparam Axes parameter pack of axis types defining the grid - /// - /// @param [in] position point to look up in the grid - /// @param [in] axes actual axis objects spanning the grid - /// @return @c true if \f$\text{xmin_i} \le x_i < \text{xmax}_i \forall i=0, - /// \dots, d-1\f$, otherwise @c false - /// - /// @pre The given @c Point type must represent a point in d (or higher) - /// dimensions where d is the number of axis objects in the tuple. - template <class Point, class... Axes> - static bool - isInside(const Point& position, const std::tuple<Axes...>& axes) - { - constexpr size_t MAX = sizeof...(Axes) - 1; - return grid_helper_impl<MAX>::isInside(position, axes); - } - }; + /// @brief retrieve lower-left bin edge from set of local bin indices + /// + /// @tparam Axes parameter pack of axis types defining the grid + /// @param [in] localIndices local bin indices along each axis + /// @param [in] axes actual axis objects spanning the grid + /// @return generalized lower-left bin edge + /// + /// @pre @c localIndices must only contain valid bin indices (excluding + /// underflow bins). + template <class... Axes> + static std::array<double, sizeof...(Axes)> getLowerLeftBinEdge( + const std::array<size_t, sizeof...(Axes)>& localIndices, + const std::tuple<Axes...>& axes) { + std::array<double, sizeof...(Axes)> llEdge; + constexpr size_t MAX = sizeof...(Axes) - 1; + grid_helper_impl<MAX>::getLowerLeftBinEdge(llEdge, localIndices, axes); + + return llEdge; + } + + /// @brief get local bin indices for lower-left neighboring bin + /// + /// @tparam Axes parameter pack of axis types defining the grid + /// @param [in] localIndices local bin indices along each axis + /// @param [in] axes actual axis objects spanning the grid + /// @return array with local bin indices of lower-left neighbor bin + /// + /// @pre @c localIndices must only contain valid bin indices (excluding + /// underflow bins). + /// + /// This function returns the local bin indices for the generalized + /// lower-left neighbor which simply means that all local bin indices are + /// decremented by one. + template <class... Axes> + static std::array<size_t, sizeof...(Axes)> getLowerLeftBinIndices( + const std::array<size_t, sizeof...(Axes)>& localIndices, + const std::tuple<Axes...>& axes) { + constexpr size_t MAX = sizeof...(Axes) - 1; + auto llIndices = localIndices; + grid_helper_impl<MAX>::getLowerLeftBinIndices(llIndices, axes); + + return llIndices; + } + + /// @brief calculate number of bins in a grid defined by a set of + /// axes for each axis + /// + /// @tparam Axes parameter pack of axis types defining the grid + /// @param [in] axes actual axis objects spanning the grid + /// @return array of number of bins for each axis of the grid + /// + /// @note This does not include under-/overflow bins along each axis. + template <class... Axes> + static std::array<size_t, sizeof...(Axes)> getNBins( + const std::tuple<Axes...>& axes) { + std::array<size_t, sizeof...(Axes)> nBinsArray; + grid_helper_impl<sizeof...(Axes) - 1>::getNBins(axes, nBinsArray); + return nBinsArray; + } + + /// @brief return an array with copies of the axes, converted + /// to type AnyAxis + /// + /// @tparam Axes parameter pack of axis types defining the grid + /// @param [in] axes actual axis objects spanning the grid + /// @return array with copies of the axis + template <class... Axes> + static std::array<const IAxis*, sizeof...(Axes)> getAxes( + const std::tuple<Axes...>& axes) { + std::array<const IAxis*, sizeof...(Axes)> arr; + grid_helper_impl<sizeof...(Axes) - 1>::getAxes(axes, arr); + return arr; + } + + /// @brief retrieve upper-right bin edge from set of local bin indices + /// + /// @tparam Axes parameter pack of axis types defining the grid + /// @param [in] localIndices local bin indices along each axis + /// @param [in] axes actual axis objects spanning the grid + /// @return generalized upper-right bin edge + /// + /// @pre @c localIndices must only contain valid bin indices (excluding + /// overflow bins). + template <class... Axes> + static std::array<double, sizeof...(Axes)> getUpperRightBinEdge( + const std::array<size_t, sizeof...(Axes)>& localIndices, + const std::tuple<Axes...>& axes) { + std::array<double, sizeof...(Axes)> urEdge; + constexpr size_t MAX = sizeof...(Axes) - 1; + grid_helper_impl<MAX>::getUpperRightBinEdge(urEdge, localIndices, axes); + + return urEdge; + } + + /// @brief get local bin indices for upper-right neighboring bin + /// + /// @tparam Axes parameter pack of axis types defining the grid + /// @param [in] localIndices local bin indices along each axis + /// @param [in] axes actual axis objects spanning the grid + /// @return array with local bin indices of upper-right neighbor bin + /// + /// @pre @c localIndices must only contain valid bin indices (excluding + /// overflow bins). + /// + /// This function returns the local bin indices for the generalized + /// upper-right neighbor which simply means that all local bin indices are + /// incremented by one. + template <class... Axes> + static std::array<size_t, sizeof...(Axes)> getUpperRightBinIndices( + const std::array<size_t, sizeof...(Axes)>& localIndices, + const std::tuple<Axes...>& axes) { + constexpr size_t MAX = sizeof...(Axes) - 1; + auto urIndices = localIndices; + grid_helper_impl<MAX>::getUpperRightBinIndices(urIndices, axes); + + return urIndices; + } + + /// @brief get the minimum value of all axes of one grid + /// + /// @tparam Axes parameter pack of axis types defining the grid + /// @param [in] axes actual axis objects spanning the grid + /// @return array returning the minima of all given axes + template <class... Axes> + static std::array<double, sizeof...(Axes)> getMin( + const std::tuple<Axes...>& axes) { + std::array<double, sizeof...(Axes)> minArray; + grid_helper_impl<sizeof...(Axes) - 1>::getMin(axes, minArray); + return minArray; + } + + /// @brief get the maximum value of all axes of one grid + /// + /// @tparam Axes parameter pack of axis types defining the grid + /// @param [in] axes actual axis objects spanning the grid + /// @return array returning the maxima of all given axes + template <class... Axes> + static std::array<double, sizeof...(Axes)> getMax( + const std::tuple<Axes...>& axes) { + std::array<double, sizeof...(Axes)> maxArray; + grid_helper_impl<sizeof...(Axes) - 1>::getMax(axes, maxArray); + return maxArray; + } + + /// @brief get global bin indices for bins in specified neighborhood + /// + /// @tparam Axes parameter pack of axis types defining the grid + /// @param [in] localIndices local bin indices along each axis + /// @param [in] size size of neighborhood determining how many + /// adjacent bins along each axis are considered + /// @param [in] axes actual axis objects spanning the grid + /// @return Sorted collection of global bin indices for all bins in + /// the neighborhood + /// + /// @note Over-/underflow bins are included in the neighborhood. + /// @note The @c size parameter sets the range by how many units each local + /// bin index is allowed to be varied. All local bin indices are + /// varied independently, that is diagonal neighbors are included. + /// Ignoring the truncation of the neighborhood size reaching beyond + /// over-/underflow bins, the neighborhood is of size \f$2 \times + /// \text{size}+1\f$ along each dimension. + /// @note The concrete bins which are returned depend on the WrappingTypes + /// of the contained axes + /// + template <class... Axes> + static GlobalNeighborHoodIndices<sizeof...(Axes)> neighborHoodIndices( + const std::array<size_t, sizeof...(Axes)>& localIndices, + std::pair<size_t, size_t> sizes, const std::tuple<Axes...>& axes) { + constexpr size_t MAX = sizeof...(Axes) - 1; + + // length N array which contains local neighbors based on size par + std::array<NeighborHoodIndices, sizeof...(Axes)> neighborIndices; + // get local bin indices for neighboring bins + grid_helper_impl<MAX>::neighborHoodIndices(localIndices, sizes, axes, + neighborIndices); + + // Query the number of bins + std::array<size_t, sizeof...(Axes)> nBinsArray = getNBins(axes); + + // Produce iterator of global indices + return GlobalNeighborHoodIndices(neighborIndices, nBinsArray); + } + + template <class... Axes> + static GlobalNeighborHoodIndices<sizeof...(Axes)> neighborHoodIndices( + const std::array<size_t, sizeof...(Axes)>& localIndices, size_t size, + const std::tuple<Axes...>& axes) { + return neighborHoodIndices(localIndices, std::make_pair(size, size), axes); + } + + /// @brief get bin indices of all overflow and underflow bins + /// + /// @tparam Axes parameter pack of axis types defining the grid + /// @param [in] axes actual axis objects spanning the grid + /// @return set of global bin indices for all over- and underflow bins + template <class... Axes> + static std::set<size_t> exteriorBinIndices(const std::tuple<Axes...>& axes) { + constexpr size_t MAX = sizeof...(Axes) - 1; + + std::array<size_t, sizeof...(Axes)> idx; + std::array<bool, sizeof...(Axes)> isExterior; + std::set<size_t> combinations; + grid_helper_impl<MAX>::exteriorBinIndices(idx, isExterior, combinations, + axes); + + return combinations; + } + + /// @brief check whether given point is inside axes limits + /// + /// @tparam Point any type with point semantics supporting component access + /// through @c operator[] + /// @tparam Axes parameter pack of axis types defining the grid + /// + /// @param [in] position point to look up in the grid + /// @param [in] axes actual axis objects spanning the grid + /// @return @c true if \f$\text{xmin_i} \le x_i < \text{xmax}_i \forall i=0, + /// \dots, d-1\f$, otherwise @c false + /// + /// @pre The given @c Point type must represent a point in d (or higher) + /// dimensions where d is the number of axis objects in the tuple. + template <class Point, class... Axes> + static bool isInside(const Point& position, const std::tuple<Axes...>& axes) { + constexpr size_t MAX = sizeof...(Axes) - 1; + return grid_helper_impl<MAX>::isInside(position, axes); + } +}; } // namespace detail diff --git a/Core/include/Acts/Utilities/detail/interpolation_impl.hpp b/Core/include/Acts/Utilities/detail/interpolation_impl.hpp index ff0d811871fbbabd517b9abceb7a43f67cbd2993..294d7befd380482e13defa2e66aaf02d293e907b 100644 --- a/Core/include/Acts/Utilities/detail/interpolation_impl.hpp +++ b/Core/include/Acts/Utilities/detail/interpolation_impl.hpp @@ -14,147 +14,122 @@ namespace Acts { namespace detail { - /// @brief check types for requirements needed by interpolation - /// - /// @tparam Point1 type for specifying geometric positions - /// @tparam Point2 type for specifying geometric positions - /// @tparam Point3 type for specifying geometric positions - /// @tparam Value type of values to be interpolated - /// - /// This helper struct provides compile-time information whether the provided - /// @c Point and @c Value types can be used in the Acts::interpolate function. - /// - /// The following boolean variable - /// @code{.cpp} - /// Acts::detail::can_interpolate<Point1,Point2,Point3,Value>::value - /// @endcode - /// - /// is @c true if all @c Point types and @c Value fulfill the type - /// requirements for being used in the interpolation function, otherwise it is - /// @c false. This expression can be employed in @c std::enable_if_t to use - /// SFINAE patterns to enable/disable (member) functions. - template <typename Point1, typename Point2, typename Point3, typename Value> - struct can_interpolate - { - template <typename C> - static auto - value_type_test(C* c) - -> decltype(C(std::declval<double>() * std::declval<C>() - + std::declval<double>() * std::declval<C>()), - std::true_type()); - template <typename C> - static std::false_type - value_type_test(...); - - template <typename C> - static auto - point_type_test(C* c) - -> decltype(double(std::declval<C>()[0]), std::true_type()); - template <typename C> - static std::false_type - point_type_test(...); - - static const bool value - = std::is_same<std::true_type, - decltype(value_type_test<Value>(nullptr))>::value - and std::is_same<std::true_type, - decltype(point_type_test<Point1>(nullptr))>::value - and std::is_same<std::true_type, - decltype(point_type_test<Point2>(nullptr))>::value - and std::is_same<std::true_type, - decltype(point_type_test<Point3>(nullptr))>::value; - }; - - /// @brief determine number of dimension from power of 2 - /// - /// @tparam N power of 2 - template <size_t N> - struct get_dimension - { - /// exponent @c d such that \f$2^d = N \f$ - static constexpr size_t value = get_dimension<(N >> 1)>::value + 1u; - }; - - /// @cond - template <> - struct get_dimension<2u> - { - static constexpr size_t value = 1u; - }; - /// @endcond - - /// @brief helper struct for performing multi-dimensional linear interpolation - /// - /// @tparam T type of values to be interpolated - /// @tparam Point1 type specifying geometric positions - /// @tparam Point2 type specifying geometric positions - /// @tparam Point3 type specifying geometric positions - /// @tparam D current dimension on which to perform reduction - /// @tparam N number of hyper box corners - /// - /// @note - /// - Given @c U and @c V of value type @c T as well as two @c double @c a and - /// @c b, then the following must be a valid expression <tt>a * U + b * V</tt> - /// yielding an object which is (implicitly) convertible to @c T. - /// - The @c Point types must represent d-dimensional positions and support - /// coordinate access using @c operator[]. Coordinate indices must start at 0. - /// - @c N is the number of hyper box corners which is \f$2^d\f$ where \f$d\f$ - /// is the dimensionality of the hyper box. The dimensionality must be - /// consistent with the provided @c Point types. - template <typename T, - class Point1, - class Point2, - class Point3, - size_t D, - size_t N> - struct interpolate_impl; - - /// @cond - // recursive implementation of linear interpolation in multiple dimensions - template <typename T, - class Point1, - class Point2, - class Point3, - size_t D, - size_t N> - struct interpolate_impl - { - static T - run(const Point1& pos, - const Point2& lowerLeft, - const Point3& upperRight, - const std::array<T, N>& fields) - { - // get distance to lower boundary relative to total bin width - const double f = (pos[D] - lowerLeft[D]) / (upperRight[D] - lowerLeft[D]); - - std::array<T, (N >> 1)> newFields; - for (size_t i = 0; i < N / 2; ++i) { - newFields.at(i) = (1 - f) * fields.at(2 * i) + f * fields.at(2 * i + 1); - } - - return interpolate_impl<T, Point1, Point2, Point3, D - 1, (N >> 1)>::run( - pos, lowerLeft, upperRight, newFields); +/// @brief check types for requirements needed by interpolation +/// +/// @tparam Point1 type for specifying geometric positions +/// @tparam Point2 type for specifying geometric positions +/// @tparam Point3 type for specifying geometric positions +/// @tparam Value type of values to be interpolated +/// +/// This helper struct provides compile-time information whether the provided +/// @c Point and @c Value types can be used in the Acts::interpolate function. +/// +/// The following boolean variable +/// @code{.cpp} +/// Acts::detail::can_interpolate<Point1,Point2,Point3,Value>::value +/// @endcode +/// +/// is @c true if all @c Point types and @c Value fulfill the type +/// requirements for being used in the interpolation function, otherwise it is +/// @c false. This expression can be employed in @c std::enable_if_t to use +/// SFINAE patterns to enable/disable (member) functions. +template <typename Point1, typename Point2, typename Point3, typename Value> +struct can_interpolate { + template <typename C> + static auto value_type_test(C* c) + -> decltype(C(std::declval<double>() * std::declval<C>() + + std::declval<double>() * std::declval<C>()), + std::true_type()); + template <typename C> + static std::false_type value_type_test(...); + + template <typename C> + static auto point_type_test(C* c) + -> decltype(double(std::declval<C>()[0]), std::true_type()); + template <typename C> + static std::false_type point_type_test(...); + + static const bool value = + std::is_same<std::true_type, + decltype(value_type_test<Value>(nullptr))>::value and + std::is_same<std::true_type, + decltype(point_type_test<Point1>(nullptr))>::value and + std::is_same<std::true_type, + decltype(point_type_test<Point2>(nullptr))>::value and + std::is_same<std::true_type, + decltype(point_type_test<Point3>(nullptr))>::value; +}; + +/// @brief determine number of dimension from power of 2 +/// +/// @tparam N power of 2 +template <size_t N> +struct get_dimension { + /// exponent @c d such that \f$2^d = N \f$ + static constexpr size_t value = get_dimension<(N >> 1)>::value + 1u; +}; + +/// @cond +template <> +struct get_dimension<2u> { + static constexpr size_t value = 1u; +}; +/// @endcond + +/// @brief helper struct for performing multi-dimensional linear interpolation +/// +/// @tparam T type of values to be interpolated +/// @tparam Point1 type specifying geometric positions +/// @tparam Point2 type specifying geometric positions +/// @tparam Point3 type specifying geometric positions +/// @tparam D current dimension on which to perform reduction +/// @tparam N number of hyper box corners +/// +/// @note +/// - Given @c U and @c V of value type @c T as well as two @c double @c a and +/// @c b, then the following must be a valid expression <tt>a * U + b * V</tt> +/// yielding an object which is (implicitly) convertible to @c T. +/// - The @c Point types must represent d-dimensional positions and support +/// coordinate access using @c operator[]. Coordinate indices must start at 0. +/// - @c N is the number of hyper box corners which is \f$2^d\f$ where \f$d\f$ +/// is the dimensionality of the hyper box. The dimensionality must be +/// consistent with the provided @c Point types. +template <typename T, class Point1, class Point2, class Point3, size_t D, + size_t N> +struct interpolate_impl; + +/// @cond +// recursive implementation of linear interpolation in multiple dimensions +template <typename T, class Point1, class Point2, class Point3, size_t D, + size_t N> +struct interpolate_impl { + static T run(const Point1& pos, const Point2& lowerLeft, + const Point3& upperRight, const std::array<T, N>& fields) { + // get distance to lower boundary relative to total bin width + const double f = (pos[D] - lowerLeft[D]) / (upperRight[D] - lowerLeft[D]); + + std::array<T, (N >> 1)> newFields; + for (size_t i = 0; i < N / 2; ++i) { + newFields.at(i) = (1 - f) * fields.at(2 * i) + f * fields.at(2 * i + 1); } - }; - - // simple linear interpolation in 1D - template <typename T, class Point1, class Point2, class Point3, size_t D> - struct interpolate_impl<T, Point1, Point2, Point3, D, 2u> - { - static T - run(const Point1& pos, - const Point2& lowerLeft, - const Point3& upperRight, - const std::array<T, 2u>& fields) - { - // get distance to lower boundary relative to total bin width - const double f = (pos[D] - lowerLeft[D]) / (upperRight[D] - lowerLeft[D]); - - return (1 - f) * fields.at(0) + f * fields.at(1); - } - }; - /// @endcond + + return interpolate_impl<T, Point1, Point2, Point3, D - 1, (N >> 1)>::run( + pos, lowerLeft, upperRight, newFields); + } +}; + +// simple linear interpolation in 1D +template <typename T, class Point1, class Point2, class Point3, size_t D> +struct interpolate_impl<T, Point1, Point2, Point3, D, 2u> { + static T run(const Point1& pos, const Point2& lowerLeft, + const Point3& upperRight, const std::array<T, 2u>& fields) { + // get distance to lower boundary relative to total bin width + const double f = (pos[D] - lowerLeft[D]) / (upperRight[D] - lowerLeft[D]); + + return (1 - f) * fields.at(0) + f * fields.at(1); + } +}; +/// @endcond } // namespace detail } // namespace Acts diff --git a/Core/include/Acts/Utilities/detail/periodic.hpp b/Core/include/Acts/Utilities/detail/periodic.hpp index f7b639930c554d493d4b6ba98f2a941249b42e46..1cfd91f9aa1aa0d232507babf3b856a21327cc1a 100644 --- a/Core/include/Acts/Utilities/detail/periodic.hpp +++ b/Core/include/Acts/Utilities/detail/periodic.hpp @@ -12,34 +12,28 @@ namespace Acts { namespace detail { - /// Wrap a periodic value back into the nominal range. - template <typename T> - inline T - wrap_periodic(T value, T start, T range) - { - using std::floor; - // only wrap if really necessary - T diff = value - start; - return ((0 <= diff) && (diff < range)) - ? value - : (value - range * floor(diff / range)); - } +/// Wrap a periodic value back into the nominal range. +template <typename T> +inline T wrap_periodic(T value, T start, T range) { + using std::floor; + // only wrap if really necessary + T diff = value - start; + return ((0 <= diff) && (diff < range)) + ? value + : (value - range * floor(diff / range)); +} - /// Calculate the equivalent angle in the [0, 2*pi) range. - template <typename T> - inline T - radian_pos(T x) - { - return wrap_periodic<T>(x, T(0), T(2 * M_PI)); - } +/// Calculate the equivalent angle in the [0, 2*pi) range. +template <typename T> +inline T radian_pos(T x) { + return wrap_periodic<T>(x, T(0), T(2 * M_PI)); +} - /// Calculate the equivalent angle in the [-pi, pi) range. - template <typename T> - inline T - radian_sym(T x) - { - return wrap_periodic<T>(x, T(-M_PI), T(2 * M_PI)); - } +/// Calculate the equivalent angle in the [-pi, pi) range. +template <typename T> +inline T radian_sym(T x) { + return wrap_periodic<T>(x, T(-M_PI), T(2 * M_PI)); +} } // namespace detail } // namespace Acts \ No newline at end of file diff --git a/Core/include/Acts/Vertexing/FullBilloirVertexFitter.hpp b/Core/include/Acts/Vertexing/FullBilloirVertexFitter.hpp index 7af958badfcf71002a6254327559f3888e2811df..de56bba14519bfdc7d812adf8e5ada32e2d49a30 100644 --- a/Core/include/Acts/Vertexing/FullBilloirVertexFitter.hpp +++ b/Core/include/Acts/Vertexing/FullBilloirVertexFitter.hpp @@ -33,15 +33,12 @@ namespace Acts { /// @tparam input_track_t Track object type /// @tparam propagator_t Propagator type -template <typename bfield_t, - typename input_track_t, +template <typename bfield_t, typename input_track_t, typename propagator_t = Propagator<EigenStepper<bfield_t>>> class FullBilloirVertexFitter - : public IVertexFitter<input_track_t, propagator_t> -{ -public: - struct Config - { + : public IVertexFitter<input_track_t, propagator_t> { + public: + struct Config { /// Magnetic field bfield_t bField; @@ -50,33 +47,29 @@ public: /// Set up factory for linearizing tracks typename LinearizedTrackFactory<bfield_t, propagator_t>::Config ltConfig; - LinearizedTrackFactory<bfield_t, propagator_t> linFactory; + LinearizedTrackFactory<bfield_t, propagator_t> linFactory; /// Propagator propagator_t propagator; /// Constructor with propagator input Config(const bfield_t& bIn, const propagator_t& propagatorIn) - : bField(bIn) - , ltConfig(bIn) - , linFactory(ltConfig) - , propagator(propagatorIn) - { - } + : bField(bIn), + ltConfig(bIn), + linFactory(ltConfig), + propagator(propagatorIn) {} /// Constructor with default propagator - template < - typename T = propagator_t, - std::enable_if_t<std::is_same<T, Propagator<EigenStepper<bfield_t>>>:: - value, - int> = 0> + template <typename T = propagator_t, + std::enable_if_t< + std::is_same<T, Propagator<EigenStepper<bfield_t>>>::value, + int> = 0> Config(const bfield_t& bIn) - : bField(bIn) - , ltConfig(bIn) - , linFactory(ltConfig) - , propagator( - Propagator<EigenStepper<bfield_t>>(EigenStepper<bfield_t>(bIn))) - { + : bField(bIn), + ltConfig(bIn), + linFactory(ltConfig), + propagator( + Propagator<EigenStepper<bfield_t>>(EigenStepper<bfield_t>(bIn))) { } }; @@ -86,19 +79,15 @@ public: template <typename T = input_track_t, std::enable_if_t<std::is_same<T, BoundParameters>::value, int> = 0> FullBilloirVertexFitter(const Config& cfg) - : m_cfg(cfg), extractParameters([&](T params) { return params; }) - { - } + : m_cfg(cfg), extractParameters([&](T params) { return params; }) {} /// @brief Constructor for user-defined input_track_t type =! BoundParameters /// /// @param cfg Configuration object /// @param func Function extracting BoundParameters from input_track_t object - FullBilloirVertexFitter(const Config& cfg, + FullBilloirVertexFitter(const Config& cfg, std::function<BoundParameters(input_track_t)> func) - : m_cfg(cfg), extractParameters(func) - { - } + : m_cfg(cfg), extractParameters(func) {} /// @brief Default destructor ~FullBilloirVertexFitter() override = default; @@ -109,11 +98,11 @@ public: /// @param vFitterOptions Vertex fitter options /// /// @return Fitted vertex - Result<Vertex<input_track_t>> - fit(const std::vector<input_track_t>& paramVector, + Result<Vertex<input_track_t>> fit( + const std::vector<input_track_t>& paramVector, const VertexFitterOptions<input_track_t>& vFitterOptions) const override; -private: + private: /// Configuration object Config m_cfg; @@ -130,8 +119,8 @@ private: /// @param thetaIn Theta /// /// @return Pair of (corrected phi, corrected theta) - std::pair<double, double> - correctPhiThetaPeriodicity(double phiIn, double thetaIn) const; + std::pair<double, double> correctPhiThetaPeriodicity(double phiIn, + double thetaIn) const; }; } // namespace Acts diff --git a/Core/include/Acts/Vertexing/FullBilloirVertexFitter.ipp b/Core/include/Acts/Vertexing/FullBilloirVertexFitter.ipp index 9738fe40c183d4cdb4dae8aa8aa2935f9d7a7f1d..d6f4157d9c84d1a098cdf58fc4300762c1e0787d 100644 --- a/Core/include/Acts/Vertexing/FullBilloirVertexFitter.ipp +++ b/Core/include/Acts/Vertexing/FullBilloirVertexFitter.ipp @@ -18,33 +18,29 @@ namespace { /// /// @brief Struct to cache track-specific matrix operations in Billoir fitter template <typename input_track_t> -struct BilloirTrack -{ +struct BilloirTrack { BilloirTrack(const input_track_t& params, Acts::LinearizedTrack lTrack) - : originalTrack(params), linTrack(std::move(lTrack)) - { - } + : originalTrack(params), linTrack(std::move(lTrack)) {} BilloirTrack(const BilloirTrack& arg) = default; - const input_track_t originalTrack; + const input_track_t originalTrack; Acts::LinearizedTrack linTrack; - double chi2; + double chi2; Acts::ActsMatrixD<5, 3> DiMat; // position jacobian Acts::ActsMatrixD<5, 3> EiMat; // momentum jacobian Acts::ActsSymMatrixD<3> GiMat; // = EtWmat * Emat (see below) Acts::ActsSymMatrixD<3> BiMat; // = DiMat^T * Wi * EiMat Acts::ActsSymMatrixD<3> CiInv; // = (EiMat^T * Wi * EiMat)^-1 - Acts::Vector3D UiVec; // = EiMat^T * Wi * dqi + Acts::Vector3D UiVec; // = EiMat^T * Wi * dqi Acts::ActsSymMatrixD<3> BCiMat; // = BiMat * Ci^-1 - Acts::ActsVectorD<5> deltaQ; + Acts::ActsVectorD<5> deltaQ; }; /// @struct BilloirVertex /// /// @brief Struct to cache vertex-specific matrix operations in Billoir fitter -struct BilloirVertex -{ +struct BilloirVertex { BilloirVertex() = default; Acts::ActsSymMatrixD<3> Amat{ @@ -64,11 +60,10 @@ struct BilloirVertex template <typename bfield_t, typename input_track_t, typename propagator_t> Acts::Result<Acts::Vertex<input_track_t>> Acts::FullBilloirVertexFitter<bfield_t, input_track_t, propagator_t>::fit( - const std::vector<input_track_t>& paramVector, - const VertexFitterOptions<input_track_t>& vFitterOptions) const -{ - double chi2 = std::numeric_limits<double>::max(); - double newChi2 = 0; + const std::vector<input_track_t>& paramVector, + const VertexFitterOptions<input_track_t>& vFitterOptions) const { + double chi2 = std::numeric_limits<double>::max(); + double newChi2 = 0; unsigned int nTracks = paramVector.size(); if (nTracks == 0) { @@ -103,35 +98,32 @@ Acts::FullBilloirVertexFitter<bfield_t, input_track_t, propagator_t>::fit( newChi2 = 0; BilloirVertex billoirVertex; - int iTrack = 0; + int iTrack = 0; // iterate over all tracks for (const input_track_t& trackContainer : paramVector) { const auto& trackParams = extractParameters(trackContainer); if (nIter == 0) { - double phi = trackParams.parameters()[ParID_t::ePHI]; + double phi = trackParams.parameters()[ParID_t::ePHI]; double theta = trackParams.parameters()[ParID_t::eTHETA]; - double qop = trackParams.parameters()[ParID_t::eQOP]; + double qop = trackParams.parameters()[ParID_t::eQOP]; trackMomenta.push_back(Vector3D(phi, theta, qop)); } - auto result - = m_cfg.linFactory.linearizeTrack(vFitterOptions.geoContext, - vFitterOptions.magFieldContext, - &trackParams, - linPoint, - m_cfg.propagator); + auto result = m_cfg.linFactory.linearizeTrack( + vFitterOptions.geoContext, vFitterOptions.magFieldContext, + &trackParams, linPoint, m_cfg.propagator); if (result.ok()) { const auto linTrack = *result; - double d0 = linTrack.parametersAtPCA[ParID_t::eLOC_D0]; - double z0 = linTrack.parametersAtPCA[ParID_t::eLOC_Z0]; - double phi = linTrack.parametersAtPCA[ParID_t::ePHI]; - double theta = linTrack.parametersAtPCA[ParID_t::eTHETA]; - double qOverP = linTrack.parametersAtPCA[ParID_t::eQOP]; + double d0 = linTrack.parametersAtPCA[ParID_t::eLOC_D0]; + double z0 = linTrack.parametersAtPCA[ParID_t::eLOC_Z0]; + double phi = linTrack.parametersAtPCA[ParID_t::ePHI]; + double theta = linTrack.parametersAtPCA[ParID_t::eTHETA]; + double qOverP = linTrack.parametersAtPCA[ParID_t::eQOP]; // calculate f(V_0,p_0) f_d0 = f_z0 = 0 - double fPhi = trackMomenta[iTrack][0]; - double fTheta = trackMomenta[iTrack][1]; - double fQOvP = trackMomenta[iTrack][2]; + double fPhi = trackMomenta[iTrack][0]; + double fTheta = trackMomenta[iTrack][1]; + double fQOvP = trackMomenta[iTrack][2]; BilloirTrack<input_track_t> currentBilloirTrack(trackContainer, linTrack); @@ -153,34 +145,37 @@ Acts::FullBilloirVertexFitter<bfield_t, input_track_t, propagator_t>::fit( ActsMatrixD<3, 5> DtWmat; ActsMatrixD<3, 5> EtWmat; ActsSymMatrixD<5> Wi = linTrack.covarianceAtPCA.inverse(); - DtWmat = Dmat.transpose() * Wi; - EtWmat = Emat.transpose() * Wi; + DtWmat = Dmat.transpose() * Wi; + EtWmat = Emat.transpose() * Wi; // compute billoir tracks currentBilloirTrack.DiMat = Dmat; currentBilloirTrack.EiMat = Emat; currentBilloirTrack.GiMat = EtWmat * Emat; currentBilloirTrack.BiMat = DtWmat * Emat; // DiMat^T * Wi * EiMat - currentBilloirTrack.UiVec - = EtWmat * currentBilloirTrack.deltaQ; // EiMat^T * Wi * dqi - currentBilloirTrack.CiInv - = (EtWmat * Emat).inverse(); // (EiMat^T * Wi * EiMat)^-1 + currentBilloirTrack.UiVec = + EtWmat * currentBilloirTrack.deltaQ; // EiMat^T * Wi * dqi + currentBilloirTrack.CiInv = + (EtWmat * Emat).inverse(); // (EiMat^T * Wi * EiMat)^-1 // sum up over all tracks - billoirVertex.Tvec - += DtWmat * currentBilloirTrack.deltaQ; // sum{DiMat^T * Wi * dqi} - billoirVertex.Amat += DtWmat * Dmat; // sum{DiMat^T * Wi * DiMat} + billoirVertex.Tvec += + DtWmat * currentBilloirTrack.deltaQ; // sum{DiMat^T * Wi * dqi} + billoirVertex.Amat += DtWmat * Dmat; // sum{DiMat^T * Wi * DiMat} // remember those results for all tracks - currentBilloirTrack.BCiMat = currentBilloirTrack.BiMat - * currentBilloirTrack.CiInv; // BCi = BiMat * Ci^-1 + currentBilloirTrack.BCiMat = + currentBilloirTrack.BiMat * + currentBilloirTrack.CiInv; // BCi = BiMat * Ci^-1 // and some summed results - billoirVertex.BCUvec += currentBilloirTrack.BCiMat - * currentBilloirTrack.UiVec; // sum{BiMat * Ci^-1 * UiVec} - billoirVertex.BCBmat += currentBilloirTrack.BCiMat - * currentBilloirTrack.BiMat - .transpose(); // sum{BiMat * Ci^-1 * BiMat^T} + billoirVertex.BCUvec += + currentBilloirTrack.BCiMat * + currentBilloirTrack.UiVec; // sum{BiMat * Ci^-1 * UiVec} + billoirVertex.BCBmat += + currentBilloirTrack.BCiMat * + currentBilloirTrack.BiMat + .transpose(); // sum{BiMat * Ci^-1 * BiMat^T} billoirTracks.push_back(currentBilloirTrack); ++iTrack; @@ -192,23 +187,24 @@ Acts::FullBilloirVertexFitter<bfield_t, input_track_t, propagator_t>::fit( // calculate delta (billoirFrameOrigin-position), might be changed by the // beam-const - Vector3D Vdel = billoirVertex.Tvec - - billoirVertex.BCUvec; // Vdel = Tvec-sum{BiMat*Ci^-1*UiVec} - ActsSymMatrixD<3> VwgtMat = billoirVertex.Amat - - billoirVertex.BCBmat; // VwgtMat = Amat-sum{BiMat*Ci^-1*BiMat^T} + Vector3D Vdel = billoirVertex.Tvec - + billoirVertex.BCUvec; // Vdel = Tvec-sum{BiMat*Ci^-1*UiVec} + ActsSymMatrixD<3> VwgtMat = + billoirVertex.Amat - + billoirVertex.BCBmat; // VwgtMat = Amat-sum{BiMat*Ci^-1*BiMat^T} if (isConstraintFit) { Vector3D posInBilloirFrame; // this will be 0 for first iteration but != 0 from second on - posInBilloirFrame[0] - = vFitterOptions.vertexConstraint.position()[0] - linPoint[0]; - posInBilloirFrame[1] - = vFitterOptions.vertexConstraint.position()[1] - linPoint[1]; - posInBilloirFrame[2] - = vFitterOptions.vertexConstraint.position()[2] - linPoint[2]; - - Vdel += vFitterOptions.vertexConstraint.covariance().inverse() - * posInBilloirFrame; + posInBilloirFrame[0] = + vFitterOptions.vertexConstraint.position()[0] - linPoint[0]; + posInBilloirFrame[1] = + vFitterOptions.vertexConstraint.position()[1] - linPoint[1]; + posInBilloirFrame[2] = + vFitterOptions.vertexConstraint.position()[2] - linPoint[2]; + + Vdel += vFitterOptions.vertexConstraint.covariance().inverse() * + posInBilloirFrame; VwgtMat += vFitterOptions.vertexConstraint.covariance().inverse(); } @@ -225,9 +221,8 @@ Acts::FullBilloirVertexFitter<bfield_t, input_track_t, propagator_t>::fit( iTrack = 0; for (auto& bTrack : billoirTracks) { - - Vector3D deltaP - = (bTrack.CiInv) * (bTrack.UiVec - bTrack.BiMat.transpose() * deltaV); + Vector3D deltaP = + (bTrack.CiInv) * (bTrack.UiVec - bTrack.BiMat.transpose() * deltaV); // update track momenta trackMomenta[iTrack][0] += deltaP[0]; @@ -266,8 +261,8 @@ Acts::FullBilloirVertexFitter<bfield_t, input_track_t, propagator_t>::fit( // cov(P,P) ActsSymMatrixD<3> PPmat; - PPmat = bTrack.CiInv - + bTrack.BCiMat.transpose() * covDeltaVmat * bTrack.BCiMat; + PPmat = bTrack.CiInv + + bTrack.BCiMat.transpose() * covDeltaVmat * bTrack.BCiMat; ActsSymMatrixD<6> covMat; covMat.setZero(); @@ -280,12 +275,12 @@ Acts::FullBilloirVertexFitter<bfield_t, input_track_t, propagator_t>::fit( covDeltaPmat[iTrack] = std::make_unique<ActsSymMatrixD<5>>( transMat * covMat * transMat.transpose()); // Calculate chi2 per track. - bTrack.chi2 - = ((bTrack.deltaQ - bTrack.DiMat * deltaV - bTrack.EiMat * deltaP) - .transpose()) - .dot(bTrack.linTrack.covarianceAtPCA.inverse() - * (bTrack.deltaQ - bTrack.DiMat * deltaV - - bTrack.EiMat * deltaP)); + bTrack.chi2 = + ((bTrack.deltaQ - bTrack.DiMat * deltaV - bTrack.EiMat * deltaP) + .transpose()) + .dot(bTrack.linTrack.covarianceAtPCA.inverse() * + (bTrack.deltaQ - bTrack.DiMat * deltaV - + bTrack.EiMat * deltaP)); newChi2 += bTrack.chi2; ++iTrack; @@ -296,15 +291,16 @@ Acts::FullBilloirVertexFitter<bfield_t, input_track_t, propagator_t>::fit( // last term will also be 0 again but only in the first iteration // = calc. vtx in billoir frame - ( isConstraintFit pos. in billoir // frame ) - deltaTrk[0] = deltaV[0] - - (vFitterOptions.vertexConstraint.position()[0] - linPoint[0]); - deltaTrk[1] = deltaV[1] - - (vFitterOptions.vertexConstraint.position()[1] - linPoint[1]); - deltaTrk[2] = deltaV[2] - - (vFitterOptions.vertexConstraint.position()[2] - linPoint[2]); - newChi2 += (deltaTrk.transpose()) - .dot(vFitterOptions.vertexConstraint.covariance().inverse() - * deltaTrk); + deltaTrk[0] = deltaV[0] - (vFitterOptions.vertexConstraint.position()[0] - + linPoint[0]); + deltaTrk[1] = deltaV[1] - (vFitterOptions.vertexConstraint.position()[1] - + linPoint[1]); + deltaTrk[2] = deltaV[2] - (vFitterOptions.vertexConstraint.position()[2] - + linPoint[2]); + newChi2 += + (deltaTrk.transpose()) + .dot(vFitterOptions.vertexConstraint.covariance().inverse() * + deltaTrk); } if (!std::isnormal(newChi2)) { @@ -324,12 +320,11 @@ Acts::FullBilloirVertexFitter<bfield_t, input_track_t, propagator_t>::fit( std::vector<TrackAtVertex<input_track_t>> tracksAtVertex; - std::shared_ptr<PerigeeSurface> perigee - = Surface::makeShared<PerigeeSurface>(vertexPos); + std::shared_ptr<PerigeeSurface> perigee = + Surface::makeShared<PerigeeSurface>(vertexPos); iTrack = 0; for (auto& bTrack : billoirTracks) { - // new refitted trackparameters TrackParametersBase::ParVector_t paramVec; paramVec << 0., 0., trackMomenta[iTrack](0), trackMomenta[iTrack](1), @@ -337,11 +332,10 @@ Acts::FullBilloirVertexFitter<bfield_t, input_track_t, propagator_t>::fit( BoundParameters refittedParams(vFitterOptions.geoContext, std::move(covDeltaPmat[iTrack]), - paramVec, - perigee); + paramVec, perigee); - TrackAtVertex<input_track_t> trackVx( - bTrack.chi2, refittedParams, bTrack.originalTrack); + TrackAtVertex<input_track_t> trackVx(bTrack.chi2, refittedParams, + bTrack.originalTrack); tracksAtVertex.push_back(std::move(trackVx)); ++iTrack; } @@ -352,10 +346,10 @@ Acts::FullBilloirVertexFitter<bfield_t, input_track_t, propagator_t>::fit( } template <typename bfield_t, typename input_track_t, typename propagator_t> -std::pair<double, double> -Acts::FullBilloirVertexFitter<bfield_t, input_track_t, propagator_t>:: - correctPhiThetaPeriodicity(double phiIn, double thetaIn) const -{ +std::pair<double, double> Acts::FullBilloirVertexFitter< + bfield_t, input_track_t, + propagator_t>::correctPhiThetaPeriodicity(double phiIn, + double thetaIn) const { double tmpPhi = std::fmod(phiIn, 2 * M_PI); // temp phi if (tmpPhi > M_PI) { tmpPhi -= 2 * M_PI; diff --git a/Core/include/Acts/Vertexing/IVertexFitter.hpp b/Core/include/Acts/Vertexing/IVertexFitter.hpp index 7f5dd0bc4b458d233b49ffb9f985c56145272487..83e4253690bb930e9754b71c5aa9d956b6fe9323 100644 --- a/Core/include/Acts/Vertexing/IVertexFitter.hpp +++ b/Core/include/Acts/Vertexing/IVertexFitter.hpp @@ -20,9 +20,7 @@ namespace Acts { /// @brief Vertex Fitter Options /// template <typename input_track_t> -struct VertexFitterOptions -{ - +struct VertexFitterOptions { /// Default contstructor is deleted VertexFitterOptions() = delete; @@ -31,13 +29,11 @@ struct VertexFitterOptions /// @param gctx The goemetry context for this fit /// @param mctx The magnetic context for this fit /// @param pconstraint The pointing contraint to a vertex - VertexFitterOptions(std::reference_wrapper<const GeometryContext> gctx, + VertexFitterOptions(std::reference_wrapper<const GeometryContext> gctx, std::reference_wrapper<const MagneticFieldContext> mctx, - const Vertex<input_track_t>& vconstr - = Vertex<input_track_t>(Vector3D(0., 0., 0.))) - : geoContext(gctx), magFieldContext(mctx), vertexConstraint(vconstr) - { - } + const Vertex<input_track_t>& vconstr = + Vertex<input_track_t>(Vector3D(0., 0., 0.))) + : geoContext(gctx), magFieldContext(mctx), vertexConstraint(vconstr) {} /// Context object for the geometry std::reference_wrapper<const GeometryContext> geoContext; @@ -54,9 +50,8 @@ struct VertexFitterOptions /// @tparam input_track_t Track object type /// @tparam propagator_t Propagator type template <typename input_track_t, typename propagator_t> -class IVertexFitter -{ -public: +class IVertexFitter { + public: /// @brief Default virtual destructor virtual ~IVertexFitter() = default; @@ -64,8 +59,8 @@ public: /// @param vFitterOptions Vertex fitter options /// /// @return Fitted vertex - virtual Result<Vertex<input_track_t>> - fit(const std::vector<input_track_t>& paramVector, + virtual Result<Vertex<input_track_t>> fit( + const std::vector<input_track_t>& paramVector, const VertexFitterOptions<input_track_t>& vFitterOptions) const = 0; }; diff --git a/Core/include/Acts/Vertexing/LinearizedTrack.hpp b/Core/include/Acts/Vertexing/LinearizedTrack.hpp index 94c27e723d6aa2852908aaec5238593884a5aaf0..44a0c24eb1eb91026c430d2071c4ed37294f9882 100644 --- a/Core/include/Acts/Vertexing/LinearizedTrack.hpp +++ b/Core/include/Acts/Vertexing/LinearizedTrack.hpp @@ -27,9 +27,7 @@ namespace Acts { /// "momentumJacobian" respectively. /// -struct LinearizedTrack -{ - +struct LinearizedTrack { /// @brief Constructor taking perigee parameters and covariance matrix /// of track propagated to closest approach (PCA) of linearization point, /// position and momentum Jacobian and const term. @@ -46,32 +44,29 @@ struct LinearizedTrack LinearizedTrack() = default; - LinearizedTrack(const ActsVectorD<5>& paramsAtPCA, + LinearizedTrack(const ActsVectorD<5>& paramsAtPCA, const ActsSymMatrixD<5>& parCovarianceAtPCA, - const Vector3D& linPoint, + const Vector3D& linPoint, const ActsMatrixD<5, 3>& posJacobian, const ActsMatrixD<5, 3>& momJacobian, - const Vector3D& position, - const Vector3D& momentum, + const Vector3D& position, const Vector3D& momentum, const ActsVectorD<5>& constTerm) - : parametersAtPCA(paramsAtPCA) - , covarianceAtPCA(parCovarianceAtPCA) - , linearizationPoint(linPoint) - , positionJacobian(posJacobian) - , momentumJacobian(momJacobian) - , positionAtPCA(position) - , momentumAtPCA(momentum) - , constantTerm(constTerm) - { - } + : parametersAtPCA(paramsAtPCA), + covarianceAtPCA(parCovarianceAtPCA), + linearizationPoint(linPoint), + positionJacobian(posJacobian), + momentumJacobian(momJacobian), + positionAtPCA(position), + momentumAtPCA(momentum), + constantTerm(constTerm) {} - ActsVectorD<5> parametersAtPCA{ActsVectorD<5>::Zero()}; + ActsVectorD<5> parametersAtPCA{ActsVectorD<5>::Zero()}; ActsSymMatrixD<5> covarianceAtPCA{ActsSymMatrixD<5>::Zero()}; - Vector3D linearizationPoint{Vector3D::Zero()}; + Vector3D linearizationPoint{Vector3D::Zero()}; ActsMatrixD<5, 3> positionJacobian{ActsMatrixD<5, 3>::Zero()}; ActsMatrixD<5, 3> momentumJacobian{ActsMatrixD<5, 3>::Zero()}; - Vector3D positionAtPCA{Vector3D::Zero()}; - Vector3D momentumAtPCA{Vector3D::Zero()}; + Vector3D positionAtPCA{Vector3D::Zero()}; + Vector3D momentumAtPCA{Vector3D::Zero()}; ActsVectorD<5> constantTerm{ActsVectorD<5>::Zero()}; }; diff --git a/Core/include/Acts/Vertexing/LinearizedTrackFactory.hpp b/Core/include/Acts/Vertexing/LinearizedTrackFactory.hpp index 3c7f0a3fc3d522a1165968f08c441135da4f8bdb..f9b1a0a59b4205a5666d89fd86d1e42f6539d174 100644 --- a/Core/include/Acts/Vertexing/LinearizedTrackFactory.hpp +++ b/Core/include/Acts/Vertexing/LinearizedTrackFactory.hpp @@ -40,15 +40,12 @@ namespace Acts { /// @tparam propagator_t Propagator type /// @tparam action_list_t Propagator action list type /// @tparam aborter_list_t Propagator aborter list type -template <typename bfield_t, - typename propagator_t, - typename action_list_t = ActionList<>, +template <typename bfield_t, typename propagator_t, + typename action_list_t = ActionList<>, typename aborter_list_t = AbortList<>> -class LinearizedTrackFactory -{ -public: - struct Config - { +class LinearizedTrackFactory { + public: + struct Config { bfield_t bField; Config(const bfield_t& bIn) : bField(bIn){}; }; @@ -68,14 +65,13 @@ public: /// @param propagator Propagator /// /// @return Linearized track - Result<LinearizedTrack> - linearizeTrack(const GeometryContext& gctx, - const MagneticFieldContext& mctx, - const BoundParameters* params, - const Vector3D& linPoint, - const propagator_t& propagator) const; + Result<LinearizedTrack> linearizeTrack(const GeometryContext& gctx, + const MagneticFieldContext& mctx, + const BoundParameters* params, + const Vector3D& linPoint, + const propagator_t& propagator) const; -private: + private: // Configuration object Config m_cfg; }; diff --git a/Core/include/Acts/Vertexing/LinearizedTrackFactory.ipp b/Core/include/Acts/Vertexing/LinearizedTrackFactory.ipp index fbcf7da5615cd862627c3cb9eb49a4bfce642916..dd368afa4da3f016878729133f234f32d8e06b05 100644 --- a/Core/include/Acts/Vertexing/LinearizedTrackFactory.ipp +++ b/Core/include/Acts/Vertexing/LinearizedTrackFactory.ipp @@ -8,32 +8,26 @@ #include "Acts/Surfaces/PerigeeSurface.hpp" -template <typename bfield_t, - typename propagator_t, - typename action_list_t, +template <typename bfield_t, typename propagator_t, typename action_list_t, typename aborter_list_t> -Acts::Result<Acts::LinearizedTrack> -Acts::LinearizedTrackFactory<bfield_t, - propagator_t, - action_list_t, - aborter_list_t>:: - linearizeTrack(const GeometryContext& gctx, - const MagneticFieldContext& mctx, - const BoundParameters* params, - const Vector3D& linPoint, - const propagator_t& propagator) const -{ +Acts::Result<Acts::LinearizedTrack> Acts::LinearizedTrackFactory< + bfield_t, propagator_t, action_list_t, + aborter_list_t>::linearizeTrack(const GeometryContext& gctx, + const MagneticFieldContext& mctx, + const BoundParameters* params, + const Vector3D& linPoint, + const propagator_t& propagator) const { if (params == nullptr) { return LinearizedTrack(); } - const std::shared_ptr<PerigeeSurface> perigeeSurface - = Surface::makeShared<PerigeeSurface>(linPoint); + const std::shared_ptr<PerigeeSurface> perigeeSurface = + Surface::makeShared<PerigeeSurface>(linPoint); // Variables to store track params and position at PCA to linPoint - ActsVectorD<5> paramsAtPCA; - Vector3D positionAtPCA; + ActsVectorD<5> paramsAtPCA; + Vector3D positionAtPCA; ActsSymMatrixD<5> parCovarianceAtPCA; PropagatorOptions<action_list_t, aborter_list_t> pOptions(gctx, mctx); @@ -42,21 +36,21 @@ Acts::LinearizedTrackFactory<bfield_t, auto result = propagator.propagate(*params, *perigeeSurface, pOptions); if (result.ok()) { const auto& propRes = *result; - paramsAtPCA = propRes.endParameters->parameters(); - positionAtPCA = propRes.endParameters->position(); - parCovarianceAtPCA = *propRes.endParameters->covariance(); + paramsAtPCA = propRes.endParameters->parameters(); + positionAtPCA = propRes.endParameters->position(); + parCovarianceAtPCA = *propRes.endParameters->covariance(); } else { return result.error(); } // phiV and functions - double phiV = paramsAtPCA(ParID_t::ePHI); + double phiV = paramsAtPCA(ParID_t::ePHI); double sinPhiV = std::sin(phiV); double cosPhiV = std::cos(phiV); // theta and functions - double th = paramsAtPCA(ParID_t::eTHETA); + double th = paramsAtPCA(ParID_t::eTHETA); double sinTh = std::sin(th); double tanTh = std::tan(th); @@ -79,10 +73,10 @@ Acts::LinearizedTrackFactory<bfield_t, } // Eq. 5.34 in Ref(1) (see .hpp) - double X = positionAtPCA(0) - linPoint.x() + rho * sinPhiV; - double Y = positionAtPCA(1) - linPoint.y() - rho * cosPhiV; + double X = positionAtPCA(0) - linPoint.x() + rho * sinPhiV; + double Y = positionAtPCA(1) - linPoint.y() - rho * cosPhiV; double S2 = (X * X + Y * Y); - double S = std::sqrt(S2); + double S = std::sqrt(S2); /// F(V, p_i) at PCA in Billoir paper /// (see FullBilloirVertexFitter.hpp for paper reference, @@ -104,8 +98,8 @@ Acts::LinearizedTrackFactory<bfield_t, // Eq. 5.33 in Ref(1) (see .hpp) predParamsAtPCA[0] = rho - sgnH * S; - predParamsAtPCA[1] - = positionAtPCA[eZ] - linPoint.z() + rho * (phiV - phiAtPCA) / tanTh; + predParamsAtPCA[1] = + positionAtPCA[eZ] - linPoint.z() + rho * (phiV - phiAtPCA) / tanTh; predParamsAtPCA[2] = phiAtPCA; predParamsAtPCA[3] = th; predParamsAtPCA[4] = qOvP; @@ -130,8 +124,8 @@ Acts::LinearizedTrackFactory<bfield_t, ActsMatrixD<5, 3> momentumJacobian; momentumJacobian.setZero(); - double R = X * cosPhiV + Y * sinPhiV; - double Q = X * sinPhiV - Y * cosPhiV; + double R = X * cosPhiV + Y * sinPhiV; + double Q = X * sinPhiV - Y * cosPhiV; double dPhi = phiAtPCA - phiV; // First row @@ -157,15 +151,11 @@ Acts::LinearizedTrackFactory<bfield_t, momentumJacobian(4, 2) = 1.; // const term F(V_0, p_0) in Talyor expansion - ActsVectorD<5> constTerm = predParamsAtPCA - positionJacobian * positionAtPCA - - momentumJacobian * momentumAtPCA; - - return LinearizedTrack(paramsAtPCA, - parCovarianceAtPCA, - linPoint, - positionJacobian, - momentumJacobian, - positionAtPCA, - momentumAtPCA, - constTerm); + ActsVectorD<5> constTerm = predParamsAtPCA - + positionJacobian * positionAtPCA - + momentumJacobian * momentumAtPCA; + + return LinearizedTrack(paramsAtPCA, parCovarianceAtPCA, linPoint, + positionJacobian, momentumJacobian, positionAtPCA, + momentumAtPCA, constTerm); } diff --git a/Core/include/Acts/Vertexing/TrackAtVertex.hpp b/Core/include/Acts/Vertexing/TrackAtVertex.hpp index 278c3c300115d064eca112c79dbff1f71be1b163..11a9bb920c616d2b42b71d8436147f9df95d36c8 100644 --- a/Core/include/Acts/Vertexing/TrackAtVertex.hpp +++ b/Core/include/Acts/Vertexing/TrackAtVertex.hpp @@ -19,8 +19,7 @@ namespace Acts { /// @tparam input_track_t Track object type template <typename input_track_t> -struct TrackAtVertex -{ +struct TrackAtVertex { /// Deleted default constructor TrackAtVertex() = delete; @@ -29,14 +28,11 @@ struct TrackAtVertex /// @param chi2perTrack Chi2 of track /// @param paramsAtVertex Fitted perigee parameter /// @param originalParams Original perigee parameter - TrackAtVertex(double chi2perTrack, - const BoundParameters& paramsAtVertex, - const input_track_t& originalTrack) - : m_chi2Track(chi2perTrack) - , m_fittedParams(paramsAtVertex) - , m_originalTrack(originalTrack) - { - } + TrackAtVertex(double chi2perTrack, const BoundParameters& paramsAtVertex, + const input_track_t& originalTrack) + : m_chi2Track(chi2perTrack), + m_fittedParams(paramsAtVertex), + m_originalTrack(originalTrack) {} /// Chi2 of track double m_chi2Track; diff --git a/Core/include/Acts/Vertexing/Vertex.hpp b/Core/include/Acts/Vertexing/Vertex.hpp index 724c9d626a78465e8317f130d3169d886fdcd15c..7f9b22d51364cf7c185ec5f7fd4647ab8424e0c9 100644 --- a/Core/include/Acts/Vertexing/Vertex.hpp +++ b/Core/include/Acts/Vertexing/Vertex.hpp @@ -20,10 +20,8 @@ namespace Acts { /// @tparam input_track_t Track object type /// template <typename input_track_t> -class Vertex -{ - -public: +class Vertex { + public: /// @brief Default constructor Vertex() = default; @@ -37,48 +35,40 @@ public: /// @param position Vertex position /// @param covariance Position covariance matrix /// @param tracks Vector of tracks associated with the vertex - Vertex(const Vector3D& position, - const ActsSymMatrixD<3>& covariance, + Vertex(const Vector3D& position, const ActsSymMatrixD<3>& covariance, std::vector<TrackAtVertex<input_track_t>>& tracks); /// @return Returns 3-position - const Vector3D& - position() const; + const Vector3D& position() const; /// @return Returns position covariance - const ActsSymMatrixD<3>& - covariance() const; + const ActsSymMatrixD<3>& covariance() const; /// @return Returns vector of tracks associated with the vertex - const std::vector<TrackAtVertex<input_track_t>>& - tracks() const; + const std::vector<TrackAtVertex<input_track_t>>& tracks() const; /// @return Returns pair of (chi2, numberDoF) - std::pair<double, double> - fitQuality() const; + std::pair<double, double> fitQuality() const; /// @param position Vertex position - void - setPosition(const Vector3D& position); + void setPosition(const Vector3D& position); /// @param covariance Position covariance matrix - void - setCovariance(const ActsSymMatrixD<3>& covariance); + void setCovariance(const ActsSymMatrixD<3>& covariance); /// @param tracks Vector of tracks at vertex - void - setTracksAtVertex(const std::vector<TrackAtVertex<input_track_t>>& tracks); + void setTracksAtVertex( + const std::vector<TrackAtVertex<input_track_t>>& tracks); /// @param chiSquared Chi2 of fit /// @param numberDoF Number of degrees of freedom - void - setFitQuality(double chiSquared, double numberDoF); + void setFitQuality(double chiSquared, double numberDoF); -private: - Vector3D m_position = Vector3D(0., 0., 0.); + private: + Vector3D m_position = Vector3D(0., 0., 0.); ActsSymMatrixD<3> m_covariance = ActsSymMatrixD<3>::Zero(); std::vector<TrackAtVertex<input_track_t>> m_tracksAtVertex; double m_chiSquared = std::numeric_limits<double>::max(); // chi2 of the fit - double m_numberDoF = 0; // number of degrees of freedom + double m_numberDoF = 0; // number of degrees of freedom }; } // namespace Acts diff --git a/Core/include/Acts/Vertexing/Vertex.ipp b/Core/include/Acts/Vertexing/Vertex.ipp index 8deffd93853bb6fc96fbd42c50a2c7089bab89c1..97b148b8a0d2533cac9236f61d12422dde6c4883 100644 --- a/Core/include/Acts/Vertexing/Vertex.ipp +++ b/Core/include/Acts/Vertexing/Vertex.ipp @@ -8,75 +8,57 @@ template <typename input_track_t> Acts::Vertex<input_track_t>::Vertex(const Vector3D& position) - : m_position(position) -{ -} + : m_position(position) {} template <typename input_track_t> Acts::Vertex<input_track_t>::Vertex( - const Vector3D& position, - const ActsSymMatrixD<3>& covariance, + const Vector3D& position, const ActsSymMatrixD<3>& covariance, std::vector<TrackAtVertex<input_track_t>>& tracks) - : m_position(position) - , m_covariance(covariance) - , m_tracksAtVertex(std::move(tracks)) -{ -} + : m_position(position), + m_covariance(covariance), + m_tracksAtVertex(std::move(tracks)) {} template <typename input_track_t> -const Acts::Vector3D& -Acts::Vertex<input_track_t>::position() const -{ +const Acts::Vector3D& Acts::Vertex<input_track_t>::position() const { return m_position; } template <typename input_track_t> -const Acts::ActsSymMatrixD<3>& -Acts::Vertex<input_track_t>::covariance() const -{ +const Acts::ActsSymMatrixD<3>& Acts::Vertex<input_track_t>::covariance() const { return m_covariance; } template <typename input_track_t> const std::vector<Acts::TrackAtVertex<input_track_t>>& -Acts::Vertex<input_track_t>::tracks() const -{ +Acts::Vertex<input_track_t>::tracks() const { return m_tracksAtVertex; } template <typename input_track_t> -std::pair<double, double> -Acts::Vertex<input_track_t>::fitQuality() const -{ +std::pair<double, double> Acts::Vertex<input_track_t>::fitQuality() const { return std::pair<double, double>(m_chiSquared, m_numberDoF); } template <typename input_track_t> -void -Acts::Vertex<input_track_t>::setPosition(const Vector3D& position) -{ +void Acts::Vertex<input_track_t>::setPosition(const Vector3D& position) { m_position = position; } template <typename input_track_t> -void -Acts::Vertex<input_track_t>::setCovariance(const ActsSymMatrixD<3>& covariance) -{ +void Acts::Vertex<input_track_t>::setCovariance( + const ActsSymMatrixD<3>& covariance) { m_covariance = covariance; } template <typename input_track_t> -void -Acts::Vertex<input_track_t>::setTracksAtVertex( - const std::vector<TrackAtVertex<input_track_t>>& tracks) -{ +void Acts::Vertex<input_track_t>::setTracksAtVertex( + const std::vector<TrackAtVertex<input_track_t>>& tracks) { m_tracksAtVertex = std::move(tracks); } template <typename input_track_t> -void -Acts::Vertex<input_track_t>::setFitQuality(double chiSquared, double numberDoF) -{ +void Acts::Vertex<input_track_t>::setFitQuality(double chiSquared, + double numberDoF) { m_chiSquared = chiSquared; - m_numberDoF = numberDoF; + m_numberDoF = numberDoF; } diff --git a/Core/include/Acts/Vertexing/VertexingError.hpp b/Core/include/Acts/Vertexing/VertexingError.hpp index e6621ea56e8fba5c0350c80727c5a9b2e6756f05..20c4d1d42fab23a9e59e84f8499205bd523523e0 100644 --- a/Core/include/Acts/Vertexing/VertexingError.hpp +++ b/Core/include/Acts/Vertexing/VertexingError.hpp @@ -17,49 +17,36 @@ namespace Acts { enum class VertexingError { NumericFailure = 1 }; namespace detail { - // Define a custom error code category derived from std::error_category - class VertexingErrorCategory : public std::error_category - { - public: - // Return a short descriptive name for the category - const char* - name() const noexcept final - { - return "VertexingError"; - } - // Return what each enum means in text - std::string - message(int c) const final - { - switch (static_cast<VertexingError>(c)) { +// Define a custom error code category derived from std::error_category +class VertexingErrorCategory : public std::error_category { + public: + // Return a short descriptive name for the category + const char* name() const noexcept final { return "VertexingError"; } + // Return what each enum means in text + std::string message(int c) const final { + switch (static_cast<VertexingError>(c)) { case VertexingError::NumericFailure: return "Numeric failure in calculation."; default: return "unknown"; - } } - }; -} + } +}; +} // namespace detail // Declare a global function returning a static instance of the custom category -extern inline const detail::VertexingErrorCategory& -VertexingErrorCategory() -{ +extern inline const detail::VertexingErrorCategory& VertexingErrorCategory() { static detail::VertexingErrorCategory c; return c; } -inline std::error_code -make_error_code(Acts::VertexingError e) -{ +inline std::error_code make_error_code(Acts::VertexingError e) { return {static_cast<int>(e), Acts::VertexingErrorCategory()}; } -} +} // namespace Acts namespace std { // register with STL template <> -struct is_error_code_enum<Acts::VertexingError> : std::true_type -{ -}; -} +struct is_error_code_enum<Acts::VertexingError> : std::true_type {}; +} // namespace std diff --git a/Core/src/EventData/TrackParametersBase.cpp b/Core/src/EventData/TrackParametersBase.cpp index 9db530808ecd3da121b4224e83b5f8270565146b..d11a119199242874df2019b6ccc312b299f8d339 100644 --- a/Core/src/EventData/TrackParametersBase.cpp +++ b/Core/src/EventData/TrackParametersBase.cpp @@ -13,12 +13,10 @@ #include "Acts/EventData/TrackParametersBase.hpp" namespace Acts { -std::ostream& -TrackParametersBase::print(std::ostream& sl) const -{ +std::ostream& TrackParametersBase::print(std::ostream& sl) const { // set stream output format auto old_precision = sl.precision(7); - auto old_flags = sl.setf(std::ios::fixed); + auto old_flags = sl.setf(std::ios::fixed); sl << " * TrackParameters:" << std::endl; sl << parameters() << std::endl; diff --git a/Core/src/Geometry/AbstractVolume.cpp b/Core/src/Geometry/AbstractVolume.cpp index 560bd9102d6f606b19fcd03f35e9c139baf6f7d1..3c573908bd4234c40f4f9a6b74c185c6664469dc 100644 --- a/Core/src/Geometry/AbstractVolume.cpp +++ b/Core/src/Geometry/AbstractVolume.cpp @@ -18,43 +18,39 @@ #include "Acts/Surfaces/Surface.hpp" Acts::AbstractVolume::AbstractVolume( - std::shared_ptr<const Transform3D> htrans, + std::shared_ptr<const Transform3D> htrans, std::shared_ptr<const VolumeBounds> volbounds) - : Volume(std::move(htrans), std::move(volbounds)) -{ + : Volume(std::move(htrans), std::move(volbounds)) { createBoundarySurfaces(); } Acts::AbstractVolume::~AbstractVolume() = default; const std::vector<Acts::BoundarySurfacePtr>& -Acts::AbstractVolume::boundarySurfaces() const -{ +Acts::AbstractVolume::boundarySurfaces() const { return m_boundarySurfaces; } -void -Acts::AbstractVolume::createBoundarySurfaces() -{ +void Acts::AbstractVolume::createBoundarySurfaces() { // transform Surfaces To BoundarySurfaces - std::vector<std::shared_ptr<const Surface>> surfaces - = Volume::volumeBounds().decomposeToSurfaces(m_transform.get()); + std::vector<std::shared_ptr<const Surface>> surfaces = + Volume::volumeBounds().decomposeToSurfaces(m_transform.get()); // counter to flip the inner/outer position for Cylinders - int sfCounter = 0; - size_t sfNumber = surfaces.size(); + int sfCounter = 0; + size_t sfNumber = surfaces.size(); for (auto& sf : surfaces) { // flip inner/outer for cylinders - AbstractVolume* inner - = (sf->type() == Surface::Cylinder && sfCounter == 3 && sfNumber > 3) - ? nullptr - : this; + AbstractVolume* inner = + (sf->type() == Surface::Cylinder && sfCounter == 3 && sfNumber > 3) + ? nullptr + : this; AbstractVolume* outer = (inner) != nullptr ? nullptr : this; // create the boundary surface - BoundarySurfacePtr bSurface - = std::make_shared<const BoundarySurfaceT<AbstractVolume>>( - std::move(sf), inner, outer); + BoundarySurfacePtr bSurface = + std::make_shared<const BoundarySurfaceT<AbstractVolume>>(std::move(sf), + inner, outer); m_boundarySurfaces.push_back(bSurface); } } diff --git a/Core/src/Geometry/BinUtility.cpp b/Core/src/Geometry/BinUtility.cpp index f3aa24f25950f40c4e3e27bc8fe765d17ef7ebb1..396688507c020ad0727d9610d1de1ba1b1dec61d 100644 --- a/Core/src/Geometry/BinUtility.cpp +++ b/Core/src/Geometry/BinUtility.cpp @@ -17,8 +17,6 @@ #include <iostream> /**Overload of << operator for std::ostream for debug output*/ -std::ostream& -Acts::operator<<(std::ostream& sl, const BinUtility& bgen) -{ +std::ostream& Acts::operator<<(std::ostream& sl, const BinUtility& bgen) { return bgen.toStream(sl); } diff --git a/Core/src/Geometry/ConeLayer.cpp b/Core/src/Geometry/ConeLayer.cpp index 4d3b1fd943f6145524b99e8f20a8bb647391c2ce..f5c2789696db457583dcdeb087f833f1c5625e16 100644 --- a/Core/src/Geometry/ConeLayer.cpp +++ b/Core/src/Geometry/ConeLayer.cpp @@ -17,25 +17,19 @@ #include "Acts/Surfaces/ConeBounds.hpp" #include "Acts/Utilities/Definitions.hpp" -Acts::ConeLayer::ConeLayer(std::shared_ptr<const Transform3D> transform, - std::shared_ptr<const ConeBounds> cbounds, - std::unique_ptr<SurfaceArray> surfaceArray, - double thickness, +Acts::ConeLayer::ConeLayer(std::shared_ptr<const Transform3D> transform, + std::shared_ptr<const ConeBounds> cbounds, + std::unique_ptr<SurfaceArray> surfaceArray, + double thickness, std::unique_ptr<ApproachDescriptor> ade, - LayerType laytyp) - : ConeSurface(std::move(transform), std::move(cbounds)) - , Layer(std::move(surfaceArray), thickness, std::move(ade), laytyp) -{ -} + LayerType laytyp) + : ConeSurface(std::move(transform), std::move(cbounds)), + Layer(std::move(surfaceArray), thickness, std::move(ade), laytyp) {} -const Acts::ConeSurface& -Acts::ConeLayer::surfaceRepresentation() const -{ +const Acts::ConeSurface& Acts::ConeLayer::surfaceRepresentation() const { return (*this); } -Acts::ConeSurface& -Acts::ConeLayer::surfaceRepresentation() -{ +Acts::ConeSurface& Acts::ConeLayer::surfaceRepresentation() { return (*this); } diff --git a/Core/src/Geometry/CuboidVolumeBounds.cpp b/Core/src/Geometry/CuboidVolumeBounds.cpp index 1e0396d43d8e2e4d6bfd554daefccdb396259b73..7492c0520781c63b99a4aae0a0251f3572171375 100644 --- a/Core/src/Geometry/CuboidVolumeBounds.cpp +++ b/Core/src/Geometry/CuboidVolumeBounds.cpp @@ -18,19 +18,15 @@ #include "Acts/Surfaces/Surface.hpp" Acts::CuboidVolumeBounds::CuboidVolumeBounds() - : VolumeBounds(), m_valueStore(bv_length, 0.) -{ -} + : VolumeBounds(), m_valueStore(bv_length, 0.) {} -Acts::CuboidVolumeBounds::CuboidVolumeBounds(double halex, - double haley, +Acts::CuboidVolumeBounds::CuboidVolumeBounds(double halex, double haley, double halez) - : VolumeBounds() - , m_valueStore(bv_length, 0.) - , m_xyBounds(nullptr) - , m_yzBounds(nullptr) - , m_zxBounds(nullptr) -{ + : VolumeBounds(), + m_valueStore(bv_length, 0.), + m_xyBounds(nullptr), + m_yzBounds(nullptr), + m_zxBounds(nullptr) { m_valueStore.at(bv_halfX) = halex; m_valueStore.at(bv_halfY) = haley; m_valueStore.at(bv_halfZ) = halez; @@ -41,82 +37,78 @@ Acts::CuboidVolumeBounds::CuboidVolumeBounds(double halex, } Acts::CuboidVolumeBounds::CuboidVolumeBounds(const CuboidVolumeBounds& bobo) - : VolumeBounds() - , m_valueStore(bobo.m_valueStore) - , m_xyBounds(bobo.m_xyBounds) - , m_yzBounds(bobo.m_yzBounds) - , m_zxBounds(bobo.m_zxBounds) -{ -} + : VolumeBounds(), + m_valueStore(bobo.m_valueStore), + m_xyBounds(bobo.m_xyBounds), + m_yzBounds(bobo.m_yzBounds), + m_zxBounds(bobo.m_zxBounds) {} Acts::CuboidVolumeBounds::~CuboidVolumeBounds() = default; -Acts::CuboidVolumeBounds& -Acts::CuboidVolumeBounds::operator=(const CuboidVolumeBounds& bobo) -{ +Acts::CuboidVolumeBounds& Acts::CuboidVolumeBounds::operator=( + const CuboidVolumeBounds& bobo) { if (this != &bobo) { m_valueStore = bobo.m_valueStore; - m_xyBounds = bobo.m_xyBounds; - m_yzBounds = bobo.m_yzBounds; - m_zxBounds = bobo.m_zxBounds; + m_xyBounds = bobo.m_xyBounds; + m_yzBounds = bobo.m_yzBounds; + m_zxBounds = bobo.m_zxBounds; } return *this; } std::vector<std::shared_ptr<const Acts::Surface>> Acts::CuboidVolumeBounds::decomposeToSurfaces( - const Transform3D* transformPtr) const -{ + const Transform3D* transformPtr) const { // the transform - apply when given - Transform3D transform - = (transformPtr == nullptr) ? Transform3D::Identity() : (*transformPtr); + Transform3D transform = + (transformPtr == nullptr) ? Transform3D::Identity() : (*transformPtr); const Transform3D* tTransform = nullptr; std::vector<std::shared_ptr<const Acts::Surface>> rSurfaces; rSurfaces.reserve(6); // face surfaces xy ------------------------------------- // (1) - at negative local z - tTransform - = new Transform3D(transform * AngleAxis3D(M_PI, Vector3D(0., 1., 0.)) - * Translation3D(Vector3D(0., 0., halflengthZ()))); + tTransform = + new Transform3D(transform * AngleAxis3D(M_PI, Vector3D(0., 1., 0.)) * + Translation3D(Vector3D(0., 0., halflengthZ()))); rSurfaces.push_back(Surface::makeShared<PlaneSurface>( std::shared_ptr<const Transform3D>(tTransform), m_xyBounds)); // (2) - at positive local z - tTransform = new Transform3D( - transform * Translation3D(Vector3D(0., 0., halflengthZ()))); + tTransform = new Transform3D(transform * + Translation3D(Vector3D(0., 0., halflengthZ()))); rSurfaces.push_back(Surface::makeShared<PlaneSurface>( std::shared_ptr<const Transform3D>(tTransform), m_xyBounds)); // face surfaces yz ------------------------------------- // transmute cyclical // (3) - at negative local x - tTransform - = new Transform3D(transform * AngleAxis3D(M_PI, Vector3D(0., 0., 1.)) - * Translation3D(Vector3D(halflengthX(), 0., 0)) - * AngleAxis3D(0.5 * M_PI, Vector3D(0., 1., 0)) - * AngleAxis3D(0.5 * M_PI, Vector3D(0., 0., 1.))); + tTransform = + new Transform3D(transform * AngleAxis3D(M_PI, Vector3D(0., 0., 1.)) * + Translation3D(Vector3D(halflengthX(), 0., 0)) * + AngleAxis3D(0.5 * M_PI, Vector3D(0., 1., 0)) * + AngleAxis3D(0.5 * M_PI, Vector3D(0., 0., 1.))); rSurfaces.push_back(Surface::makeShared<PlaneSurface>( std::shared_ptr<const Transform3D>(tTransform), m_yzBounds)); // (4) - at positive local x - tTransform = new Transform3D(transform - * Translation3D(Vector3D(halflengthX(), 0., 0.)) - * AngleAxis3D(0.5 * M_PI, Vector3D(0., 1., 0.)) - * AngleAxis3D(0.5 * M_PI, Vector3D(0., 0., 1.))); + tTransform = new Transform3D(transform * + Translation3D(Vector3D(halflengthX(), 0., 0.)) * + AngleAxis3D(0.5 * M_PI, Vector3D(0., 1., 0.)) * + AngleAxis3D(0.5 * M_PI, Vector3D(0., 0., 1.))); rSurfaces.push_back(Surface::makeShared<PlaneSurface>( std::shared_ptr<const Transform3D>(tTransform), m_yzBounds)); // face surfaces zx ------------------------------------- // (5) - at negative local y - tTransform - = new Transform3D(transform * AngleAxis3D(M_PI, Vector3D(1., 0., 0.)) - * Translation3D(Vector3D(0., halflengthY(), 0.)) - * AngleAxis3D(-0.5 * M_PI, Vector3D(0., 1., 0.)) - * AngleAxis3D(-0.5 * M_PI, Vector3D(1., 0., 0.))); + tTransform = + new Transform3D(transform * AngleAxis3D(M_PI, Vector3D(1., 0., 0.)) * + Translation3D(Vector3D(0., halflengthY(), 0.)) * + AngleAxis3D(-0.5 * M_PI, Vector3D(0., 1., 0.)) * + AngleAxis3D(-0.5 * M_PI, Vector3D(1., 0., 0.))); rSurfaces.push_back(Surface::makeShared<PlaneSurface>( std::shared_ptr<const Transform3D>(tTransform), m_zxBounds)); // (6) - at positive local y - tTransform = new Transform3D( - transform * Translation3D(Vector3D(0., halflengthY(), 0.)) - * AngleAxis3D(-0.5 * M_PI, Vector3D(0., 1., 0.)) - * AngleAxis3D(-0.5 * M_PI, Vector3D(1., 0., 0.))); + tTransform = new Transform3D(transform * + Translation3D(Vector3D(0., halflengthY(), 0.)) * + AngleAxis3D(-0.5 * M_PI, Vector3D(0., 1., 0.)) * + AngleAxis3D(-0.5 * M_PI, Vector3D(1., 0., 0.))); rSurfaces.push_back(Surface::makeShared<PlaneSurface>( std::shared_ptr<const Transform3D>(tTransform), m_zxBounds)); // return the surfaces @@ -124,29 +116,24 @@ Acts::CuboidVolumeBounds::decomposeToSurfaces( } std::shared_ptr<const Acts::RectangleBounds> -Acts::CuboidVolumeBounds::faceXYRectangleBounds() const -{ +Acts::CuboidVolumeBounds::faceXYRectangleBounds() const { return std::make_shared<const RectangleBounds>(m_valueStore.at(bv_halfX), m_valueStore.at(bv_halfY)); } std::shared_ptr<const Acts::RectangleBounds> -Acts::CuboidVolumeBounds::faceYZRectangleBounds() const -{ +Acts::CuboidVolumeBounds::faceYZRectangleBounds() const { return std::make_shared<const RectangleBounds>(m_valueStore.at(bv_halfY), m_valueStore.at(bv_halfZ)); } std::shared_ptr<const Acts::RectangleBounds> -Acts::CuboidVolumeBounds::faceZXRectangleBounds() const -{ +Acts::CuboidVolumeBounds::faceZXRectangleBounds() const { return std::make_shared<const RectangleBounds>(m_valueStore.at(bv_halfZ), m_valueStore.at(bv_halfX)); } // ostream operator overload -std::ostream& -Acts::CuboidVolumeBounds::toStream(std::ostream& sl) const -{ +std::ostream& Acts::CuboidVolumeBounds::toStream(std::ostream& sl) const { return dumpT(sl); } diff --git a/Core/src/Geometry/CuboidVolumeBuilder.cpp b/Core/src/Geometry/CuboidVolumeBuilder.cpp index 5c721a30ce58144f906e7a85ea53e98ba83d20c8..c27d7509ac55a0012bafeff62c9718b2277b41cd 100644 --- a/Core/src/Geometry/CuboidVolumeBuilder.cpp +++ b/Core/src/Geometry/CuboidVolumeBuilder.cpp @@ -28,8 +28,7 @@ std::shared_ptr<const Acts::PlaneSurface> Acts::CuboidVolumeBuilder::buildSurface( const GeometryContext& /*gctx*/, - const CuboidVolumeBuilder::SurfaceConfig& cfg) const -{ + const CuboidVolumeBuilder::SurfaceConfig& cfg) const { std::shared_ptr<PlaneSurface> surface; // Build transformation @@ -41,8 +40,7 @@ Acts::CuboidVolumeBuilder::buildSurface( surface = Surface::makeShared<PlaneSurface>( cfg.rBounds, *(cfg.detElementConstructor(std::make_shared<const Transform3D>(trafo), - cfg.rBounds, - cfg.thickness))); + cfg.rBounds, cfg.thickness))); } else { surface = Surface::makeShared<PlaneSurface>( std::make_shared<const Transform3D>(trafo), cfg.rBounds); @@ -51,11 +49,9 @@ Acts::CuboidVolumeBuilder::buildSurface( return surface; } -std::shared_ptr<const Acts::Layer> -Acts::CuboidVolumeBuilder::buildLayer( - const GeometryContext& gctx, - Acts::CuboidVolumeBuilder::LayerConfig& cfg) const -{ +std::shared_ptr<const Acts::Layer> Acts::CuboidVolumeBuilder::buildLayer( + const GeometryContext& gctx, + Acts::CuboidVolumeBuilder::LayerConfig& cfg) const { // Build the surface if (cfg.surface == nullptr) { cfg.surface = buildSurface(gctx, cfg.surfaceCfg); @@ -68,20 +64,14 @@ Acts::CuboidVolumeBuilder::buildLayer( lCfg.surfaceArrayCreator = std::make_shared<const SurfaceArrayCreator>(); LayerCreator layerCreator(lCfg); - return layerCreator.planeLayer(gctx, - {cfg.surface}, - cfg.binsY, - cfg.binsZ, - BinningValue::binX, - boost::none, + return layerCreator.planeLayer(gctx, {cfg.surface}, cfg.binsY, cfg.binsZ, + BinningValue::binX, boost::none, std::make_shared<const Transform3D>(trafo)); } -std::pair<double, double> -Acts::CuboidVolumeBuilder::binningRange( +std::pair<double, double> Acts::CuboidVolumeBuilder::binningRange( const GeometryContext& /*gctx*/, - const Acts::CuboidVolumeBuilder::VolumeConfig& cfg) const -{ + const Acts::CuboidVolumeBuilder::VolumeConfig& cfg) const { // Construct return value std::pair<double, double> minMax = std::make_pair( std::numeric_limits<double>::max(), -std::numeric_limits<double>::max()); @@ -97,11 +87,9 @@ Acts::CuboidVolumeBuilder::binningRange( return minMax; } -std::shared_ptr<Acts::TrackingVolume> -Acts::CuboidVolumeBuilder::buildVolume( - const GeometryContext& gctx, - Acts::CuboidVolumeBuilder::VolumeConfig& cfg) const -{ +std::shared_ptr<Acts::TrackingVolume> Acts::CuboidVolumeBuilder::buildVolume( + const GeometryContext& gctx, + Acts::CuboidVolumeBuilder::VolumeConfig& cfg) const { // Build transformation Transform3D trafo(Transform3D::Identity()); trafo.translation() = cfg.position; @@ -148,35 +136,24 @@ Acts::CuboidVolumeBuilder::buildVolume( // Build layer array std::pair<double, double> minMax = binningRange(gctx, cfg); LayerArrayCreator::Config lacCnf; - LayerArrayCreator layArrCreator( + LayerArrayCreator layArrCreator( lacCnf, getDefaultLogger("LayerArrayCreator", Logging::INFO)); std::unique_ptr<const LayerArray> layArr( - layArrCreator.layerArray(gctx, - layVec, - minMax.first, - minMax.second, - BinningType::arbitrary, - BinningValue::binX)); + layArrCreator.layerArray(gctx, layVec, minMax.first, minMax.second, + BinningType::arbitrary, BinningValue::binX)); // Build TrackingVolume - auto trackVolume - = TrackingVolume::create(std::make_shared<const Transform3D>(trafo), - bounds, - cfg.volumeMaterial, - std::move(layArr), - nullptr, - cfg.name); + auto trackVolume = TrackingVolume::create( + std::make_shared<const Transform3D>(trafo), bounds, cfg.volumeMaterial, + std::move(layArr), nullptr, cfg.name); trackVolume->sign(GeometrySignature::Global); return trackVolume; } -Acts::MutableTrackingVolumePtr -Acts::CuboidVolumeBuilder::trackingVolume( - const GeometryContext& gctx, - Acts::TrackingVolumePtr /*unused*/, - Acts::VolumeBoundsPtr /*unused*/) const -{ +Acts::MutableTrackingVolumePtr Acts::CuboidVolumeBuilder::trackingVolume( + const GeometryContext& gctx, Acts::TrackingVolumePtr /*unused*/, + Acts::VolumeBoundsPtr /*unused*/) const { // Build volumes std::vector<std::shared_ptr<TrackingVolume>> volumes; volumes.reserve(m_cfg.volumeCfg.size()); @@ -186,12 +163,10 @@ Acts::CuboidVolumeBuilder::trackingVolume( // Glue volumes for (unsigned int i = 0; i < volumes.size() - 1; i++) { - volumes[i + 1]->glueTrackingVolume(gctx, - BoundarySurfaceFace::negativeFaceYZ, - volumes[i], - BoundarySurfaceFace::positiveFaceYZ); - volumes[i]->glueTrackingVolume(gctx, - BoundarySurfaceFace::positiveFaceYZ, + volumes[i + 1]->glueTrackingVolume( + gctx, BoundarySurfaceFace::negativeFaceYZ, volumes[i], + BoundarySurfaceFace::positiveFaceYZ); + volumes[i]->glueTrackingVolume(gctx, BoundarySurfaceFace::positiveFaceYZ, volumes[i + 1], BoundarySurfaceFace::negativeFaceYZ); } @@ -213,16 +188,16 @@ Acts::CuboidVolumeBuilder::trackingVolume( // Set bin boundaries along binning std::vector<float> binBoundaries; - binBoundaries.push_back(volumes[0]->center().x() - - m_cfg.volumeCfg[0].length.x() * 0.5); + binBoundaries.push_back(volumes[0]->center().x() - + m_cfg.volumeCfg[0].length.x() * 0.5); for (size_t i = 0; i < volumes.size(); i++) { - binBoundaries.push_back(volumes[i]->center().x() - + m_cfg.volumeCfg[i].length.x() * 0.5); + binBoundaries.push_back(volumes[i]->center().x() + + m_cfg.volumeCfg[i].length.x() * 0.5); } // Build binning BinningData binData(BinningOption::open, BinningValue::binX, binBoundaries); - auto bu = std::make_unique<const BinUtility>(binData); + auto bu = std::make_unique<const BinUtility>(binData); // Build TrackingVolume array std::shared_ptr<const TrackingVolumeArray> trVolArr( diff --git a/Core/src/Geometry/CutoutCylinderVolumeBounds.cpp b/Core/src/Geometry/CutoutCylinderVolumeBounds.cpp index e9d6d89272f622e8bbfb52f5e316d3dec24ef2cc..3135444615ce223c30a2ce12e99f084b89653dff 100644 --- a/Core/src/Geometry/CutoutCylinderVolumeBounds.cpp +++ b/Core/src/Geometry/CutoutCylinderVolumeBounds.cpp @@ -19,16 +19,12 @@ #include "Acts/Utilities/Helpers.hpp" #include "Acts/Utilities/IVisualization.hpp" -Acts::VolumeBounds* -Acts::CutoutCylinderVolumeBounds::clone() const -{ +Acts::VolumeBounds* Acts::CutoutCylinderVolumeBounds::clone() const { return new CutoutCylinderVolumeBounds(*this); } -bool -Acts::CutoutCylinderVolumeBounds::inside(const Acts::Vector3D& gpos, - double tol) const -{ +bool Acts::CutoutCylinderVolumeBounds::inside(const Acts::Vector3D& gpos, + double tol) const { // first check whether we are in the outer envelope at all (ignore r_med) using VectorHelpers::perp; using VectorHelpers::phi; @@ -51,8 +47,7 @@ Acts::CutoutCylinderVolumeBounds::inside(const Acts::Vector3D& gpos, std::vector<std::shared_ptr<const Acts::Surface>> Acts::CutoutCylinderVolumeBounds::decomposeToSurfaces( - const Transform3D* transform) const -{ + const Transform3D* transform) const { std::vector<std::shared_ptr<const Acts::Surface>> surfaces; // transform copy @@ -79,55 +74,54 @@ Acts::CutoutCylinderVolumeBounds::decomposeToSurfaces( // z position of the pos and neg choke points double hlChoke = (m_dz1 - m_dz2) * 0.5; - double zChoke = m_dz2 + hlChoke; + double zChoke = m_dz2 + hlChoke; if (m_rmin > 0.) { auto posChokeTrf = std::make_shared<const Transform3D>( *trf * Translation3D(Vector3D(0, 0, zChoke))); - auto posInner - = Surface::makeShared<CylinderSurface>(posChokeTrf, m_rmin, hlChoke); + auto posInner = + Surface::makeShared<CylinderSurface>(posChokeTrf, m_rmin, hlChoke); surfaces.at(index7) = posInner; auto negChokeTrf = std::make_shared<const Transform3D>( *trf * Translation3D(Vector3D(0, 0, -zChoke))); - auto negInner - = Surface::makeShared<CylinderSurface>(negChokeTrf, m_rmin, hlChoke); + auto negInner = + Surface::makeShared<CylinderSurface>(negChokeTrf, m_rmin, hlChoke); surfaces.at(index6) = negInner; } // outer disks auto posOutDiscTrf = std::make_shared<const Transform3D>( *trf * Translation3D(Vector3D(0, 0, m_dz1))); - auto posOutDisc - = Surface::makeShared<DiscSurface>(posOutDiscTrf, m_rmin, m_rmax); + auto posOutDisc = + Surface::makeShared<DiscSurface>(posOutDiscTrf, m_rmin, m_rmax); surfaces.at(positiveFaceXY) = posOutDisc; auto negOutDiscTrf = std::make_shared<const Transform3D>( - *trf * Translation3D(Vector3D(0, 0, -m_dz1)) - * AngleAxis3D(M_PI, Vector3D::UnitX())); - auto negOutDisc - = Surface::makeShared<DiscSurface>(negOutDiscTrf, m_rmin, m_rmax); + *trf * Translation3D(Vector3D(0, 0, -m_dz1)) * + AngleAxis3D(M_PI, Vector3D::UnitX())); + auto negOutDisc = + Surface::makeShared<DiscSurface>(negOutDiscTrf, m_rmin, m_rmax); surfaces.at(negativeFaceXY) = negOutDisc; // inner disks auto posInDiscTrf = std::make_shared<const Transform3D>( *trf * Translation3D(Vector3D(0, 0, m_dz2))); - auto posInDisc - = Surface::makeShared<DiscSurface>(posInDiscTrf, m_rmin, m_rmed); + auto posInDisc = + Surface::makeShared<DiscSurface>(posInDiscTrf, m_rmin, m_rmed); surfaces.at(index5) = posInDisc; auto negInDiscTrf = std::make_shared<const Transform3D>( - *trf * Translation3D(Vector3D(0, 0, -m_dz2)) - * AngleAxis3D(M_PI, Vector3D::UnitX())); - auto negInDisc - = Surface::makeShared<DiscSurface>(negInDiscTrf, m_rmin, m_rmed); + *trf * Translation3D(Vector3D(0, 0, -m_dz2)) * + AngleAxis3D(M_PI, Vector3D::UnitX())); + auto negInDisc = + Surface::makeShared<DiscSurface>(negInDiscTrf, m_rmin, m_rmed); surfaces.at(index4) = negInDisc; return surfaces; } -std::ostream& -Acts::CutoutCylinderVolumeBounds::toStream(std::ostream& sl) const -{ +std::ostream& Acts::CutoutCylinderVolumeBounds::toStream( + std::ostream& sl) const { sl << "Acts::CutoutCylinderVolumeBounds(\n"; sl << "rmin = " << m_rmin << " rmed = " << m_rmed << " rmax = " << m_rmax << "\n"; @@ -135,14 +129,12 @@ Acts::CutoutCylinderVolumeBounds::toStream(std::ostream& sl) const return sl; } -void -Acts::CutoutCylinderVolumeBounds::draw(IVisualization& helper, - const Transform3D& transform) const -{ - std::vector<std::shared_ptr<const Acts::Surface>> surfaces - = decomposeToSurfaces(&transform); +void Acts::CutoutCylinderVolumeBounds::draw( + IVisualization& helper, const Transform3D& transform) const { + std::vector<std::shared_ptr<const Acts::Surface>> surfaces = + decomposeToSurfaces(&transform); for (const auto& srf : surfaces) { - auto cyl = dynamic_cast<const CylinderSurface*>(srf.get()); + auto cyl = dynamic_cast<const CylinderSurface*>(srf.get()); auto disc = dynamic_cast<const DiscSurface*>(srf.get()); if (cyl != nullptr) { cyl->polyhedronRepresentation(50).draw(helper); diff --git a/Core/src/Geometry/CylinderLayer.cpp b/Core/src/Geometry/CylinderLayer.cpp index 55a7e4ea3a72fd93a6e1f49aa503a3a684cf99d4..d3e349c1c527aa26ae375b8c2458b3b475c3cd5b 100644 --- a/Core/src/Geometry/CylinderLayer.cpp +++ b/Core/src/Geometry/CylinderLayer.cpp @@ -22,21 +22,18 @@ using Acts::VectorHelpers::phi; Acts::CylinderLayer::CylinderLayer( - const std::shared_ptr<const Transform3D>& transform, + const std::shared_ptr<const Transform3D>& transform, const std::shared_ptr<const CylinderBounds>& cBounds, - std::unique_ptr<SurfaceArray> surfaceArray, - double thickness, - std::unique_ptr<ApproachDescriptor> ades, - LayerType laytyp) - : CylinderSurface(transform, cBounds) - , Layer(std::move(surfaceArray), thickness, std::move(ades), laytyp) -{ + std::unique_ptr<SurfaceArray> surfaceArray, double thickness, + std::unique_ptr<ApproachDescriptor> ades, LayerType laytyp) + : CylinderSurface(transform, cBounds), + Layer(std::move(surfaceArray), thickness, std::move(ades), laytyp) { // create the representing volume auto cVolumeBounds = std::make_shared<const CylinderVolumeBounds>( *CylinderSurface::m_bounds, thickness); // @todo rotate around x for the avePhi if you have a sector - m_representingVolume - = std::make_unique<AbstractVolume>(m_transform, cVolumeBounds); + m_representingVolume = + std::make_unique<AbstractVolume>(m_transform, cVolumeBounds); // associate the layer to the surface CylinderSurface::associateLayer(*this); @@ -50,21 +47,16 @@ Acts::CylinderLayer::CylinderLayer( } } -const Acts::CylinderSurface& -Acts::CylinderLayer::surfaceRepresentation() const -{ +const Acts::CylinderSurface& Acts::CylinderLayer::surfaceRepresentation() + const { return (*this); } -Acts::CylinderSurface& -Acts::CylinderLayer::surfaceRepresentation() -{ +Acts::CylinderSurface& Acts::CylinderLayer::surfaceRepresentation() { return (*this); } -void -Acts::CylinderLayer::buildApproachDescriptor() -{ +void Acts::CylinderLayer::buildApproachDescriptor() { // delete and reset as you build a new one m_approachDescriptor.reset(nullptr); @@ -72,8 +64,7 @@ Acts::CylinderLayer::buildApproachDescriptor() if (m_representingVolume != nullptr) { // get the boundary surfaces const std::vector<std::shared_ptr<const BoundarySurfaceT<AbstractVolume>>>& - bSurfaces - = m_representingVolume->boundarySurfaces(); + bSurfaces = m_representingVolume->boundarySurfaces(); // fill in the surfaces into the vector std::vector<std::shared_ptr<const Surface>> aSurfaces; @@ -84,8 +75,8 @@ Acts::CylinderLayer::buildApproachDescriptor() aSurfaces.push_back( bSurfaces.at(tubeOuterCover)->surfaceRepresentation().getSharedPtr()); // create an ApproachDescriptor with Boundary surfaces - m_approachDescriptor = std::make_unique<const GenericApproachDescriptor>( - std::move(aSurfaces)); + m_approachDescriptor = + std::make_unique<const GenericApproachDescriptor>(std::move(aSurfaces)); } for (auto& sfPtr : (m_approachDescriptor->containedSurfaces())) { diff --git a/Core/src/Geometry/CylinderVolumeBounds.cpp b/Core/src/Geometry/CylinderVolumeBounds.cpp index a05daf69a1bd1ceb2dca806edc986f6c1904e10d..d889efd550417165c4d90d2f8f0df85209f05852 100644 --- a/Core/src/Geometry/CylinderVolumeBounds.cpp +++ b/Core/src/Geometry/CylinderVolumeBounds.cpp @@ -24,75 +24,61 @@ const double Acts::CylinderVolumeBounds::s_numericalStable = 10e-2; Acts::CylinderVolumeBounds::CylinderVolumeBounds() - : VolumeBounds(), m_valueStore(4, 0.) -{ -} + : VolumeBounds(), m_valueStore(4, 0.) {} Acts::CylinderVolumeBounds::CylinderVolumeBounds(double radius, double halez) - : VolumeBounds(), m_valueStore(4, 0.) -{ - m_valueStore.at(bv_innerRadius) = 0.; - m_valueStore.at(bv_outerRadius) = std::abs(radius); + : VolumeBounds(), m_valueStore(4, 0.) { + m_valueStore.at(bv_innerRadius) = 0.; + m_valueStore.at(bv_outerRadius) = std::abs(radius); m_valueStore.at(bv_halfPhiSector) = M_PI; - m_valueStore.at(bv_halfZ) = std::abs(halez); + m_valueStore.at(bv_halfZ) = std::abs(halez); } -Acts::CylinderVolumeBounds::CylinderVolumeBounds(double rinner, - double router, +Acts::CylinderVolumeBounds::CylinderVolumeBounds(double rinner, double router, double halez) - : VolumeBounds(), m_valueStore(4, 0.) -{ - m_valueStore.at(bv_innerRadius) = std::abs(rinner); - m_valueStore.at(bv_outerRadius) = std::abs(router); + : VolumeBounds(), m_valueStore(4, 0.) { + m_valueStore.at(bv_innerRadius) = std::abs(rinner); + m_valueStore.at(bv_outerRadius) = std::abs(router); m_valueStore.at(bv_halfPhiSector) = M_PI; - m_valueStore.at(bv_halfZ) = std::abs(halez); + m_valueStore.at(bv_halfZ) = std::abs(halez); } -Acts::CylinderVolumeBounds::CylinderVolumeBounds(double rinner, - double router, - double haphi, - double halez) - : VolumeBounds(), m_valueStore(4, 0.) -{ - m_valueStore.at(bv_innerRadius) = std::abs(rinner); - m_valueStore.at(bv_outerRadius) = std::abs(router); +Acts::CylinderVolumeBounds::CylinderVolumeBounds(double rinner, double router, + double haphi, double halez) + : VolumeBounds(), m_valueStore(4, 0.) { + m_valueStore.at(bv_innerRadius) = std::abs(rinner); + m_valueStore.at(bv_outerRadius) = std::abs(router); m_valueStore.at(bv_halfPhiSector) = std::abs(haphi); - m_valueStore.at(bv_halfZ) = std::abs(halez); + m_valueStore.at(bv_halfZ) = std::abs(halez); } Acts::CylinderVolumeBounds::CylinderVolumeBounds(const CylinderBounds& cBounds, double thickness) - : VolumeBounds(), m_valueStore(4, 0.) -{ - - double cR = cBounds.r(); - m_valueStore.at(bv_innerRadius) = cR - 0.5 * thickness; - m_valueStore.at(bv_outerRadius) = cR + 0.5 * thickness; + : VolumeBounds(), m_valueStore(4, 0.) { + double cR = cBounds.r(); + m_valueStore.at(bv_innerRadius) = cR - 0.5 * thickness; + m_valueStore.at(bv_outerRadius) = cR + 0.5 * thickness; m_valueStore.at(bv_halfPhiSector) = cBounds.halfPhiSector(); - m_valueStore.at(bv_halfZ) = cBounds.halflengthZ(); + m_valueStore.at(bv_halfZ) = cBounds.halflengthZ(); } Acts::CylinderVolumeBounds::CylinderVolumeBounds(const RadialBounds& rBounds, - double thickness) - : VolumeBounds(), m_valueStore(4, 0.) -{ - m_valueStore.at(bv_innerRadius) = rBounds.rMin(); - m_valueStore.at(bv_outerRadius) = rBounds.rMax(); + double thickness) + : VolumeBounds(), m_valueStore(4, 0.) { + m_valueStore.at(bv_innerRadius) = rBounds.rMin(); + m_valueStore.at(bv_outerRadius) = rBounds.rMax(); m_valueStore.at(bv_halfPhiSector) = rBounds.halfPhiSector(); - m_valueStore.at(bv_halfZ) = 0.5 * thickness; + m_valueStore.at(bv_halfZ) = 0.5 * thickness; } Acts::CylinderVolumeBounds::CylinderVolumeBounds( const CylinderVolumeBounds& cylbo) - : VolumeBounds(), m_valueStore(cylbo.m_valueStore) -{ -} + : VolumeBounds(), m_valueStore(cylbo.m_valueStore) {} Acts::CylinderVolumeBounds::~CylinderVolumeBounds() = default; -Acts::CylinderVolumeBounds& -Acts::CylinderVolumeBounds::operator=(const CylinderVolumeBounds& cylbo) -{ +Acts::CylinderVolumeBounds& Acts::CylinderVolumeBounds::operator=( + const CylinderVolumeBounds& cylbo) { if (this != &cylbo) { m_valueStore = cylbo.m_valueStore; } @@ -101,29 +87,28 @@ Acts::CylinderVolumeBounds::operator=(const CylinderVolumeBounds& cylbo) std::vector<std::shared_ptr<const Acts::Surface>> Acts::CylinderVolumeBounds::decomposeToSurfaces( - const Transform3D* transformPtr) const -{ + const Transform3D* transformPtr) const { std::vector<std::shared_ptr<const Surface>> rSurfaces; rSurfaces.reserve(6); // set the transform - Transform3D transform - = (transformPtr == nullptr) ? Transform3D::Identity() : (*transformPtr); + Transform3D transform = + (transformPtr == nullptr) ? Transform3D::Identity() : (*transformPtr); auto trfShared = std::make_shared<Transform3D>(transform); const Transform3D* tTransform = nullptr; - Vector3D cylCenter(transform.translation()); + Vector3D cylCenter(transform.translation()); std::shared_ptr<const DiscBounds> dBounds = discBounds(); // bottom Disc (negative z) - tTransform - = new Transform3D(transform * AngleAxis3D(M_PI, Vector3D(1., 0., 0.)) - * Translation3D(Vector3D(0., 0., halflengthZ()))); + tTransform = + new Transform3D(transform * AngleAxis3D(M_PI, Vector3D(1., 0., 0.)) * + Translation3D(Vector3D(0., 0., halflengthZ()))); rSurfaces.push_back(Surface::makeShared<DiscSurface>( std::shared_ptr<const Transform3D>(tTransform), dBounds)); // top Disc (positive z) - tTransform = new Transform3D( - transform * Translation3D(Vector3D(0., 0., halflengthZ()))); + tTransform = new Transform3D(transform * + Translation3D(Vector3D(0., 0., halflengthZ()))); rSurfaces.push_back(Surface::makeShared<DiscSurface>( std::shared_ptr<const Transform3D>(tTransform), dBounds)); @@ -142,16 +127,16 @@ Acts::CylinderVolumeBounds::decomposeToSurfaces( std::shared_ptr<const PlanarBounds> sp12Bounds = sectorPlaneBounds(); // sectorPlane 1 (negative phi) const Transform3D* sp1Transform = new Transform3D( - transform * AngleAxis3D(-halfPhiSector(), Vector3D(0., 0., 1.)) - * Translation3D(Vector3D(mediumRadius(), 0., 0.)) - * AngleAxis3D(M_PI / 2, Vector3D(1., 0., 0.))); + transform * AngleAxis3D(-halfPhiSector(), Vector3D(0., 0., 1.)) * + Translation3D(Vector3D(mediumRadius(), 0., 0.)) * + AngleAxis3D(M_PI / 2, Vector3D(1., 0., 0.))); rSurfaces.push_back(Surface::makeShared<PlaneSurface>( std::shared_ptr<const Transform3D>(sp1Transform), sp12Bounds)); // sectorPlane 2 (positive phi) const Transform3D* sp2Transform = new Transform3D( - transform * AngleAxis3D(halfPhiSector(), Vector3D(0., 0., 1.)) - * Translation3D(Vector3D(mediumRadius(), 0., 0.)) - * AngleAxis3D(-M_PI / 2, Vector3D(1., 0., 0.))); + transform * AngleAxis3D(halfPhiSector(), Vector3D(0., 0., 1.)) * + Translation3D(Vector3D(mediumRadius(), 0., 0.)) * + AngleAxis3D(-M_PI / 2, Vector3D(1., 0., 0.))); rSurfaces.push_back(Surface::makeShared<PlaneSurface>( std::shared_ptr<const Transform3D>(sp2Transform), sp12Bounds)); } @@ -159,53 +144,42 @@ Acts::CylinderVolumeBounds::decomposeToSurfaces( } std::shared_ptr<const Acts::CylinderBounds> -Acts::CylinderVolumeBounds::innerCylinderBounds() const -{ +Acts::CylinderVolumeBounds::innerCylinderBounds() const { return std::make_shared<const CylinderBounds>( - m_valueStore.at(bv_innerRadius), - m_valueStore.at(bv_halfPhiSector), + m_valueStore.at(bv_innerRadius), m_valueStore.at(bv_halfPhiSector), m_valueStore.at(bv_halfZ)); } std::shared_ptr<const Acts::CylinderBounds> -Acts::CylinderVolumeBounds::outerCylinderBounds() const -{ +Acts::CylinderVolumeBounds::outerCylinderBounds() const { return std::make_shared<const CylinderBounds>( - m_valueStore.at(bv_outerRadius), - m_valueStore.at(bv_halfPhiSector), + m_valueStore.at(bv_outerRadius), m_valueStore.at(bv_halfPhiSector), m_valueStore.at(bv_halfZ)); } -std::shared_ptr<const Acts::DiscBounds> -Acts::CylinderVolumeBounds::discBounds() const -{ - return std::shared_ptr<const DiscBounds>( - new RadialBounds(m_valueStore.at(bv_innerRadius), - m_valueStore.at(bv_outerRadius), - m_valueStore.at(bv_halfPhiSector))); +std::shared_ptr<const Acts::DiscBounds> Acts::CylinderVolumeBounds::discBounds() + const { + return std::shared_ptr<const DiscBounds>(new RadialBounds( + m_valueStore.at(bv_innerRadius), m_valueStore.at(bv_outerRadius), + m_valueStore.at(bv_halfPhiSector))); } std::shared_ptr<const Acts::PlanarBounds> -Acts::CylinderVolumeBounds::sectorPlaneBounds() const -{ +Acts::CylinderVolumeBounds::sectorPlaneBounds() const { return std::shared_ptr<const PlanarBounds>(new RectangleBounds( 0.5 * (m_valueStore.at(bv_outerRadius) - m_valueStore.at(bv_innerRadius)), m_valueStore.at(bv_halfZ))); } -std::ostream& -Acts::CylinderVolumeBounds::toStream(std::ostream& sl) const -{ +std::ostream& Acts::CylinderVolumeBounds::toStream(std::ostream& sl) const { return dumpT<std::ostream>(sl); } -void -Acts::CylinderVolumeBounds::draw(IVisualization& helper, - const Transform3D& transform) const -{ - std::vector<std::shared_ptr<const Acts::Surface>> surfaces - = decomposeToSurfaces(&transform); +void Acts::CylinderVolumeBounds::draw(IVisualization& helper, + const Transform3D& transform) const { + std::vector<std::shared_ptr<const Acts::Surface>> surfaces = + decomposeToSurfaces(&transform); for (const auto& srf : surfaces) { - auto cyl = dynamic_cast<const CylinderSurface*>(srf.get()); + auto cyl = dynamic_cast<const CylinderSurface*>(srf.get()); auto disc = dynamic_cast<const DiscSurface*>(srf.get()); if (cyl != nullptr) { cyl->polyhedronRepresentation(50).draw(helper); diff --git a/Core/src/Geometry/CylinderVolumeBuilder.cpp b/Core/src/Geometry/CylinderVolumeBuilder.cpp index 5fd37b29caa01f417ff4786866e2174bf13c2756..ce9b405f4f494fc5f7f473fc791fef8d5eaf8e4f 100644 --- a/Core/src/Geometry/CylinderVolumeBuilder.cpp +++ b/Core/src/Geometry/CylinderVolumeBuilder.cpp @@ -22,35 +22,29 @@ Acts::CylinderVolumeBuilder::CylinderVolumeBuilder( const Acts::CylinderVolumeBuilder::Config& cvbConfig, - std::unique_ptr<const Logger> logger) - : Acts::ITrackingVolumeBuilder(), m_cfg(), m_logger(std::move(logger)) -{ + std::unique_ptr<const Logger> logger) + : Acts::ITrackingVolumeBuilder(), m_cfg(), m_logger(std::move(logger)) { setConfiguration(cvbConfig); } Acts::CylinderVolumeBuilder::~CylinderVolumeBuilder() = default; -void -Acts::CylinderVolumeBuilder::setConfiguration( - const Acts::CylinderVolumeBuilder::Config& cvbConfig) -{ +void Acts::CylinderVolumeBuilder::setConfiguration( + const Acts::CylinderVolumeBuilder::Config& cvbConfig) { // @todo check consistency // copy the configuration m_cfg = cvbConfig; } -void -Acts::CylinderVolumeBuilder::setLogger(std::unique_ptr<const Logger> newLogger) -{ +void Acts::CylinderVolumeBuilder::setLogger( + std::unique_ptr<const Logger> newLogger) { m_logger = std::move(newLogger); } std::shared_ptr<Acts::TrackingVolume> Acts::CylinderVolumeBuilder::trackingVolume( - const GeometryContext& gctx, - TrackingVolumePtr existingVolume, - VolumeBoundsPtr externalBounds) const -{ + const GeometryContext& gctx, TrackingVolumePtr existingVolume, + VolumeBoundsPtr externalBounds) const { ACTS_DEBUG("Configured to build volume : " << m_cfg.volumeName); // the return volume @@ -84,28 +78,28 @@ Acts::CylinderVolumeBuilder::trackingVolume( &existingVolume->volumeBounds()); // set the inside values wConfig.existingVolumeConfig.present = true; - wConfig.existingVolumeConfig.rMin = existingBounds->innerRadius(); - wConfig.existingVolumeConfig.rMax = existingBounds->outerRadius(); - wConfig.existingVolumeConfig.zMin - = existingVolume->center().z() - existingBounds->halflengthZ(); - wConfig.existingVolumeConfig.zMax - = existingVolume->center().z() + existingBounds->halflengthZ(); + wConfig.existingVolumeConfig.rMin = existingBounds->innerRadius(); + wConfig.existingVolumeConfig.rMax = existingBounds->outerRadius(); + wConfig.existingVolumeConfig.zMin = + existingVolume->center().z() - existingBounds->halflengthZ(); + wConfig.existingVolumeConfig.zMax = + existingVolume->center().z() + existingBounds->halflengthZ(); } // // b) outside config // the volume config for the Outside VolumeConfig externalBoundConfig; if (externalBounds) { - const CylinderVolumeBounds* ocvBounds - = dynamic_cast<const CylinderVolumeBounds*>(externalBounds.get()); + const CylinderVolumeBounds* ocvBounds = + dynamic_cast<const CylinderVolumeBounds*>(externalBounds.get()); // the cast to CylinderVolumeBounds needs to be successful if (ocvBounds != nullptr) { // get values from the out bounds wConfig.externalVolumeConfig.present = true; - wConfig.externalVolumeConfig.rMin = ocvBounds->innerRadius(); - wConfig.externalVolumeConfig.rMax = ocvBounds->outerRadius(); - wConfig.externalVolumeConfig.zMin = -ocvBounds->halflengthZ(); - wConfig.externalVolumeConfig.zMax = ocvBounds->halflengthZ(); + wConfig.externalVolumeConfig.rMin = ocvBounds->innerRadius(); + wConfig.externalVolumeConfig.rMax = ocvBounds->outerRadius(); + wConfig.externalVolumeConfig.zMin = -ocvBounds->halflengthZ(); + wConfig.externalVolumeConfig.zMax = ocvBounds->halflengthZ(); } } @@ -183,46 +177,40 @@ Acts::CylinderVolumeBuilder::trackingVolume( // (C) VOLUME CREATION ---------------------------------- auto tvHelper = m_cfg.trackingVolumeHelper; // the barrel is always created - auto barrel = wConfig.cVolumeConfig - ? tvHelper->createTrackingVolume(gctx, - wConfig.cVolumeConfig.layers, - m_cfg.volumeMaterial, - wConfig.cVolumeConfig.rMin, - wConfig.cVolumeConfig.rMax, - wConfig.cVolumeConfig.zMin, - wConfig.cVolumeConfig.zMax, - m_cfg.volumeName + "::Barrel") - : nullptr; + auto barrel = + wConfig.cVolumeConfig + ? tvHelper->createTrackingVolume( + gctx, wConfig.cVolumeConfig.layers, m_cfg.volumeMaterial, + wConfig.cVolumeConfig.rMin, wConfig.cVolumeConfig.rMax, + wConfig.cVolumeConfig.zMin, wConfig.cVolumeConfig.zMax, + m_cfg.volumeName + "::Barrel") + : nullptr; // the negative endcap is created if present - auto nEndcap = wConfig.nVolumeConfig - ? tvHelper->createTrackingVolume(gctx, - wConfig.nVolumeConfig.layers, - m_cfg.volumeMaterial, - wConfig.nVolumeConfig.rMin, - wConfig.nVolumeConfig.rMax, - wConfig.nVolumeConfig.zMin, - wConfig.nVolumeConfig.zMax, - m_cfg.volumeName + "::NegativeEndcap") - : nullptr; + auto nEndcap = + wConfig.nVolumeConfig + ? tvHelper->createTrackingVolume( + gctx, wConfig.nVolumeConfig.layers, m_cfg.volumeMaterial, + wConfig.nVolumeConfig.rMin, wConfig.nVolumeConfig.rMax, + wConfig.nVolumeConfig.zMin, wConfig.nVolumeConfig.zMax, + m_cfg.volumeName + "::NegativeEndcap") + : nullptr; // the positive endcap is created - auto pEndcap = wConfig.pVolumeConfig - ? tvHelper->createTrackingVolume(gctx, - wConfig.pVolumeConfig.layers, - m_cfg.volumeMaterial, - wConfig.pVolumeConfig.rMin, - wConfig.pVolumeConfig.rMax, - wConfig.pVolumeConfig.zMin, - wConfig.pVolumeConfig.zMax, - m_cfg.volumeName + "::PositiveEndcap") - : nullptr; + auto pEndcap = + wConfig.pVolumeConfig + ? tvHelper->createTrackingVolume( + gctx, wConfig.pVolumeConfig.layers, m_cfg.volumeMaterial, + wConfig.pVolumeConfig.rMin, wConfig.pVolumeConfig.rMax, + wConfig.pVolumeConfig.zMin, wConfig.pVolumeConfig.zMax, + m_cfg.volumeName + "::PositiveEndcap") + : nullptr; ACTS_DEBUG("Newly created volume(s) will be " << wConfig.wConditionScreen); // standalone container, full wrapping, full insertion & if no existing volume // is present needs a bare triple - if (wConfig.wCondition == Wrapping || wConfig.wCondition == Inserting - || wConfig.wCondition == NoWrapping) { + if (wConfig.wCondition == Wrapping || wConfig.wCondition == Inserting || + wConfig.wCondition == NoWrapping) { ACTS_VERBOSE("Combined new container is being built."); // stuff into the container what you have std::vector<std::shared_ptr<const TrackingVolume>> volumesContainer; @@ -239,9 +227,10 @@ Acts::CylinderVolumeBuilder::trackingVolume( volume = pEndcap; } // and low lets create the new volume - volume = volumesContainer.size() > 1 - ? tvHelper->createContainerTrackingVolume(gctx, volumesContainer) - : volume; + volume = + volumesContainer.size() > 1 + ? tvHelper->createContainerTrackingVolume(gctx, volumesContainer) + : volume; } else if (wConfig.wCondition != Attaching) { // the new volume is the only one present volume = nEndcap ? nEndcap : (barrel ? barrel : pEndcap); @@ -255,40 +244,29 @@ Acts::CylinderVolumeBuilder::trackingVolume( std::vector<std::shared_ptr<const TrackingVolume>> existingContainer; if (wConfig.fGapVolumeConfig) { // create the gap volume - auto fGap - = tvHelper->createGapTrackingVolume(gctx, - m_cfg.volumeMaterial, - wConfig.fGapVolumeConfig.rMin, - wConfig.fGapVolumeConfig.rMax, - wConfig.fGapVolumeConfig.zMin, - wConfig.fGapVolumeConfig.zMax, - 1, - false, - m_cfg.volumeName + "::fGap"); + auto fGap = tvHelper->createGapTrackingVolume( + gctx, m_cfg.volumeMaterial, wConfig.fGapVolumeConfig.rMin, + wConfig.fGapVolumeConfig.rMax, wConfig.fGapVolumeConfig.zMin, + wConfig.fGapVolumeConfig.zMax, 1, false, m_cfg.volumeName + "::fGap"); // push it back into the list existingContainer.push_back(fGap); } existingContainer.push_back(existingVolumeCp); if (wConfig.sGapVolumeConfig) { // create the gap volume - auto sGap - = tvHelper->createGapTrackingVolume(gctx, - m_cfg.volumeMaterial, - wConfig.sGapVolumeConfig.rMin, - wConfig.sGapVolumeConfig.rMax, - wConfig.sGapVolumeConfig.zMin, - wConfig.sGapVolumeConfig.zMax, - 1, - false, - m_cfg.volumeName + "::sGap"); + auto sGap = tvHelper->createGapTrackingVolume( + gctx, m_cfg.volumeMaterial, wConfig.sGapVolumeConfig.rMin, + wConfig.sGapVolumeConfig.rMax, wConfig.sGapVolumeConfig.zMin, + wConfig.sGapVolumeConfig.zMax, 1, false, m_cfg.volumeName + "::sGap"); // push it back into the list existingContainer.push_back(sGap); } // and low lets create the new existing volume with gaps - existingVolumeCp = existingContainer.size() > 1 - ? tvHelper->createContainerTrackingVolume(gctx, existingContainer) - : existingVolumeCp; + existingVolumeCp = + existingContainer.size() > 1 + ? tvHelper->createContainerTrackingVolume(gctx, existingContainer) + : existingVolumeCp; // for central wrapping or inserting, we need to update once more // clear the container @@ -301,14 +279,16 @@ Acts::CylinderVolumeBuilder::trackingVolume( existingContainer.push_back(existingVolumeCp); } // update - existingVolumeCp = !existingContainer.empty() - ? tvHelper->createContainerTrackingVolume(gctx, existingContainer) - : existingVolumeCp; + existingVolumeCp = + !existingContainer.empty() + ? tvHelper->createContainerTrackingVolume(gctx, existingContainer) + : existingVolumeCp; std::vector<std::shared_ptr<const TrackingVolume>> totalContainer; // check what to do with the existing - if (wConfig.wCondition == Attaching || wConfig.wCondition == CentralWrapping - || wConfig.wCondition == CentralInserting) { + if (wConfig.wCondition == Attaching || + wConfig.wCondition == CentralWrapping || + wConfig.wCondition == CentralInserting) { if (nEndcap) { totalContainer.push_back(nEndcap); } @@ -336,10 +316,8 @@ Acts::CylinderVolumeBuilder::trackingVolume( } // ----------------------------- -Acts::VolumeConfig -Acts::CylinderVolumeBuilder::analyzeLayers(const GeometryContext& gctx, - const LayerVector& lVector) const -{ +Acts::VolumeConfig Acts::CylinderVolumeBuilder::analyzeLayers( + const GeometryContext& gctx, const LayerVector& lVector) const { // @TODO add envelope tolerance // // return object @@ -355,14 +333,14 @@ Acts::CylinderVolumeBuilder::analyzeLayers(const GeometryContext& gctx, // get the center of the layer const Vector3D& center = layer->surfaceRepresentation().center(gctx); // check if it is a cylinder layer - const CylinderLayer* cLayer - = dynamic_cast<const CylinderLayer*>(layer.get()); + const CylinderLayer* cLayer = + dynamic_cast<const CylinderLayer*>(layer.get()); if (cLayer != nullptr) { // now we have access to all the information - double rMinC - = cLayer->surfaceRepresentation().bounds().r() - 0.5 * thickness; - double rMaxC - = cLayer->surfaceRepresentation().bounds().r() + 0.5 * thickness; + double rMinC = + cLayer->surfaceRepresentation().bounds().r() - 0.5 * thickness; + double rMaxC = + cLayer->surfaceRepresentation().bounds().r() + 0.5 * thickness; double hZ = cLayer->surfaceRepresentation().bounds().halflengthZ(); takeSmaller(lConfig.rMin, rMinC - m_cfg.layerEnvelopeR.first); diff --git a/Core/src/Geometry/CylinderVolumeHelper.cpp b/Core/src/Geometry/CylinderVolumeHelper.cpp index d295b7c7e9c35d2e2f2754e759f4622ddaf9644f..9089d197a5c680dc858c4c63857376c2892b78f1 100644 --- a/Core/src/Geometry/CylinderVolumeHelper.cpp +++ b/Core/src/Geometry/CylinderVolumeHelper.cpp @@ -30,38 +30,31 @@ Acts::CylinderVolumeHelper::CylinderVolumeHelper( const Acts::CylinderVolumeHelper::Config& cvhConfig, - std::unique_ptr<const Logger> logger) - : Acts::ITrackingVolumeHelper(), m_cfg(), m_logger(std::move(logger)) -{ + std::unique_ptr<const Logger> logger) + : Acts::ITrackingVolumeHelper(), m_cfg(), m_logger(std::move(logger)) { setConfiguration(cvhConfig); } // configuration -void -Acts::CylinderVolumeHelper::setConfiguration( - const Acts::CylinderVolumeHelper::Config& cvhConfig) -{ +void Acts::CylinderVolumeHelper::setConfiguration( + const Acts::CylinderVolumeHelper::Config& cvhConfig) { // @todo check consistency // copy the configuration m_cfg = cvhConfig; } -void -Acts::CylinderVolumeHelper::setLogger(std::unique_ptr<const Logger> newLogger) -{ +void Acts::CylinderVolumeHelper::setLogger( + std::unique_ptr<const Logger> newLogger) { m_logger = std::move(newLogger); } std::shared_ptr<Acts::TrackingVolume> Acts::CylinderVolumeHelper::createTrackingVolume( - const GeometryContext& gctx, - const LayerVector& layers, + const GeometryContext& gctx, const LayerVector& layers, std::shared_ptr<const IVolumeMaterial> volumeMaterial, - std::shared_ptr<const VolumeBounds> volumeBounds, - std::shared_ptr<const Transform3D> transform, - const std::string& volumeName, - BinningType bType) const -{ + std::shared_ptr<const VolumeBounds> volumeBounds, + std::shared_ptr<const Transform3D> transform, const std::string& volumeName, + BinningType bType) const { // the final one to build / sensitive Volume / Bounds MutableTrackingVolumePtr tVolume = nullptr; // the layer array @@ -75,8 +68,8 @@ Acts::CylinderVolumeHelper::createTrackingVolume( const CylinderVolumeBounds* cylinderBounds = nullptr; // this is the implementation of CylinderVolumeHelper if (volumeBounds) { - cylinderBounds - = dynamic_cast<const CylinderVolumeBounds*>(volumeBounds.get()); + cylinderBounds = + dynamic_cast<const CylinderVolumeBounds*>(volumeBounds.get()); if (cylinderBounds == nullptr) { ACTS_WARNING( "[!] Problem: given bounds are not cylindrical - return nullptr"); @@ -94,18 +87,12 @@ Acts::CylinderVolumeHelper::createTrackingVolume( BinningValue bValue = binR; // check the dimension and fill raw data - if (not estimateAndCheckDimension(gctx, - layers, - cylinderBounds, - transform, - rMinRaw, - rMaxRaw, - zMinRaw, - zMaxRaw, - bValue, - bType)) { - ACTS_WARNING("[!] Problem with given dimensions - return nullptr and " - "delete provided objects"); + if (not estimateAndCheckDimension(gctx, layers, cylinderBounds, transform, + rMinRaw, rMaxRaw, zMinRaw, zMaxRaw, + bValue, bType)) { + ACTS_WARNING( + "[!] Problem with given dimensions - return nullptr and " + "delete provided objects"); // delete if newly created bounds if (volumeBounds == nullptr) { delete cylinderBounds; @@ -113,40 +100,39 @@ Acts::CylinderVolumeHelper::createTrackingVolume( return tVolume; } // get the zMin/Max - double zMin = (transform ? transform->translation().z() : 0.) - + (cylinderBounds != nullptr ? -cylinderBounds->halflengthZ() : 0.); - double zMax = (transform ? transform->translation().z() : 0.) - + (cylinderBounds != nullptr ? cylinderBounds->halflengthZ() : 0.); + double zMin = + (transform ? transform->translation().z() : 0.) + + (cylinderBounds != nullptr ? -cylinderBounds->halflengthZ() : 0.); + double zMax = + (transform ? transform->translation().z() : 0.) + + (cylinderBounds != nullptr ? cylinderBounds->halflengthZ() : 0.); // get the rMin/rmAx - double rMin - = cylinderBounds != nullptr ? cylinderBounds->innerRadius() : rMinRaw; - double rMax - = cylinderBounds != nullptr ? cylinderBounds->outerRadius() : rMaxRaw; + double rMin = + cylinderBounds != nullptr ? cylinderBounds->innerRadius() : rMinRaw; + double rMax = + cylinderBounds != nullptr ? cylinderBounds->outerRadius() : rMaxRaw; - ACTS_VERBOSE("Filling the layers into an appropriate layer array - with " - "binningValue = " - << bValue); + ACTS_VERBOSE( + "Filling the layers into an appropriate layer array - with " + "binningValue = " + << bValue); // create the Layer Array layerArray = (bValue == binR) - ? m_cfg.layerArrayCreator->layerArray( - gctx, layers, rMin, rMax, bType, bValue) - : m_cfg.layerArrayCreator->layerArray( - gctx, layers, zMin, zMax, bType, bValue); + ? m_cfg.layerArrayCreator->layerArray(gctx, layers, rMin, + rMax, bType, bValue) + : m_cfg.layerArrayCreator->layerArray(gctx, layers, zMin, + zMax, bType, bValue); } // layers are created and done // make sure the ownership of the bounds is correct - std::shared_ptr<const VolumeBounds> volumeBoundsFinal - = volumeBounds.get() != nullptr - ? volumeBounds - : std::shared_ptr<const VolumeBounds>(cylinderBounds); + std::shared_ptr<const VolumeBounds> volumeBoundsFinal = + volumeBounds.get() != nullptr + ? volumeBounds + : std::shared_ptr<const VolumeBounds>(cylinderBounds); // finally create the TrackingVolume - tVolume = TrackingVolume::create(transform, - volumeBoundsFinal, - volumeMaterial, - std::move(layerArray), - nullptr, - volumeName); + tVolume = TrackingVolume::create(transform, volumeBoundsFinal, volumeMaterial, + std::move(layerArray), nullptr, volumeName); // screen output ACTS_VERBOSE( "Created cylindrical volume at z-position :" << tVolume->center().z()); @@ -157,78 +143,55 @@ Acts::CylinderVolumeHelper::createTrackingVolume( std::shared_ptr<Acts::TrackingVolume> Acts::CylinderVolumeHelper::createTrackingVolume( - const GeometryContext& gctx, - const LayerVector& layers, - std::shared_ptr<const IVolumeMaterial> volumeMaterial, - double rMin, - double rMax, - double zMin, - double zMax, - const std::string& volumeName, - BinningType bType) const -{ + const GeometryContext& gctx, const LayerVector& layers, + std::shared_ptr<const IVolumeMaterial> volumeMaterial, double rMin, + double rMax, double zMin, double zMax, const std::string& volumeName, + BinningType bType) const { // that's what is needed CylinderVolumeBounds* cBounds = nullptr; // screen output ACTS_VERBOSE("Create cylindrical TrackingVolume '" << volumeName << "'."); - ACTS_VERBOSE( - " -> with given dimensions of (rMin/rMax/zMin/Max) = " << rMin << " / " - << rMax - << " / " - << zMin - << " / " - << zMax); + ACTS_VERBOSE(" -> with given dimensions of (rMin/rMax/zMin/Max) = " + << rMin << " / " << rMax << " / " << zMin << " / " << zMax); // check for consistency if (zMin > zMax || rMin > rMax) { ACTS_WARNING("Inconsistent dimensions given :" << ((zMin > zMax) ? " zMin > zMax (" : " rMin > rMax (") - << ((zMin > zMax) ? zMin : rMin) - << " > " - << ((zMin > zMax) ? zMax : rMax) - << " ) - return 0"); + << ((zMin > zMax) ? zMin : rMin) << " > " + << ((zMin > zMax) ? zMax : rMax) << " ) - return 0"); return nullptr; } // create a Transform3D and VolumeBounds out of the zMin/zMax double halflengthZ = 0.5 * (zMax - zMin); - double zPosition = 0.5 * (zMin + zMax); - zPosition = std::abs(zPosition) < 0.1 ? 0. : zPosition; + double zPosition = 0.5 * (zMin + zMax); + zPosition = std::abs(zPosition) < 0.1 ? 0. : zPosition; // now create the cylinder volume bounds cBounds = rMin > 0.1 ? new CylinderVolumeBounds(rMin, rMax, halflengthZ) : new CylinderVolumeBounds(rMax, halflengthZ); // transform - std::shared_ptr<const Transform3D> transform = (zPosition != 0) - ? std::make_shared<const Transform3D>(Translation3D(0., 0., zPosition)) - : nullptr; + std::shared_ptr<const Transform3D> transform = + (zPosition != 0) ? std::make_shared<const Transform3D>( + Translation3D(0., 0., zPosition)) + : nullptr; // call to the creation method with Bounds & Translation3D - return createTrackingVolume(gctx, - layers, - volumeMaterial, - VolumeBoundsPtr(cBounds), - transform, - volumeName, + return createTrackingVolume(gctx, layers, volumeMaterial, + VolumeBoundsPtr(cBounds), transform, volumeName, bType); } std::shared_ptr<Acts::TrackingVolume> Acts::CylinderVolumeHelper::createGapTrackingVolume( - const GeometryContext& gctx, - std::shared_ptr<const IVolumeMaterial> volumeMaterial, - double rMin, - double rMax, - double zMin, - double zMax, - unsigned int materialLayers, - bool cylinder, - const std::string& volumeName) const -{ + const GeometryContext& gctx, + std::shared_ptr<const IVolumeMaterial> volumeMaterial, double rMin, + double rMax, double zMin, double zMax, unsigned int materialLayers, + bool cylinder, const std::string& volumeName) const { // screen output ACTS_VERBOSE("Create cylindrical gap TrackingVolume '" - << volumeName - << "' with (rMin/rMax/zMin/Max) = "); + << volumeName << "' with (rMin/rMax/zMin/Max) = "); ACTS_VERBOSE('\t' << rMin << " / " << rMax << " / " << zMin << " / " << zMax); // assing min/max @@ -248,35 +211,21 @@ Acts::CylinderVolumeHelper::createGapTrackingVolume( } // now call the main method - return createGapTrackingVolume(gctx, - volumeMaterial, - rMin, - rMax, - zMin, - zMax, - layerPositions, - cylinder, - volumeName, + return createGapTrackingVolume(gctx, volumeMaterial, rMin, rMax, zMin, zMax, + layerPositions, cylinder, volumeName, arbitrary); } std::shared_ptr<Acts::TrackingVolume> Acts::CylinderVolumeHelper::createGapTrackingVolume( - const GeometryContext& gctx, - std::shared_ptr<const IVolumeMaterial> volumeMaterial, - double rMin, - double rMax, - double zMin, - double zMax, - const std::vector<double>& layerPositions, - bool cylinder, - const std::string& volumeName, - BinningType bType) const -{ + const GeometryContext& gctx, + std::shared_ptr<const IVolumeMaterial> volumeMaterial, double rMin, + double rMax, double zMin, double zMax, + const std::vector<double>& layerPositions, bool cylinder, + const std::string& volumeName, BinningType bType) const { // screen output ACTS_VERBOSE("Create cylindrical gap TrackingVolume '" - << volumeName - << "' with (rMin/rMax/zMin/Max) = "); + << volumeName << "' with (rMin/rMax/zMin/Max) = "); ACTS_VERBOSE('\t' << rMin << " / " << rMax << " / " << zMin << " / " << zMax); // create the layers @@ -284,7 +233,7 @@ Acts::CylinderVolumeHelper::createGapTrackingVolume( layers.reserve(layerPositions.size()); std::vector<double>::const_iterator layerPropIter = layerPositions.begin(); - std::vector<double>::const_iterator layerPropEnd = layerPositions.end(); + std::vector<double>::const_iterator layerPropEnd = layerPositions.end(); for (; layerPropIter != layerPropEnd; ++layerPropIter) { // create cylinder layers if (cylinder) { @@ -292,41 +241,34 @@ Acts::CylinderVolumeHelper::createGapTrackingVolume( double zMinLayer = zMin; double zMaxLayer = zMax; // create the layer - layers.push_back( - createCylinderLayer(0.5 * (zMinLayer + zMaxLayer), - (*layerPropIter), - std::abs(0.5 * (zMaxLayer - zMinLayer)), - m_cfg.passiveLayerThickness, - m_cfg.passiveLayerPhiBins, - m_cfg.passiveLayerRzBins)); + layers.push_back(createCylinderLayer( + 0.5 * (zMinLayer + zMaxLayer), (*layerPropIter), + std::abs(0.5 * (zMaxLayer - zMinLayer)), m_cfg.passiveLayerThickness, + m_cfg.passiveLayerPhiBins, m_cfg.passiveLayerRzBins)); } else { // take the envelopes into account double rMinLayer = rMin; double rMaxLayer = rMax; // create the layer - layers.push_back(createDiscLayer((*layerPropIter), - rMinLayer, - rMaxLayer, - m_cfg.passiveLayerThickness, - m_cfg.passiveLayerPhiBins, - m_cfg.passiveLayerRzBins)); + layers.push_back(createDiscLayer( + (*layerPropIter), rMinLayer, rMaxLayer, m_cfg.passiveLayerThickness, + m_cfg.passiveLayerPhiBins, m_cfg.passiveLayerRzBins)); } } // now call the createTrackingVolume() method - return createTrackingVolume( - gctx, layers, volumeMaterial, rMin, rMax, zMin, zMax, volumeName, bType); + return createTrackingVolume(gctx, layers, volumeMaterial, rMin, rMax, zMin, + zMax, volumeName, bType); } std::shared_ptr<Acts::TrackingVolume> Acts::CylinderVolumeHelper::createContainerTrackingVolume( - const GeometryContext& gctx, - const TrackingVolumeVector& volumes) const -{ + const GeometryContext& gctx, const TrackingVolumeVector& volumes) const { // check if you have more than one volume if (volumes.size() <= (size_t)1) { - ACTS_WARNING("None (only one) TrackingVolume given to create container " - "volume (min required: 2) - returning 0 "); + ACTS_WARNING( + "None (only one) TrackingVolume given to create container " + "volume (min required: 2) - returning 0 "); return nullptr; } // screen output @@ -336,14 +278,13 @@ Acts::CylinderVolumeHelper::createContainerTrackingVolume( // volumes need to be sorted in either r or z - both increasing // set the iterator to the volumes, the first and the end auto firstVolume = volumes.begin(); - auto lastVolume = volumes.end(); + auto lastVolume = volumes.end(); for (size_t ivol = 0; firstVolume != lastVolume; ++firstVolume, ++ivol) { - ACTS_VERBOSE( - " - volume (" << ivol << ") is : " << (*firstVolume)->volumeName()); + ACTS_VERBOSE(" - volume (" << ivol + << ") is : " << (*firstVolume)->volumeName()); ACTS_VERBOSE(" at position : " << (*firstVolume)->center().x() << ", " - << (*firstVolume)->center().y() - << ", " + << (*firstVolume)->center().y() << ", " << (*firstVolume)->center().z()); ACTS_VERBOSE(" with bounds : " << (*firstVolume)->volumeBounds()); @@ -360,73 +301,76 @@ Acts::CylinderVolumeHelper::createContainerTrackingVolume( --lastVolume; // set to the last volume if (firstVolume == lastVolume) { - ACTS_WARNING("Only one TrackingVolume given to create Top level volume " - "(min required: 2) - returning 0 "); + ACTS_WARNING( + "Only one TrackingVolume given to create Top level volume " + "(min required: 2) - returning 0 "); return nullptr; } // get the bounds - const CylinderVolumeBounds* firstVolumeBounds - = dynamic_cast<const CylinderVolumeBounds*>( + const CylinderVolumeBounds* firstVolumeBounds = + dynamic_cast<const CylinderVolumeBounds*>( &((*firstVolume)->volumeBounds())); - const CylinderVolumeBounds* lastVolumeBounds - = dynamic_cast<const CylinderVolumeBounds*>( + const CylinderVolumeBounds* lastVolumeBounds = + dynamic_cast<const CylinderVolumeBounds*>( &((*lastVolume)->volumeBounds())); // check the dynamic cast if ((firstVolumeBounds == nullptr) || (lastVolumeBounds == nullptr)) { - ACTS_WARNING("VolumeBounds given are not of type: CylinderVolumeBounds " - "(required) - returning 0 "); + ACTS_WARNING( + "VolumeBounds given are not of type: CylinderVolumeBounds " + "(required) - returning 0 "); return nullptr; } // check whether it is a r-binned case or a z-binned case - bool rCase = std::abs(firstVolumeBounds->innerRadius() - - lastVolumeBounds->innerRadius()) - > 0.1; + bool rCase = std::abs(firstVolumeBounds->innerRadius() - + lastVolumeBounds->innerRadius()) > 0.1; // fill these ones depending on the rCase though assignment - no parsing at // that stage - double zMin = 0.; - double zMax = 0.; - double rMin = 0.; + double zMin = 0.; + double zMax = 0.; + double rMin = 0.; double rGlueMin = 0.; - double rMax = 0.; - double zSep1 = 0.; - double zSep2 = 0.; + double rMax = 0.; + double zSep1 = 0.; + double zSep2 = 0.; if (rCase) { - zMin = (*firstVolume)->center().z() - firstVolumeBounds->halflengthZ(); - zMax = (*firstVolume)->center().z() + firstVolumeBounds->halflengthZ(); - zSep1 = zMin; - zSep2 = zMax; - rMin = firstVolumeBounds->innerRadius(); + zMin = (*firstVolume)->center().z() - firstVolumeBounds->halflengthZ(); + zMax = (*firstVolume)->center().z() + firstVolumeBounds->halflengthZ(); + zSep1 = zMin; + zSep2 = zMax; + rMin = firstVolumeBounds->innerRadius(); rGlueMin = firstVolumeBounds->outerRadius(); - rMax = lastVolumeBounds->outerRadius(); + rMax = lastVolumeBounds->outerRadius(); } else { - zMin = (*firstVolume)->center().z() - firstVolumeBounds->halflengthZ(); - zMax = (*lastVolume)->center().z() + lastVolumeBounds->halflengthZ(); + zMin = (*firstVolume)->center().z() - firstVolumeBounds->halflengthZ(); + zMax = (*lastVolume)->center().z() + lastVolumeBounds->halflengthZ(); zSep1 = (*firstVolume)->center().z() + firstVolumeBounds->halflengthZ(); zSep2 = zSep1; - rMin = firstVolumeBounds->innerRadius(); - rMax = firstVolumeBounds->outerRadius(); + rMin = firstVolumeBounds->innerRadius(); + rMax = firstVolumeBounds->outerRadius(); } // estimate the z - position double zPos = 0.5 * (zMin + zMax); // create the HEP transform from the stuff known so far - std::shared_ptr<const Transform3D> topVolumeTransform = (std::abs(zPos) > 0.1) - ? std::make_shared<const Transform3D>(Translation3D(0., 0., zPos)) - : nullptr; + std::shared_ptr<const Transform3D> topVolumeTransform = + (std::abs(zPos) > 0.1) + ? std::make_shared<const Transform3D>(Translation3D(0., 0., zPos)) + : nullptr; // create the bounds from the information gathered so far - CylinderVolumeBounds* topVolumeBounds = std::abs(rMin) > 0.1 - ? new CylinderVolumeBounds(rMin, rMax, 0.5 * std::abs(zMax - zMin)) - : new CylinderVolumeBounds(rMax, 0.5 * std::abs(zMax - zMin)); + CylinderVolumeBounds* topVolumeBounds = + std::abs(rMin) > 0.1 + ? new CylinderVolumeBounds(rMin, rMax, 0.5 * std::abs(zMax - zMin)) + : new CylinderVolumeBounds(rMax, 0.5 * std::abs(zMax - zMin)); // some screen output ACTS_VERBOSE("Container volume bounds are " << (*topVolumeBounds)); // create the volume array with the ITrackingVolumeArrayCreator - std::shared_ptr<const TrackingVolumeArray> volumeArray = (rCase) - ? m_cfg.trackingVolumeArrayCreator->trackingVolumeArray( - gctx, volumes, binR) - : m_cfg.trackingVolumeArrayCreator->trackingVolumeArray( - gctx, volumes, binZ); + std::shared_ptr<const TrackingVolumeArray> volumeArray = + (rCase) ? m_cfg.trackingVolumeArrayCreator->trackingVolumeArray( + gctx, volumes, binR) + : m_cfg.trackingVolumeArrayCreator->trackingVolumeArray( + gctx, volumes, binZ); if (volumeArray == nullptr) { ACTS_WARNING( "Creation of TrackingVolume array did not succeed - returning 0 "); @@ -434,17 +378,16 @@ Acts::CylinderVolumeHelper::createContainerTrackingVolume( return nullptr; } // we have the bounds and the volume array, create the volume - std::shared_ptr<TrackingVolume> topVolume - = TrackingVolume::create(topVolumeTransform, - VolumeBoundsPtr(topVolumeBounds), - volumeArray, - volumeName); + std::shared_ptr<TrackingVolume> topVolume = TrackingVolume::create( + topVolumeTransform, VolumeBoundsPtr(topVolumeBounds), volumeArray, + volumeName); // glueing section // -------------------------------------------------------------------------------------- - if (not interGlueTrackingVolume( - gctx, topVolume, rCase, rMin, rGlueMin, rMax, zSep1, zSep2)) { - ACTS_WARNING("Problem with inter-glueing of TrackingVolumes (needed) - " - "returning 0 "); + if (not interGlueTrackingVolume(gctx, topVolume, rCase, rMin, rGlueMin, rMax, + zSep1, zSep2)) { + ACTS_WARNING( + "Problem with inter-glueing of TrackingVolumes (needed) - " + "returning 0 "); return nullptr; } @@ -456,39 +399,28 @@ Acts::CylinderVolumeHelper::createContainerTrackingVolume( /** private helper method to estimate and check the dimensions of a tracking * volume */ -bool -Acts::CylinderVolumeHelper::estimateAndCheckDimension( - const GeometryContext& gctx, - const LayerVector& layers, - const CylinderVolumeBounds*& cylinderVolumeBounds, - std::shared_ptr<const Transform3D>& transform, - double& rMinClean, - double& rMaxClean, - double& zMinClean, - double& zMaxClean, - BinningValue& bValue, - BinningType /*unused*/) const -{ +bool Acts::CylinderVolumeHelper::estimateAndCheckDimension( + const GeometryContext& gctx, const LayerVector& layers, + const CylinderVolumeBounds*& cylinderVolumeBounds, + std::shared_ptr<const Transform3D>& transform, double& rMinClean, + double& rMaxClean, double& zMinClean, double& zMaxClean, + BinningValue& bValue, BinningType /*unused*/) const { // some verbose output ACTS_VERBOSE("Parsing the " << layers.size() << " layers to gather overall dimensions"); if (cylinderVolumeBounds != nullptr) ACTS_DEBUG("Cylinder volume bounds are given: (rmin/rmax/dz) = " - << "(" - << cylinderVolumeBounds->innerRadius() - << "/" - << cylinderVolumeBounds->outerRadius() - << "/" - << cylinderVolumeBounds->halflengthZ() - << ")"); + << "(" << cylinderVolumeBounds->innerRadius() << "/" + << cylinderVolumeBounds->outerRadius() << "/" + << cylinderVolumeBounds->halflengthZ() << ")"); // prepare for parsing the layers double layerRmin = 10e10; double layerRmax = 0.; double layerZmin = 10e10; double layerZmax = -10e10; - bool radial = false; + bool radial = false; rMinClean = 10e10; rMaxClean = 0.; @@ -510,7 +442,7 @@ Acts::CylinderVolumeHelper::estimateAndCheckDimension( radial = true; // get the raw data double currentR = cylBounds->r(); - double centerZ = (layerIter->surfaceRepresentation()).center(gctx).z(); + double centerZ = (layerIter->surfaceRepresentation()).center(gctx).z(); // check for min/max in the cylinder bounds case currentRmin = currentR - (0.5 * (layerIter)->thickness()); currentRmax = currentR + (0.5 * (layerIter)->thickness()); @@ -523,10 +455,10 @@ Acts::CylinderVolumeHelper::estimateAndCheckDimension( if (discBounds != nullptr) { // check for min/max in the cylinder bounds case double centerZ = (layerIter->surfaceRepresentation()).center(gctx).z(); - currentRmin = discBounds->rMin(); - currentRmax = discBounds->rMax(); - currentZmin = centerZ - (0.5 * (layerIter)->thickness()); - currentZmax = centerZ + (0.5 * (layerIter)->thickness()); + currentRmin = discBounds->rMin(); + currentRmax = discBounds->rMax(); + currentZmin = centerZ - (0.5 * (layerIter)->thickness()); + currentZmax = centerZ + (0.5 * (layerIter)->thickness()); } // the raw data takeSmaller(rMinClean, currentRmin); @@ -543,10 +475,11 @@ Acts::CylinderVolumeHelper::estimateAndCheckDimension( // set the binning value bValue = radial ? binR : binZ; - ACTS_VERBOSE("Estimate/check CylinderVolumeBounds from/w.r.t. enclosed " - "layers + envelope covers"); + ACTS_VERBOSE( + "Estimate/check CylinderVolumeBounds from/w.r.t. enclosed " + "layers + envelope covers"); // the z from the layers w and w/o envelopes - double zEstFromLayerEnv = 0.5 * ((layerZmax) + (layerZmin)); + double zEstFromLayerEnv = 0.5 * ((layerZmax) + (layerZmin)); double halflengthFromLayer = 0.5 * std::abs((layerZmax) - (layerZmin)); bool concentric = (zEstFromLayerEnv * zEstFromLayerEnv < 0.001); @@ -554,8 +487,8 @@ Acts::CylinderVolumeHelper::estimateAndCheckDimension( // no CylinderBounds and Translation given - make it if ((cylinderVolumeBounds == nullptr) && !transform) { // create the CylinderBounds from parsed layer inputs - cylinderVolumeBounds - = new CylinderVolumeBounds(layerRmin, layerRmax, halflengthFromLayer); + cylinderVolumeBounds = + new CylinderVolumeBounds(layerRmin, layerRmax, halflengthFromLayer); // and the transform transform = concentric ? std::make_shared<const Transform3D>( Translation3D(0., 0., zEstFromLayerEnv)) @@ -565,36 +498,28 @@ Acts::CylinderVolumeHelper::estimateAndCheckDimension( Translation3D(0., 0., zEstFromLayerEnv)); } else if (transform && (cylinderVolumeBounds == nullptr)) { // create the CylinderBounds from parsed layer inputs - cylinderVolumeBounds - = new CylinderVolumeBounds(layerRmin, layerRmax, halflengthFromLayer); + cylinderVolumeBounds = + new CylinderVolumeBounds(layerRmin, layerRmax, halflengthFromLayer); } ACTS_VERBOSE(" -> dimensions from layers (rMin/rMax/zMin/zMax) = " - << layerRmin - << " / " - << layerRmax - << " / " - << layerZmin - << " / " + << layerRmin << " / " << layerRmax << " / " << layerZmin << " / " << layerZmax); double zFromTransform = transform ? transform->translation().z() : 0.; ACTS_VERBOSE(" -> while created bounds are (rMin/rMax/zMin/zMax) = " - << cylinderVolumeBounds->innerRadius() - << " / " - << cylinderVolumeBounds->outerRadius() - << " / " - << zFromTransform - cylinderVolumeBounds->halflengthZ() - << " / " + << cylinderVolumeBounds->innerRadius() << " / " + << cylinderVolumeBounds->outerRadius() << " / " + << zFromTransform - cylinderVolumeBounds->halflengthZ() << " / " << zFromTransform + cylinderVolumeBounds->halflengthZ()); // both is NOW given --- check it ----------------------------- if (cylinderVolumeBounds != nullptr) { // only check - if (zFromTransform - cylinderVolumeBounds->halflengthZ() <= layerZmin - && zFromTransform + cylinderVolumeBounds->halflengthZ() >= layerZmax - && cylinderVolumeBounds->innerRadius() <= layerRmin - && cylinderVolumeBounds->outerRadius() >= layerRmax) { + if (zFromTransform - cylinderVolumeBounds->halflengthZ() <= layerZmin && + zFromTransform + cylinderVolumeBounds->halflengthZ() >= layerZmax && + cylinderVolumeBounds->innerRadius() <= layerRmin && + cylinderVolumeBounds->outerRadius() >= layerRmax) { return true; } else { ACTS_WARNING( @@ -602,18 +527,14 @@ Acts::CylinderVolumeHelper::estimateAndCheckDimension( ACTS_WARNING("- zFromTransform: " << zFromTransform); ACTS_WARNING("- volumeZmin:" << zFromTransform - cylinderVolumeBounds->halflengthZ() - << ", layerZmin: " - << layerZmin); + << ", layerZmin: " << layerZmin); ACTS_WARNING("- volumeZmax: " << zFromTransform + cylinderVolumeBounds->halflengthZ() - << ", layerZmax: " - << layerZmax); + << ", layerZmax: " << layerZmax); ACTS_WARNING("- volumeRmin: " << cylinderVolumeBounds->innerRadius() - << ", layerRmin: " - << layerRmin); + << ", layerRmin: " << layerRmin); ACTS_WARNING("- volumeRmax: " << cylinderVolumeBounds->outerRadius() - << ", layerRmax: " - << layerRmax); + << ", layerRmax: " << layerRmax); return false; } } @@ -622,20 +543,12 @@ Acts::CylinderVolumeHelper::estimateAndCheckDimension( return true; } -bool -Acts::CylinderVolumeHelper::interGlueTrackingVolume( - const GeometryContext& gctx, - const std::shared_ptr<TrackingVolume>& tVolume, - bool rBinned, - double rMin, - double rGlueMin, - double rMax, - double zMin, - double zMax) const -{ +bool Acts::CylinderVolumeHelper::interGlueTrackingVolume( + const GeometryContext& gctx, const std::shared_ptr<TrackingVolume>& tVolume, + bool rBinned, double rMin, double rGlueMin, double rMax, double zMin, + double zMax) const { ACTS_VERBOSE("Glue contained TrackingVolumes of container '" - << tVolume->volumeName() - << "'."); + << tVolume->volumeName() << "'."); // only go on if you have confinedVolumes if (tVolume->confinedVolumes()) { @@ -653,9 +566,9 @@ Acts::CylinderVolumeHelper::interGlueTrackingVolume( ACTS_VERBOSE("[" << ivol++ << "] - volume : " << vol->volumeName()); // the needed iterators - auto tVolIter = volumes.begin(); + auto tVolIter = volumes.begin(); auto tVolFirst = volumes.begin(); - auto tVolLast = volumes.end(); + auto tVolLast = volumes.end(); --tVolLast; auto tVolEnd = volumes.end(); @@ -673,8 +586,8 @@ Acts::CylinderVolumeHelper::interGlueTrackingVolume( // screen output ACTS_VERBOSE("r-binning: Processing volume [" << ivol++ << "]"); // for the first one - std::shared_ptr<TrackingVolume> tVol - = std::const_pointer_cast<TrackingVolume>(*tVolIter); + std::shared_ptr<TrackingVolume> tVol = + std::const_pointer_cast<TrackingVolume>(*tVolIter); if (tVolIter == tVolFirst) { addFaceVolumes(tVol, tubeInnerCover, glueVolumesInnerTube); } @@ -685,20 +598,12 @@ Acts::CylinderVolumeHelper::interGlueTrackingVolume( addFaceVolumes(tVol, tubeOuterCover, glueVolumesOuterTube); ++tVolIter; } else { - std::shared_ptr<TrackingVolume> tVol1 - = std::const_pointer_cast<TrackingVolume>(*tVolIter); - std::shared_ptr<TrackingVolume> tVol2 - = std::const_pointer_cast<TrackingVolume>(*(++tVolIter)); - glueTrackingVolumes(gctx, - tVol1, - tubeOuterCover, - tVol2, - tubeInnerCover, - rMin, - rGlueMin, - rMax, - zMin, - zMax); + std::shared_ptr<TrackingVolume> tVol1 = + std::const_pointer_cast<TrackingVolume>(*tVolIter); + std::shared_ptr<TrackingVolume> tVol2 = + std::const_pointer_cast<TrackingVolume>(*(++tVolIter)); + glueTrackingVolumes(gctx, tVol1, tubeOuterCover, tVol2, + tubeInnerCover, rMin, rGlueMin, rMax, zMin, zMax); } } } else { @@ -707,10 +612,9 @@ Acts::CylinderVolumeHelper::interGlueTrackingVolume( for (; tVolIter != tVolEnd;) { // screen output ACTS_VERBOSE("z-binning: Processing volume '" - << (*tVolIter)->volumeName() - << "'."); - std::shared_ptr<TrackingVolume> tVol - = std::const_pointer_cast<TrackingVolume>(*tVolIter); + << (*tVolIter)->volumeName() << "'."); + std::shared_ptr<TrackingVolume> tVol = + std::const_pointer_cast<TrackingVolume>(*tVolIter); if (tVolIter == tVolFirst) { addFaceVolumes(tVol, negativeFaceXY, glueVolumesNegativeFace); } @@ -720,20 +624,12 @@ Acts::CylinderVolumeHelper::interGlueTrackingVolume( addFaceVolumes(tVol, positiveFaceXY, glueVolumesPositiveFace); ++tVolIter; } else { - std::shared_ptr<TrackingVolume> tVol1 - = std::const_pointer_cast<TrackingVolume>(*tVolIter); - std::shared_ptr<TrackingVolume> tVol2 - = std::const_pointer_cast<TrackingVolume>(*(++tVolIter)); - glueTrackingVolumes(gctx, - tVol1, - positiveFaceXY, - tVol2, - negativeFaceXY, - rMin, - rGlueMin, - rMax, - zMin, - zMax); + std::shared_ptr<TrackingVolume> tVol1 = + std::const_pointer_cast<TrackingVolume>(*tVolIter); + std::shared_ptr<TrackingVolume> tVol2 = + std::const_pointer_cast<TrackingVolume>(*(++tVolIter)); + glueTrackingVolumes(gctx, tVol1, positiveFaceXY, tVol2, + negativeFaceXY, rMin, rGlueMin, rMax, zMin, zMax); } } } @@ -741,8 +637,8 @@ Acts::CylinderVolumeHelper::interGlueTrackingVolume( // upstream glueing if (!glueVolumesNegativeFace.empty()) { // create the outside volume array - std::shared_ptr<const TrackingVolumeArray> glueVolumesNegativeFaceArray - = m_cfg.trackingVolumeArrayCreator->trackingVolumeArray( + std::shared_ptr<const TrackingVolumeArray> glueVolumesNegativeFaceArray = + m_cfg.trackingVolumeArrayCreator->trackingVolumeArray( gctx, glueVolumesNegativeFace, binR); // register the glue voluems glueDescr.registerGlueVolumes(negativeFaceXY, @@ -750,8 +646,8 @@ Acts::CylinderVolumeHelper::interGlueTrackingVolume( } if (!glueVolumesPositiveFace.empty()) { // create the outside volume array - std::shared_ptr<const TrackingVolumeArray> glueVolumesPositiveFaceArray - = m_cfg.trackingVolumeArrayCreator->trackingVolumeArray( + std::shared_ptr<const TrackingVolumeArray> glueVolumesPositiveFaceArray = + m_cfg.trackingVolumeArrayCreator->trackingVolumeArray( gctx, glueVolumesPositiveFace, binR); // register the glue voluems glueDescr.registerGlueVolumes(positiveFaceXY, @@ -759,16 +655,16 @@ Acts::CylinderVolumeHelper::interGlueTrackingVolume( } if (!glueVolumesInnerTube.empty()) { // create the outside volume array - std::shared_ptr<const TrackingVolumeArray> glueVolumesInnerTubeArray - = m_cfg.trackingVolumeArrayCreator->trackingVolumeArray( + std::shared_ptr<const TrackingVolumeArray> glueVolumesInnerTubeArray = + m_cfg.trackingVolumeArrayCreator->trackingVolumeArray( gctx, glueVolumesInnerTube, binZ); // register the glue voluems glueDescr.registerGlueVolumes(tubeInnerCover, glueVolumesInnerTubeArray); } if (!glueVolumesOuterTube.empty()) { // create the outside volume array - std::shared_ptr<const TrackingVolumeArray> glueVolumesOuterTubeArray - = m_cfg.trackingVolumeArrayCreator->trackingVolumeArray( + std::shared_ptr<const TrackingVolumeArray> glueVolumesOuterTubeArray = + m_cfg.trackingVolumeArrayCreator->trackingVolumeArray( gctx, glueVolumesOuterTube, binZ); // register the glue voluems glueDescr.registerGlueVolumes(tubeOuterCover, glueVolumesOuterTubeArray); @@ -777,26 +673,22 @@ Acts::CylinderVolumeHelper::interGlueTrackingVolume( ACTS_VERBOSE("[GV] Register " << glueVolumesNegativeFace.size() << " volumes at face negativeFaceXY:"); for (tVolIter = glueVolumesNegativeFace.begin(); - tVolIter != glueVolumesNegativeFace.end(); - ++tVolIter) + tVolIter != glueVolumesNegativeFace.end(); ++tVolIter) ACTS_VERBOSE(" -> volume '" << (*tVolIter)->volumeName() << "'"); ACTS_VERBOSE("[GV] Register " << glueVolumesPositiveFace.size() << " volumes at face positiveFaceXY: "); for (tVolIter = glueVolumesPositiveFace.begin(); - tVolIter != glueVolumesPositiveFace.end(); - ++tVolIter) + tVolIter != glueVolumesPositiveFace.end(); ++tVolIter) ACTS_VERBOSE(" -> volume '" << (*tVolIter)->volumeName() << "'"); ACTS_VERBOSE("[GV] Register " << glueVolumesInnerTube.size() << " volumes at face tubeInnerCover: "); for (tVolIter = glueVolumesInnerTube.begin(); - tVolIter != glueVolumesInnerTube.end(); - ++tVolIter) + tVolIter != glueVolumesInnerTube.end(); ++tVolIter) ACTS_VERBOSE(" -> volume '" << (*tVolIter)->volumeName() << "'"); ACTS_VERBOSE("[GV] Register " << glueVolumesOuterTube.size() << " volumes at face tubeOuterCover:"); for (tVolIter = glueVolumesOuterTube.begin(); - tVolIter != glueVolumesOuterTube.end(); - ++tVolIter) + tVolIter != glueVolumesOuterTube.end(); ++tVolIter) ACTS_VERBOSE(" -> volume '" << (*tVolIter)->volumeName()); } // return success @@ -804,49 +696,41 @@ Acts::CylinderVolumeHelper::interGlueTrackingVolume( } /** private helper method to fill the glue volumes (or the volume itself in) */ -void -Acts::CylinderVolumeHelper::glueTrackingVolumes( - const GeometryContext& gctx, - const std::shared_ptr<TrackingVolume>& tvolOne, - BoundarySurfaceFace faceOne, - const std::shared_ptr<TrackingVolume>& tvolTwo, - BoundarySurfaceFace faceTwo, - double rMin, - double rGlueMin, - double rMax, - double zMin, - double zMax) const -{ +void Acts::CylinderVolumeHelper::glueTrackingVolumes( + const GeometryContext& gctx, const std::shared_ptr<TrackingVolume>& tvolOne, + BoundarySurfaceFace faceOne, const std::shared_ptr<TrackingVolume>& tvolTwo, + BoundarySurfaceFace faceTwo, double rMin, double rGlueMin, double rMax, + double zMin, double zMax) const { // get the two gluevolume descriptors - const GlueVolumesDescriptor& gvDescriptorOne - = tvolOne->glueVolumesDescriptor(); - const GlueVolumesDescriptor& gvDescriptorTwo - = tvolTwo->glueVolumesDescriptor(); - - size_t volOneGlueVols = gvDescriptorOne.glueVolumes(faceOne) - ? gvDescriptorOne.glueVolumes(faceOne)->arrayObjects().size() - : 0; - ACTS_VERBOSE("GlueVolumeDescriptor of volume '" << tvolOne->volumeName() - << "' has " - << volOneGlueVols - << " @ " - << faceOne); - size_t volTwoGlueVols = gvDescriptorTwo.glueVolumes(faceTwo) - ? gvDescriptorTwo.glueVolumes(faceTwo)->arrayObjects().size() - : 0; - ACTS_VERBOSE("GlueVolumeDescriptor of volume '" << tvolTwo->volumeName() - << "' has " - << volTwoGlueVols - << " @ " - << faceTwo); + const GlueVolumesDescriptor& gvDescriptorOne = + tvolOne->glueVolumesDescriptor(); + const GlueVolumesDescriptor& gvDescriptorTwo = + tvolTwo->glueVolumesDescriptor(); + + size_t volOneGlueVols = + gvDescriptorOne.glueVolumes(faceOne) + ? gvDescriptorOne.glueVolumes(faceOne)->arrayObjects().size() + : 0; + ACTS_VERBOSE("GlueVolumeDescriptor of volume '" + << tvolOne->volumeName() << "' has " << volOneGlueVols << " @ " + << faceOne); + size_t volTwoGlueVols = + gvDescriptorTwo.glueVolumes(faceTwo) + ? gvDescriptorTwo.glueVolumes(faceTwo)->arrayObjects().size() + : 0; + ACTS_VERBOSE("GlueVolumeDescriptor of volume '" + << tvolTwo->volumeName() << "' has " << volTwoGlueVols << " @ " + << faceTwo); // they could still be a container though - should not happen usually - TrackingVolumePtr glueVolOne = volOneGlueVols != 0u - ? gvDescriptorOne.glueVolumes(faceOne)->arrayObjects()[0] - : tvolOne; - TrackingVolumePtr glueVolTwo = volTwoGlueVols != 0u - ? gvDescriptorTwo.glueVolumes(faceTwo)->arrayObjects()[0] - : tvolTwo; + TrackingVolumePtr glueVolOne = + volOneGlueVols != 0u + ? gvDescriptorOne.glueVolumes(faceOne)->arrayObjects()[0] + : tvolOne; + TrackingVolumePtr glueVolTwo = + volTwoGlueVols != 0u + ? gvDescriptorTwo.glueVolumes(faceTwo)->arrayObjects()[0] + : tvolTwo; // We'll need to mutate those volumes in order to glue them together auto mutableGlueVolOne = std::const_pointer_cast<TrackingVolume>(glueVolOne); @@ -856,55 +740,41 @@ Acts::CylinderVolumeHelper::glueTrackingVolumes( if (volOneGlueVols <= 1 && volTwoGlueVols <= 1) { // (i) one -> one ACTS_VERBOSE(" glue : one[ " << glueVolOne->volumeName() << " @ " - << faceOne - << " ]-to-one[ " - << glueVolTwo->volumeName() - << " @ " - << faceTwo - << " ]"); + << faceOne << " ]-to-one[ " + << glueVolTwo->volumeName() << " @ " + << faceTwo << " ]"); // one to one is easy - mutableGlueVolOne->glueTrackingVolume( - gctx, faceOne, mutableGlueVolTwo, faceTwo); + mutableGlueVolOne->glueTrackingVolume(gctx, faceOne, mutableGlueVolTwo, + faceTwo); } else if (volOneGlueVols <= 1) { // (ii) one -> many - ACTS_VERBOSE(" glue : one[ " << glueVolOne->volumeName() << " @ " - << faceOne - << " ]-to-many[ " - << tvolTwo->volumeName() - << " @ " - << faceTwo - << " ]"); + ACTS_VERBOSE(" glue : one[ " + << glueVolOne->volumeName() << " @ " << faceOne + << " ]-to-many[ " << tvolTwo->volumeName() << " @ " << faceTwo + << " ]"); auto mutableFaceTwoVolumes = std::const_pointer_cast<TrackingVolumeArray>( gvDescriptorTwo.glueVolumes(faceTwo)); - mutableGlueVolOne->glueTrackingVolumes( - gctx, faceOne, mutableFaceTwoVolumes, faceTwo); + mutableGlueVolOne->glueTrackingVolumes(gctx, faceOne, mutableFaceTwoVolumes, + faceTwo); } else if (volTwoGlueVols <= 1) { // (iii) many -> one - ACTS_VERBOSE(" glue : many[ " << tvolOne->volumeName() << " @ " - << faceOne - << " ]-to-one[ " - << glueVolTwo->volumeName() - << " @ " - << faceTwo - << " ]"); + ACTS_VERBOSE(" glue : many[ " + << tvolOne->volumeName() << " @ " << faceOne << " ]-to-one[ " + << glueVolTwo->volumeName() << " @ " << faceTwo << " ]"); auto mutableFaceOneVolumes = std::const_pointer_cast<TrackingVolumeArray>( gvDescriptorOne.glueVolumes(faceOne)); - mutableGlueVolTwo->glueTrackingVolumes( - gctx, faceTwo, mutableFaceOneVolumes, faceOne); + mutableGlueVolTwo->glueTrackingVolumes(gctx, faceTwo, mutableFaceOneVolumes, + faceOne); } else { // (iv) glue array to array - ACTS_VERBOSE(" glue : many[ " << tvolOne->volumeName() << " @ " - << faceOne - << " ]-to-many[ " - << tvolTwo->volumeName() - << " @ " - << faceTwo - << " ]"); + ACTS_VERBOSE(" glue : many[ " + << tvolOne->volumeName() << " @ " << faceOne << " ]-to-many[ " + << tvolTwo->volumeName() << " @ " << faceTwo << " ]"); // create the BoundarySurface as shared pointer - std::shared_ptr<const BoundarySurfaceT<TrackingVolume>> boundarySurface - = nullptr; + std::shared_ptr<const BoundarySurfaceT<TrackingVolume>> boundarySurface = + nullptr; // the transform of the new boundary surface std::shared_ptr<const Transform3D> transform = nullptr; @@ -918,17 +788,17 @@ Acts::CylinderVolumeHelper::glueTrackingVolumes( if (faceOne == cylinderCover || faceOne == tubeOuterCover) { // (1) create the BoundaryCylinderSurface // now create the CylinderSurface - std::shared_ptr<const Surface> cSurface - = Surface::makeShared<CylinderSurface>( - transform, rGlueMin, 0.5 * (zMax - zMin)); - ACTS_VERBOSE(" creating a new cylindrical boundary surface " - "with bounds = " - << cSurface->bounds()); + std::shared_ptr<const Surface> cSurface = + Surface::makeShared<CylinderSurface>(transform, rGlueMin, + 0.5 * (zMax - zMin)); + ACTS_VERBOSE( + " creating a new cylindrical boundary surface " + "with bounds = " + << cSurface->bounds()); ACTS_VERBOSE(" at " << cSurface->center(gctx).transpose()); - boundarySurface - = std::make_shared<const BoundarySurfaceT<TrackingVolume>>( - std::move(cSurface), - gvDescriptorOne.glueVolumes(faceOne), + boundarySurface = + std::make_shared<const BoundarySurfaceT<TrackingVolume>>( + std::move(cSurface), gvDescriptorOne.glueVolumes(faceOne), gvDescriptorTwo.glueVolumes(faceTwo)); } else { // Calculate correct position for disc surface @@ -937,60 +807,56 @@ Acts::CylinderVolumeHelper::glueTrackingVolumes( auto cylVolBounds = dynamic_cast<const Acts::CylinderVolumeBounds*>( &tvolOne->volumeBounds()); double zPos = tvolOne->center().z(); - double zHL = cylVolBounds->halflengthZ(); - transform = std::make_shared<const Transform3D>( - Translation3D(0, 0, zPos + zHL)); + double zHL = cylVolBounds->halflengthZ(); + transform = + std::make_shared<const Transform3D>(Translation3D(0, 0, zPos + zHL)); // this puts the surface on the positive z side of the cyl vol bounds // iteration is from neg to pos, so it should always be in between. // (2) create the BoundaryDiscSurface, in that case the zMin/zMax provided // are both the position of the disk in question - std::shared_ptr<const Surface> dSurface - = Surface::makeShared<DiscSurface>(transform, rMin, rMax); - ACTS_VERBOSE(" creating a new disc-like boundary surface " - "with bounds = " - << dSurface->bounds()); + std::shared_ptr<const Surface> dSurface = + Surface::makeShared<DiscSurface>(transform, rMin, rMax); + ACTS_VERBOSE( + " creating a new disc-like boundary surface " + "with bounds = " + << dSurface->bounds()); ACTS_VERBOSE(" at " << dSurface->center(gctx).transpose()); - boundarySurface - = std::make_shared<const BoundarySurfaceT<TrackingVolume>>( - std::move(dSurface), - gvDescriptorOne.glueVolumes(faceOne), + boundarySurface = + std::make_shared<const BoundarySurfaceT<TrackingVolume>>( + std::move(dSurface), gvDescriptorOne.glueVolumes(faceOne), gvDescriptorTwo.glueVolumes(faceTwo)); } // update the volume with the boundary surface accordingly // it's safe to access directly, they can not be nullptr for (auto& oneVolume : gvDescriptorOne.glueVolumes(faceOne)->arrayObjects()) { - auto mutableOneVolume - = std::const_pointer_cast<TrackingVolume>(oneVolume); + auto mutableOneVolume = + std::const_pointer_cast<TrackingVolume>(oneVolume); mutableOneVolume->updateBoundarySurface(faceOne, boundarySurface); } for (auto& twoVolume : gvDescriptorTwo.glueVolumes(faceTwo)->arrayObjects()) { - auto mutableTwoVolume - = std::const_pointer_cast<TrackingVolume>(twoVolume); + auto mutableTwoVolume = + std::const_pointer_cast<TrackingVolume>(twoVolume); mutableTwoVolume->updateBoundarySurface(faceTwo, boundarySurface); } } // end of case (iv) } /** Private method - helper method not to duplicate code */ -void -Acts::CylinderVolumeHelper::addFaceVolumes( - const std::shared_ptr<TrackingVolume>& tvol, - BoundarySurfaceFace glueFace, - TrackingVolumeVector& vols) const -{ +void Acts::CylinderVolumeHelper::addFaceVolumes( + const std::shared_ptr<TrackingVolume>& tvol, BoundarySurfaceFace glueFace, + TrackingVolumeVector& vols) const { ACTS_VERBOSE("Adding face volumes of face " << glueFace << " for the volume '" - << tvol->volumeName() - << "'."); + << tvol->volumeName() << "'."); // retrieve the gluevolume descriptor const GlueVolumesDescriptor& gvDescriptor = tvol->glueVolumesDescriptor(); // if volumes are registered: take them if (gvDescriptor.glueVolumes(glueFace)) { // get the navigation level subvolumes auto volIter = gvDescriptor.glueVolumes(glueFace)->arrayObjects().begin(); - auto volEnd = gvDescriptor.glueVolumes(glueFace)->arrayObjects().end(); + auto volEnd = gvDescriptor.glueVolumes(glueFace)->arrayObjects().end(); for (; volIter != volEnd; ++volIter) { ACTS_VERBOSE(" -> adding : " << (*volIter)->volumeName()); vols.push_back(*volIter); @@ -1006,23 +872,21 @@ Acts::CylinderVolumeHelper::addFaceVolumes( } std::shared_ptr<const Acts::Layer> -Acts::CylinderVolumeHelper::createCylinderLayer(double z, - double r, +Acts::CylinderVolumeHelper::createCylinderLayer(double z, double r, double halflengthZ, - double thickness, - int binsPhi, - int binsZ) const -{ + double thickness, int binsPhi, + int binsZ) const { ACTS_VERBOSE("Creating a CylinderLayer at position " << z << " and radius " << r); // positioning - std::shared_ptr<const Transform3D> transform = (std::abs(z) > 0.1) - ? std::make_shared<const Transform3D>(Translation3D(0., 0., z)) - : nullptr; + std::shared_ptr<const Transform3D> transform = + (std::abs(z) > 0.1) + ? std::make_shared<const Transform3D>(Translation3D(0., 0., z)) + : nullptr; // z-binning - BinUtility layerBinUtility( - binsZ, z - halflengthZ, z + halflengthZ, open, binZ); + BinUtility layerBinUtility(binsZ, z - halflengthZ, z + halflengthZ, open, + binZ); if (binsPhi == 1) { // the BinUtility for the material // ---------------------> create material for the layer surface @@ -1031,42 +895,33 @@ Acts::CylinderVolumeHelper::createCylinderLayer(double z, } else { // break the phi symmetry // update the BinUtility: local position on Cylinder is rPhi, z - BinUtility layerBinUtilityPhiZ( - binsPhi, -r * M_PI, +r * M_PI, closed, binPhi); + BinUtility layerBinUtilityPhiZ(binsPhi, -r * M_PI, +r * M_PI, closed, + binPhi); layerBinUtilityPhiZ += layerBinUtility; // ---------------------> create material for the layer surface - ACTS_VERBOSE( - " -> Preparing the binned material with " << binsPhi << " / " << binsZ - << " bins in phi / Z. "); + ACTS_VERBOSE(" -> Preparing the binned material with " + << binsPhi << " / " << binsZ << " bins in phi / Z. "); } // @todo create the SurfaceMaterial // bounds for cylinderical surface CylinderBounds* cylinderBounds = new CylinderBounds(r, halflengthZ); // create the cylinder return CylinderLayer::create( - transform, - std::shared_ptr<const CylinderBounds>(cylinderBounds), - nullptr, + transform, std::shared_ptr<const CylinderBounds>(cylinderBounds), nullptr, thickness); } -std::shared_ptr<const Acts::Layer> -Acts::CylinderVolumeHelper::createDiscLayer(double z, - double rMin, - double rMax, - double thickness, - int binsPhi, - int binsR) const -{ +std::shared_ptr<const Acts::Layer> Acts::CylinderVolumeHelper::createDiscLayer( + double z, double rMin, double rMax, double thickness, int binsPhi, + int binsR) const { ACTS_VERBOSE("Creating a DiscLayer at position " << z << " and rMin/rMax " - << rMin - << " / " - << rMax); + << rMin << " / " << rMax); // positioning - std::shared_ptr<const Transform3D> transform = (std::abs(z) > 0.1) - ? std::make_shared<const Transform3D>(Translation3D(0., 0., z)) - : nullptr; + std::shared_ptr<const Transform3D> transform = + (std::abs(z) > 0.1) + ? std::make_shared<const Transform3D>(Translation3D(0., 0., z)) + : nullptr; // R is the primary binning for the material BinUtility materialBinUtility(binsR, rMin, rMax, open, binR); @@ -1076,9 +931,8 @@ Acts::CylinderVolumeHelper::createDiscLayer(double z, } else { // also binning in phi chosen materialBinUtility += BinUtility(binsPhi, -M_PI, M_PI, closed, binPhi); - ACTS_VERBOSE( - " -> Preparing the binned material with " << binsPhi << " / " << binsR - << " bins in phi / R. "); + ACTS_VERBOSE(" -> Preparing the binned material with " + << binsPhi << " / " << binsR << " bins in phi / R. "); } // @todo create the SurfaceMaterial @@ -1087,6 +941,5 @@ Acts::CylinderVolumeHelper::createDiscLayer(double z, // create the disc return DiscLayer::create(transform, std::shared_ptr<const DiscBounds>(discBounds), - nullptr, - thickness); + nullptr, thickness); } diff --git a/Core/src/Geometry/DiscLayer.cpp b/Core/src/Geometry/DiscLayer.cpp index e0bbdd421b3bdcca094c70537c42426cd6c4a479..a7dfb26fdfe08c8a699873a397e2c5a4d62350da 100644 --- a/Core/src/Geometry/DiscLayer.cpp +++ b/Core/src/Geometry/DiscLayer.cpp @@ -21,28 +21,27 @@ #include "Acts/Utilities/BinUtility.hpp" #include "Acts/Utilities/Definitions.hpp" -using Acts::VectorHelpers::phi; using Acts::VectorHelpers::perp; +using Acts::VectorHelpers::phi; Acts::DiscLayer::DiscLayer(const std::shared_ptr<const Transform3D>& transform, - const std::shared_ptr<const DiscBounds>& dbounds, - std::unique_ptr<SurfaceArray> surfaceArray, - double thickness, + const std::shared_ptr<const DiscBounds>& dbounds, + std::unique_ptr<SurfaceArray> surfaceArray, + double thickness, std::unique_ptr<ApproachDescriptor> ades, - LayerType laytyp) - : DiscSurface(transform, dbounds) - , Layer(std::move(surfaceArray), thickness, std::move(ades), laytyp) -{ + LayerType laytyp) + : DiscSurface(transform, dbounds), + Layer(std::move(surfaceArray), thickness, std::move(ades), laytyp) { // In case we have Radial bounds - const RadialBounds* rBounds - = dynamic_cast<const RadialBounds*>(DiscSurface::m_bounds.get()); + const RadialBounds* rBounds = + dynamic_cast<const RadialBounds*>(DiscSurface::m_bounds.get()); if (rBounds != nullptr) { // The volume bounds - auto rVolumeBounds - = std::make_shared<const CylinderVolumeBounds>(*rBounds, thickness); + auto rVolumeBounds = + std::make_shared<const CylinderVolumeBounds>(*rBounds, thickness); // @todo rotate around x for the avePhi if you have a sector - m_representingVolume - = std::make_unique<AbstractVolume>(m_transform, rVolumeBounds); + m_representingVolume = + std::make_unique<AbstractVolume>(m_transform, rVolumeBounds); } // associate the layer to the layer surface itself DiscSurface::associateLayer(*this); @@ -56,29 +55,22 @@ Acts::DiscLayer::DiscLayer(const std::shared_ptr<const Transform3D>& transform, } } -const Acts::DiscSurface& -Acts::DiscLayer::surfaceRepresentation() const -{ +const Acts::DiscSurface& Acts::DiscLayer::surfaceRepresentation() const { return (*this); } -Acts::DiscSurface& -Acts::DiscLayer::surfaceRepresentation() -{ +Acts::DiscSurface& Acts::DiscLayer::surfaceRepresentation() { return (*this); } -void -Acts::DiscLayer::buildApproachDescriptor() -{ +void Acts::DiscLayer::buildApproachDescriptor() { // delete it m_approachDescriptor.reset(nullptr); // take the boundary surfaces of the representving volume if they exist if (m_representingVolume != nullptr) { // get the boundary surfaces const std::vector<std::shared_ptr<const BoundarySurfaceT<AbstractVolume>>>& - bSurfaces - = m_representingVolume->boundarySurfaces(); + bSurfaces = m_representingVolume->boundarySurfaces(); // fill in the surfaces into the vector std::vector<std::shared_ptr<const Surface>> aSurfaces; aSurfaces.push_back( @@ -86,8 +78,8 @@ Acts::DiscLayer::buildApproachDescriptor() aSurfaces.push_back( bSurfaces.at(positiveFaceXY)->surfaceRepresentation().getSharedPtr()); // create an ApproachDescriptor with Boundary surfaces - m_approachDescriptor = std::make_unique<const GenericApproachDescriptor>( - std::move(aSurfaces)); + m_approachDescriptor = + std::make_unique<const GenericApproachDescriptor>(std::move(aSurfaces)); } // @todo check if we can give the layer at curface creation diff --git a/Core/src/Geometry/DoubleTrapezoidVolumeBounds.cpp b/Core/src/Geometry/DoubleTrapezoidVolumeBounds.cpp index 256c61cdb6d925811bd31a4e3ad225730c70b515..ae511c251653a0c3dcbe5ef0f634ca676ff42892 100644 --- a/Core/src/Geometry/DoubleTrapezoidVolumeBounds.cpp +++ b/Core/src/Geometry/DoubleTrapezoidVolumeBounds.cpp @@ -19,44 +19,34 @@ #include "Acts/Surfaces/RectangleBounds.hpp" Acts::DoubleTrapezoidVolumeBounds::DoubleTrapezoidVolumeBounds() - : VolumeBounds(), m_valueStore(bv_length, 0.) -{ -} + : VolumeBounds(), m_valueStore(bv_length, 0.) {} -Acts::DoubleTrapezoidVolumeBounds::DoubleTrapezoidVolumeBounds(double minhalex, - double medhalex, - double maxhalex, - double haley1, - double haley2, - double halez) - : VolumeBounds(), m_valueStore(bv_length, 0.) -{ +Acts::DoubleTrapezoidVolumeBounds::DoubleTrapezoidVolumeBounds( + double minhalex, double medhalex, double maxhalex, double haley1, + double haley2, double halez) + : VolumeBounds(), m_valueStore(bv_length, 0.) { m_valueStore.at(bv_minHalfX) = minhalex; m_valueStore.at(bv_medHalfX) = medhalex; m_valueStore.at(bv_maxHalfX) = maxhalex; - m_valueStore.at(bv_halfY1) = haley1; - m_valueStore.at(bv_halfY2) = haley2; - m_valueStore.at(bv_halfZ) = halez; - m_valueStore.at(bv_alpha1) - = atan2(m_valueStore.at(bv_medHalfX) - m_valueStore.at(bv_minHalfX), - 2. * m_valueStore.at(bv_halfY1)); - m_valueStore.at(bv_alpha2) - = atan2(m_valueStore.at(bv_medHalfX) - m_valueStore.at(bv_maxHalfX), - 2. * m_valueStore.at(bv_halfY2)); + m_valueStore.at(bv_halfY1) = haley1; + m_valueStore.at(bv_halfY2) = haley2; + m_valueStore.at(bv_halfZ) = halez; + m_valueStore.at(bv_alpha1) = + atan2(m_valueStore.at(bv_medHalfX) - m_valueStore.at(bv_minHalfX), + 2. * m_valueStore.at(bv_halfY1)); + m_valueStore.at(bv_alpha2) = + atan2(m_valueStore.at(bv_medHalfX) - m_valueStore.at(bv_maxHalfX), + 2. * m_valueStore.at(bv_halfY2)); } Acts::DoubleTrapezoidVolumeBounds::DoubleTrapezoidVolumeBounds( const Acts::DoubleTrapezoidVolumeBounds& trabo) - : VolumeBounds(), m_valueStore(trabo.m_valueStore) -{ -} + : VolumeBounds(), m_valueStore(trabo.m_valueStore) {} Acts::DoubleTrapezoidVolumeBounds::~DoubleTrapezoidVolumeBounds() = default; -Acts::DoubleTrapezoidVolumeBounds& -Acts::DoubleTrapezoidVolumeBounds:: -operator=(const Acts::DoubleTrapezoidVolumeBounds& trabo) -{ +Acts::DoubleTrapezoidVolumeBounds& Acts::DoubleTrapezoidVolumeBounds::operator=( + const Acts::DoubleTrapezoidVolumeBounds& trabo) { if (this != &trabo) { m_valueStore = trabo.m_valueStore; } @@ -65,119 +55,117 @@ operator=(const Acts::DoubleTrapezoidVolumeBounds& trabo) std::vector<std::shared_ptr<const Acts::Surface>> Acts::DoubleTrapezoidVolumeBounds::decomposeToSurfaces( - const Transform3D* transformPtr) const -{ + const Transform3D* transformPtr) const { std::vector<std::shared_ptr<const Surface>> rSurfaces; // the transform - Transform3D transform - = (transformPtr == nullptr) ? Transform3D::Identity() : (*transformPtr); + Transform3D transform = + (transformPtr == nullptr) ? Transform3D::Identity() : (*transformPtr); // face surfaces xy RotationMatrix3D diamondRotation(transform.rotation()); - Vector3D diamondX(diamondRotation.col(0)); - Vector3D diamondY(diamondRotation.col(1)); - Vector3D diamondZ(diamondRotation.col(2)); - Vector3D diamondCenter(transform.translation()); + Vector3D diamondX(diamondRotation.col(0)); + Vector3D diamondY(diamondRotation.col(1)); + Vector3D diamondZ(diamondRotation.col(2)); + Vector3D diamondCenter(transform.translation()); const Transform3D* tTransform = nullptr; // (1) - at negative local z - tTransform - = new Transform3D(transform * AngleAxis3D(M_PI, Vector3D(0., 1., 0.)) - * Translation3D(Vector3D(0., 0., halflengthZ()))); + tTransform = + new Transform3D(transform * AngleAxis3D(M_PI, Vector3D(0., 1., 0.)) * + Translation3D(Vector3D(0., 0., halflengthZ()))); rSurfaces.push_back(Surface::makeShared<PlaneSurface>( std::shared_ptr<const Transform3D>(tTransform), std::shared_ptr<const PlanarBounds>(faceXYDiamondBounds()))); // (2) - at positive local z - tTransform = new Transform3D( - transform * Translation3D(Vector3D(0., 0., halflengthZ()))); + tTransform = new Transform3D(transform * + Translation3D(Vector3D(0., 0., halflengthZ()))); rSurfaces.push_back(Surface::makeShared<PlaneSurface>( std::shared_ptr<const Transform3D>(tTransform), std::shared_ptr<const PlanarBounds>(faceXYDiamondBounds()))); // face surfaces yz // transmute cyclical // (3) - at point A, attached to alpha opening angle - Vector3D A(diamondCenter - minHalflengthX() * diamondX - - 2 * halflengthY1() * diamondY); - AngleAxis3D alpha1ZRotation(alpha1(), Vector3D(0., 0., 1.)); + Vector3D A(diamondCenter - minHalflengthX() * diamondX - + 2 * halflengthY1() * diamondY); + AngleAxis3D alpha1ZRotation(alpha1(), Vector3D(0., 0., 1.)); RotationMatrix3D alpha1Rotation( - diamondRotation * alpha1ZRotation - * AngleAxis3D(-0.5 * M_PI, Vector3D(0., 1., 0.)) - * AngleAxis3D(0.5 * M_PI, Vector3D(0., 0., 1.))); + diamondRotation * alpha1ZRotation * + AngleAxis3D(-0.5 * M_PI, Vector3D(0., 1., 0.)) * + AngleAxis3D(0.5 * M_PI, Vector3D(0., 0., 1.))); RectangleBounds* faceAlpha1Bounds = faceAlpha1RectangleBounds(); - Vector3D faceAlpha1Position( - A + alpha1Rotation.col(0) * faceAlpha1Bounds->halflengthX()); - tTransform - = new Transform3D(Translation3D(faceAlpha1Position) * alpha1Rotation); + Vector3D faceAlpha1Position(A + alpha1Rotation.col(0) * + faceAlpha1Bounds->halflengthX()); + tTransform = + new Transform3D(Translation3D(faceAlpha1Position) * alpha1Rotation); rSurfaces.push_back(Surface::makeShared<PlaneSurface>( std::shared_ptr<const Transform3D>(tTransform), std::shared_ptr<const PlanarBounds>(faceAlpha1Bounds))); // (4) - at point B, attached to beta opening angle - Vector3D B(diamondCenter + minHalflengthX() * diamondX - - 2 * halflengthY1() * diamondY); - AngleAxis3D beta1ZRotation(-alpha1(), Vector3D(0., 0., 1.)); - RotationMatrix3D beta1Rotation( - diamondRotation * beta1ZRotation - * AngleAxis3D(0.5 * M_PI, Vector3D(0., 1., 0.)) - * AngleAxis3D(0.5 * M_PI, Vector3D(0., 0., 1.))); + Vector3D B(diamondCenter + minHalflengthX() * diamondX - + 2 * halflengthY1() * diamondY); + AngleAxis3D beta1ZRotation(-alpha1(), Vector3D(0., 0., 1.)); + RotationMatrix3D beta1Rotation(diamondRotation * beta1ZRotation * + AngleAxis3D(0.5 * M_PI, Vector3D(0., 1., 0.)) * + AngleAxis3D(0.5 * M_PI, Vector3D(0., 0., 1.))); RectangleBounds* faceBeta1Bounds = faceBeta1RectangleBounds(); - Vector3D faceBeta1Position( - B + beta1Rotation.col(0) * faceBeta1Bounds->halflengthX()); - tTransform - = new Transform3D(Translation3D(faceBeta1Position) * beta1Rotation); + Vector3D faceBeta1Position(B + beta1Rotation.col(0) * + faceBeta1Bounds->halflengthX()); + tTransform = + new Transform3D(Translation3D(faceBeta1Position) * beta1Rotation); rSurfaces.push_back(Surface::makeShared<PlaneSurface>( std::shared_ptr<const Transform3D>(tTransform), std::shared_ptr<const PlanarBounds>(faceBeta1Bounds))); // face surfaces yz // transmute cyclical // (5) - at point A', attached to alpha opening angle - Vector3D AA(diamondCenter - maxHalflengthX() * diamondX - + 2 * halflengthY2() * diamondY); - AngleAxis3D alpha2ZRotation(-alpha2(), Vector3D(0., 0., 1.)); + Vector3D AA(diamondCenter - maxHalflengthX() * diamondX + + 2 * halflengthY2() * diamondY); + AngleAxis3D alpha2ZRotation(-alpha2(), Vector3D(0., 0., 1.)); RotationMatrix3D alpha2Rotation( - diamondRotation * alpha2ZRotation - * AngleAxis3D(-0.5 * M_PI, Vector3D(0., 1., 0.)) - * AngleAxis3D(-0.5 * M_PI, Vector3D(0., 0., 1.))); + diamondRotation * alpha2ZRotation * + AngleAxis3D(-0.5 * M_PI, Vector3D(0., 1., 0.)) * + AngleAxis3D(-0.5 * M_PI, Vector3D(0., 0., 1.))); RectangleBounds* faceAlpha2Bounds = faceAlpha2RectangleBounds(); - Vector3D faceAlpha2Position( - AA + alpha2Rotation.col(0) * faceAlpha2Bounds->halflengthX()); - tTransform - = new Transform3D(Translation3D(faceAlpha2Position) * alpha2Rotation); + Vector3D faceAlpha2Position(AA + alpha2Rotation.col(0) * + faceAlpha2Bounds->halflengthX()); + tTransform = + new Transform3D(Translation3D(faceAlpha2Position) * alpha2Rotation); rSurfaces.push_back(Surface::makeShared<PlaneSurface>( std::shared_ptr<const Transform3D>(tTransform), std::shared_ptr<const PlanarBounds>(faceAlpha2Bounds))); // (6) - at point B', attached to beta opening angle - Vector3D BB(diamondCenter + maxHalflengthX() * diamondX - + 2 * halflengthY2() * diamondY); - AngleAxis3D beta2ZRotation(alpha2(), Vector3D(0., 0., 1.)); + Vector3D BB(diamondCenter + maxHalflengthX() * diamondX + + 2 * halflengthY2() * diamondY); + AngleAxis3D beta2ZRotation(alpha2(), Vector3D(0., 0., 1.)); RotationMatrix3D beta2Rotation( - diamondRotation * beta2ZRotation - * AngleAxis3D(0.5 * M_PI, Vector3D(0., 1., 0.)) - * AngleAxis3D(-0.5 * M_PI, Vector3D(0., 0., 1.))); + diamondRotation * beta2ZRotation * + AngleAxis3D(0.5 * M_PI, Vector3D(0., 1., 0.)) * + AngleAxis3D(-0.5 * M_PI, Vector3D(0., 0., 1.))); RectangleBounds* faceBeta2Bounds = faceBeta2RectangleBounds(); - Vector3D faceBeta2Position( - BB + beta2Rotation.col(0) * faceBeta2Bounds->halflengthX()); - tTransform - = new Transform3D(Translation3D(faceBeta2Position) * beta2Rotation); + Vector3D faceBeta2Position(BB + beta2Rotation.col(0) * + faceBeta2Bounds->halflengthX()); + tTransform = + new Transform3D(Translation3D(faceBeta2Position) * beta2Rotation); rSurfaces.push_back(Surface::makeShared<PlaneSurface>( std::shared_ptr<const Transform3D>(tTransform), std::shared_ptr<const PlanarBounds>(faceBeta2Bounds))); // face surfaces zx // (7) - at negative local y - tTransform - = new Transform3D(transform * AngleAxis3D(M_PI, Vector3D(1., 0., 0.)) - * Translation3D(Vector3D(0., 2 * halflengthY1(), 0.)) - * AngleAxis3D(-0.5 * M_PI, Vector3D(0., 1., 0.)) - * AngleAxis3D(-0.5 * M_PI, Vector3D(1., 0., 0.))); + tTransform = + new Transform3D(transform * AngleAxis3D(M_PI, Vector3D(1., 0., 0.)) * + Translation3D(Vector3D(0., 2 * halflengthY1(), 0.)) * + AngleAxis3D(-0.5 * M_PI, Vector3D(0., 1., 0.)) * + AngleAxis3D(-0.5 * M_PI, Vector3D(1., 0., 0.))); rSurfaces.push_back(Surface::makeShared<PlaneSurface>( std::shared_ptr<const Transform3D>(tTransform), std::shared_ptr<const PlanarBounds>(faceZXRectangleBoundsBottom()))); // (8) - at positive local y tTransform = new Transform3D( - transform * Translation3D(Vector3D(0., 2 * halflengthY2(), 0.)) - * AngleAxis3D(-0.5 * M_PI, Vector3D(0., 1., 0.)) - * AngleAxis3D(-0.5 * M_PI, Vector3D(1., 0., 0.))); + transform * Translation3D(Vector3D(0., 2 * halflengthY2(), 0.)) * + AngleAxis3D(-0.5 * M_PI, Vector3D(0., 1., 0.)) * + AngleAxis3D(-0.5 * M_PI, Vector3D(1., 0., 0.))); rSurfaces.push_back(Surface::makeShared<PlaneSurface>( std::shared_ptr<const Transform3D>(tTransform), std::shared_ptr<const PlanarBounds>(faceZXRectangleBoundsTop()))); @@ -186,65 +174,56 @@ Acts::DoubleTrapezoidVolumeBounds::decomposeToSurfaces( } // faces in xy -Acts::DiamondBounds* -Acts::DoubleTrapezoidVolumeBounds::faceXYDiamondBounds() const -{ - return new DiamondBounds(m_valueStore.at(bv_minHalfX), - m_valueStore.at(bv_medHalfX), - m_valueStore.at(bv_maxHalfX), - 2 * m_valueStore.at(bv_halfY1), - 2 * m_valueStore.at(bv_halfY2)); +Acts::DiamondBounds* Acts::DoubleTrapezoidVolumeBounds::faceXYDiamondBounds() + const { + return new DiamondBounds( + m_valueStore.at(bv_minHalfX), m_valueStore.at(bv_medHalfX), + m_valueStore.at(bv_maxHalfX), 2 * m_valueStore.at(bv_halfY1), + 2 * m_valueStore.at(bv_halfY2)); } Acts::RectangleBounds* -Acts::DoubleTrapezoidVolumeBounds::faceAlpha1RectangleBounds() const -{ - return new RectangleBounds(m_valueStore.at(bv_halfY1) - / cos(m_valueStore.at(bv_alpha1)), - m_valueStore.at(bv_halfZ)); +Acts::DoubleTrapezoidVolumeBounds::faceAlpha1RectangleBounds() const { + return new RectangleBounds( + m_valueStore.at(bv_halfY1) / cos(m_valueStore.at(bv_alpha1)), + m_valueStore.at(bv_halfZ)); } Acts::RectangleBounds* -Acts::DoubleTrapezoidVolumeBounds::faceAlpha2RectangleBounds() const -{ - return new RectangleBounds(m_valueStore.at(bv_halfY2) - / cos(m_valueStore.at(bv_alpha2)), - m_valueStore.at(bv_halfZ)); +Acts::DoubleTrapezoidVolumeBounds::faceAlpha2RectangleBounds() const { + return new RectangleBounds( + m_valueStore.at(bv_halfY2) / cos(m_valueStore.at(bv_alpha2)), + m_valueStore.at(bv_halfZ)); } Acts::RectangleBounds* -Acts::DoubleTrapezoidVolumeBounds::faceBeta1RectangleBounds() const -{ - return new RectangleBounds(m_valueStore.at(bv_halfY1) - / cos(m_valueStore.at(bv_alpha1)), - m_valueStore.at(bv_halfZ)); +Acts::DoubleTrapezoidVolumeBounds::faceBeta1RectangleBounds() const { + return new RectangleBounds( + m_valueStore.at(bv_halfY1) / cos(m_valueStore.at(bv_alpha1)), + m_valueStore.at(bv_halfZ)); } Acts::RectangleBounds* -Acts::DoubleTrapezoidVolumeBounds::faceBeta2RectangleBounds() const -{ - return new RectangleBounds(m_valueStore.at(bv_halfY2) - / cos(m_valueStore.at(bv_alpha2)), - m_valueStore.at(bv_halfZ)); +Acts::DoubleTrapezoidVolumeBounds::faceBeta2RectangleBounds() const { + return new RectangleBounds( + m_valueStore.at(bv_halfY2) / cos(m_valueStore.at(bv_alpha2)), + m_valueStore.at(bv_halfZ)); } Acts::RectangleBounds* -Acts::DoubleTrapezoidVolumeBounds::faceZXRectangleBoundsBottom() const -{ +Acts::DoubleTrapezoidVolumeBounds::faceZXRectangleBoundsBottom() const { return new RectangleBounds(m_valueStore.at(bv_halfZ), m_valueStore.at(bv_minHalfX)); } Acts::RectangleBounds* -Acts::DoubleTrapezoidVolumeBounds::faceZXRectangleBoundsTop() const -{ +Acts::DoubleTrapezoidVolumeBounds::faceZXRectangleBoundsTop() const { return new RectangleBounds(m_valueStore.at(bv_halfZ), m_valueStore.at(bv_maxHalfX)); } -bool -Acts::DoubleTrapezoidVolumeBounds::inside(const Vector3D& pos, double tol) const -{ +bool Acts::DoubleTrapezoidVolumeBounds::inside(const Vector3D& pos, + double tol) const { if (std::abs(pos.z()) > m_valueStore.at(bv_halfZ) + tol) { return false; } @@ -255,15 +234,14 @@ Acts::DoubleTrapezoidVolumeBounds::inside(const Vector3D& pos, double tol) const return false; } DiamondBounds* faceXYBounds = faceXYDiamondBounds(); - Vector2D locp(pos.x(), pos.y()); + Vector2D locp(pos.x(), pos.y()); bool inside(faceXYBounds->inside(locp, BoundaryCheck(true, true, tol, tol))); delete faceXYBounds; return inside; } // ostream operator overload -std::ostream& -Acts::DoubleTrapezoidVolumeBounds::toStream(std::ostream& sl) const -{ +std::ostream& Acts::DoubleTrapezoidVolumeBounds::toStream( + std::ostream& sl) const { return dumpT<std::ostream>(sl); } diff --git a/Core/src/Geometry/GenericApproachDescriptor.cpp b/Core/src/Geometry/GenericApproachDescriptor.cpp index 01e9bf635fc13adfe11478f7df89ce0b304a7606..5330dbc3b56c23d86075298393cf3f8035a12664 100644 --- a/Core/src/Geometry/GenericApproachDescriptor.cpp +++ b/Core/src/Geometry/GenericApproachDescriptor.cpp @@ -10,9 +10,7 @@ #include "Acts/Surfaces/Surface.hpp" #include "Acts/Utilities/Intersection.hpp" -void -Acts::GenericApproachDescriptor::registerLayer(const Layer& lay) -{ +void Acts::GenericApproachDescriptor::registerLayer(const Layer& lay) { // go through the surfaces for (auto& sf : m_surfaceCache) { auto mutableSf = const_cast<Surface*>(sf); @@ -22,19 +20,18 @@ Acts::GenericApproachDescriptor::registerLayer(const Layer& lay) Acts::ObjectIntersection<Acts::Surface> Acts::GenericApproachDescriptor::approachSurface(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& gdir, - NavigationDirection navDir, - const BoundaryCheck& bcheck, - CorrFnc corrfnc) const -{ + const Vector3D& gpos, + const Vector3D& gdir, + NavigationDirection navDir, + const BoundaryCheck& bcheck, + CorrFnc corrfnc) const { // the intersection estimates std::vector<ObjectIntersection<Surface>> sIntersections; sIntersections.reserve(m_surfaceCache.size()); for (auto& sf : m_surfaceCache) { // intersect - auto intersection - = sf->intersectionEstimate(gctx, gpos, gdir, navDir, bcheck, corrfnc); + auto intersection = + sf->intersectionEstimate(gctx, gpos, gdir, navDir, bcheck, corrfnc); sIntersections.push_back( ObjectIntersection<Surface>(intersection, sf, navDir)); } @@ -49,13 +46,11 @@ Acts::GenericApproachDescriptor::approachSurface(const GeometryContext& gctx, } const std::vector<const Acts::Surface*>& -Acts::GenericApproachDescriptor::containedSurfaces() const -{ +Acts::GenericApproachDescriptor::containedSurfaces() const { return m_surfaceCache; } std::vector<const Acts::Surface*>& -Acts::GenericApproachDescriptor::containedSurfaces() -{ +Acts::GenericApproachDescriptor::containedSurfaces() { return m_surfaceCache; } diff --git a/Core/src/Geometry/GenericCuboidVolumeBounds.cpp b/Core/src/Geometry/GenericCuboidVolumeBounds.cpp index 240f552be6acfc1bfd57d24b008ef72232421641..86cd8842e7d9a600ddbdde3902be6552d62f7cd8 100644 --- a/Core/src/Geometry/GenericCuboidVolumeBounds.cpp +++ b/Core/src/Geometry/GenericCuboidVolumeBounds.cpp @@ -22,8 +22,7 @@ Acts::GenericCuboidVolumeBounds::GenericCuboidVolumeBounds( const std::array<Acts::Vector3D, 8>& vertices) - : m_vertices(vertices) -{ + : m_vertices(vertices) { // calculate approximate center of gravity first, so we can make sure // the normals point inwards Vector3D cog(0, 0, 0); @@ -36,27 +35,27 @@ Acts::GenericCuboidVolumeBounds::GenericCuboidVolumeBounds( size_t idx = 0; - auto handle_face - = [&](const auto& a, const auto& b, const auto& c, const auto& d) { - // we assume a b c d to be counter clockwise - const Vector3D ab = b - a, ac = c - a; - Vector3D normal = ab.cross(ac).normalized(); + auto handle_face = [&](const auto& a, const auto& b, const auto& c, + const auto& d) { + // we assume a b c d to be counter clockwise + const Vector3D ab = b - a, ac = c - a; + Vector3D normal = ab.cross(ac).normalized(); - if ((cog - a).dot(normal) < 0) { - // normal points outwards, flip normal - normal *= -1.; - } + if ((cog - a).dot(normal) < 0) { + // normal points outwards, flip normal + normal *= -1.; + } - // get rid of -0 values if present - normal += Vector3D::Zero(); + // get rid of -0 values if present + normal += Vector3D::Zero(); - // check if d is on the surface - throw_assert((std::abs((a - d).dot(normal)) < 1e-6), - "Four points do not lie on the same plane!"); + // check if d is on the surface + throw_assert((std::abs((a - d).dot(normal)) < 1e-6), + "Four points do not lie on the same plane!"); - m_normals[idx] = normal; - idx++; - }; + m_normals[idx] = normal; + idx++; + }; // handle faces handle_face(m_vertices[0], m_vertices[1], m_vertices[2], m_vertices[3]); @@ -67,16 +66,12 @@ Acts::GenericCuboidVolumeBounds::GenericCuboidVolumeBounds( handle_face(m_vertices[1], m_vertices[0], m_vertices[4], m_vertices[5]); } -Acts::VolumeBounds* -Acts::GenericCuboidVolumeBounds::clone() const -{ +Acts::VolumeBounds* Acts::GenericCuboidVolumeBounds::clone() const { return new GenericCuboidVolumeBounds(*this); } -bool -Acts::GenericCuboidVolumeBounds::inside(const Acts::Vector3D& gpos, - double tol) const -{ +bool Acts::GenericCuboidVolumeBounds::inside(const Acts::Vector3D& gpos, + double tol) const { constexpr std::array<size_t, 6> vtxs = {0, 4, 0, 1, 2, 1}; // needs to be on same side, get ref bool ref = std::signbit((gpos - m_vertices[vtxs[0]]).dot(m_normals[0])); @@ -96,8 +91,7 @@ Acts::GenericCuboidVolumeBounds::inside(const Acts::Vector3D& gpos, std::vector<std::shared_ptr<const Acts::Surface>> Acts::GenericCuboidVolumeBounds::decomposeToSurfaces( - const Acts::Transform3D* transform) const -{ + const Acts::Transform3D* transform) const { std::vector<std::shared_ptr<const Acts::Surface>> surfaces; // approximate cog of the volume @@ -109,13 +103,13 @@ Acts::GenericCuboidVolumeBounds::decomposeToSurfaces( cog *= 0.125; // 1/8. - auto make_surface = [&]( - const auto& a, const auto& b, const auto& c, const auto& d) { + auto make_surface = [&](const auto& a, const auto& b, const auto& c, + const auto& d) { // calculate centroid of these points Vector3D ctrd = (a + b + c + d) / 4.; // create normal const Vector3D ab = b - a, ac = c - a; - Vector3D normal = ab.cross(ac).normalized(); + Vector3D normal = ab.cross(ac).normalized(); if ((cog - d).dot(normal) > 0) { // normal points inwards, flip normal @@ -169,9 +163,8 @@ Acts::GenericCuboidVolumeBounds::decomposeToSurfaces( return surfaces; } -std::ostream& -Acts::GenericCuboidVolumeBounds::toStream(std::ostream& sl) const -{ +std::ostream& Acts::GenericCuboidVolumeBounds::toStream( + std::ostream& sl) const { sl << "Acts::GenericCuboidVolumeBounds: vertices (x, y, z) =\n"; for (size_t i = 0; i < 8; i++) { if (i > 0) { @@ -181,15 +174,13 @@ Acts::GenericCuboidVolumeBounds::toStream(std::ostream& sl) const } return sl; } -void -Acts::GenericCuboidVolumeBounds::draw(IVisualization& helper, - const Transform3D& transform) const -{ - auto draw_face - = [&](const auto& a, const auto& b, const auto& c, const auto& d) { - helper.face(std::vector<Vector3D>( - {transform * a, transform * b, transform * c, transform * d})); - }; +void Acts::GenericCuboidVolumeBounds::draw(IVisualization& helper, + const Transform3D& transform) const { + auto draw_face = [&](const auto& a, const auto& b, const auto& c, + const auto& d) { + helper.face(std::vector<Vector3D>( + {transform * a, transform * b, transform * c, transform * d})); + }; draw_face(m_vertices[0], m_vertices[1], m_vertices[2], m_vertices[3]); draw_face(m_vertices[4], m_vertices[5], m_vertices[6], m_vertices[7]); diff --git a/Core/src/Geometry/GeometryID.cpp b/Core/src/Geometry/GeometryID.cpp index 7208d3b73e32d154e99f5f79eba4139a076c2b19..5bf49a9c6d1c9f9aa991b1a2b7aba4ed2e402a9b 100644 --- a/Core/src/Geometry/GeometryID.cpp +++ b/Core/src/Geometry/GeometryID.cpp @@ -12,33 +12,25 @@ #include "Acts/Geometry/GeometryID.hpp" -bool -Acts::operator<(const Acts::GeometryID& one, const Acts::GeometryID& two) -{ +bool Acts::operator<(const Acts::GeometryID& one, const Acts::GeometryID& two) { return (one.value() < two.value()); } -bool -Acts::operator<=(const Acts::GeometryID& one, const Acts::GeometryID& two) -{ +bool Acts::operator<=(const Acts::GeometryID& one, + const Acts::GeometryID& two) { return (one.value() <= two.value()); } -bool -Acts::operator>(const Acts::GeometryID& one, const Acts::GeometryID& two) -{ +bool Acts::operator>(const Acts::GeometryID& one, const Acts::GeometryID& two) { return (one.value() > two.value()); } -bool -Acts::operator>=(const Acts::GeometryID& one, const Acts::GeometryID& two) -{ +bool Acts::operator>=(const Acts::GeometryID& one, + const Acts::GeometryID& two) { return (one.value() >= two.value()); } -std::ostream& -Acts::operator<<(std::ostream& sl, const Acts::GeometryID& tid) -{ +std::ostream& Acts::operator<<(std::ostream& sl, const Acts::GeometryID& tid) { sl << tid.value(); return sl; } diff --git a/Core/src/Geometry/GlueVolumesDescriptor.cpp b/Core/src/Geometry/GlueVolumesDescriptor.cpp index f50064a04b8933c4a19898534d42c11b94284130..43a909cac25880ea304c5d90ab54399e6280a040 100644 --- a/Core/src/Geometry/GlueVolumesDescriptor.cpp +++ b/Core/src/Geometry/GlueVolumesDescriptor.cpp @@ -18,32 +18,28 @@ Acts::GlueVolumesDescriptor::GlueVolumesDescriptor( const std::map<BoundarySurfaceFace, std::shared_ptr<const TrackingVolumeArray>>& gvs) - : m_glueVolumes(gvs) -{ + : m_glueVolumes(gvs) { // fill the available faces for (auto& gvIter : m_glueVolumes) { m_glueFaces.push_back(gvIter.first); } } -void -Acts::GlueVolumesDescriptor::registerGlueVolumes( - Acts::BoundarySurfaceFace bsf, - std::shared_ptr<const TrackingVolumeArray> gvs) -{ +void Acts::GlueVolumesDescriptor::registerGlueVolumes( + Acts::BoundarySurfaceFace bsf, + std::shared_ptr<const TrackingVolumeArray> gvs) { // register the face auto searchIter = m_glueVolumes.find(bsf); if (searchIter == m_glueVolumes.end()) { m_glueFaces.push_back(bsf); } // simple assignment overwrites already existing entries - m_glueVolumes[bsf] - = std::move(gvs); //!< @todo change to addGlueVolumes principle + m_glueVolumes[bsf] = + std::move(gvs); //!< @todo change to addGlueVolumes principle } std::shared_ptr<const Acts::TrackingVolumeArray> -Acts::GlueVolumesDescriptor::glueVolumes(Acts::BoundarySurfaceFace bsf) const -{ +Acts::GlueVolumesDescriptor::glueVolumes(Acts::BoundarySurfaceFace bsf) const { // searching for the glue volumes according auto searchIter = m_glueVolumes.find(bsf); if (searchIter != m_glueVolumes.end()) { @@ -52,9 +48,7 @@ Acts::GlueVolumesDescriptor::glueVolumes(Acts::BoundarySurfaceFace bsf) const return nullptr; } -std::string -Acts::GlueVolumesDescriptor::screenOutput() const -{ +std::string Acts::GlueVolumesDescriptor::screenOutput() const { std::stringstream sl; sl << "Acts::GlueVolumesDescriptor: " << std::endl; const std::vector<Acts::BoundarySurfaceFace>& glueFaceVector = glueFaces(); @@ -62,8 +56,8 @@ Acts::GlueVolumesDescriptor::screenOutput() const << " Volume faces." << std::endl; // loop over the faces for (auto& gFace : glueFaceVector) { - const std::vector<TrackingVolumePtr>& glueVolumesVector - = glueVolumes(gFace)->arrayObjects(); + const std::vector<TrackingVolumePtr>& glueVolumesVector = + glueVolumes(gFace)->arrayObjects(); // loop over the TrackingVolumes sl << " -----> Processing Face: " << int(gFace) << " - has "; sl << glueVolumesVector.size() @@ -76,9 +70,8 @@ Acts::GlueVolumesDescriptor::screenOutput() const return sl.str(); } -std::ostream& -Acts::operator<<(std::ostream& sl, const GlueVolumesDescriptor& gvd) -{ +std::ostream& Acts::operator<<(std::ostream& sl, + const GlueVolumesDescriptor& gvd) { sl << gvd.screenOutput(); return sl; } diff --git a/Core/src/Geometry/Layer.cpp b/Core/src/Geometry/Layer.cpp index 35c2a5c26b129c5fdd2aeae9d3d9984eafd7e384..5926b2c1c6815be5c479a566bbc418ad050aa840 100644 --- a/Core/src/Geometry/Layer.cpp +++ b/Core/src/Geometry/Layer.cpp @@ -17,18 +17,15 @@ #include "Acts/Surfaces/Surface.hpp" #include "Acts/Utilities/BinUtility.hpp" -Acts::Layer::Layer(std::unique_ptr<SurfaceArray> surfaceArray, - double thickness, - std::unique_ptr<ApproachDescriptor> ades, - LayerType laytyp) - : m_nextLayers(NextLayers(nullptr, nullptr)) - , m_surfaceArray(surfaceArray.release()) - , m_layerThickness(thickness) - , m_approachDescriptor(nullptr) - , m_representingVolume(nullptr) - , m_layerType(laytyp) - , m_ssRepresentingSurface(1) -{ +Acts::Layer::Layer(std::unique_ptr<SurfaceArray> surfaceArray, double thickness, + std::unique_ptr<ApproachDescriptor> ades, LayerType laytyp) + : m_nextLayers(NextLayers(nullptr, nullptr)), + m_surfaceArray(surfaceArray.release()), + m_layerThickness(thickness), + m_approachDescriptor(nullptr), + m_representingVolume(nullptr), + m_layerType(laytyp), + m_ssRepresentingSurface(1) { if (ades) { ades->registerLayer(*this); m_approachDescriptor = std::move(ades); @@ -40,23 +37,16 @@ Acts::Layer::Layer(std::unique_ptr<SurfaceArray> surfaceArray, } } -const Acts::ApproachDescriptor* -Acts::Layer::approachDescriptor() const -{ +const Acts::ApproachDescriptor* Acts::Layer::approachDescriptor() const { return m_approachDescriptor.get(); } -Acts::ApproachDescriptor* -Acts::Layer::approachDescriptor() -{ +Acts::ApproachDescriptor* Acts::Layer::approachDescriptor() { return const_cast<ApproachDescriptor*>(m_approachDescriptor.get()); } -void -Acts::Layer::closeGeometry(const IMaterialDecorator* materialDecorator, - const GeometryID& layerID) -{ - +void Acts::Layer::closeGeometry(const IMaterialDecorator* materialDecorator, + const GeometryID& layerID) { // set the volumeID of this assignGeoID(layerID); // assign to the representing surface diff --git a/Core/src/Geometry/LayerArrayCreator.cpp b/Core/src/Geometry/LayerArrayCreator.cpp index 4778e09b78e9ae9363072ad30cff5a97b1d752d7..8cf79aa5e208182b034dcddca2ce62bbe5ec8ad4 100644 --- a/Core/src/Geometry/LayerArrayCreator.cpp +++ b/Core/src/Geometry/LayerArrayCreator.cpp @@ -27,14 +27,9 @@ #include "Acts/Utilities/BinnedArrayXD.hpp" #include "Acts/Utilities/Definitions.hpp" -std::unique_ptr<const Acts::LayerArray> -Acts::LayerArrayCreator::layerArray(const GeometryContext& gctx, - const LayerVector& layersInput, - double min, - double max, - BinningType bType, - BinningValue bValue) const -{ +std::unique_ptr<const Acts::LayerArray> Acts::LayerArrayCreator::layerArray( + const GeometryContext& gctx, const LayerVector& layersInput, double min, + double max, BinningType bType, BinningValue bValue) const { ACTS_VERBOSE("Build LayerArray with " << layersInput.size() << " layers at input."); ACTS_VERBOSE(" min/max provided : " << min << " / " << max); @@ -50,165 +45,162 @@ Acts::LayerArrayCreator::layerArray(const GeometryContext& gctx, // useful typedef using LayerOrderPosition = std::pair<std::shared_ptr<const Layer>, Vector3D>; // needed for all cases - std::shared_ptr<const Layer> layer = nullptr; + std::shared_ptr<const Layer> layer = nullptr; std::unique_ptr<const BinUtility> binUtility = nullptr; - std::vector<LayerOrderPosition> layerOrderVector; + std::vector<LayerOrderPosition> layerOrderVector; // switch the binning type switch (bType) { - // equidistant binning - no navigation layers built - only equdistant layers - case equidistant: { - // loop over layers and put them in - for (auto& layIter : layers) { - ACTS_VERBOSE("equidistant : registering a Layer at binning position : " - << (layIter->binningPosition(gctx, bValue))); - layerOrderVector.push_back( - LayerOrderPosition(layIter, layIter->binningPosition(gctx, bValue))); - } - // create the binUitlity - binUtility = std::make_unique<const BinUtility>( - layers.size(), min, max, open, bValue); - ACTS_VERBOSE("equidistant : created a BinUtility as " << *binUtility); - } break; + // equidistant binning - no navigation layers built - only equdistant layers + case equidistant: { + // loop over layers and put them in + for (auto& layIter : layers) { + ACTS_VERBOSE("equidistant : registering a Layer at binning position : " + << (layIter->binningPosition(gctx, bValue))); + layerOrderVector.push_back(LayerOrderPosition( + layIter, layIter->binningPosition(gctx, bValue))); + } + // create the binUitlity + binUtility = std::make_unique<const BinUtility>(layers.size(), min, max, + open, bValue); + ACTS_VERBOSE("equidistant : created a BinUtility as " << *binUtility); + } break; - // arbitrary binning - case arbitrary: { - std::vector<float> boundaries; - // initial step - boundaries.push_back(min); - double layerValue = 0.; - double layerThickness = 0.; - std::shared_ptr<const Layer> navLayer = nullptr; - std::shared_ptr<const Layer> lastLayer = nullptr; - // loop over layers - for (auto& layIter : layers) { - // estimate the offset - layerThickness = layIter->thickness(); - layerValue = layIter->binningPositionValue(gctx, bValue); - // register the new boundaries in the step vector - boundaries.push_back(layerValue - 0.5 * layerThickness); - boundaries.push_back(layerValue + 0.5 * layerThickness); - // calculate the layer value for the offset - double navigationValue = 0.5 * ((layerValue - 0.5 * layerThickness) - + boundaries.at(boundaries.size() - 3)); - // if layers are attached to each other bail out - navigation will not - // work anymore - if (navigationValue == (layerValue - 0.5 * layerThickness)) { - ACTS_ERROR("Layers are attached to each other at: " - << layerValue - 0.5 * layerThickness - << ", which corrupts " - "navigation. This should never happen. Please detach the " - "layers in your geometry description."); + // arbitrary binning + case arbitrary: { + std::vector<float> boundaries; + // initial step + boundaries.push_back(min); + double layerValue = 0.; + double layerThickness = 0.; + std::shared_ptr<const Layer> navLayer = nullptr; + std::shared_ptr<const Layer> lastLayer = nullptr; + // loop over layers + for (auto& layIter : layers) { + // estimate the offset + layerThickness = layIter->thickness(); + layerValue = layIter->binningPositionValue(gctx, bValue); + // register the new boundaries in the step vector + boundaries.push_back(layerValue - 0.5 * layerThickness); + boundaries.push_back(layerValue + 0.5 * layerThickness); + // calculate the layer value for the offset + double navigationValue = 0.5 * ((layerValue - 0.5 * layerThickness) + + boundaries.at(boundaries.size() - 3)); + // if layers are attached to each other bail out - navigation will not + // work anymore + if (navigationValue == (layerValue - 0.5 * layerThickness)) { + ACTS_ERROR( + "Layers are attached to each other at: " + << layerValue - 0.5 * layerThickness + << ", which corrupts " + "navigation. This should never happen. Please detach the " + "layers in your geometry description."); + } + // if layers are overlapping bail out + if (navigationValue > (layerValue - 0.5 * layerThickness)) { + ACTS_ERROR("Layers are overlapping at: " + << layerValue - 0.5 * layerThickness + << ". This should never happen. " + "Please check your geometry description."); + } + + // create the navigation layer surface from the layer + std::shared_ptr<const Surface> navLayerSurface = + createNavigationSurface(gctx, *layIter, bValue, + -std::abs(layerValue - navigationValue)); + ACTS_VERBOSE( + "arbitrary : creating a NavigationLayer at " + << (navLayerSurface->binningPosition(gctx, bValue)).x() << ", " + << (navLayerSurface->binningPosition(gctx, bValue)).y() << ", " + << (navLayerSurface->binningPosition(gctx, bValue)).z()); + navLayer = NavigationLayer::create(std::move(navLayerSurface)); + // push the navigation layer in + layerOrderVector.push_back(LayerOrderPosition( + navLayer, navLayer->binningPosition(gctx, bValue))); + + // push the original layer in + layerOrderVector.push_back(LayerOrderPosition( + layIter, layIter->binningPosition(gctx, bValue))); + ACTS_VERBOSE("arbitrary : registering MaterialLayer at " + << (layIter->binningPosition(gctx, bValue)).x() << ", " + << (layIter->binningPosition(gctx, bValue)).y() << ", " + << (layIter->binningPosition(gctx, bValue)).z()); + // remember the last + lastLayer = layIter; } - // if layers are overlapping bail out - if (navigationValue > (layerValue - 0.5 * layerThickness)) { - ACTS_ERROR("Layers are overlapping at: " - << layerValue - 0.5 * layerThickness - << ". This should never happen. " - "Please check your geometry description."); + // a final navigation layer + // calculate the layer value for the offset + double navigationValue = + 0.5 * (boundaries.at(boundaries.size() - 1) + max); + // create navigation layer only when necessary + if (navigationValue != max) { + // create the navigation layer surface from the layer + std::shared_ptr<const Surface> navLayerSurface = + createNavigationSurface(gctx, *lastLayer, bValue, + navigationValue - layerValue); + ACTS_VERBOSE( + "arbitrary : creating a NavigationLayer at " + << (navLayerSurface->binningPosition(gctx, bValue)).x() << ", " + << (navLayerSurface->binningPosition(gctx, bValue)).y() << ", " + << (navLayerSurface->binningPosition(gctx, bValue)).z()); + navLayer = NavigationLayer::create(std::move(navLayerSurface)); + // push the navigation layer in + layerOrderVector.push_back(LayerOrderPosition( + navLayer, navLayer->binningPosition(gctx, bValue))); } + // now close the boundaries + boundaries.push_back(max); + // some screen output + ACTS_VERBOSE(layerOrderVector.size() + << " Layers (material + navigation) built. "); + // create the BinUtility + binUtility = std::make_unique<const BinUtility>(boundaries, open, bValue); + ACTS_VERBOSE("arbitrary : created a BinUtility as " << *binUtility); - // create the navigation layer surface from the layer - std::shared_ptr<const Surface> navLayerSurface = createNavigationSurface( - gctx, *layIter, bValue, -std::abs(layerValue - navigationValue)); - ACTS_VERBOSE("arbitrary : creating a NavigationLayer at " - << (navLayerSurface->binningPosition(gctx, bValue)).x() - << ", " - << (navLayerSurface->binningPosition(gctx, bValue)).y() - << ", " - << (navLayerSurface->binningPosition(gctx, bValue)).z()); - navLayer = NavigationLayer::create(std::move(navLayerSurface)); - // push the navigation layer in - layerOrderVector.push_back(LayerOrderPosition( - navLayer, navLayer->binningPosition(gctx, bValue))); - - // push the original layer in - layerOrderVector.push_back( - LayerOrderPosition(layIter, layIter->binningPosition(gctx, bValue))); - ACTS_VERBOSE("arbitrary : registering MaterialLayer at " - << (layIter->binningPosition(gctx, bValue)).x() - << ", " - << (layIter->binningPosition(gctx, bValue)).y() - << ", " - << (layIter->binningPosition(gctx, bValue)).z()); - // remember the last - lastLayer = layIter; - } - // a final navigation layer - // calculate the layer value for the offset - double navigationValue = 0.5 * (boundaries.at(boundaries.size() - 1) + max); - // create navigation layer only when necessary - if (navigationValue != max) { - // create the navigation layer surface from the layer - std::shared_ptr<const Surface> navLayerSurface = createNavigationSurface( - gctx, *lastLayer, bValue, navigationValue - layerValue); - ACTS_VERBOSE("arbitrary : creating a NavigationLayer at " - << (navLayerSurface->binningPosition(gctx, bValue)).x() - << ", " - << (navLayerSurface->binningPosition(gctx, bValue)).y() - << ", " - << (navLayerSurface->binningPosition(gctx, bValue)).z()); - navLayer = NavigationLayer::create(std::move(navLayerSurface)); - // push the navigation layer in - layerOrderVector.push_back(LayerOrderPosition( - navLayer, navLayer->binningPosition(gctx, bValue))); + } break; + // default return nullptr + default: { + return nullptr; } - // now close the boundaries - boundaries.push_back(max); - // some screen output - ACTS_VERBOSE(layerOrderVector.size() - << " Layers (material + navigation) built. "); - // create the BinUtility - binUtility = std::make_unique<const BinUtility>(boundaries, open, bValue); - ACTS_VERBOSE("arbitrary : created a BinUtility as " << *binUtility); - - } break; - // default return nullptr - default: { - return nullptr; - } } // return the binned array return std::make_unique<const BinnedArrayXD<LayerPtr>>(layerOrderVector, std::move(binUtility)); } -std::shared_ptr<Acts::Surface> -Acts::LayerArrayCreator::createNavigationSurface(const GeometryContext& gctx, - const Layer& layer, - BinningValue bValue, - double offset) const -{ +std::shared_ptr<Acts::Surface> Acts::LayerArrayCreator::createNavigationSurface( + const GeometryContext& gctx, const Layer& layer, BinningValue bValue, + double offset) const { // surface reference const Surface& layerSurface = layer.surfaceRepresentation(); // translation to be applied Vector3D translation(0., 0., 0.); // switching he binnig values switch (bValue) { - // case x - case binX: { - translation = Vector3D(offset, 0., 0.); - } break; - // case y - case binY: { - translation = Vector3D(0., offset, 0.); - } break; - // case z - case binZ: { - translation = Vector3D(0., 0., offset); - } break; - // case R - case binR: { - // binning in R and cylinder surface means something different - if (layerSurface.type() == Surface::Cylinder) { - break; + // case x + case binX: { + translation = Vector3D(offset, 0., 0.); + } break; + // case y + case binY: { + translation = Vector3D(0., offset, 0.); + } break; + // case z + case binZ: { + translation = Vector3D(0., 0., offset); + } break; + // case R + case binR: { + // binning in R and cylinder surface means something different + if (layerSurface.type() == Surface::Cylinder) { + break; + } + translation = Vector3D(offset, 0., 0.); + } break; + // do nothing for the default + default: { + ACTS_WARNING("Not yet implemented."); } - translation = Vector3D(offset, 0., 0.); - } break; - // do nothing for the default - default: { - ACTS_WARNING("Not yet implemented."); - } } // navigation surface std::shared_ptr<Surface> navigationSurface; @@ -219,15 +211,15 @@ Acts::LayerArrayCreator::createNavigationSurface(const GeometryContext& gctx, navigationSurface = layerSurface.clone(gctx, shift); } else { // get the bounds - const CylinderBounds* cBounds - = dynamic_cast<const CylinderBounds*>(&(layerSurface.bounds())); + const CylinderBounds* cBounds = + dynamic_cast<const CylinderBounds*>(&(layerSurface.bounds())); double navigationR = cBounds->r() + offset; double halflengthZ = cBounds->halflengthZ(); // create the new layer surface - std::shared_ptr<const Transform3D> navTrasform - = (!layerSurface.transform(gctx).isApprox(s_idTransform)) - ? std::make_shared<const Transform3D>(layerSurface.transform(gctx)) - : nullptr; + std::shared_ptr<const Transform3D> navTrasform = + (!layerSurface.transform(gctx).isApprox(s_idTransform)) + ? std::make_shared<const Transform3D>(layerSurface.transform(gctx)) + : nullptr; // new navigation layer navigationSurface = Surface::makeShared<CylinderSurface>( navTrasform, navigationR, halflengthZ); diff --git a/Core/src/Geometry/LayerCreator.cpp b/Core/src/Geometry/LayerCreator.cpp index ba7069fb845378acd4bb38fc2c9c7eb29e647b35..b19e4d70507fde04b79047f5f1e615f4f4521ebf 100644 --- a/Core/src/Geometry/LayerCreator.cpp +++ b/Core/src/Geometry/LayerCreator.cpp @@ -28,52 +28,40 @@ using Acts::VectorHelpers::perp; using Acts::VectorHelpers::phi; Acts::LayerCreator::LayerCreator(const Acts::LayerCreator::Config& lcConfig, - std::unique_ptr<const Logger> logger) - : m_cfg(lcConfig), m_logger(std::move(logger)) -{ -} + std::unique_ptr<const Logger> logger) + : m_cfg(lcConfig), m_logger(std::move(logger)) {} -void -Acts::LayerCreator::setConfiguration(const Acts::LayerCreator::Config& lcConfig) -{ +void Acts::LayerCreator::setConfiguration( + const Acts::LayerCreator::Config& lcConfig) { // @todo check consistency // copy the configuration m_cfg = lcConfig; } -void -Acts::LayerCreator::setLogger(std::unique_ptr<const Logger> newLogger) -{ +void Acts::LayerCreator::setLogger(std::unique_ptr<const Logger> newLogger) { m_logger = std::move(newLogger); } -Acts::MutableLayerPtr -Acts::LayerCreator::cylinderLayer( - const GeometryContext& gctx, - std::vector<std::shared_ptr<const Surface>> surfaces, - size_t binsPhi, - size_t binsZ, - boost::optional<ProtoLayer> _protoLayer, - std::shared_ptr<const Transform3D> transform, - std::unique_ptr<ApproachDescriptor> ad) const -{ - - ProtoLayer protoLayer - = _protoLayer ? *_protoLayer : ProtoLayer(gctx, surfaces); +Acts::MutableLayerPtr Acts::LayerCreator::cylinderLayer( + const GeometryContext& gctx, + std::vector<std::shared_ptr<const Surface>> surfaces, size_t binsPhi, + size_t binsZ, boost::optional<ProtoLayer> _protoLayer, + std::shared_ptr<const Transform3D> transform, + std::unique_ptr<ApproachDescriptor> ad) const { + ProtoLayer protoLayer = + _protoLayer ? *_protoLayer : ProtoLayer(gctx, surfaces); // remaining layer parameters - double layerR - = 0.5 * (protoLayer.minR - protoLayer.envR.first + protoLayer.maxR - + protoLayer.envR.second); + double layerR = 0.5 * (protoLayer.minR - protoLayer.envR.first + + protoLayer.maxR + protoLayer.envR.second); double binPosZ = 0.5 * (protoLayer.minZ + protoLayer.maxZ); double envZShift = 0.5 * (-protoLayer.envZ.first + protoLayer.envZ.second); - double layerZ = binPosZ + envZShift; - double layerHalfZ - = 0.5 * std::abs(protoLayer.maxZ + protoLayer.envZ.second - - (protoLayer.minZ - protoLayer.envZ.first)); - double layerThickness = (protoLayer.maxR - protoLayer.minR) - + protoLayer.envR.first + protoLayer.envR.second; + double layerZ = binPosZ + envZShift; + double layerHalfZ = 0.5 * std::abs(protoLayer.maxZ + protoLayer.envZ.second - + (protoLayer.minZ - protoLayer.envZ.first)); + double layerThickness = (protoLayer.maxR - protoLayer.minR) + + protoLayer.envR.first + protoLayer.envR.second; ACTS_VERBOSE("Creating a cylindrical Layer:"); ACTS_VERBOSE(" - with layer R = " << layerR); @@ -83,13 +71,9 @@ Acts::LayerCreator::cylinderLayer( ACTS_VERBOSE(" - incl envelope = " << protoLayer.envR.first << " / " << protoLayer.envR.second); - ACTS_VERBOSE(" - with z min/max = " << protoLayer.minZ << " (-" - << protoLayer.envZ.first - << ") / " - << protoLayer.maxZ - << " (+" - << protoLayer.envZ.second - << ")"); + ACTS_VERBOSE(" - with z min/max = " + << protoLayer.minZ << " (-" << protoLayer.envZ.first << ") / " + << protoLayer.maxZ << " (+" << protoLayer.envZ.second << ")"); ACTS_VERBOSE(" - z center = " << layerZ); ACTS_VERBOSE(" - halflength z = " << layerHalfZ); @@ -99,18 +83,15 @@ Acts::LayerCreator::cylinderLayer( // correctly defined using the halflength if (!transform) { // double shift = -(layerZ + envZShift); - transform - = std::make_shared<const Transform3D>(Translation3D(0., 0., layerZ)); + transform = + std::make_shared<const Transform3D>(Translation3D(0., 0., layerZ)); ACTS_VERBOSE(" - layer z shift = " << -layerZ); } ACTS_VERBOSE(" - with phi min/max = " << protoLayer.minPhi << " / " << protoLayer.maxPhi); ACTS_VERBOSE(" - # of modules = " << surfaces.size() << " ordered in ( " - << binsPhi - << " x " - << binsZ - << ")"); + << binsPhi << " x " << binsZ << ")"); std::unique_ptr<SurfaceArray> sArray; if (!surfaces.empty()) { sArray = m_cfg.surfaceArrayCreator->surfaceArrayOnCylinder( @@ -124,48 +105,39 @@ Acts::LayerCreator::cylinderLayer( new CylinderBounds(layerR, layerHalfZ)); // create the layer - MutableLayerPtr cLayer = CylinderLayer::create(transform, - cBounds, - std::move(sArray), - layerThickness, - std::move(ad), - active); - - if (!cLayer) ACTS_ERROR("Creation of cylinder layer did not succeed!"); + MutableLayerPtr cLayer = + CylinderLayer::create(transform, cBounds, std::move(sArray), + layerThickness, std::move(ad), active); + + if (!cLayer) + ACTS_ERROR("Creation of cylinder layer did not succeed!"); associateSurfacesToLayer(*cLayer); // now return return cLayer; } -Acts::MutableLayerPtr -Acts::LayerCreator::cylinderLayer( - const GeometryContext& gctx, - std::vector<std::shared_ptr<const Surface>> surfaces, - BinningType bTypePhi, - BinningType bTypeZ, - boost::optional<ProtoLayer> _protoLayer, - std::shared_ptr<const Transform3D> transform, - std::unique_ptr<ApproachDescriptor> ad) const -{ - - ProtoLayer protoLayer - = _protoLayer ? *_protoLayer : ProtoLayer(gctx, surfaces); +Acts::MutableLayerPtr Acts::LayerCreator::cylinderLayer( + const GeometryContext& gctx, + std::vector<std::shared_ptr<const Surface>> surfaces, BinningType bTypePhi, + BinningType bTypeZ, boost::optional<ProtoLayer> _protoLayer, + std::shared_ptr<const Transform3D> transform, + std::unique_ptr<ApproachDescriptor> ad) const { + ProtoLayer protoLayer = + _protoLayer ? *_protoLayer : ProtoLayer(gctx, surfaces); // remaining layer parameters - double layerR - = 0.5 * (protoLayer.minR - protoLayer.envR.first + protoLayer.maxR - + protoLayer.envR.second); - double binPosZ = 0.5 * (protoLayer.minZ + protoLayer.maxZ); + double layerR = 0.5 * (protoLayer.minR - protoLayer.envR.first + + protoLayer.maxR + protoLayer.envR.second); + double binPosZ = 0.5 * (protoLayer.minZ + protoLayer.maxZ); double envZShift = 0.5 * (-protoLayer.envZ.first + protoLayer.envZ.second); - double layerZ = binPosZ + envZShift; + double layerZ = binPosZ + envZShift; - double layerHalfZ - = 0.5 * std::abs(protoLayer.maxZ + protoLayer.envZ.second - - (protoLayer.minZ - protoLayer.envZ.first)); + double layerHalfZ = 0.5 * std::abs(protoLayer.maxZ + protoLayer.envZ.second - + (protoLayer.minZ - protoLayer.envZ.first)); - double layerThickness = (protoLayer.maxR - protoLayer.minR) - + protoLayer.envR.first + protoLayer.envR.second; + double layerThickness = (protoLayer.maxR - protoLayer.minR) + + protoLayer.envR.first + protoLayer.envR.second; // adjust the layer radius ACTS_VERBOSE("Creating a cylindrical Layer:"); @@ -175,13 +147,9 @@ Acts::LayerCreator::cylinderLayer( ACTS_VERBOSE(" - with R thickness = " << layerThickness); ACTS_VERBOSE(" - incl envelope = " << protoLayer.envR.first << " / " << protoLayer.envR.second); - ACTS_VERBOSE(" - with z min/max = " << protoLayer.minZ << " (-" - << protoLayer.envZ.first - << ") / " - << protoLayer.maxZ - << " (+" - << protoLayer.envZ.second - << ")"); + ACTS_VERBOSE(" - with z min/max = " + << protoLayer.minZ << " (-" << protoLayer.envZ.first << ") / " + << protoLayer.maxZ << " (+" << protoLayer.envZ.second << ")"); ACTS_VERBOSE(" - z center = " << layerZ); ACTS_VERBOSE(" - halflength z = " << layerHalfZ); @@ -189,8 +157,8 @@ Acts::LayerCreator::cylinderLayer( // we need to transform in case layerZ != 0, so that the layer will be // correctly defined using the halflength if (!transform && bTypeZ == equidistant) { - transform - = std::make_shared<const Transform3D>(Translation3D(0., 0., layerZ)); + transform = + std::make_shared<const Transform3D>(Translation3D(0., 0., layerZ)); ACTS_VERBOSE(" - layer z shift = " << -layerZ); } @@ -212,38 +180,31 @@ Acts::LayerCreator::cylinderLayer( new CylinderBounds(layerR, layerHalfZ)); // create the layer - MutableLayerPtr cLayer = CylinderLayer::create(transform, - cBounds, - std::move(sArray), - layerThickness, - std::move(ad), - active); - - if (!cLayer) ACTS_ERROR("Creation of cylinder layer did not succeed!"); + MutableLayerPtr cLayer = + CylinderLayer::create(transform, cBounds, std::move(sArray), + layerThickness, std::move(ad), active); + + if (!cLayer) + ACTS_ERROR("Creation of cylinder layer did not succeed!"); associateSurfacesToLayer(*cLayer); // now return return cLayer; } -Acts::MutableLayerPtr -Acts::LayerCreator::discLayer( - const GeometryContext& gctx, - std::vector<std::shared_ptr<const Surface>> surfaces, - size_t binsR, - size_t binsPhi, - boost::optional<ProtoLayer> _protoLayer, - std::shared_ptr<const Transform3D> transform, - std::unique_ptr<ApproachDescriptor> ad) const -{ - ProtoLayer protoLayer - = _protoLayer ? *_protoLayer : ProtoLayer(gctx, surfaces); - - double layerZ - = 0.5 * (protoLayer.minZ - protoLayer.envZ.first + protoLayer.maxZ - + protoLayer.envZ.second); - double layerThickness = (protoLayer.maxZ - protoLayer.minZ) - + protoLayer.envZ.first + protoLayer.envZ.second; +Acts::MutableLayerPtr Acts::LayerCreator::discLayer( + const GeometryContext& gctx, + std::vector<std::shared_ptr<const Surface>> surfaces, size_t binsR, + size_t binsPhi, boost::optional<ProtoLayer> _protoLayer, + std::shared_ptr<const Transform3D> transform, + std::unique_ptr<ApproachDescriptor> ad) const { + ProtoLayer protoLayer = + _protoLayer ? *_protoLayer : ProtoLayer(gctx, surfaces); + + double layerZ = 0.5 * (protoLayer.minZ - protoLayer.envZ.first + + protoLayer.maxZ + protoLayer.envZ.second); + double layerThickness = (protoLayer.maxZ - protoLayer.minZ) + + protoLayer.envZ.first + protoLayer.envZ.second; // adjust the layer radius ACTS_VERBOSE("Creating a disk Layer:"); @@ -253,25 +214,18 @@ Acts::LayerCreator::discLayer( ACTS_VERBOSE(" - with Z thickness = " << layerThickness); ACTS_VERBOSE(" - incl envelope = " << protoLayer.envZ.first << " / " << protoLayer.envZ.second); - ACTS_VERBOSE(" - with R min/max = " << protoLayer.minR << " (-" - << protoLayer.envR.first - << ") / " - << protoLayer.maxR - << " (+" - << protoLayer.envR.second - << ")"); + ACTS_VERBOSE(" - with R min/max = " + << protoLayer.minR << " (-" << protoLayer.envR.first << ") / " + << protoLayer.maxR << " (+" << protoLayer.envR.second << ")"); ACTS_VERBOSE(" - with phi min/max = " << protoLayer.minPhi << " / " << protoLayer.maxPhi); ACTS_VERBOSE(" - # of modules = " << surfaces.size() << " ordered in ( " - << binsR - << " x " - << binsPhi - << ")"); + << binsR << " x " << binsPhi << ")"); // create the layer transforms if not given if (!transform) { - transform - = std::make_shared<const Transform3D>(Translation3D(0., 0., layerZ)); + transform = + std::make_shared<const Transform3D>(Translation3D(0., 0., layerZ)); } // create the surface array std::unique_ptr<SurfaceArray> sArray; @@ -290,37 +244,30 @@ Acts::LayerCreator::discLayer( // create the layers // we use the same transform here as for the layer itself // for disk this is fine since we don't bin in Z, so does not matter - MutableLayerPtr dLayer = DiscLayer::create(transform, - dBounds, - std::move(sArray), - layerThickness, - std::move(ad), - active); - - if (!dLayer) ACTS_ERROR("Creation of disc layer did not succeed!"); + MutableLayerPtr dLayer = + DiscLayer::create(transform, dBounds, std::move(sArray), layerThickness, + std::move(ad), active); + + if (!dLayer) + ACTS_ERROR("Creation of disc layer did not succeed!"); associateSurfacesToLayer(*dLayer); // return the layer return dLayer; } -Acts::MutableLayerPtr -Acts::LayerCreator::discLayer( - const GeometryContext& gctx, - std::vector<std::shared_ptr<const Surface>> surfaces, - BinningType bTypeR, - BinningType bTypePhi, - boost::optional<ProtoLayer> _protoLayer, - std::shared_ptr<const Transform3D> transform, - std::unique_ptr<ApproachDescriptor> ad) const -{ - ProtoLayer protoLayer - = _protoLayer ? *_protoLayer : ProtoLayer(gctx, surfaces); - - double layerZ - = 0.5 * (protoLayer.minZ - protoLayer.envZ.first + protoLayer.maxZ - + protoLayer.envZ.second); - double layerThickness = std::abs(protoLayer.maxZ - protoLayer.minZ) - + protoLayer.envZ.first + protoLayer.envZ.second; +Acts::MutableLayerPtr Acts::LayerCreator::discLayer( + const GeometryContext& gctx, + std::vector<std::shared_ptr<const Surface>> surfaces, BinningType bTypeR, + BinningType bTypePhi, boost::optional<ProtoLayer> _protoLayer, + std::shared_ptr<const Transform3D> transform, + std::unique_ptr<ApproachDescriptor> ad) const { + ProtoLayer protoLayer = + _protoLayer ? *_protoLayer : ProtoLayer(gctx, surfaces); + + double layerZ = 0.5 * (protoLayer.minZ - protoLayer.envZ.first + + protoLayer.maxZ + protoLayer.envZ.second); + double layerThickness = std::abs(protoLayer.maxZ - protoLayer.minZ) + + protoLayer.envZ.first + protoLayer.envZ.second; // adjust the layer radius ACTS_VERBOSE("Creating a disk Layer:"); @@ -330,21 +277,17 @@ Acts::LayerCreator::discLayer( ACTS_VERBOSE(" - with Z thickness = " << layerThickness); ACTS_VERBOSE(" - incl envelope = " << protoLayer.envZ.first << " / " << protoLayer.envZ.second); - ACTS_VERBOSE(" - with R min/max = " << protoLayer.minR << " (-" - << protoLayer.envR.first - << ") / " - << protoLayer.maxR - << " (+" - << protoLayer.envR.second - << ")"); + ACTS_VERBOSE(" - with R min/max = " + << protoLayer.minR << " (-" << protoLayer.envR.first << ") / " + << protoLayer.maxR << " (+" << protoLayer.envR.second << ")"); ACTS_VERBOSE(" - with phi min/max = " << protoLayer.minPhi << " / " << protoLayer.maxPhi); ACTS_VERBOSE(" - # of modules = " << surfaces.size()); // create the layer transforms if not given if (!transform) { - transform - = std::make_shared<const Transform3D>(Translation3D(0., 0., layerZ)); + transform = + std::make_shared<const Transform3D>(Translation3D(0., 0., layerZ)); } // create the surface array @@ -362,52 +305,45 @@ Acts::LayerCreator::discLayer( protoLayer.maxR + protoLayer.envR.second); // create the layers - MutableLayerPtr dLayer = DiscLayer::create(transform, - dBounds, - std::move(sArray), - layerThickness, - std::move(ad), - active); - if (!dLayer) ACTS_ERROR("Creation of disc layer did not succeed!"); + MutableLayerPtr dLayer = + DiscLayer::create(transform, dBounds, std::move(sArray), layerThickness, + std::move(ad), active); + if (!dLayer) + ACTS_ERROR("Creation of disc layer did not succeed!"); associateSurfacesToLayer(*dLayer); // return the layer return dLayer; } -Acts::MutableLayerPtr -Acts::LayerCreator::planeLayer( - const GeometryContext& gctx, - std::vector<std::shared_ptr<const Surface>> surfaces, - size_t bins1, - size_t bins2, - BinningValue bValue, - boost::optional<ProtoLayer> _protoLayer, - std::shared_ptr<const Transform3D> transform, - std::unique_ptr<ApproachDescriptor> ad) const -{ - ProtoLayer protoLayer - = _protoLayer ? *_protoLayer : ProtoLayer(gctx, surfaces); +Acts::MutableLayerPtr Acts::LayerCreator::planeLayer( + const GeometryContext& gctx, + std::vector<std::shared_ptr<const Surface>> surfaces, size_t bins1, + size_t bins2, BinningValue bValue, boost::optional<ProtoLayer> _protoLayer, + std::shared_ptr<const Transform3D> transform, + std::unique_ptr<ApproachDescriptor> ad) const { + ProtoLayer protoLayer = + _protoLayer ? *_protoLayer : ProtoLayer(gctx, surfaces); // remaining layer parameters double layerHalf1, layerHalf2, layerThickness; switch (bValue) { - case BinningValue::binX: { - layerHalf1 = 0.5 * (protoLayer.maxY - protoLayer.minY); - layerHalf2 = 0.5 * (protoLayer.maxZ - protoLayer.minZ); - layerThickness = (protoLayer.maxX - protoLayer.minX); - break; - } - case BinningValue::binY: { - layerHalf1 = 0.5 * (protoLayer.maxX - protoLayer.minX); - layerHalf2 = 0.5 * (protoLayer.maxZ - protoLayer.minZ); - layerThickness = (protoLayer.maxY - protoLayer.minY); - break; - } - default: { - layerHalf1 = 0.5 * (protoLayer.maxX - protoLayer.minX); - layerHalf2 = 0.5 * (protoLayer.maxY - protoLayer.minY); - layerThickness = (protoLayer.maxZ - protoLayer.minZ); - } + case BinningValue::binX: { + layerHalf1 = 0.5 * (protoLayer.maxY - protoLayer.minY); + layerHalf2 = 0.5 * (protoLayer.maxZ - protoLayer.minZ); + layerThickness = (protoLayer.maxX - protoLayer.minX); + break; + } + case BinningValue::binY: { + layerHalf1 = 0.5 * (protoLayer.maxX - protoLayer.minX); + layerHalf2 = 0.5 * (protoLayer.maxZ - protoLayer.minZ); + layerThickness = (protoLayer.maxY - protoLayer.minY); + break; + } + default: { + layerHalf1 = 0.5 * (protoLayer.maxX - protoLayer.minX); + layerHalf2 = 0.5 * (protoLayer.maxY - protoLayer.minY); + layerThickness = (protoLayer.maxZ - protoLayer.minZ); + } } double centerX = 0.5 * (protoLayer.maxX + protoLayer.minX); @@ -416,13 +352,7 @@ Acts::LayerCreator::planeLayer( ACTS_VERBOSE("Creating a plane Layer:"); ACTS_VERBOSE(" - with layer center = " - << "(" - << centerX - << ", " - << centerY - << ", " - << centerZ - << ")"); + << "(" << centerX << ", " << centerY << ", " << centerZ << ")"); ACTS_VERBOSE(" - from X min/max = " << protoLayer.minX << " / " << protoLayer.maxX); ACTS_VERBOSE(" - from Y min/max = " << protoLayer.minY << " / " @@ -437,12 +367,7 @@ Acts::LayerCreator::planeLayer( transform = std::make_shared<const Transform3D>( Translation3D(centerX, centerY, centerZ)); ACTS_VERBOSE(" - layer shift = " - << "(" - << centerX - << ", " - << centerY - << ", " - << centerZ + << "(" << centerX << ", " << centerY << ", " << centerZ << ")"); } @@ -459,23 +384,19 @@ Acts::LayerCreator::planeLayer( new RectangleBounds(layerHalf1, layerHalf2)); // create the layer - MutableLayerPtr pLayer = PlaneLayer::create(transform, - pBounds, - std::move(sArray), - layerThickness, - std::move(ad), - active); - - if (!pLayer) ACTS_ERROR("Creation of plane layer did not succeed!"); + MutableLayerPtr pLayer = + PlaneLayer::create(transform, pBounds, std::move(sArray), layerThickness, + std::move(ad), active); + + if (!pLayer) + ACTS_ERROR("Creation of plane layer did not succeed!"); associateSurfacesToLayer(*pLayer); // now return return pLayer; } -void -Acts::LayerCreator::associateSurfacesToLayer(Layer& layer) const -{ +void Acts::LayerCreator::associateSurfacesToLayer(Layer& layer) const { if (layer.surfaceArray() != nullptr) { auto surfaces = layer.surfaceArray()->surfaces(); @@ -486,11 +407,8 @@ Acts::LayerCreator::associateSurfacesToLayer(Layer& layer) const } } -bool -Acts::LayerCreator::checkBinning(const GeometryContext& gctx, - const SurfaceArray& sArray) const -{ - +bool Acts::LayerCreator::checkBinning(const GeometryContext& gctx, + const SurfaceArray& sArray) const { // do consistency check: can we access all sensitive surfaces // through the binning? If not, surfaces get lost and the binning does not // work @@ -500,8 +418,8 @@ Acts::LayerCreator::checkBinning(const GeometryContext& gctx, std::vector<const Surface*> surfaces = sArray.surfaces(); std::set<const Surface*> sensitiveSurfaces(surfaces.begin(), surfaces.end()); std::set<const Surface*> accessibleSurfaces; - size_t nEmptyBins = 0; - size_t nBinsChecked = 0; + size_t nEmptyBins = 0; + size_t nBinsChecked = 0; // iterate over all bins size_t size = sArray.size(); @@ -521,10 +439,8 @@ Acts::LayerCreator::checkBinning(const GeometryContext& gctx, } std::vector<const Acts::Surface*> diff; - std::set_difference(sensitiveSurfaces.begin(), - sensitiveSurfaces.end(), - accessibleSurfaces.begin(), - accessibleSurfaces.end(), + std::set_difference(sensitiveSurfaces.begin(), sensitiveSurfaces.end(), + accessibleSurfaces.begin(), accessibleSurfaces.end(), std::inserter(diff, diff.begin())); ACTS_VERBOSE(" - Checked " << nBinsChecked << " valid bins"); @@ -536,24 +452,20 @@ Acts::LayerCreator::checkBinning(const GeometryContext& gctx, } if (!diff.empty()) { - ACTS_ERROR(" -- Not all sensitive surfaces are accessible through binning. " - "sensitive: " - << sensitiveSurfaces.size() - << " accessible: " - << accessibleSurfaces.size()); + ACTS_ERROR( + " -- Not all sensitive surfaces are accessible through binning. " + "sensitive: " + << sensitiveSurfaces.size() + << " accessible: " << accessibleSurfaces.size()); // print all inaccessibles ACTS_ERROR(" -- Inaccessible surfaces: "); for (const auto& srf : diff) { // have to choose BinningValue here Vector3D ctr = srf->binningPosition(gctx, binR); - ACTS_ERROR(" Surface(x=" << ctr.x() << ", y=" << ctr.y() << ", z=" - << ctr.z() - << ", r=" - << perp(ctr) - << ", phi=" - << phi(ctr) - << ")"); + ACTS_ERROR(" Surface(x=" << ctr.x() << ", y=" << ctr.y() + << ", z=" << ctr.z() << ", r=" << perp(ctr) + << ", phi=" << phi(ctr) << ")"); } } else { diff --git a/Core/src/Geometry/NavigationLayer.cpp b/Core/src/Geometry/NavigationLayer.cpp index 93bd73d50406b70d0e75e6e5e11a1798a5561e53..c7f6682daea00eabf02ede680342205ef0205e15 100644 --- a/Core/src/Geometry/NavigationLayer.cpp +++ b/Core/src/Geometry/NavigationLayer.cpp @@ -14,13 +14,11 @@ #include "Acts/Surfaces/Surface.hpp" Acts::NavigationLayer::NavigationLayer( - std::shared_ptr<const Surface> surfaceRepresentation, - double thickness) - : Acts::Layer(nullptr) - , m_surfaceRepresentation(std::move(surfaceRepresentation)) -{ + std::shared_ptr<const Surface> surfaceRepresentation, double thickness) + : Acts::Layer(nullptr), + m_surfaceRepresentation(std::move(surfaceRepresentation)) { m_layerThickness = thickness; - m_layerType = navigation; + m_layerType = navigation; } Acts::NavigationLayer::~NavigationLayer() = default; diff --git a/Core/src/Geometry/PassiveLayerBuilder.cpp b/Core/src/Geometry/PassiveLayerBuilder.cpp index d966b25f9a7a9ce3d0024887650a646f39684055..27458cc83b68bc99f5d95580ae08bca9bc2a9b2f 100644 --- a/Core/src/Geometry/PassiveLayerBuilder.cpp +++ b/Core/src/Geometry/PassiveLayerBuilder.cpp @@ -21,73 +21,60 @@ Acts::PassiveLayerBuilder::PassiveLayerBuilder( const PassiveLayerBuilder::Config& plConfig, - std::unique_ptr<const Logger> logger) - : m_cfg(), m_logger(std::move(logger)) -{ + std::unique_ptr<const Logger> logger) + : m_cfg(), m_logger(std::move(logger)) { setConfiguration(plConfig); } -void -Acts::PassiveLayerBuilder::setConfiguration( - const PassiveLayerBuilder::Config& plConfig) -{ +void Acts::PassiveLayerBuilder::setConfiguration( + const PassiveLayerBuilder::Config& plConfig) { //!< @todo add configuration check m_cfg = plConfig; } -void -Acts::PassiveLayerBuilder::setLogger(std::unique_ptr<const Logger> newLogger) -{ +void Acts::PassiveLayerBuilder::setLogger( + std::unique_ptr<const Logger> newLogger) { m_logger = std::move(newLogger); } -const Acts::LayerVector -Acts::PassiveLayerBuilder::positiveLayers(const GeometryContext& gctx) const -{ +const Acts::LayerVector Acts::PassiveLayerBuilder::positiveLayers( + const GeometryContext& gctx) const { return endcapLayers(gctx, 1); } -const Acts::LayerVector -Acts::PassiveLayerBuilder::negativeLayers(const GeometryContext& gctx) const -{ +const Acts::LayerVector Acts::PassiveLayerBuilder::negativeLayers( + const GeometryContext& gctx) const { return endcapLayers(gctx, -1); } -const Acts::LayerVector -Acts::PassiveLayerBuilder::endcapLayers(const Acts::GeometryContext& /*gctx*/, - int side) const -{ +const Acts::LayerVector Acts::PassiveLayerBuilder::endcapLayers( + const Acts::GeometryContext& /*gctx*/, int side) const { LayerVector eLayers; // pos/neg layers size_t numpnLayers = m_cfg.posnegLayerPositionZ.size(); if (numpnLayers != 0u) { ACTS_DEBUG("Configured to build " << numpnLayers - << " passive layers on side :" - << side); + << " passive layers on side :" << side); eLayers.reserve(numpnLayers); // loop through for (size_t ipnl = 0; ipnl < numpnLayers; ++ipnl) { // some screen output - ACTS_VERBOSE("- build layers " << (ipnl) << " at = " - << side - * m_cfg.posnegLayerPositionZ.at(ipnl) - << " and rMin/rMax = " - << m_cfg.posnegLayerRmin.at(ipnl) - << " / " - << m_cfg.posnegLayerRmax.at(ipnl)); + ACTS_VERBOSE("- build layers " + << (ipnl) + << " at = " << side * m_cfg.posnegLayerPositionZ.at(ipnl) + << " and rMin/rMax = " << m_cfg.posnegLayerRmin.at(ipnl) + << " / " << m_cfg.posnegLayerRmax.at(ipnl)); // create the share disc bounds - std::shared_ptr<const DiscBounds> dBounds - = std::make_shared<const RadialBounds>( - m_cfg.posnegLayerRmin.at(ipnl), m_cfg.posnegLayerRmax.at(ipnl)); + std::shared_ptr<const DiscBounds> dBounds = + std::make_shared<const RadialBounds>(m_cfg.posnegLayerRmin.at(ipnl), + m_cfg.posnegLayerRmax.at(ipnl)); // create the layer transforms const Transform3D* eTransform = new Transform3D( Translation3D(0., 0., side * m_cfg.posnegLayerPositionZ.at(ipnl))); // create the layers - MutableLayerPtr eLayer - = DiscLayer::create(std::shared_ptr<const Transform3D>(eTransform), - dBounds, - nullptr, - m_cfg.posnegLayerThickness.at(ipnl)); + MutableLayerPtr eLayer = DiscLayer::create( + std::shared_ptr<const Transform3D>(eTransform), dBounds, nullptr, + m_cfg.posnegLayerThickness.at(ipnl)); // assign the material to the layer surface std::shared_ptr<const ISurfaceMaterial> material = nullptr; @@ -105,25 +92,22 @@ Acts::PassiveLayerBuilder::endcapLayers(const Acts::GeometryContext& /*gctx*/, return eLayers; } -const Acts::LayerVector -Acts::PassiveLayerBuilder::centralLayers( - const Acts::GeometryContext& /*gctx*/) const -{ +const Acts::LayerVector Acts::PassiveLayerBuilder::centralLayers( + const Acts::GeometryContext& /*gctx*/) const { LayerVector cLayers; // the central layers size_t numcLayers = m_cfg.centralLayerRadii.size(); if (numcLayers != 0u) { - ACTS_DEBUG("Configured to build " << numcLayers << " passive central layers."); cLayers.reserve(numcLayers); // loop through for (size_t icl = 0; icl < numcLayers; ++icl) { // some screen output - ACTS_VERBOSE("- build layer " << icl << " with radius = " - << m_cfg.centralLayerRadii.at(icl) - << " and halfZ = " - << m_cfg.centralLayerHalflengthZ.at(icl)); + ACTS_VERBOSE("- build layer " + << icl + << " with radius = " << m_cfg.centralLayerRadii.at(icl) + << " and halfZ = " << m_cfg.centralLayerHalflengthZ.at(icl)); // create the layer and push it back auto cBounds = std::make_shared<const CylinderBounds>( m_cfg.centralLayerRadii[icl], m_cfg.centralLayerHalflengthZ.at(icl)); diff --git a/Core/src/Geometry/PlaneLayer.cpp b/Core/src/Geometry/PlaneLayer.cpp index 0c9e4589a3553474ffc225562f23deeccbe85aae..2ee8fae51546f2dd02fb60a84dc8450057d5b59a 100644 --- a/Core/src/Geometry/PlaneLayer.cpp +++ b/Core/src/Geometry/PlaneLayer.cpp @@ -19,15 +19,14 @@ #include "Acts/Utilities/Definitions.hpp" #include "Acts/Utilities/Helpers.hpp" -Acts::PlaneLayer::PlaneLayer(std::shared_ptr<const Transform3D> transform, +Acts::PlaneLayer::PlaneLayer(std::shared_ptr<const Transform3D> transform, std::shared_ptr<const PlanarBounds>& pbounds, - std::unique_ptr<SurfaceArray> surfaceArray, - double thickness, - std::unique_ptr<ApproachDescriptor> ades, - LayerType laytyp) - : PlaneSurface(std::move(transform), pbounds) - , Layer(std::move(surfaceArray), thickness, std::move(ades), laytyp) -{ + std::unique_ptr<SurfaceArray> surfaceArray, + double thickness, + std::unique_ptr<ApproachDescriptor> ades, + LayerType laytyp) + : PlaneSurface(std::move(transform), pbounds), + Layer(std::move(surfaceArray), thickness, std::move(ades), laytyp) { // @todo create representing volume // register the layer to the surface Acts::PlaneSurface::associateLayer(*this); @@ -41,21 +40,15 @@ Acts::PlaneLayer::PlaneLayer(std::shared_ptr<const Transform3D> transform, } } -const Acts::PlaneSurface& -Acts::PlaneLayer::surfaceRepresentation() const -{ +const Acts::PlaneSurface& Acts::PlaneLayer::surfaceRepresentation() const { return (*this); } -Acts::PlaneSurface& -Acts::PlaneLayer::surfaceRepresentation() -{ +Acts::PlaneSurface& Acts::PlaneLayer::surfaceRepresentation() { return (*this); } -void -Acts::PlaneLayer::buildApproachDescriptor() -{ +void Acts::PlaneLayer::buildApproachDescriptor() { // delete it m_approachDescriptor.reset(nullptr); // delete the surfaces @@ -64,16 +57,16 @@ Acts::PlaneLayer::buildApproachDescriptor() //@todo fix with representing volume const Transform3D& lTransform = PlaneSurface::transform(GeometryContext()); - RotationMatrix3D lRotation = lTransform.rotation(); - const Vector3D& lCenter = PlaneSurface::center(GeometryContext()); - const Vector3D& lVector = Surface::normal(GeometryContext(), lCenter); + RotationMatrix3D lRotation = lTransform.rotation(); + const Vector3D& lCenter = PlaneSurface::center(GeometryContext()); + const Vector3D& lVector = Surface::normal(GeometryContext(), lCenter); // create new surfaces const Transform3D* apnTransform = new Transform3D( - Translation3D(lCenter - 0.5 * Layer::m_layerThickness * lVector) - * lRotation); + Translation3D(lCenter - 0.5 * Layer::m_layerThickness * lVector) * + lRotation); const Transform3D* appTransform = new Transform3D( - Translation3D(lCenter + 0.5 * Layer::m_layerThickness * lVector) - * lRotation); + Translation3D(lCenter + 0.5 * Layer::m_layerThickness * lVector) * + lRotation); // create the new surfaces aSurfaces.push_back(Surface::makeShared<Acts::PlaneSurface>( std::shared_ptr<const Transform3D>(apnTransform), @@ -87,6 +80,6 @@ Acts::PlaneLayer::buildApproachDescriptor() mutableSf->associateLayer(*this); } // @todo check if we can provide the layer at surface creation - m_approachDescriptor - = std::make_unique<const GenericApproachDescriptor>(std::move(aSurfaces)); + m_approachDescriptor = + std::make_unique<const GenericApproachDescriptor>(std::move(aSurfaces)); } \ No newline at end of file diff --git a/Core/src/Geometry/ProtoLayer.cpp b/Core/src/Geometry/ProtoLayer.cpp index c20d27ed98671572ecaa702f9b8568bccd606bb0..4492a966a5a33be0f1fdd975c3865a07f4f22e1e 100644 --- a/Core/src/Geometry/ProtoLayer.cpp +++ b/Core/src/Geometry/ProtoLayer.cpp @@ -15,34 +15,31 @@ #include "Acts/Surfaces/PolyhedronRepresentation.hpp" #include "Acts/Utilities/Helpers.hpp" -using Acts::VectorHelpers::phi; using Acts::VectorHelpers::perp; +using Acts::VectorHelpers::phi; namespace Acts { -ProtoLayer::ProtoLayer(const GeometryContext& gctx, - const std::vector<const Surface*>& surfaces) -{ +ProtoLayer::ProtoLayer(const GeometryContext& gctx, + const std::vector<const Surface*>& surfaces) { measure(gctx, surfaces); } ProtoLayer::ProtoLayer( - const GeometryContext& gctx, - const std::vector<std::shared_ptr<const Surface>>& surfaces) -{ + const GeometryContext& gctx, + const std::vector<std::shared_ptr<const Surface>>& surfaces) { measure(gctx, unpack_shared_vector(surfaces)); } -double -ProtoLayer::radialDistance(const Vector3D& pos1, const Vector3D& pos2) const -{ +double ProtoLayer::radialDistance(const Vector3D& pos1, + const Vector3D& pos2) const { Vector2D p1(pos1.x(), pos1.y()); Vector2D p2(pos2.x(), pos2.y()); Vector2D O(0, 0); Vector2D p1p2 = (p2 - p1); - double L = p1p2.norm(); - Vector2D p1O = (O - p1); + double L = p1p2.norm(); + Vector2D p1O = (O - p1); // don't do division if L is very small if (L < 1e-7) { @@ -54,14 +51,12 @@ ProtoLayer::radialDistance(const Vector3D& pos1, const Vector3D& pos2) const f = std::min(L, std::max(0., f)); Vector2D closest = f * p1p2.normalized() + p1; - double dist = (closest - O).norm(); + double dist = (closest - O).norm(); return dist; } -std::ostream& -ProtoLayer::toStream(std::ostream& sl) const -{ +std::ostream& ProtoLayer::toStream(std::ostream& sl) const { sl << "ProtoLayer with dimensions (min/max)" << std::endl; sl << " - r : " << minR << " - " << envR.first << " / " << maxR << " + " << envR.second << std::endl; @@ -73,43 +68,40 @@ ProtoLayer::toStream(std::ostream& sl) const return sl; } -void -ProtoLayer::measure(const GeometryContext& gctx, - const std::vector<const Surface*>& surfaces) -{ - minR = std::numeric_limits<double>::max(); - maxR = std::numeric_limits<double>::lowest(); - minX = std::numeric_limits<double>::max(); - maxX = std::numeric_limits<double>::lowest(); - minY = std::numeric_limits<double>::max(); - maxY = std::numeric_limits<double>::lowest(); - minZ = std::numeric_limits<double>::max(); - maxZ = std::numeric_limits<double>::lowest(); +void ProtoLayer::measure(const GeometryContext& gctx, + const std::vector<const Surface*>& surfaces) { + minR = std::numeric_limits<double>::max(); + maxR = std::numeric_limits<double>::lowest(); + minX = std::numeric_limits<double>::max(); + maxX = std::numeric_limits<double>::lowest(); + minY = std::numeric_limits<double>::max(); + maxY = std::numeric_limits<double>::lowest(); + minZ = std::numeric_limits<double>::max(); + maxZ = std::numeric_limits<double>::lowest(); minPhi = std::numeric_limits<double>::max(); maxPhi = std::numeric_limits<double>::lowest(); for (const auto& sf : surfaces) { // if the associated detector element exists, use // it for thickness - double thickness = 0; - const DetectorElementBase* element = sf->associatedDetectorElement(); + double thickness = 0; + const DetectorElementBase* element = sf->associatedDetectorElement(); if (element != nullptr) { thickness = element->thickness(); } // check the shape - const PlanarBounds* pBounds - = dynamic_cast<const PlanarBounds*>(&(sf->bounds())); + const PlanarBounds* pBounds = + dynamic_cast<const PlanarBounds*>(&(sf->bounds())); - const CylinderSurface* cylSurface - = dynamic_cast<const CylinderSurface*>(sf); + const CylinderSurface* cylSurface = + dynamic_cast<const CylinderSurface*>(sf); if (pBounds != nullptr) { - const auto& sTransform = sf->transform(gctx); // get the vertices - std::vector<Vector2D> vertices = pBounds->vertices(); - size_t nVertices = vertices.size(); + std::vector<Vector2D> vertices = pBounds->vertices(); + size_t nVertices = vertices.size(); // loop over the two sides of the module // we only need to run once if no element i.e. no thickness for (int side = 0; side < (element != nullptr ? 2 : 1); ++side) { @@ -119,12 +111,10 @@ ProtoLayer::measure(const GeometryContext& gctx, // thickness double locz = side != 0 ? 0.5 * thickness : -0.5 * thickness; // p1 & p2 vectors - Vector3D p2(sTransform * Vector3D(vertices.at(iv).x(), - vertices.at(iv).y(), - locz)); + Vector3D p2(sTransform * + Vector3D(vertices.at(iv).x(), vertices.at(iv).y(), locz)); Vector3D p1(sTransform * Vector3D(vertices.at(ivp).x(), - vertices.at(ivp).y(), - locz)); + vertices.at(ivp).y(), locz)); maxX = std::max(maxX, p2.x()); minX = std::min(minX, p2.x()); @@ -172,36 +162,35 @@ ProtoLayer::measure(const GeometryContext& gctx, for (size_t i = 0; i < face.size(); i++) { Vector3D p1 = ph.vertices.at(face.at(i)); Vector3D p2 = ph.vertices.at(face.at((i + 1) % face.size())); - minR = std::min(minR, radialDistance(p1, p2)); + minR = std::min(minR, radialDistance(p1, p2)); } } // set envelopes to half radius double cylBoundsR = cylSurface->bounds().r(); - double env = cylBoundsR / 2.; - envX = {env, env}; - envY = {env, env}; - envZ = {env, env}; - envR = {env, env}; + double env = cylBoundsR / 2.; + envX = {env, env}; + envY = {env, env}; + envZ = {env, env}; + envR = {env, env}; // evaluate impact of r shift on phi double cylPosR = perp(cylSurface->center(gctx)); - double dPhi = std::atan((cylBoundsR + env) / cylPosR) - - std::atan(cylBoundsR / cylPosR); + double dPhi = std::atan((cylBoundsR + env) / cylPosR) - + std::atan(cylBoundsR / cylPosR); // use this as phi envelope envPhi = {dPhi, dPhi}; } else { // check for cylinder bounds - const CylinderBounds* cBounds - = dynamic_cast<const CylinderBounds*>(&(sf->bounds())); + const CylinderBounds* cBounds = + dynamic_cast<const CylinderBounds*>(&(sf->bounds())); if (cBounds != nullptr) { - - double r = cBounds->r(); - double z = sf->center(gctx).z(); - double hZ = cBounds->halflengthZ(); - double phi = cBounds->averagePhi(); + double r = cBounds->r(); + double z = sf->center(gctx).z(); + double hZ = cBounds->halflengthZ(); + double phi = cBounds->averagePhi(); double hPhi = cBounds->halfPhiSector(); maxX = r; diff --git a/Core/src/Geometry/SurfaceArrayCreator.cpp b/Core/src/Geometry/SurfaceArrayCreator.cpp index 5e981c1314b2a4f2fa86d9a682ebcdaeeab79da4..471ca727ce305aa7ebea0239509d4a9411b588f0 100644 --- a/Core/src/Geometry/SurfaceArrayCreator.cpp +++ b/Core/src/Geometry/SurfaceArrayCreator.cpp @@ -24,36 +24,32 @@ #include "Acts/Utilities/Units.hpp" #include "Acts/Utilities/detail/Axis.hpp" -using Acts::VectorHelpers::phi; using Acts::VectorHelpers::perp; +using Acts::VectorHelpers::phi; std::unique_ptr<Acts::SurfaceArray> Acts::SurfaceArrayCreator::surfaceArrayOnCylinder( - const GeometryContext& gctx, - std::vector<std::shared_ptr<const Surface>> surfaces, - size_t binsPhi, - size_t binsZ, - boost::optional<ProtoLayer> protoLayerOpt, - const std::shared_ptr<const Transform3D>& transformOpt) const -{ + const GeometryContext& gctx, + std::vector<std::shared_ptr<const Surface>> surfaces, size_t binsPhi, + size_t binsZ, boost::optional<ProtoLayer> protoLayerOpt, + const std::shared_ptr<const Transform3D>& transformOpt) const { std::vector<const Surface*> surfacesRaw = unpack_shared_vector(surfaces); // check if we have proto layer, else build it - ProtoLayer protoLayer - = protoLayerOpt ? *protoLayerOpt : ProtoLayer(gctx, surfacesRaw); + ProtoLayer protoLayer = + protoLayerOpt ? *protoLayerOpt : ProtoLayer(gctx, surfacesRaw); ACTS_VERBOSE("Creating a SurfaceArray on a cylinder"); ACTS_VERBOSE(" -- with " << surfaces.size() << " surfaces.") ACTS_VERBOSE(" -- with phi x z = " << binsPhi << " x " << binsZ << " = " - << binsPhi * binsZ - << " bins."); + << binsPhi * binsZ << " bins."); - Transform3D transform - = transformOpt != nullptr ? *transformOpt : Transform3D::Identity(); + Transform3D transform = + transformOpt != nullptr ? *transformOpt : Transform3D::Identity(); - ProtoAxis pAxisPhi = createEquidistantAxis( - gctx, surfacesRaw, binPhi, protoLayer, transform, binsPhi); - ProtoAxis pAxisZ = createEquidistantAxis( - gctx, surfacesRaw, binZ, protoLayer, transform, binsZ); + ProtoAxis pAxisPhi = createEquidistantAxis(gctx, surfacesRaw, binPhi, + protoLayer, transform, binsPhi); + ProtoAxis pAxisZ = createEquidistantAxis(gctx, surfacesRaw, binZ, protoLayer, + transform, binsZ); double R = protoLayer.maxR - protoLayer.minR; @@ -64,118 +60,109 @@ Acts::SurfaceArrayCreator::surfaceArrayOnCylinder( return Vector2D(phi(loc), loc.z()); }; auto localToGlobal = [itransform, R](const Vector2D& loc) { - return itransform - * Vector3D(R * std::cos(loc[0]), R * std::sin(loc[0]), loc[1]); + return itransform * + Vector3D(R * std::cos(loc[0]), R * std::sin(loc[0]), loc[1]); }; - std::unique_ptr<SurfaceArray::ISurfaceGridLookup> sl - = makeSurfaceGridLookup2D<detail::AxisBoundaryType::Closed, - detail::AxisBoundaryType::Bound>( + std::unique_ptr<SurfaceArray::ISurfaceGridLookup> sl = + makeSurfaceGridLookup2D<detail::AxisBoundaryType::Closed, + detail::AxisBoundaryType::Bound>( globalToLocal, localToGlobal, pAxisPhi, pAxisZ); sl->fill(gctx, surfacesRaw); completeBinning(gctx, *sl, surfacesRaw); return std::make_unique<SurfaceArray>( - std::move(sl), - std::move(surfaces), + std::move(sl), std::move(surfaces), std::make_shared<const Transform3D>(transform)); } std::unique_ptr<Acts::SurfaceArray> Acts::SurfaceArrayCreator::surfaceArrayOnCylinder( - const GeometryContext& gctx, - std::vector<std::shared_ptr<const Surface>> surfaces, - BinningType bTypePhi, - BinningType bTypeZ, - boost::optional<ProtoLayer> protoLayerOpt, - const std::shared_ptr<const Transform3D>& transformOpt) const -{ + const GeometryContext& gctx, + std::vector<std::shared_ptr<const Surface>> surfaces, BinningType bTypePhi, + BinningType bTypeZ, boost::optional<ProtoLayer> protoLayerOpt, + const std::shared_ptr<const Transform3D>& transformOpt) const { std::vector<const Surface*> surfacesRaw = unpack_shared_vector(surfaces); // check if we have proto layer, else build it - ProtoLayer protoLayer - = protoLayerOpt ? *protoLayerOpt : ProtoLayer(gctx, surfacesRaw); + ProtoLayer protoLayer = + protoLayerOpt ? *protoLayerOpt : ProtoLayer(gctx, surfacesRaw); - double R = 0.5 * (protoLayer.maxR - protoLayer.minR); - Transform3D transform - = transformOpt != nullptr ? *transformOpt : Transform3D::Identity(); + double R = 0.5 * (protoLayer.maxR - protoLayer.minR); + Transform3D transform = + transformOpt != nullptr ? *transformOpt : Transform3D::Identity(); ProtoAxis pAxisPhi; ProtoAxis pAxisZ; if (bTypePhi == equidistant) { - pAxisPhi = createEquidistantAxis( - gctx, surfacesRaw, binPhi, protoLayer, transform, 0); + pAxisPhi = createEquidistantAxis(gctx, surfacesRaw, binPhi, protoLayer, + transform, 0); } else { - pAxisPhi - = createVariableAxis(gctx, surfacesRaw, binPhi, protoLayer, transform); + pAxisPhi = + createVariableAxis(gctx, surfacesRaw, binPhi, protoLayer, transform); } if (bTypeZ == equidistant) { - pAxisZ - = createEquidistantAxis(gctx, surfacesRaw, binZ, protoLayer, transform); + pAxisZ = + createEquidistantAxis(gctx, surfacesRaw, binZ, protoLayer, transform); } else { pAxisZ = createVariableAxis(gctx, surfacesRaw, binZ, protoLayer, transform); } Transform3D itransform = transform.inverse(); - auto globalToLocal = [transform](const Vector3D& pos) { + auto globalToLocal = [transform](const Vector3D& pos) { Vector3D loc = transform * pos; return Vector2D(phi(loc), loc.z()); }; auto localToGlobal = [itransform, R](const Vector2D& loc) { - return itransform - * Vector3D(R * std::cos(loc[0]), R * std::sin(loc[0]), loc[1]); + return itransform * + Vector3D(R * std::cos(loc[0]), R * std::sin(loc[0]), loc[1]); }; - std::unique_ptr<SurfaceArray::ISurfaceGridLookup> sl - = makeSurfaceGridLookup2D<detail::AxisBoundaryType::Closed, - detail::AxisBoundaryType::Bound>( + std::unique_ptr<SurfaceArray::ISurfaceGridLookup> sl = + makeSurfaceGridLookup2D<detail::AxisBoundaryType::Closed, + detail::AxisBoundaryType::Bound>( globalToLocal, localToGlobal, pAxisPhi, pAxisZ); sl->fill(gctx, surfacesRaw); completeBinning(gctx, *sl, surfacesRaw); // get the number of bins - auto axes = sl->getAxes(); + auto axes = sl->getAxes(); size_t bins0 = axes.at(0)->getNBins(); size_t bins1 = axes.at(1)->getNBins(); ACTS_VERBOSE("Creating a SurfaceArray on a cylinder"); ACTS_VERBOSE(" -- with " << surfaces.size() << " surfaces.") ACTS_VERBOSE(" -- with phi x z = " << bins0 << " x " << bins1 << " = " - << bins0 * bins1 - << " bins."); + << bins0 * bins1 << " bins."); return std::make_unique<SurfaceArray>( - std::move(sl), - std::move(surfaces), + std::move(sl), std::move(surfaces), std::make_shared<const Transform3D>(transform)); } std::unique_ptr<Acts::SurfaceArray> Acts::SurfaceArrayCreator::surfaceArrayOnDisc( - const GeometryContext& gctx, - std::vector<std::shared_ptr<const Surface>> surfaces, - size_t binsR, - size_t binsPhi, - boost::optional<ProtoLayer> protoLayerOpt, - const std::shared_ptr<const Transform3D>& transformOpt) const -{ + const GeometryContext& gctx, + std::vector<std::shared_ptr<const Surface>> surfaces, size_t binsR, + size_t binsPhi, boost::optional<ProtoLayer> protoLayerOpt, + const std::shared_ptr<const Transform3D>& transformOpt) const { std::vector<const Surface*> surfacesRaw = unpack_shared_vector(surfaces); // check if we have proto layer, else build it - ProtoLayer protoLayer - = protoLayerOpt ? *protoLayerOpt : ProtoLayer(gctx, surfacesRaw); + ProtoLayer protoLayer = + protoLayerOpt ? *protoLayerOpt : ProtoLayer(gctx, surfacesRaw); ACTS_VERBOSE("Creating a SurfaceArray on a disc"); - Transform3D transform - = transformOpt != nullptr ? *transformOpt : Transform3D::Identity(); + Transform3D transform = + transformOpt != nullptr ? *transformOpt : Transform3D::Identity(); - ProtoAxis pAxisR = createEquidistantAxis( - gctx, surfacesRaw, binR, protoLayer, transform, binsR); - ProtoAxis pAxisPhi = createEquidistantAxis( - gctx, surfacesRaw, binPhi, protoLayer, transform, binsPhi); + ProtoAxis pAxisR = createEquidistantAxis(gctx, surfacesRaw, binR, protoLayer, + transform, binsR); + ProtoAxis pAxisPhi = createEquidistantAxis(gctx, surfacesRaw, binPhi, + protoLayer, transform, binsPhi); double Z = 0.5 * (protoLayer.minZ + protoLayer.maxZ); ACTS_VERBOSE("- z-position of disk estimated as " << Z); @@ -187,58 +174,53 @@ Acts::SurfaceArrayCreator::surfaceArrayOnDisc( return Vector2D(perp(loc), phi(loc)); }; auto localToGlobal = [itransform, Z](const Vector2D& loc) { - return itransform - * Vector3D(loc[0] * std::cos(loc[1]), loc[0] * std::sin(loc[1]), Z); + return itransform * + Vector3D(loc[0] * std::cos(loc[1]), loc[0] * std::sin(loc[1]), Z); }; - std::unique_ptr<SurfaceArray::ISurfaceGridLookup> sl - = makeSurfaceGridLookup2D<detail::AxisBoundaryType::Bound, - detail::AxisBoundaryType::Closed>( + std::unique_ptr<SurfaceArray::ISurfaceGridLookup> sl = + makeSurfaceGridLookup2D<detail::AxisBoundaryType::Bound, + detail::AxisBoundaryType::Closed>( globalToLocal, localToGlobal, pAxisR, pAxisPhi); // get the number of bins - auto axes = sl->getAxes(); + auto axes = sl->getAxes(); size_t bins0 = axes.at(0)->getNBins(); size_t bins1 = axes.at(1)->getNBins(); ACTS_VERBOSE(" -- with " << surfaces.size() << " surfaces.") ACTS_VERBOSE(" -- with r x phi = " << bins0 << " x " << bins1 << " = " - << bins0 * bins1 - << " bins."); + << bins0 * bins1 << " bins."); sl->fill(gctx, surfacesRaw); completeBinning(gctx, *sl, surfacesRaw); return std::make_unique<SurfaceArray>( - std::move(sl), - std::move(surfaces), + std::move(sl), std::move(surfaces), std::make_shared<const Transform3D>(transform)); } std::unique_ptr<Acts::SurfaceArray> Acts::SurfaceArrayCreator::surfaceArrayOnDisc( - const GeometryContext& gctx, - std::vector<std::shared_ptr<const Surface>> surfaces, - BinningType bTypeR, - BinningType bTypePhi, - boost::optional<ProtoLayer> protoLayerOpt, - const std::shared_ptr<const Transform3D>& transformOpt) const -{ + const GeometryContext& gctx, + std::vector<std::shared_ptr<const Surface>> surfaces, BinningType bTypeR, + BinningType bTypePhi, boost::optional<ProtoLayer> protoLayerOpt, + const std::shared_ptr<const Transform3D>& transformOpt) const { std::vector<const Surface*> surfacesRaw = unpack_shared_vector(surfaces); // check if we have proto layer, else build it - ProtoLayer protoLayer - = protoLayerOpt ? *protoLayerOpt : ProtoLayer(gctx, surfacesRaw); + ProtoLayer protoLayer = + protoLayerOpt ? *protoLayerOpt : ProtoLayer(gctx, surfacesRaw); ACTS_VERBOSE("Creating a SurfaceArray on a disc"); - Transform3D transform - = transformOpt != nullptr ? *transformOpt : Transform3D::Identity(); + Transform3D transform = + transformOpt != nullptr ? *transformOpt : Transform3D::Identity(); ProtoAxis pAxisPhi; ProtoAxis pAxisR; if (bTypeR == equidistant) { - pAxisR - = createEquidistantAxis(gctx, surfacesRaw, binR, protoLayer, transform); + pAxisR = + createEquidistantAxis(gctx, surfacesRaw, binR, protoLayer, transform); } else { pAxisR = createVariableAxis(gctx, surfacesRaw, binR, protoLayer, transform); } @@ -251,20 +233,18 @@ Acts::SurfaceArrayCreator::surfaceArrayOnDisc( std::vector<std::vector<const Surface*>> phiModules(pAxisR.nBins); for (const auto& srf : surfacesRaw) { Vector3D bpos = srf->binningPosition(gctx, binR); - size_t bin = pAxisR.getBin(perp(bpos)); + size_t bin = pAxisR.getBin(perp(bpos)); phiModules.at(bin).push_back(srf); } std::vector<size_t> nPhiModules; - auto matcher = m_cfg.surfaceMatcher; + auto matcher = m_cfg.surfaceMatcher; auto equal = [&gctx, &matcher](const Surface* a, const Surface* b) { return matcher(gctx, binPhi, a, b); }; std::transform( - phiModules.begin(), - phiModules.end(), - std::back_inserter(nPhiModules), + phiModules.begin(), phiModules.end(), std::back_inserter(nPhiModules), [&equal, this](std::vector<const Surface*> surfaces_) -> size_t { return this->findKeySurfaces(surfaces_, equal).size(); }); @@ -275,19 +255,19 @@ Acts::SurfaceArrayCreator::surfaceArrayOnDisc( // but the rotation is done considering all bins. // This might be resolved through bin completion, but not sure. // @TODO: check in extrapolation - size_t nBinsPhi - = (*std::min_element(nPhiModules.begin(), nPhiModules.end())); - pAxisPhi = createEquidistantAxis( - gctx, surfacesRaw, binPhi, protoLayer, transform, nBinsPhi); + size_t nBinsPhi = + (*std::min_element(nPhiModules.begin(), nPhiModules.end())); + pAxisPhi = createEquidistantAxis(gctx, surfacesRaw, binPhi, protoLayer, + transform, nBinsPhi); } else { // use regular determination if (bTypePhi == equidistant) { - pAxisPhi = createEquidistantAxis( - gctx, surfacesRaw, binPhi, protoLayer, transform, 0); + pAxisPhi = createEquidistantAxis(gctx, surfacesRaw, binPhi, protoLayer, + transform, 0); } else { - pAxisPhi = createVariableAxis( - gctx, surfacesRaw, binPhi, protoLayer, transform); + pAxisPhi = + createVariableAxis(gctx, surfacesRaw, binPhi, protoLayer, transform); } } @@ -301,49 +281,44 @@ Acts::SurfaceArrayCreator::surfaceArrayOnDisc( return Vector2D(perp(loc), phi(loc)); }; auto localToGlobal = [itransform, Z](const Vector2D& loc) { - return itransform - * Vector3D(loc[0] * std::cos(loc[1]), loc[0] * std::sin(loc[1]), Z); + return itransform * + Vector3D(loc[0] * std::cos(loc[1]), loc[0] * std::sin(loc[1]), Z); }; - std::unique_ptr<SurfaceArray::ISurfaceGridLookup> sl - = makeSurfaceGridLookup2D<detail::AxisBoundaryType::Bound, - detail::AxisBoundaryType::Closed>( + std::unique_ptr<SurfaceArray::ISurfaceGridLookup> sl = + makeSurfaceGridLookup2D<detail::AxisBoundaryType::Bound, + detail::AxisBoundaryType::Closed>( globalToLocal, localToGlobal, pAxisR, pAxisPhi); // get the number of bins - auto axes = sl->getAxes(); + auto axes = sl->getAxes(); size_t bins0 = axes.at(0)->getNBins(); size_t bins1 = axes.at(1)->getNBins(); ACTS_VERBOSE(" -- with " << surfaces.size() << " surfaces.") ACTS_VERBOSE(" -- with r x phi = " << bins0 << " x " << bins1 << " = " - << bins0 * bins1 - << " bins."); + << bins0 * bins1 << " bins."); sl->fill(gctx, surfacesRaw); completeBinning(gctx, *sl, surfacesRaw); return std::make_unique<SurfaceArray>( - std::move(sl), - std::move(surfaces), + std::move(sl), std::move(surfaces), std::make_shared<const Transform3D>(transform)); } /// SurfaceArrayCreator interface method - create an array on a plane std::unique_ptr<Acts::SurfaceArray> Acts::SurfaceArrayCreator::surfaceArrayOnPlane( - const GeometryContext& gctx, - std::vector<std::shared_ptr<const Surface>> surfaces, - size_t bins1, - size_t bins2, - BinningValue bValue, - boost::optional<ProtoLayer> protoLayerOpt, - const std::shared_ptr<const Transform3D>& transformOpt) const -{ + const GeometryContext& gctx, + std::vector<std::shared_ptr<const Surface>> surfaces, size_t bins1, + size_t bins2, BinningValue bValue, + boost::optional<ProtoLayer> protoLayerOpt, + const std::shared_ptr<const Transform3D>& transformOpt) const { std::vector<const Surface*> surfacesRaw = unpack_shared_vector(surfaces); // check if we have proto layer, else build it - ProtoLayer protoLayer - = protoLayerOpt ? *protoLayerOpt : ProtoLayer(gctx, surfacesRaw); + ProtoLayer protoLayer = + protoLayerOpt ? *protoLayerOpt : ProtoLayer(gctx, surfacesRaw); ACTS_VERBOSE("Creating a SurfaceArray on a plance"); ACTS_VERBOSE(" -- with " << surfaces.size() << " surfaces.") @@ -351,8 +326,8 @@ Acts::SurfaceArrayCreator::surfaceArrayOnPlane( << " bins."); // Transformation - Transform3D transform - = transformOpt != nullptr ? *transformOpt : Transform3D::Identity(); + Transform3D transform = + transformOpt != nullptr ? *transformOpt : Transform3D::Identity(); Transform3D itransform = transform.inverse(); // transform lambda captures the transform matrix @@ -368,58 +343,56 @@ Acts::SurfaceArrayCreator::surfaceArrayOnPlane( // Axis along the binning switch (bValue) { - case BinningValue::binX: { - ProtoAxis pAxis1 = createEquidistantAxis( - gctx, surfacesRaw, binY, protoLayer, transform, bins1); - ProtoAxis pAxis2 = createEquidistantAxis( - gctx, surfacesRaw, binZ, protoLayer, transform, bins2); - sl = makeSurfaceGridLookup2D<detail::AxisBoundaryType::Bound, - detail::AxisBoundaryType::Bound>( - globalToLocal, localToGlobal, pAxis1, pAxis2); - break; - } - case BinningValue::binY: { - ProtoAxis pAxis1 = createEquidistantAxis( - gctx, surfacesRaw, binX, protoLayer, transform, bins1); - ProtoAxis pAxis2 = createEquidistantAxis( - gctx, surfacesRaw, binZ, protoLayer, transform, bins2); - sl = makeSurfaceGridLookup2D<detail::AxisBoundaryType::Bound, - detail::AxisBoundaryType::Bound>( - globalToLocal, localToGlobal, pAxis1, pAxis2); - break; - } - case BinningValue::binZ: { - ProtoAxis pAxis1 = createEquidistantAxis( - gctx, surfacesRaw, binX, protoLayer, transform, bins1); - ProtoAxis pAxis2 = createEquidistantAxis( - gctx, surfacesRaw, binY, protoLayer, transform, bins2); - sl = makeSurfaceGridLookup2D<detail::AxisBoundaryType::Bound, - detail::AxisBoundaryType::Bound>( - globalToLocal, localToGlobal, pAxis1, pAxis2); - break; - } - default: { - throw std::invalid_argument("Acts::SurfaceArrayCreator::" - "surfaceArrayOnPlane: Invalid binning " - "direction"); - } + case BinningValue::binX: { + ProtoAxis pAxis1 = createEquidistantAxis(gctx, surfacesRaw, binY, + protoLayer, transform, bins1); + ProtoAxis pAxis2 = createEquidistantAxis(gctx, surfacesRaw, binZ, + protoLayer, transform, bins2); + sl = makeSurfaceGridLookup2D<detail::AxisBoundaryType::Bound, + detail::AxisBoundaryType::Bound>( + globalToLocal, localToGlobal, pAxis1, pAxis2); + break; + } + case BinningValue::binY: { + ProtoAxis pAxis1 = createEquidistantAxis(gctx, surfacesRaw, binX, + protoLayer, transform, bins1); + ProtoAxis pAxis2 = createEquidistantAxis(gctx, surfacesRaw, binZ, + protoLayer, transform, bins2); + sl = makeSurfaceGridLookup2D<detail::AxisBoundaryType::Bound, + detail::AxisBoundaryType::Bound>( + globalToLocal, localToGlobal, pAxis1, pAxis2); + break; + } + case BinningValue::binZ: { + ProtoAxis pAxis1 = createEquidistantAxis(gctx, surfacesRaw, binX, + protoLayer, transform, bins1); + ProtoAxis pAxis2 = createEquidistantAxis(gctx, surfacesRaw, binY, + protoLayer, transform, bins2); + sl = makeSurfaceGridLookup2D<detail::AxisBoundaryType::Bound, + detail::AxisBoundaryType::Bound>( + globalToLocal, localToGlobal, pAxis1, pAxis2); + break; + } + default: { + throw std::invalid_argument( + "Acts::SurfaceArrayCreator::" + "surfaceArrayOnPlane: Invalid binning " + "direction"); + } } sl->fill(gctx, surfacesRaw); completeBinning(gctx, *sl, surfacesRaw); return std::make_unique<SurfaceArray>( - std::move(sl), - std::move(surfaces), + std::move(sl), std::move(surfaces), std::make_shared<const Transform3D>(transform)); //!< @todo implement - take from ATLAS complex TRT builder } -std::vector<const Acts::Surface*> -Acts::SurfaceArrayCreator::findKeySurfaces( +std::vector<const Acts::Surface*> Acts::SurfaceArrayCreator::findKeySurfaces( const std::vector<const Surface*>& surfaces, - const std::function<bool(const Surface*, const Surface*)>& equal) const -{ + const std::function<bool(const Surface*, const Surface*)>& equal) const { std::vector<const Surface*> keys; for (const auto& srfA : surfaces) { bool exists = false; @@ -437,13 +410,9 @@ Acts::SurfaceArrayCreator::findKeySurfaces( return keys; } -size_t -Acts::SurfaceArrayCreator::determineBinCount( - const GeometryContext& gctx, - const std::vector<const Surface*>& surfaces, - BinningValue bValue) const -{ - +size_t Acts::SurfaceArrayCreator::determineBinCount( + const GeometryContext& gctx, const std::vector<const Surface*>& surfaces, + BinningValue bValue) const { auto matcher = m_cfg.surfaceMatcher; auto equal = [&gctx, &bValue, &matcher](const Surface* a, const Surface* b) { return matcher(gctx, bValue, a, b); @@ -455,12 +424,8 @@ Acts::SurfaceArrayCreator::determineBinCount( Acts::SurfaceArrayCreator::ProtoAxis Acts::SurfaceArrayCreator::createVariableAxis( - const GeometryContext& gctx, - const std::vector<const Surface*>& surfaces, - BinningValue bValue, - ProtoLayer protoLayer, - Transform3D& transform) const -{ + const GeometryContext& gctx, const std::vector<const Surface*>& surfaces, + BinningValue bValue, ProtoLayer protoLayer, Transform3D& transform) const { if (surfaces.empty()) { throw std::logic_error( "No surfaces handed over for creating arbitrary bin utility!"); @@ -478,19 +443,18 @@ Acts::SurfaceArrayCreator::createVariableAxis( std::vector<double> bValues; if (bValue == Acts::binPhi) { - std::stable_sort(keys.begin(), - keys.end(), + std::stable_sort(keys.begin(), keys.end(), [&gctx](const Acts::Surface* a, const Acts::Surface* b) { - return (phi(a->binningPosition(gctx, binPhi)) - < phi(b->binningPosition(gctx, binPhi))); + return (phi(a->binningPosition(gctx, binPhi)) < + phi(b->binningPosition(gctx, binPhi))); }); - double maxPhi = 0.5 * (phi(keys.at(0)->binningPosition(gctx, binPhi)) - + phi(keys.at(1)->binningPosition(gctx, binPhi))); + double maxPhi = 0.5 * (phi(keys.at(0)->binningPosition(gctx, binPhi)) + + phi(keys.at(1)->binningPosition(gctx, binPhi))); // create rotation, so that maxPhi is +pi double angle = -(M_PI + maxPhi); - transform = (transform)*AngleAxis3D(angle, Vector3D::UnitZ()); + transform = (transform)*AngleAxis3D(angle, Vector3D::UnitZ()); // iterate over all key surfaces, and use their mean position as bValues, // but @@ -502,26 +466,26 @@ Acts::SurfaceArrayCreator::createVariableAxis( // create central binning values which is the mean of the center // positions in the binning direction of the current and previous // surface - double edge - = 0.5 * (previous + phi(surface->binningPosition(gctx, binPhi))) - + angle; + double edge = + 0.5 * (previous + phi(surface->binningPosition(gctx, binPhi))) + + angle; bValues.push_back(edge); previous = phi(surface->binningPosition(gctx, binPhi)); } // get the bounds of the last surfaces - const Acts::Surface* backSurface = keys.back(); - const Acts::PlanarBounds* backBounds - = dynamic_cast<const Acts::PlanarBounds*>(&(backSurface->bounds())); + const Acts::Surface* backSurface = keys.back(); + const Acts::PlanarBounds* backBounds = + dynamic_cast<const Acts::PlanarBounds*>(&(backSurface->bounds())); if (backBounds == nullptr) - ACTS_ERROR("Given SurfaceBounds are not planar - not implemented for " - "other bounds yet! "); + ACTS_ERROR( + "Given SurfaceBounds are not planar - not implemented for " + "other bounds yet! "); // get the global vertices - std::vector<Acts::Vector3D> backVertices - = makeGlobalVertices(gctx, *backSurface, backBounds->vertices()); + std::vector<Acts::Vector3D> backVertices = + makeGlobalVertices(gctx, *backSurface, backBounds->vertices()); double maxBValue = phi( - *std::max_element(backVertices.begin(), - backVertices.end(), + *std::max_element(backVertices.begin(), backVertices.end(), [](const Acts::Vector3D& a, const Acts::Vector3D& b) { return phi(a) < phi(b); })); @@ -531,11 +495,10 @@ Acts::SurfaceArrayCreator::createVariableAxis( bValues.push_back(M_PI); } else if (bValue == Acts::binZ) { - std::stable_sort(keys.begin(), - keys.end(), + std::stable_sort(keys.begin(), keys.end(), [&gctx](const Acts::Surface* a, const Acts::Surface* b) { - return (a->binningPosition(gctx, binZ).z() - < b->binningPosition(gctx, binZ).z()); + return (a->binningPosition(gctx, binZ).z() < + b->binningPosition(gctx, binZ).z()); }); bValues.push_back(protoLayer.minZ); @@ -553,11 +516,10 @@ Acts::SurfaceArrayCreator::createVariableAxis( previous = (*surface)->binningPosition(gctx, binZ).z(); } } else { // binR - std::stable_sort(keys.begin(), - keys.end(), + std::stable_sort(keys.begin(), keys.end(), [&gctx](const Acts::Surface* a, const Acts::Surface* b) { - return (perp(a->binningPosition(gctx, binR)) - < perp(b->binningPosition(gctx, binR))); + return (perp(a->binningPosition(gctx, binR)) < + perp(b->binningPosition(gctx, binR))); }); bValues.push_back(protoLayer.minR); @@ -579,30 +541,27 @@ Acts::SurfaceArrayCreator::createVariableAxis( std::sort(bValues.begin(), bValues.end()); ACTS_VERBOSE("Create variable binning Axis for binned SurfaceArray"); ACTS_VERBOSE(" BinningValue: " << bValue); - ACTS_VERBOSE(" (binX = 0, binY = 1, binZ = 2, binR = 3, binPhi = 4, " - "binRPhi = 5, binH = 6, binEta = 7)"); + ACTS_VERBOSE( + " (binX = 0, binY = 1, binZ = 2, binR = 3, binPhi = 4, " + "binRPhi = 5, binH = 6, binEta = 7)"); ACTS_VERBOSE(" Number of bins: " << (bValues.size() - 1)); - ACTS_VERBOSE(" (Min/Max) = (" << bValues.front() << "/" << bValues.back() - << ")"); + ACTS_VERBOSE(" (Min/Max) = (" << bValues.front() << "/" + << bValues.back() << ")"); ProtoAxis pAxis; - pAxis.bType = arbitrary; - pAxis.bValue = bValue; + pAxis.bType = arbitrary; + pAxis.bValue = bValue; pAxis.binEdges = bValues; - pAxis.nBins = bValues.size() - 1; + pAxis.nBins = bValues.size() - 1; return pAxis; } Acts::SurfaceArrayCreator::ProtoAxis Acts::SurfaceArrayCreator::createEquidistantAxis( - const GeometryContext& gctx, - const std::vector<const Surface*>& surfaces, - BinningValue bValue, - ProtoLayer protoLayer, - Transform3D& transform, - size_t nBins) const -{ + const GeometryContext& gctx, const std::vector<const Surface*>& surfaces, + BinningValue bValue, ProtoLayer protoLayer, Transform3D& transform, + size_t nBins) const { if (surfaces.empty()) { throw std::logic_error( "No surfaces handed over for creating equidistant axis!"); @@ -633,123 +592,120 @@ Acts::SurfaceArrayCreator::createEquidistantAxis( // now check the binning value switch (bValue) { - case Acts::binPhi: { - - if (m_cfg.doPhiBinningOptimization) { - // Phi binning - // set the binning option for phi - // sort first in phi - const Acts::Surface* maxElem = *std::max_element( - surfaces.begin(), - surfaces.end(), - [&gctx](const Acts::Surface* a, const Acts::Surface* b) { - return phi(a->binningPosition(gctx, binR)) - < phi(b->binningPosition(gctx, binR)); - }); - - // get the key surfaces at the different phi positions - auto equal - = [&gctx, &bValue, &matcher](const Surface* a, const Surface* b) { - return matcher(gctx, bValue, a, b); - }; - keys = findKeySurfaces(surfaces, equal); - - // multiple surfaces, we bin from -pi to pi closed - if (keys.size() > 1) { - // bOption = Acts::closed; - + case Acts::binPhi: { + if (m_cfg.doPhiBinningOptimization) { + // Phi binning + // set the binning option for phi + // sort first in phi + const Acts::Surface* maxElem = *std::max_element( + surfaces.begin(), surfaces.end(), + [&gctx](const Acts::Surface* a, const Acts::Surface* b) { + return phi(a->binningPosition(gctx, binR)) < + phi(b->binningPosition(gctx, binR)); + }); + + // get the key surfaces at the different phi positions + auto equal = [&gctx, &bValue, &matcher](const Surface* a, + const Surface* b) { + return matcher(gctx, bValue, a, b); + }; + keys = findKeySurfaces(surfaces, equal); + + // multiple surfaces, we bin from -pi to pi closed + if (keys.size() > 1) { + // bOption = Acts::closed; + + minimum = -M_PI; + maximum = M_PI; + + // double step = 2 * M_PI / keys.size(); + double step = 2 * M_PI / binNumber; + // rotate to max phi module plus one half step + // this should make sure that phi wrapping at +- pi + // never falls on a module center + double max = phi(maxElem->binningPosition(gctx, binR)); + double angle = M_PI - (max + 0.5 * step); + + // replace given transform ref + transform = (transform)*AngleAxis3D(angle, Vector3D::UnitZ()); + + } else { + minimum = protoLayer.minPhi; + maximum = protoLayer.maxPhi; + + // we do not need a transform in this case + } + } else { minimum = -M_PI; maximum = M_PI; - - // double step = 2 * M_PI / keys.size(); - double step = 2 * M_PI / binNumber; - // rotate to max phi module plus one half step - // this should make sure that phi wrapping at +- pi - // never falls on a module center - double max = phi(maxElem->binningPosition(gctx, binR)); - double angle = M_PI - (max + 0.5 * step); - - // replace given transform ref - transform = (transform)*AngleAxis3D(angle, Vector3D::UnitZ()); - - } else { - minimum = protoLayer.minPhi; - maximum = protoLayer.maxPhi; - - // we do not need a transform in this case } - } else { - minimum = -M_PI; - maximum = M_PI; + break; + } + case Acts::binR: { + // R binning + + // just use maximum and minimum of all surfaces + // we do not need key surfaces here + maximum = protoLayer.maxR; + minimum = protoLayer.minR; + break; + } + case Acts::binX: { + // X binning + + // just use maximum and minimum of all surfaces + // we do not need key surfaces here + maximum = protoLayer.maxX; + minimum = protoLayer.minX; + break; + } + case Acts::binY: { + // Y binning + + // just use maximum and minimum of all surfaces + // we do not need key surfaces here + maximum = protoLayer.maxY; + minimum = protoLayer.minY; + break; + } + case Acts::binZ: { + // Z binning + + // just use maximum and minimum of all surfaces + // we do not need key surfaces here + maximum = protoLayer.maxZ; + minimum = protoLayer.minZ; + break; + } + default: { + throw std::invalid_argument( + "Acts::SurfaceArrayCreator::" + "createEquidistantAxis: Invalid binning " + "direction"); } - break; - } - case Acts::binR: { - // R binning - - // just use maximum and minimum of all surfaces - // we do not need key surfaces here - maximum = protoLayer.maxR; - minimum = protoLayer.minR; - break; - } - case Acts::binX: { - // X binning - - // just use maximum and minimum of all surfaces - // we do not need key surfaces here - maximum = protoLayer.maxX; - minimum = protoLayer.minX; - break; - } - case Acts::binY: { - // Y binning - - // just use maximum and minimum of all surfaces - // we do not need key surfaces here - maximum = protoLayer.maxY; - minimum = protoLayer.minY; - break; - } - case Acts::binZ: { - // Z binning - - // just use maximum and minimum of all surfaces - // we do not need key surfaces here - maximum = protoLayer.maxZ; - minimum = protoLayer.minZ; - break; - } - default: { - throw std::invalid_argument("Acts::SurfaceArrayCreator::" - "createEquidistantAxis: Invalid binning " - "direction"); - } } // assign the bin size ACTS_VERBOSE("Create equidistant binning Axis for binned SurfaceArray"); ACTS_VERBOSE(" BinningValue: " << bValue); - ACTS_VERBOSE(" (binX = 0, binY = 1, binZ = 2, binR = 3, binPhi = 4, " - "binRPhi = 5, binH = 6, binEta = 7)"); + ACTS_VERBOSE( + " (binX = 0, binY = 1, binZ = 2, binR = 3, binPhi = 4, " + "binRPhi = 5, binH = 6, binEta = 7)"); ACTS_VERBOSE(" Number of bins: " << binNumber); ACTS_VERBOSE(" (Min/Max) = (" << minimum << "/" << maximum << ")"); ProtoAxis pAxis; - pAxis.max = maximum; - pAxis.min = minimum; - pAxis.bType = equidistant; + pAxis.max = maximum; + pAxis.min = minimum; + pAxis.bType = equidistant; pAxis.bValue = bValue; - pAxis.nBins = binNumber; + pAxis.nBins = binNumber; return pAxis; } -std::vector<Acts::Vector3D> -Acts::SurfaceArrayCreator::makeGlobalVertices( - const GeometryContext& gctx, - const Acts::Surface& surface, - const std::vector<Acts::Vector2D>& locVertices) const -{ +std::vector<Acts::Vector3D> Acts::SurfaceArrayCreator::makeGlobalVertices( + const GeometryContext& gctx, const Acts::Surface& surface, + const std::vector<Acts::Vector2D>& locVertices) const { std::vector<Acts::Vector3D> globVertices; for (auto& vertex : locVertices) { Acts::Vector3D globVertex(0., 0., 0.); diff --git a/Core/src/Geometry/TrackingGeometry.cpp b/Core/src/Geometry/TrackingGeometry.cpp index 11a9eac0be8e6459b6a3d8b7b1a74e6f67885fce..16e419d921d8f0c8bb7d3362d9d991f6efa20260 100644 --- a/Core/src/Geometry/TrackingGeometry.cpp +++ b/Core/src/Geometry/TrackingGeometry.cpp @@ -20,10 +20,9 @@ Acts::TrackingGeometry::TrackingGeometry( const MutableTrackingVolumePtr& highestVolume, - const IMaterialDecorator* materialDecorator) - : m_world(highestVolume) - , m_beam(Surface::makeShared<PerigeeSurface>(s_origin)) -{ + const IMaterialDecorator* materialDecorator) + : m_world(highestVolume), + m_beam(Surface::makeShared<PerigeeSurface>(s_origin)) { // Close the geometry: assign geometryID and successively the material size_t volumeID = 0; highestVolume->closeGeometry(materialDecorator, m_trackingVolumes, volumeID); @@ -31,67 +30,54 @@ Acts::TrackingGeometry::TrackingGeometry( Acts::TrackingGeometry::~TrackingGeometry() = default; -const Acts::TrackingVolume* -Acts::TrackingGeometry::lowestTrackingVolume(const GeometryContext& gctx, - const Acts::Vector3D& gp) const -{ - const TrackingVolume* searchVolume = m_world.get(); +const Acts::TrackingVolume* Acts::TrackingGeometry::lowestTrackingVolume( + const GeometryContext& gctx, const Acts::Vector3D& gp) const { + const TrackingVolume* searchVolume = m_world.get(); const TrackingVolume* currentVolume = nullptr; while (currentVolume != searchVolume && (searchVolume != nullptr)) { currentVolume = searchVolume; - searchVolume = searchVolume->lowestTrackingVolume(gctx, gp); + searchVolume = searchVolume->lowestTrackingVolume(gctx, gp); } return currentVolume; } -const Acts::TrackingVolume* -Acts::TrackingGeometry::highestTrackingVolume() const -{ +const Acts::TrackingVolume* Acts::TrackingGeometry::highestTrackingVolume() + const { return (m_world.get()); } -void -Acts::TrackingGeometry::sign(GeometrySignature geosit, GeometryType geotype) -{ +void Acts::TrackingGeometry::sign(GeometrySignature geosit, + GeometryType geotype) { auto mutableWorld = std::const_pointer_cast<TrackingVolume>(m_world); mutableWorld->sign(geosit, geotype); } -const Acts::TrackingVolume* -Acts::TrackingGeometry::trackingVolume(const std::string& name) const -{ +const Acts::TrackingVolume* Acts::TrackingGeometry::trackingVolume( + const std::string& name) const { auto sVol = m_trackingVolumes.begin(); - sVol = m_trackingVolumes.find(name); + sVol = m_trackingVolumes.find(name); if (sVol != m_trackingVolumes.end()) { return (sVol->second); } return nullptr; } -const Acts::Layer* -Acts::TrackingGeometry::associatedLayer(const GeometryContext& gctx, - const Acts::Vector3D& gp) const -{ +const Acts::Layer* Acts::TrackingGeometry::associatedLayer( + const GeometryContext& gctx, const Acts::Vector3D& gp) const { const TrackingVolume* lowestVol = (lowestTrackingVolume(gctx, gp)); return lowestVol->associatedLayer(gctx, gp); } -void -Acts::TrackingGeometry::registerBeamTube( - std::shared_ptr<const PerigeeSurface> beam) -{ +void Acts::TrackingGeometry::registerBeamTube( + std::shared_ptr<const PerigeeSurface> beam) { m_beam = std::move(beam); } -const Acts::Surface* -Acts::TrackingGeometry::getBeamline() const -{ +const Acts::Surface* Acts::TrackingGeometry::getBeamline() const { return m_beam.get(); } -void -Acts::TrackingGeometry::visitSurfaces( - const std::function<void(const Acts::Surface*)>& visitor) const -{ +void Acts::TrackingGeometry::visitSurfaces( + const std::function<void(const Acts::Surface*)>& visitor) const { highestTrackingVolume()->visitSurfaces(visitor); } diff --git a/Core/src/Geometry/TrackingGeometryBuilder.cpp b/Core/src/Geometry/TrackingGeometryBuilder.cpp index a7e344be7d2cbf2f0cda155c3fe9c154dcf89dde..a3af9dcb9e68077c94caa5e1285003bd14ab33d1 100644 --- a/Core/src/Geometry/TrackingGeometryBuilder.cpp +++ b/Core/src/Geometry/TrackingGeometryBuilder.cpp @@ -21,35 +21,29 @@ Acts::TrackingGeometryBuilder::TrackingGeometryBuilder( const Acts::TrackingGeometryBuilder::Config& cgbConfig, - std::unique_ptr<const Logger> logger) - : m_cfg(), m_logger(std::move(logger)) -{ + std::unique_ptr<const Logger> logger) + : m_cfg(), m_logger(std::move(logger)) { setConfiguration(cgbConfig); } -void -Acts::TrackingGeometryBuilder::setConfiguration( - const Acts::TrackingGeometryBuilder::Config& cgbConfig) -{ +void Acts::TrackingGeometryBuilder::setConfiguration( + const Acts::TrackingGeometryBuilder::Config& cgbConfig) { // @todo check consistency // copy the configuration m_cfg = cgbConfig; } -void -Acts::TrackingGeometryBuilder::setLogger( - std::unique_ptr<const Logger> newLogger) -{ +void Acts::TrackingGeometryBuilder::setLogger( + std::unique_ptr<const Logger> newLogger) { m_logger = std::move(newLogger); } std::unique_ptr<const Acts::TrackingGeometry> Acts::TrackingGeometryBuilder::trackingGeometry( - const GeometryContext& gctx) const -{ + const GeometryContext& gctx) const { // the return geometry with the highest volume std::unique_ptr<const TrackingGeometry> trackingGeometry; - MutableTrackingVolumePtr highestVolume = nullptr; + MutableTrackingVolumePtr highestVolume = nullptr; // loop over the builders and wrap one around the other // ----------------------------- for (auto& volumeBuilder : m_cfg.trackingVolumeBuilders) { @@ -61,8 +55,8 @@ Acts::TrackingGeometryBuilder::trackingGeometry( // create the TrackingGeometry & decorate it with the material if (highestVolume) { // first check if we have material to get - const IMaterialDecorator* materialDecorator - = m_cfg.materialDecorator ? m_cfg.materialDecorator.get() : nullptr; + const IMaterialDecorator* materialDecorator = + m_cfg.materialDecorator ? m_cfg.materialDecorator.get() : nullptr; // build and set the TrackingGeometry trackingGeometry.reset( new TrackingGeometry(highestVolume, materialDecorator)); diff --git a/Core/src/Geometry/TrackingVolume.cpp b/Core/src/Geometry/TrackingVolume.cpp index f62e91a542cf7ebbd2d70989ce63f3d5863e8963..cb733c7766aa1f346f6b2668cbb91021194948d9 100644 --- a/Core/src/Geometry/TrackingVolume.cpp +++ b/Core/src/Geometry/TrackingVolume.cpp @@ -21,58 +21,49 @@ #include "Acts/Utilities/BinUtility.hpp" Acts::TrackingVolume::TrackingVolume() - : Volume() - , m_volumeMaterial(nullptr) - , m_boundarySurfaces() - , m_confinedLayers(nullptr) - , m_confinedVolumes(nullptr) - , m_name("undefined") -{ -} + : Volume(), + m_volumeMaterial(nullptr), + m_boundarySurfaces(), + m_confinedLayers(nullptr), + m_confinedVolumes(nullptr), + m_name("undefined") {} Acts::TrackingVolume::TrackingVolume( - std::shared_ptr<const Transform3D> htrans, - VolumeBoundsPtr volbounds, + std::shared_ptr<const Transform3D> htrans, VolumeBoundsPtr volbounds, const std::shared_ptr<const TrackingVolumeArray>& containedVolumeArray, - const std::string& volumeName) - : Volume(std::move(htrans), std::move(volbounds)) - , m_volumeMaterial(nullptr) - , m_boundarySurfaces() - , m_confinedLayers(nullptr) - , m_confinedVolumes(containedVolumeArray) - , m_name(volumeName) -{ + const std::string& volumeName) + : Volume(std::move(htrans), std::move(volbounds)), + m_volumeMaterial(nullptr), + m_boundarySurfaces(), + m_confinedLayers(nullptr), + m_confinedVolumes(containedVolumeArray), + m_name(volumeName) { createBoundarySurfaces(); interlinkLayers(); } // constructor for arguments Acts::TrackingVolume::TrackingVolume( - std::shared_ptr<const Transform3D> htrans, - VolumeBoundsPtr volumeBounds, - std::shared_ptr<const IVolumeMaterial> volumeMaterial, - std::unique_ptr<const LayerArray> staticLayerArray, + std::shared_ptr<const Transform3D> htrans, VolumeBoundsPtr volumeBounds, + std::shared_ptr<const IVolumeMaterial> volumeMaterial, + std::unique_ptr<const LayerArray> staticLayerArray, std::shared_ptr<const TrackingVolumeArray> containedVolumeArray, - const std::string& volumeName) - : Volume(std::move(htrans), std::move(volumeBounds)) - , m_volumeMaterial(std::move(volumeMaterial)) - , m_confinedLayers(std::move(staticLayerArray)) - , m_confinedVolumes(std::move(containedVolumeArray)) - , m_name(volumeName) -{ + const std::string& volumeName) + : Volume(std::move(htrans), std::move(volumeBounds)), + m_volumeMaterial(std::move(volumeMaterial)), + m_confinedLayers(std::move(staticLayerArray)), + m_confinedVolumes(std::move(containedVolumeArray)), + m_name(volumeName) { createBoundarySurfaces(); interlinkLayers(); } -Acts::TrackingVolume::~TrackingVolume() -{ +Acts::TrackingVolume::~TrackingVolume() { delete m_glueVolumeDescriptor; } -const Acts::TrackingVolume* -Acts::TrackingVolume::lowestTrackingVolume(const GeometryContext& /*gctx*/, - const Vector3D& gp) const -{ +const Acts::TrackingVolume* Acts::TrackingVolume::lowestTrackingVolume( + const GeometryContext& /*gctx*/, const Vector3D& gp) const { // confined static volumes - highest hierarchy if (m_confinedVolumes) { return (m_confinedVolumes->object(gp).get()); @@ -82,9 +73,8 @@ Acts::TrackingVolume::lowestTrackingVolume(const GeometryContext& /*gctx*/, return this; } -void -Acts::TrackingVolume::sign(GeometrySignature geosign, GeometryType geotype) -{ +void Acts::TrackingVolume::sign(GeometrySignature geosign, + GeometryType geotype) { // never overwrite what is already signed, that's a crime if (m_geometrySignature == Unsigned) { m_geometrySignature = geosign; @@ -94,117 +84,105 @@ Acts::TrackingVolume::sign(GeometrySignature geosign, GeometryType geotype) // confined static volumes if (m_confinedVolumes) { for (auto& volumesIter : (m_confinedVolumes->arrayObjects())) { - auto mutableVolumesIter - = std::const_pointer_cast<TrackingVolume>(volumesIter); + auto mutableVolumesIter = + std::const_pointer_cast<TrackingVolume>(volumesIter); mutableVolumesIter->sign(geosign, geotype); } } } -const std:: - vector<std::shared_ptr<const Acts::BoundarySurfaceT<Acts::TrackingVolume>>>& - Acts::TrackingVolume::boundarySurfaces() const -{ +const std::vector< + std::shared_ptr<const Acts::BoundarySurfaceT<Acts::TrackingVolume>>>& +Acts::TrackingVolume::boundarySurfaces() const { return (m_boundarySurfaces); } -void -Acts::TrackingVolume::createBoundarySurfaces() -{ +void Acts::TrackingVolume::createBoundarySurfaces() { // transform Surfaces To BoundarySurfaces - std::vector<std::shared_ptr<const Surface>> surfaces - = Volume::volumeBounds().decomposeToSurfaces(m_transform.get()); + std::vector<std::shared_ptr<const Surface>> surfaces = + Volume::volumeBounds().decomposeToSurfaces(m_transform.get()); // counter to flip the inner/outer position for Cylinders - int sfCounter = 0; - size_t sfNumber = surfaces.size(); + int sfCounter = 0; + size_t sfNumber = surfaces.size(); for (auto& sf : surfaces) { // flip inner/outer for cylinders - TrackingVolume* inner - = (sf->type() == Surface::Cylinder && sfCounter == 3 && sfNumber > 3) - ? nullptr - : this; + TrackingVolume* inner = + (sf->type() == Surface::Cylinder && sfCounter == 3 && sfNumber > 3) + ? nullptr + : this; TrackingVolume* outer = (inner) != nullptr ? nullptr : this; // create the boundary surface m_boundarySurfaces.push_back( - std::make_shared<const BoundarySurfaceT<TrackingVolume>>( - std::move(sf), inner, outer)); + std::make_shared<const BoundarySurfaceT<TrackingVolume>>(std::move(sf), + inner, outer)); // increase the counter ++sfCounter; } } -void -Acts::TrackingVolume::glueTrackingVolume( - const GeometryContext& gctx, - BoundarySurfaceFace bsfMine, +void Acts::TrackingVolume::glueTrackingVolume( + const GeometryContext& gctx, BoundarySurfaceFace bsfMine, const std::shared_ptr<TrackingVolume>& neighbor, - BoundarySurfaceFace bsfNeighbor) -{ - + BoundarySurfaceFace bsfNeighbor) { // find the connection of the two tracking volumes : binR returns the center // except for cylindrical volumes Vector3D bPosition(binningPosition(gctx, binR)); - Vector3D distance - = Vector3D(neighbor->binningPosition(gctx, binR) - bPosition); + Vector3D distance = + Vector3D(neighbor->binningPosition(gctx, binR) - bPosition); // glue to the face - std::shared_ptr<const BoundarySurfaceT<TrackingVolume>> bSurfaceMine - = boundarySurfaces().at(bsfMine); + std::shared_ptr<const BoundarySurfaceT<TrackingVolume>> bSurfaceMine = + boundarySurfaces().at(bsfMine); // @todo - complex glueing could be possible with actual intersection for the // normal vector - Vector3D normal - = bSurfaceMine->surfaceRepresentation().normal(gctx, bPosition); + Vector3D normal = + bSurfaceMine->surfaceRepresentation().normal(gctx, bPosition); // estimate the orientation - BoundaryOrientation bOrientation - = (normal.dot(distance) > 0.) ? outsideVolume : insideVolume; + BoundaryOrientation bOrientation = + (normal.dot(distance) > 0.) ? outsideVolume : insideVolume; // the easy case : // - no glue volume descriptors on either side - if ((m_glueVolumeDescriptor == nullptr) - || !m_glueVolumeDescriptor->glueVolumes(bsfMine)) { + if ((m_glueVolumeDescriptor == nullptr) || + !m_glueVolumeDescriptor->glueVolumes(bsfMine)) { // the boundary orientation - auto mutableBSurfaceMine - = std::const_pointer_cast<BoundarySurfaceT<TrackingVolume>>( - bSurfaceMine); + auto mutableBSurfaceMine = + std::const_pointer_cast<BoundarySurfaceT<TrackingVolume>>(bSurfaceMine); mutableBSurfaceMine->attachVolume(neighbor, bOrientation); // now set it to the neighbor volume - the optised way (neighbor->m_boundarySurfaces).at(bsfNeighbor) = bSurfaceMine; } } -void -Acts::TrackingVolume::glueTrackingVolumes( - const GeometryContext& gctx, - BoundarySurfaceFace bsfMine, +void Acts::TrackingVolume::glueTrackingVolumes( + const GeometryContext& gctx, BoundarySurfaceFace bsfMine, const std::shared_ptr<TrackingVolumeArray>& neighbors, - BoundarySurfaceFace bsfNeighbor) -{ + BoundarySurfaceFace bsfNeighbor) { // find the connection of the two tracking volumes : binR returns the center // except for cylindrical volumes - std::shared_ptr<const TrackingVolume> nRefVolume - = neighbors->arrayObjects().at(0); + std::shared_ptr<const TrackingVolume> nRefVolume = + neighbors->arrayObjects().at(0); // get the distance Vector3D bPosition(binningPosition(gctx, binR)); - Vector3D distance - = Vector3D(nRefVolume->binningPosition(gctx, binR) - bPosition); + Vector3D distance = + Vector3D(nRefVolume->binningPosition(gctx, binR) - bPosition); // take the normal at the binning positio - std::shared_ptr<const BoundarySurfaceT<TrackingVolume>> bSurfaceMine - = boundarySurfaces().at(bsfMine); + std::shared_ptr<const BoundarySurfaceT<TrackingVolume>> bSurfaceMine = + boundarySurfaces().at(bsfMine); // @todo - complex glueing could be possible with actual intersection for the // normal vector - Vector3D normal - = bSurfaceMine->surfaceRepresentation().normal(gctx, bPosition); + Vector3D normal = + bSurfaceMine->surfaceRepresentation().normal(gctx, bPosition); // estimate the orientation - BoundaryOrientation bOrientation - = (normal.dot(distance) > 0.) ? outsideVolume : insideVolume; + BoundaryOrientation bOrientation = + (normal.dot(distance) > 0.) ? outsideVolume : insideVolume; // the easy case : // - no glue volume descriptors on either side - if ((m_glueVolumeDescriptor == nullptr) - || !m_glueVolumeDescriptor->glueVolumes(bsfMine)) { + if ((m_glueVolumeDescriptor == nullptr) || + !m_glueVolumeDescriptor->glueVolumes(bsfMine)) { // the boundary orientation - auto mutableBSurfaceMine - = std::const_pointer_cast<BoundarySurfaceT<TrackingVolume>>( - bSurfaceMine); + auto mutableBSurfaceMine = + std::const_pointer_cast<BoundarySurfaceT<TrackingVolume>>(bSurfaceMine); mutableBSurfaceMine->attachVolumeArray(neighbors, bOrientation); // now set it to the neighbor volumes - the optised way for (auto& nVolume : neighbors->arrayObjects()) { @@ -214,33 +192,26 @@ Acts::TrackingVolume::glueTrackingVolumes( } } -void -Acts::TrackingVolume::updateBoundarySurface( - BoundarySurfaceFace bsf, - std::shared_ptr<const BoundarySurfaceT<TrackingVolume>> bs) -{ +void Acts::TrackingVolume::updateBoundarySurface( + BoundarySurfaceFace bsf, + std::shared_ptr<const BoundarySurfaceT<TrackingVolume>> bs) { m_boundarySurfaces.at(bsf) = std::move(bs); } -void -Acts::TrackingVolume::registerGlueVolumeDescriptor(GlueVolumesDescriptor* gvd) -{ +void Acts::TrackingVolume::registerGlueVolumeDescriptor( + GlueVolumesDescriptor* gvd) { delete m_glueVolumeDescriptor; m_glueVolumeDescriptor = gvd; } -Acts::GlueVolumesDescriptor& -Acts::TrackingVolume::glueVolumesDescriptor() -{ +Acts::GlueVolumesDescriptor& Acts::TrackingVolume::glueVolumesDescriptor() { if (m_glueVolumeDescriptor == nullptr) { m_glueVolumeDescriptor = new GlueVolumesDescriptor; } return (*m_glueVolumeDescriptor); } -void -Acts::TrackingVolume::synchronizeLayers(double envelope) const -{ +void Acts::TrackingVolume::synchronizeLayers(double envelope) const { // case a : Layers exist // msgstream << MSG::VERBOSE << " -> synchronizing Layer dimensions of // TrackingVolume '" << volumeName() << "'." << endreq; @@ -274,9 +245,7 @@ Acts::TrackingVolume::synchronizeLayers(double envelope) const } } -void -Acts::TrackingVolume::interlinkLayers() -{ +void Acts::TrackingVolume::interlinkLayers() { if (m_confinedLayers) { auto& layers = m_confinedLayers->arrayObjects(); @@ -301,17 +270,14 @@ Acts::TrackingVolume::interlinkLayers() // set the other next volume Layer& mutableLayer = *(std::const_pointer_cast<Layer>(*layerIter)); mutableLayer.m_nextLayers.second = lastLayer; - lastLayer = &mutableLayer; + lastLayer = &mutableLayer; } } } -void -Acts::TrackingVolume::closeGeometry( +void Acts::TrackingVolume::closeGeometry( const IMaterialDecorator* materialDecorator, - std::map<std::string, const TrackingVolume*>& volumeMap, - size_t& vol) -{ + std::map<std::string, const TrackingVolume*>& volumeMap, size_t& vol) { // insert the volume into the map volumeMap[volumeName()] = this; @@ -364,17 +330,15 @@ Acts::TrackingVolume::closeGeometry( // B) this is a container volume, go through sub volume // do the loop for (auto& volumesIter : m_confinedVolumes->arrayObjects()) { - auto mutableVolumesIter - = std::const_pointer_cast<TrackingVolume>(volumesIter); + auto mutableVolumesIter = + std::const_pointer_cast<TrackingVolume>(volumesIter); mutableVolumesIter->closeGeometry(materialDecorator, volumeMap, vol); } } } -void -Acts::TrackingVolume::visitSurfaces( - const std::function<void(const Acts::Surface*)>& visitor) const -{ +void Acts::TrackingVolume::visitSurfaces( + const std::function<void(const Acts::Surface*)>& visitor) const { if (!m_confinedVolumes) { // no sub volumes => loop over the confined layers if (m_confinedLayers) { diff --git a/Core/src/Geometry/TrackingVolumeArrayCreator.cpp b/Core/src/Geometry/TrackingVolumeArrayCreator.cpp index f732a0ca15dd58daea707571becf5d16b1adf844..f7aead17015251dd0dd79740975774fbc7fff978 100644 --- a/Core/src/Geometry/TrackingVolumeArrayCreator.cpp +++ b/Core/src/Geometry/TrackingVolumeArrayCreator.cpp @@ -20,10 +20,8 @@ std::shared_ptr<const Acts::TrackingVolumeArray> Acts::TrackingVolumeArrayCreator::trackingVolumeArray( - const GeometryContext& gctx, - const TrackingVolumeVector& tVolumes, - BinningValue bValue) const -{ + const GeometryContext& gctx, const TrackingVolumeVector& tVolumes, + BinningValue bValue) const { // MSG_VERBOSE("Create VolumeArray of "<< tVolumes.size() << " TrackingVolumes // with binning in : " << binningValueNames[bValue] ); // let's copy and sort @@ -44,7 +42,7 @@ Acts::TrackingVolumeArrayCreator::trackingVolumeArray( for (auto& tVolume : volumes) { // get the binning position Vector3D binningPosition = tVolume->binningPosition(gctx, bValue); - double binningBorder = tVolume->volumeBounds().binningBorder(bValue); + double binningBorder = tVolume->volumeBounds().binningBorder(bValue); // get the center value according to the bin double value = tVolume->binningPositionValue(gctx, bValue); // for the first one take low and high boundary @@ -59,8 +57,8 @@ Acts::TrackingVolumeArrayCreator::trackingVolumeArray( } // now create the bin utility - auto binUtility - = std::make_unique<const BinUtility>(boundaries, open, bValue); + auto binUtility = + std::make_unique<const BinUtility>(boundaries, open, bValue); // and return the newly created binned array return std::make_shared<const BinnedArrayXD<TrackingVolumePtr>>( diff --git a/Core/src/Geometry/TrapezoidVolumeBounds.cpp b/Core/src/Geometry/TrapezoidVolumeBounds.cpp index 6fd41729ba72f2bb9b56dcf61f944738b45ead10..6b1cb546346423d506feb84d161493deaa80de35 100644 --- a/Core/src/Geometry/TrapezoidVolumeBounds.cpp +++ b/Core/src/Geometry/TrapezoidVolumeBounds.cpp @@ -20,39 +20,32 @@ #include "Acts/Surfaces/TrapezoidBounds.hpp" Acts::TrapezoidVolumeBounds::TrapezoidVolumeBounds() - : VolumeBounds(), m_valueStore(bv_length, 0.) -{ -} + : VolumeBounds(), m_valueStore(bv_length, 0.) {} Acts::TrapezoidVolumeBounds::TrapezoidVolumeBounds(double minhalex, double maxhalex, - double haley, - double halez) - : VolumeBounds(), m_valueStore(bv_length, 0.) -{ + double haley, double halez) + : VolumeBounds(), m_valueStore(bv_length, 0.) { m_valueStore.at(bv_minHalfX) = minhalex; m_valueStore.at(bv_maxHalfX) = maxhalex; - m_valueStore.at(bv_halfY) = haley; - m_valueStore.at(bv_halfZ) = halez; - m_valueStore.at(bv_alpha) - = atan((m_valueStore.at(bv_maxHalfX) - m_valueStore.at(bv_minHalfX)) / 2 - / m_valueStore.at(bv_halfY)) - + 0.5 * M_PI; + m_valueStore.at(bv_halfY) = haley; + m_valueStore.at(bv_halfZ) = halez; + m_valueStore.at(bv_alpha) = + atan((m_valueStore.at(bv_maxHalfX) - m_valueStore.at(bv_minHalfX)) / 2 / + m_valueStore.at(bv_halfY)) + + 0.5 * M_PI; m_valueStore.at(bv_beta) = m_valueStore.at(bv_alpha); } Acts::TrapezoidVolumeBounds::TrapezoidVolumeBounds(double minhalex, - double haley, - double halez, - double alpha, - double beta) - : VolumeBounds(), m_valueStore(bv_length, 0.) -{ + double haley, double halez, + double alpha, double beta) + : VolumeBounds(), m_valueStore(bv_length, 0.) { m_valueStore.at(bv_minHalfX) = minhalex; - m_valueStore.at(bv_halfY) = haley; - m_valueStore.at(bv_halfZ) = halez; - m_valueStore.at(bv_alpha) = alpha; - m_valueStore.at(bv_beta) = beta; + m_valueStore.at(bv_halfY) = haley; + m_valueStore.at(bv_halfZ) = halez; + m_valueStore.at(bv_alpha) = alpha; + m_valueStore.at(bv_beta) = beta; // now calculate the remaining max half X double gamma = (alpha > beta) ? (alpha - 0.5 * M_PI) : (beta - 0.5 * M_PI); m_valueStore.at(bv_maxHalfX) = minhalex + (2. * haley) * tan(gamma); @@ -60,15 +53,12 @@ Acts::TrapezoidVolumeBounds::TrapezoidVolumeBounds(double minhalex, Acts::TrapezoidVolumeBounds::TrapezoidVolumeBounds( const TrapezoidVolumeBounds& trabo) - : VolumeBounds(), m_valueStore(trabo.m_valueStore) -{ -} + : VolumeBounds(), m_valueStore(trabo.m_valueStore) {} Acts::TrapezoidVolumeBounds::~TrapezoidVolumeBounds() = default; -Acts::TrapezoidVolumeBounds& -Acts::TrapezoidVolumeBounds::operator=(const TrapezoidVolumeBounds& trabo) -{ +Acts::TrapezoidVolumeBounds& Acts::TrapezoidVolumeBounds::operator=( + const TrapezoidVolumeBounds& trabo) { if (this != &trabo) { m_valueStore = trabo.m_valueStore; } @@ -77,40 +67,39 @@ Acts::TrapezoidVolumeBounds::operator=(const TrapezoidVolumeBounds& trabo) std::vector<std::shared_ptr<const Acts::Surface>> Acts::TrapezoidVolumeBounds::decomposeToSurfaces( - const Transform3D* transformPtr) const -{ + const Transform3D* transformPtr) const { std::vector<std::shared_ptr<const Surface>> rSurfaces; - Transform3D transform - = (transformPtr == nullptr) ? Transform3D::Identity() : (*transformPtr); + Transform3D transform = + (transformPtr == nullptr) ? Transform3D::Identity() : (*transformPtr); const Transform3D* tTransform = nullptr; // face surfaces xy RotationMatrix3D trapezoidRotation(transform.rotation()); - Vector3D trapezoidX(trapezoidRotation.col(0)); - Vector3D trapezoidY(trapezoidRotation.col(1)); - Vector3D trapezoidZ(trapezoidRotation.col(2)); - Vector3D trapezoidCenter(transform.translation()); + Vector3D trapezoidX(trapezoidRotation.col(0)); + Vector3D trapezoidY(trapezoidRotation.col(1)); + Vector3D trapezoidZ(trapezoidRotation.col(2)); + Vector3D trapezoidCenter(transform.translation()); // (1) - at negative local z std::shared_ptr<const PlanarBounds> xytBounds(faceXYTrapezoidBounds()); - tTransform - = new Transform3D(transform * AngleAxis3D(M_PI, Vector3D(0., 1., 0.)) - * Translation3D(Vector3D(0., 0., halflengthZ()))); + tTransform = + new Transform3D(transform * AngleAxis3D(M_PI, Vector3D(0., 1., 0.)) * + Translation3D(Vector3D(0., 0., halflengthZ()))); rSurfaces.push_back(Surface::makeShared<PlaneSurface>( std::shared_ptr<const Transform3D>(tTransform), xytBounds)); // (2) - at positive local z - tTransform = new Transform3D( - transform * Translation3D(Vector3D(0., 0., halflengthZ()))); + tTransform = new Transform3D(transform * + Translation3D(Vector3D(0., 0., halflengthZ()))); rSurfaces.push_back(Surface::makeShared<PlaneSurface>( std::shared_ptr<const Transform3D>(tTransform), xytBounds)); // face surfaces yz // transmute cyclical // (3) - at point A, attached to alpha opening angle - Vector3D A(minHalflengthX(), halflengthY(), trapezoidCenter.z()); - RotationMatrix3D alphaZRotation - = (s_idRotation * AngleAxis3D(alpha() - 0.5 * M_PI, Vector3D(0., 0., 1.))) - .toRotationMatrix(); + Vector3D A(minHalflengthX(), halflengthY(), trapezoidCenter.z()); + RotationMatrix3D alphaZRotation = + (s_idRotation * AngleAxis3D(alpha() - 0.5 * M_PI, Vector3D(0., 0., 1.))) + .toRotationMatrix(); RotationMatrix3D faceAlphaRotation; faceAlphaRotation.col(0) = alphaZRotation.col(1); faceAlphaRotation.col(1) = -alphaZRotation.col(2); @@ -119,20 +108,19 @@ Acts::TrapezoidVolumeBounds::decomposeToSurfaces( faceAlphaRectangleBounds()); // Vector3D // faceAlphaPosition(A+faceAlphaRotation.colX()*faceAlphaBounds->halflengthX()); - Vector3D faceAlphaPosition0( - -0.5 * (minHalflengthX() + maxHalflengthX()), 0., 0.); + Vector3D faceAlphaPosition0(-0.5 * (minHalflengthX() + maxHalflengthX()), 0., + 0.); Vector3D faceAlphaPosition = transform * faceAlphaPosition0; - tTransform = new Transform3D(Translation3D(faceAlphaPosition) - * (trapezoidRotation * faceAlphaRotation)); + tTransform = new Transform3D(Translation3D(faceAlphaPosition) * + (trapezoidRotation * faceAlphaRotation)); rSurfaces.push_back(Surface::makeShared<PlaneSurface>( std::shared_ptr<const Transform3D>(tTransform), faceAlphaBounds)); // (4) - at point B, attached to beta opening angle - Vector3D B(minHalflengthX(), -halflengthY(), trapezoidCenter.z()); - RotationMatrix3D betaZRotation - = (s_idRotation - * AngleAxis3D(-(beta() - 0.5 * M_PI), Vector3D(0., 0., 1.))) - .toRotationMatrix(); + Vector3D B(minHalflengthX(), -halflengthY(), trapezoidCenter.z()); + RotationMatrix3D betaZRotation = + (s_idRotation * AngleAxis3D(-(beta() - 0.5 * M_PI), Vector3D(0., 0., 1.))) + .toRotationMatrix(); RotationMatrix3D faceBetaRotation; faceBetaRotation.col(0) = betaZRotation.col(1); faceBetaRotation.col(1) = betaZRotation.col(2); @@ -140,29 +128,29 @@ Acts::TrapezoidVolumeBounds::decomposeToSurfaces( std::shared_ptr<const PlanarBounds> faceBetaBounds(faceBetaRectangleBounds()); // Vector3D // faceBetaPosition(B+faceBetaRotation.colX()*faceBetaBounds->halflengthX()); - Vector3D faceBetaPosition0( - 0.5 * (minHalflengthX() + maxHalflengthX()), 0., 0.); + Vector3D faceBetaPosition0(0.5 * (minHalflengthX() + maxHalflengthX()), 0., + 0.); Vector3D faceBetaPosition = transform * faceBetaPosition0; - tTransform = new Transform3D(Translation3D(faceBetaPosition) - * (trapezoidRotation * faceBetaRotation)); + tTransform = new Transform3D(Translation3D(faceBetaPosition) * + (trapezoidRotation * faceBetaRotation)); rSurfaces.push_back(Surface::makeShared<PlaneSurface>( std::shared_ptr<const Transform3D>(tTransform), faceBetaBounds)); // face surfaces zx // (5) - at negative local x - tTransform - = new Transform3D(transform * AngleAxis3D(M_PI, Vector3D(1., 0., 0.)) - * Translation3D(Vector3D(0., halflengthY(), 0.)) - * AngleAxis3D(-0.5 * M_PI, Vector3D(0., 1., 0.)) - * AngleAxis3D(-0.5 * M_PI, Vector3D(1., 0., 0.))); + tTransform = + new Transform3D(transform * AngleAxis3D(M_PI, Vector3D(1., 0., 0.)) * + Translation3D(Vector3D(0., halflengthY(), 0.)) * + AngleAxis3D(-0.5 * M_PI, Vector3D(0., 1., 0.)) * + AngleAxis3D(-0.5 * M_PI, Vector3D(1., 0., 0.))); rSurfaces.push_back(Surface::makeShared<PlaneSurface>( std::shared_ptr<const Transform3D>(tTransform), std::shared_ptr<const PlanarBounds>(faceZXRectangleBoundsBottom()))); // (6) - at positive local x - tTransform = new Transform3D( - transform * Translation3D(Vector3D(0., halflengthY(), 0.)) - * AngleAxis3D(-0.5 * M_PI, Vector3D(0., 1., 0.)) - * AngleAxis3D(-0.5 * M_PI, Vector3D(1., 0., 0.))); + tTransform = new Transform3D(transform * + Translation3D(Vector3D(0., halflengthY(), 0.)) * + AngleAxis3D(-0.5 * M_PI, Vector3D(0., 1., 0.)) * + AngleAxis3D(-0.5 * M_PI, Vector3D(1., 0., 0.))); rSurfaces.push_back(Surface::makeShared<PlaneSurface>( std::shared_ptr<const Transform3D>(tTransform), std::shared_ptr<const PlanarBounds>(faceZXRectangleBoundsTop()))); @@ -170,40 +158,35 @@ Acts::TrapezoidVolumeBounds::decomposeToSurfaces( return rSurfaces; } -Acts::TrapezoidBounds* -Acts::TrapezoidVolumeBounds::faceXYTrapezoidBounds() const -{ +Acts::TrapezoidBounds* Acts::TrapezoidVolumeBounds::faceXYTrapezoidBounds() + const { return new TrapezoidBounds(m_valueStore.at(bv_minHalfX), m_valueStore.at(bv_maxHalfX), m_valueStore.at(bv_halfY)); } -Acts::RectangleBounds* -Acts::TrapezoidVolumeBounds::faceAlphaRectangleBounds() const -{ - return new RectangleBounds(m_valueStore.at(bv_halfY) - / cos(m_valueStore.at(bv_alpha) - 0.5 * M_PI), - m_valueStore.at(bv_halfZ)); +Acts::RectangleBounds* Acts::TrapezoidVolumeBounds::faceAlphaRectangleBounds() + const { + return new RectangleBounds( + m_valueStore.at(bv_halfY) / cos(m_valueStore.at(bv_alpha) - 0.5 * M_PI), + m_valueStore.at(bv_halfZ)); } -Acts::RectangleBounds* -Acts::TrapezoidVolumeBounds::faceBetaRectangleBounds() const -{ - return new RectangleBounds(m_valueStore.at(bv_halfY) - / cos(m_valueStore.at(bv_beta) - 0.5 * M_PI), - m_valueStore.at(bv_halfZ)); +Acts::RectangleBounds* Acts::TrapezoidVolumeBounds::faceBetaRectangleBounds() + const { + return new RectangleBounds( + m_valueStore.at(bv_halfY) / cos(m_valueStore.at(bv_beta) - 0.5 * M_PI), + m_valueStore.at(bv_halfZ)); } Acts::RectangleBounds* -Acts::TrapezoidVolumeBounds::faceZXRectangleBoundsBottom() const -{ +Acts::TrapezoidVolumeBounds::faceZXRectangleBoundsBottom() const { return new RectangleBounds(m_valueStore.at(bv_halfZ), m_valueStore.at(bv_minHalfX)); } -Acts::RectangleBounds* -Acts::TrapezoidVolumeBounds::faceZXRectangleBoundsTop() const -{ +Acts::RectangleBounds* Acts::TrapezoidVolumeBounds::faceZXRectangleBoundsTop() + const { // double delta = (m_valueStore.at(bv_alpha) < m_valueStore.at(bv_beta)) ? // m_valueStore.at(bv_alpha) - M_PI/2. : m_valueStore.at(bv_beta) - M_PI/2.; // return new RectangleBounds(m_valueStore.at(bv_halfZ), @@ -212,9 +195,8 @@ Acts::TrapezoidVolumeBounds::faceZXRectangleBoundsTop() const m_valueStore.at(bv_maxHalfX)); } -bool -Acts::TrapezoidVolumeBounds::inside(const Vector3D& pos, double tol) const -{ +bool Acts::TrapezoidVolumeBounds::inside(const Vector3D& pos, + double tol) const { if (std::abs(pos.z()) > m_valueStore.at(bv_halfZ) + tol) { return false; } @@ -222,14 +204,12 @@ Acts::TrapezoidVolumeBounds::inside(const Vector3D& pos, double tol) const return false; } TrapezoidBounds* faceXYBounds = faceXYTrapezoidBounds(); - Vector2D locp(pos.x(), pos.y()); + Vector2D locp(pos.x(), pos.y()); bool inside(faceXYBounds->inside(locp, BoundaryCheck(true, true, tol, tol))); delete faceXYBounds; return inside; } -std::ostream& -Acts::TrapezoidVolumeBounds::toStream(std::ostream& sl) const -{ +std::ostream& Acts::TrapezoidVolumeBounds::toStream(std::ostream& sl) const { return dumpT<std::ostream>(sl); } diff --git a/Core/src/Geometry/Volume.cpp b/Core/src/Geometry/Volume.cpp index 46ac0b11fd1673789c13942fbac05e7cecf48b2b..d7b133db71928a58675ab58deb77101d197d2301 100644 --- a/Core/src/Geometry/Volume.cpp +++ b/Core/src/Geometry/Volume.cpp @@ -16,31 +16,27 @@ #include "Acts/Geometry/VolumeBounds.hpp" Acts::Volume::Volume() - : GeometryObject() - , m_transform(nullptr) - , m_center(s_origin) - , m_volumeBounds(nullptr) -{ -} + : GeometryObject(), + m_transform(nullptr), + m_center(s_origin), + m_volumeBounds(nullptr) {} Acts::Volume::Volume(const std::shared_ptr<const Transform3D>& htrans, - std::shared_ptr<const VolumeBounds> volbounds) - : GeometryObject() - , m_transform(htrans) - , m_center(s_origin) - , m_volumeBounds(std::move(volbounds)) -{ + std::shared_ptr<const VolumeBounds> volbounds) + : GeometryObject(), + m_transform(htrans), + m_center(s_origin), + m_volumeBounds(std::move(volbounds)) { if (htrans) { m_center = htrans->translation(); } } Acts::Volume::Volume(const Volume& vol, const Transform3D* shift) - : GeometryObject() - , m_transform(vol.m_transform) - , m_center(s_origin) - , m_volumeBounds(vol.m_volumeBounds) -{ + : GeometryObject(), + m_transform(vol.m_transform), + m_center(s_origin), + m_volumeBounds(vol.m_volumeBounds) { // applyt he shift if it exists if (shift != nullptr) { m_transform = std::make_shared<const Transform3D>(transform() * (*shift)); @@ -51,10 +47,8 @@ Acts::Volume::Volume(const Volume& vol, const Transform3D* shift) Acts::Volume::~Volume() = default; -const Acts::Vector3D -Acts::Volume::binningPosition(const GeometryContext& /*gctx*/, - Acts::BinningValue bValue) const -{ +const Acts::Vector3D Acts::Volume::binningPosition( + const GeometryContext& /*gctx*/, Acts::BinningValue bValue) const { // for most of the binning types it is actually the center, // just for R-binning types the if (bValue == Acts::binR || bValue == Acts::binRPhi) { @@ -66,26 +60,20 @@ Acts::Volume::binningPosition(const GeometryContext& /*gctx*/, } // assignment operator -Acts::Volume& -Acts::Volume::operator=(const Acts::Volume& vol) -{ +Acts::Volume& Acts::Volume::operator=(const Acts::Volume& vol) { if (this != &vol) { - m_transform = vol.m_transform; - m_center = vol.m_center; + m_transform = vol.m_transform; + m_center = vol.m_center; m_volumeBounds = vol.m_volumeBounds; } return *this; } -Acts::Volume* -Acts::Volume::clone() const -{ +Acts::Volume* Acts::Volume::clone() const { return new Acts::Volume(*this); } -bool -Acts::Volume::inside(const Acts::Vector3D& gpos, double tol) const -{ +bool Acts::Volume::inside(const Acts::Vector3D& gpos, double tol) const { if (!m_transform) { return (volumeBounds()).inside(gpos, tol); } @@ -93,9 +81,7 @@ Acts::Volume::inside(const Acts::Vector3D& gpos, double tol) const return (volumeBounds()).inside(posInVolFrame, tol); } -std::ostream& -Acts::operator<<(std::ostream& sl, const Acts::Volume& vol) -{ +std::ostream& Acts::operator<<(std::ostream& sl, const Acts::Volume& vol) { sl << "Voluem with " << vol.volumeBounds() << std::endl; return sl; } diff --git a/Core/src/Geometry/VolumeBounds.cpp b/Core/src/Geometry/VolumeBounds.cpp index 00c613d5f8569da0ce19912bf09544bdbf56d284..6800e8e0697b8f76f700a8674dda13c8a95f428d 100644 --- a/Core/src/Geometry/VolumeBounds.cpp +++ b/Core/src/Geometry/VolumeBounds.cpp @@ -13,8 +13,6 @@ #include "Acts/Geometry/VolumeBounds.hpp" /**Overload of << operator for std::ostream for debug output*/ -std::ostream& -Acts::operator<<(std::ostream& sl, const Acts::VolumeBounds& vb) -{ +std::ostream& Acts::operator<<(std::ostream& sl, const Acts::VolumeBounds& vb) { return vb.toStream(sl); } diff --git a/Core/src/MagneticField/BFieldMapUtils.cpp b/Core/src/MagneticField/BFieldMapUtils.cpp index fff0a7ef30e85cac6602ed515801a839bc8e9220..9bfd27ba02ead60c9deebc9d10f6999a3a8b0219 100644 --- a/Core/src/MagneticField/BFieldMapUtils.cpp +++ b/Core/src/MagneticField/BFieldMapUtils.cpp @@ -16,21 +16,15 @@ using Acts::VectorHelpers::perp; using Acts::VectorHelpers::phi; -Acts:: - InterpolatedBFieldMapper<Acts::detail::Grid<Acts::Vector2D, - Acts::detail::EquidistantAxis, - Acts::detail::EquidistantAxis>> - Acts::fieldMapperRZ( - const std::function<size_t(std::array<size_t, 2> binsRZ, - std::array<size_t, 2> nBinsRZ)>& - localToGlobalBin, - std::vector<double> rPos, - std::vector<double> zPos, - std::vector<Acts::Vector2D> bField, - double lengthUnit, - double BFieldUnit, - bool firstQuadrant) -{ +Acts::InterpolatedBFieldMapper< + Acts::detail::Grid<Acts::Vector2D, Acts::detail::EquidistantAxis, + Acts::detail::EquidistantAxis>> +Acts::fieldMapperRZ(const std::function<size_t(std::array<size_t, 2> binsRZ, + std::array<size_t, 2> nBinsRZ)>& + localToGlobalBin, + std::vector<double> rPos, std::vector<double> zPos, + std::vector<Acts::Vector2D> bField, double lengthUnit, + double BFieldUnit, bool firstQuadrant) { // [1] Create Grid // sort the values std::sort(rPos.begin(), rPos.end()); @@ -45,12 +39,12 @@ Acts:: size_t nBinsZ = zPos.size(); // get the minimum and maximum - auto minMaxR = std::minmax_element(rPos.begin(), rPos.end()); - auto minMaxZ = std::minmax_element(zPos.begin(), zPos.end()); - double rMin = *minMaxR.first; - double zMin = *minMaxZ.first; - double rMax = *minMaxR.second; - double zMax = *minMaxZ.second; + auto minMaxR = std::minmax_element(rPos.begin(), rPos.end()); + auto minMaxZ = std::minmax_element(zPos.begin(), zPos.end()); + double rMin = *minMaxR.first; + double zMin = *minMaxZ.first; + double rMax = *minMaxR.second; + double zMax = *minMaxZ.second; // calculate maxima (add one last bin, because bin value always corresponds to // left boundary) double stepZ = std::fabs(zMax - zMin) / (nBinsZ - 1); @@ -58,20 +52,20 @@ Acts:: rMax += stepR; zMax += stepZ; if (firstQuadrant) { - zMin = -(*minMaxZ.second); + zMin = -(*minMaxZ.second); nBinsZ = 2. * nBinsZ - 1; } // Create the axis for the grid - Acts::detail::EquidistantAxis rAxis( - rMin * lengthUnit, rMax * lengthUnit, nBinsR); - Acts::detail::EquidistantAxis zAxis( - zMin * lengthUnit, zMax * lengthUnit, nBinsZ); + Acts::detail::EquidistantAxis rAxis(rMin * lengthUnit, rMax * lengthUnit, + nBinsR); + Acts::detail::EquidistantAxis zAxis(zMin * lengthUnit, zMax * lengthUnit, + nBinsZ); // Create the grid - using Grid_t = Acts::detail::Grid<Acts::Vector2D, - Acts::detail::EquidistantAxis, - Acts::detail::EquidistantAxis>; + using Grid_t = + Acts::detail::Grid<Acts::Vector2D, Acts::detail::EquidistantAxis, + Acts::detail::EquidistantAxis>; Grid_t grid(std::make_tuple(std::move(rAxis), std::move(zAxis))); // [2] Set the bField values @@ -83,19 +77,19 @@ Acts:: // std::vectors begin with 0 and we do not want the user needing to // take underflow or overflow bins in account this is why we need to // subtract by one - size_t n = std::abs(int(j) - int(zPos.size())); + size_t n = std::abs(int(j) - int(zPos.size())); Grid_t::index_t indicesFirstQuadrant = {{i - 1, n}}; - grid.atLocalBins(indices) - = bField.at(localToGlobalBin(indicesFirstQuadrant, nIndices)) - * BFieldUnit; + grid.atLocalBins(indices) = + bField.at(localToGlobalBin(indicesFirstQuadrant, nIndices)) * + BFieldUnit; } else { // std::vectors begin with 0 and we do not want the user needing to // take underflow or overflow bins in account this is why we need to // subtract by one - grid.atLocalBins(indices) - = bField.at(localToGlobalBin({{i - 1, j - 1}}, nIndices)) - * BFieldUnit; + grid.atLocalBins(indices) = + bField.at(localToGlobalBin({{i - 1, j - 1}}, nIndices)) * + BFieldUnit; } } } @@ -115,8 +109,8 @@ Acts:: double cos_phi, sin_phi; if (r_sin_theta_2 > std::numeric_limits<double>::min()) { double inv_r_sin_theta = 1. / sqrt(r_sin_theta_2); - cos_phi = pos.x() * inv_r_sin_theta; - sin_phi = pos.y() * inv_r_sin_theta; + cos_phi = pos.x() * inv_r_sin_theta; + sin_phi = pos.y() * inv_r_sin_theta; } else { cos_phi = 1.; sin_phi = 0.; @@ -126,27 +120,20 @@ Acts:: // [5] Create the mapper & BField Service // create field mapping - return Acts::InterpolatedBFieldMapper<Grid_t>( - transformPos, transformBField, std::move(grid)); + return Acts::InterpolatedBFieldMapper<Grid_t>(transformPos, transformBField, + std::move(grid)); } -Acts:: - InterpolatedBFieldMapper<Acts::detail::Grid<Acts::Vector3D, - Acts::detail::EquidistantAxis, - Acts::detail::EquidistantAxis, - Acts::detail::EquidistantAxis>> - Acts::fieldMapperXYZ( - const std::function<size_t(std::array<size_t, 3> binsXYZ, - std::array<size_t, 3> nBinsXYZ)>& - localToGlobalBin, - std::vector<double> xPos, - std::vector<double> yPos, - std::vector<double> zPos, - std::vector<Acts::Vector3D> bField, - double lengthUnit, - double BFieldUnit, - bool firstOctant) -{ +Acts::InterpolatedBFieldMapper<Acts::detail::Grid< + Acts::Vector3D, Acts::detail::EquidistantAxis, + Acts::detail::EquidistantAxis, Acts::detail::EquidistantAxis>> +Acts::fieldMapperXYZ( + const std::function<size_t(std::array<size_t, 3> binsXYZ, + std::array<size_t, 3> nBinsXYZ)>& + localToGlobalBin, + std::vector<double> xPos, std::vector<double> yPos, + std::vector<double> zPos, std::vector<Acts::Vector3D> bField, + double lengthUnit, double BFieldUnit, bool firstOctant) { // [1] Create Grid // Sort the values std::sort(xPos.begin(), xPos.end()); @@ -188,24 +175,24 @@ Acts:: // If only the first octant is given if (firstOctant) { - xMin = -*minMaxX.second; - yMin = -*minMaxY.second; - zMin = -*minMaxZ.second; + xMin = -*minMaxX.second; + yMin = -*minMaxY.second; + zMin = -*minMaxZ.second; nBinsX = 2 * nBinsX - 1; nBinsY = 2 * nBinsY - 1; nBinsZ = 2 * nBinsZ - 1; } - Acts::detail::EquidistantAxis xAxis( - xMin * lengthUnit, xMax * lengthUnit, nBinsX); - Acts::detail::EquidistantAxis yAxis( - yMin * lengthUnit, yMax * lengthUnit, nBinsY); - Acts::detail::EquidistantAxis zAxis( - zMin * lengthUnit, zMax * lengthUnit, nBinsZ); + Acts::detail::EquidistantAxis xAxis(xMin * lengthUnit, xMax * lengthUnit, + nBinsX); + Acts::detail::EquidistantAxis yAxis(yMin * lengthUnit, yMax * lengthUnit, + nBinsY); + Acts::detail::EquidistantAxis zAxis(zMin * lengthUnit, zMax * lengthUnit, + nBinsZ); // Create the grid - using Grid_t = Acts::detail::Grid<Acts::Vector3D, - Acts::detail::EquidistantAxis, - Acts::detail::EquidistantAxis, - Acts::detail::EquidistantAxis>; + using Grid_t = + Acts::detail::Grid<Acts::Vector3D, Acts::detail::EquidistantAxis, + Acts::detail::EquidistantAxis, + Acts::detail::EquidistantAxis>; Grid_t grid( std::make_tuple(std::move(xAxis), std::move(yAxis), std::move(zAxis))); @@ -214,28 +201,28 @@ Acts:: for (size_t j = 1; j <= nBinsY; ++j) { for (size_t k = 1; k <= nBinsZ; ++k) { Grid_t::index_t indices = {{i, j, k}}; - std::array<size_t, 3> nIndices - = {{xPos.size(), yPos.size(), zPos.size()}}; + std::array<size_t, 3> nIndices = { + {xPos.size(), yPos.size(), zPos.size()}}; if (firstOctant) { // std::vectors begin with 0 and we do not want the user needing to // take underflow or overflow bins in account this is why we need to // subtract by one - size_t m = std::abs(int(i) - (int(xPos.size()))); - size_t n = std::abs(int(j) - (int(yPos.size()))); - size_t l = std::abs(int(k) - (int(zPos.size()))); + size_t m = std::abs(int(i) - (int(xPos.size()))); + size_t n = std::abs(int(j) - (int(yPos.size()))); + size_t l = std::abs(int(k) - (int(zPos.size()))); Grid_t::index_t indicesFirstOctant = {{m, n, l}}; - grid.atLocalBins(indices) - = bField.at(localToGlobalBin(indicesFirstOctant, nIndices)) - * BFieldUnit; + grid.atLocalBins(indices) = + bField.at(localToGlobalBin(indicesFirstOctant, nIndices)) * + BFieldUnit; } else { // std::vectors begin with 0 and we do not want the user needing to // take underflow or overflow bins in account this is why we need to // subtract by one - grid.atLocalBins(indices) - = bField.at(localToGlobalBin({{i - 1, j - 1, k - 1}}, nIndices)) - * BFieldUnit; + grid.atLocalBins(indices) = + bField.at(localToGlobalBin({{i - 1, j - 1, k - 1}}, nIndices)) * + BFieldUnit; } } } @@ -253,19 +240,17 @@ Acts:: // [5] Create the mapper & BField Service // create field mapping - return Acts::InterpolatedBFieldMapper<Grid_t>( - transformPos, transformBField, std::move(grid)); + return Acts::InterpolatedBFieldMapper<Grid_t>(transformPos, transformBField, + std::move(grid)); } -Acts:: - InterpolatedBFieldMapper<Acts::detail::Grid<Acts::Vector2D, - Acts::detail::EquidistantAxis, - Acts::detail::EquidistantAxis>> - Acts::solenoidFieldMapper(std::pair<double, double> rlim, - std::pair<double, double> zlim, - std::pair<size_t, size_t> nbins, - const SolenoidBField& field) -{ +Acts::InterpolatedBFieldMapper< + Acts::detail::Grid<Acts::Vector2D, Acts::detail::EquidistantAxis, + Acts::detail::EquidistantAxis>> +Acts::solenoidFieldMapper(std::pair<double, double> rlim, + std::pair<double, double> zlim, + std::pair<size_t, size_t> nbins, + const SolenoidBField& field) { double rMin, rMax, zMin, zMax; std::tie(rMin, rMax) = rlim; std::tie(zMin, zMax) = zlim; @@ -284,9 +269,9 @@ Acts:: Acts::detail::EquidistantAxis zAxis(zMin, zMax, nBinsZ); // Create the grid - using Grid_t = Acts::detail::Grid<Acts::Vector2D, - Acts::detail::EquidistantAxis, - Acts::detail::EquidistantAxis>; + using Grid_t = + Acts::detail::Grid<Acts::Vector2D, Acts::detail::EquidistantAxis, + Acts::detail::EquidistantAxis>; Grid_t grid(std::make_tuple(std::move(rAxis), std::move(zAxis))); // Create the transformation for the position @@ -297,21 +282,21 @@ Acts:: // Create the transformation for the bfield // map (Br,Bz) -> (Bx,By,Bz) - auto transformBField - = [](const Acts::Vector2D& bfield, const Acts::Vector3D& pos) { - double r_sin_theta_2 = pos.x() * pos.x() + pos.y() * pos.y(); - double cos_phi, sin_phi; - if (r_sin_theta_2 > std::numeric_limits<double>::min()) { - double inv_r_sin_theta = 1. / sqrt(r_sin_theta_2); - cos_phi = pos.x() * inv_r_sin_theta; - sin_phi = pos.y() * inv_r_sin_theta; - } else { - cos_phi = 1.; - sin_phi = 0.; - } - return Acts::Vector3D( - bfield.x() * cos_phi, bfield.x() * sin_phi, bfield.y()); - }; + auto transformBField = [](const Acts::Vector2D& bfield, + const Acts::Vector3D& pos) { + double r_sin_theta_2 = pos.x() * pos.x() + pos.y() * pos.y(); + double cos_phi, sin_phi; + if (r_sin_theta_2 > std::numeric_limits<double>::min()) { + double inv_r_sin_theta = 1. / sqrt(r_sin_theta_2); + cos_phi = pos.x() * inv_r_sin_theta; + sin_phi = pos.y() * inv_r_sin_theta; + } else { + cos_phi = 1.; + sin_phi = 0.; + } + return Acts::Vector3D(bfield.x() * cos_phi, bfield.x() * sin_phi, + bfield.y()); + }; // iterate over all bins, set their value to the solenoid value // at their lower left position @@ -333,7 +318,7 @@ Acts:: // Create the mapper & BField Service // create field mapping - Acts::InterpolatedBFieldMapper<Grid_t> mapper( - transformPos, transformBField, std::move(grid)); + Acts::InterpolatedBFieldMapper<Grid_t> mapper(transformPos, transformBField, + std::move(grid)); return mapper; } diff --git a/Core/src/MagneticField/SolenoidBField.cpp b/Core/src/MagneticField/SolenoidBField.cpp index 786e46ca3e1a8560ffc435f8a1ab05ec3508020d..f85cadfb9916c4ca775c6bb0bb5004d602dcda9a 100644 --- a/Core/src/MagneticField/SolenoidBField.cpp +++ b/Core/src/MagneticField/SolenoidBField.cpp @@ -12,19 +12,16 @@ #include <boost/math/special_functions/ellint_1.hpp> #include <boost/math/special_functions/ellint_2.hpp> -Acts::SolenoidBField::SolenoidBField(Config config) : m_cfg(std::move(config)) -{ +Acts::SolenoidBField::SolenoidBField(Config config) : m_cfg(std::move(config)) { m_dz = m_cfg.length / m_cfg.nCoils; m_R2 = m_cfg.radius * m_cfg.radius; // we need to scale so we reproduce the expected B field strength // at the center of the solenoid Vector2D field = multiCoilField({0, 0}, 1.); // scale = 1 - m_scale = m_cfg.bMagCenter / field.norm(); + m_scale = m_cfg.bMagCenter / field.norm(); } -Acts::Vector3D -Acts::SolenoidBField::getField(const Vector3D& position) const -{ +Acts::Vector3D Acts::SolenoidBField::getField(const Vector3D& position) const { using VectorHelpers::perp; Vector2D rzPos(perp(position), position.z()); Vector2D rzField = multiCoilField(rzPos, m_scale); @@ -39,57 +36,45 @@ Acts::SolenoidBField::getField(const Vector3D& position) const return xyzField; } -Acts::Vector3D -Acts::SolenoidBField::getField(const Vector3D& position, Cache& /*cache*/) const -{ +Acts::Vector3D Acts::SolenoidBField::getField(const Vector3D& position, + Cache& /*cache*/) const { return getField(position); } -Acts::Vector2D -Acts::SolenoidBField::getField(const Vector2D& position) const -{ +Acts::Vector2D Acts::SolenoidBField::getField(const Vector2D& position) const { return multiCoilField(position, m_scale); } -Acts::Vector3D -Acts::SolenoidBField::getFieldGradient(const Vector3D& position, - ActsMatrixD<3, 3>& /*derivative*/) const -{ +Acts::Vector3D Acts::SolenoidBField::getFieldGradient( + const Vector3D& position, ActsMatrixD<3, 3>& /*derivative*/) const { return getField(position); } -Acts::Vector3D -Acts::SolenoidBField::getFieldGradient(const Vector3D& position, - ActsMatrixD<3, 3>& /*derivative*/, - Cache& /*cache*/) const -{ +Acts::Vector3D Acts::SolenoidBField::getFieldGradient( + const Vector3D& position, ActsMatrixD<3, 3>& /*derivative*/, + Cache& /*cache*/) const { return getField(position); } -Acts::Vector2D -Acts::SolenoidBField::multiCoilField(const Vector2D& pos, double scale) const -{ +Acts::Vector2D Acts::SolenoidBField::multiCoilField(const Vector2D& pos, + double scale) const { // iterate over all coils Vector2D resultField(0, 0); for (size_t coil = 0; coil < m_cfg.nCoils; coil++) { - Vector2D shiftedPos - = Vector2D(pos[0], pos[1] + m_cfg.length * 0.5 - m_dz * (coil + 0.5)); + Vector2D shiftedPos = + Vector2D(pos[0], pos[1] + m_cfg.length * 0.5 - m_dz * (coil + 0.5)); resultField += singleCoilField(shiftedPos, scale); } return resultField; } -Acts::Vector2D -Acts::SolenoidBField::singleCoilField(const Vector2D& pos, double scale) const -{ +Acts::Vector2D Acts::SolenoidBField::singleCoilField(const Vector2D& pos, + double scale) const { return {B_r(pos, scale), B_z(pos, scale)}; } -double -Acts::SolenoidBField::B_r(const Vector2D& pos, double scale) const -{ - +double Acts::SolenoidBField::B_r(const Vector2D& pos, double scale) const { // _ // 2 / pi / 2 2 2 - 1 / 2 // E (k ) = | ( 1 - k sin {theta} ) dtheta @@ -116,9 +101,9 @@ Acts::SolenoidBField::B_r(const Vector2D& pos, double scale) const // | / 3 |_ \2 - 2k / _| // |/ Rr double k_2 = k2(r, z); - double k = std::sqrt(k_2); - double constant - = scale * k * z / (4 * M_PI * std::sqrt(m_cfg.radius * r * r * r)); + double k = std::sqrt(k_2); + double constant = + scale * k * z / (4 * M_PI * std::sqrt(m_cfg.radius * r * r * r)); double B = (2. - k_2) / (2. - 2. * k_2) * ellint_2(k_2) - ellint_1(k_2); @@ -126,9 +111,7 @@ Acts::SolenoidBField::B_r(const Vector2D& pos, double scale) const return r / pos[0] * constant * B; } -double -Acts::SolenoidBField::B_z(const Vector2D& pos, double scale) const -{ +double Acts::SolenoidBField::B_z(const Vector2D& pos, double scale) const { // _ // 2 / pi / 2 2 2 - 1 / 2 // E (k ) = | ( 1 - k sin {theta} ) dtheta @@ -155,23 +138,21 @@ Acts::SolenoidBField::B_z(const Vector2D& pos, double scale) const return res; } - double k_2 = k2(r, z); - double k = std::sqrt(k_2); + double k_2 = k2(r, z); + double k = std::sqrt(k_2); double constant = scale * k / (4 * M_PI * std::sqrt(m_cfg.radius * r)); - double B = ((m_cfg.radius + r) * k_2 - 2. * r) / (2. * r * (1. - k_2)) - * ellint_2(k_2) - + ellint_1(k_2); + double B = ((m_cfg.radius + r) * k_2 - 2. * r) / (2. * r * (1. - k_2)) * + ellint_2(k_2) + + ellint_1(k_2); return constant * B; } -double -Acts::SolenoidBField::k2(double r, double z) const -{ +double Acts::SolenoidBField::k2(double r, double z) const { // 2 4Rr // k = --------------- // 2 2 // (R + r) + z - return 4 * m_cfg.radius * r - / ((m_cfg.radius + r) * (m_cfg.radius + r) + z * z); + return 4 * m_cfg.radius * r / + ((m_cfg.radius + r) * (m_cfg.radius + r) + z * z); } diff --git a/Core/src/Material/AccumulatedSurfaceMaterial.cpp b/Core/src/Material/AccumulatedSurfaceMaterial.cpp index 099a749f6ae6418ef2bc7ff3fc09a4e69cbd3f6a..262903f361e1e1fe58c3c68e6f20cb2830945823 100644 --- a/Core/src/Material/AccumulatedSurfaceMaterial.cpp +++ b/Core/src/Material/AccumulatedSurfaceMaterial.cpp @@ -16,30 +16,24 @@ // Default Constructor - for homogeneous material Acts::AccumulatedSurfaceMaterial::AccumulatedSurfaceMaterial(double splitFactor) - : m_splitFactor(splitFactor) -{ + : m_splitFactor(splitFactor) { AccumulatedVector accMat = {{AccumulatedMaterialProperties()}}; - m_accumulatedMaterial = {{accMat}}; + m_accumulatedMaterial = {{accMat}}; } // Binned Material constructor with split factor Acts::AccumulatedSurfaceMaterial::AccumulatedSurfaceMaterial( - const BinUtility& binUtility, - double splitFactor) - : m_binUtility(binUtility), m_splitFactor(splitFactor) -{ - size_t bins0 = m_binUtility.bins(0); - size_t bins1 = m_binUtility.bins(1); + const BinUtility& binUtility, double splitFactor) + : m_binUtility(binUtility), m_splitFactor(splitFactor) { + size_t bins0 = m_binUtility.bins(0); + size_t bins1 = m_binUtility.bins(1); AccumulatedVector accVec(bins0, AccumulatedMaterialProperties()); m_accumulatedMaterial = AccumulatedMatrix(bins1, accVec); } // Assign a material properites object -std::array<size_t, 3> -Acts::AccumulatedSurfaceMaterial::accumulate(const Vector2D& lp, - const MaterialProperties& mp, - double pathCorrection) -{ +std::array<size_t, 3> Acts::AccumulatedSurfaceMaterial::accumulate( + const Vector2D& lp, const MaterialProperties& mp, double pathCorrection) { if (m_binUtility.dimensions() == 0) { m_accumulatedMaterial[0][0].accumulate(mp, pathCorrection); return {0, 0, 0}; @@ -51,11 +45,8 @@ Acts::AccumulatedSurfaceMaterial::accumulate(const Vector2D& lp, } // Assign a material properites object -std::array<size_t, 3> -Acts::AccumulatedSurfaceMaterial::accumulate(const Vector3D& gp, - const MaterialProperties& mp, - double pathCorrection) -{ +std::array<size_t, 3> Acts::AccumulatedSurfaceMaterial::accumulate( + const Vector3D& gp, const MaterialProperties& mp, double pathCorrection) { if (m_binUtility.dimensions() == 0) { m_accumulatedMaterial[0][0].accumulate(mp, pathCorrection); return {0, 0, 0}; @@ -66,11 +57,8 @@ Acts::AccumulatedSurfaceMaterial::accumulate(const Vector3D& gp, } // Average the information accumulated during one event -void -Acts::AccumulatedSurfaceMaterial::trackAverage( - const std::vector<std::array<size_t, 3>>& trackBins) -{ - +void Acts::AccumulatedSurfaceMaterial::trackAverage( + const std::vector<std::array<size_t, 3>>& trackBins) { // The touched bins are known, so you can access them directly if (not trackBins.empty()) { for (auto bin : trackBins) { @@ -88,8 +76,7 @@ Acts::AccumulatedSurfaceMaterial::trackAverage( /// Total average creates SurfaceMaterial std::unique_ptr<const Acts::ISurfaceMaterial> -Acts::AccumulatedSurfaceMaterial::totalAverage() -{ +Acts::AccumulatedSurfaceMaterial::totalAverage() { if (m_binUtility.bins() == 1) { // Return HomogeneousSurfaceMaterial return std::make_unique<HomogeneousSurfaceMaterial>( diff --git a/Core/src/Material/AccumulatedVolumeMaterial.cpp b/Core/src/Material/AccumulatedVolumeMaterial.cpp index 5710313219a2e13cd0847fa5538f77afc2c1c785..88108ac123353efaf3c65d7acb897e0843a3f773 100644 --- a/Core/src/Material/AccumulatedVolumeMaterial.cpp +++ b/Core/src/Material/AccumulatedVolumeMaterial.cpp @@ -12,9 +12,7 @@ #include "Acts/Material/AccumulatedVolumeMaterial.hpp" -void -Acts::AccumulatedVolumeMaterial::accumulate(const Material& mat) -{ +void Acts::AccumulatedVolumeMaterial::accumulate(const Material& mat) { // If nothing is set it is vacuum if (mat.A() == 0. || mat.Z() == 0. || mat.rho() == 0.) { m_vacuumEntries++; @@ -37,23 +35,19 @@ Acts::AccumulatedVolumeMaterial::accumulate(const Material& mat) } } -Acts::Material -Acts::AccumulatedVolumeMaterial::average() -{ +Acts::Material Acts::AccumulatedVolumeMaterial::average() { if (m_materialEntries > 0) { /// The following rescaling is a combination of two steps. /// 1) All material entries are averaged. /// 2) The numbers are rescaled by a material-to-totalEntries factor. This /// rescaling is performed by dividing A, Z and rho by this factor and /// multiplying X0 and L0 by it. - float scalor = m_materialEntries * m_materialEntries; + float scalor = m_materialEntries * m_materialEntries; float totalEntries = (float)(m_vacuumEntries + m_materialEntries); // Create the material return Material(m_totalX0 * totalEntries / scalor, - m_totalL0 * totalEntries / scalor, - m_totalA / totalEntries, - m_totalZ / totalEntries, - m_totalRho / totalEntries); + m_totalL0 * totalEntries / scalor, m_totalA / totalEntries, + m_totalZ / totalEntries, m_totalRho / totalEntries); } // Create vacuum return Material(); diff --git a/Core/src/Material/BinnedSurfaceMaterial.cpp b/Core/src/Material/BinnedSurfaceMaterial.cpp index 39f778fb7289263e493f68f2a7d927b310ebeb70..b65bc9b95918e9f0ce2eb352fb79f5068b48d04e 100644 --- a/Core/src/Material/BinnedSurfaceMaterial.cpp +++ b/Core/src/Material/BinnedSurfaceMaterial.cpp @@ -14,28 +14,22 @@ #include "Acts/Material/MaterialProperties.hpp" Acts::BinnedSurfaceMaterial::BinnedSurfaceMaterial( - const BinUtility& binUtility, - MaterialPropertiesVector fullProperties, - double splitFactor) - : ISurfaceMaterial(splitFactor), m_binUtility(binUtility) -{ + const BinUtility& binUtility, MaterialPropertiesVector fullProperties, + double splitFactor) + : ISurfaceMaterial(splitFactor), m_binUtility(binUtility) { // fill the material with deep copy m_fullMaterial.push_back(std::move(fullProperties)); } Acts::BinnedSurfaceMaterial::BinnedSurfaceMaterial( - const BinUtility& binUtility, - MaterialPropertiesMatrix fullProperties, - double splitFactor) - : ISurfaceMaterial(splitFactor) - , m_binUtility(binUtility) - , m_fullMaterial(std::move(fullProperties)) -{ -} + const BinUtility& binUtility, MaterialPropertiesMatrix fullProperties, + double splitFactor) + : ISurfaceMaterial(splitFactor), + m_binUtility(binUtility), + m_fullMaterial(std::move(fullProperties)) {} -Acts::BinnedSurfaceMaterial& -Acts::BinnedSurfaceMaterial::operator*=(double scale) -{ +Acts::BinnedSurfaceMaterial& Acts::BinnedSurfaceMaterial::operator*=( + double scale) { for (auto& materialVector : m_fullMaterial) { for (auto& materialBin : materialVector) { (materialBin) *= scale; @@ -44,27 +38,23 @@ Acts::BinnedSurfaceMaterial::operator*=(double scale) return (*this); } -const Acts::MaterialProperties& -Acts::BinnedSurfaceMaterial::materialProperties(const Vector2D& lp) const -{ +const Acts::MaterialProperties& Acts::BinnedSurfaceMaterial::materialProperties( + const Vector2D& lp) const { // the first bin size_t ibin0 = m_binUtility.bin(lp, 0); size_t ibin1 = m_binUtility.max(1) != 0u ? m_binUtility.bin(lp, 1) : 0; return m_fullMaterial[ibin1][ibin0]; } -const Acts::MaterialProperties& -Acts::BinnedSurfaceMaterial::materialProperties(const Acts::Vector3D& gp) const -{ +const Acts::MaterialProperties& Acts::BinnedSurfaceMaterial::materialProperties( + const Acts::Vector3D& gp) const { // the first bin size_t ibin0 = m_binUtility.bin(gp, 0); size_t ibin1 = m_binUtility.max(1) != 0u ? m_binUtility.bin(gp, 1) : 0; return m_fullMaterial[ibin1][ibin0]; } -std::ostream& -Acts::BinnedSurfaceMaterial::toStream(std::ostream& sl) const -{ +std::ostream& Acts::BinnedSurfaceMaterial::toStream(std::ostream& sl) const { sl << "Acts::BinnedSurfaceMaterial : " << std::endl; sl << " - Number of Material bins [0,1] : " << m_binUtility.max(0) + 1 << " / " << m_binUtility.max(1) + 1 << std::endl; diff --git a/Core/src/Material/HomogeneousSurfaceMaterial.cpp b/Core/src/Material/HomogeneousSurfaceMaterial.cpp index 4892435bc34c0a5b3bf45ef59639e1ffdcffa2db..b89b6a37fd8f166834115d341c56a44d0d9b27cb 100644 --- a/Core/src/Material/HomogeneousSurfaceMaterial.cpp +++ b/Core/src/Material/HomogeneousSurfaceMaterial.cpp @@ -14,23 +14,18 @@ #include "Acts/Material/MaterialProperties.hpp" Acts::HomogeneousSurfaceMaterial::HomogeneousSurfaceMaterial( - const MaterialProperties& full, - double splitFactor) - : ISurfaceMaterial(splitFactor), m_fullMaterial(full) -{ -} + const MaterialProperties& full, double splitFactor) + : ISurfaceMaterial(splitFactor), m_fullMaterial(full) {} -Acts::HomogeneousSurfaceMaterial& -Acts::HomogeneousSurfaceMaterial::operator*=(double scale) -{ +Acts::HomogeneousSurfaceMaterial& Acts::HomogeneousSurfaceMaterial::operator*=( + double scale) { // scale the sub properties m_fullMaterial *= scale; return (*this); } -std::ostream& -Acts::HomogeneousSurfaceMaterial::toStream(std::ostream& sl) const -{ +std::ostream& Acts::HomogeneousSurfaceMaterial::toStream( + std::ostream& sl) const { sl << "Acts::HomogeneousSurfaceMaterial : " << std::endl; sl << " - fullMaterial : " << m_fullMaterial << std::endl; sl << " - split factor : " << m_splitFactor << std::endl; diff --git a/Core/src/Material/MaterialMapUtils.cpp b/Core/src/Material/MaterialMapUtils.cpp index 305aa19307017ad81aec59027a7c3d6a48f9405d..7d777e54ce366d88b2e6248a1eb7ad2c4d524caf 100644 --- a/Core/src/Material/MaterialMapUtils.cpp +++ b/Core/src/Material/MaterialMapUtils.cpp @@ -16,18 +16,14 @@ using Acts::VectorHelpers::perp; using Acts::VectorHelpers::phi; -auto -Acts::materialMapperRZ( +auto Acts::materialMapperRZ( const std::function<size_t(std::array<size_t, 2> binsRZ, std::array<size_t, 2> nBinsRZ)>& - materialVectorToGridMapper, - std::vector<double> rPos, - std::vector<double> zPos, - std::vector<Acts::Material> material, - double lengthUnit) -> MaterialMapper<detail::Grid<ActsVectorF<5>, - detail::EquidistantAxis, - detail::EquidistantAxis>> -{ + materialVectorToGridMapper, + std::vector<double> rPos, std::vector<double> zPos, + std::vector<Acts::Material> material, double lengthUnit) + -> MaterialMapper<detail::Grid<ActsVectorF<5>, detail::EquidistantAxis, + detail::EquidistantAxis>> { // [1] Decompose material std::vector<ActsVectorF<5>> materialVector; materialVector.reserve(material.size()); @@ -50,12 +46,12 @@ Acts::materialMapperRZ( size_t nBinsZ = zPos.size(); // get the minimum and maximum - auto minMaxR = std::minmax_element(rPos.begin(), rPos.end()); - auto minMaxZ = std::minmax_element(zPos.begin(), zPos.end()); - double rMin = *minMaxR.first; - double zMin = *minMaxZ.first; - double rMax = *minMaxR.second; - double zMax = *minMaxZ.second; + auto minMaxR = std::minmax_element(rPos.begin(), rPos.end()); + auto minMaxZ = std::minmax_element(zPos.begin(), zPos.end()); + double rMin = *minMaxR.first; + double zMin = *minMaxZ.first; + double rMax = *minMaxR.second; + double zMax = *minMaxZ.second; // calculate maxima (add one last bin, because bin value always corresponds to // left boundary) double stepZ = std::fabs(zMax - zMin) / (nBinsZ - 1); @@ -68,8 +64,8 @@ Acts::materialMapperRZ( detail::EquidistantAxis zAxis(zMin * lengthUnit, zMax * lengthUnit, nBinsZ); // Create the grid - using Grid_t = detail:: - Grid<ActsVectorF<5>, detail::EquidistantAxis, detail::EquidistantAxis>; + using Grid_t = detail::Grid<ActsVectorF<5>, detail::EquidistantAxis, + detail::EquidistantAxis>; Grid_t grid(std::make_tuple(std::move(rAxis), std::move(zAxis))); // [3] Set the material values @@ -91,31 +87,26 @@ Acts::materialMapperRZ( // [4] Create the transformation for the position // map (x,y,z) -> (r,z) - auto transformPos - = [](const Vector3D& pos) { return Vector2D(perp(pos), pos.z()); }; + auto transformPos = [](const Vector3D& pos) { + return Vector2D(perp(pos), pos.z()); + }; // [5] Create the mapper & BField Service // create material mapping - return MaterialMapper<detail::Grid<ActsVectorF<5>, - detail::EquidistantAxis, + return MaterialMapper<detail::Grid<ActsVectorF<5>, detail::EquidistantAxis, detail::EquidistantAxis>>(transformPos, std::move(grid)); } -auto -Acts::materialMapperXYZ( +auto Acts::materialMapperXYZ( const std::function<size_t(std::array<size_t, 3> binsXYZ, std::array<size_t, 3> nBinsXYZ)>& - materialVectorToGridMapper, - std::vector<double> xPos, - std::vector<double> yPos, - std::vector<double> zPos, - std::vector<Material> material, - double lengthUnit) -> MaterialMapper<detail::Grid<ActsVectorF<5>, - detail::EquidistantAxis, - detail::EquidistantAxis, - detail::EquidistantAxis>> -{ + materialVectorToGridMapper, + std::vector<double> xPos, std::vector<double> yPos, + std::vector<double> zPos, std::vector<Material> material, double lengthUnit) + -> MaterialMapper< + detail::Grid<ActsVectorF<5>, detail::EquidistantAxis, + detail::EquidistantAxis, detail::EquidistantAxis>> { // [1] Decompose material std::vector<ActsVectorF<5>> materialVector; materialVector.reserve(material.size()); @@ -167,10 +158,8 @@ Acts::materialMapperXYZ( detail::EquidistantAxis yAxis(yMin * lengthUnit, yMax * lengthUnit, nBinsY); detail::EquidistantAxis zAxis(zMin * lengthUnit, zMax * lengthUnit, nBinsZ); // Create the grid - using Grid_t = detail::Grid<ActsVectorF<5>, - detail::EquidistantAxis, - detail::EquidistantAxis, - detail::EquidistantAxis>; + using Grid_t = detail::Grid<ActsVectorF<5>, detail::EquidistantAxis, + detail::EquidistantAxis, detail::EquidistantAxis>; Grid_t grid( std::make_tuple(std::move(xAxis), std::move(yAxis), std::move(zAxis))); @@ -179,8 +168,8 @@ Acts::materialMapperXYZ( for (size_t j = 1; j <= nBinsY; ++j) { for (size_t k = 1; k <= nBinsZ; ++k) { Grid_t::index_t indices = {{i, j, k}}; - std::array<size_t, 3> nIndices - = {{xPos.size(), yPos.size(), zPos.size()}}; + std::array<size_t, 3> nIndices = { + {xPos.size(), yPos.size(), zPos.size()}}; // std::vectors begin with 0 and we do not want the user needing to // take underflow or overflow bins in account this is why we need to // subtract by one @@ -200,9 +189,8 @@ Acts::materialMapperXYZ( // [5] Create the mapper & BField Service // create material mapping - return MaterialMapper<detail::Grid<ActsVectorF<5>, - detail::EquidistantAxis, - detail::EquidistantAxis, - detail::EquidistantAxis>>(transformPos, - std::move(grid)); + return MaterialMapper< + detail::Grid<ActsVectorF<5>, detail::EquidistantAxis, + detail::EquidistantAxis, detail::EquidistantAxis>>( + transformPos, std::move(grid)); } \ No newline at end of file diff --git a/Core/src/Material/MaterialProperties.cpp b/Core/src/Material/MaterialProperties.cpp index 17235efe0b9dc03e2ae09337468edae701890fc1..2f131a813782c00a27b6c01bc12081a5cb6bc89e 100644 --- a/Core/src/Material/MaterialProperties.cpp +++ b/Core/src/Material/MaterialProperties.cpp @@ -14,44 +14,33 @@ #include <climits> Acts::MaterialProperties::MaterialProperties(float thickness) - : m_thickness(thickness) -{ -} + : m_thickness(thickness) {} -Acts::MaterialProperties::MaterialProperties(float Xo, - float Lo, - float averageA, - float averageZ, - float averageRho, +Acts::MaterialProperties::MaterialProperties(float Xo, float Lo, float averageA, + float averageZ, float averageRho, float thickness) - : m_material(Xo, Lo, averageA, averageZ, averageRho) - , m_thickness(thickness) - , m_dInX0(Xo * Xo > 10e-10 ? thickness / Xo : 0.) - , m_dInL0(Lo * Lo > 10e-10 ? thickness / Lo : 0.) -{ -} + : m_material(Xo, Lo, averageA, averageZ, averageRho), + m_thickness(thickness), + m_dInX0(Xo * Xo > 10e-10 ? thickness / Xo : 0.), + m_dInL0(Lo * Lo > 10e-10 ? thickness / Lo : 0.) {} Acts::MaterialProperties::MaterialProperties(const Material& material, - float thickness) - : m_material(material) - , m_thickness(thickness) - , m_dInX0(material.X0() * material.X0() > 10e-10 ? thickness / material.X0() - : 0.) - , m_dInL0(material.L0() * material.L0() > 10e-10 ? thickness / material.L0() - : 0.) -{ -} + float thickness) + : m_material(material), + m_thickness(thickness), + m_dInX0(material.X0() * material.X0() > 10e-10 ? thickness / material.X0() + : 0.), + m_dInL0(material.L0() * material.L0() > 10e-10 ? thickness / material.L0() + : 0.) {} Acts::MaterialProperties::MaterialProperties( - const std::vector<MaterialProperties>& matLayers, - bool unitThickness) - : m_material(), m_thickness(0.), m_dInX0(0.), m_dInL0(0.) -{ + const std::vector<MaterialProperties>& matLayers, bool unitThickness) + : m_material(), m_thickness(0.), m_dInX0(0.), m_dInL0(0.) { double rho = 0.; - double A = 0.; - double Z = 0.; - double X0 = 0.; - double L0 = 0.; + double A = 0.; + double Z = 0.; + double X0 = 0.; + double L0 = 0.; for (auto& mat : matLayers) { // thickness in X0 and L0 are strictly additive @@ -79,9 +68,7 @@ Acts::MaterialProperties::MaterialProperties( } } -Acts::MaterialProperties& -Acts::MaterialProperties::operator*=(float scale) -{ +Acts::MaterialProperties& Acts::MaterialProperties::operator*=(float scale) { // assuming rescaling of the material thickness m_dInX0 *= scale; m_dInL0 *= scale; @@ -89,23 +76,20 @@ Acts::MaterialProperties::operator*=(float scale) return (*this); } -void -Acts::MaterialProperties::scaleToUnitThickness() -{ +void Acts::MaterialProperties::scaleToUnitThickness() { // And 'condense to unit thickness' if configured - double t = thickness(); - double X0 = m_material.X0() / t; - double L0 = m_material.L0() / t; - double A = m_material.A(); - double Z = m_material.Z(); - double rho = m_material.rho() * t; - m_material = Material(X0, L0, A, Z, rho); + double t = thickness(); + double X0 = m_material.X0() / t; + double L0 = m_material.L0() / t; + double A = m_material.A(); + double Z = m_material.Z(); + double rho = m_material.rho() * t; + m_material = Material(X0, L0, A, Z, rho); m_thickness = 1.; } -std::ostream& -Acts::operator<<(std::ostream& sl, const MaterialProperties& mprop) -{ +std::ostream& Acts::operator<<(std::ostream& sl, + const MaterialProperties& mprop) { if (mprop) { sl << "Acts::MaterialProperties: " << std::endl; sl << " - thickness/X0 = " diff --git a/Core/src/Material/ProtoSurfaceMaterial.cpp b/Core/src/Material/ProtoSurfaceMaterial.cpp index 25e7cffc5793b91a6e8d8970d79b55f87a1fb449..4330ac7691d529df10e12f52e2ca16f10f325e63 100644 --- a/Core/src/Material/ProtoSurfaceMaterial.cpp +++ b/Core/src/Material/ProtoSurfaceMaterial.cpp @@ -13,19 +13,14 @@ #include "Acts/Material/ProtoSurfaceMaterial.hpp" Acts::ProtoSurfaceMaterial::ProtoSurfaceMaterial(const BinUtility& binUtility) - : ISurfaceMaterial(), m_binUtility(binUtility) -{ -} + : ISurfaceMaterial(), m_binUtility(binUtility) {} -Acts::ProtoSurfaceMaterial& -Acts::ProtoSurfaceMaterial::operator*=(double /*scale*/) -{ +Acts::ProtoSurfaceMaterial& Acts::ProtoSurfaceMaterial::operator*=( + double /*scale*/) { return (*this); } -std::ostream& -Acts::ProtoSurfaceMaterial::toStream(std::ostream& sl) const -{ +std::ostream& Acts::ProtoSurfaceMaterial::toStream(std::ostream& sl) const { sl << "Acts::ProtoSurfaceMaterial : " << std::endl; if (m_binUtility.bins(0) * m_binUtility.bins(1) > 1) { sl << " - Number of Material bins [0,1] : " << m_binUtility.bins(0) diff --git a/Core/src/Material/SurfaceMaterialMapper.cpp b/Core/src/Material/SurfaceMaterialMapper.cpp index 0ca54801b54ac958b2f9c8929eec65f45f10d7f0..ed6ee1caa8f182d6018122ed81cf7deb4068b908 100644 --- a/Core/src/Material/SurfaceMaterialMapper.cpp +++ b/Core/src/Material/SurfaceMaterialMapper.cpp @@ -24,21 +24,15 @@ #include "Acts/Utilities/BinUtility.hpp" Acts::SurfaceMaterialMapper::SurfaceMaterialMapper( - const Config& cfg, - StraightLinePropagator propagator, + const Config& cfg, StraightLinePropagator propagator, std::unique_ptr<const Logger> slogger) - : m_cfg(cfg) - , m_propagator(std::move(propagator)) - , m_logger(std::move(slogger)) -{ -} + : m_cfg(cfg), + m_propagator(std::move(propagator)), + m_logger(std::move(slogger)) {} -Acts::SurfaceMaterialMapper::State -Acts::SurfaceMaterialMapper::createState( - const GeometryContext& gctx, - const MagneticFieldContext& mctx, - const TrackingGeometry& tGeometry) const -{ +Acts::SurfaceMaterialMapper::State Acts::SurfaceMaterialMapper::createState( + const GeometryContext& gctx, const MagneticFieldContext& mctx, + const TrackingGeometry& tGeometry) const { // Parse the geometry and find all surfaces with material proxies auto world = tGeometry.highestTrackingVolume(); @@ -54,11 +48,8 @@ Acts::SurfaceMaterialMapper::createState( return mState; } -void -Acts::SurfaceMaterialMapper::resolveMaterialSurfaces( - State& mState, - const TrackingVolume& tVolume) const -{ +void Acts::SurfaceMaterialMapper::resolveMaterialSurfaces( + State& mState, const TrackingVolume& tVolume) const { ACTS_VERBOSE("Checking volume '" << tVolume.volumeName() << "' for material surfaces.") // check the boundary surfaces @@ -102,16 +93,12 @@ Acts::SurfaceMaterialMapper::resolveMaterialSurfaces( } } -void -Acts::SurfaceMaterialMapper::checkAndInsert(State& mState, - const Surface& surface) const -{ - +void Acts::SurfaceMaterialMapper::checkAndInsert(State& mState, + const Surface& surface) const { auto surfaceMaterial = surface.surfaceMaterial(); // check if the surface has a proxy if (surfaceMaterial != nullptr) { - - auto geoID = surface.geoID(); + auto geoID = surface.geoID(); size_t volumeID = geoID.value(GeometryID::volume_mask); ACTS_INFO("Material surface found with volumeID " << volumeID); ACTS_INFO(" - surfaceID is " << geoID.toString()); @@ -129,14 +116,14 @@ Acts::SurfaceMaterialMapper::checkAndInsert(State& mState, BinUtility buAdjusted = adjustBinUtility(*bu, surface); // Screen output for Binned Surface material ACTS_INFO(" - adjusted binning is " << buAdjusted); - mState.accumulatedMaterial[geoID] - = AccumulatedSurfaceMaterial(buAdjusted); + mState.accumulatedMaterial[geoID] = + AccumulatedSurfaceMaterial(buAdjusted); return; } // Second attempt: binned material auto bmp = dynamic_cast<const BinnedSurfaceMaterial*>(surfaceMaterial); - bu = (bmp != nullptr) ? (&bmp->binUtility()) : nullptr; + bu = (bmp != nullptr) ? (&bmp->binUtility()) : nullptr; // Creaete a binned type of material if (bu != nullptr) { // Screen output for Binned Surface material @@ -150,39 +137,34 @@ Acts::SurfaceMaterialMapper::checkAndInsert(State& mState, } } -void -Acts::SurfaceMaterialMapper::finalizeMaps(State& mState) const -{ +void Acts::SurfaceMaterialMapper::finalizeMaps(State& mState) const { // iterate over the map to call the total average for (auto& accMaterial : mState.accumulatedMaterial) { - mState.surfaceMaterial[accMaterial.first] - = accMaterial.second.totalAverage(); + mState.surfaceMaterial[accMaterial.first] = + accMaterial.second.totalAverage(); } } -void -Acts::SurfaceMaterialMapper::mapMaterialTrack( - State& mState, - const RecordedMaterialTrack& mTrack) const -{ +void Acts::SurfaceMaterialMapper::mapMaterialTrack( + State& mState, const RecordedMaterialTrack& mTrack) const { // Neutral curvilinear parameters - NeutralCurvilinearParameters start( - nullptr, mTrack.first.first, mTrack.first.second); + NeutralCurvilinearParameters start(nullptr, mTrack.first.first, + mTrack.first.second); // Prepare Action list and abort list - using DebugOutput = detail::DebugOutputActor; + using DebugOutput = detail::DebugOutputActor; using MaterialSurfaceCollector = SurfaceCollector<MaterialSurface>; using ActionList = ActionList<MaterialSurfaceCollector, DebugOutput>; - using AbortList = AbortList<detail::EndOfWorldReached>; + using AbortList = AbortList<detail::EndOfWorldReached>; PropagatorOptions<ActionList, AbortList> options(mState.geoContext, mState.magFieldContext); options.debug = m_cfg.mapperDebugOutput; // Now collect the material layers by using the straight line propagator - const auto& result = m_propagator.propagate(start, options).value(); - auto mcResult = result.get<MaterialSurfaceCollector::result_type>(); - auto mappingSurfaces = mcResult.collected; + const auto& result = m_propagator.propagate(start, options).value(); + auto mcResult = result.get<MaterialSurfaceCollector::result_type>(); + auto mappingSurfaces = mcResult.collected; // Retrieve the recorded material from the recorded material track const auto& rMaterial = mTrack.second.materialInteractions; @@ -202,11 +184,11 @@ Acts::SurfaceMaterialMapper::mapMaterialTrack( auto sfIter = mappingSurfaces.begin(); // Use those to minimize the lookup - GeometryID lastID = GeometryID(); + GeometryID lastID = GeometryID(); GeometryID currentID = GeometryID(); - Vector3D currentPos(0., 0., 0); - double currentPathCorrection = 0.; - auto currentAccMaterial = mState.accumulatedMaterial.end(); + Vector3D currentPos(0., 0., 0); + double currentPathCorrection = 0.; + auto currentAccMaterial = mState.accumulatedMaterial.end(); // To remember the bins of this event using MapBin = std::pair<AccumulatedSurfaceMaterial*, std::array<size_t, 3>>; @@ -217,9 +199,9 @@ Acts::SurfaceMaterialMapper::mapMaterialTrack( while (rmIter != rMaterial.end() && sfIter != mappingSurfaces.end()) { // First check if the distance to the next surface is already closer // don't do the check for the last one, stay on the last possible surface - if (sfIter != mappingSurfaces.end() - 1 - && (rmIter->position - sfIter->position).norm() - > (rmIter->position - (sfIter + 1)->position).norm()) { + if (sfIter != mappingSurfaces.end() - 1 && + (rmIter->position - sfIter->position).norm() > + (rmIter->position - (sfIter + 1)->position).norm()) { // switch to next assignment surface // @TODO: empty hits, i.e. surface is hit but, // has no recorded material assigned @@ -230,8 +212,8 @@ Acts::SurfaceMaterialMapper::mapMaterialTrack( // We have work to do: the assignemnt surface has changed if (currentID != lastID) { // Let's (re-)assess the information - lastID = currentID; - currentPos = (sfIter)->position; + lastID = currentID; + currentPos = (sfIter)->position; currentPathCorrection = sfIter->surface->pathCorrection( mState.geoContext, currentPos, sfIter->direction); currentAccMaterial = mState.accumulatedMaterial.find(currentID); diff --git a/Core/src/Material/VolumeMaterialMapper.cpp b/Core/src/Material/VolumeMaterialMapper.cpp index d602bcd24e6260e080df58c29d48c67e4ff1780c..a317269a62205a661f224e51dd7da2f324c398eb 100644 --- a/Core/src/Material/VolumeMaterialMapper.cpp +++ b/Core/src/Material/VolumeMaterialMapper.cpp @@ -20,14 +20,14 @@ using Acts::VectorHelpers::phi; namespace { using RecordedMaterial = std::vector<std::pair<Acts::Material, Acts::Vector3D>>; -using EAxis = Acts::detail::EquidistantAxis; -using Grid2D - = Acts::detail::Grid<Acts::AccumulatedVolumeMaterial, EAxis, EAxis>; -using Grid3D - = Acts::detail::Grid<Acts::AccumulatedVolumeMaterial, EAxis, EAxis, EAxis>; +using EAxis = Acts::detail::EquidistantAxis; +using Grid2D = + Acts::detail::Grid<Acts::AccumulatedVolumeMaterial, EAxis, EAxis>; +using Grid3D = + Acts::detail::Grid<Acts::AccumulatedVolumeMaterial, EAxis, EAxis, EAxis>; using MaterialGrid2D = Acts::detail::Grid<Acts::ActsVectorF<5>, EAxis, EAxis>; -using MaterialGrid3D - = Acts::detail::Grid<Acts::ActsVectorF<5>, EAxis, EAxis, EAxis>; +using MaterialGrid3D = + Acts::detail::Grid<Acts::ActsVectorF<5>, EAxis, EAxis, EAxis>; /// @brief Helper method that creates the cache grid for the mapping. This /// grid allows the collection of material at a the anchor points. @@ -38,9 +38,8 @@ using MaterialGrid3D /// maximum value, number of bins} /// /// @return The grid -Grid2D -createGrid(std::array<double, 3> gridAxis1, std::array<double, 3> gridAxis2) -{ +Grid2D createGrid(std::array<double, 3> gridAxis1, + std::array<double, 3> gridAxis2) { // get the number of bins size_t nBinsAxis1 = gridAxis1[2]; size_t nBinsAxis2 = gridAxis2[2]; @@ -76,11 +75,9 @@ createGrid(std::array<double, 3> gridAxis1, std::array<double, 3> gridAxis2) /// maximum value, number of bins} /// /// @return The grid -Grid3D -createGrid(std::array<double, 3> gridAxis1, - std::array<double, 3> gridAxis2, - std::array<double, 3> gridAxis3) -{ +Grid3D createGrid(std::array<double, 3> gridAxis1, + std::array<double, 3> gridAxis2, + std::array<double, 3> gridAxis3) { // get the number of bins size_t nBinsAxis1 = gridAxis1[2]; size_t nBinsAxis2 = gridAxis2[2]; @@ -122,13 +119,10 @@ createGrid(std::array<double, 3> gridAxis1, /// of @p mPoints to the grid points by its local index /// /// @return The average material grid decomposed into classification numbers -MaterialGrid2D -mapMaterialPoints( - Grid2D& grid, - const RecordedMaterial& mPoints, +MaterialGrid2D mapMaterialPoints( + Grid2D& grid, const RecordedMaterial& mPoints, const std::function<Grid2D::index_t(const Acts::Vector3D&, const Grid2D&)>& - matchToGridPoint) -{ + matchToGridPoint) { // Walk over each point for (const auto& rm : mPoints) { // Search for fitting grid point and accumulate @@ -138,8 +132,8 @@ mapMaterialPoints( // Build material grid // Re-build the axes - Grid2D::point_t min = grid.minPosition(); - Grid2D::point_t max = grid.maxPosition(); + Grid2D::point_t min = grid.minPosition(); + Grid2D::point_t max = grid.maxPosition(); Grid2D::index_t nBins = grid.numLocalBins(); EAxis axis1(min[0], max[0], nBins[0]); @@ -163,13 +157,10 @@ mapMaterialPoints( /// of @p mPoints to the grid points by its local index /// /// @return The average material grid decomposed into classification numbers -MaterialGrid3D -mapMaterialPoints( - Grid3D& grid, - const RecordedMaterial& mPoints, +MaterialGrid3D mapMaterialPoints( + Grid3D& grid, const RecordedMaterial& mPoints, const std::function<Grid3D::index_t(const Acts::Vector3D&, const Grid3D&)>& - matchToGridPoint) -{ + matchToGridPoint) { // Walk over each point for (const auto& rm : mPoints) { // Search for fitting grid point and accumulate @@ -179,8 +170,8 @@ mapMaterialPoints( // Build material grid // Re-build the axes - Grid3D::point_t min = grid.minPosition(); - Grid3D::point_t max = grid.maxPosition(); + Grid3D::point_t min = grid.minPosition(); + Grid3D::point_t max = grid.maxPosition(); Grid3D::index_t nBins = grid.numLocalBins(); EAxis axis1(min[0], max[0], nBins[0]); @@ -196,28 +187,21 @@ mapMaterialPoints( } } // namespace -MaterialGrid2D -Acts::createMaterialGrid( - std::array<double, 3> gridAxis1, - std::array<double, 3> gridAxis2, +MaterialGrid2D Acts::createMaterialGrid( + std::array<double, 3> gridAxis1, std::array<double, 3> gridAxis2, const RecordedMaterial& mPoints, const std::function<Grid2D::index_t(const Vector3D&, const Grid2D&)>& - matchToGridPoint) -{ + matchToGridPoint) { Grid2D grid = createGrid(std::move(gridAxis1), std::move(gridAxis2)); return mapMaterialPoints(grid, mPoints, matchToGridPoint); } -MaterialGrid3D -Acts::createMaterialGrid( - std::array<double, 3> gridAxis1, - std::array<double, 3> gridAxis2, - std::array<double, 3> gridAxis3, - const RecordedMaterial& mPoints, +MaterialGrid3D Acts::createMaterialGrid( + std::array<double, 3> gridAxis1, std::array<double, 3> gridAxis2, + std::array<double, 3> gridAxis3, const RecordedMaterial& mPoints, const std::function<Grid3D::index_t(const Vector3D&, const Grid3D&)>& - matchToGridPoint) -{ - Grid3D grid = createGrid( - std::move(gridAxis1), std::move(gridAxis2), std::move(gridAxis3)); + matchToGridPoint) { + Grid3D grid = createGrid(std::move(gridAxis1), std::move(gridAxis2), + std::move(gridAxis3)); return mapMaterialPoints(grid, mPoints, matchToGridPoint); } \ No newline at end of file diff --git a/Core/src/Surfaces/ConeBounds.cpp b/Core/src/Surfaces/ConeBounds.cpp index f06d7c08bee3869ac416c238db880f1de4c0719e..226bd5a4dc3d3d471536486338eaaf750241a8c1 100644 --- a/Core/src/Surfaces/ConeBounds.cpp +++ b/Core/src/Surfaces/ConeBounds.cpp @@ -19,93 +19,67 @@ #include "Acts/Utilities/detail/periodic.hpp" -Acts::ConeBounds::ConeBounds(double alpha, - bool symm, - double halfphi, +Acts::ConeBounds::ConeBounds(double alpha, bool symm, double halfphi, double avphi) - : ConeBounds(alpha, - symm ? -std::numeric_limits<double>::infinity() : 0, - std::numeric_limits<double>::infinity(), - halfphi, - avphi) -{ -} + : ConeBounds(alpha, symm ? -std::numeric_limits<double>::infinity() : 0, + std::numeric_limits<double>::infinity(), halfphi, avphi) {} -Acts::ConeBounds::ConeBounds(double alpha, - double zmin, - double zmax, - double halfphi, - double avphi) - : m_alpha(alpha) - , m_tanAlpha(std::tan(alpha)) - , m_zMin(zmin) - , m_zMax(zmax) - , m_avgPhi(detail::radian_sym(avphi)) - , m_halfPhi(std::abs(halfphi)) -{ -} +Acts::ConeBounds::ConeBounds(double alpha, double zmin, double zmax, + double halfphi, double avphi) + : m_alpha(alpha), + m_tanAlpha(std::tan(alpha)), + m_zMin(zmin), + m_zMax(zmax), + m_avgPhi(detail::radian_sym(avphi)), + m_halfPhi(std::abs(halfphi)) {} Acts::ConeBounds::~ConeBounds() = default; -Acts::ConeBounds* -Acts::ConeBounds::clone() const -{ +Acts::ConeBounds* Acts::ConeBounds::clone() const { return new ConeBounds(*this); } -Acts::SurfaceBounds::BoundsType -Acts::ConeBounds::type() const -{ +Acts::SurfaceBounds::BoundsType Acts::ConeBounds::type() const { return SurfaceBounds::Cone; } -std::vector<TDD_real_t> -Acts::ConeBounds::valueStore() const -{ +std::vector<TDD_real_t> Acts::ConeBounds::valueStore() const { std::vector<TDD_real_t> values(ConeBounds::bv_length); - values[ConeBounds::bv_alpha] = alpha(); - values[ConeBounds::bv_minZ] = minZ(); - values[ConeBounds::bv_maxZ] = maxZ(); - values[ConeBounds::bv_averagePhi] = averagePhi(); + values[ConeBounds::bv_alpha] = alpha(); + values[ConeBounds::bv_minZ] = minZ(); + values[ConeBounds::bv_maxZ] = maxZ(); + values[ConeBounds::bv_averagePhi] = averagePhi(); values[ConeBounds::bv_halfPhiSector] = halfPhiSector(); return values; } /// Shift r-phi coordinate to be centered around the average phi. -Acts::Vector2D -Acts::ConeBounds::shifted(const Acts::Vector2D& lpos) const -{ +Acts::Vector2D Acts::ConeBounds::shifted(const Acts::Vector2D& lpos) const { using Acts::detail::radian_sym; - auto x = r(lpos[eLOC_Z]); // cone radius at the local position + auto x = r(lpos[eLOC_Z]); // cone radius at the local position Vector2D shifted; - shifted[eLOC_Z] = lpos[eLOC_Z]; - shifted[eLOC_RPHI] = std::isnormal(x) - ? (x * radian_sym((lpos[eLOC_RPHI] / x) - averagePhi())) - : lpos[eLOC_RPHI]; + shifted[eLOC_Z] = lpos[eLOC_Z]; + shifted[eLOC_RPHI] = + std::isnormal(x) ? (x * radian_sym((lpos[eLOC_RPHI] / x) - averagePhi())) + : lpos[eLOC_RPHI]; return shifted; } -bool -Acts::ConeBounds::inside(const Acts::Vector2D& lpos, - const Acts::BoundaryCheck& bcheck) const -{ +bool Acts::ConeBounds::inside(const Acts::Vector2D& lpos, + const Acts::BoundaryCheck& bcheck) const { auto rphiHalf = r(lpos[eLOC_Z]) * halfPhiSector(); - return bcheck.isInside( - shifted(lpos), Vector2D(-rphiHalf, minZ()), Vector2D(rphiHalf, maxZ())); + return bcheck.isInside(shifted(lpos), Vector2D(-rphiHalf, minZ()), + Vector2D(rphiHalf, maxZ())); } -double -Acts::ConeBounds::distanceToBoundary(const Acts::Vector2D& lpos) const -{ +double Acts::ConeBounds::distanceToBoundary(const Acts::Vector2D& lpos) const { auto rphiHalf = r(lpos[eLOC_Z]) * halfPhiSector(); return BoundaryCheck(true).distance( shifted(lpos), Vector2D(-rphiHalf, minZ()), Vector2D(rphiHalf, maxZ())); } -std::ostream& -Acts::ConeBounds::toStream(std::ostream& sl) const -{ +std::ostream& Acts::ConeBounds::toStream(std::ostream& sl) const { sl << std::setiosflags(std::ios::fixed); sl << std::setprecision(7); sl << "Acts::ConeBounds: (tanAlpha, minZ, maxZ, averagePhi, halfPhiSector) " diff --git a/Core/src/Surfaces/ConeSurface.cpp b/Core/src/Surfaces/ConeSurface.cpp index bed051a1bae4fb2a3d2bb4c889a7a380adc56e94..30257680dbd0295d9f6772179caf8d0ced591f54 100644 --- a/Core/src/Surfaces/ConeSurface.cpp +++ b/Core/src/Surfaces/ConeSurface.cpp @@ -21,92 +21,73 @@ #include "Acts/Utilities/ThrowAssert.hpp" #include "Acts/Utilities/detail/RealQuadraticEquation.hpp" -using Acts::VectorHelpers::phi; using Acts::VectorHelpers::perp; +using Acts::VectorHelpers::phi; Acts::ConeSurface::ConeSurface(const ConeSurface& other) - : GeometryObject(), Surface(other), m_bounds(other.m_bounds) -{ -} + : GeometryObject(), Surface(other), m_bounds(other.m_bounds) {} Acts::ConeSurface::ConeSurface(const GeometryContext& gctx, - const ConeSurface& other, - const Transform3D& transf) - : GeometryObject(), Surface(gctx, other, transf), m_bounds(other.m_bounds) -{ -} + const ConeSurface& other, + const Transform3D& transf) + : GeometryObject(), + Surface(gctx, other, transf), + m_bounds(other.m_bounds) {} Acts::ConeSurface::ConeSurface(std::shared_ptr<const Transform3D> htrans, - double alpha, - bool symmetric) - : GeometryObject() - , Surface(std::move(htrans)) - , m_bounds(std::make_shared<const ConeBounds>(alpha, symmetric)) -{ -} + double alpha, bool symmetric) + : GeometryObject(), + Surface(std::move(htrans)), + m_bounds(std::make_shared<const ConeBounds>(alpha, symmetric)) {} Acts::ConeSurface::ConeSurface(std::shared_ptr<const Transform3D> htrans, - double alpha, - double zmin, - double zmax, - double halfPhi) - : GeometryObject() - , Surface(std::move(htrans)) - , m_bounds(std::make_shared<const ConeBounds>(alpha, zmin, zmax, halfPhi)) -{ + double alpha, double zmin, double zmax, + double halfPhi) + : GeometryObject(), + Surface(std::move(htrans)), + m_bounds(std::make_shared<const ConeBounds>(alpha, zmin, zmax, halfPhi)) { } -Acts::ConeSurface::ConeSurface(std::shared_ptr<const Transform3D> htrans, +Acts::ConeSurface::ConeSurface(std::shared_ptr<const Transform3D> htrans, const std::shared_ptr<const ConeBounds>& cbounds) - : GeometryObject(), Surface(std::move(htrans)), m_bounds(cbounds) -{ + : GeometryObject(), Surface(std::move(htrans)), m_bounds(cbounds) { throw_assert(cbounds, "ConeBounds must not be nullptr"); } -const Acts::Vector3D -Acts::ConeSurface::binningPosition(const GeometryContext& gctx, - Acts::BinningValue bValue) const -{ - +const Acts::Vector3D Acts::ConeSurface::binningPosition( + const GeometryContext& gctx, Acts::BinningValue bValue) const { const Vector3D& sfCenter = center(gctx); // special binning type for R-type methods if (bValue == Acts::binR || bValue == Acts::binRPhi) { - return Vector3D( - sfCenter.x() + bounds().r(sfCenter.z()), sfCenter.y(), sfCenter.z()); + return Vector3D(sfCenter.x() + bounds().r(sfCenter.z()), sfCenter.y(), + sfCenter.z()); } // give the center as default for all of these binning types // binX, binY, binZ, binR, binPhi, binRPhi, binH, binEta return sfCenter; } -Acts::Surface::SurfaceType -Acts::ConeSurface::type() const -{ +Acts::Surface::SurfaceType Acts::ConeSurface::type() const { return Surface::Cone; } -Acts::ConeSurface& -Acts::ConeSurface::operator=(const ConeSurface& other) -{ +Acts::ConeSurface& Acts::ConeSurface::operator=(const ConeSurface& other) { if (this != &other) { Surface::operator=(other); - m_bounds = other.m_bounds; + m_bounds = other.m_bounds; } return *this; } -const Acts::Vector3D -Acts::ConeSurface::rotSymmetryAxis(const GeometryContext& gctx) const -{ +const Acts::Vector3D Acts::ConeSurface::rotSymmetryAxis( + const GeometryContext& gctx) const { return std::move(transform(gctx).matrix().block<3, 1>(0, 2)); } -const Acts::RotationMatrix3D -Acts::ConeSurface::referenceFrame(const GeometryContext& gctx, - const Vector3D& pos, - const Vector3D& /*unused*/) const -{ +const Acts::RotationMatrix3D Acts::ConeSurface::referenceFrame( + const GeometryContext& gctx, const Vector3D& pos, + const Vector3D& /*unused*/) const { RotationMatrix3D mFrame; // construct the measurement frame // measured Y is the local z axis @@ -125,15 +106,13 @@ Acts::ConeSurface::referenceFrame(const GeometryContext& gctx, return mFrame; } -void -Acts::ConeSurface::localToGlobal(const GeometryContext& gctx, - const Vector2D& lpos, - const Vector3D& /*unused*/, - Vector3D& gpos) const -{ +void Acts::ConeSurface::localToGlobal(const GeometryContext& gctx, + const Vector2D& lpos, + const Vector3D& /*unused*/, + Vector3D& gpos) const { // create the position in the local 3d frame - double r = lpos[Acts::eLOC_Z] * bounds().tanAlpha(); - double phi = lpos[Acts::eLOC_RPHI] / r; + double r = lpos[Acts::eLOC_Z] * bounds().tanAlpha(); + double phi = lpos[Acts::eLOC_RPHI] / r; Vector3D loc3Dframe(r * cos(phi), r * sin(phi), lpos[Acts::eLOC_Z]); // transport it to the globalframe if (m_transform) { @@ -141,33 +120,28 @@ Acts::ConeSurface::localToGlobal(const GeometryContext& gctx, } } -bool -Acts::ConeSurface::globalToLocal(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& /*unused*/, - Vector2D& lpos) const -{ +bool Acts::ConeSurface::globalToLocal(const GeometryContext& gctx, + const Vector3D& gpos, + const Vector3D& /*unused*/, + Vector2D& lpos) const { Vector3D loc3Dframe = m_transform ? (transform(gctx).inverse() * gpos) : gpos; - double r = loc3Dframe.z() * bounds().tanAlpha(); + double r = loc3Dframe.z() * bounds().tanAlpha(); lpos = Vector2D(r * atan2(loc3Dframe.y(), loc3Dframe.x()), loc3Dframe.z()); // now decide on the quility of the transformation double inttol = r * 0.0001; - inttol = (inttol < 0.01) ? 0.01 : 0.01; // ? + inttol = (inttol < 0.01) ? 0.01 : 0.01; // ? return ((std::abs(perp(loc3Dframe) - r) > inttol) ? false : true); } -double -Acts::ConeSurface::pathCorrection(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& mom) const -{ +double Acts::ConeSurface::pathCorrection(const GeometryContext& gctx, + const Vector3D& gpos, + const Vector3D& mom) const { // (cos phi cos alpha, sin phi cos alpha, sgn z sin alpha) Vector3D posLocal = m_transform ? transform(gctx).inverse() * gpos : gpos; - double phi = VectorHelpers::phi(posLocal); - double sgn = posLocal.z() > 0. ? -1. : +1.; + double phi = VectorHelpers::phi(posLocal); + double sgn = posLocal.z() > 0. ? -1. : +1.; Vector3D normalC(cos(phi) * bounds().cosAlpha(), - sin(phi) * bounds().cosAlpha(), - sgn * bounds().sinAlpha()); + sin(phi) * bounds().cosAlpha(), sgn * bounds().sinAlpha()); if (m_transform) { normalC = transform(gctx) * normalC; } @@ -176,30 +150,22 @@ Acts::ConeSurface::pathCorrection(const GeometryContext& gctx, return std::abs(1. / cAlpha); } -std::string -Acts::ConeSurface::name() const -{ +std::string Acts::ConeSurface::name() const { return "Acts::ConeSurface"; } -std::shared_ptr<Acts::ConeSurface> -Acts::ConeSurface::clone(const GeometryContext& gctx, - const Transform3D& shift) const -{ +std::shared_ptr<Acts::ConeSurface> Acts::ConeSurface::clone( + const GeometryContext& gctx, const Transform3D& shift) const { return std::shared_ptr<ConeSurface>(this->clone_impl(gctx, shift)); } -Acts::ConeSurface* -Acts::ConeSurface::clone_impl(const GeometryContext& gctx, - const Transform3D& shift) const -{ +Acts::ConeSurface* Acts::ConeSurface::clone_impl( + const GeometryContext& gctx, const Transform3D& shift) const { return new ConeSurface(gctx, *this, shift); } -const Acts::Vector3D -Acts::ConeSurface::normal(const GeometryContext& gctx, - const Acts::Vector2D& lp) const -{ +const Acts::Vector3D Acts::ConeSurface::normal(const GeometryContext& gctx, + const Acts::Vector2D& lp) const { // (cos phi cos alpha, sin phi cos alpha, sgn z sin alpha) double phi = lp[Acts::eLOC_RPHI] / (bounds().r(lp[Acts::eLOC_Z])), sgn = lp[Acts::eLOC_Z] > 0 ? -1. : +1.; @@ -210,23 +176,19 @@ Acts::ConeSurface::normal(const GeometryContext& gctx, : localNormal; } -const Acts::Vector3D -Acts::ConeSurface::normal(const GeometryContext& gctx, - const Acts::Vector3D& gpos) const -{ +const Acts::Vector3D Acts::ConeSurface::normal( + const GeometryContext& gctx, const Acts::Vector3D& gpos) const { // get it into the cylinder frame if needed // @todo respect opening angle Vector3D pos3D = gpos; if (m_transform || (m_associatedDetElement != nullptr)) { - pos3D = transform(gctx).inverse() * gpos; + pos3D = transform(gctx).inverse() * gpos; pos3D.z() = 0; } return pos3D.normalized(); } -const Acts::ConeBounds& -Acts::ConeSurface::bounds() const -{ +const Acts::ConeBounds& Acts::ConeSurface::bounds() const { // is safe because no constructor w/o bounds exists return (*m_bounds.get()); } diff --git a/Core/src/Surfaces/CylinderBounds.cpp b/Core/src/Surfaces/CylinderBounds.cpp index 681cd1d2bf8c3d80029b2c0dbc5f33b3cf898e1d..d3297efa9607e237ab1be70541b2f444b4f91e1f 100644 --- a/Core/src/Surfaces/CylinderBounds.cpp +++ b/Core/src/Surfaces/CylinderBounds.cpp @@ -19,32 +19,25 @@ #include "Acts/Utilities/Helpers.hpp" #include "Acts/Utilities/detail/periodic.hpp" -using Acts::VectorHelpers::phi; using Acts::VectorHelpers::perp; +using Acts::VectorHelpers::phi; Acts::CylinderBounds::CylinderBounds(double radius, double halfZ) - : CylinderBounds(radius, 0, M_PI, halfZ) -{ + : CylinderBounds(radius, 0, M_PI, halfZ) { m_closed = true; } -Acts::CylinderBounds::CylinderBounds(double radius, - double halfPhi, - double halfZ) - : CylinderBounds(radius, 0, halfPhi, halfZ) -{ -} - -Acts::CylinderBounds::CylinderBounds(double radius, - double averagePhi, - double halfPhi, +Acts::CylinderBounds::CylinderBounds(double radius, double halfPhi, double halfZ) - : m_radius(std::abs(radius)) - , m_avgPhi(detail::radian_sym(averagePhi)) - , m_halfPhi(std::abs(halfPhi)) - , m_halfZ(std::abs(halfZ)) - , m_closed(false) -{ + : CylinderBounds(radius, 0, halfPhi, halfZ) {} + +Acts::CylinderBounds::CylinderBounds(double radius, double averagePhi, + double halfPhi, double halfZ) + : m_radius(std::abs(radius)), + m_avgPhi(detail::radian_sym(averagePhi)), + m_halfPhi(std::abs(halfPhi)), + m_halfZ(std::abs(halfZ)), + m_closed(false) { if (halfPhi == M_PI) { m_closed = true; } @@ -52,98 +45,80 @@ Acts::CylinderBounds::CylinderBounds(double radius, Acts::CylinderBounds::~CylinderBounds() = default; -Acts::CylinderBounds* -Acts::CylinderBounds::clone() const -{ +Acts::CylinderBounds* Acts::CylinderBounds::clone() const { return new CylinderBounds(*this); } -Acts::SurfaceBounds::BoundsType -Acts::CylinderBounds::type() const -{ +Acts::SurfaceBounds::BoundsType Acts::CylinderBounds::type() const { return SurfaceBounds::Cylinder; } -std::vector<TDD_real_t> -Acts::CylinderBounds::valueStore() const -{ +std::vector<TDD_real_t> Acts::CylinderBounds::valueStore() const { std::vector<TDD_real_t> values(CylinderBounds::bv_length); - values[CylinderBounds::bv_radius] = m_radius; - values[CylinderBounds::bv_averagePhi] = m_avgPhi; + values[CylinderBounds::bv_radius] = m_radius; + values[CylinderBounds::bv_averagePhi] = m_avgPhi; values[CylinderBounds::bv_halfPhiSector] = m_halfPhi; - values[CylinderBounds::bv_halfZ] = m_halfZ; + values[CylinderBounds::bv_halfZ] = m_halfZ; return values; } // Convert from (r*phi,z) to (phi,z) centered around phi0 -Acts::Vector2D -Acts::CylinderBounds::shifted(const Acts::Vector2D& lpos) const -{ +Acts::Vector2D Acts::CylinderBounds::shifted(const Acts::Vector2D& lpos) const { return { Acts::detail::radian_sym((lpos[Acts::eLOC_RPHI] / m_radius) - m_avgPhi), lpos[Acts::eLOC_Z]}; } // Jacobian from (r*phi,z) to (phi,z) -Acts::ActsSymMatrixD<2> -Acts::CylinderBounds::jacobian() const -{ +Acts::ActsSymMatrixD<2> Acts::CylinderBounds::jacobian() const { ActsSymMatrixD<2> j; j(0, eLOC_RPHI) = 1 / m_radius; - j(0, eLOC_Z) = 0; + j(0, eLOC_Z) = 0; j(1, eLOC_RPHI) = 0; - j(1, eLOC_Z) = 1; + j(1, eLOC_Z) = 1; return j; } -bool -Acts::CylinderBounds::inside(const Vector2D& lpos, - const BoundaryCheck& bcheck) const -{ +bool Acts::CylinderBounds::inside(const Vector2D& lpos, + const BoundaryCheck& bcheck) const { return bcheck.transformed(jacobian()) - .isInside(shifted(lpos), - Vector2D(-m_halfPhi, -m_halfZ), + .isInside(shifted(lpos), Vector2D(-m_halfPhi, -m_halfZ), Vector2D(m_halfPhi, m_halfZ)); } -bool -Acts::CylinderBounds::inside3D(const Vector3D& pos, - const BoundaryCheck& bcheck) const -{ +bool Acts::CylinderBounds::inside3D(const Vector3D& pos, + const BoundaryCheck& bcheck) const { // additional tolerance from the boundary check if configred bool checkAbsolute = bcheck.m_type == BoundaryCheck::Type::eAbsolute; // this fast check only applies to closed cylindrical bounds - double addToleranceR - = (checkAbsolute && m_closed) ? bcheck.m_tolerance[0] : 0.; + double addToleranceR = + (checkAbsolute && m_closed) ? bcheck.m_tolerance[0] : 0.; double addToleranceZ = checkAbsolute ? bcheck.m_tolerance[1] : 0.; // check if the position compatible with the radius - if ((s_onSurfaceTolerance + addToleranceR) - <= std::abs(perp(pos) - m_radius)) { + if ((s_onSurfaceTolerance + addToleranceR) <= + std::abs(perp(pos) - m_radius)) { return false; } else if (checkAbsolute && m_closed) { - return ((s_onSurfaceTolerance + addToleranceZ + m_halfZ) - >= std::abs(pos.z())); + return ((s_onSurfaceTolerance + addToleranceZ + m_halfZ) >= + std::abs(pos.z())); } // detailed, but slower check Vector2D lpos(detail::radian_sym(phi(pos) - m_avgPhi), pos.z()); return bcheck.transformed(jacobian()) - .isInside( - lpos, Vector2D(-m_halfPhi, -m_halfZ), Vector2D(m_halfPhi, m_halfZ)); + .isInside(lpos, Vector2D(-m_halfPhi, -m_halfZ), + Vector2D(m_halfPhi, m_halfZ)); } -double -Acts::CylinderBounds::distanceToBoundary(const Acts::Vector2D& lpos) const -{ +double Acts::CylinderBounds::distanceToBoundary( + const Acts::Vector2D& lpos) const { return BoundaryCheck(true).distance(shifted(lpos), Vector2D(-m_halfPhi, -m_halfZ), Vector2D(m_halfPhi, m_halfZ)); } // ostream operator overload -std::ostream& -Acts::CylinderBounds::toStream(std::ostream& sl) const -{ +std::ostream& Acts::CylinderBounds::toStream(std::ostream& sl) const { sl << std::setiosflags(std::ios::fixed); sl << std::setprecision(7); sl << "Acts::CylinderBounds: (radius, averagePhi, halfPhiSector, " diff --git a/Core/src/Surfaces/CylinderSurface.cpp b/Core/src/Surfaces/CylinderSurface.cpp index f207649a5ad143401aba194d8e1ab39358739550..ee2de8f5235ebeb84121770b54d0b5996670c3b7 100644 --- a/Core/src/Surfaces/CylinderSurface.cpp +++ b/Core/src/Surfaces/CylinderSurface.cpp @@ -21,82 +21,66 @@ #include "Acts/Utilities/ThrowAssert.hpp" -using Acts::VectorHelpers::phi; using Acts::VectorHelpers::perp; +using Acts::VectorHelpers::phi; Acts::CylinderSurface::CylinderSurface(const CylinderSurface& other) - : GeometryObject(), Surface(other), m_bounds(other.m_bounds) -{ -} + : GeometryObject(), Surface(other), m_bounds(other.m_bounds) {} Acts::CylinderSurface::CylinderSurface(const GeometryContext& gctx, const CylinderSurface& other, - const Transform3D& transf) - : GeometryObject(), Surface(gctx, other, transf), m_bounds(other.m_bounds) -{ -} + const Transform3D& transf) + : GeometryObject(), + Surface(gctx, other, transf), + m_bounds(other.m_bounds) {} Acts::CylinderSurface::CylinderSurface( - std::shared_ptr<const Transform3D> htrans, - double radius, - double hlength) - : GeometryObject() - , Surface(std::move(htrans)) - , m_bounds(std::make_shared<const CylinderBounds>(radius, hlength)) -{ -} + std::shared_ptr<const Transform3D> htrans, double radius, double hlength) + : GeometryObject(), + Surface(std::move(htrans)), + m_bounds(std::make_shared<const CylinderBounds>(radius, hlength)) {} Acts::CylinderSurface::CylinderSurface( - std::shared_ptr<const Transform3D> htrans, - double radius, - double hphi, - double hlength) - : GeometryObject() - , Surface(std::move(htrans)) - , m_bounds(std::make_shared<const CylinderBounds>(radius, hphi, hlength)) -{ -} + std::shared_ptr<const Transform3D> htrans, double radius, double hphi, + double hlength) + : GeometryObject(), + Surface(std::move(htrans)), + m_bounds(std::make_shared<const CylinderBounds>(radius, hphi, hlength)) {} Acts::CylinderSurface::CylinderSurface( std::shared_ptr<const CylinderBounds> cbounds, - const Acts::DetectorElementBase& detelement) - : Surface(detelement), m_bounds(std::move(cbounds)) -{ + const Acts::DetectorElementBase& detelement) + : Surface(detelement), m_bounds(std::move(cbounds)) { /// surfaces representing a detector element must have bounds assert(cbounds); } Acts::CylinderSurface::CylinderSurface( - std::shared_ptr<const Transform3D> htrans, + std::shared_ptr<const Transform3D> htrans, const std::shared_ptr<const CylinderBounds>& cbounds) - : Surface(std::move(htrans)), m_bounds(cbounds) -{ + : Surface(std::move(htrans)), m_bounds(cbounds) { throw_assert(cbounds, "CylinderBounds must not be nullptr"); } -Acts::CylinderSurface& -Acts::CylinderSurface::operator=(const CylinderSurface& other) -{ +Acts::CylinderSurface& Acts::CylinderSurface::operator=( + const CylinderSurface& other) { if (this != &other) { Surface::operator=(other); - m_bounds = other.m_bounds; + m_bounds = other.m_bounds; } return *this; } // return the binning position for ordering in the BinnedArray -const Acts::Vector3D -Acts::CylinderSurface::binningPosition(const GeometryContext& gctx, - BinningValue bValue) const -{ - +const Acts::Vector3D Acts::CylinderSurface::binningPosition( + const GeometryContext& gctx, BinningValue bValue) const { const Acts::Vector3D& sfCenter = center(gctx); // special binning type for R-type methods if (bValue == Acts::binR || bValue == Acts::binRPhi) { - double R = bounds().r(); + double R = bounds().r(); double phi = m_bounds ? m_bounds->averagePhi() : 0.; - return Vector3D( - sfCenter.x() + R * cos(phi), sfCenter.y() + R * sin(phi), sfCenter.z()); + return Vector3D(sfCenter.x() + R * cos(phi), sfCenter.y() + R * sin(phi), + sfCenter.z()); } // give the center as default for all of these binning types // binX, binY, binZ, binR, binPhi, binRPhi, binH, binEta @@ -104,11 +88,9 @@ Acts::CylinderSurface::binningPosition(const GeometryContext& gctx, } // return the measurement frame: it's the tangential plane -const Acts::RotationMatrix3D -Acts::CylinderSurface::referenceFrame(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& /*unused*/) const -{ +const Acts::RotationMatrix3D Acts::CylinderSurface::referenceFrame( + const GeometryContext& gctx, const Vector3D& gpos, + const Vector3D& /*unused*/) const { RotationMatrix3D mFrame; // construct the measurement frame // measured Y is the z axis @@ -125,31 +107,25 @@ Acts::CylinderSurface::referenceFrame(const GeometryContext& gctx, return mFrame; } -Acts::Surface::SurfaceType -Acts::CylinderSurface::type() const -{ +Acts::Surface::SurfaceType Acts::CylinderSurface::type() const { return Surface::Cylinder; } -void -Acts::CylinderSurface::localToGlobal(const GeometryContext& gctx, - const Vector2D& lpos, - const Vector3D& /*unused*/, - Vector3D& gpos) const -{ +void Acts::CylinderSurface::localToGlobal(const GeometryContext& gctx, + const Vector2D& lpos, + const Vector3D& /*unused*/, + Vector3D& gpos) const { // create the position in the local 3d frame - double r = bounds().r(); + double r = bounds().r(); double phi = lpos[Acts::eLOC_RPHI] / r; - gpos = Vector3D(r * cos(phi), r * sin(phi), lpos[Acts::eLOC_Z]); - gpos = transform(gctx) * gpos; + gpos = Vector3D(r * cos(phi), r * sin(phi), lpos[Acts::eLOC_Z]); + gpos = transform(gctx) * gpos; } -bool -Acts::CylinderSurface::globalToLocal(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& /*unused*/, - Vector2D& lpos) const -{ +bool Acts::CylinderSurface::globalToLocal(const GeometryContext& gctx, + const Vector3D& gpos, + const Vector3D& /*unused*/, + Vector2D& lpos) const { // get the transform & transform global position into cylinder frame // @todo clean up intolerance parameters // transform it to the globalframe: CylinderSurfaces are allowed to have 0 @@ -161,47 +137,37 @@ Acts::CylinderSurface::globalToLocal(const GeometryContext& gctx, } const Transform3D& sfTransform = transform(gctx); - Transform3D inverseTrans(sfTransform.inverse()); - Vector3D loc3Dframe(inverseTrans * gpos); - lpos = Vector2D(bounds().r() * phi(loc3Dframe), loc3Dframe.z()); + Transform3D inverseTrans(sfTransform.inverse()); + Vector3D loc3Dframe(inverseTrans * gpos); + lpos = Vector2D(bounds().r() * phi(loc3Dframe), loc3Dframe.z()); radius = perp(loc3Dframe); // return true or false return ((std::abs(radius - bounds().r()) > inttol) ? false : true); } -std::string -Acts::CylinderSurface::name() const -{ +std::string Acts::CylinderSurface::name() const { return "Acts::CylinderSurface"; } -std::shared_ptr<Acts::CylinderSurface> -Acts::CylinderSurface::clone(const GeometryContext& gctx, - const Transform3D& shift) const -{ +std::shared_ptr<Acts::CylinderSurface> Acts::CylinderSurface::clone( + const GeometryContext& gctx, const Transform3D& shift) const { return std::shared_ptr<CylinderSurface>(this->clone_impl(gctx, shift)); } -Acts::CylinderSurface* -Acts::CylinderSurface::clone_impl(const GeometryContext& gctx, - const Transform3D& shift) const -{ +Acts::CylinderSurface* Acts::CylinderSurface::clone_impl( + const GeometryContext& gctx, const Transform3D& shift) const { return new CylinderSurface(gctx, *this, shift); } -const Acts::Vector3D -Acts::CylinderSurface::normal(const GeometryContext& gctx, - const Acts::Vector2D& lpos) const -{ - double phi = lpos[Acts::eLOC_RPHI] / m_bounds->r(); +const Acts::Vector3D Acts::CylinderSurface::normal( + const GeometryContext& gctx, const Acts::Vector2D& lpos) const { + double phi = lpos[Acts::eLOC_RPHI] / m_bounds->r(); Vector3D localNormal(cos(phi), sin(phi), 0.); return Vector3D(transform(gctx).matrix().block<3, 3>(0, 0) * localNormal); } -const Acts::Vector3D -Acts::CylinderSurface::normal(const GeometryContext& gctx, - const Acts::Vector3D& gpos) const -{ +const Acts::Vector3D Acts::CylinderSurface::normal( + const GeometryContext& gctx, const Acts::Vector3D& gpos) const { const Transform3D& sfTransform = transform(gctx); // get it into the cylinder frame Vector3D pos3D = sfTransform.inverse() * gpos; @@ -211,28 +177,21 @@ Acts::CylinderSurface::normal(const GeometryContext& gctx, return sfTransform.linear() * pos3D.normalized(); } -double -Acts::CylinderSurface::pathCorrection(const GeometryContext& gctx, - const Acts::Vector3D& gpos, - const Acts::Vector3D& mom) const -{ - Vector3D normalT = normal(gctx, gpos); - double cosAlpha = normalT.dot(mom.normalized()); +double Acts::CylinderSurface::pathCorrection(const GeometryContext& gctx, + const Acts::Vector3D& gpos, + const Acts::Vector3D& mom) const { + Vector3D normalT = normal(gctx, gpos); + double cosAlpha = normalT.dot(mom.normalized()); return std::fabs(1. / cosAlpha); } -const Acts::CylinderBounds& -Acts::CylinderSurface::bounds() const -{ +const Acts::CylinderBounds& Acts::CylinderSurface::bounds() const { return (*m_bounds.get()); } -Acts::PolyhedronRepresentation -Acts::CylinderSurface::polyhedronRepresentation(const GeometryContext& gctx, - size_t l0div, - size_t /*unused*/) const -{ - std::vector<Vector3D> vertices; +Acts::PolyhedronRepresentation Acts::CylinderSurface::polyhedronRepresentation( + const GeometryContext& gctx, size_t l0div, size_t /*unused*/) const { + std::vector<Vector3D> vertices; std::vector<std::vector<size_t>> faces; if (l0div <= 1) { @@ -241,8 +200,8 @@ Acts::CylinderSurface::polyhedronRepresentation(const GeometryContext& gctx, } double phistep = 2 * M_PI / l0div; - double hlZ = bounds().halflengthZ(); - double r = bounds().r(); + double hlZ = bounds().halflengthZ(); + double r = bounds().r(); Vector3D left(r, 0, -hlZ); Vector3D right(r, 0, hlZ); @@ -256,7 +215,6 @@ Acts::CylinderSurface::polyhedronRepresentation(const GeometryContext& gctx, } for (size_t v = 0; v < vertices.size() - 2; v = v + 2) { - faces.push_back({v, v + 1, v + 3, v + 2}); } if (l0div > 2) { diff --git a/Core/src/Surfaces/DiamondBounds.cpp b/Core/src/Surfaces/DiamondBounds.cpp index e8ec586b4d7d3c1a43f6f6dba4cd8fd6fda31c6f..7b4603fc433e110a35107a4146c62bad932edaf8 100644 --- a/Core/src/Surfaces/DiamondBounds.cpp +++ b/Core/src/Surfaces/DiamondBounds.cpp @@ -17,65 +17,51 @@ #include <iomanip> #include <iostream> -Acts::DiamondBounds::DiamondBounds(double minhalex, - double medhalex, - double maxhalex, - double haley1, +Acts::DiamondBounds::DiamondBounds(double minhalex, double medhalex, + double maxhalex, double haley1, double haley2) - : m_minHalfX(std::abs(minhalex)) - , m_medHalfX(std::abs(medhalex)) - , m_maxHalfX(std::abs(maxhalex)) - , m_minY(std::abs(haley1)) - , m_maxY(std::abs(haley2)) - , m_boundingBox(std::max(std::max(minhalex, medhalex), maxhalex), - std::max(haley1, haley2)) -{ + : m_minHalfX(std::abs(minhalex)), + m_medHalfX(std::abs(medhalex)), + m_maxHalfX(std::abs(maxhalex)), + m_minY(std::abs(haley1)), + m_maxY(std::abs(haley2)), + m_boundingBox(std::max(std::max(minhalex, medhalex), maxhalex), + std::max(haley1, haley2)) { throw_assert((minhalex <= medhalex), "Hexagon must be a convex polygon"); throw_assert((maxhalex <= medhalex), "Hexagon must be a convex polygon"); } Acts::DiamondBounds::~DiamondBounds() = default; -Acts::DiamondBounds* -Acts::DiamondBounds::clone() const -{ +Acts::DiamondBounds* Acts::DiamondBounds::clone() const { return new DiamondBounds(*this); } -Acts::SurfaceBounds::BoundsType -Acts::DiamondBounds::type() const -{ +Acts::SurfaceBounds::BoundsType Acts::DiamondBounds::type() const { return SurfaceBounds::Diamond; } -std::vector<TDD_real_t> -Acts::DiamondBounds::valueStore() const -{ +std::vector<TDD_real_t> Acts::DiamondBounds::valueStore() const { std::vector<TDD_real_t> values(DiamondBounds::bv_length); values[DiamondBounds::bv_minHalfX] = minHalflengthX(); values[DiamondBounds::bv_medHalfX] = medHalflengthX(); values[DiamondBounds::bv_maxHalfX] = maxHalflengthX(); - values[DiamondBounds::bv_halfY1] = halflengthY1(); - values[DiamondBounds::bv_halfY2] = halflengthY2(); + values[DiamondBounds::bv_halfY1] = halflengthY1(); + values[DiamondBounds::bv_halfY2] = halflengthY2(); return values; } -bool -Acts::DiamondBounds::inside(const Acts::Vector2D& lpos, - const Acts::BoundaryCheck& bcheck) const -{ +bool Acts::DiamondBounds::inside(const Acts::Vector2D& lpos, + const Acts::BoundaryCheck& bcheck) const { return bcheck.isInside(lpos, vertices()); } -double -Acts::DiamondBounds::distanceToBoundary(const Acts::Vector2D& lpos) const -{ +double Acts::DiamondBounds::distanceToBoundary( + const Acts::Vector2D& lpos) const { return BoundaryCheck(true).distance(lpos, vertices()); } -std::vector<Acts::Vector2D> -Acts::DiamondBounds::vertices() const -{ +std::vector<Acts::Vector2D> Acts::DiamondBounds::vertices() const { // vertices starting from lower right in clock-wise order return {{minHalflengthX(), -halflengthY1()}, {medHalflengthX(), 0}, @@ -85,16 +71,12 @@ Acts::DiamondBounds::vertices() const {-minHalflengthX(), -halflengthY1()}}; } -const Acts::RectangleBounds& -Acts::DiamondBounds::boundingBox() const -{ +const Acts::RectangleBounds& Acts::DiamondBounds::boundingBox() const { return m_boundingBox; } // ostream operator overload -std::ostream& -Acts::DiamondBounds::toStream(std::ostream& sl) const -{ +std::ostream& Acts::DiamondBounds::toStream(std::ostream& sl) const { sl << std::setiosflags(std::ios::fixed); sl << std::setprecision(7); sl << "Acts::DiamondBounds: (minHlengthX, medHlengthX, maxHlengthX, " diff --git a/Core/src/Surfaces/DiscSurface.cpp b/Core/src/Surfaces/DiscSurface.cpp index facfe20ca9a0ca73af85a3cb1e063a44b4d859a5..ed510f77c7a898006044c5d0cd569e92e047257e 100644 --- a/Core/src/Surfaces/DiscSurface.cpp +++ b/Core/src/Surfaces/DiscSurface.cpp @@ -24,117 +24,90 @@ #include "Acts/Utilities/Definitions.hpp" #include "Acts/Utilities/ThrowAssert.hpp" -using Acts::VectorHelpers::phi; using Acts::VectorHelpers::perp; +using Acts::VectorHelpers::phi; Acts::DiscSurface::DiscSurface(const DiscSurface& other) - : GeometryObject(), Surface(other), m_bounds(other.m_bounds) -{ -} + : GeometryObject(), Surface(other), m_bounds(other.m_bounds) {} Acts::DiscSurface::DiscSurface(const GeometryContext& gctx, - const DiscSurface& other, - const Transform3D& transf) - : GeometryObject(), Surface(gctx, other, transf), m_bounds(other.m_bounds) -{ -} + const DiscSurface& other, + const Transform3D& transf) + : GeometryObject(), + Surface(gctx, other, transf), + m_bounds(other.m_bounds) {} Acts::DiscSurface::DiscSurface(std::shared_ptr<const Transform3D> htrans, - double rmin, - double rmax, - double hphisec) - : GeometryObject() - , Surface(std::move(htrans)) - , m_bounds(std::make_shared<const RadialBounds>(rmin, rmax, hphisec)) -{ -} + double rmin, double rmax, double hphisec) + : GeometryObject(), + Surface(std::move(htrans)), + m_bounds(std::make_shared<const RadialBounds>(rmin, rmax, hphisec)) {} Acts::DiscSurface::DiscSurface(std::shared_ptr<const Transform3D> htrans, - double minhalfx, - double maxhalfx, - double maxR, - double minR, - double avephi, - double stereo) - : GeometryObject() - , Surface(std::move(htrans)) - , m_bounds(std::make_shared<const DiscTrapezoidalBounds>(minhalfx, - maxhalfx, - maxR, - minR, - avephi, - stereo)) -{ -} + double minhalfx, double maxhalfx, double maxR, + double minR, double avephi, double stereo) + : GeometryObject(), + Surface(std::move(htrans)), + m_bounds(std::make_shared<const DiscTrapezoidalBounds>( + minhalfx, maxhalfx, maxR, minR, avephi, stereo)) {} Acts::DiscSurface::DiscSurface(std::shared_ptr<const Transform3D> htrans, - std::shared_ptr<const DiscBounds> dbounds) - : GeometryObject(), Surface(std::move(htrans)), m_bounds(std::move(dbounds)) -{ -} + std::shared_ptr<const DiscBounds> dbounds) + : GeometryObject(), + Surface(std::move(htrans)), + m_bounds(std::move(dbounds)) {} Acts::DiscSurface::DiscSurface(const std::shared_ptr<const DiscBounds>& dbounds, const DetectorElementBase& detelement) - : GeometryObject(), Surface(detelement), m_bounds(dbounds) -{ + : GeometryObject(), Surface(detelement), m_bounds(dbounds) { throw_assert(dbounds, "nullptr as DiscBounds"); } -Acts::DiscSurface& -Acts::DiscSurface::operator=(const DiscSurface& other) -{ +Acts::DiscSurface& Acts::DiscSurface::operator=(const DiscSurface& other) { if (this != &other) { Acts::Surface::operator=(other); - m_bounds = other.m_bounds; + m_bounds = other.m_bounds; } return *this; } -Acts::Surface::SurfaceType -Acts::DiscSurface::type() const -{ +Acts::Surface::SurfaceType Acts::DiscSurface::type() const { return Surface::Disc; } -void -Acts::DiscSurface::localToGlobal(const GeometryContext& gctx, - const Vector2D& lpos, - const Vector3D& /*gmom*/, - Vector3D& gpos) const -{ +void Acts::DiscSurface::localToGlobal(const GeometryContext& gctx, + const Vector2D& lpos, + const Vector3D& /*gmom*/, + Vector3D& gpos) const { // create the position in the local 3d frame Vector3D loc3Dframe(lpos[Acts::eLOC_R] * cos(lpos[Acts::eLOC_PHI]), - lpos[Acts::eLOC_R] * sin(lpos[Acts::eLOC_PHI]), - 0.); + lpos[Acts::eLOC_R] * sin(lpos[Acts::eLOC_PHI]), 0.); // transport it to the globalframe (very unlikely that this is not needed) gpos = transform(gctx) * loc3Dframe; } -bool -Acts::DiscSurface::globalToLocal(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& /*gmom*/, - Vector2D& lpos) const -{ +bool Acts::DiscSurface::globalToLocal(const GeometryContext& gctx, + const Vector3D& gpos, + const Vector3D& /*gmom*/, + Vector2D& lpos) const { // transport it to the globalframe (very unlikely that this is not needed) Vector3D loc3Dframe = (transform(gctx).inverse()) * gpos; - lpos = Acts::Vector2D(perp(loc3Dframe), phi(loc3Dframe)); + lpos = Acts::Vector2D(perp(loc3Dframe), phi(loc3Dframe)); return ((std::abs(loc3Dframe.z()) > s_onSurfaceTolerance) ? false : true); } -const Acts::Vector2D -Acts::DiscSurface::localPolarToLocalCartesian(const Vector2D& locpol) const -{ - const DiscTrapezoidalBounds* dtbo - = dynamic_cast<const Acts::DiscTrapezoidalBounds*>(&(bounds())); +const Acts::Vector2D Acts::DiscSurface::localPolarToLocalCartesian( + const Vector2D& locpol) const { + const DiscTrapezoidalBounds* dtbo = + dynamic_cast<const Acts::DiscTrapezoidalBounds*>(&(bounds())); if (dtbo != nullptr) { double rMedium = dtbo->rCenter(); - double phi = dtbo->averagePhi(); + double phi = dtbo->averagePhi(); Vector2D polarCenter(rMedium, phi); Vector2D cartCenter = localPolarToCartesian(polarCenter); - Vector2D cartPos = localPolarToCartesian(locpol); - Vector2D Pos = cartPos - cartCenter; + Vector2D cartPos = localPolarToCartesian(locpol); + Vector2D Pos = cartPos - cartCenter; Acts::Vector2D locPos( Pos[Acts::eLOC_X] * sin(phi) - Pos[Acts::eLOC_Y] * cos(phi), @@ -145,58 +118,43 @@ Acts::DiscSurface::localPolarToLocalCartesian(const Vector2D& locpol) const locpol[Acts::eLOC_R] * sin(locpol[Acts::eLOC_PHI])); } -const Acts::Vector3D -Acts::DiscSurface::localCartesianToGlobal(const GeometryContext& gctx, - const Vector2D& lpos) const -{ +const Acts::Vector3D Acts::DiscSurface::localCartesianToGlobal( + const GeometryContext& gctx, const Vector2D& lpos) const { Vector3D loc3Dframe(lpos[Acts::eLOC_X], lpos[Acts::eLOC_Y], 0.); return Vector3D(transform(gctx) * loc3Dframe); } -const Acts::Vector2D -Acts::DiscSurface::globalToLocalCartesian(const GeometryContext& gctx, - const Vector3D& gpos, - double /*unused*/) const -{ +const Acts::Vector2D Acts::DiscSurface::globalToLocalCartesian( + const GeometryContext& gctx, const Vector3D& gpos, + double /*unused*/) const { Vector3D loc3Dframe = (transform(gctx).inverse()) * gpos; return Vector2D(loc3Dframe.x(), loc3Dframe.y()); } -std::string -Acts::DiscSurface::name() const -{ +std::string Acts::DiscSurface::name() const { return "Acts::DiscSurface"; } -std::shared_ptr<Acts::DiscSurface> -Acts::DiscSurface::clone(const GeometryContext& gctx, - const Transform3D& shift) const -{ +std::shared_ptr<Acts::DiscSurface> Acts::DiscSurface::clone( + const GeometryContext& gctx, const Transform3D& shift) const { return std::shared_ptr<DiscSurface>(this->clone_impl(gctx, shift)); } -Acts::DiscSurface* -Acts::DiscSurface::clone_impl(const GeometryContext& gctx, - const Transform3D& shift) const -{ +Acts::DiscSurface* Acts::DiscSurface::clone_impl( + const GeometryContext& gctx, const Transform3D& shift) const { return new DiscSurface(gctx, *this, shift); } -const Acts::SurfaceBounds& -Acts::DiscSurface::bounds() const -{ +const Acts::SurfaceBounds& Acts::DiscSurface::bounds() const { if (m_bounds) { return (*(m_bounds.get())); } return s_noBounds; } -Acts::PolyhedronRepresentation -Acts::DiscSurface::polyhedronRepresentation(const GeometryContext& gctx, - size_t l0div, - size_t /*unused*/) const -{ - std::vector<Vector3D> vertices; +Acts::PolyhedronRepresentation Acts::DiscSurface::polyhedronRepresentation( + const GeometryContext& gctx, size_t l0div, size_t /*unused*/) const { + std::vector<Vector3D> vertices; std::vector<std::vector<size_t>> faces; if (l0div < 3) { @@ -210,8 +168,8 @@ Acts::DiscSurface::polyhedronRepresentation(const GeometryContext& gctx, } double phistep = 2 * M_PI / l0div; - double rMin = bounds->rMin(); - double rMax = bounds->rMax(); + double rMin = bounds->rMin(); + double rMax = bounds->rMax(); Vector3D inner(rMin, 0, 0); Vector3D outer(rMax, 0, 0); @@ -225,7 +183,6 @@ Acts::DiscSurface::polyhedronRepresentation(const GeometryContext& gctx, } for (size_t v = 0; v < vertices.size() - 2; v = v + 2) { - faces.push_back({v, v + 1, v + 3, v + 2}); } if (l0div > 2) { diff --git a/Core/src/Surfaces/DiscTrapezoidalBounds.cpp b/Core/src/Surfaces/DiscTrapezoidalBounds.cpp index 5ea9e62fa91917da6b7a05c97e9f13fd4cbb543d..24b5eeb2576bcfd53f451491210563095cd64193 100644 --- a/Core/src/Surfaces/DiscTrapezoidalBounds.cpp +++ b/Core/src/Surfaces/DiscTrapezoidalBounds.cpp @@ -19,69 +19,55 @@ #include "Acts/Utilities/detail/periodic.hpp" Acts::DiscTrapezoidalBounds::DiscTrapezoidalBounds(double minhalfx, - double maxhalfx, - double maxR, - double minR, - double avephi, + double maxhalfx, double maxR, + double minR, double avephi, double stereo) - : m_rMin(std::min(std::abs(minR), std::abs(maxR))) - , m_rMax(std::max(std::abs(minR), std::abs(maxR))) - , m_minHalfX(std::abs(minhalfx)) - , m_maxHalfX(std::abs(maxhalfx)) - , m_avgPhi(detail::radian_sym(avephi)) - , m_stereo(stereo) -{ -} + : m_rMin(std::min(std::abs(minR), std::abs(maxR))), + m_rMax(std::max(std::abs(minR), std::abs(maxR))), + m_minHalfX(std::abs(minhalfx)), + m_maxHalfX(std::abs(maxhalfx)), + m_avgPhi(detail::radian_sym(avephi)), + m_stereo(stereo) {} Acts::DiscTrapezoidalBounds::~DiscTrapezoidalBounds() = default; -Acts::DiscTrapezoidalBounds* -Acts::DiscTrapezoidalBounds::clone() const -{ +Acts::DiscTrapezoidalBounds* Acts::DiscTrapezoidalBounds::clone() const { return new DiscTrapezoidalBounds(*this); } -Acts::SurfaceBounds::BoundsType -Acts::DiscTrapezoidalBounds::type() const -{ +Acts::SurfaceBounds::BoundsType Acts::DiscTrapezoidalBounds::type() const { return SurfaceBounds::DiscTrapezoidal; } -std::vector<TDD_real_t> -Acts::DiscTrapezoidalBounds::valueStore() const -{ +std::vector<TDD_real_t> Acts::DiscTrapezoidalBounds::valueStore() const { std::vector<TDD_real_t> values(DiscTrapezoidalBounds::bv_length); - values[bv_rMin] = rMin(); - values[bv_rMax] = rMax(); - values[bv_minHalfX] = minHalflengthX(); - values[bv_maxHalfX] = maxHalflengthX(); + values[bv_rMin] = rMin(); + values[bv_rMax] = rMax(); + values[bv_minHalfX] = minHalflengthX(); + values[bv_maxHalfX] = maxHalflengthX(); values[bv_averagePhi] = averagePhi(); - values[bv_stereo] = m_stereo; + values[bv_stereo] = m_stereo; return values; } -Acts::Vector2D -Acts::DiscTrapezoidalBounds::toLocalXY(const Acts::Vector2D& lpos) const -{ +Acts::Vector2D Acts::DiscTrapezoidalBounds::toLocalXY( + const Acts::Vector2D& lpos) const { return {lpos[eLOC_R] * std::sin(lpos[eLOC_PHI] - m_avgPhi), lpos[eLOC_R] * std::cos(lpos[eLOC_PHI] - m_avgPhi)}; } -Acts::ActsMatrixD<2, 2> -Acts::DiscTrapezoidalBounds::jacobianToLocalXY(const Acts::Vector2D& lpos) const -{ +Acts::ActsMatrixD<2, 2> Acts::DiscTrapezoidalBounds::jacobianToLocalXY( + const Acts::Vector2D& lpos) const { ActsMatrixD<2, 2> jacobian; - jacobian(0, eLOC_R) = std::sin(lpos[eLOC_PHI] - m_avgPhi); - jacobian(1, eLOC_R) = std::cos(lpos[eLOC_PHI] - m_avgPhi); + jacobian(0, eLOC_R) = std::sin(lpos[eLOC_PHI] - m_avgPhi); + jacobian(1, eLOC_R) = std::cos(lpos[eLOC_PHI] - m_avgPhi); jacobian(0, eLOC_PHI) = lpos[eLOC_R] * std::cos(lpos[eLOC_PHI]); jacobian(1, eLOC_PHI) = lpos[eLOC_R] * -std::sin(lpos[eLOC_PHI]); return jacobian; } -bool -Acts::DiscTrapezoidalBounds::inside(const Acts::Vector2D& lpos, - const Acts::BoundaryCheck& bcheck) const -{ +bool Acts::DiscTrapezoidalBounds::inside( + const Acts::Vector2D& lpos, const Acts::BoundaryCheck& bcheck) const { Vector2D vertices[] = {{minHalflengthX(), rMin()}, {maxHalflengthX(), rMax()}, {-maxHalflengthX(), rMax()}, @@ -90,10 +76,8 @@ Acts::DiscTrapezoidalBounds::inside(const Acts::Vector2D& lpos, return bcheck.transformed(jacobian).isInside(toLocalXY(lpos), vertices); } -double -Acts::DiscTrapezoidalBounds::distanceToBoundary( - const Acts::Vector2D& lpos) const -{ +double Acts::DiscTrapezoidalBounds::distanceToBoundary( + const Acts::Vector2D& lpos) const { Vector2D vertices[] = {{minHalflengthX(), rMin()}, {maxHalflengthX(), rMax()}, {-maxHalflengthX(), rMax()}, @@ -102,9 +86,7 @@ Acts::DiscTrapezoidalBounds::distanceToBoundary( } // ostream operator overload -std::ostream& -Acts::DiscTrapezoidalBounds::toStream(std::ostream& sl) const -{ +std::ostream& Acts::DiscTrapezoidalBounds::toStream(std::ostream& sl) const { sl << std::setiosflags(std::ios::fixed); sl << std::setprecision(7); sl << "Acts::DiscTrapezoidalBounds: (innerRadius, outerRadius, hMinX, " diff --git a/Core/src/Surfaces/EllipseBounds.cpp b/Core/src/Surfaces/EllipseBounds.cpp index 119421856567d2c4ed83423bb2b3e6fa898c7b09..0c96931feca194e78a85a16e5e05fb3e1a8a7b29 100644 --- a/Core/src/Surfaces/EllipseBounds.cpp +++ b/Core/src/Surfaces/EllipseBounds.cpp @@ -19,76 +19,60 @@ #include "Acts/Utilities/Helpers.hpp" #include "Acts/Utilities/detail/periodic.hpp" -using Acts::VectorHelpers::phi; using Acts::VectorHelpers::perp; +using Acts::VectorHelpers::phi; -Acts::EllipseBounds::EllipseBounds(double minRadius0, - double minRadius1, - double maxRadius0, - double maxRadius1, - double averagePhi, - double halfPhi) - : m_rMinX(std::abs(minRadius0)) - , m_rMinY(std::abs(minRadius1)) - , m_rMaxX(std::abs(maxRadius0)) - , m_rMaxY(std::abs(maxRadius1)) - , m_avgPhi(detail::radian_sym(averagePhi)) - , m_halfPhi(std::abs(halfPhi)) - , m_boundingBox(std::max(minRadius0, maxRadius0), - std::max(minRadius1, maxRadius1)) -{ -} +Acts::EllipseBounds::EllipseBounds(double minRadius0, double minRadius1, + double maxRadius0, double maxRadius1, + double averagePhi, double halfPhi) + : m_rMinX(std::abs(minRadius0)), + m_rMinY(std::abs(minRadius1)), + m_rMaxX(std::abs(maxRadius0)), + m_rMaxY(std::abs(maxRadius1)), + m_avgPhi(detail::radian_sym(averagePhi)), + m_halfPhi(std::abs(halfPhi)), + m_boundingBox(std::max(minRadius0, maxRadius0), + std::max(minRadius1, maxRadius1)) {} Acts::EllipseBounds::~EllipseBounds() = default; -Acts::EllipseBounds* -Acts::EllipseBounds::clone() const -{ +Acts::EllipseBounds* Acts::EllipseBounds::clone() const { return new EllipseBounds(*this); } -Acts::SurfaceBounds::BoundsType -Acts::EllipseBounds::type() const -{ +Acts::SurfaceBounds::BoundsType Acts::EllipseBounds::type() const { return SurfaceBounds::Ellipse; } -std::vector<TDD_real_t> -Acts::EllipseBounds::valueStore() const -{ +std::vector<TDD_real_t> Acts::EllipseBounds::valueStore() const { std::vector<TDD_real_t> values(EllipseBounds::bv_length); - values[EllipseBounds::bv_rMinX] = m_rMinX; - values[EllipseBounds::bv_rMinY] = m_rMinY; - values[EllipseBounds::bv_rMaxX] = m_rMaxX; - values[EllipseBounds::bv_rMaxY] = m_rMaxY; - values[EllipseBounds::bv_averagePhi] = m_avgPhi; + values[EllipseBounds::bv_rMinX] = m_rMinX; + values[EllipseBounds::bv_rMinY] = m_rMinY; + values[EllipseBounds::bv_rMaxX] = m_rMaxX; + values[EllipseBounds::bv_rMaxY] = m_rMaxY; + values[EllipseBounds::bv_averagePhi] = m_avgPhi; values[EllipseBounds::bv_halfPhiSector] = m_halfPhi; return values; } -static inline double -square(double x) -{ +static inline double square(double x) { return x * x; } /// @warning This **only** works for tolerance-based checks -bool -Acts::EllipseBounds::inside(const Acts::Vector2D& lpos, - const Acts::BoundaryCheck& bcheck) const -{ - double tol0 = bcheck.m_tolerance[0]; - double tol1 = bcheck.m_tolerance[1]; - double phi = detail::radian_sym(VectorHelpers::phi(lpos) - averagePhi()); +bool Acts::EllipseBounds::inside(const Acts::Vector2D& lpos, + const Acts::BoundaryCheck& bcheck) const { + double tol0 = bcheck.m_tolerance[0]; + double tol1 = bcheck.m_tolerance[1]; + double phi = detail::radian_sym(VectorHelpers::phi(lpos) - averagePhi()); double phiHalf = halfPhiSector() + tol1; - bool insidePhi = (-phiHalf <= phi) && (phi < phiHalf); - bool insideInner = (rMinX() <= tol0) || (rMinY() <= tol0) - || (1 < (square(lpos[Acts::eLOC_X] / (rMinX() - tol0)) - + square(lpos[Acts::eLOC_Y] / (rMinY() - tol0)))); - bool insideOuter = ((square(lpos[Acts::eLOC_X] / (rMaxX() + tol0)) - + square(lpos[Acts::eLOC_Y] / (rMaxY() + tol0))) - < 1); + bool insidePhi = (-phiHalf <= phi) && (phi < phiHalf); + bool insideInner = (rMinX() <= tol0) || (rMinY() <= tol0) || + (1 < (square(lpos[Acts::eLOC_X] / (rMinX() - tol0)) + + square(lpos[Acts::eLOC_Y] / (rMinY() - tol0)))); + bool insideOuter = ((square(lpos[Acts::eLOC_X] / (rMaxX() + tol0)) + + square(lpos[Acts::eLOC_Y] / (rMaxY() + tol0))) < 1); return (insidePhi && insideInner && insideOuter); } @@ -98,9 +82,7 @@ Acts::EllipseBounds::inside(const Acts::Vector2D& lpos, // and m_valueStore.at(EllipseBounds::bv_rMaxX) ~= // m_valueStore.at(EllipseBounds::bv_rMaxY) // -double -Acts::EllipseBounds::distanceToBoundary(const Vector2D& lpos) const -{ +double Acts::EllipseBounds::distanceToBoundary(const Vector2D& lpos) const { double r = perp(lpos); if (r == 0) { return std::min(rMinX(), rMinY()); @@ -113,7 +95,7 @@ Acts::EllipseBounds::distanceToBoundary(const Vector2D& lpos) const if (m_halfPhi < M_PI) { double df = std::abs(dF) - m_halfPhi; - sf = r * std::sin(df); + sf = r * std::sin(df); if (df > 0.) { r *= std::cos(df); } @@ -122,14 +104,14 @@ Acts::EllipseBounds::distanceToBoundary(const Vector2D& lpos) const } if (sf <= 0.) { - double a = cs / m_rMaxX; - double b = sn / m_rMaxY; + double a = cs / m_rMaxX; + double b = sn / m_rMaxY; double sr0 = r - 1. / std::hypot(a, b); if (sr0 >= 0.) { return sr0; } - a = cs / m_rMinX; - b = sn / m_rMinY; + a = cs / m_rMinX; + b = sn / m_rMinY; double sr1 = 1. / std::hypot(a, b) - r; if (sr1 >= 0.) { return sr1; @@ -144,17 +126,17 @@ Acts::EllipseBounds::distanceToBoundary(const Vector2D& lpos) const } double fb; - fb = (dF > 0.) ? (m_avgPhi + m_halfPhi) : (m_avgPhi - m_halfPhi); - sn = sin(fb); - cs = cos(fb); - double a = cs / m_rMaxX; - double b = sn / m_rMaxY; + fb = (dF > 0.) ? (m_avgPhi + m_halfPhi) : (m_avgPhi - m_halfPhi); + sn = sin(fb); + cs = cos(fb); + double a = cs / m_rMaxX; + double b = sn / m_rMaxY; double sr0 = r - 1. / std::hypot(a, b); if (sr0 >= 0.) { return std::hypot(sr0, sf); } - a = cs / m_rMinX; - b = sn / m_rMinY; + a = cs / m_rMinX; + b = sn / m_rMinY; double sr1 = (1. / std::hypot(a, b)) - r; if (sr1 >= 0.) { return std::hypot(sr1, sf); @@ -162,23 +144,17 @@ Acts::EllipseBounds::distanceToBoundary(const Vector2D& lpos) const return sf; } -std::vector<Acts::Vector2D> -Acts::EllipseBounds::vertices() const -{ +std::vector<Acts::Vector2D> Acts::EllipseBounds::vertices() const { // 2017-04-08 msmk: this is definitely too coarse return {{rMaxX(), 0}, {0, rMaxY()}, {-rMaxX(), 0}, {0, -rMaxY()}}; } -const Acts::RectangleBounds& -Acts::EllipseBounds::boundingBox() const -{ +const Acts::RectangleBounds& Acts::EllipseBounds::boundingBox() const { return m_boundingBox; } // ostream operator overload -std::ostream& -Acts::EllipseBounds::toStream(std::ostream& sl) const -{ +std::ostream& Acts::EllipseBounds::toStream(std::ostream& sl) const { sl << std::setiosflags(std::ios::fixed); sl << std::setprecision(7); sl << "Acts::EllipseBounds: (innerRadiusX, innerRadiusY, outerRadiusX, " diff --git a/Core/src/Surfaces/LineBounds.cpp b/Core/src/Surfaces/LineBounds.cpp index da7e9e2362e910a2f913db85a844c626ab7f7a94..75b069c00410a7e98621eee94bd59964f31cb237 100644 --- a/Core/src/Surfaces/LineBounds.cpp +++ b/Core/src/Surfaces/LineBounds.cpp @@ -16,52 +16,38 @@ #include <iostream> Acts::LineBounds::LineBounds(double radius, double halez) - : m_radius(std::abs(radius)), m_halfZ(std::abs(halez)) -{ -} + : m_radius(std::abs(radius)), m_halfZ(std::abs(halez)) {} Acts::LineBounds::~LineBounds() = default; -Acts::LineBounds* -Acts::LineBounds::clone() const -{ +Acts::LineBounds* Acts::LineBounds::clone() const { return new LineBounds(*this); } -Acts::SurfaceBounds::BoundsType -Acts::LineBounds::type() const -{ +Acts::SurfaceBounds::BoundsType Acts::LineBounds::type() const { return SurfaceBounds::Line; } -std::vector<TDD_real_t> -Acts::LineBounds::valueStore() const -{ +std::vector<TDD_real_t> Acts::LineBounds::valueStore() const { std::vector<TDD_real_t> values(LineBounds::bv_length); values[LineBounds::bv_radius] = r(); - values[LineBounds::bv_halfZ] = halflengthZ(); + values[LineBounds::bv_halfZ] = halflengthZ(); return values; } -bool -Acts::LineBounds::inside(const Acts::Vector2D& lpos, - const Acts::BoundaryCheck& bcheck) const -{ - return bcheck.isInside( - lpos, Vector2D(0, -halflengthZ()), Vector2D(r(), halflengthZ())); +bool Acts::LineBounds::inside(const Acts::Vector2D& lpos, + const Acts::BoundaryCheck& bcheck) const { + return bcheck.isInside(lpos, Vector2D(0, -halflengthZ()), + Vector2D(r(), halflengthZ())); } -double -Acts::LineBounds::distanceToBoundary(const Acts::Vector2D& lpos) const -{ +double Acts::LineBounds::distanceToBoundary(const Acts::Vector2D& lpos) const { // per definition the min Distance of a correct local position is r return lpos[Acts::eLOC_R]; } // ostream operator overload -std::ostream& -Acts::LineBounds::toStream(std::ostream& sl) const -{ +std::ostream& Acts::LineBounds::toStream(std::ostream& sl) const { sl << std::setiosflags(std::ios::fixed); sl << std::setprecision(7); sl << "Acts::LineBounds: (radius, halflengthInZ) = "; diff --git a/Core/src/Surfaces/LineSurface.cpp b/Core/src/Surfaces/LineSurface.cpp index bffdd9add9581f7333049b41459195e8d0eb370e..e165be96306e7ba326ad18967685347703cc70b9 100644 --- a/Core/src/Surfaces/LineSurface.cpp +++ b/Core/src/Surfaces/LineSurface.cpp @@ -20,45 +20,37 @@ #include "Acts/Utilities/ThrowAssert.hpp" Acts::LineSurface::LineSurface(std::shared_ptr<const Transform3D> htrans, - double radius, - double halez) - : GeometryObject() - , Surface(std::move(htrans)) - , m_bounds(std::make_shared<const LineBounds>(radius, halez)) -{ -} + double radius, double halez) + : GeometryObject(), + Surface(std::move(htrans)), + m_bounds(std::make_shared<const LineBounds>(radius, halez)) {} Acts::LineSurface::LineSurface(std::shared_ptr<const Transform3D> htrans, - std::shared_ptr<const LineBounds> lbounds) - : GeometryObject(), Surface(std::move(htrans)), m_bounds(std::move(lbounds)) -{ -} + std::shared_ptr<const LineBounds> lbounds) + : GeometryObject(), + Surface(std::move(htrans)), + m_bounds(std::move(lbounds)) {} Acts::LineSurface::LineSurface(const std::shared_ptr<const LineBounds>& lbounds, const DetectorElementBase& detelement) - : GeometryObject(), Surface(detelement), m_bounds(lbounds) -{ + : GeometryObject(), Surface(detelement), m_bounds(lbounds) { throw_assert(lbounds, "LineBounds must not be nullptr"); } Acts::LineSurface::LineSurface(const LineSurface& other) - : GeometryObject(), Surface(other), m_bounds(other.m_bounds) -{ -} + : GeometryObject(), Surface(other), m_bounds(other.m_bounds) {} Acts::LineSurface::LineSurface(const GeometryContext& gctx, - const LineSurface& other, - const Transform3D& transf) - : GeometryObject(), Surface(gctx, other, transf), m_bounds(other.m_bounds) -{ -} + const LineSurface& other, + const Transform3D& transf) + : GeometryObject(), + Surface(gctx, other, transf), + m_bounds(other.m_bounds) {} -Acts::LineSurface& -Acts::LineSurface::operator=(const LineSurface& other) -{ +Acts::LineSurface& Acts::LineSurface::operator=(const LineSurface& other) { if (this != &other) { Surface::operator=(other); - m_bounds = other.m_bounds; + m_bounds = other.m_bounds; } return *this; } diff --git a/Core/src/Surfaces/PerigeeSurface.cpp b/Core/src/Surfaces/PerigeeSurface.cpp index 3b310e4d0849efc6e4006ccaf082db8695629b80..18e6dd5803eb4377cdea3688cc819775dd3d4537 100644 --- a/Core/src/Surfaces/PerigeeSurface.cpp +++ b/Core/src/Surfaces/PerigeeSurface.cpp @@ -17,69 +17,51 @@ #include <utility> Acts::PerigeeSurface::PerigeeSurface(const Vector3D& gp) - : LineSurface(nullptr, nullptr) -{ + : LineSurface(nullptr, nullptr) { Surface::m_transform = std::make_shared<const Transform3D>( Translation3D(gp.x(), gp.y(), gp.z())); } Acts::PerigeeSurface::PerigeeSurface( std::shared_ptr<const Transform3D> tTransform) - : GeometryObject(), LineSurface(std::move(tTransform)) -{ -} + : GeometryObject(), LineSurface(std::move(tTransform)) {} Acts::PerigeeSurface::PerigeeSurface(const PerigeeSurface& other) - : GeometryObject(), LineSurface(other) -{ -} + : GeometryObject(), LineSurface(other) {} Acts::PerigeeSurface::PerigeeSurface(const GeometryContext& gctx, - const PerigeeSurface& other, - const Transform3D& transf) - : GeometryObject(), LineSurface(gctx, other, transf) -{ -} + const PerigeeSurface& other, + const Transform3D& transf) + : GeometryObject(), LineSurface(gctx, other, transf) {} -Acts::PerigeeSurface& -Acts::PerigeeSurface::operator=(const PerigeeSurface& other) -{ +Acts::PerigeeSurface& Acts::PerigeeSurface::operator=( + const PerigeeSurface& other) { if (this != &other) { LineSurface::operator=(other); } return *this; } -std::shared_ptr<Acts::PerigeeSurface> -Acts::PerigeeSurface::clone(const GeometryContext& gctx, - const Transform3D& shift) const -{ +std::shared_ptr<Acts::PerigeeSurface> Acts::PerigeeSurface::clone( + const GeometryContext& gctx, const Transform3D& shift) const { return std::shared_ptr<PerigeeSurface>(this->clone_impl(gctx, shift)); } -Acts::PerigeeSurface* -Acts::PerigeeSurface::clone_impl(const GeometryContext& gctx, - const Transform3D& shift) const -{ +Acts::PerigeeSurface* Acts::PerigeeSurface::clone_impl( + const GeometryContext& gctx, const Transform3D& shift) const { return new PerigeeSurface(gctx, *this, shift); } -Acts::Surface::SurfaceType -Acts::PerigeeSurface::type() const -{ +Acts::Surface::SurfaceType Acts::PerigeeSurface::type() const { return Surface::Perigee; } -std::string -Acts::PerigeeSurface::name() const -{ +std::string Acts::PerigeeSurface::name() const { return "Acts::PerigeeSurface"; } -std::ostream& -Acts::PerigeeSurface::toStream(const GeometryContext& gctx, - std::ostream& sl) const -{ +std::ostream& Acts::PerigeeSurface::toStream(const GeometryContext& gctx, + std::ostream& sl) const { sl << std::setiosflags(std::ios::fixed); sl << std::setprecision(7); sl << "Acts::PerigeeSurface:" << std::endl; diff --git a/Core/src/Surfaces/PlaneSurface.cpp b/Core/src/Surfaces/PlaneSurface.cpp index b14b7da9b191509a276de7896d86559ed021d66d..d3e1bd431037528382421a0cb1a8056195a1bffe 100644 --- a/Core/src/Surfaces/PlaneSurface.cpp +++ b/Core/src/Surfaces/PlaneSurface.cpp @@ -21,29 +21,26 @@ #include "Acts/Utilities/ThrowAssert.hpp" Acts::PlaneSurface::PlaneSurface(const PlaneSurface& other) - : GeometryObject(), Surface(other), m_bounds(other.m_bounds) -{ -} + : GeometryObject(), Surface(other), m_bounds(other.m_bounds) {} Acts::PlaneSurface::PlaneSurface(const GeometryContext& gctx, - const PlaneSurface& other, - const Transform3D& transf) - : GeometryObject(), Surface(gctx, other, transf), m_bounds(other.m_bounds) -{ -} + const PlaneSurface& other, + const Transform3D& transf) + : GeometryObject(), + Surface(gctx, other, transf), + m_bounds(other.m_bounds) {} Acts::PlaneSurface::PlaneSurface(const Vector3D& center, const Vector3D& normal) - : Surface(), m_bounds(nullptr) -{ + : Surface(), m_bounds(nullptr) { /// the right-handed coordinate system is defined as /// T = normal /// U = Z x T if T not parallel to Z otherwise U = X x T /// V = T x U Vector3D T = normal.normalized(); Vector3D U = std::abs(T.dot(Vector3D::UnitZ())) < s_curvilinearProjTolerance - ? Vector3D::UnitZ().cross(T).normalized() - : Vector3D::UnitX().cross(T).normalized(); - Vector3D V = T.cross(U); + ? Vector3D::UnitZ().cross(T).normalized() + : Vector3D::UnitX().cross(T).normalized(); + Vector3D V = T.cross(U); RotationMatrix3D curvilinearRotation; curvilinearRotation.col(0) = U; curvilinearRotation.col(1) = V; @@ -57,84 +54,65 @@ Acts::PlaneSurface::PlaneSurface(const Vector3D& center, const Vector3D& normal) Acts::PlaneSurface::PlaneSurface( const std::shared_ptr<const PlanarBounds>& pbounds, - const Acts::DetectorElementBase& detelement) - : Surface(detelement), m_bounds(pbounds) -{ + const Acts::DetectorElementBase& detelement) + : Surface(detelement), m_bounds(pbounds) { /// surfaces representing a detector element must have bounds throw_assert(pbounds, "PlaneBounds must not be nullptr"); } -Acts::PlaneSurface::PlaneSurface(std::shared_ptr<const Transform3D> htrans, +Acts::PlaneSurface::PlaneSurface(std::shared_ptr<const Transform3D> htrans, std::shared_ptr<const PlanarBounds> pbounds) - : Surface(std::move(htrans)), m_bounds(std::move(pbounds)) -{ -} + : Surface(std::move(htrans)), m_bounds(std::move(pbounds)) {} -Acts::PlaneSurface& -Acts::PlaneSurface::operator=(const PlaneSurface& other) -{ +Acts::PlaneSurface& Acts::PlaneSurface::operator=(const PlaneSurface& other) { if (this != &other) { Surface::operator=(other); - m_bounds = other.m_bounds; + m_bounds = other.m_bounds; } return *this; } -Acts::Surface::SurfaceType -Acts::PlaneSurface::type() const -{ +Acts::Surface::SurfaceType Acts::PlaneSurface::type() const { return Surface::Plane; } -void -Acts::PlaneSurface::localToGlobal(const GeometryContext& gctx, - const Vector2D& lpos, - const Vector3D& /*gmom*/, - Vector3D& gpos) const -{ +void Acts::PlaneSurface::localToGlobal(const GeometryContext& gctx, + const Vector2D& lpos, + const Vector3D& /*gmom*/, + Vector3D& gpos) const { Vector3D loc3Dframe(lpos[Acts::eLOC_X], lpos[Acts::eLOC_Y], 0.); /// the chance that there is no transform is almost 0, let's apply it gpos = transform(gctx) * loc3Dframe; } -bool -Acts::PlaneSurface::globalToLocal(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& /*gmom*/, - Acts::Vector2D& lpos) const -{ +bool Acts::PlaneSurface::globalToLocal(const GeometryContext& gctx, + const Vector3D& gpos, + const Vector3D& /*gmom*/, + Acts::Vector2D& lpos) const { /// the chance that there is no transform is almost 0, let's apply it Vector3D loc3Dframe = (transform(gctx).inverse()) * gpos; - lpos = Vector2D(loc3Dframe.x(), loc3Dframe.y()); - return ((loc3Dframe.z() * loc3Dframe.z() - > s_onSurfaceTolerance * s_onSurfaceTolerance) + lpos = Vector2D(loc3Dframe.x(), loc3Dframe.y()); + return ((loc3Dframe.z() * loc3Dframe.z() > + s_onSurfaceTolerance * s_onSurfaceTolerance) ? false : true); } -std::string -Acts::PlaneSurface::name() const -{ +std::string Acts::PlaneSurface::name() const { return "Acts::PlaneSurface"; } -std::shared_ptr<Acts::PlaneSurface> -Acts::PlaneSurface::clone(const GeometryContext& gctx, - const Transform3D& shift) const -{ +std::shared_ptr<Acts::PlaneSurface> Acts::PlaneSurface::clone( + const GeometryContext& gctx, const Transform3D& shift) const { return std::shared_ptr<PlaneSurface>(this->clone_impl(gctx, shift)); } -Acts::PlaneSurface* -Acts::PlaneSurface::clone_impl(const GeometryContext& gctx, - const Transform3D& shift) const -{ +Acts::PlaneSurface* Acts::PlaneSurface::clone_impl( + const GeometryContext& gctx, const Transform3D& shift) const { return new PlaneSurface(gctx, *this, shift); } -const Acts::SurfaceBounds& -Acts::PlaneSurface::bounds() const -{ +const Acts::SurfaceBounds& Acts::PlaneSurface::bounds() const { if (m_bounds) { return (*m_bounds.get()); } diff --git a/Core/src/Surfaces/PolyhedronRepresentation.cpp b/Core/src/Surfaces/PolyhedronRepresentation.cpp index b9bb19e2e9660d8c799bf0937a1e9401f13388d3..6d37aae75983bf15455402eb59e6acee7a3d0664 100644 --- a/Core/src/Surfaces/PolyhedronRepresentation.cpp +++ b/Core/src/Surfaces/PolyhedronRepresentation.cpp @@ -10,9 +10,7 @@ #include "Acts/Surfaces/PolyhedronRepresentation.hpp" -std::string -Acts::PolyhedronRepresentation::objString(size_t vtxOffset) const -{ +std::string Acts::PolyhedronRepresentation::objString(size_t vtxOffset) const { std::stringstream sstr; for (const auto& vtx : vertices) { diff --git a/Core/src/Surfaces/RadialBounds.cpp b/Core/src/Surfaces/RadialBounds.cpp index 175e31ace772f4b9f187b2647ed963fd1d49f672..3772d8136b50ec6a9bff059ae6eeda9e3b4d1334 100644 --- a/Core/src/Surfaces/RadialBounds.cpp +++ b/Core/src/Surfaces/RadialBounds.cpp @@ -19,76 +19,56 @@ #include "Acts/Utilities/detail/periodic.hpp" Acts::RadialBounds::RadialBounds(double minrad, double maxrad, double hphisec) - : RadialBounds(minrad, maxrad, 0, hphisec) -{ -} + : RadialBounds(minrad, maxrad, 0, hphisec) {} -Acts::RadialBounds::RadialBounds(double minrad, - double maxrad, - double avephi, +Acts::RadialBounds::RadialBounds(double minrad, double maxrad, double avephi, double hphisec) - : m_rMin(std::min(minrad, maxrad)) - , m_rMax(std::max(minrad, maxrad)) - , m_avgPhi(detail::radian_sym(avephi)) - , m_halfPhi(std::abs(hphisec)) -{ -} + : m_rMin(std::min(minrad, maxrad)), + m_rMax(std::max(minrad, maxrad)), + m_avgPhi(detail::radian_sym(avephi)), + m_halfPhi(std::abs(hphisec)) {} Acts::RadialBounds::~RadialBounds() = default; -Acts::RadialBounds* -Acts::RadialBounds::clone() const -{ +Acts::RadialBounds* Acts::RadialBounds::clone() const { return new RadialBounds(*this); } -Acts::SurfaceBounds::BoundsType -Acts::RadialBounds::type() const -{ +Acts::SurfaceBounds::BoundsType Acts::RadialBounds::type() const { return SurfaceBounds::Disc; } -std::vector<TDD_real_t> -Acts::RadialBounds::valueStore() const -{ +std::vector<TDD_real_t> Acts::RadialBounds::valueStore() const { std::vector<TDD_real_t> values(RadialBounds::bv_length); - values[RadialBounds::bv_rMin] = rMin(); - values[RadialBounds::bv_rMax] = rMax(); - values[RadialBounds::bv_averagePhi] = averagePhi(); + values[RadialBounds::bv_rMin] = rMin(); + values[RadialBounds::bv_rMax] = rMax(); + values[RadialBounds::bv_averagePhi] = averagePhi(); values[RadialBounds::bv_halfPhiSector] = halfPhiSector(); return values; } -Acts::Vector2D -Acts::RadialBounds::shifted(const Acts::Vector2D& lpos) const -{ +Acts::Vector2D Acts::RadialBounds::shifted(const Acts::Vector2D& lpos) const { Vector2D tmp; - tmp[eLOC_R] = lpos[eLOC_R]; + tmp[eLOC_R] = lpos[eLOC_R]; tmp[eLOC_PHI] = detail::radian_sym(lpos[eLOC_PHI] - averagePhi()); return tmp; } -bool -Acts::RadialBounds::inside(const Acts::Vector2D& lpos, - const Acts::BoundaryCheck& bcheck) const -{ - return bcheck.isInside(shifted(lpos), - Vector2D(rMin(), -halfPhiSector()), +bool Acts::RadialBounds::inside(const Acts::Vector2D& lpos, + const Acts::BoundaryCheck& bcheck) const { + return bcheck.isInside(shifted(lpos), Vector2D(rMin(), -halfPhiSector()), Vector2D(rMax(), halfPhiSector())); } -double -Acts::RadialBounds::distanceToBoundary(const Acts::Vector2D& lpos) const -{ +double Acts::RadialBounds::distanceToBoundary( + const Acts::Vector2D& lpos) const { return BoundaryCheck(true).distance(shifted(lpos), Vector2D(rMin(), -halfPhiSector()), Vector2D(rMax(), halfPhiSector())); } // ostream operator overload -std::ostream& -Acts::RadialBounds::toStream(std::ostream& sl) const -{ +std::ostream& Acts::RadialBounds::toStream(std::ostream& sl) const { sl << std::setiosflags(std::ios::fixed); sl << std::setprecision(7); sl << "Acts::RadialBounds: (innerRadius, outerRadius, hPhiSector) = "; diff --git a/Core/src/Surfaces/RectangleBounds.cpp b/Core/src/Surfaces/RectangleBounds.cpp index 2bf59924a265224952f8b66297e2c9e032b86c2b..5341857026cd26fa84435ae6268b876dc6d3beab 100644 --- a/Core/src/Surfaces/RectangleBounds.cpp +++ b/Core/src/Surfaces/RectangleBounds.cpp @@ -18,62 +18,48 @@ #include <iostream> Acts::RectangleBounds::RectangleBounds(double halex, double haley) - : m_min(-halex, -haley), m_max(halex, haley) -{ -} + : m_min(-halex, -haley), m_max(halex, haley) {} Acts::RectangleBounds::RectangleBounds(const Vector2D& vmin, const Vector2D& vmax) - : m_min(vmin), m_max(vmax) -{ -} + : m_min(vmin), m_max(vmax) {} -Acts::RectangleBounds* -Acts::RectangleBounds::clone() const -{ +Acts::RectangleBounds* Acts::RectangleBounds::clone() const { return new RectangleBounds(*this); } -std::vector<TDD_real_t> -Acts::RectangleBounds::valueStore() const -{ +std::vector<TDD_real_t> Acts::RectangleBounds::valueStore() const { std::vector<TDD_real_t> values(RectangleBounds::bv_length); values = {m_min.x(), m_min.y(), m_max.x(), m_max.y()}; return values; } -bool -Acts::RectangleBounds::inside(const Acts::Vector2D& lpos, - const Acts::BoundaryCheck& bcheck) const -{ +bool Acts::RectangleBounds::inside(const Acts::Vector2D& lpos, + const Acts::BoundaryCheck& bcheck) const { return bcheck.isInside(lpos, m_min, m_max); } -double -Acts::RectangleBounds::distanceToBoundary(const Acts::Vector2D& lpos) const -{ +double Acts::RectangleBounds::distanceToBoundary( + const Acts::Vector2D& lpos) const { return BoundaryCheck(true).distance(lpos, m_min, m_max); } -std::vector<Acts::Vector2D> -Acts::RectangleBounds::vertices() const -{ +std::vector<Acts::Vector2D> Acts::RectangleBounds::vertices() const { // counter-clockwise starting from bottom-right corner return { - {m_max.x(), m_min.y()}, m_max, {m_min.x(), m_max.y()}, m_min, + {m_max.x(), m_min.y()}, + m_max, + {m_min.x(), m_max.y()}, + m_min, }; } -const Acts::RectangleBounds& -Acts::RectangleBounds::boundingBox() const -{ +const Acts::RectangleBounds& Acts::RectangleBounds::boundingBox() const { return (*this); } // ostream operator overload -std::ostream& -Acts::RectangleBounds::toStream(std::ostream& sl) const -{ +std::ostream& Acts::RectangleBounds::toStream(std::ostream& sl) const { sl << std::setiosflags(std::ios::fixed); sl << std::setprecision(7); sl << "Acts::RectangleBounds: (hlX, hlY) = " diff --git a/Core/src/Surfaces/StrawSurface.cpp b/Core/src/Surfaces/StrawSurface.cpp index a2ade50a7d3f964242cfb2773cce0c4ec261d38f..f8d55714f2dcf859212a8b34aecb4809bf46db14 100644 --- a/Core/src/Surfaces/StrawSurface.cpp +++ b/Core/src/Surfaces/StrawSurface.cpp @@ -20,67 +20,47 @@ #include "Acts/Surfaces/InfiniteBounds.hpp" Acts::StrawSurface::StrawSurface(std::shared_ptr<const Transform3D> htrans, - double radius, - double halez) - : GeometryObject(), LineSurface(std::move(htrans), radius, halez) -{ -} + double radius, double halez) + : GeometryObject(), LineSurface(std::move(htrans), radius, halez) {} Acts::StrawSurface::StrawSurface(std::shared_ptr<const Transform3D> htrans, - std::shared_ptr<const LineBounds> lbounds) - : GeometryObject(), LineSurface(std::move(htrans), std::move(lbounds)) -{ -} + std::shared_ptr<const LineBounds> lbounds) + : GeometryObject(), LineSurface(std::move(htrans), std::move(lbounds)) {} Acts::StrawSurface::StrawSurface( const std::shared_ptr<const LineBounds>& lbounds, - const DetectorElementBase& detelement) - : GeometryObject(), LineSurface(lbounds, detelement) -{ -} + const DetectorElementBase& detelement) + : GeometryObject(), LineSurface(lbounds, detelement) {} Acts::StrawSurface::StrawSurface(const Acts::StrawSurface& other) - : GeometryObject(), LineSurface(other) -{ -} + : GeometryObject(), LineSurface(other) {} Acts::StrawSurface::StrawSurface(const GeometryContext& gctx, - const StrawSurface& other, - const Transform3D& transf) - : GeometryObject(), LineSurface(gctx, other, transf) -{ -} + const StrawSurface& other, + const Transform3D& transf) + : GeometryObject(), LineSurface(gctx, other, transf) {} -Acts::StrawSurface& -Acts::StrawSurface::operator=(const StrawSurface& other) -{ +Acts::StrawSurface& Acts::StrawSurface::operator=(const StrawSurface& other) { if (this != &other) { LineSurface::operator=(other); - m_bounds = other.m_bounds; + m_bounds = other.m_bounds; } return *this; } -std::shared_ptr<Acts::StrawSurface> -Acts::StrawSurface::clone(const GeometryContext& gctx, - const Transform3D& shift) const -{ +std::shared_ptr<Acts::StrawSurface> Acts::StrawSurface::clone( + const GeometryContext& gctx, const Transform3D& shift) const { return std::shared_ptr<StrawSurface>(this->clone_impl(gctx, shift)); } -Acts::StrawSurface* -Acts::StrawSurface::clone_impl(const GeometryContext& gctx, - const Transform3D& shift) const -{ +Acts::StrawSurface* Acts::StrawSurface::clone_impl( + const GeometryContext& gctx, const Transform3D& shift) const { return new StrawSurface(gctx, *this, shift); } -Acts::PolyhedronRepresentation -Acts::StrawSurface::polyhedronRepresentation(const GeometryContext& gctx, - size_t l0div, - size_t /*l1div*/) const -{ - std::vector<Vector3D> vertices; +Acts::PolyhedronRepresentation Acts::StrawSurface::polyhedronRepresentation( + const GeometryContext& gctx, size_t l0div, size_t /*l1div*/) const { + std::vector<Vector3D> vertices; std::vector<std::vector<size_t>> faces; if (l0div == 1) { @@ -88,8 +68,8 @@ Acts::StrawSurface::polyhedronRepresentation(const GeometryContext& gctx, } double phistep = 2 * M_PI / l0div; - double hlZ = m_bounds->halflengthZ(); - double r = m_bounds->r(); + double hlZ = m_bounds->halflengthZ(); + double r = m_bounds->r(); Vector3D left(r, 0, -hlZ); Vector3D right(r, 0, hlZ); @@ -103,7 +83,6 @@ Acts::StrawSurface::polyhedronRepresentation(const GeometryContext& gctx, } for (size_t v = 0; v < vertices.size() - 2; v = v + 2) { - faces.push_back({v, v + 1, v + 3, v + 2}); } if (l0div > 2) { diff --git a/Core/src/Surfaces/Surface.cpp b/Core/src/Surfaces/Surface.cpp index 918420342cbde21e3012379f67e0a7671a4efa25..a4e605e5e0b92e02d683d509574b5627da5c60e1 100644 --- a/Core/src/Surfaces/Surface.cpp +++ b/Core/src/Surfaces/Surface.cpp @@ -17,42 +17,32 @@ #include <utility> Acts::Surface::Surface(std::shared_ptr<const Transform3D> tform) - : GeometryObject(), m_transform(std::move(tform)) -{ -} + : GeometryObject(), m_transform(std::move(tform)) {} Acts::Surface::Surface(const DetectorElementBase& detelement) - : GeometryObject(), m_transform(nullptr), m_associatedDetElement(&detelement) -{ -} + : GeometryObject(), + m_transform(nullptr), + m_associatedDetElement(&detelement) {} Acts::Surface::Surface(const Surface& other) - : GeometryObject(other) - , std::enable_shared_from_this<Surface>() - , m_transform(other.m_transform) - , m_surfaceMaterial(other.m_surfaceMaterial) -{ -} - -Acts::Surface::Surface(const GeometryContext& gctx, - const Surface& other, - const Transform3D& shift) - : GeometryObject() - , m_transform(std::make_shared<const Transform3D>( - Transform3D(shift * other.transform(gctx)))) - , m_associatedLayer(nullptr) - , m_surfaceMaterial(other.m_surfaceMaterial) -{ -} + : GeometryObject(other), + std::enable_shared_from_this<Surface>(), + m_transform(other.m_transform), + m_surfaceMaterial(other.m_surfaceMaterial) {} + +Acts::Surface::Surface(const GeometryContext& gctx, const Surface& other, + const Transform3D& shift) + : GeometryObject(), + m_transform(std::make_shared<const Transform3D>( + Transform3D(shift * other.transform(gctx)))), + m_associatedLayer(nullptr), + m_surfaceMaterial(other.m_surfaceMaterial) {} Acts::Surface::~Surface() = default; -bool -Acts::Surface::isOnSurface(const GeometryContext& gctx, - const Vector3D& gpos, - const Vector3D& gmom, - const BoundaryCheck& bcheck) const -{ +bool Acts::Surface::isOnSurface(const GeometryContext& gctx, + const Vector3D& gpos, const Vector3D& gmom, + const BoundaryCheck& bcheck) const { // create the local position Vector2D lpos; // global to local transformation @@ -64,35 +54,27 @@ Acts::Surface::isOnSurface(const GeometryContext& gctx, return false; } -std::shared_ptr<Acts::Surface> -Acts::Surface::getSharedPtr() -{ +std::shared_ptr<Acts::Surface> Acts::Surface::getSharedPtr() { return shared_from_this(); } -std::shared_ptr<const Acts::Surface> -Acts::Surface::getSharedPtr() const -{ +std::shared_ptr<const Acts::Surface> Acts::Surface::getSharedPtr() const { return shared_from_this(); } -Acts::Surface& -Acts::Surface::operator=(const Surface& other) -{ +Acts::Surface& Acts::Surface::operator=(const Surface& other) { if (&other != this) { GeometryObject::operator=(other); // detector element, identifier & layer association are unique - m_transform = other.m_transform; - m_associatedLayer = other.m_associatedLayer; - m_surfaceMaterial = other.m_surfaceMaterial; + m_transform = other.m_transform; + m_associatedLayer = other.m_associatedLayer; + m_surfaceMaterial = other.m_surfaceMaterial; m_associatedDetElement = other.m_associatedDetElement; } return *this; } -bool -Acts::Surface::operator==(const Surface& other) const -{ +bool Acts::Surface::operator==(const Surface& other) const { // (a) fast exit for pointer comparison if (&other == this) { return true; @@ -125,9 +107,8 @@ Acts::Surface::operator==(const Surface& other) const } // overload dump for stream operator -std::ostream& -Acts::Surface::toStream(const GeometryContext& gctx, std::ostream& sl) const -{ +std::ostream& Acts::Surface::toStream(const GeometryContext& gctx, + std::ostream& sl) const { sl << std::setiosflags(std::ios::fixed); sl << std::setprecision(4); sl << name() << std::endl; @@ -135,9 +116,9 @@ Acts::Surface::toStream(const GeometryContext& gctx, std::ostream& sl) const sl << " Center position (x, y, z) = (" << sfcenter.x() << ", " << sfcenter.y() << ", " << sfcenter.z() << ")" << std::endl; Acts::RotationMatrix3D rot(transform(gctx).matrix().block<3, 3>(0, 0)); - Acts::Vector3D rotX(rot.col(0)); - Acts::Vector3D rotY(rot.col(1)); - Acts::Vector3D rotZ(rot.col(2)); + Acts::Vector3D rotX(rot.col(0)); + Acts::Vector3D rotY(rot.col(1)); + Acts::Vector3D rotZ(rot.col(2)); sl << std::setprecision(6); sl << " Rotation: colX = (" << rotX(0) << ", " << rotX(1) << ", " << rotX(2) << ")" << std::endl; @@ -150,8 +131,6 @@ Acts::Surface::toStream(const GeometryContext& gctx, std::ostream& sl) const return sl; } -bool -Acts::Surface::operator!=(const Acts::Surface& sf) const -{ +bool Acts::Surface::operator!=(const Acts::Surface& sf) const { return !(operator==(sf)); } diff --git a/Core/src/Surfaces/SurfaceArray.cpp b/Core/src/Surfaces/SurfaceArray.cpp index 49f3273926af5dbece90c86e4dd5c7c5c4a85647..c1bf681f301a35a85b98c00b59d00867f50c9b1a 100644 --- a/Core/src/Surfaces/SurfaceArray.cpp +++ b/Core/src/Surfaces/SurfaceArray.cpp @@ -17,28 +17,23 @@ Acts::SurfaceArray::ISurfaceGridLookup::~ISurfaceGridLookup() = default; Acts::SurfaceArray::SurfaceArray( - std::unique_ptr<ISurfaceGridLookup> gridLookup, + std::unique_ptr<ISurfaceGridLookup> gridLookup, std::vector<std::shared_ptr<const Surface>> surfaces, - std::shared_ptr<const Transform3D> transform) - : p_gridLookup(std::move(gridLookup)) - , m_surfaces(std::move(surfaces)) - , m_surfacesRawPointers(unpack_shared_vector(m_surfaces)) - , m_transform(std::move(transform)) -{ -} + std::shared_ptr<const Transform3D> transform) + : p_gridLookup(std::move(gridLookup)), + m_surfaces(std::move(surfaces)), + m_surfacesRawPointers(unpack_shared_vector(m_surfaces)), + m_transform(std::move(transform)) {} Acts::SurfaceArray::SurfaceArray(std::shared_ptr<const Surface> srf) - : p_gridLookup( - static_cast<ISurfaceGridLookup*>(new SingleElementLookup(srf.get()))) - , m_surfaces({std::move(srf)}) -{ + : p_gridLookup( + static_cast<ISurfaceGridLookup*>(new SingleElementLookup(srf.get()))), + m_surfaces({std::move(srf)}) { m_surfacesRawPointers.push_back(m_surfaces.at(0).get()); } -std::ostream& -Acts::SurfaceArray::toStream(const GeometryContext& /*gctx*/, - std::ostream& sl) const -{ +std::ostream& Acts::SurfaceArray::toStream(const GeometryContext& /*gctx*/, + std::ostream& sl) const { sl << std::fixed << std::setprecision(4); sl << "SurfaceArray:" << std::endl; sl << " - no surfaces: " << m_surfaces.size() << std::endl; diff --git a/Core/src/Surfaces/TrapezoidBounds.cpp b/Core/src/Surfaces/TrapezoidBounds.cpp index 9422759c0c7ead338d27527792f6ab9025fbd19d..6c5f12b2a712655f0a716f236053b79ddbb755af 100644 --- a/Core/src/Surfaces/TrapezoidBounds.cpp +++ b/Core/src/Surfaces/TrapezoidBounds.cpp @@ -16,56 +16,42 @@ #include <iomanip> #include <iostream> -Acts::TrapezoidBounds::TrapezoidBounds(double minhalex, - double maxhalex, +Acts::TrapezoidBounds::TrapezoidBounds(double minhalex, double maxhalex, double haley) - : m_minHalfX(std::abs(minhalex)) - , m_maxHalfX(std::abs(maxhalex)) - , m_halfY(std::abs(haley)) - , m_boundingBox(std::max(minhalex, maxhalex), haley) -{ -} + : m_minHalfX(std::abs(minhalex)), + m_maxHalfX(std::abs(maxhalex)), + m_halfY(std::abs(haley)), + m_boundingBox(std::max(minhalex, maxhalex), haley) {} Acts::TrapezoidBounds::~TrapezoidBounds() = default; -Acts::TrapezoidBounds* -Acts::TrapezoidBounds::clone() const -{ +Acts::TrapezoidBounds* Acts::TrapezoidBounds::clone() const { return new TrapezoidBounds(*this); } -Acts::SurfaceBounds::BoundsType -Acts::TrapezoidBounds::type() const -{ +Acts::SurfaceBounds::BoundsType Acts::TrapezoidBounds::type() const { return SurfaceBounds::Trapezoid; } -std::vector<TDD_real_t> -Acts::TrapezoidBounds::valueStore() const -{ +std::vector<TDD_real_t> Acts::TrapezoidBounds::valueStore() const { std::vector<TDD_real_t> values(TrapezoidBounds::bv_length); values[TrapezoidBounds::bv_minHalfX] = minHalflengthX(); values[TrapezoidBounds::bv_maxHalfX] = maxHalflengthX(); - values[TrapezoidBounds::bv_halfY] = halflengthY(); + values[TrapezoidBounds::bv_halfY] = halflengthY(); return values; } -bool -Acts::TrapezoidBounds::inside(const Acts::Vector2D& lpos, - const Acts::BoundaryCheck& bcheck) const -{ +bool Acts::TrapezoidBounds::inside(const Acts::Vector2D& lpos, + const Acts::BoundaryCheck& bcheck) const { return bcheck.isInside(lpos, vertices()); } -double -Acts::TrapezoidBounds::distanceToBoundary(const Acts::Vector2D& lpos) const -{ +double Acts::TrapezoidBounds::distanceToBoundary( + const Acts::Vector2D& lpos) const { return BoundaryCheck(true).distance(lpos, vertices()); } -std::vector<Acts::Vector2D> -Acts::TrapezoidBounds::vertices() const -{ +std::vector<Acts::Vector2D> Acts::TrapezoidBounds::vertices() const { // counter-clockwise from bottom-right corner return {{minHalflengthX(), -halflengthY()}, {maxHalflengthX(), halflengthY()}, @@ -73,15 +59,11 @@ Acts::TrapezoidBounds::vertices() const {-minHalflengthX(), -halflengthY()}}; } -const Acts::RectangleBounds& -Acts::TrapezoidBounds::boundingBox() const -{ +const Acts::RectangleBounds& Acts::TrapezoidBounds::boundingBox() const { return m_boundingBox; } -std::ostream& -Acts::TrapezoidBounds::toStream(std::ostream& sl) const -{ +std::ostream& Acts::TrapezoidBounds::toStream(std::ostream& sl) const { sl << std::setiosflags(std::ios::fixed); sl << std::setprecision(7); sl << "Acts::TrapezoidBounds: (minHlengthX, maxHlengthX, hlengthY) = " diff --git a/Core/src/Surfaces/TriangleBounds.cpp b/Core/src/Surfaces/TriangleBounds.cpp index 0b265d84792685fd82b5c98409e89d36e6cab6eb..779289cb3999e5c8d0a5ddf9619a71e2f53d19e7 100644 --- a/Core/src/Surfaces/TriangleBounds.cpp +++ b/Core/src/Surfaces/TriangleBounds.cpp @@ -16,8 +16,7 @@ #include <iostream> Acts::TriangleBounds::TriangleBounds(const std::array<Vector2D, 3>& vertices) - : m_vertices(vertices), m_boundingBox(0, 0) -{ + : m_vertices(vertices), m_boundingBox(0, 0) { double mx = 0; double my = 0; for (auto& v : vertices) { @@ -29,21 +28,15 @@ Acts::TriangleBounds::TriangleBounds(const std::array<Vector2D, 3>& vertices) Acts::TriangleBounds::~TriangleBounds() = default; -Acts::TriangleBounds* -Acts::TriangleBounds::clone() const -{ +Acts::TriangleBounds* Acts::TriangleBounds::clone() const { return new TriangleBounds(*this); } -Acts::SurfaceBounds::BoundsType -Acts::TriangleBounds::type() const -{ +Acts::SurfaceBounds::BoundsType Acts::TriangleBounds::type() const { return SurfaceBounds::Triangle; } -std::vector<TDD_real_t> -Acts::TriangleBounds::valueStore() const -{ +std::vector<TDD_real_t> Acts::TriangleBounds::valueStore() const { std::vector<TDD_real_t> values(TriangleBounds::bv_length); values[TriangleBounds::bv_x1] = m_vertices[0].x(); values[TriangleBounds::bv_y1] = m_vertices[0].y(); @@ -54,35 +47,26 @@ Acts::TriangleBounds::valueStore() const return values; } -bool -Acts::TriangleBounds::inside(const Acts::Vector2D& lpos, - const Acts::BoundaryCheck& bcheck) const -{ +bool Acts::TriangleBounds::inside(const Acts::Vector2D& lpos, + const Acts::BoundaryCheck& bcheck) const { return bcheck.isInside(lpos, m_vertices); } -double -Acts::TriangleBounds::distanceToBoundary(const Acts::Vector2D& lpos) const -{ +double Acts::TriangleBounds::distanceToBoundary( + const Acts::Vector2D& lpos) const { return BoundaryCheck(true).distance(lpos, m_vertices); } -std::vector<Acts::Vector2D> -Acts::TriangleBounds::vertices() const -{ +std::vector<Acts::Vector2D> Acts::TriangleBounds::vertices() const { return {std::begin(m_vertices), std::end(m_vertices)}; } -const Acts::RectangleBounds& -Acts::TriangleBounds::boundingBox() const -{ +const Acts::RectangleBounds& Acts::TriangleBounds::boundingBox() const { return m_boundingBox; } // ostream operator overload -std::ostream& -Acts::TriangleBounds::toStream(std::ostream& sl) const -{ +std::ostream& Acts::TriangleBounds::toStream(std::ostream& sl) const { sl << std::setiosflags(std::ios::fixed); sl << std::setprecision(7); sl << "Acts::TriangleBounds: generating vertices (X, Y)"; diff --git a/Core/src/Utilities/Logger.cpp b/Core/src/Utilities/Logger.cpp index 1746bbde4e3c7646cb896d3bf017fd976d5a6163..a18e67092cd322ee7c02d48d8cac91a1c79ce20d 100644 --- a/Core/src/Utilities/Logger.cpp +++ b/Core/src/Utilities/Logger.cpp @@ -10,11 +10,9 @@ namespace Acts { -std::unique_ptr<const Logger> -getDefaultLogger(const std::string& name, - const Logging::Level& lvl, - std::ostream* log_stream) -{ +std::unique_ptr<const Logger> getDefaultLogger(const std::string& name, + const Logging::Level& lvl, + std::ostream* log_stream) { using namespace Logging; auto output = std::make_unique<LevelOutputDecorator>( std::make_unique<NamedOutputDecorator>( diff --git a/Core/src/Utilities/Units.cpp b/Core/src/Utilities/Units.cpp index bda0724969821f2a3896f702a07b1955929f0143..1353a9d9954d9ce834c7d7058d3e57d416d893c8 100644 --- a/Core/src/Utilities/Units.cpp +++ b/Core/src/Utilities/Units.cpp @@ -11,72 +11,56 @@ namespace Acts { namespace units { - template <> - double - SI2Nat<ENERGY>(const double E) - { - static const double conversion = _GeV_per_J; - return E * conversion; - } +template <> +double SI2Nat<ENERGY>(const double E) { + static const double conversion = _GeV_per_J; + return E * conversion; +} - template <> - double - Nat2SI<ENERGY>(const double E) - { - static const double conversion = 1. / _GeV_per_J; - return E * conversion; - } +template <> +double Nat2SI<ENERGY>(const double E) { + static const double conversion = 1. / _GeV_per_J; + return E * conversion; +} - template <> - double - SI2Nat<LENGTH>(const double l) - { - static const double conversion = 1. / _mm_times_GeV; - return l * conversion; - } +template <> +double SI2Nat<LENGTH>(const double l) { + static const double conversion = 1. / _mm_times_GeV; + return l * conversion; +} - template <> - double - Nat2SI<LENGTH>(const double l) - { - static const double conversion = _mm_times_GeV; - return l * conversion; - } +template <> +double Nat2SI<LENGTH>(const double l) { + static const double conversion = _mm_times_GeV; + return l * conversion; +} - template <> - double - SI2Nat<MOMENTUM>(const double p) - { - // p(NU) = p(SI) * c - static const double conversion = _c * _GeV_per_J; - return p * conversion; - } +template <> +double SI2Nat<MOMENTUM>(const double p) { + // p(NU) = p(SI) * c + static const double conversion = _c * _GeV_per_J; + return p * conversion; +} - template <> - double - Nat2SI<MOMENTUM>(const double p) - { - // p(SI) = p(NU)/c - static const double conversion = 1. / (_c * _GeV_per_J); - return p * conversion; - } +template <> +double Nat2SI<MOMENTUM>(const double p) { + // p(SI) = p(NU)/c + static const double conversion = 1. / (_c * _GeV_per_J); + return p * conversion; +} - template <> - double - SI2Nat<MASS>(const double m) - { - // p(NU) = p(SI) * c - static const double conversion = _c * _c * _GeV_per_J; - return m * conversion; - } +template <> +double SI2Nat<MASS>(const double m) { + // p(NU) = p(SI) * c + static const double conversion = _c * _c * _GeV_per_J; + return m * conversion; +} - template <> - double - Nat2SI<MASS>(const double m) - { - // p(SI) = p(NU)/c - static const double conversion = 1. / (_c * _c * _GeV_per_J); - return m * conversion; - } +template <> +double Nat2SI<MASS>(const double m) { + // p(SI) = p(NU)/c + static const double conversion = 1. / (_c * _c * _GeV_per_J); + return m * conversion; +} } // namespace units } // namespace Acts diff --git a/Legacy/include/Acts/Propagator/AtlasStepper.hpp b/Legacy/include/Acts/Propagator/AtlasStepper.hpp index 416e1a0ca4f40f3ea5818e8b582d1a18e9079d2f..799384103de3e69e0eef424ed8da195db3901537 100644 --- a/Legacy/include/Acts/Propagator/AtlasStepper.hpp +++ b/Legacy/include/Acts/Propagator/AtlasStepper.hpp @@ -24,37 +24,31 @@ namespace Acts { /// @brief the AtlasStepper implementation for the template <typename bfield_t> -class AtlasStepper -{ - +class AtlasStepper { // This struct is a meta-function which normally maps to BoundParameters... template <typename T, typename S> - struct s - { + struct s { using type = BoundParameters; }; // Unless S is int, then it maps to CurvilinearParameters ... template <typename T> - struct s<T, int> - { + struct s<T, int> { using type = CurvilinearParameters; }; -public: + public: using cstep = detail::ConstrainedStep; - using Jacobian = ActsMatrixD<5, 5>; - using Covariance = ActsSymMatrixD<5>; - using BoundState = std::tuple<BoundParameters, Jacobian, double>; + using Jacobian = ActsMatrixD<5, 5>; + using Covariance = ActsSymMatrixD<5>; + using BoundState = std::tuple<BoundParameters, Jacobian, double>; using CurvilinearState = std::tuple<CurvilinearParameters, Jacobian, double>; using Corrector = VoidIntersectionCorrector; /// @brief Nested State struct for the local caching - struct State - { - + struct State { /// Constructor /// /// @tparams Type of TrackParameters @@ -65,31 +59,29 @@ public: /// @param[in] ndir The navigation direction w.r.t. parameters /// @param[in] ssize the steps size limitation template <typename Parameters> - State(std::reference_wrapper<const GeometryContext> gctx, + State(std::reference_wrapper<const GeometryContext> gctx, std::reference_wrapper<const MagneticFieldContext> mctx, - const Parameters& pars, - NavigationDirection ndir = forward, + const Parameters& pars, NavigationDirection ndir = forward, double ssize = std::numeric_limits<double>::max()) - : state_ready(false) - , navDir(ndir) - , useJacobian(false) - , step(0.) - , maxPathLength(0.) - , mcondition(false) - , needgradient(false) - , newfield(true) - , field(0., 0., 0.) - , covariance(nullptr) - , stepSize(ndir * std::abs(ssize)) - , fieldCache(mctx) - , geoContext(gctx) - { + : state_ready(false), + navDir(ndir), + useJacobian(false), + step(0.), + maxPathLength(0.), + mcondition(false), + needgradient(false), + newfield(true), + field(0., 0., 0.), + covariance(nullptr), + stepSize(ndir * std::abs(ssize)), + fieldCache(mctx), + geoContext(gctx) { // The rest of this constructor is copy&paste of AtlasStepper::update() - // this is a nasty but working solution for the stepper state without // functions const ActsVectorD<3> pos = pars.position(); - const auto Vp = pars.parameters(); + const auto Vp = pars.parameters(); double Sf, Cf, Ce, Se; Sf = sin(Vp(2)); @@ -114,24 +106,24 @@ public: // prepare the jacobian if we have a covariance if (pars.covariance()) { // copy the covariance matrix - covariance = new ActsSymMatrixD<NGlobalPars>(*pars.covariance()); + covariance = new ActsSymMatrixD<NGlobalPars>(*pars.covariance()); covTransport = true; - useJacobian = true; + useJacobian = true; const auto transform = pars.referenceFrame(geoContext); - pVector[7] = transform(0, eLOC_0); + pVector[7] = transform(0, eLOC_0); pVector[14] = transform(0, eLOC_1); pVector[21] = 0.; pVector[28] = 0.; pVector[35] = 0.; // dX / - pVector[8] = transform(1, eLOC_0); + pVector[8] = transform(1, eLOC_0); pVector[15] = transform(1, eLOC_1); pVector[22] = 0.; pVector[29] = 0.; pVector[36] = 0.; // dY / - pVector[9] = transform(2, eLOC_0); + pVector[9] = transform(2, eLOC_0); pVector[16] = transform(2, eLOC_1); pVector[23] = 0.; pVector[30] = 0.; @@ -169,25 +161,24 @@ public: const auto& surface = pars.referenceSurface(); // the disc needs polar coordinate adaptations if (surface.type() == Surface::Disc) { - double lCf = cos(Vp[1]); - double lSf = sin(Vp[1]); + double lCf = cos(Vp[1]); + double lSf = sin(Vp[1]); double Ax[3] = {transform(0, 0), transform(1, 0), transform(2, 0)}; double Ay[3] = {transform(0, 1), transform(1, 1), transform(2, 1)}; - double d0 = lCf * Ax[0] + lSf * Ay[0]; - double d1 = lCf * Ax[1] + lSf * Ay[1]; - double d2 = lCf * Ax[2] + lSf * Ay[2]; - pVector[7] = d0; - pVector[8] = d1; - pVector[9] = d2; - pVector[14] = Vp[0] * (lCf * Ay[0] - lSf * Ax[0]); - pVector[15] = Vp[0] * (lCf * Ay[1] - lSf * Ax[1]); - pVector[16] = Vp[0] * (lCf * Ay[2] - lSf * Ax[2]); + double d0 = lCf * Ax[0] + lSf * Ay[0]; + double d1 = lCf * Ax[1] + lSf * Ay[1]; + double d2 = lCf * Ax[2] + lSf * Ay[2]; + pVector[7] = d0; + pVector[8] = d1; + pVector[9] = d2; + pVector[14] = Vp[0] * (lCf * Ay[0] - lSf * Ax[0]); + pVector[15] = Vp[0] * (lCf * Ay[1] - lSf * Ax[1]); + pVector[16] = Vp[0] * (lCf * Ay[2] - lSf * Ax[2]); } // the line needs components that relate direction change // with global frame change - if (surface.type() == Surface::Perigee - || surface.type() == Surface::Straw) { - + if (surface.type() == Surface::Perigee || + surface.type() == Surface::Straw) { // sticking to the nomenclature of the original RkPropagator // - axis pointing along the drift/transverse direction double B[3] = {transform(0, 0), transform(1, 0), transform(2, 0)}; @@ -236,21 +227,21 @@ public: bool state_ready = false; // configuration NavigationDirection navDir; - bool useJacobian; - double step; - double maxPathLength; - bool mcondition; - bool needgradient; - bool newfield; + bool useJacobian; + double step; + double maxPathLength; + bool mcondition; + bool needgradient; + bool newfield; // internal parameters to be used Vector3D field; - double pVector[64]; + double pVector[64]; // result double parameters[NGlobalPars] = {0., 0., 0., 0., 0.}; const ActsSymMatrixD<NGlobalPars>* covariance; - Covariance cov = Covariance::Zero(); - bool covTransport = false; - double jacobian[NGlobalPars * NGlobalPars]; + Covariance cov = Covariance::Zero(); + bool covTransport = false; + double jacobian[NGlobalPars * NGlobalPars]; // accummulated path length cache double pathAccumulated = 0.; @@ -267,7 +258,7 @@ public: /// Debug output /// the string where debug messages are stored (optionally) - bool debug = false; + bool debug = false; std::string debugString = ""; /// buffer & formatting for consistent output size_t debugPfxWidth = 30; @@ -286,36 +277,26 @@ public: /// @param [in,out] state is the stepper state associated with the track /// the magnetic field cell is used (and potentially updated) /// @param [in] pos is the field position - Vector3D - getField(State& state, const Vector3D& pos) const - { + Vector3D getField(State& state, const Vector3D& pos) const { // get the field from the cell state.field = m_bField.getField(pos, state.fieldCache); return state.field; } - Vector3D - position(const State& state) const - { + Vector3D position(const State& state) const { return Vector3D(state.pVector[0], state.pVector[1], state.pVector[2]); } - Vector3D - direction(const State& state) const - { + Vector3D direction(const State& state) const { return Vector3D(state.pVector[3], state.pVector[4], state.pVector[5]); } - double - momentum(const State& state) const - { + double momentum(const State& state) const { return 1. / std::abs(state.pVector[6]); } /// Charge access - double - charge(const State& state) const - { + double charge(const State& state) const { return state.pVector[6] > 0. ? 1. : -1.; } @@ -325,11 +306,9 @@ public: /// @param [in] surface Surface that is tested /// /// @return Boolean statement if surface is reached by state - bool - surfaceReached(const State& state, const Surface* surface) const - { - return surface->isOnSurface( - state.geoContext, position(state), direction(state), true); + bool surfaceReached(const State& state, const Surface* surface) const { + return surface->isOnSurface(state.geoContext, position(state), + direction(state), true); } /// Create and return the bound state at the current position @@ -344,10 +323,8 @@ public: /// - the parameters at the surface /// - the stepwise jacobian towards it /// - and the path length (from start - for ordering) - BoundState - boundState(State& state, const Surface& surface, bool /*unused*/) const - { - + BoundState boundState(State& state, const Surface& surface, + bool /*unused*/) const { // the convert method invalidates the state (in case it's reused) state.state_ready = false; @@ -364,15 +341,11 @@ public: } // Fill the end parameters - BoundParameters parameters(state.geoContext, - std::move(cov), - gp, - mom, - charge(state), - surface.getSharedPtr()); - - return BoundState( - std::move(parameters), state.jacobian, state.pathAccumulated); + BoundParameters parameters(state.geoContext, std::move(cov), gp, mom, + charge(state), surface.getSharedPtr()); + + return BoundState(std::move(parameters), state.jacobian, + state.pathAccumulated); } /// Create and return a curvilinear state at the current position @@ -386,9 +359,7 @@ public: /// - the curvilinear parameters at given position /// - the stepweise jacobian towards it /// - and the path length (from start - for ordering) - CurvilinearState - curvilinearState(State& state, bool /*unused*/) const - { + CurvilinearState curvilinearState(State& state, bool /*unused*/) const { // the convert method invalidates the state (in case it's reused) state.state_ready = false; // @@ -404,24 +375,22 @@ public: CurvilinearParameters parameters(std::move(cov), gp, mom, charge(state)); - return CurvilinearState( - std::move(parameters), state.jacobian, state.pathAccumulated); + return CurvilinearState(std::move(parameters), state.jacobian, + state.pathAccumulated); } /// The state update method /// /// @param [in,out] state The stepper state for /// @param [in] pars The new track parameters at start - void - update(State& state, const BoundParameters& pars) const - { + void update(State& state, const BoundParameters& pars) const { // state is ready - noting to do if (state.state_ready) { return; } const ActsVectorD<3> pos = pars.position(); - const auto Vp = pars.parameters(); + const auto Vp = pars.parameters(); double Sf, Cf, Ce, Se; Sf = sin(Vp(2)); @@ -446,23 +415,23 @@ public: // prepare the jacobian if we have a covariance if (pars.covariance()) { // copy the covariance matrix - state.covariance = new ActsSymMatrixD<NGlobalPars>(*pars.covariance()); + state.covariance = new ActsSymMatrixD<NGlobalPars>(*pars.covariance()); state.covTransport = true; - state.useJacobian = true; + state.useJacobian = true; const auto transform = pars.referenceFrame(state.geoContext); - state.pVector[7] = transform(0, eLOC_0); - state.pVector[14] = transform(0, eLOC_1); - state.pVector[21] = 0.; - state.pVector[28] = 0.; - state.pVector[35] = 0.; // dX / + state.pVector[7] = transform(0, eLOC_0); + state.pVector[14] = transform(0, eLOC_1); + state.pVector[21] = 0.; + state.pVector[28] = 0.; + state.pVector[35] = 0.; // dX / - state.pVector[8] = transform(1, eLOC_0); + state.pVector[8] = transform(1, eLOC_0); state.pVector[15] = transform(1, eLOC_1); state.pVector[22] = 0.; state.pVector[29] = 0.; state.pVector[36] = 0.; // dY / - state.pVector[9] = transform(2, eLOC_0); + state.pVector[9] = transform(2, eLOC_0); state.pVector[16] = transform(2, eLOC_1); state.pVector[23] = 0.; state.pVector[30] = 0.; @@ -500,25 +469,24 @@ public: const auto& surface = pars.referenceSurface(); // the disc needs polar coordinate adaptations if (surface.type() == Surface::Disc) { - double lCf = cos(Vp[1]); - double lSf = sin(Vp[1]); - double Ax[3] = {transform(0, 0), transform(1, 0), transform(2, 0)}; - double Ay[3] = {transform(0, 1), transform(1, 1), transform(2, 1)}; - double d0 = lCf * Ax[0] + lSf * Ay[0]; - double d1 = lCf * Ax[1] + lSf * Ay[1]; - double d2 = lCf * Ax[2] + lSf * Ay[2]; - state.pVector[7] = d0; - state.pVector[8] = d1; - state.pVector[9] = d2; + double lCf = cos(Vp[1]); + double lSf = sin(Vp[1]); + double Ax[3] = {transform(0, 0), transform(1, 0), transform(2, 0)}; + double Ay[3] = {transform(0, 1), transform(1, 1), transform(2, 1)}; + double d0 = lCf * Ax[0] + lSf * Ay[0]; + double d1 = lCf * Ax[1] + lSf * Ay[1]; + double d2 = lCf * Ax[2] + lSf * Ay[2]; + state.pVector[7] = d0; + state.pVector[8] = d1; + state.pVector[9] = d2; state.pVector[14] = Vp[0] * (lCf * Ay[0] - lSf * Ax[0]); state.pVector[15] = Vp[0] * (lCf * Ay[1] - lSf * Ax[1]); state.pVector[16] = Vp[0] * (lCf * Ay[2] - lSf * Ax[2]); } // the line needs components that relate direction change // with global frame change - if (surface.type() == Surface::Perigee - || surface.type() == Surface::Straw) { - + if (surface.type() == Surface::Perigee || + surface.type() == Surface::Straw) { // sticking to the nomenclature of the original RkPropagator // - axis pointing along the drift/transverse direction double B[3] = {transform(0, 0), transform(1, 0), transform(2, 0)}; @@ -528,8 +496,8 @@ public: double C[3] = {transform(0, 2), transform(1, 2), transform(2, 2)}; // projection of direction onto normal vector of reference frame - double PC = state.pVector[3] * C[0] + state.pVector[4] * C[1] - + state.pVector[5] * C[2]; + double PC = state.pVector[3] * C[0] + state.pVector[4] * C[1] + + state.pVector[5] * C[2]; double Bn = 1. / PC; double Bx2 = -A[2] * state.pVector[25]; @@ -569,12 +537,8 @@ public: /// @param uposition the updated position /// @param udirection the updated direction /// @param p the updated momentum value - void - update(State& state, - const Vector3D& uposition, - const Vector3D& udirection, - double up) const - { + void update(State& state, const Vector3D& uposition, + const Vector3D& udirection, double up) const { // update the vector state.pVector[0] = uposition[0]; state.pVector[1] = uposition[1]; @@ -586,9 +550,7 @@ public: } /// Return a corrector - VoidIntersectionCorrector - corrector(State& /*unused*/) const - { + VoidIntersectionCorrector corrector(State& /*unused*/) const { return VoidIntersectionCorrector(); } @@ -601,9 +563,7 @@ public: /// reinitialized at the new position /// /// @return the full transport jacobian - void - covarianceTransport(State& state, bool /*unused*/) const - { + void covarianceTransport(State& state, bool /*unused*/) const { double P[45]; for (unsigned int i = 0; i < 45; ++i) { P[i] = state.pVector[i]; @@ -630,7 +590,7 @@ public: } double Ay[3] = {-Ax[1] * P[5], Ax[0] * P[5], An}; - double S[3] = {P[3], P[4], P[5]}; + double S[3] = {P[3], P[4], P[5]}; double A = P[3] * S[0] + P[4] * S[1] + P[5] * S[2]; if (A != 0.) { @@ -679,12 +639,12 @@ public: double P3, P4, C = P[3] * P[3] + P[4] * P[4]; if (C > 1.e-20) { - C = 1. / C; + C = 1. / C; P3 = P[3] * C; P4 = P[4] * C; - C = -sqrt(C); + C = -sqrt(C); } else { - C = -1.e10; + C = -1.e10; P3 = 1.; P4 = 0.; } @@ -698,14 +658,14 @@ public: state.jacobian[4] = Ax[0] * P[35] + Ax[1] * P[36]; // dL0/dCM state.jacobian[5] = Ay[0] * P[7] + Ay[1] * P[8] + Ay[2] * P[9]; // dL1/dL0 - state.jacobian[6] - = Ay[0] * P[14] + Ay[1] * P[15] + Ay[2] * P[16]; // dL1/dL1 - state.jacobian[7] - = Ay[0] * P[21] + Ay[1] * P[22] + Ay[2] * P[23]; // dL1/dPhi - state.jacobian[8] - = Ay[0] * P[28] + Ay[1] * P[29] + Ay[2] * P[30]; // dL1/dThe - state.jacobian[9] - = Ay[0] * P[35] + Ay[1] * P[36] + Ay[2] * P[37]; // dL1/dCM + state.jacobian[6] = + Ay[0] * P[14] + Ay[1] * P[15] + Ay[2] * P[16]; // dL1/dL1 + state.jacobian[7] = + Ay[0] * P[21] + Ay[1] * P[22] + Ay[2] * P[23]; // dL1/dPhi + state.jacobian[8] = + Ay[0] * P[28] + Ay[1] * P[29] + Ay[2] * P[30]; // dL1/dThe + state.jacobian[9] = + Ay[0] * P[35] + Ay[1] * P[36] + Ay[2] * P[37]; // dL1/dCM state.jacobian[10] = P3 * P[11] - P4 * P[10]; // dPhi/dL0 state.jacobian[11] = P3 * P[18] - P4 * P[17]; // dPhi/dL1 @@ -741,11 +701,8 @@ public: /// @param [in] surface is the surface to which the covariance is forwarded to /// @param [in] reinitialize is a flag to steer whether the state should be /// reinitialized at the new position - void - covarianceTransport(State& state, - const Surface& surface, - bool /*unused*/) const - { + void covarianceTransport(State& state, const Surface& surface, + bool /*unused*/) const { Acts::Vector3D gp(state.pVector[0], state.pVector[1], state.pVector[2]); Acts::Vector3D mom(state.pVector[3], state.pVector[4], state.pVector[5]); mom /= std::abs(state.pVector[6]); @@ -762,11 +719,11 @@ public: double Ax[3] = {fFrame(0, 0), fFrame(1, 0), fFrame(2, 0)}; double Ay[3] = {fFrame(0, 1), fFrame(1, 1), fFrame(2, 1)}; - double S[3] = {fFrame(0, 2), fFrame(1, 2), fFrame(2, 2)}; + double S[3] = {fFrame(0, 2), fFrame(1, 2), fFrame(2, 2)}; // this is the projection of direction onto the local normal vector - double A = state.pVector[3] * S[0] + state.pVector[4] * S[1] - + state.pVector[5] * S[2]; + double A = state.pVector[3] * S[0] + state.pVector[4] * S[1] + + state.pVector[5] * S[2]; if (A != 0.) { A = 1. / A; @@ -776,30 +733,30 @@ public: S[1] *= A; S[2] *= A; - double s0 = state.pVector[7] * S[0] + state.pVector[8] * S[1] - + state.pVector[9] * S[2]; - double s1 = state.pVector[14] * S[0] + state.pVector[15] * S[1] - + state.pVector[16] * S[2]; - double s2 = state.pVector[21] * S[0] + state.pVector[22] * S[1] - + state.pVector[23] * S[2]; - double s3 = state.pVector[28] * S[0] + state.pVector[29] * S[1] - + state.pVector[30] * S[2]; - double s4 = state.pVector[35] * S[0] + state.pVector[36] * S[1] - + state.pVector[37] * S[2]; + double s0 = state.pVector[7] * S[0] + state.pVector[8] * S[1] + + state.pVector[9] * S[2]; + double s1 = state.pVector[14] * S[0] + state.pVector[15] * S[1] + + state.pVector[16] * S[2]; + double s2 = state.pVector[21] * S[0] + state.pVector[22] * S[1] + + state.pVector[23] * S[2]; + double s3 = state.pVector[28] * S[0] + state.pVector[29] * S[1] + + state.pVector[30] * S[2]; + double s4 = state.pVector[35] * S[0] + state.pVector[36] * S[1] + + state.pVector[37] * S[2]; // in case of line-type surfaces - we need to take into account that // the reference frame changes with variations of all local // parameters - if (surface.type() == Surface::Straw - || surface.type() == Surface::Perigee) { + if (surface.type() == Surface::Straw || + surface.type() == Surface::Perigee) { // vector from position to center double x = state.pVector[0] - surface.center(state.geoContext).x(); double y = state.pVector[1] - surface.center(state.geoContext).y(); double z = state.pVector[2] - surface.center(state.geoContext).z(); // this is the projection of the direction onto the local y axis - double d = state.pVector[3] * Ay[0] + state.pVector[4] * Ay[1] - + state.pVector[5] * Ay[2]; + double d = state.pVector[3] * Ay[0] + state.pVector[4] * Ay[1] + + state.pVector[5] * Ay[2]; // this is cos(beta) double a = (1. - d) * (1. + d); @@ -813,48 +770,48 @@ public: double Z = d * Ay[2] - state.pVector[5]; // // d0 to d1 - double d0 = state.pVector[10] * Ay[0] + state.pVector[11] * Ay[1] - + state.pVector[12] * Ay[2]; - double d1 = state.pVector[17] * Ay[0] + state.pVector[18] * Ay[1] - + state.pVector[19] * Ay[2]; - double d2 = state.pVector[24] * Ay[0] + state.pVector[25] * Ay[1] - + state.pVector[26] * Ay[2]; - double d3 = state.pVector[31] * Ay[0] + state.pVector[32] * Ay[1] - + state.pVector[33] * Ay[2]; - double d4 = state.pVector[38] * Ay[0] + state.pVector[39] * Ay[1] - + state.pVector[40] * Ay[2]; - - s0 = (((state.pVector[7] * X + state.pVector[8] * Y - + state.pVector[9] * Z) - + x * (d0 * Ay[0] - state.pVector[10])) - + (y * (d0 * Ay[1] - state.pVector[11]) - + z * (d0 * Ay[2] - state.pVector[12]))) - * (-a); - - s1 = (((state.pVector[14] * X + state.pVector[15] * Y - + state.pVector[16] * Z) - + x * (d1 * Ay[0] - state.pVector[17])) - + (y * (d1 * Ay[1] - state.pVector[18]) - + z * (d1 * Ay[2] - state.pVector[19]))) - * (-a); - s2 = (((state.pVector[21] * X + state.pVector[22] * Y - + state.pVector[23] * Z) - + x * (d2 * Ay[0] - state.pVector[24])) - + (y * (d2 * Ay[1] - state.pVector[25]) - + z * (d2 * Ay[2] - state.pVector[26]))) - * (-a); - s3 = (((state.pVector[28] * X + state.pVector[29] * Y - + state.pVector[30] * Z) - + x * (d3 * Ay[0] - state.pVector[31])) - + (y * (d3 * Ay[1] - state.pVector[32]) - + z * (d3 * Ay[2] - state.pVector[33]))) - * (-a); - s4 = (((state.pVector[35] * X + state.pVector[36] * Y - + state.pVector[37] * Z) - + x * (d4 * Ay[0] - state.pVector[38])) - + (y * (d4 * Ay[1] - state.pVector[39]) - + z * (d4 * Ay[2] - state.pVector[40]))) - * (-a); + double d0 = state.pVector[10] * Ay[0] + state.pVector[11] * Ay[1] + + state.pVector[12] * Ay[2]; + double d1 = state.pVector[17] * Ay[0] + state.pVector[18] * Ay[1] + + state.pVector[19] * Ay[2]; + double d2 = state.pVector[24] * Ay[0] + state.pVector[25] * Ay[1] + + state.pVector[26] * Ay[2]; + double d3 = state.pVector[31] * Ay[0] + state.pVector[32] * Ay[1] + + state.pVector[33] * Ay[2]; + double d4 = state.pVector[38] * Ay[0] + state.pVector[39] * Ay[1] + + state.pVector[40] * Ay[2]; + + s0 = (((state.pVector[7] * X + state.pVector[8] * Y + + state.pVector[9] * Z) + + x * (d0 * Ay[0] - state.pVector[10])) + + (y * (d0 * Ay[1] - state.pVector[11]) + + z * (d0 * Ay[2] - state.pVector[12]))) * + (-a); + + s1 = (((state.pVector[14] * X + state.pVector[15] * Y + + state.pVector[16] * Z) + + x * (d1 * Ay[0] - state.pVector[17])) + + (y * (d1 * Ay[1] - state.pVector[18]) + + z * (d1 * Ay[2] - state.pVector[19]))) * + (-a); + s2 = (((state.pVector[21] * X + state.pVector[22] * Y + + state.pVector[23] * Z) + + x * (d2 * Ay[0] - state.pVector[24])) + + (y * (d2 * Ay[1] - state.pVector[25]) + + z * (d2 * Ay[2] - state.pVector[26]))) * + (-a); + s3 = (((state.pVector[28] * X + state.pVector[29] * Y + + state.pVector[30] * Z) + + x * (d3 * Ay[0] - state.pVector[31])) + + (y * (d3 * Ay[1] - state.pVector[32]) + + z * (d3 * Ay[2] - state.pVector[33]))) * + (-a); + s4 = (((state.pVector[35] * X + state.pVector[36] * Y + + state.pVector[37] * Z) + + x * (d4 * Ay[0] - state.pVector[38])) + + (y * (d4 * Ay[1] - state.pVector[39]) + + z * (d4 * Ay[2] - state.pVector[40]))) * + (-a); } state.pVector[7] -= (s0 * state.pVector[3]); @@ -893,15 +850,15 @@ public: state.pVector[40] -= (s4 * state.pVector[44]); double P3, P4, - C = state.pVector[3] * state.pVector[3] - + state.pVector[4] * state.pVector[4]; + C = state.pVector[3] * state.pVector[3] + + state.pVector[4] * state.pVector[4]; if (C > 1.e-20) { - C = 1. / C; + C = 1. / C; P3 = state.pVector[3] * C; P4 = state.pVector[4] * C; - C = -sqrt(C); + C = -sqrt(C); } else { - C = -1.e10; + C = -1.e10; P3 = 1.; P4 = 0.; } @@ -911,9 +868,8 @@ public: // Jacobian production of transport and to_local if (surface.type() == Surface::Disc) { // the vector from the disc surface to the p - const auto& sfc = surface.center(state.geoContext); - double d[3] = {state.pVector[0] - sfc(0), - state.pVector[1] - sfc(1), + const auto& sfc = surface.center(state.geoContext); + double d[3] = {state.pVector[0] - sfc(0), state.pVector[1] - sfc(1), state.pVector[2] - sfc(2)}; // this needs the transformation to polar coordinates double RC = d[0] * Ax[0] + d[1] * Ax[1] + d[2] * Ax[2]; @@ -922,56 +878,56 @@ public: // inverse radius double Ri = 1. / sqrt(R2); - MA[0] = (RC * Ax[0] + RS * Ay[0]) * Ri; - MA[1] = (RC * Ax[1] + RS * Ay[1]) * Ri; - MA[2] = (RC * Ax[2] + RS * Ay[2]) * Ri; + MA[0] = (RC * Ax[0] + RS * Ay[0]) * Ri; + MA[1] = (RC * Ax[1] + RS * Ay[1]) * Ri; + MA[2] = (RC * Ax[2] + RS * Ay[2]) * Ri; MB[0] = (RC * Ay[0] - RS * Ax[0]) * (Ri = 1. / R2); - MB[1] = (RC * Ay[1] - RS * Ax[1]) * Ri; - MB[2] = (RC * Ay[2] - RS * Ax[2]) * Ri; + MB[1] = (RC * Ay[1] - RS * Ax[1]) * Ri; + MB[2] = (RC * Ay[2] - RS * Ax[2]) * Ri; } - state.jacobian[0] = MA[0] * state.pVector[7] + MA[1] * state.pVector[8] - + MA[2] * state.pVector[9]; // dL0/dL0 - state.jacobian[1] = MA[0] * state.pVector[14] + MA[1] * state.pVector[15] - + MA[2] * state.pVector[16]; // dL0/dL1 - state.jacobian[2] = MA[0] * state.pVector[21] + MA[1] * state.pVector[22] - + MA[2] * state.pVector[23]; // dL0/dPhi - state.jacobian[3] = MA[0] * state.pVector[28] + MA[1] * state.pVector[29] - + MA[2] * state.pVector[30]; // dL0/dThe - state.jacobian[4] = MA[0] * state.pVector[35] + MA[1] * state.pVector[36] - + MA[2] * state.pVector[37]; // dL0/dCM - - state.jacobian[5] = MB[0] * state.pVector[7] + MB[1] * state.pVector[8] - + MB[2] * state.pVector[9]; // dL1/dL0 - state.jacobian[6] = MB[0] * state.pVector[14] + MB[1] * state.pVector[15] - + MB[2] * state.pVector[16]; // dL1/dL1 - state.jacobian[7] = MB[0] * state.pVector[21] + MB[1] * state.pVector[22] - + MB[2] * state.pVector[23]; // dL1/dPhi - state.jacobian[8] = MB[0] * state.pVector[28] + MB[1] * state.pVector[29] - + MB[2] * state.pVector[30]; // dL1/dThe - state.jacobian[9] = MB[0] * state.pVector[35] + MB[1] * state.pVector[36] - + MB[2] * state.pVector[37]; // dL1/dCM - - state.jacobian[10] - = P3 * state.pVector[11] - P4 * state.pVector[10]; // dPhi/dL0 - state.jacobian[11] - = P3 * state.pVector[18] - P4 * state.pVector[17]; // dPhi/dL1 - state.jacobian[12] - = P3 * state.pVector[25] - P4 * state.pVector[24]; // dPhi/dPhi - state.jacobian[13] - = P3 * state.pVector[32] - P4 * state.pVector[31]; // dPhi/dThe - state.jacobian[14] - = P3 * state.pVector[39] - P4 * state.pVector[38]; // dPhi/dCM - state.jacobian[15] = C * state.pVector[12]; // dThe/dL0 - state.jacobian[16] = C * state.pVector[19]; // dThe/dL1 - state.jacobian[17] = C * state.pVector[26]; // dThe/dPhi - state.jacobian[18] = C * state.pVector[33]; // dThe/dThe - state.jacobian[19] = C * state.pVector[40]; // dThe/dCM - state.jacobian[20] = 0.; // dCM /dL0 - state.jacobian[21] = 0.; // dCM /dL1 - state.jacobian[22] = 0.; // dCM /dPhi - state.jacobian[23] = 0.; // dCM /dTheta - state.jacobian[24] = state.pVector[41]; // dCM /dCM + state.jacobian[0] = MA[0] * state.pVector[7] + MA[1] * state.pVector[8] + + MA[2] * state.pVector[9]; // dL0/dL0 + state.jacobian[1] = MA[0] * state.pVector[14] + MA[1] * state.pVector[15] + + MA[2] * state.pVector[16]; // dL0/dL1 + state.jacobian[2] = MA[0] * state.pVector[21] + MA[1] * state.pVector[22] + + MA[2] * state.pVector[23]; // dL0/dPhi + state.jacobian[3] = MA[0] * state.pVector[28] + MA[1] * state.pVector[29] + + MA[2] * state.pVector[30]; // dL0/dThe + state.jacobian[4] = MA[0] * state.pVector[35] + MA[1] * state.pVector[36] + + MA[2] * state.pVector[37]; // dL0/dCM + + state.jacobian[5] = MB[0] * state.pVector[7] + MB[1] * state.pVector[8] + + MB[2] * state.pVector[9]; // dL1/dL0 + state.jacobian[6] = MB[0] * state.pVector[14] + MB[1] * state.pVector[15] + + MB[2] * state.pVector[16]; // dL1/dL1 + state.jacobian[7] = MB[0] * state.pVector[21] + MB[1] * state.pVector[22] + + MB[2] * state.pVector[23]; // dL1/dPhi + state.jacobian[8] = MB[0] * state.pVector[28] + MB[1] * state.pVector[29] + + MB[2] * state.pVector[30]; // dL1/dThe + state.jacobian[9] = MB[0] * state.pVector[35] + MB[1] * state.pVector[36] + + MB[2] * state.pVector[37]; // dL1/dCM + + state.jacobian[10] = + P3 * state.pVector[11] - P4 * state.pVector[10]; // dPhi/dL0 + state.jacobian[11] = + P3 * state.pVector[18] - P4 * state.pVector[17]; // dPhi/dL1 + state.jacobian[12] = + P3 * state.pVector[25] - P4 * state.pVector[24]; // dPhi/dPhi + state.jacobian[13] = + P3 * state.pVector[32] - P4 * state.pVector[31]; // dPhi/dThe + state.jacobian[14] = + P3 * state.pVector[39] - P4 * state.pVector[38]; // dPhi/dCM + state.jacobian[15] = C * state.pVector[12]; // dThe/dL0 + state.jacobian[16] = C * state.pVector[19]; // dThe/dL1 + state.jacobian[17] = C * state.pVector[26]; // dThe/dPhi + state.jacobian[18] = C * state.pVector[33]; // dThe/dThe + state.jacobian[19] = C * state.pVector[40]; // dThe/dCM + state.jacobian[20] = 0.; // dCM /dL0 + state.jacobian[21] = 0.; // dCM /dL1 + state.jacobian[22] = 0.; // dCM /dPhi + state.jacobian[23] = 0.; // dCM /dTheta + state.jacobian[24] = state.pVector[41]; // dCM /dCM Eigen::Map<Eigen::Matrix<double, NGlobalPars, NGlobalPars, Eigen::RowMajor>> J(state.jacobian); @@ -983,19 +939,17 @@ public: /// /// @param state is the provided stepper state (caller keeps thread locality) template <typename propagator_state_t> - Result<double> - step(propagator_state_t& state) const - { + Result<double> step(propagator_state_t& state) const { // we use h for keeping the nominclature with the original atlas code - double h = state.stepping.stepSize; - bool Jac = state.stepping.useJacobian; + double h = state.stepping.stepSize; + bool Jac = state.stepping.useJacobian; - double* R = &(state.stepping.pVector[0]); // Coordinates - double* A = &(state.stepping.pVector[3]); // Directions + double* R = &(state.stepping.pVector[0]); // Coordinates + double* A = &(state.stepping.pVector[3]); // Directions double* sA = &(state.stepping.pVector[42]); // Invert mometum/2. - double Pi - = 0.5 / units::Nat2SI<units::MOMENTUM>(1. / state.stepping.pVector[6]); + double Pi = + 0.5 / units::Nat2SI<units::MOMENTUM>(1. / state.stepping.pVector[6]); // double dltm = 0.0002 * .03; Vector3D f0, f; @@ -1011,21 +965,20 @@ public: // if (std::abs(S) < m_cfg.helixStep) Helix = true; while (h != 0.) { - double S3 = (1. / 3.) * h, S4 = .25 * h, PS2 = Pi * h; // First point // double H0[3] = {f0[0] * PS2, f0[1] * PS2, f0[2] * PS2}; - double A0 = A[1] * H0[2] - A[2] * H0[1]; - double B0 = A[2] * H0[0] - A[0] * H0[2]; - double C0 = A[0] * H0[1] - A[1] * H0[0]; - double A2 = A0 + A[0]; - double B2 = B0 + A[1]; - double C2 = C0 + A[2]; - double A1 = A2 + A[0]; - double B1 = B2 + A[1]; - double C1 = C2 + A[2]; + double A0 = A[1] * H0[2] - A[2] * H0[1]; + double B0 = A[2] * H0[0] - A[0] * H0[2]; + double C0 = A[0] * H0[1] - A[1] * H0[0]; + double A2 = A0 + A[0]; + double B2 = B0 + A[1]; + double C2 = C0 + A[2]; + double A1 = A2 + A[0]; + double B1 = B2 + A[1]; + double C1 = C2 + A[2]; // Second point // @@ -1037,15 +990,15 @@ public: } double H1[3] = {f[0] * PS2, f[1] * PS2, f[2] * PS2}; - double A3 = (A[0] + B2 * H1[2]) - C2 * H1[1]; - double B3 = (A[1] + C2 * H1[0]) - A2 * H1[2]; - double C3 = (A[2] + A2 * H1[1]) - B2 * H1[0]; - double A4 = (A[0] + B3 * H1[2]) - C3 * H1[1]; - double B4 = (A[1] + C3 * H1[0]) - A3 * H1[2]; - double C4 = (A[2] + A3 * H1[1]) - B3 * H1[0]; - double A5 = 2. * A4 - A[0]; - double B5 = 2. * B4 - A[1]; - double C5 = 2. * C4 - A[2]; + double A3 = (A[0] + B2 * H1[2]) - C2 * H1[1]; + double B3 = (A[1] + C2 * H1[0]) - A2 * H1[2]; + double C3 = (A[2] + A2 * H1[1]) - B2 * H1[0]; + double A4 = (A[0] + B3 * H1[2]) - C3 * H1[1]; + double B4 = (A[1] + C3 * H1[0]) - A3 * H1[2]; + double C4 = (A[2] + A3 * H1[1]) - B3 * H1[0]; + double A5 = 2. * A4 - A[0]; + double B5 = 2. * B4 - A[1]; + double C5 = 2. * C4 - A[2]; // Last point // @@ -1057,15 +1010,15 @@ public: } double H2[3] = {f[0] * PS2, f[1] * PS2, f[2] * PS2}; - double A6 = B5 * H2[2] - C5 * H2[1]; - double B6 = C5 * H2[0] - A5 * H2[2]; - double C6 = A5 * H2[1] - B5 * H2[0]; + double A6 = B5 * H2[2] - C5 * H2[1]; + double B6 = C5 * H2[0] - A5 * H2[2]; + double C6 = A5 * H2[1] - B5 * H2[0]; // Test approximation quality on give step and possible step reduction // - double EST = 2. - * (std::abs((A1 + A6) - (A3 + A4)) + std::abs((B1 + B6) - (B3 + B4)) - + std::abs((C1 + C6) - (C3 + C4))); + double EST = 2. * (std::abs((A1 + A6) - (A3 + A4)) + + std::abs((B1 + B6) - (B3 + B4)) + + std::abs((C1 + C6) - (C3 + C4))); if (EST > 0.0002) { h *= .5; // dltm = 0.; @@ -1082,9 +1035,9 @@ public: A[1] = 2. * B3 + (B0 + B5 + B6); A[2] = 2. * C3 + (C0 + C5 + C6); - double D = (A[0] * A[0] + A[1] * A[1]) + (A[2] * A[2] - 9.); + double D = (A[0] * A[0] + A[1] * A[1]) + (A[2] * A[2] - 9.); double Sl = 2. / h; - D = (1. / 3.) - ((1. / 648.) * D) * (12. - D); + D = (1. / 3.) - ((1. / 648.) * D) * (12. - D); R[0] += (A2 + A3 + A4) * S3; R[1] += (B2 + B3 + B4) * S3; @@ -1096,72 +1049,72 @@ public: sA[1] = B6 * Sl; sA[2] = C6 * Sl; - state.stepping.field = f; + state.stepping.field = f; state.stepping.newfield = false; if (Jac) { // Jacobian calculation // - double* d2A = &state.stepping.pVector[24]; - double* d3A = &state.stepping.pVector[31]; - double* d4A = &state.stepping.pVector[38]; - double d2A0 = H0[2] * d2A[1] - H0[1] * d2A[2]; - double d2B0 = H0[0] * d2A[2] - H0[2] * d2A[0]; - double d2C0 = H0[1] * d2A[0] - H0[0] * d2A[1]; - double d3A0 = H0[2] * d3A[1] - H0[1] * d3A[2]; - double d3B0 = H0[0] * d3A[2] - H0[2] * d3A[0]; - double d3C0 = H0[1] * d3A[0] - H0[0] * d3A[1]; - double d4A0 = (A0 + H0[2] * d4A[1]) - H0[1] * d4A[2]; - double d4B0 = (B0 + H0[0] * d4A[2]) - H0[2] * d4A[0]; - double d4C0 = (C0 + H0[1] * d4A[0]) - H0[0] * d4A[1]; - double d2A2 = d2A0 + d2A[0]; - double d2B2 = d2B0 + d2A[1]; - double d2C2 = d2C0 + d2A[2]; - double d3A2 = d3A0 + d3A[0]; - double d3B2 = d3B0 + d3A[1]; - double d3C2 = d3C0 + d3A[2]; - double d4A2 = d4A0 + d4A[0]; - double d4B2 = d4B0 + d4A[1]; - double d4C2 = d4C0 + d4A[2]; - double d0 = d4A[0] - A00; - double d1 = d4A[1] - A11; - double d2 = d4A[2] - A22; - double d2A3 = (d2A[0] + d2B2 * H1[2]) - d2C2 * H1[1]; - double d2B3 = (d2A[1] + d2C2 * H1[0]) - d2A2 * H1[2]; - double d2C3 = (d2A[2] + d2A2 * H1[1]) - d2B2 * H1[0]; - double d3A3 = (d3A[0] + d3B2 * H1[2]) - d3C2 * H1[1]; - double d3B3 = (d3A[1] + d3C2 * H1[0]) - d3A2 * H1[2]; - double d3C3 = (d3A[2] + d3A2 * H1[1]) - d3B2 * H1[0]; - double d4A3 = ((A3 + d0) + d4B2 * H1[2]) - d4C2 * H1[1]; - double d4B3 = ((B3 + d1) + d4C2 * H1[0]) - d4A2 * H1[2]; - double d4C3 = ((C3 + d2) + d4A2 * H1[1]) - d4B2 * H1[0]; - double d2A4 = (d2A[0] + d2B3 * H1[2]) - d2C3 * H1[1]; - double d2B4 = (d2A[1] + d2C3 * H1[0]) - d2A3 * H1[2]; - double d2C4 = (d2A[2] + d2A3 * H1[1]) - d2B3 * H1[0]; - double d3A4 = (d3A[0] + d3B3 * H1[2]) - d3C3 * H1[1]; - double d3B4 = (d3A[1] + d3C3 * H1[0]) - d3A3 * H1[2]; - double d3C4 = (d3A[2] + d3A3 * H1[1]) - d3B3 * H1[0]; - double d4A4 = ((A4 + d0) + d4B3 * H1[2]) - d4C3 * H1[1]; - double d4B4 = ((B4 + d1) + d4C3 * H1[0]) - d4A3 * H1[2]; - double d4C4 = ((C4 + d2) + d4A3 * H1[1]) - d4B3 * H1[0]; - double d2A5 = 2. * d2A4 - d2A[0]; - double d2B5 = 2. * d2B4 - d2A[1]; - double d2C5 = 2. * d2C4 - d2A[2]; - double d3A5 = 2. * d3A4 - d3A[0]; - double d3B5 = 2. * d3B4 - d3A[1]; - double d3C5 = 2. * d3C4 - d3A[2]; - double d4A5 = 2. * d4A4 - d4A[0]; - double d4B5 = 2. * d4B4 - d4A[1]; - double d4C5 = 2. * d4C4 - d4A[2]; - double d2A6 = d2B5 * H2[2] - d2C5 * H2[1]; - double d2B6 = d2C5 * H2[0] - d2A5 * H2[2]; - double d2C6 = d2A5 * H2[1] - d2B5 * H2[0]; - double d3A6 = d3B5 * H2[2] - d3C5 * H2[1]; - double d3B6 = d3C5 * H2[0] - d3A5 * H2[2]; - double d3C6 = d3A5 * H2[1] - d3B5 * H2[0]; - double d4A6 = d4B5 * H2[2] - d4C5 * H2[1]; - double d4B6 = d4C5 * H2[0] - d4A5 * H2[2]; - double d4C6 = d4A5 * H2[1] - d4B5 * H2[0]; + double* d2A = &state.stepping.pVector[24]; + double* d3A = &state.stepping.pVector[31]; + double* d4A = &state.stepping.pVector[38]; + double d2A0 = H0[2] * d2A[1] - H0[1] * d2A[2]; + double d2B0 = H0[0] * d2A[2] - H0[2] * d2A[0]; + double d2C0 = H0[1] * d2A[0] - H0[0] * d2A[1]; + double d3A0 = H0[2] * d3A[1] - H0[1] * d3A[2]; + double d3B0 = H0[0] * d3A[2] - H0[2] * d3A[0]; + double d3C0 = H0[1] * d3A[0] - H0[0] * d3A[1]; + double d4A0 = (A0 + H0[2] * d4A[1]) - H0[1] * d4A[2]; + double d4B0 = (B0 + H0[0] * d4A[2]) - H0[2] * d4A[0]; + double d4C0 = (C0 + H0[1] * d4A[0]) - H0[0] * d4A[1]; + double d2A2 = d2A0 + d2A[0]; + double d2B2 = d2B0 + d2A[1]; + double d2C2 = d2C0 + d2A[2]; + double d3A2 = d3A0 + d3A[0]; + double d3B2 = d3B0 + d3A[1]; + double d3C2 = d3C0 + d3A[2]; + double d4A2 = d4A0 + d4A[0]; + double d4B2 = d4B0 + d4A[1]; + double d4C2 = d4C0 + d4A[2]; + double d0 = d4A[0] - A00; + double d1 = d4A[1] - A11; + double d2 = d4A[2] - A22; + double d2A3 = (d2A[0] + d2B2 * H1[2]) - d2C2 * H1[1]; + double d2B3 = (d2A[1] + d2C2 * H1[0]) - d2A2 * H1[2]; + double d2C3 = (d2A[2] + d2A2 * H1[1]) - d2B2 * H1[0]; + double d3A3 = (d3A[0] + d3B2 * H1[2]) - d3C2 * H1[1]; + double d3B3 = (d3A[1] + d3C2 * H1[0]) - d3A2 * H1[2]; + double d3C3 = (d3A[2] + d3A2 * H1[1]) - d3B2 * H1[0]; + double d4A3 = ((A3 + d0) + d4B2 * H1[2]) - d4C2 * H1[1]; + double d4B3 = ((B3 + d1) + d4C2 * H1[0]) - d4A2 * H1[2]; + double d4C3 = ((C3 + d2) + d4A2 * H1[1]) - d4B2 * H1[0]; + double d2A4 = (d2A[0] + d2B3 * H1[2]) - d2C3 * H1[1]; + double d2B4 = (d2A[1] + d2C3 * H1[0]) - d2A3 * H1[2]; + double d2C4 = (d2A[2] + d2A3 * H1[1]) - d2B3 * H1[0]; + double d3A4 = (d3A[0] + d3B3 * H1[2]) - d3C3 * H1[1]; + double d3B4 = (d3A[1] + d3C3 * H1[0]) - d3A3 * H1[2]; + double d3C4 = (d3A[2] + d3A3 * H1[1]) - d3B3 * H1[0]; + double d4A4 = ((A4 + d0) + d4B3 * H1[2]) - d4C3 * H1[1]; + double d4B4 = ((B4 + d1) + d4C3 * H1[0]) - d4A3 * H1[2]; + double d4C4 = ((C4 + d2) + d4A3 * H1[1]) - d4B3 * H1[0]; + double d2A5 = 2. * d2A4 - d2A[0]; + double d2B5 = 2. * d2B4 - d2A[1]; + double d2C5 = 2. * d2C4 - d2A[2]; + double d3A5 = 2. * d3A4 - d3A[0]; + double d3B5 = 2. * d3B4 - d3A[1]; + double d3C5 = 2. * d3C4 - d3A[2]; + double d4A5 = 2. * d4A4 - d4A[0]; + double d4B5 = 2. * d4B4 - d4A[1]; + double d4C5 = 2. * d4C4 - d4A[2]; + double d2A6 = d2B5 * H2[2] - d2C5 * H2[1]; + double d2B6 = d2C5 * H2[0] - d2A5 * H2[2]; + double d2C6 = d2A5 * H2[1] - d2B5 * H2[0]; + double d3A6 = d3B5 * H2[2] - d3C5 * H2[1]; + double d3B6 = d3C5 * H2[0] - d3A5 * H2[2]; + double d3C6 = d3A5 * H2[1] - d3B5 * H2[0]; + double d4A6 = d4B5 * H2[2] - d4C5 * H2[1]; + double d4B6 = d4C5 * H2[0] - d4A5 * H2[2]; + double d4C6 = d4A5 * H2[1] - d4B5 * H2[0]; double* dR = &state.stepping.pVector[21]; dR[0] += (d2A2 + d2A3 + d2A4) * S3; @@ -1196,7 +1149,7 @@ public: return h; } -private: + private: bfield_t m_bField; }; diff --git a/Legacy/include/Acts/Seeding/AtlasSeedfinder.hpp b/Legacy/include/Acts/Seeding/AtlasSeedfinder.hpp index 460ed23e1ce8b144ac0552b9977cae2052c0f81a..e5b0a39fffa352ca1e64d4aaa30f4b4e737b8ecc 100644 --- a/Legacy/include/Acts/Seeding/AtlasSeedfinder.hpp +++ b/Legacy/include/Acts/Seeding/AtlasSeedfinder.hpp @@ -23,312 +23,280 @@ namespace Acts { namespace Legacy { - template <typename SpacePoint> - class AtlasSeedfinder - { - struct Config - { - // UNIT AS RETURNED BY m_fieldService->getField() default value in ATLAS - // was - // 5. Unit is kilo-Tesla - // double bFieldInZ = 5.; - double bFieldInZ = 0.00208; - - double SCT_rMin = 200.; - - double beamPosX = 0; - double beamPosY = 0; - double beamPosZ = 0; - double beamTiltX = 0; - double beamTiltY = 0; - }; - /////////////////////////////////////////////////////////////////// - // Public methods: - /////////////////////////////////////////////////////////////////// - - public: - /////////////////////////////////////////////////////////////////// - // Standard tool methods - /////////////////////////////////////////////////////////////////// - - AtlasSeedfinder(); - virtual ~AtlasSeedfinder(); - - /////////////////////////////////////////////////////////////////// - // Methods to initialize tool for new event or region - /////////////////////////////////////////////////////////////////// - - template <class RandIter> - void - newEvent(int, RandIter, RandIter); - - ////////////////////////////////////////////////////////////////// - // Method to initialize seeds production - ////////////////////////////////////////////////////////////////// - void - find3Sp(); - - /////////////////////////////////////////////////////////////////// - // Iterator through seeds pseudo collection produced accordingly - // methods find - /////////////////////////////////////////////////////////////////// - - const Seed<SpacePoint>* - next(); - - /////////////////////////////////////////////////////////////////// - // Configuration - /////////////////////////////////////////////////////////////////// - - const Config m_config; - - protected: - /** @name Disallow default instantiation, copy, assignment */ - //@{ - AtlasSeedfinder(const AtlasSeedfinder<SpacePoint>&) = delete; - AtlasSeedfinder<SpacePoint>& - operator=(const AtlasSeedfinder<SpacePoint>&) - = delete; - //@} - /////////////////////////////////////////////////////////////////// - // Protected data and methods - /////////////////////////////////////////////////////////////////// - - bool m_endlist; - bool m_checketa; - bool m_isvertex; - int m_nprint; - int m_nlist; - int m_maxsize; - int m_state; - // event number since tool init - int m_iteration; - float m_etamin, m_etamax; - float m_drmin, m_drminv; - float m_drmax; - float m_dzdrmin0; - float m_dzdrmax0; - float m_dzdrmin; - float m_dzdrmax; - float m_zmin; - float m_zmax; - float m_zminU; - float m_zmaxU; - float m_zminB; - float m_zmaxB; - float m_ftrig; - float m_ftrigW; - // maximum radius of outermost detector element - float r_rmax; - // size of one r-slice - float r_rstep; - - float m_dzver; - float m_dzdrver; - float m_diver; - float m_diverpps; - float m_diversss; - float m_divermax; - float m_dazmax; - float m_ptmin; - float m_ipt; - float m_ipt2; - float m_COF; - float m_K; - float m_ipt2K; - float m_ipt2C; - float m_COFK; - float m_umax; - // number of r-slices - int r_size; - int r_first; - int rf_size; - int rfz_size; - std::list<SPForSeed<SpacePoint>*>* r_Sorted; - std::list<SPForSeed<SpacePoint>*> rfz_Sorted[583]; - std::list<SPForSeed<SpacePoint>*> l_spforseed; - typename std::list<SPForSeed<SpacePoint>*>::iterator i_spforseed; - typename std::list<SPForSeed<SpacePoint>*>::iterator m_rMin; - - int m_nsaz, m_nsazv; - int m_fNmax, m_fvNmax; - int m_fNmin, m_fvNmin; - int m_zMin; - // m_nr: number of bins used in r_Sorted; r_index: index of all used bins in - // r_Sorted; r_map is number of SP in each bin in r_Sorted - int m_nr; - int* r_index; - int* r_map; - int m_nrfz, rfz_index[583], rfz_map[583]; - int rfz_b[583], rfz_t[593], rfz_ib[583][9], rfz_it[583][9]; - float m_sF; - - /////////////////////////////////////////////////////////////////// - // Tables for 3 space points seeds search - /////////////////////////////////////////////////////////////////// - - int m_maxsizeSP; - SPForSeed<SpacePoint>** m_SP; - float* m_Zo; - float* m_Tz; - float* m_R; - float* m_U; - float* m_V; - float* m_Er; - - Seed<SpacePoint>* m_seedOutput; - - std::list<InternalSeed<SpacePoint>*> l_seeds; - typename std::list<InternalSeed<SpacePoint>*>::iterator i_seed; - typename std::list<InternalSeed<SpacePoint>*>::iterator i_seede; - - std::multimap<float, InternalSeed<SpacePoint>*> m_seeds; - typename std::multimap<float, InternalSeed<SpacePoint>*>::iterator m_seed; - - std::multimap<float, InternalSeed<SpacePoint>*> m_mapOneSeeds; - InternalSeed<SpacePoint>* m_OneSeeds; - int m_maxOneSize; - int m_nOneSeeds; - int m_fillOneSeeds; - std::vector<std::pair<float, SPForSeed<SpacePoint>*>> m_CmSp; - - /////////////////////////////////////////////////////////////////// - // Beam geometry - /////////////////////////////////////////////////////////////////// - - float m_xbeam; // x-center of beam-axis - float m_ybeam; // y-center of beam-axis - float m_zbeam; // z-center of beam-axis - - /////////////////////////////////////////////////////////////////// - // Protected methods - /////////////////////////////////////////////////////////////////// - - void - buildFrameWork(); - void - buildBeamFrameWork(); - - SPForSeed<SpacePoint>* - newSpacePoint(SpacePoint* const&); - - void - newOneSeed(SPForSeed<SpacePoint>*&, - SPForSeed<SpacePoint>*&, - SPForSeed<SpacePoint>*&, - float, - float); - - void - newOneSeedWithCurvaturesComparison(SPForSeed<SpacePoint>*&, - SPForSeed<SpacePoint>*&, - float); - - void - fillSeeds(); - void - fillLists(); - void - erase(); - void - production3Sp(); - void - production3Sp(typename std::list<SPForSeed<SpacePoint>*>::iterator*, - typename std::list<SPForSeed<SpacePoint>*>::iterator*, - typename std::list<SPForSeed<SpacePoint>*>::iterator*, - typename std::list<SPForSeed<SpacePoint>*>::iterator*, - int, - int, - int&); - - void - findNext(); - bool - isZCompatible(float&); - void - convertToBeamFrameWork(SpacePoint* const&, float*); +template <typename SpacePoint> +class AtlasSeedfinder { + struct Config { + // UNIT AS RETURNED BY m_fieldService->getField() default value in ATLAS + // was + // 5. Unit is kilo-Tesla + // double bFieldInZ = 5.; + double bFieldInZ = 0.00208; + + double SCT_rMin = 200.; + + double beamPosX = 0; + double beamPosY = 0; + double beamPosZ = 0; + double beamTiltX = 0; + double beamTiltY = 0; }; + /////////////////////////////////////////////////////////////////// + // Public methods: + /////////////////////////////////////////////////////////////////// + public: /////////////////////////////////////////////////////////////////// - // Inline methods + // Standard tool methods /////////////////////////////////////////////////////////////////// - template <typename SpacePoint> - inline const Seed<SpacePoint>* - AtlasSeedfinder<SpacePoint>::next() - { - do { - if (i_seed == i_seede) { - findNext(); - if (i_seed == i_seede) { - return 0; - } - } - ++i_seed; - } while (!(*m_seed++).second->set3(*m_seedOutput)); - return (m_seedOutput); - } + AtlasSeedfinder(); + virtual ~AtlasSeedfinder(); - template <typename SpacePoint> - inline bool - AtlasSeedfinder<SpacePoint>::isZCompatible(float& Zv) - { - if (Zv < m_zminU || Zv > m_zmaxU) { - return false; - } else { - return true; - } - } + /////////////////////////////////////////////////////////////////// + // Methods to initialize tool for new event or region + /////////////////////////////////////////////////////////////////// + + template <class RandIter> + void newEvent(int, RandIter, RandIter); + + ////////////////////////////////////////////////////////////////// + // Method to initialize seeds production + ////////////////////////////////////////////////////////////////// + void find3Sp(); /////////////////////////////////////////////////////////////////// - // New space point for seeds + // Iterator through seeds pseudo collection produced accordingly + // methods find /////////////////////////////////////////////////////////////////// - template <typename SpacePoint> - inline SPForSeed<SpacePoint>* - AtlasSeedfinder<SpacePoint>::newSpacePoint(SpacePoint* const& sp) - { - SPForSeed<SpacePoint>* sps; - - float r[3]; - convertToBeamFrameWork(sp, r); - - if (m_checketa) { - // filter SP outside of eta-range - float z = (fabs(r[2]) + m_zmax); - float x = r[0] * m_dzdrmin; - float y = r[1] * m_dzdrmin; - if ((z * z) < (x * x + y * y)) { + const Seed<SpacePoint>* next(); + + /////////////////////////////////////////////////////////////////// + // Configuration + /////////////////////////////////////////////////////////////////// + + const Config m_config; + + protected: + /** @name Disallow default instantiation, copy, assignment */ + //@{ + AtlasSeedfinder(const AtlasSeedfinder<SpacePoint>&) = delete; + AtlasSeedfinder<SpacePoint>& operator=(const AtlasSeedfinder<SpacePoint>&) = + delete; + //@} + /////////////////////////////////////////////////////////////////// + // Protected data and methods + /////////////////////////////////////////////////////////////////// + + bool m_endlist; + bool m_checketa; + bool m_isvertex; + int m_nprint; + int m_nlist; + int m_maxsize; + int m_state; + // event number since tool init + int m_iteration; + float m_etamin, m_etamax; + float m_drmin, m_drminv; + float m_drmax; + float m_dzdrmin0; + float m_dzdrmax0; + float m_dzdrmin; + float m_dzdrmax; + float m_zmin; + float m_zmax; + float m_zminU; + float m_zmaxU; + float m_zminB; + float m_zmaxB; + float m_ftrig; + float m_ftrigW; + // maximum radius of outermost detector element + float r_rmax; + // size of one r-slice + float r_rstep; + + float m_dzver; + float m_dzdrver; + float m_diver; + float m_diverpps; + float m_diversss; + float m_divermax; + float m_dazmax; + float m_ptmin; + float m_ipt; + float m_ipt2; + float m_COF; + float m_K; + float m_ipt2K; + float m_ipt2C; + float m_COFK; + float m_umax; + // number of r-slices + int r_size; + int r_first; + int rf_size; + int rfz_size; + std::list<SPForSeed<SpacePoint>*>* r_Sorted; + std::list<SPForSeed<SpacePoint>*> rfz_Sorted[583]; + std::list<SPForSeed<SpacePoint>*> l_spforseed; + typename std::list<SPForSeed<SpacePoint>*>::iterator i_spforseed; + typename std::list<SPForSeed<SpacePoint>*>::iterator m_rMin; + + int m_nsaz, m_nsazv; + int m_fNmax, m_fvNmax; + int m_fNmin, m_fvNmin; + int m_zMin; + // m_nr: number of bins used in r_Sorted; r_index: index of all used bins in + // r_Sorted; r_map is number of SP in each bin in r_Sorted + int m_nr; + int* r_index; + int* r_map; + int m_nrfz, rfz_index[583], rfz_map[583]; + int rfz_b[583], rfz_t[593], rfz_ib[583][9], rfz_it[583][9]; + float m_sF; + + /////////////////////////////////////////////////////////////////// + // Tables for 3 space points seeds search + /////////////////////////////////////////////////////////////////// + + int m_maxsizeSP; + SPForSeed<SpacePoint>** m_SP; + float* m_Zo; + float* m_Tz; + float* m_R; + float* m_U; + float* m_V; + float* m_Er; + + Seed<SpacePoint>* m_seedOutput; + + std::list<InternalSeed<SpacePoint>*> l_seeds; + typename std::list<InternalSeed<SpacePoint>*>::iterator i_seed; + typename std::list<InternalSeed<SpacePoint>*>::iterator i_seede; + + std::multimap<float, InternalSeed<SpacePoint>*> m_seeds; + typename std::multimap<float, InternalSeed<SpacePoint>*>::iterator m_seed; + + std::multimap<float, InternalSeed<SpacePoint>*> m_mapOneSeeds; + InternalSeed<SpacePoint>* m_OneSeeds; + int m_maxOneSize; + int m_nOneSeeds; + int m_fillOneSeeds; + std::vector<std::pair<float, SPForSeed<SpacePoint>*>> m_CmSp; + + /////////////////////////////////////////////////////////////////// + // Beam geometry + /////////////////////////////////////////////////////////////////// + + float m_xbeam; // x-center of beam-axis + float m_ybeam; // y-center of beam-axis + float m_zbeam; // z-center of beam-axis + + /////////////////////////////////////////////////////////////////// + // Protected methods + /////////////////////////////////////////////////////////////////// + + void buildFrameWork(); + void buildBeamFrameWork(); + + SPForSeed<SpacePoint>* newSpacePoint(SpacePoint* const&); + + void newOneSeed(SPForSeed<SpacePoint>*&, SPForSeed<SpacePoint>*&, + SPForSeed<SpacePoint>*&, float, float); + + void newOneSeedWithCurvaturesComparison(SPForSeed<SpacePoint>*&, + SPForSeed<SpacePoint>*&, float); + + void fillSeeds(); + void fillLists(); + void erase(); + void production3Sp(); + void production3Sp(typename std::list<SPForSeed<SpacePoint>*>::iterator*, + typename std::list<SPForSeed<SpacePoint>*>::iterator*, + typename std::list<SPForSeed<SpacePoint>*>::iterator*, + typename std::list<SPForSeed<SpacePoint>*>::iterator*, int, + int, int&); + + void findNext(); + bool isZCompatible(float&); + void convertToBeamFrameWork(SpacePoint* const&, float*); +}; + +/////////////////////////////////////////////////////////////////// +// Inline methods +/////////////////////////////////////////////////////////////////// + +template <typename SpacePoint> +inline const Seed<SpacePoint>* AtlasSeedfinder<SpacePoint>::next() { + do { + if (i_seed == i_seede) { + findNext(); + if (i_seed == i_seede) { return 0; } } + ++i_seed; + } while (!(*m_seed++).second->set3(*m_seedOutput)); + return (m_seedOutput); +} + +template <typename SpacePoint> +inline bool AtlasSeedfinder<SpacePoint>::isZCompatible(float& Zv) { + if (Zv < m_zminU || Zv > m_zmaxU) { + return false; + } else { + return true; + } +} + +/////////////////////////////////////////////////////////////////// +// New space point for seeds +/////////////////////////////////////////////////////////////////// - if (i_spforseed != l_spforseed.end()) { - sps = (*i_spforseed++); - sps->set(sp, r); - } else { - l_spforseed.push_back((sps = new SPForSeed<SpacePoint>(sp, r))); - i_spforseed = l_spforseed.end(); +template <typename SpacePoint> +inline SPForSeed<SpacePoint>* AtlasSeedfinder<SpacePoint>::newSpacePoint( + SpacePoint* const& sp) { + SPForSeed<SpacePoint>* sps; + + float r[3]; + convertToBeamFrameWork(sp, r); + + if (m_checketa) { + // filter SP outside of eta-range + float z = (fabs(r[2]) + m_zmax); + float x = r[0] * m_dzdrmin; + float y = r[1] * m_dzdrmin; + if ((z * z) < (x * x + y * y)) { + return 0; } + } - return sps; + if (i_spforseed != l_spforseed.end()) { + sps = (*i_spforseed++); + sps->set(sp, r); + } else { + l_spforseed.push_back((sps = new SPForSeed<SpacePoint>(sp, r))); + i_spforseed = l_spforseed.end(); } - /////////////////////////////////////////////////////////////////// - // Object-function for curvature seeds comparison - /////////////////////////////////////////////////////////////////// + return sps; +} - class comCurvature - { - public: - template <typename SpacePoint> - bool - operator()(const std::pair<float, Acts::Legacy::SPForSeed<SpacePoint>*>& i1, - const std::pair<float, Acts::Legacy::SPForSeed<SpacePoint>*>& i2) - { - return i1.first < i2.first; - } - }; -} // end of Legacy namespace -} // end of Acts namespace +/////////////////////////////////////////////////////////////////// +// Object-function for curvature seeds comparison +/////////////////////////////////////////////////////////////////// + +class comCurvature { + public: + template <typename SpacePoint> + bool operator()( + const std::pair<float, Acts::Legacy::SPForSeed<SpacePoint>*>& i1, + const std::pair<float, Acts::Legacy::SPForSeed<SpacePoint>*>& i2) { + return i1.first < i2.first; + } +}; +} // namespace Legacy +} // namespace Acts #include "Acts/Seeding/AtlasSeedfinder.ipp" diff --git a/Legacy/include/Acts/Seeding/AtlasSeedfinder.ipp b/Legacy/include/Acts/Seeding/AtlasSeedfinder.ipp index af4d06f84b6063da157733b6ccc3d7b938b1bd86..2432560540276545e48b9269f84a43f863e6eead 100644 --- a/Legacy/include/Acts/Seeding/AtlasSeedfinder.ipp +++ b/Legacy/include/Acts/Seeding/AtlasSeedfinder.ipp @@ -17,29 +17,27 @@ /////////////////////////////////////////////////////////////////// template <typename SpacePoint> -Acts::Legacy::AtlasSeedfinder<SpacePoint>::AtlasSeedfinder() -{ - +Acts::Legacy::AtlasSeedfinder<SpacePoint>::AtlasSeedfinder() { m_checketa = false; - m_maxsize = 50000; - m_ptmin = 400.; - m_etamin = 0.; - m_etamax = 2.7; + m_maxsize = 50000; + m_ptmin = 400.; + m_etamin = 0.; + m_etamax = 2.7; // delta R minimum & maximum within a seed - m_drmin = 5.; + m_drmin = 5.; m_drminv = 20.; - m_drmax = 270.; + m_drmax = 270.; // restrict z coordinate of particle origin m_zmin = -250.; m_zmax = +250.; // radius of detector in mm - r_rmax = 600.; + r_rmax = 600.; r_rstep = 2.; // checking if Z is compatible: // m_dzver is related to delta-Z // m_dzdrver is related to delta-Z divided by delta-R - m_dzver = 5.; + m_dzver = 5.; m_dzdrver = .02; // shift all spacepoints by this offset such that the beam can be assumed to @@ -54,7 +52,7 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::AtlasSeedfinder() // config // max impact parameters // m_diver = max ppp impact params - m_diver = 10.; + m_diver = 10.; m_diverpps = 1.7; m_diversss = 50; m_divermax = 20.; @@ -63,25 +61,25 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::AtlasSeedfinder() // limit for sp compatible with 1 middle space point // ridiculously large to be EXTRA safe // only actually keep 5 of these max 5000 (m_maxOneSize of m_maxsizeSP) - m_maxsizeSP = 5000; + m_maxsizeSP = 5000; m_maxOneSize = 5; // cache: counting if ran already m_state = 0; - m_nlist = 0; - m_endlist = true; - r_Sorted = 0; - r_index = 0; - r_map = 0; - m_SP = 0; - m_R = 0; - m_Tz = 0; - m_Er = 0; - m_U = 0; - m_V = 0; - m_Zo = 0; - m_OneSeeds = 0; + m_nlist = 0; + m_endlist = true; + r_Sorted = 0; + r_index = 0; + r_map = 0; + m_SP = 0; + m_R = 0; + m_Tz = 0; + m_Er = 0; + m_U = 0; + m_V = 0; + m_Zo = 0; + m_OneSeeds = 0; m_seedOutput = 0; // Build framework @@ -94,8 +92,7 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::AtlasSeedfinder() // Destructor /////////////////////////////////////////////////////////////////// template <class SpacePoint> -Acts::Legacy::AtlasSeedfinder<SpacePoint>::~AtlasSeedfinder() -{ +Acts::Legacy::AtlasSeedfinder<SpacePoint>::~AtlasSeedfinder() { if (r_index) { delete[] r_index; } @@ -152,16 +149,14 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::~AtlasSeedfinder() /////////////////////////////////////////////////////////////////// template <typename SpacePoint> template <class RandIter> -void -Acts::Legacy::AtlasSeedfinder<SpacePoint>::newEvent(int iteration, - RandIter spBegin, - RandIter spEnd) -{ +void Acts::Legacy::AtlasSeedfinder<SpacePoint>::newEvent(int iteration, + RandIter spBegin, + RandIter spEnd) { iteration <= 0 ? m_iteration = 0 : m_iteration = iteration; erase(); m_dzdrmin = m_dzdrmin0; m_dzdrmax = m_dzdrmax0; - m_umax = 100.; + m_umax = 100.; // if first event r_first = 0; if (!m_iteration) { @@ -174,7 +169,7 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::newEvent(int iteration, // scattering of min pT track m_ipt2C = m_ipt2 * m_COF; // scattering times curvature (missing: div by pT) - m_COFK = m_COF * (m_K * m_K); + m_COFK = m_COF * (m_K * m_K); i_spforseed = l_spforseed.begin(); } // only if not first event @@ -184,10 +179,10 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::newEvent(int iteration, } float irstep = 1. / r_rstep; - int irmax = r_size - 1; + int irmax = r_size - 1; // TODO using 3 member vars to clear r_Sorted for (int i = 0; i != m_nr; ++i) { - int n = r_index[i]; + int n = r_index[i]; r_map[n] = 0; r_Sorted[n].clear(); } @@ -198,7 +193,6 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::newEvent(int iteration, // store number of SP per bin in r_map RandIter sp = spBegin; for (; sp != spEnd; ++sp) { - Acts::Legacy::SPForSeed<SpacePoint>* sps = newSpacePoint((*sp)); if (!sps) { continue; @@ -226,20 +220,18 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::newEvent(int iteration, /////////////////////////////////////////////////////////////////// template <class SpacePoint> -void -Acts::Legacy::AtlasSeedfinder<SpacePoint>::find3Sp() -{ +void Acts::Legacy::AtlasSeedfinder<SpacePoint>::find3Sp() { m_zminU = m_zmin; m_zmaxU = m_zmax; if ((m_state == 0) || m_nlist) { - i_seede = l_seeds.begin(); - m_state = 1; - m_nlist = 0; + i_seede = l_seeds.begin(); + m_state = 1; + m_nlist = 0; m_endlist = true; - m_fvNmin = 0; - m_fNmin = 0; - m_zMin = 0; + m_fvNmin = 0; + m_fNmin = 0; + m_zMin = 0; production3Sp(); } i_seed = l_seeds.begin(); @@ -250,9 +242,7 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::find3Sp() // Find next set space points /////////////////////////////////////////////////////////////////// template <class SpacePoint> -void -Acts::Legacy::AtlasSeedfinder<SpacePoint>::findNext() -{ +void Acts::Legacy::AtlasSeedfinder<SpacePoint>::findNext() { if (m_endlist) { return; } @@ -270,9 +260,7 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::findNext() // Initiate frame work for seed generator /////////////////////////////////////////////////////////////////// template <class SpacePoint> -void -Acts::Legacy::AtlasSeedfinder<SpacePoint>::buildFrameWork() -{ +void Acts::Legacy::AtlasSeedfinder<SpacePoint>::buildFrameWork() { m_ptmin = fabs(m_ptmin); if (m_ptmin < 100.) { @@ -294,30 +282,30 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::buildFrameWork() // scattering factor. depends on error, forward direction and distance between // SP - m_COF = 134 * .05 * 9.; - m_ipt = 1. / fabs(.9 * m_ptmin); + m_COF = 134 * .05 * 9.; + m_ipt = 1. / fabs(.9 * m_ptmin); m_ipt2 = m_ipt * m_ipt; - m_K = 0.; + m_K = 0.; // set all counters zero m_nsaz = m_nsazv = m_nr = m_nrfz = 0; // Build radius sorted containers // - r_size = int((r_rmax + .1) / r_rstep); + r_size = int((r_rmax + .1) / r_rstep); r_Sorted = new std::list<Acts::Legacy::SPForSeed<SpacePoint>*>[r_size]; - r_index = new int[r_size]; - r_map = new int[r_size]; + r_index = new int[r_size]; + r_map = new int[r_size]; for (int i = 0; i != r_size; ++i) { r_index[i] = 0; - r_map[i] = 0; + r_map[i] = 0; } // Build radius-azimuthal sorted containers // - const float pi2 = 2. * M_PI; - const int NFmax = 53; - const float sFmax = float(NFmax) / pi2; + const float pi2 = 2. * M_PI; + const int NFmax = 53; + const float sFmax = float(NFmax) / pi2; const float m_sFmin = 100. / 60.; // make phi-slices for 400MeV tracks, unless ptMin is even smaller float ptm = 400.; @@ -341,13 +329,12 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::buildFrameWork() m_nrfz = 0; for (int i = 0; i != 583; ++i) { rfz_index[i] = 0; - rfz_map[i] = 0; + rfz_map[i] = 0; } // Build maps for radius-azimuthal-Z sorted collections // for (int f = 0; f <= m_fNmax; ++f) { - int fb = f - 1; if (fb < 0) { fb = m_fNmax; @@ -360,12 +347,11 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::buildFrameWork() // For each azimuthal region loop through all Z regions // for (int z = 0; z != 11; ++z) { - - int a = f * 11 + z; - int b = fb * 11 + z; - int c = ft * 11 + z; - rfz_b[a] = 3; - rfz_t[a] = 3; + int a = f * 11 + z; + int b = fb * 11 + z; + int c = ft * 11 + z; + rfz_b[a] = 3; + rfz_t[a] = 3; rfz_ib[a][0] = a; rfz_it[a][0] = a; rfz_ib[a][1] = b; @@ -373,8 +359,7 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::buildFrameWork() rfz_ib[a][2] = c; rfz_it[a][2] = c; if (z == 5) { - - rfz_t[a] = 9; + rfz_t[a] = 9; rfz_it[a][3] = a + 1; rfz_it[a][4] = b + 1; rfz_it[a][5] = c + 1; @@ -382,29 +367,25 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::buildFrameWork() rfz_it[a][7] = b - 1; rfz_it[a][8] = c - 1; } else if (z > 5) { - - rfz_b[a] = 6; + rfz_b[a] = 6; rfz_ib[a][3] = a - 1; rfz_ib[a][4] = b - 1; rfz_ib[a][5] = c - 1; if (z < 10) { - - rfz_t[a] = 6; + rfz_t[a] = 6; rfz_it[a][3] = a + 1; rfz_it[a][4] = b + 1; rfz_it[a][5] = c + 1; } } else { - - rfz_b[a] = 6; + rfz_b[a] = 6; rfz_ib[a][3] = a + 1; rfz_ib[a][4] = b + 1; rfz_ib[a][5] = c + 1; if (z > 0) { - - rfz_t[a] = 6; + rfz_t[a] = 6; rfz_it[a][3] = a - 1; rfz_it[a][4] = b - 1; rfz_it[a][5] = c - 1; @@ -412,12 +393,12 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::buildFrameWork() } if (z == 3) { - rfz_b[a] = 9; + rfz_b[a] = 9; rfz_ib[a][6] = a + 2; rfz_ib[a][7] = b + 2; rfz_ib[a][8] = c + 2; } else if (z == 7) { - rfz_b[a] = 9; + rfz_b[a] = 9; rfz_ib[a][6] = a - 2; rfz_ib[a][7] = b - 2; rfz_ib[a][8] = c - 2; @@ -454,7 +435,7 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::buildFrameWork() m_seedOutput = new Acts::Legacy::Seed<SpacePoint>(); } - i_seed = l_seeds.begin(); + i_seed = l_seeds.begin(); i_seede = l_seeds.end(); } @@ -462,10 +443,7 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::buildFrameWork() // Initiate beam frame work for seed generator /////////////////////////////////////////////////////////////////// template <class SpacePoint> -void -Acts::Legacy::AtlasSeedfinder<SpacePoint>::buildBeamFrameWork() -{ - +void Acts::Legacy::AtlasSeedfinder<SpacePoint>::buildBeamFrameWork() { double bx = m_config.beamPosX; double by = m_config.beamPosY; double bz = m_config.beamPosZ; @@ -479,12 +457,8 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::buildBeamFrameWork() // Initiate beam frame work for seed generator /////////////////////////////////////////////////////////////////// template <class SpacePoint> -void -Acts::Legacy::AtlasSeedfinder<SpacePoint>::convertToBeamFrameWork( - SpacePoint* const& sp, - float* r) -{ - +void Acts::Legacy::AtlasSeedfinder<SpacePoint>::convertToBeamFrameWork( + SpacePoint* const& sp, float* r) { r[0] = float(sp->x) - m_xbeam; r[1] = float(sp->y) - m_ybeam; r[2] = float(sp->z) - m_zbeam; @@ -494,13 +468,11 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::convertToBeamFrameWork( // Initiate space points seed maker /////////////////////////////////////////////////////////////////// template <class SpacePoint> -void -Acts::Legacy::AtlasSeedfinder<SpacePoint>::fillLists() -{ +void Acts::Legacy::AtlasSeedfinder<SpacePoint>::fillLists() { const float pi2 = 2. * M_PI; typename std::list<Acts::Legacy::SPForSeed<SpacePoint>*>::iterator r, re; - int ir0 = 0; + int ir0 = 0; bool ibl = false; r_first = 0; @@ -508,12 +480,11 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::fillLists() r_first = m_config.SCT_rMin / r_rstep; } for (int i = r_first; i != r_size; ++i) { - if (!r_map[i]) { continue; } - r = r_Sorted[i].begin(); + r = r_Sorted[i].begin(); re = r_Sorted[i].end(); if (ir0 == 0) { @@ -534,7 +505,6 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::fillLists() } for (; r != re; ++r) { - // Azimuthal (Phi) angle sort // bin nr "f" is phi * phi-slices float F = (*r)->phi(); @@ -549,7 +519,7 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::fillLists() f = 0; } - int z; + int z; float Z = (*r)->z(); // Azimuthal angle and Z-coordinate sort @@ -557,16 +527,17 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::fillLists() // space-point if (Z > 0.) { Z < 250. ? z = 5 - : Z < 450. - ? z = 6 - : Z < 925. ? z = 7 - : Z < 1400. ? z = 8 : Z < 2500. ? z = 9 : z = 10; + : Z < 450. ? z = 6 + : Z < 925. ? z = 7 + : Z < 1400. ? z = 8 + : Z < 2500. ? z = 9 : z = 10; } else { - Z > -250. ? z = 5 - : Z > -450. - ? z = 4 - : Z > -925. ? z = 3 - : Z > -1400. ? z = 2 : Z > -2500. ? z = 1 : z = 0; + Z > -250. + ? z = 5 + : Z > -450. + ? z = 4 + : Z > -925. ? z = 3 + : Z > -1400. ? z = 2 : Z > -2500. ? z = 1 : z = 0; } // calculate bin nr "n" for self made r-phi-z sorted 3D array "rfz_Sorted" // record number of sp in m_nsaz @@ -588,28 +559,24 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::fillLists() // Erase space point information /////////////////////////////////////////////////////////////////// template <class SpacePoint> -void -Acts::Legacy::AtlasSeedfinder<SpacePoint>::erase() -{ +void Acts::Legacy::AtlasSeedfinder<SpacePoint>::erase() { for (int i = 0; i != m_nrfz; ++i) { - int n = rfz_index[i]; + int n = rfz_index[i]; rfz_map[n] = 0; rfz_Sorted[n].clear(); } m_state = 0; - m_nsaz = 0; + m_nsaz = 0; m_nsazv = 0; - m_nrfz = 0; + m_nrfz = 0; } /////////////////////////////////////////////////////////////////// // Production 3 space points seeds /////////////////////////////////////////////////////////////////// template <class SpacePoint> -void -Acts::Legacy::AtlasSeedfinder<SpacePoint>::production3Sp() -{ +void Acts::Legacy::AtlasSeedfinder<SpacePoint>::production3Sp() { // if less than 3 sp in total if (m_nsaz < 3) { return; @@ -626,7 +593,6 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::production3Sp() // Loop through all azimuthal regions // for (int f = m_fNmin; f <= m_fNmax; ++f) { - // For each azimuthal region loop through all Z regions // first for barrel, then left EC, then right EC int z = 0; @@ -634,38 +600,35 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::production3Sp() z = m_zMin; } for (; z != 11; ++z) { - int a = f * 11 + ZI[z]; if (!rfz_map[a]) { continue; } int NB = 0, NT = 0; for (int i = 0; i != rfz_b[a]; ++i) { - int an = rfz_ib[a][i]; // if bin has no entry: continue if (!rfz_map[an]) { continue; } // assign begin-pointer and end-pointer of current bin to rb and rbe - rb[NB] = rfz_Sorted[an].begin(); + rb[NB] = rfz_Sorted[an].begin(); rbe[NB++] = rfz_Sorted[an].end(); } for (int i = 0; i != rfz_t[a]; ++i) { - int an = rfz_it[a][i]; // if bin has no entry: continue if (!rfz_map[an]) { continue; } // assign begin-pointer and end-pointer of current bin to rt and rte - rt[NT] = rfz_Sorted[an].begin(); + rt[NT] = rfz_Sorted[an].begin(); rte[NT++] = rfz_Sorted[an].end(); } production3Sp(rb, rbe, rt, rte, NB, NT, nseed); if (!m_endlist) { m_fNmin = f; - m_zMin = z; + m_zMin = z; return; } } @@ -677,26 +640,22 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::production3Sp() // Production 3 space points seeds for full scan /////////////////////////////////////////////////////////////////// template <class SpacePoint> -void -Acts::Legacy::AtlasSeedfinder<SpacePoint>::production3Sp( +void Acts::Legacy::AtlasSeedfinder<SpacePoint>::production3Sp( typename std::list<Acts::Legacy::SPForSeed<SpacePoint>*>::iterator* rb, typename std::list<Acts::Legacy::SPForSeed<SpacePoint>*>::iterator* rbe, typename std::list<Acts::Legacy::SPForSeed<SpacePoint>*>::iterator* rt, typename std::list<Acts::Legacy::SPForSeed<SpacePoint>*>::iterator* rte, - int NB, - int NT, - int& nseed) -{ + int NB, int NT, int& nseed) { typename std::list<Acts::Legacy::SPForSeed<SpacePoint>*>::iterator r0 = rb[0], r; if (!m_endlist) { - r0 = m_rMin; + r0 = m_rMin; m_endlist = true; } float ipt2K = m_ipt2K; float ipt2C = m_ipt2C; - float COFK = m_COFK; + float COFK = m_COFK; float imaxp = m_diver; float imaxs = m_divermax; @@ -705,24 +664,21 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::production3Sp( // Loop through all space points // first bottom bin used as "current bin" for middle spacepoints for (; r0 != rbe[0]; ++r0) { - m_nOneSeeds = 0; m_mapOneSeeds.clear(); float R = (*r0)->radius(); const int sur0 = (*r0)->surface(); - float X = (*r0)->x(); - float Y = (*r0)->y(); - float Z = (*r0)->z(); - int Nb = 0; + float X = (*r0)->x(); + float Y = (*r0)->y(); + float Z = (*r0)->z(); + int Nb = 0; // Bottom links production // for (int i = 0; i != NB; ++i) { - for (r = rb[i]; r != rbe[i]; ++r) { - float Rb = (*r)->radius(); float dR = R - Rb; // if deltaR larger than deltaRMax, store spacepoint counter position in @@ -736,15 +692,15 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::production3Sp( // if dR is smaller than drmin, stop processing this bottombin // because it has no more sp with lower radii // OR break because processing PPP and encountered SCT SP - if (dR < m_drmin - || (m_iteration && (*r)->spacepoint->clusterList().second)) { + if (dR < m_drmin || + (m_iteration && (*r)->spacepoint->clusterList().second)) { break; } if ((*r)->surface() == sur0) { continue; } // forward direction of SP duplet - float Tz = (Z - (*r)->z()) / dR; + float Tz = (Z - (*r)->z()) / dR; float aTz = fabs(Tz); // why also exclude seeds with small pseudorapidity?? if (aTz < m_dzdrmin || aTz > m_dzdrmax) { @@ -772,9 +728,7 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::production3Sp( // Top links production // for (int i = 0; i != NT; ++i) { - for (r = rt[i]; r != rte[i]; ++r) { - float Rt = (*r)->radius(); float dR = Rt - R; @@ -790,7 +744,7 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::production3Sp( continue; } - float Tz = ((*r)->z() - Z) / dR; + float Tz = ((*r)->z() - Z) / dR; float aTz = fabs(Tz); if (aTz < m_dzdrmin || aTz > m_dzdrmax) { @@ -816,11 +770,10 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::production3Sp( } float covr0 = (*r0)->covr(); float covz0 = (*r0)->covz(); - float ax = X / R; - float ay = Y / R; + float ax = X / R; + float ay = Y / R; for (int i = 0; i != Nt; ++i) { - Acts::Legacy::SPForSeed<SpacePoint>* sp = m_SP[i]; float dx = sp->x() - X; @@ -844,9 +797,9 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::production3Sp( m_Tz[i] = tz; m_Zo[i] = Z - R * tz; - m_R[i] = dr; - m_U[i] = x * r2; - m_V[i] = y * r2; + m_R[i] = dr; + m_U[i] = x * r2; + m_V[i] = y * r2; m_Er[i] = ((covz0 + sp->covz()) + (tz * tz) * (covr0 + sp->covr())) * r2; } covr0 *= .5; @@ -855,16 +808,15 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::production3Sp( // Three space points comparison // for (int b = 0; b != Nb; ++b) { - - float Zob = m_Zo[b]; - float Tzb = m_Tz[b]; + float Zob = m_Zo[b]; + float Tzb = m_Tz[b]; float Rb2r = m_R[b] * covr0; float Rb2z = m_R[b] * covz0; - float Erb = m_Er[b]; - float Vb = m_V[b]; - float Ub = m_U[b]; + float Erb = m_Er[b]; + float Vb = m_V[b]; + float Ub = m_U[b]; // Tzb2 = 1/sin^2(theta) - float Tzb2 = (1. + Tzb * Tzb); + float Tzb2 = (1. + Tzb * Tzb); float sTzb2 = sqrt(Tzb2); // CSA = curvature^2/(pT^2 * sin^2(theta)) * scatteringFactor float CSA = Tzb2 * COFK; @@ -876,10 +828,9 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::production3Sp( } for (int t = Nb; t != Nt; ++t) { - - float dT = ((Tzb - m_Tz[t]) * (Tzb - m_Tz[t]) - m_R[t] * Rb2z - - (Erb + m_Er[t])) - - (m_R[t] * Rb2r) * ((Tzb + m_Tz[t]) * (Tzb + m_Tz[t])); + float dT = ((Tzb - m_Tz[t]) * (Tzb - m_Tz[t]) - m_R[t] * Rb2z - + (Erb + m_Er[t])) - + (m_R[t] * Rb2r) * ((Tzb + m_Tz[t]) * (Tzb + m_Tz[t])); if (dT > ICSA) { continue; } @@ -888,9 +839,9 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::production3Sp( if (dU == 0.) { continue; } - float A = (m_V[t] - Vb) / dU; + float A = (m_V[t] - Vb) / dU; float S2 = 1. + A * A; - float B = Vb - A * Ub; + float B = Vb - A * Ub; float B2 = B * B; // B2/S2=1/helixradius^2 if (B2 > ipt2K * S2 || dT * S2 > B2 * CSA) { @@ -929,18 +880,13 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::production3Sp( // New 3 space points pro seeds /////////////////////////////////////////////////////////////////// template <class SpacePoint> -void -Acts::Legacy::AtlasSeedfinder<SpacePoint>::newOneSeed( +void Acts::Legacy::AtlasSeedfinder<SpacePoint>::newOneSeed( Acts::Legacy::SPForSeed<SpacePoint>*& p1, Acts::Legacy::SPForSeed<SpacePoint>*& p2, - Acts::Legacy::SPForSeed<SpacePoint>*& p3, - float z, - float q) -{ + Acts::Legacy::SPForSeed<SpacePoint>*& p3, float z, float q) { // if the number of seeds already in m_OneSeeds does not exceed m_maxOneSize // then insert the current SP into m_mapOneSeeds and m_OneSeeds. if (m_nOneSeeds < m_maxOneSize) { - m_OneSeeds[m_nOneSeeds].set(p1, p2, p3, z); m_mapOneSeeds.insert(std::make_pair(q, m_OneSeeds + m_nOneSeeds)); ++m_nOneSeeds; @@ -953,9 +899,9 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::newOneSeed( // Then remove all entries after the newly inserted entry equal to the new // seed. else { - typename std::multimap<float, Acts::Legacy::InternalSeed<SpacePoint>*>:: - reverse_iterator l - = m_mapOneSeeds.rbegin(); + typename std::multimap< + float, Acts::Legacy::InternalSeed<SpacePoint>*>::reverse_iterator l = + m_mapOneSeeds.rbegin(); if ((*l).first <= q) { return; @@ -964,9 +910,9 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::newOneSeed( Acts::Legacy::InternalSeed<SpacePoint>* s = (*l).second; s->set(p1, p2, p3, z); - typename std::multimap<float, - Acts::Legacy::InternalSeed<SpacePoint>*>::iterator i - = m_mapOneSeeds.insert(std::make_pair(q, s)); + typename std::multimap< + float, Acts::Legacy::InternalSeed<SpacePoint>*>::iterator i = + m_mapOneSeeds.insert(std::make_pair(q, s)); for (++i; i != m_mapOneSeeds.end(); ++i) { if ((*i).second == s) { @@ -981,39 +927,36 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::newOneSeed( // New 3 space points pro seeds production /////////////////////////////////////////////////////////////////// template <class SpacePoint> -void -Acts::Legacy::AtlasSeedfinder<SpacePoint>::newOneSeedWithCurvaturesComparison( - Acts::Legacy::SPForSeed<SpacePoint>*& SPb, - Acts::Legacy::SPForSeed<SpacePoint>*& SP0, - float Zob) -{ +void Acts::Legacy::AtlasSeedfinder<SpacePoint>:: + newOneSeedWithCurvaturesComparison( + Acts::Legacy::SPForSeed<SpacePoint>*& SPb, + Acts::Legacy::SPForSeed<SpacePoint>*& SP0, float Zob) { // allowed (1/helixradius)-delta between 2 seeds const float dC = .00003; - bool pixb = !SPb->spacepoint->clusterList().second; - float ub = SPb->quality(); - float u0 = SP0->quality(); + bool pixb = !SPb->spacepoint->clusterList().second; + float ub = SPb->quality(); + float u0 = SP0->quality(); std::sort(m_CmSp.begin(), m_CmSp.end(), Acts::Legacy::comCurvature()); - typename std::vector<std::pair<float, Acts::Legacy::SPForSeed<SpacePoint>*>>:: - iterator j, + typename std::vector< + std::pair<float, Acts::Legacy::SPForSeed<SpacePoint>*>>::iterator j, jn, i = m_CmSp.begin(), ie = m_CmSp.end(); jn = i; for (; i != ie; ++i) { - - float u = (*i).second->param(); + float u = (*i).second->param(); float Im = (*i).second->param(); bool pixt = !(*i).second->spacepoint->clusterList().second; const int Sui = (*i).second->surface(); - float Ri = (*i).second->radius(); - float Ci1 = (*i).first - dC; - float Ci2 = (*i).first + dC; - float Rmi = 0.; - float Rma = 0.; - bool in = false; + float Ri = (*i).second->radius(); + float Ci1 = (*i).first - dC; + float Ci2 = (*i).first + dC; + float Rmi = 0.; + float Rma = 0.; + bool in = false; if (!pixb) { u -= 400.; @@ -1059,7 +1002,7 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::newOneSeedWithCurvaturesComparison( } } else { // first found compatible seed: add 200 to quality - in = true; + in = true; Rma = Rmi = Rj; u -= 200.; } @@ -1092,15 +1035,13 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::newOneSeedWithCurvaturesComparison( // Fill seeds /////////////////////////////////////////////////////////////////// template <class SpacePoint> -void -Acts::Legacy::AtlasSeedfinder<SpacePoint>::fillSeeds() -{ +void Acts::Legacy::AtlasSeedfinder<SpacePoint>::fillSeeds() { m_fillOneSeeds = 0; - typename std::multimap<float, - Acts::Legacy::InternalSeed<SpacePoint>*>::iterator lf - = m_mapOneSeeds.begin(), - l = m_mapOneSeeds.begin(), le = m_mapOneSeeds.end(); + typename std::multimap<float, Acts::Legacy::InternalSeed<SpacePoint> + *>::iterator lf = m_mapOneSeeds.begin(), + l = m_mapOneSeeds.begin(), + le = m_mapOneSeeds.end(); if (l == le) { return; @@ -1109,9 +1050,8 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::fillSeeds() Acts::Legacy::InternalSeed<SpacePoint>* s; for (; l != le; ++l) { - float w = (*l).first; - s = (*l).second; + s = (*l).second; if (l != lf && s->spacepoint0()->radius() < 43. && w > -200.) { continue; } @@ -1120,7 +1060,7 @@ Acts::Legacy::AtlasSeedfinder<SpacePoint>::fillSeeds() } if (i_seede != l_seeds.end()) { - s = (*i_seede++); + s = (*i_seede++); *s = *(*l).second; } else { s = new Acts::Legacy::InternalSeed<SpacePoint>(*(*l).second); diff --git a/Legacy/include/Acts/Seeding/LegacyInternalSeed.hpp b/Legacy/include/Acts/Seeding/LegacyInternalSeed.hpp index f6bfaa40f933a2fb7cb1ff2a394115e197b4f516..932f6edd56eed970be7e5356e3c1fdb32d8ced23 100644 --- a/Legacy/include/Acts/Seeding/LegacyInternalSeed.hpp +++ b/Legacy/include/Acts/Seeding/LegacyInternalSeed.hpp @@ -16,200 +16,155 @@ namespace Acts { namespace Legacy { - template <typename SpacePoint> - class InternalSeed - { - - ///////////////////////////////////////////////////////////////////////////////// - // Public methods: - ///////////////////////////////////////////////////////////////////////////////// - - public: - InternalSeed(); - InternalSeed(SPForSeed<SpacePoint>*&, - SPForSeed<SpacePoint>*&, - SPForSeed<SpacePoint>*&, - float); - InternalSeed(const InternalSeed<SpacePoint>&); - virtual ~InternalSeed(); - InternalSeed<SpacePoint>& - operator=(const InternalSeed<SpacePoint>&); - - SPForSeed<SpacePoint>* - spacepoint0() - { - return m_s0; - } - SPForSeed<SpacePoint>* - spacepoint1() - { - return m_s1; - } - SPForSeed<SpacePoint>* - spacepoint2() - { - return m_s2; - } - const float& - z() const - { - return m_z; - } - const float& - quality() const - { - return m_q; - } - - void - set(SPForSeed<SpacePoint>*&, - SPForSeed<SpacePoint>*&, - SPForSeed<SpacePoint>*&, - float); - - bool - setQuality(float); - - bool - set3(Acts::Legacy::Seed<SpacePoint>&); - - protected: - SPForSeed<SpacePoint>* m_s0; - SPForSeed<SpacePoint>* m_s1; - SPForSeed<SpacePoint>* m_s2; - float m_z; - float m_q; - }; - +template <typename SpacePoint> +class InternalSeed { ///////////////////////////////////////////////////////////////////////////////// - // Inline methods + // Public methods: ///////////////////////////////////////////////////////////////////////////////// - template <typename SpacePoint> - inline InternalSeed<SpacePoint>::InternalSeed() - { - m_s0 = 0; - m_s1 = 0; - m_s2 = 0; - m_z = 0.; - m_q = 0.; + public: + InternalSeed(); + InternalSeed(SPForSeed<SpacePoint>*&, SPForSeed<SpacePoint>*&, + SPForSeed<SpacePoint>*&, float); + InternalSeed(const InternalSeed<SpacePoint>&); + virtual ~InternalSeed(); + InternalSeed<SpacePoint>& operator=(const InternalSeed<SpacePoint>&); + + SPForSeed<SpacePoint>* spacepoint0() { return m_s0; } + SPForSeed<SpacePoint>* spacepoint1() { return m_s1; } + SPForSeed<SpacePoint>* spacepoint2() { return m_s2; } + const float& z() const { return m_z; } + const float& quality() const { return m_q; } + + void set(SPForSeed<SpacePoint>*&, SPForSeed<SpacePoint>*&, + SPForSeed<SpacePoint>*&, float); + + bool setQuality(float); + + bool set3(Acts::Legacy::Seed<SpacePoint>&); + + protected: + SPForSeed<SpacePoint>* m_s0; + SPForSeed<SpacePoint>* m_s1; + SPForSeed<SpacePoint>* m_s2; + float m_z; + float m_q; +}; + +///////////////////////////////////////////////////////////////////////////////// +// Inline methods +///////////////////////////////////////////////////////////////////////////////// + +template <typename SpacePoint> +inline InternalSeed<SpacePoint>::InternalSeed() { + m_s0 = 0; + m_s1 = 0; + m_s2 = 0; + m_z = 0.; + m_q = 0.; +} + +template <typename SpacePoint> +inline InternalSeed<SpacePoint>& InternalSeed<SpacePoint>::operator=( + const InternalSeed& sp) { + if (&sp != this) { + m_z = sp.m_z; + m_q = sp.m_q; + m_s0 = sp.m_s0; + m_s1 = sp.m_s1; + m_s2 = sp.m_s2; } - - template <typename SpacePoint> - inline InternalSeed<SpacePoint>& - InternalSeed<SpacePoint>::operator=(const InternalSeed& sp) - { - if (&sp != this) { - - m_z = sp.m_z; - m_q = sp.m_q; - m_s0 = sp.m_s0; - m_s1 = sp.m_s1; - m_s2 = sp.m_s2; + return (*this); +} + +template <typename SpacePoint> +inline InternalSeed<SpacePoint>::InternalSeed(SPForSeed<SpacePoint>*& s0, + SPForSeed<SpacePoint>*& s1, + SPForSeed<SpacePoint>*& s2, + float z) { + set(s0, s1, s2, z); + m_q = 0.; +} + +///////////////////////////////////////////////////////////////////////////////// +// Copy constructor +///////////////////////////////////////////////////////////////////////////////// + +template <typename SpacePoint> +inline InternalSeed<SpacePoint>::InternalSeed(const InternalSeed& sp) + : m_s0(sp.m_s0), m_s1(sp.m_s1), m_s2(sp.m_s2) { + *this = sp; +} + +///////////////////////////////////////////////////////////////////////////////// +// Destructor +///////////////////////////////////////////////////////////////////////////////// + +template <typename SpacePoint> +inline InternalSeed<SpacePoint>::~InternalSeed() {} + +///////////////////////////////////////////////////////////////////////////////// +// Set +///////////////////////////////////////////////////////////////////////////////// + +template <typename SpacePoint> +inline void InternalSeed<SpacePoint>::set(SPForSeed<SpacePoint>*& s0, + SPForSeed<SpacePoint>*& s1, + SPForSeed<SpacePoint>*& s2, float z) { + m_z = z; + m_s0 = s0; + m_s1 = s1; + m_s2 = s2; +} + +///////////////////////////////////////////////////////////////////////////////// +// Set three space points seed +///////////////////////////////////////////////////////////////////////////////// + +template <typename SpacePoint> +inline bool InternalSeed<SpacePoint>::set3(Acts::Legacy::Seed<SpacePoint>& s) { + bool pixb = !m_s0->spacepoint->clusterList().second; + bool pixt = !m_s2->spacepoint->clusterList().second; + + if (pixb != pixt) { + if (m_q > m_s0->quality() && m_q > m_s1->quality() && + m_q > m_s2->quality()) { + return false; } - return (*this); } - template <typename SpacePoint> - inline InternalSeed<SpacePoint>::InternalSeed(SPForSeed<SpacePoint>*& s0, - SPForSeed<SpacePoint>*& s1, - SPForSeed<SpacePoint>*& s2, - float z) - { - set(s0, s1, s2, z); - m_q = 0.; - } - - ///////////////////////////////////////////////////////////////////////////////// - // Copy constructor - ///////////////////////////////////////////////////////////////////////////////// - - template <typename SpacePoint> - inline InternalSeed<SpacePoint>::InternalSeed(const InternalSeed& sp) - : m_s0(sp.m_s0), m_s1(sp.m_s1), m_s2(sp.m_s2) - { - *this = sp; - } - - ///////////////////////////////////////////////////////////////////////////////// - // Destructor - ///////////////////////////////////////////////////////////////////////////////// - - template <typename SpacePoint> - inline InternalSeed<SpacePoint>::~InternalSeed() - { - } - - ///////////////////////////////////////////////////////////////////////////////// - // Set - ///////////////////////////////////////////////////////////////////////////////// - - template <typename SpacePoint> - inline void - InternalSeed<SpacePoint>::set(SPForSeed<SpacePoint>*& s0, - SPForSeed<SpacePoint>*& s1, - SPForSeed<SpacePoint>*& s2, - float z) - { - m_z = z; - m_s0 = s0; - m_s1 = s1; - m_s2 = s2; - } - - ///////////////////////////////////////////////////////////////////////////////// - // Set three space points seed - ///////////////////////////////////////////////////////////////////////////////// - - template <typename SpacePoint> - inline bool - InternalSeed<SpacePoint>::set3(Acts::Legacy::Seed<SpacePoint>& s) - { - - bool pixb = !m_s0->spacepoint->clusterList().second; - bool pixt = !m_s2->spacepoint->clusterList().second; - - if (pixb != pixt) { - if (m_q > m_s0->quality() && m_q > m_s1->quality() - && m_q > m_s2->quality()) { - return false; - } - } - - m_s0->setQuality(m_q); - m_s1->setQuality(m_q); - m_s2->setQuality(m_q); - - s.erase(); - s.add(m_s0->spacepoint); - s.add(m_s1->spacepoint); - s.add(m_s2->spacepoint); - s.setZVertex(double(m_z)); + m_s0->setQuality(m_q); + m_s1->setQuality(m_q); + m_s2->setQuality(m_q); + + s.erase(); + s.add(m_s0->spacepoint); + s.add(m_s1->spacepoint); + s.add(m_s2->spacepoint); + s.setZVertex(double(m_z)); + return true; +} + +///////////////////////////////////////////////////////////////////////////////// +// Set quality in pro seed +///////////////////////////////////////////////////////////////////////////////// + +template <typename SpacePoint> +inline bool InternalSeed<SpacePoint>::setQuality(float q) { + m_q = q; + bool pixb = !m_s0->spacepoint->clusterList().second; + bool pixt = !m_s2->spacepoint->clusterList().second; + if (pixb == pixt) { + m_s0->setQuality(q); + m_s1->setQuality(q); + m_s2->setQuality(q); return true; } - - ///////////////////////////////////////////////////////////////////////////////// - // Set quality in pro seed - ///////////////////////////////////////////////////////////////////////////////// - - template <typename SpacePoint> - inline bool - InternalSeed<SpacePoint>::setQuality(float q) - { - m_q = q; - bool pixb = !m_s0->spacepoint->clusterList().second; - bool pixt = !m_s2->spacepoint->clusterList().second; - if (pixb == pixt) { - m_s0->setQuality(q); - m_s1->setQuality(q); - m_s2->setQuality(q); - return true; - } - if (q < m_s0->quality() || q < m_s1->quality() || q < m_s2->quality()) { - return true; - } - return false; + if (q < m_s0->quality() || q < m_s1->quality() || q < m_s2->quality()) { + return true; } + return false; +} -} // end of Legacy namespace -} // end of Acts namespace +} // namespace Legacy +} // namespace Acts diff --git a/Legacy/include/Acts/Seeding/LegacySeed.hpp b/Legacy/include/Acts/Seeding/LegacySeed.hpp index 7c1cb0e5ccd19e0b73b1640600fc93c346c25906..98f0396f17a34143919b47f60fc671f8afa68cd4 100644 --- a/Legacy/include/Acts/Seeding/LegacySeed.hpp +++ b/Legacy/include/Acts/Seeding/LegacySeed.hpp @@ -16,120 +16,93 @@ namespace Acts { namespace Legacy { - template <typename SpacePoint> - class Seed - { - - ///////////////////////////////////////////////////////////////////////////////// - // Public methods: - ///////////////////////////////////////////////////////////////////////////////// - - public: - Seed(); - Seed(const SpacePoint*, const SpacePoint*, const SpacePoint*, const double); - Seed(const Seed&); - Seed& - operator=(const Seed&); - virtual ~Seed(); - void - erase(); - void - add(const SpacePoint*&); - void - setZVertex(const double&); - const std::list<const SpacePoint*>& - spacePoints() const; - const double& - zVertex() const; - - ///////////////////////////////////////////////////////////////////////////////// - // Protected data members - ///////////////////////////////////////////////////////////////////////////////// - - protected: - std::list<const SpacePoint*> m_spacepoints; - double m_zvertex; - }; +template <typename SpacePoint> +class Seed { + ///////////////////////////////////////////////////////////////////////////////// + // Public methods: + ///////////////////////////////////////////////////////////////////////////////// + + public: + Seed(); + Seed(const SpacePoint*, const SpacePoint*, const SpacePoint*, const double); + Seed(const Seed&); + Seed& operator=(const Seed&); + virtual ~Seed(); + void erase(); + void add(const SpacePoint*&); + void setZVertex(const double&); + const std::list<const SpacePoint*>& spacePoints() const; + const double& zVertex() const; ///////////////////////////////////////////////////////////////////////////////// - // Inline methods + // Protected data members ///////////////////////////////////////////////////////////////////////////////// - template <typename SpacePoint> - inline const std::list<const SpacePoint*>& - Seed<SpacePoint>::spacePoints() const - { - return this->m_spacepoints; - } - - template <typename SpacePoint> - inline void - Seed<SpacePoint>::erase() - { - m_spacepoints.erase(m_spacepoints.begin(), m_spacepoints.end()); - } - - template <typename SpacePoint> - inline void - Seed<SpacePoint>::add(const SpacePoint*& p) - { - m_spacepoints.push_back(p); - } - - template <typename SpacePoint> - inline void - Seed<SpacePoint>::setZVertex(const double& z) - { - m_zvertex = z; - } - - template <typename SpacePoint> - inline const double& - Seed<SpacePoint>::zVertex() const - { - return m_zvertex; - } - - /////////////////////////////////////////////////////////////////////////////// - // Constructors - /////////////////////////////////////////////////////////////////////////////// - - template <typename SpacePoint> - Seed<SpacePoint>::Seed(const Seed<SpacePoint>& s) - { - m_spacepoints = s.spacePoints(); - m_zvertex = s.zVertex(); - } - - template <typename SpacePoint> - Seed<SpacePoint>& - Seed<SpacePoint>::operator=(const Seed<SpacePoint>& s) - { - m_spacepoints = s.spacePoints(); - m_zvertex = s.zVertex(); - return *this; - } - - template <typename SpacePoint> - Seed<SpacePoint>::Seed() - { - } - - template <typename SpacePoint> - Seed<SpacePoint>::Seed(const SpacePoint* b, - const SpacePoint* m, - const SpacePoint* u, - const double vertex) - { - m_zvertex = vertex; - m_spacepoints.push_back(b); - m_spacepoints.push_back(m); - m_spacepoints.push_back(u); - } - - template <typename SpacePoint> - Seed<SpacePoint>::~Seed() - { - } -} // end of Legacy namespace -} // end of Acts namespace + protected: + std::list<const SpacePoint*> m_spacepoints; + double m_zvertex; +}; + +///////////////////////////////////////////////////////////////////////////////// +// Inline methods +///////////////////////////////////////////////////////////////////////////////// + +template <typename SpacePoint> +inline const std::list<const SpacePoint*>& Seed<SpacePoint>::spacePoints() + const { + return this->m_spacepoints; +} + +template <typename SpacePoint> +inline void Seed<SpacePoint>::erase() { + m_spacepoints.erase(m_spacepoints.begin(), m_spacepoints.end()); +} + +template <typename SpacePoint> +inline void Seed<SpacePoint>::add(const SpacePoint*& p) { + m_spacepoints.push_back(p); +} + +template <typename SpacePoint> +inline void Seed<SpacePoint>::setZVertex(const double& z) { + m_zvertex = z; +} + +template <typename SpacePoint> +inline const double& Seed<SpacePoint>::zVertex() const { + return m_zvertex; +} + +/////////////////////////////////////////////////////////////////////////////// +// Constructors +/////////////////////////////////////////////////////////////////////////////// + +template <typename SpacePoint> +Seed<SpacePoint>::Seed(const Seed<SpacePoint>& s) { + m_spacepoints = s.spacePoints(); + m_zvertex = s.zVertex(); +} + +template <typename SpacePoint> +Seed<SpacePoint>& Seed<SpacePoint>::operator=(const Seed<SpacePoint>& s) { + m_spacepoints = s.spacePoints(); + m_zvertex = s.zVertex(); + return *this; +} + +template <typename SpacePoint> +Seed<SpacePoint>::Seed() {} + +template <typename SpacePoint> +Seed<SpacePoint>::Seed(const SpacePoint* b, const SpacePoint* m, + const SpacePoint* u, const double vertex) { + m_zvertex = vertex; + m_spacepoints.push_back(b); + m_spacepoints.push_back(m); + m_spacepoints.push_back(u); +} + +template <typename SpacePoint> +Seed<SpacePoint>::~Seed() {} +} // namespace Legacy +} // namespace Acts diff --git a/Legacy/include/Acts/Seeding/SPForSeed.hpp b/Legacy/include/Acts/Seeding/SPForSeed.hpp index b7a82d3f3135edce40702861e9ab6938c4f3bd08..e2a9f00e878924118e5a84128335d9b20eb83171 100644 --- a/Legacy/include/Acts/Seeding/SPForSeed.hpp +++ b/Legacy/include/Acts/Seeding/SPForSeed.hpp @@ -31,285 +31,221 @@ namespace Acts { namespace Legacy { - template <typename SpacePoint> - class SPForSeed - { - - ///////////////////////////////////////////////////////////////////////////////// - // Public methods: - ///////////////////////////////////////////////////////////////////////////////// - - public: - SPForSeed(); - SPForSeed(SpacePoint* const&, const float*); - SPForSeed(SpacePoint* const&, const float*, const float*); - SPForSeed(const SPForSeed&); - virtual ~SPForSeed(); - SPForSeed& - operator=(const SPForSeed&); - - void - set(SpacePoint* const&, const float*); - void - set(SpacePoint* const&, const float*, const float*); - void - setQuality(float); - void - setParam(const float&); +template <typename SpacePoint> +class SPForSeed { + ///////////////////////////////////////////////////////////////////////////////// + // Public methods: + ///////////////////////////////////////////////////////////////////////////////// - const SpacePoint* spacepoint; - const float& - x() const - { - return m_x; - } - const float& - y() const - { - return m_y; - } - const float& - z() const - { - return m_z; - } - const float& - radius() const - { - return m_r; - } - float - phi() const - { - return atan2(m_y, m_x); + public: + SPForSeed(); + SPForSeed(SpacePoint* const&, const float*); + SPForSeed(SpacePoint* const&, const float*, const float*); + SPForSeed(const SPForSeed&); + virtual ~SPForSeed(); + SPForSeed& operator=(const SPForSeed&); + + void set(SpacePoint* const&, const float*); + void set(SpacePoint* const&, const float*, const float*); + void setQuality(float); + void setParam(const float&); + + const SpacePoint* spacepoint; + const float& x() const { return m_x; } + const float& y() const { return m_y; } + const float& z() const { return m_z; } + const float& radius() const { return m_r; } + float phi() const { return atan2(m_y, m_x); } + const float& covr() const { return m_covr; } + const float& covz() const { return m_covz; } + const float& param() const { return m_param; } + const float& quality() const { return m_q; } + + const int& surface() const { return m_surface; } + + protected: + float m_x; // x-coordinate in beam system coordinates + float m_y; // y-coordinate in beam system coordinates + float m_z; // z-coordinate in beam system coordinetes + float m_r; // radius in beam system coordinates + float m_covr; // + float m_covz; // + float m_param; + float m_q; + + int m_surface; // surface identifier +}; + +///////////////////////////////////////////////////////////////////////////////// +// Inline methods +///////////////////////////////////////////////////////////////////////////////// + +template <typename SpacePoint> +inline SPForSeed<SpacePoint>::SPForSeed() { + spacepoint = 0; + m_x = 0.; + m_y = 0.; + m_z = 0.; + m_r = 0.; + m_covr = 0.; + m_covz = 0.; + m_param = 0.; + m_q = 0.; +} + +template <typename SpacePoint> +inline SPForSeed<SpacePoint>& SPForSeed<SpacePoint>::operator=( + const SPForSeed<SpacePoint>& sp) { + if (&sp != this) { + spacepoint = sp.spacepoint; + m_x = sp.m_x; + m_y = sp.m_y; + m_z = sp.m_z; + m_r = sp.m_r; + m_covr = sp.m_covr; + m_covz = sp.m_covz; + m_q = sp.m_q; + } + return (*this); +} + +template <typename SpacePoint> +inline SPForSeed<SpacePoint>::SPForSeed(SpacePoint* const& sp, const float* r) { + set(sp, r); + m_param = 0.; +} + +template <typename SpacePoint> +inline SPForSeed<SpacePoint>::SPForSeed(SpacePoint* const& sp, const float* r, + const float* sc) { + set(sp, r, sc); + m_param = 0.; +} + +///////////////////////////////////////////////////////////////////////////////// +// Copy constructor +///////////////////////////////////////////////////////////////////////////////// + +template <typename SpacePoint> +inline SPForSeed<SpacePoint>::SPForSeed(const SPForSeed& sp) { + *this = sp; +} + +///////////////////////////////////////////////////////////////////////////////// +// Destructor +///////////////////////////////////////////////////////////////////////////////// + +template <typename SpacePoint> +inline SPForSeed<SpacePoint>::~SPForSeed() {} + +///////////////////////////////////////////////////////////////////////////////// +// Set +///////////////////////////////////////////////////////////////////////////////// + +template <typename SpacePoint> +inline void SPForSeed<SpacePoint>::set(SpacePoint* const& sp, const float* r) { + spacepoint = sp; + m_x = r[0]; + m_y = r[1]; + m_z = r[2]; + m_r = sqrt(m_x * m_x + m_y * m_y); + m_surface = sp->surface; + m_q = 100000.; + + if (!sp->clusterList().second) { + m_covr = sp->covr * 9.; + m_covz = sp->covz * 9.; + if (m_covr < 0.06) { + m_covr = 0.06; } - const float& - covr() const - { - return m_covr; + if (m_covz < 0.06) { + m_covz = 0.06; } - const float& - covz() const - { - return m_covz; + } else { + m_covr = sp->covr * 8.; + m_covz = sp->covz * 8.; + if (m_covr < 0.1) { + m_covr = 0.1; } - const float& - param() const - { - return m_param; + if (m_covz < 0.1) { + m_covz = 0.1; } - const float& - quality() const - { - return m_q; + } +} + +///////////////////////////////////////////////////////////////////////////////// +// Set with error correction +// sc[0] - barrel pixels error correction +// sc[1] - endcap pixels +// sc[2] - barrel sct +// sc[3] - endcap sct +///////////////////////////////////////////////////////////////////////////////// + +template <typename SpacePoint> +inline void SPForSeed<SpacePoint>::set(SpacePoint* const& sp, const float* r, + const float* sc) { + spacepoint = sp; + m_x = r[0]; + m_y = r[1]; + m_z = r[2]; + m_r = sqrt(m_x * m_x + m_y * m_y); + m_q = 100000.; + if (!sp->clusterList().second) { + m_covr = sp->covr * 9. * sc[0]; + m_covz = sp->covz * 9. * sc[1]; + if (m_covr < 0.06) { + m_covr = 0.06; } - - const int& - surface() const - { - return m_surface; + if (m_covz < 0.06) { + m_covz = 0.06; } - - protected: - float m_x; // x-coordinate in beam system coordinates - float m_y; // y-coordinate in beam system coordinates - float m_z; // z-coordinate in beam system coordinetes - float m_r; // radius in beam system coordinates - float m_covr; // - float m_covz; // - float m_param; - float m_q; - - int m_surface; // surface identifier - }; - - ///////////////////////////////////////////////////////////////////////////////// - // Inline methods - ///////////////////////////////////////////////////////////////////////////////// - - template <typename SpacePoint> - inline SPForSeed<SpacePoint>::SPForSeed() - { - spacepoint = 0; - m_x = 0.; - m_y = 0.; - m_z = 0.; - m_r = 0.; - m_covr = 0.; - m_covz = 0.; - m_param = 0.; - m_q = 0.; - } - - template <typename SpacePoint> - inline SPForSeed<SpacePoint>& - SPForSeed<SpacePoint>::operator=(const SPForSeed<SpacePoint>& sp) - { - if (&sp != this) { - spacepoint = sp.spacepoint; - m_x = sp.m_x; - m_y = sp.m_y; - m_z = sp.m_z; - m_r = sp.m_r; - m_covr = sp.m_covr; - m_covz = sp.m_covz; - m_q = sp.m_q; + } else { + m_covr = sp->covr * 8. * sc[2]; + m_covz = sp->covz * 8. * sc[3]; + if (m_covr < 0.1) { + m_covr = 0.1; } - return (*this); - } - - template <typename SpacePoint> - inline SPForSeed<SpacePoint>::SPForSeed(SpacePoint* const& sp, const float* r) - { - set(sp, r); - m_param = 0.; - } - - template <typename SpacePoint> - inline SPForSeed<SpacePoint>::SPForSeed(SpacePoint* const& sp, - const float* r, - const float* sc) - { - set(sp, r, sc); - m_param = 0.; - } - - ///////////////////////////////////////////////////////////////////////////////// - // Copy constructor - ///////////////////////////////////////////////////////////////////////////////// - - template <typename SpacePoint> - inline SPForSeed<SpacePoint>::SPForSeed(const SPForSeed& sp) - { - *this = sp; - } - - ///////////////////////////////////////////////////////////////////////////////// - // Destructor - ///////////////////////////////////////////////////////////////////////////////// - - template <typename SpacePoint> - inline SPForSeed<SpacePoint>::~SPForSeed() - { - } - - ///////////////////////////////////////////////////////////////////////////////// - // Set - ///////////////////////////////////////////////////////////////////////////////// - - template <typename SpacePoint> - inline void - SPForSeed<SpacePoint>::set(SpacePoint* const& sp, const float* r) - { - spacepoint = sp; - m_x = r[0]; - m_y = r[1]; - m_z = r[2]; - m_r = sqrt(m_x * m_x + m_y * m_y); - m_surface = sp->surface; - m_q = 100000.; - - if (!sp->clusterList().second) { - m_covr = sp->covr * 9.; - m_covz = sp->covz * 9.; - if (m_covr < 0.06) { - m_covr = 0.06; - } - if (m_covz < 0.06) { - m_covz = 0.06; - } - } else { - m_covr = sp->covr * 8.; - m_covz = sp->covz * 8.; - if (m_covr < 0.1) { - m_covr = 0.1; - } - if (m_covz < 0.1) { - m_covz = 0.1; - } + if (m_covz < 0.1) { + m_covz = 0.1; } } - ///////////////////////////////////////////////////////////////////////////////// - // Set with error correction - // sc[0] - barrel pixels error correction - // sc[1] - endcap pixels - // sc[2] - barrel sct - // sc[3] - endcap sct - ///////////////////////////////////////////////////////////////////////////////// - - template <typename SpacePoint> - inline void - SPForSeed<SpacePoint>::set(SpacePoint* const& sp, - const float* r, - const float* sc) - { - spacepoint = sp; - m_x = r[0]; - m_y = r[1]; - m_z = r[2]; - m_r = sqrt(m_x * m_x + m_y * m_y); - m_q = 100000.; - if (!sp->clusterList().second) { - m_covr = sp->covr * 9. * sc[0]; - m_covz = sp->covz * 9. * sc[1]; - if (m_covr < 0.06) { - m_covr = 0.06; - } - if (m_covz < 0.06) { - m_covz = 0.06; - } - } else { - m_covr = sp->covr * 8. * sc[2]; - m_covz = sp->covz * 8. * sc[3]; - if (m_covr < 0.1) { - m_covr = 0.1; - } - if (m_covz < 0.1) { - m_covz = 0.1; - } - } - - // old code: - // const InDet::SiCluster* c = static_cast<const - // InDet::SiCluster*>(sp->clusterList().first); - // if( de->isPixel() ) { - // - // const Amg::MatrixX& v = sp->localCovariance(); - // //ATTENTION: v(1,1) contains error for z in barrel, error for r in - // endcaps - // float f22 = float(v(1,1)); - // //ATTENTION: Variable Z contains width of R in the endcaps. - // float wid = float(c->width().z()); - // float cov = wid*wid*.08333; if(cov < f22) cov = f22; - // // Set error of low uncertainty dimension (i.e. r for barrel, z for - // EC) - // to "small" - // if(sp->isBarrel()) {m_covz = 9.*cov*sc[0]; m_covr = .06;} - // else {m_covr = 9.*cov*sc[1]; m_covz = .06;} - // } - // else { - // - // const Amg::MatrixX& v = sp->localCovariance(); - // float f22 = float(v(1,1)); - // if(sp->isBarrel()) {m_covz = 8.*f22*sc[2]; m_covr = .1;} - // else {m_covr = 8.*f22*sc[3]; m_covz = .1;} - // } - } - template <typename SpacePoint> - inline void - SPForSeed<SpacePoint>::setParam(const float& p) - { - m_param = p; - } - template <typename SpacePoint> - inline void - SPForSeed<SpacePoint>::setQuality(float q) - { - if (q <= m_q) { - m_q = q; - } + // old code: + // const InDet::SiCluster* c = static_cast<const + // InDet::SiCluster*>(sp->clusterList().first); + // if( de->isPixel() ) { + // + // const Amg::MatrixX& v = sp->localCovariance(); + // //ATTENTION: v(1,1) contains error for z in barrel, error for r in + // endcaps + // float f22 = float(v(1,1)); + // //ATTENTION: Variable Z contains width of R in the endcaps. + // float wid = float(c->width().z()); + // float cov = wid*wid*.08333; if(cov < f22) cov = f22; + // // Set error of low uncertainty dimension (i.e. r for barrel, z for + // EC) + // to "small" + // if(sp->isBarrel()) {m_covz = 9.*cov*sc[0]; m_covr = .06;} + // else {m_covr = 9.*cov*sc[1]; m_covz = .06;} + // } + // else { + // + // const Amg::MatrixX& v = sp->localCovariance(); + // float f22 = float(v(1,1)); + // if(sp->isBarrel()) {m_covz = 8.*f22*sc[2]; m_covr = .1;} + // else {m_covr = 8.*f22*sc[3]; m_covz = .1;} + // } +} +template <typename SpacePoint> +inline void SPForSeed<SpacePoint>::setParam(const float& p) { + m_param = p; +} +template <typename SpacePoint> +inline void SPForSeed<SpacePoint>::setQuality(float q) { + if (q <= m_q) { + m_q = q; } +} -} // end of Legacy namespace -} // end of Acts namespace +} // namespace Legacy +} // namespace Acts diff --git a/Plugins/DD4hep/include/Acts/Plugins/DD4hep/ActsExtension.hpp b/Plugins/DD4hep/include/Acts/Plugins/DD4hep/ActsExtension.hpp index 163e9ca1116a5f753ba7fe0c860611c3b709247a..e8cedff6131bda3ddbdc62688b2ddc57832a49e9 100644 --- a/Plugins/DD4hep/include/Acts/Plugins/DD4hep/ActsExtension.hpp +++ b/Plugins/DD4hep/include/Acts/Plugins/DD4hep/ActsExtension.hpp @@ -83,12 +83,10 @@ class DigitizationModule; /// the envelope of the layer around the surfaces. /// -class ActsExtension : public IActsExtension -{ -public: +class ActsExtension : public IActsExtension { + public: /// The configuration object of an ActsExtension - struct Config - { + struct Config { /// Indicating that the DD4hep::DetElement is the beampipe bool isBeampipe{false}; /// Indicating that the DD4hep::DetElement is a barrel @@ -182,49 +180,35 @@ public: ~ActsExtension() override = default; /// Set configuration method /// @param config is the new configuration struct - void - setConfiguration(const Config& config); + void setConfiguration(const Config& config); /// @copydoc IActsExtension::isBeampipe() - bool - isBeampipe() const final; + bool isBeampipe() const final; /// @copydoc IActsExtension::isBarrel() - bool - isBarrel() const final; + bool isBarrel() const final; /// @copydoc IActsExtension::isEndcap() - bool - isEndcap() const final; + bool isEndcap() const final; /// @copydoc IActsExtension::isLayer() - bool - isLayer() const final; + bool isLayer() const final; /// @copydoc IActsExtension::hasSupportMaterial() - bool - hasSupportMaterial() const final; + bool hasSupportMaterial() const final; /// @copydoc IActsExtension::materialBins() - std::pair<size_t, size_t> - materialBins() const final; + std::pair<size_t, size_t> materialBins() const final; /// @copydoc IActsExtension::layerMaterialPosition() - Acts::LayerMaterialPos - layerMaterialPosition() const final; + Acts::LayerMaterialPos layerMaterialPosition() const final; /// @copydoc IActsExtension::axes() - const std::string - axes() const final; + const std::string axes() const final; /// @copydoc IActsExtension::buildEnvelope() - bool - buildEnvelope() const final; + bool buildEnvelope() const final; /// @copydoc IActsExtension::envelopeZ() - double - envelopeR() const final; + double envelopeR() const final; /// @copydoc IActsExtension::envelopeZ() - double - envelopeZ() const final; + double envelopeZ() const final; /// @copydoc IActsExtension::material() - std::shared_ptr<const Acts::ISurfaceMaterial> - material() const final; + std::shared_ptr<const Acts::ISurfaceMaterial> material() const final; /// @copydoc IActsExtension::digitizationModule - std::shared_ptr<const DigitizationModule> - digitizationModule() const final; + std::shared_ptr<const DigitizationModule> digitizationModule() const final; -private: + private: /// The configuration object Config m_cfg; // The Acts SurfaceMaterial @@ -238,86 +222,62 @@ private: std::shared_ptr<const DigitizationModule> m_digitizationModule{nullptr}; }; -inline bool -ActsExtension::isBeampipe() const -{ +inline bool ActsExtension::isBeampipe() const { return m_cfg.isBeampipe; } -inline bool -ActsExtension::isBarrel() const -{ +inline bool ActsExtension::isBarrel() const { return m_cfg.isBarrel; } -inline bool -ActsExtension::isEndcap() const -{ +inline bool ActsExtension::isEndcap() const { return m_cfg.isEndcap; } -inline bool -ActsExtension::isLayer() const -{ +inline bool ActsExtension::isLayer() const { return m_cfg.isLayer; } -inline bool -ActsExtension::hasSupportMaterial() const -{ +inline bool ActsExtension::hasSupportMaterial() const { if ((m_cfg.materialBins1 > 0) || (m_cfg.materialBins2 > 0)) { return true; } return false; } -inline std::pair<size_t, size_t> -ActsExtension::materialBins() const -{ +inline std::pair<size_t, size_t> ActsExtension::materialBins() const { std::pair<size_t, size_t> materialBins(m_cfg.materialBins1, m_cfg.materialBins2); return (materialBins); } -inline Acts::LayerMaterialPos -ActsExtension::layerMaterialPosition() const -{ +inline Acts::LayerMaterialPos ActsExtension::layerMaterialPosition() const { return m_cfg.layerMaterialPosition; } -inline const std::string -ActsExtension::axes() const -{ +inline const std::string ActsExtension::axes() const { return m_cfg.axes; } -inline bool -ActsExtension::buildEnvelope() const -{ +inline bool ActsExtension::buildEnvelope() const { return ((m_cfg.envelopeR > 0.) && (m_cfg.envelopeZ > 0.)); } -inline double -ActsExtension::envelopeR() const -{ +inline double ActsExtension::envelopeR() const { return (m_cfg.envelopeR); } -inline double -ActsExtension::envelopeZ() const -{ +inline double ActsExtension::envelopeZ() const { return (m_cfg.envelopeR); } inline std::shared_ptr<const Acts::ISurfaceMaterial> -Acts::ActsExtension::material() const -{ +Acts::ActsExtension::material() const { return m_material; } inline std::shared_ptr<const DigitizationModule> -Acts::ActsExtension::digitizationModule() const -{ +Acts::ActsExtension::digitizationModule() const { return m_digitizationModule; } -} +} // namespace Acts diff --git a/Plugins/DD4hep/include/Acts/Plugins/DD4hep/ConvertDD4hepDetector.hpp b/Plugins/DD4hep/include/Acts/Plugins/DD4hep/ConvertDD4hepDetector.hpp index 68f16ef4a140fcff698f7a509c41526bb6ae42d9..7c53a6e1eed1bdf67ec00610f9e10fdca9e36a76 100644 --- a/Plugins/DD4hep/include/Acts/Plugins/DD4hep/ConvertDD4hepDetector.hpp +++ b/Plugins/DD4hep/include/Acts/Plugins/DD4hep/ConvertDD4hepDetector.hpp @@ -19,11 +19,8 @@ namespace Acts { /// Sort function which sorts dd4hep::DetElement by their ID /// @param[in][out] det the dd4hep::DetElements to be sorted -void -sortDetElementsByID(std::vector<dd4hep::DetElement>& det) -{ - sort(det.begin(), - det.end(), +void sortDetElementsByID(std::vector<dd4hep::DetElement>& det) { + sort(det.begin(), det.end(), [](const dd4hep::DetElement& a, const dd4hep::DetElement& b) { return (a.id() < b.id()); }); @@ -44,8 +41,8 @@ sortDetElementsByID(std::vector<dd4hep::DetElement>& det) /// binned in a layer in phi direction. /// @note Possible binningtypes: /// - arbitrary - of the sizes if the surfaces and the distance inbetween -/// vary. This mode finds out the bin boundaries by scanning through the -/// surfaces. +/// vary. This mode finds out the bin boundaries by scanning through +/// the surfaces. /// - equidistant - if the sensitive surfaces are placed equidistantly /// @note equidistant binningtype is recommended because it is faster not only /// while building the geometry but also for look up during the extrapolation @@ -81,19 +78,15 @@ sortDetElementsByID(std::vector<dd4hep::DetElement>& det) /// dd4hep::DetElement. In case another sorting needs to be applied, the users /// can provide their own function -std::unique_ptr<const TrackingGeometry> -convertDD4hepDetector( +std::unique_ptr<const TrackingGeometry> convertDD4hepDetector( dd4hep::DetElement worldDetElement, - Logging::Level loggingLevel = Logging::Level::INFO, - BinningType bTypePhi = equidistant, - BinningType bTypeR = equidistant, - BinningType bTypeZ = equidistant, - double layerEnvelopeR = 1. * units::_mm, - double layerEnvelopeZ = 1. * units::_mm, - double defaultLayerThickness = 10e-10 * units::_mm, + Logging::Level loggingLevel = Logging::Level::INFO, + BinningType bTypePhi = equidistant, BinningType bTypeR = equidistant, + BinningType bTypeZ = equidistant, double layerEnvelopeR = 1. * units::_mm, + double layerEnvelopeZ = 1. * units::_mm, + double defaultLayerThickness = 10e-10 * units::_mm, const std::function<void(std::vector<dd4hep::DetElement>& detectors)>& - sortSubDetectors - = sortDetElementsByID, + sortSubDetectors = sortDetElementsByID, const GeometryContext& gctx = GeometryContext()); /// @brief Method internally used to create an Acts::CylinderVolumeBuilder @@ -110,8 +103,8 @@ convertDD4hepDetector( /// binned in a layer in phi direction. /// @note Possible binningtypes: /// - arbitrary - of the sizes if the surfaces and the distance inbetween -/// vary. This mode finds out the bin boundaries by scanning through the -/// surfaces. +/// vary. This mode finds out the bin boundaries by scanning through +/// the surfaces. /// - equidistant - if the sensitive surfaces are placed equidistantly /// @note equidistant binningtype is recommended because it is faster not only /// while building the geometry but also for look up during the extrapolation @@ -135,20 +128,18 @@ convertDD4hepDetector( /// touching or overlapping with the next layer can happen. /// @return std::shared_ptr the Acts::CylinderVolumeBuilder which can be used to /// build the full tracking geometry -std::shared_ptr<const CylinderVolumeBuilder> -volumeBuilder_dd4hep(dd4hep::DetElement subDetector, - Logging::Level loggingLevel = Logging::Level::INFO, - BinningType bTypePhi = equidistant, - BinningType bTypeR = equidistant, - BinningType bTypeZ = equidistant, - double layerEnvelopeR = 1. * units::_mm, - double layerEnvelopeZ = 1. * units::_mm, - double defaultLayerThickness = 10e-10 * units::_mm); +std::shared_ptr<const CylinderVolumeBuilder> volumeBuilder_dd4hep( + dd4hep::DetElement subDetector, + Logging::Level loggingLevel = Logging::Level::INFO, + BinningType bTypePhi = equidistant, BinningType bTypeR = equidistant, + BinningType bTypeZ = equidistant, double layerEnvelopeR = 1. * units::_mm, + double layerEnvelopeZ = 1. * units::_mm, + double defaultLayerThickness = 10e-10 * units::_mm); /// Helper method internally used to create a default /// Acts::CylinderVolumeBuilder -std::shared_ptr<const CylinderVolumeHelper> -cylinderVolumeHelper_dd4hep(Logging::Level loggingLevel = Logging::Level::INFO); +std::shared_ptr<const CylinderVolumeHelper> cylinderVolumeHelper_dd4hep( + Logging::Level loggingLevel = Logging::Level::INFO); /// Method internally used by convertDD4hepDetector to collect all sub detectors /// Sub detector means each 'compound' DetElement or DetElements which are @@ -157,9 +148,8 @@ cylinderVolumeHelper_dd4hep(Logging::Level loggingLevel = Logging::Level::INFO); /// detectors should be collected /// @param [out] subdetectors the DD4hep::DetElements of the sub detectors /// contained by detElement -void -collectSubDetectors_dd4hep(dd4hep::DetElement& detElement, - std::vector<dd4hep::DetElement>& subdetectors); +void collectSubDetectors_dd4hep(dd4hep::DetElement& detElement, + std::vector<dd4hep::DetElement>& subdetectors); /// Method internally used by convertDD4hepDetector to collect all volumes of a /// compound detector @@ -167,16 +157,14 @@ collectSubDetectors_dd4hep(dd4hep::DetElement& detElement, /// compounds should be collected /// @param [out] compounds the DD4hep::DetElements of the compounds contained by /// detElement -void -collectCompounds_dd4hep(dd4hep::DetElement& detElement, - std::vector<dd4hep::DetElement>& compounds); +void collectCompounds_dd4hep(dd4hep::DetElement& detElement, + std::vector<dd4hep::DetElement>& compounds); /// Method internally used by convertDD4hepDetector /// @param [in] detElement the dd4hep::DetElement of the volume of which the /// layers should be collected /// @param [out] layers the DD4hep::DetElements of the layers contained by /// detElement -void -collectLayers_dd4hep(dd4hep::DetElement& detElement, - std::vector<dd4hep::DetElement>& layers); -} \ No newline at end of file +void collectLayers_dd4hep(dd4hep::DetElement& detElement, + std::vector<dd4hep::DetElement>& layers); +} // namespace Acts \ No newline at end of file diff --git a/Plugins/DD4hep/include/Acts/Plugins/DD4hep/DD4hepDetectorElement.hpp b/Plugins/DD4hep/include/Acts/Plugins/DD4hep/DD4hepDetectorElement.hpp index f75de5240cd13f754d3700eda289c6a19616aeaf..58b86df8417c5877ff774f6ed041fc61d3ba4336 100644 --- a/Plugins/DD4hep/include/Acts/Plugins/DD4hep/DD4hepDetectorElement.hpp +++ b/Plugins/DD4hep/include/Acts/Plugins/DD4hep/DD4hepDetectorElement.hpp @@ -38,9 +38,8 @@ class DigitizationModule; /// if not used with DD4hep? /// @todo segmentation -class DD4hepDetectorElement : public TGeoDetectorElement -{ -public: +class DD4hepDetectorElement : public TGeoDetectorElement { + public: /// Broadcast the context type using ContextType = GeometryContext; @@ -74,20 +73,18 @@ public: /// translated into a cylindrical surface. /// @param material Possible material of detector element DD4hepDetectorElement( - const dd4hep::DetElement detElement, - const std::string& axes = "XYZ", - double scalor = 1., - bool isDisc = false, - std::shared_ptr<const ISurfaceMaterial> material = nullptr, + const dd4hep::DetElement detElement, const std::string& axes = "XYZ", + double scalor = 1., bool isDisc = false, + std::shared_ptr<const ISurfaceMaterial> material = nullptr, std::shared_ptr<const DigitizationModule> digitizationModule = nullptr); /// Desctructor ~DD4hepDetectorElement() override = default; -private: + private: /// DD4hep detector element dd4hep::DetElement m_detElement; /// DD4hep segmentation dd4hep::Segmentation m_segmentation; }; -} +} // namespace Acts diff --git a/Plugins/DD4hep/include/Acts/Plugins/DD4hep/DD4hepLayerBuilder.hpp b/Plugins/DD4hep/include/Acts/Plugins/DD4hep/DD4hepLayerBuilder.hpp index f46dc8726bfd4d7bb431a1e1c4e316b6d9ae1c86..47da6681a2697b25ff8039fc0125f75b880c5309 100644 --- a/Plugins/DD4hep/include/Acts/Plugins/DD4hep/DD4hepLayerBuilder.hpp +++ b/Plugins/DD4hep/include/Acts/Plugins/DD4hep/DD4hepLayerBuilder.hpp @@ -29,13 +29,11 @@ namespace Acts { /// (layers of endcaps) of one hierarchy (e.g. PixelDetector, StripDetector,...) /// with input from DD4hep. -class DD4hepLayerBuilder : public ILayerBuilder -{ -public: +class DD4hepLayerBuilder : public ILayerBuilder { + public: /// @struct Config /// nested configuration struct for steering of the layer builder - struct Config - { + struct Config { /// string based identification std::string configurationName = "undefined"; /// layer creator which is internally used to build layers @@ -79,7 +77,7 @@ public: /// @param config is the configuration struct /// @param logger is the logging instance DD4hepLayerBuilder(const Acts::DD4hepLayerBuilder::Config& config, - std::unique_ptr<const Logger> logger); + std::unique_ptr<const Logger> logger); /// Destructor ~DD4hepLayerBuilder() override; @@ -88,44 +86,37 @@ public: /// @param gctx the geometry context for this build call /// /// @return the layers at negative side - const LayerVector - negativeLayers(const GeometryContext& gctx) const final; + const LayerVector negativeLayers(const GeometryContext& gctx) const final; /// LayerBuilder interface method /// /// @param gctx the geometry context for this build call /// /// @return the layers at the central sector - const LayerVector - centralLayers(const GeometryContext& gctx) const final; + const LayerVector centralLayers(const GeometryContext& gctx) const final; /// LayerBuilder interface method /// /// @param gctx the geometry context for this build call /// /// @return the layers at positive side - const LayerVector - positiveLayers(const GeometryContext& gctx) const final; + const LayerVector positiveLayers(const GeometryContext& gctx) const final; /// Name identification /// @return the string based identification of this configuration - const std::string& - identification() const final; + const std::string& identification() const final; /// set the configuration object /// @param config is the configuration struct - void - setConfiguration(const Config& config); + void setConfiguration(const Config& config); /// get the configuration object - Config - getConfiguration() const; + Config getConfiguration() const; /// set logging instance - void - setLogger(std::unique_ptr<const Logger> logger); + void setLogger(std::unique_ptr<const Logger> logger); -private: + private: /// configruation object Config m_cfg; @@ -133,11 +124,7 @@ private: std::unique_ptr<const Logger> m_logger; /// Private access to the logger - const Logger& - logger() const - { - return *m_logger; - } + const Logger& logger() const { return *m_logger; } /// Private helper function collecting all sensitive detector elements of a /// layer @@ -146,10 +133,10 @@ private: /// @param surfaces the vector of surfaces which should be filled with the /// sensitive detector elements /// @param axes the orientation of the modules to the Acts frame - void - resolveSensitive(const dd4hep::DetElement& detElement, - std::vector<std::shared_ptr<const Acts::Surface>>& surfaces, - const std::string& axes = "XYZ") const; + void resolveSensitive( + const dd4hep::DetElement& detElement, + std::vector<std::shared_ptr<const Acts::Surface>>& surfaces, + const std::string& axes = "XYZ") const; /// Private helper function to create a sensitive surface from a given /// detector element @@ -158,29 +145,24 @@ private: /// @param isDisc in case the sensitive detector module should be translated /// as disc (e.g. for endcaps) this flag should be set to true /// @param axes the orientation of the modules to the Acts frame - std::shared_ptr<const Acts::Surface> - createSensitiveSurface(const dd4hep::DetElement& detElement, - bool isDisc = false, - const std::string& axes = "XYZ") const; + std::shared_ptr<const Acts::Surface> createSensitiveSurface( + const dd4hep::DetElement& detElement, bool isDisc = false, + const std::string& axes = "XYZ") const; // Private helper function to convert the TGeo transformation matrix into // a // Acts transformation matrix /// @param tGeoTrans TGeo transformation matrix which should be converted - std::shared_ptr<const Acts::Transform3D> - convertTransform(const TGeoMatrix* tGeoTrans) const; + std::shared_ptr<const Acts::Transform3D> convertTransform( + const TGeoMatrix* tGeoTrans) const; }; -inline const std::string& -DD4hepLayerBuilder::identification() const -{ +inline const std::string& DD4hepLayerBuilder::identification() const { return m_cfg.configurationName; } -inline DD4hepLayerBuilder::Config -DD4hepLayerBuilder::getConfiguration() const -{ +inline DD4hepLayerBuilder::Config DD4hepLayerBuilder::getConfiguration() const { return m_cfg; } -} // namespace \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Plugins/DD4hep/include/Acts/Plugins/DD4hep/IActsExtension.hpp b/Plugins/DD4hep/include/Acts/Plugins/DD4hep/IActsExtension.hpp index c46be9f938ed6a4ea185b27b23f5e474302eb324..d47f07835dc9afb9b6a538e1177bebc55ca1ba50 100644 --- a/Plugins/DD4hep/include/Acts/Plugins/DD4hep/IActsExtension.hpp +++ b/Plugins/DD4hep/include/Acts/Plugins/DD4hep/IActsExtension.hpp @@ -21,7 +21,7 @@ class DetElement; class Segmentation; class Volume; class Material; -} +} // namespace dd4hep namespace Acts { @@ -79,71 +79,58 @@ class ISurfaceMaterial; /// the other boundary surface of the layer or at the representing (center) /// surface of the layer enum LayerMaterialPos { - inner = 0, + inner = 0, central = 1, - outer = 2, + outer = 2, }; -class IActsExtension -{ -public: +class IActsExtension { + public: /// Virtual destructor virtual ~IActsExtension() = default; /// Indicates if the DD4hep::DetElement is the beampipe - virtual bool - isBeampipe() const = 0; + virtual bool isBeampipe() const = 0; /// Indicates that the DD4hep::DetElement is a barrel - virtual bool - isBarrel() const = 0; + virtual bool isBarrel() const = 0; /// Indicates that the DD4hep::DetElement is an endcap - virtual bool - isEndcap() const = 0; + virtual bool isEndcap() const = 0; /// Indicates that the DD4hep::DetElement is a layer - virtual bool - isLayer() const = 0; + virtual bool isLayer() const = 0; /// Bool returning true if the layers should carry material using material /// mapping /// @note automatically set when the material bins are set - virtual bool - hasSupportMaterial() const = 0; + virtual bool hasSupportMaterial() const = 0; /// Access to the two bin numbers determining the granularity of the two /// dimensional grid on which the material of the layer should be mapped on /// @return std::pair with the number of bins in th first and the second /// direction - virtual std::pair<size_t, size_t> - materialBins() const = 0; + virtual std::pair<size_t, size_t> materialBins() const = 0; /// @return states if the material should be mapped on the inner, /// the center or the outer surface of the layer - virtual Acts::LayerMaterialPos - layerMaterialPosition() const = 0; + virtual Acts::LayerMaterialPos layerMaterialPosition() const = 0; /// Access the orientation of the module in respect to the tracking frame /// @return string describing the orientation of the axes - virtual const std::string - axes() const = 0; + virtual const std::string axes() const = 0; /// @return states if the geometrical boundaries of the current object should /// be built automatically by adding given tolerances to the expansion of the /// contained modules - virtual bool - buildEnvelope() const = 0; + virtual bool buildEnvelope() const = 0; /// @return the tolerance which should be added in r to the geometrical /// expansion of the contained surfaces (sensituive DetElements) of this /// DetElement to automatically create the layer envelope - virtual double - envelopeR() const = 0; + virtual double envelopeR() const = 0; /// @return the tolerance which should be added in z to the geometrical /// expansion of the contained surfaces (sensituive DetElements) of this /// DetElement to automatically create the layer envelope - virtual double - envelopeZ() const = 0; + virtual double envelopeZ() const = 0; /// @return The SurfaceMaterial - virtual std::shared_ptr<const Acts::ISurfaceMaterial> - material() const = 0; + virtual std::shared_ptr<const Acts::ISurfaceMaterial> material() const = 0; /// @return the shared pointer to the digitization module - virtual std::shared_ptr<const DigitizationModule> - digitizationModule() const = 0; + virtual std::shared_ptr<const DigitizationModule> digitizationModule() + const = 0; -protected: + protected: /// Protected constructor IActsExtension() = default; }; -} +} // namespace Acts diff --git a/Plugins/DD4hep/src/ActsExtension.cpp b/Plugins/DD4hep/src/ActsExtension.cpp index 41c33b4601ba585100cb653d36453686e27cd6bc..b44e3a9f4f43c313afe2d0a07069544a29e13f4c 100644 --- a/Plugins/DD4hep/src/ActsExtension.cpp +++ b/Plugins/DD4hep/src/ActsExtension.cpp @@ -16,39 +16,32 @@ #include "DD4hep/CartesianGridXY.h" Acts::ActsExtension::ActsExtension(const Config& cfg) - : Acts::IActsExtension(), m_material(nullptr) -{ + : Acts::IActsExtension(), m_material(nullptr) { setConfiguration(cfg); } Acts::ActsExtension::ActsExtension(const ActsExtension& det, const dd4hep::DetElement& /*elem*/) - : Acts::IActsExtension(), m_cfg(det.m_cfg), m_material(det.m_material) -{ -} + : Acts::IActsExtension(), m_cfg(det.m_cfg), m_material(det.m_material) {} Acts::ActsExtension::ActsExtension( std::shared_ptr<const DigitizationModule> digiModule) - : Acts::IActsExtension() - , m_material(nullptr) - , m_digitizationModule(std::move(digiModule)) -{ -} + : Acts::IActsExtension(), + m_material(nullptr), + m_digitizationModule(std::move(digiModule)) {} Acts::ActsExtension::ActsExtension( const std::vector<std::pair<dd4hep::Material, double>>& materials, std::shared_ptr<const DigitizationModule> digiModule) - : Acts::IActsExtension() - , m_material(nullptr) - , m_digitizationModule(std::move(digiModule)) -{ + : Acts::IActsExtension(), + m_material(nullptr), + m_digitizationModule(std::move(digiModule)) { std::vector<Acts::MaterialProperties> partialMaterial; partialMaterial.reserve(materials.size()); for (auto& mat : materials) { Acts::Material pm{float(mat.first.radLength() * units::_cm), float(mat.first.intLength() * units::_cm), - float(mat.first.A()), - float(mat.first.Z()), + float(mat.first.A()), float(mat.first.Z()), float(mat.first.density() / pow(Acts::units::_cm, 3))}; partialMaterial.push_back( Acts::MaterialProperties(pm, mat.second * units::_mm)); @@ -58,9 +51,8 @@ Acts::ActsExtension::ActsExtension( m_material = std::make_shared<Acts::HomogeneousSurfaceMaterial>(matprop); } -void -Acts::ActsExtension::setConfiguration(const Acts::ActsExtension::Config& config) -{ +void Acts::ActsExtension::setConfiguration( + const Acts::ActsExtension::Config& config) { // @todo check consistency // copy the configuration m_cfg = config; diff --git a/Plugins/DD4hep/src/ConvertDD4hepDetector.cpp b/Plugins/DD4hep/src/ConvertDD4hepDetector.cpp index ac260c511d03e41e8c85392f3335ae0486a78010..3013acd636778c17e590e3cb13947028b5fc1699 100644 --- a/Plugins/DD4hep/src/ConvertDD4hepDetector.cpp +++ b/Plugins/DD4hep/src/ConvertDD4hepDetector.cpp @@ -24,23 +24,16 @@ #include "TGeoManager.h" namespace Acts { -std::unique_ptr<const TrackingGeometry> -convertDD4hepDetector( - dd4hep::DetElement worldDetElement, - Logging::Level loggingLevel, - BinningType bTypePhi, - BinningType bTypeR, - BinningType bTypeZ, - double layerEnvelopeR, - double layerEnvelopeZ, - double defaultLayerThickness, +std::unique_ptr<const TrackingGeometry> convertDD4hepDetector( + dd4hep::DetElement worldDetElement, Logging::Level loggingLevel, + BinningType bTypePhi, BinningType bTypeR, BinningType bTypeZ, + double layerEnvelopeR, double layerEnvelopeZ, double defaultLayerThickness, const std::function<void(std::vector<dd4hep::DetElement>& detectors)>& - sortSubDetectors, - const Acts::GeometryContext& gctx) -{ + sortSubDetectors, + const Acts::GeometryContext& gctx) { // create local logger for conversion - auto DD4hepConverterlogger - = Acts::getDefaultLogger("DD4hepConversion", loggingLevel); + auto DD4hepConverterlogger = + Acts::getDefaultLogger("DD4hepConversion", loggingLevel); ACTS_LOCAL_LOGGER(DD4hepConverterlogger); ACTS_INFO("Translating DD4hep geometry into Acts geometry"); @@ -59,14 +52,9 @@ convertDD4hepDetector( // loop over the sub detectors for (auto& subDetector : subDetectors) { // create volume builder - auto volBuilder = volumeBuilder_dd4hep(subDetector, - loggingLevel, - bTypePhi, - bTypeR, - bTypeZ, - layerEnvelopeR, - layerEnvelopeZ, - defaultLayerThickness); + auto volBuilder = volumeBuilder_dd4hep( + subDetector, loggingLevel, bTypePhi, bTypeR, bTypeZ, layerEnvelopeR, + layerEnvelopeZ, defaultLayerThickness); if (volBuilder) { // distinguish beam pipe if (volBuilder->getConfiguration().buildToRadiusZero) { @@ -75,10 +63,10 @@ convertDD4hepDetector( throw std::logic_error( std::string("Beampipe has already been set! There can only " "exist one beam pipe. Please check your " - "detector construction. Current volume name: ") - + volBuilder->getConfiguration().volumeName - + std::string(", name of volume, already set as beam pipe: ") - + beamPipeVolumeBuilder->getConfiguration().volumeName); + "detector construction. Current volume name: ") + + volBuilder->getConfiguration().volumeName + + std::string(", name of volume, already set as beam pipe: ") + + beamPipeVolumeBuilder->getConfiguration().volumeName); } // set the beam pipe beamPipeVolumeBuilder = volBuilder; @@ -93,44 +81,40 @@ convertDD4hepDetector( } std::vector<std::function<std::shared_ptr<TrackingVolume>( - const GeometryContext&, - const TrackingVolumePtr&, + const GeometryContext&, const TrackingVolumePtr&, const VolumeBoundsPtr&)>> volumeFactories; for (const auto& vb : volumeBuilders) { - volumeFactories.push_back([vb]( - const GeometryContext& vgctx, - const std::shared_ptr<const TrackingVolume>& inner, - const VolumeBoundsPtr&) { return vb->trackingVolume(vgctx, inner); }); + volumeFactories.push_back( + [vb](const GeometryContext& vgctx, + const std::shared_ptr<const TrackingVolume>& inner, + const VolumeBoundsPtr&) { + return vb->trackingVolume(vgctx, inner); + }); } // create cylinder volume helper auto volumeHelper = cylinderVolumeHelper_dd4hep(); // hand over the collected volume builders Acts::TrackingGeometryBuilder::Config tgbConfig; - tgbConfig.trackingVolumeHelper = volumeHelper; + tgbConfig.trackingVolumeHelper = volumeHelper; tgbConfig.trackingVolumeBuilders = std::move(volumeFactories); - auto trackingGeometryBuilder - = std::make_shared<const Acts::TrackingGeometryBuilder>(tgbConfig); + auto trackingGeometryBuilder = + std::make_shared<const Acts::TrackingGeometryBuilder>(tgbConfig); return (trackingGeometryBuilder->trackingGeometry(gctx)); } -std::shared_ptr<const CylinderVolumeBuilder> -volumeBuilder_dd4hep(dd4hep::DetElement subDetector, - Logging::Level loggingLevel, - BinningType bTypePhi, - BinningType bTypeR, - BinningType bTypeZ, - double layerEnvelopeR, - double layerEnvelopeZ, - double defaultLayerThickness) -{ +std::shared_ptr<const CylinderVolumeBuilder> volumeBuilder_dd4hep( + dd4hep::DetElement subDetector, Logging::Level loggingLevel, + BinningType bTypePhi, BinningType bTypeR, BinningType bTypeZ, + double layerEnvelopeR, double layerEnvelopeZ, + double defaultLayerThickness) { // create cylinder volume helper auto volumeHelper = cylinderVolumeHelper_dd4hep(); // create local logger for conversion - auto DD4hepConverterlogger - = Acts::getDefaultLogger("DD4hepConversion", loggingLevel); + auto DD4hepConverterlogger = + Acts::getDefaultLogger("DD4hepConversion", loggingLevel); ACTS_LOCAL_LOGGER(DD4hepConverterlogger); Acts::IActsExtension* subDetExtension = nullptr; @@ -164,26 +148,26 @@ volumeBuilder_dd4hep(dd4hep::DetElement subDetector, // flags to catch if sub volumes have been set already bool nEndCap = false; bool pEndCap = false; - bool barrel = false; + bool barrel = false; for (auto& volumeDetElement : compounds) { ACTS_VERBOSE("[V] Volume : '" << subDetector.name() << "'is a compound volume -> resolve now the sub volumes"); // get the dimensions of the volume - TGeoShape* geoShape - = volumeDetElement.placement().ptr()->GetVolume()->GetShape(); + TGeoShape* geoShape = + volumeDetElement.placement().ptr()->GetVolume()->GetShape(); // check if it has a shape (the other case should not happen) if (geoShape != nullptr) { zPos = volumeDetElement.placement() .ptr() ->GetMatrix() - ->GetTranslation()[2] - * units::_cm; + ->GetTranslation()[2] * + units::_cm; } else { - throw std::logic_error(std::string("Volume of DetElement: ") - + volumeDetElement.name() - + std::string(" has no shape!")); + throw std::logic_error(std::string("Volume of DetElement: ") + + volumeDetElement.name() + + std::string(" has no shape!")); } // check if it has a volume extension telling if it is a barrel or an // endcap @@ -192,16 +176,16 @@ volumeBuilder_dd4hep(dd4hep::DetElement subDetector, volumeExtension = volumeDetElement.extension<IActsExtension>(); } catch (std::runtime_error& e) { throw std::logic_error( - std::string("[V] Current DetElement: ") + volumeDetElement.name() - + std::string(" has no ActsExtension! At this stage it should be a " - "detector volume declared as Barrel or Endcap. Please" - "check your detector construction.")); + std::string("[V] Current DetElement: ") + volumeDetElement.name() + + std::string(" has no ActsExtension! At this stage it should be a " + "detector volume declared as Barrel or Endcap. Please" + "check your detector construction.")); } if (volumeExtension->isEndcap()) { ACTS_VERBOSE( - std::string("[V] Subvolume : '") + volumeDetElement.name() - + std::string("' is a disc volume -> handling as an endcap")); + std::string("[V] Subvolume : '") + volumeDetElement.name() + + std::string("' is a disc volume -> handling as an endcap")); if (zPos < 0.) { if (nEndCap) { throw std::logic_error( @@ -227,10 +211,11 @@ volumeBuilder_dd4hep(dd4hep::DetElement subDetector, } } else if (volumeExtension->isBarrel()) { if (barrel) { - throw std::logic_error("[V] Barrel was already given for this " - "hierachy! Please create a new " - "DD4hep_SubDetectorAssembly for the next " - "hierarchy."); + throw std::logic_error( + "[V] Barrel was already given for this " + "hierachy! Please create a new " + "DD4hep_SubDetectorAssembly for the next " + "hierarchy."); } barrel = true; ACTS_VERBOSE("[V] Subvolume : " @@ -239,52 +224,50 @@ volumeBuilder_dd4hep(dd4hep::DetElement subDetector, collectLayers_dd4hep(volumeDetElement, centralLayers); } else { throw std::logic_error( - std::string("[V] Current DetElement: ") + volumeDetElement.name() - + std::string( - " has wrong ActsExtension! At this stage it should be a " - "detector volume declared as Barrel or Endcap. Please " - "check your detector construction.")); + std::string("[V] Current DetElement: ") + volumeDetElement.name() + + std::string( + " has wrong ActsExtension! At this stage it should be a " + "detector volume declared as Barrel or Endcap. Please " + "check your detector construction.")); } } if ((pEndCap && !nEndCap) || (!pEndCap && nEndCap)) { - throw std::logic_error("Only one Endcap is given for the current " - "hierarchy! Endcaps should always occur in " - "pairs. Please check your detector " - "construction."); + throw std::logic_error( + "Only one Endcap is given for the current " + "hierarchy! Endcaps should always occur in " + "pairs. Please check your detector " + "construction."); } // configure SurfaceArrayCreator - auto surfaceArrayCreator - = std::make_shared<const Acts::SurfaceArrayCreator>( + auto surfaceArrayCreator = + std::make_shared<const Acts::SurfaceArrayCreator>( Acts::getDefaultLogger("SurfaceArrayCreator", loggingLevel)); // configure LayerCreator Acts::LayerCreator::Config lcConfig; lcConfig.surfaceArrayCreator = surfaceArrayCreator; - auto layerCreator = std::make_shared<const Acts::LayerCreator>( + auto layerCreator = std::make_shared<const Acts::LayerCreator>( lcConfig, Acts::getDefaultLogger("LayerCreator", loggingLevel)); // configure DD4hepLayerBuilder Acts::DD4hepLayerBuilder::Config lbConfig; lbConfig.configurationName = subDetector.name(); - lbConfig.layerCreator = layerCreator; - lbConfig.negativeLayers = negativeLayers; - lbConfig.centralLayers = centralLayers; - lbConfig.positiveLayers = positiveLayers; - lbConfig.bTypePhi = bTypePhi; - lbConfig.bTypeR = bTypeR; - lbConfig.bTypeZ = bTypeZ; - lbConfig.defaultThickness = defaultLayerThickness; + lbConfig.layerCreator = layerCreator; + lbConfig.negativeLayers = negativeLayers; + lbConfig.centralLayers = centralLayers; + lbConfig.positiveLayers = positiveLayers; + lbConfig.bTypePhi = bTypePhi; + lbConfig.bTypeR = bTypeR; + lbConfig.bTypeZ = bTypeZ; + lbConfig.defaultThickness = defaultLayerThickness; auto dd4hepLayerBuilder = std::make_shared<const Acts::DD4hepLayerBuilder>( lbConfig, Acts::getDefaultLogger("DD4hepLayerBuilder", loggingLevel)); // get the possible material of the surounding volume dd4hep::Material ddmaterial = subDetector.volume().material(); - auto volumeMaterial - = std::make_shared<const Acts::HomogeneousVolumeMaterial>( - Acts::Material(ddmaterial.radLength(), - ddmaterial.intLength(), - ddmaterial.A(), - ddmaterial.Z(), - ddmaterial.density())); + auto volumeMaterial = + std::make_shared<const Acts::HomogeneousVolumeMaterial>(Acts::Material( + ddmaterial.radLength(), ddmaterial.intLength(), ddmaterial.A(), + ddmaterial.Z(), ddmaterial.density())); // the configuration object of the volume builder Acts::CylinderVolumeBuilder::Config cvbConfig; @@ -295,12 +278,12 @@ volumeBuilder_dd4hep(dd4hep::DetElement subDetector, cvbConfig.layerEnvelopeR = std::make_pair(layerEnvelopeR, layerEnvelopeR); cvbConfig.layerEnvelopeZ = layerEnvelopeZ; cvbConfig.trackingVolumeHelper = volumeHelper; - cvbConfig.volumeSignature = 0; - cvbConfig.volumeName = subDetector.name(); - cvbConfig.volumeMaterial = volumeMaterial; - cvbConfig.layerBuilder = dd4hepLayerBuilder; - auto cylinderVolumeBuilder - = std::make_shared<const Acts::CylinderVolumeBuilder>( + cvbConfig.volumeSignature = 0; + cvbConfig.volumeName = subDetector.name(); + cvbConfig.volumeMaterial = volumeMaterial; + cvbConfig.layerBuilder = dd4hepLayerBuilder; + auto cylinderVolumeBuilder = + std::make_shared<const Acts::CylinderVolumeBuilder>( cvbConfig, Acts::getDefaultLogger("CylinderVolumeBuilder", loggingLevel)); return cylinderVolumeBuilder; @@ -310,64 +293,57 @@ volumeBuilder_dd4hep(dd4hep::DetElement subDetector, << subDetector.name() << " is the beampipe - building beam pipe."); // get the dimensions of the volume - TGeoShape* geoShape - = subDetector.placement().ptr()->GetVolume()->GetShape(); + TGeoShape* geoShape = + subDetector.placement().ptr()->GetVolume()->GetShape(); TGeoTubeSeg* tube = dynamic_cast<TGeoTubeSeg*>(geoShape); if (tube == nullptr) { throw std::logic_error( "Beampipe has wrong shape - needs to be TGeoTubeSeg!"); } // get the dimension of TGeo and convert lengths - double rMin = tube->GetRmin() * units::_cm + layerEnvelopeR; - double rMax = tube->GetRmax() * units::_cm - layerEnvelopeR; + double rMin = tube->GetRmin() * units::_cm + layerEnvelopeR; + double rMax = tube->GetRmax() * units::_cm - layerEnvelopeR; double halfZ = tube->GetDz() * units::_cm - layerEnvelopeZ; - ACTS_VERBOSE("[V] Extracting cylindrical volume bounds ( rmin / rmax / " - "halfZ )= ( " - << rMin - << " / " - << rMax - << " / " - << halfZ - << " )"); + ACTS_VERBOSE( + "[V] Extracting cylindrical volume bounds ( rmin / rmax / " + "halfZ )= ( " + << rMin << " / " << rMax << " / " << halfZ << " )"); // get the possible material of the surounding volume - dd4hep::Material ddmaterial = subDetector.volume().material(); + dd4hep::Material ddmaterial = subDetector.volume().material(); Acts::MaterialProperties bpMaterial( ddmaterial.radLength() * units::_cm, - ddmaterial.intLength() * units::_cm, - ddmaterial.A(), - ddmaterial.Z(), + ddmaterial.intLength() * units::_cm, ddmaterial.A(), ddmaterial.Z(), ddmaterial.density() / pow(Acts::units::_cm, 3), fabs(tube->GetRmax() - tube->GetRmin()) * units::_cm); // configure the beam pipe layer builder Acts::PassiveLayerBuilder::Config bplConfig; bplConfig.layerIdentification = subDetector.name(); - bplConfig.centralLayerRadii = std::vector<double>(1, 0.5 * (rMax + rMin)); + bplConfig.centralLayerRadii = std::vector<double>(1, 0.5 * (rMax + rMin)); bplConfig.centralLayerHalflengthZ = std::vector<double>(1, halfZ); bplConfig.centralLayerThickness = std::vector<double>(1, fabs(rMax - rMin)); - bplConfig.centralLayerMaterial - = {std::make_shared<const HomogeneousSurfaceMaterial>(bpMaterial)}; + bplConfig.centralLayerMaterial = { + std::make_shared<const HomogeneousSurfaceMaterial>(bpMaterial)}; auto beamPipeBuilder = std::make_shared<const Acts::PassiveLayerBuilder>( bplConfig, Acts::getDefaultLogger(subDetector.name(), loggingLevel)); // the configuration object of the volume builder Acts::CylinderVolumeBuilder::Config cvbConfig; cvbConfig.trackingVolumeHelper = volumeHelper; - cvbConfig.volumeSignature = 0; - cvbConfig.volumeName = subDetector.name(); - cvbConfig.layerBuilder = beamPipeBuilder; - cvbConfig.layerEnvelopeR = {layerEnvelopeR, layerEnvelopeR}; - cvbConfig.layerEnvelopeZ = layerEnvelopeZ; - cvbConfig.buildToRadiusZero = true; + cvbConfig.volumeSignature = 0; + cvbConfig.volumeName = subDetector.name(); + cvbConfig.layerBuilder = beamPipeBuilder; + cvbConfig.layerEnvelopeR = {layerEnvelopeR, layerEnvelopeR}; + cvbConfig.layerEnvelopeZ = layerEnvelopeZ; + cvbConfig.buildToRadiusZero = true; // beam pipe volume builder - auto beamPipeVolumeBuilder - = std::make_shared<const Acts::CylinderVolumeBuilder>( - cvbConfig, - Acts::getDefaultLogger(subDetector.name() - + std::string("VolumdeBuilder"), - loggingLevel)); + auto beamPipeVolumeBuilder = + std::make_shared<const Acts::CylinderVolumeBuilder>( + cvbConfig, Acts::getDefaultLogger( + subDetector.name() + std::string("VolumdeBuilder"), + loggingLevel)); return beamPipeVolumeBuilder; } else if ((subDetExtension != nullptr) && subDetExtension->isBarrel()) { @@ -379,56 +355,53 @@ volumeBuilder_dd4hep(dd4hep::DetElement subDetector, collectLayers_dd4hep(subDetector, centralLayers); // configure SurfaceArrayCreator - auto surfaceArrayCreator - = std::make_shared<const Acts::SurfaceArrayCreator>( + auto surfaceArrayCreator = + std::make_shared<const Acts::SurfaceArrayCreator>( Acts::getDefaultLogger("SurfaceArrayCreator", loggingLevel)); // configure LayerCreator Acts::LayerCreator::Config lcConfig; lcConfig.surfaceArrayCreator = surfaceArrayCreator; - auto layerCreator = std::make_shared<const Acts::LayerCreator>( + auto layerCreator = std::make_shared<const Acts::LayerCreator>( lcConfig, Acts::getDefaultLogger("LayerCreator", loggingLevel)); // configure DD4hepLayerBuilder Acts::DD4hepLayerBuilder::Config lbConfig; lbConfig.configurationName = subDetector.name(); - lbConfig.layerCreator = layerCreator; - lbConfig.centralLayers = centralLayers; - lbConfig.bTypePhi = bTypePhi; - lbConfig.bTypeZ = bTypeZ; - lbConfig.defaultThickness = defaultLayerThickness; + lbConfig.layerCreator = layerCreator; + lbConfig.centralLayers = centralLayers; + lbConfig.bTypePhi = bTypePhi; + lbConfig.bTypeZ = bTypeZ; + lbConfig.defaultThickness = defaultLayerThickness; auto dd4hepLayerBuilder = std::make_shared<const Acts::DD4hepLayerBuilder>( lbConfig, Acts::getDefaultLogger("DD4hepLayerBuilder", loggingLevel)); // the configuration object of the volume builder Acts::CylinderVolumeBuilder::Config cvbConfig; // get the dimensions of the volume - TGeoShape* geoShape - = subDetector.placement().ptr()->GetVolume()->GetShape(); + TGeoShape* geoShape = + subDetector.placement().ptr()->GetVolume()->GetShape(); // this should not happen if (geoShape == nullptr) { - throw std::logic_error(std::string("Volume of DetElement: ") - + subDetector.name() - + std::string(" has no a shape!")); + throw std::logic_error(std::string("Volume of DetElement: ") + + subDetector.name() + + std::string(" has no a shape!")); } // get the possible material /// @todo volume material currently not used dd4hep::Material ddmaterial = subDetector.volume().material(); - auto volumeMaterial - = std::make_shared<const Acts::HomogeneousVolumeMaterial>( - Acts::Material(ddmaterial.radLength(), - ddmaterial.intLength(), - ddmaterial.A(), - ddmaterial.Z(), - ddmaterial.density())); + auto volumeMaterial = + std::make_shared<const Acts::HomogeneousVolumeMaterial>(Acts::Material( + ddmaterial.radLength(), ddmaterial.intLength(), ddmaterial.A(), + ddmaterial.Z(), ddmaterial.density())); cvbConfig.layerEnvelopeR = std::make_pair(layerEnvelopeR, layerEnvelopeR); cvbConfig.layerEnvelopeZ = layerEnvelopeZ; cvbConfig.trackingVolumeHelper = volumeHelper; - cvbConfig.volumeSignature = 0; - cvbConfig.volumeName = subDetector.name(); - cvbConfig.volumeMaterial = volumeMaterial; - cvbConfig.layerBuilder = dd4hepLayerBuilder; - auto cylinderVolumeBuilder - = std::make_shared<const Acts::CylinderVolumeBuilder>( + cvbConfig.volumeSignature = 0; + cvbConfig.volumeName = subDetector.name(); + cvbConfig.volumeMaterial = volumeMaterial; + cvbConfig.layerBuilder = dd4hepLayerBuilder; + auto cylinderVolumeBuilder = + std::make_shared<const Acts::CylinderVolumeBuilder>( cvbConfig, Acts::getDefaultLogger("CylinderVolumeBuilder", loggingLevel)); return cylinderVolumeBuilder; @@ -448,9 +421,8 @@ volumeBuilder_dd4hep(dd4hep::DetElement subDetector, } } -std::shared_ptr<const Acts::CylinderVolumeHelper> -cylinderVolumeHelper_dd4hep(Logging::Level loggingLevel) -{ +std::shared_ptr<const Acts::CylinderVolumeHelper> cylinderVolumeHelper_dd4hep( + Logging::Level loggingLevel) { // create cylindervolumehelper which can be used by all instances // hand over LayerArrayCreator Acts::LayerArrayCreator::Config lacConfig; @@ -458,35 +430,33 @@ cylinderVolumeHelper_dd4hep(Logging::Level loggingLevel) lacConfig, Acts::getDefaultLogger("LayArrayCreator", loggingLevel)); // tracking volume array creator Acts::TrackingVolumeArrayCreator::Config tvacConfig; - auto trackingVolumeArrayCreator - = std::make_shared<const Acts::TrackingVolumeArrayCreator>( + auto trackingVolumeArrayCreator = + std::make_shared<const Acts::TrackingVolumeArrayCreator>( tvacConfig, Acts::getDefaultLogger("TrkVolArrayCreator", loggingLevel)); // configure the cylinder volume helper Acts::CylinderVolumeHelper::Config cvhConfig; - cvhConfig.layerArrayCreator = layerArrayCreator; + cvhConfig.layerArrayCreator = layerArrayCreator; cvhConfig.trackingVolumeArrayCreator = trackingVolumeArrayCreator; - auto cylinderVolumeHelper - = std::make_shared<const Acts::CylinderVolumeHelper>( + auto cylinderVolumeHelper = + std::make_shared<const Acts::CylinderVolumeHelper>( cvhConfig, Acts::getDefaultLogger("CylVolHelper", loggingLevel)); return cylinderVolumeHelper; } -void -collectCompounds_dd4hep(dd4hep::DetElement& detElement, - std::vector<dd4hep::DetElement>& compounds) -{ +void collectCompounds_dd4hep(dd4hep::DetElement& detElement, + std::vector<dd4hep::DetElement>& compounds) { const dd4hep::DetElement::Children& children = detElement.children(); for (auto& child : children) { - dd4hep::DetElement childDetElement = child.second; - Acts::IActsExtension* detExtension = nullptr; + dd4hep::DetElement childDetElement = child.second; + Acts::IActsExtension* detExtension = nullptr; try { detExtension = childDetElement.extension<Acts::IActsExtension>(); } catch (std::runtime_error& e) { } - if ((detExtension != nullptr) - && (detExtension->isBarrel() || detExtension->isEndcap())) { + if ((detExtension != nullptr) && + (detExtension->isBarrel() || detExtension->isEndcap())) { compounds.push_back(childDetElement); continue; } @@ -494,14 +464,12 @@ collectCompounds_dd4hep(dd4hep::DetElement& detElement, } } -void -collectSubDetectors_dd4hep(dd4hep::DetElement& detElement, - std::vector<dd4hep::DetElement>& subdetectors) -{ +void collectSubDetectors_dd4hep(dd4hep::DetElement& detElement, + std::vector<dd4hep::DetElement>& subdetectors) { const dd4hep::DetElement::Children& children = detElement.children(); for (auto& child : children) { - dd4hep::DetElement childDetElement = child.second; - Acts::IActsExtension* detExtension = nullptr; + dd4hep::DetElement childDetElement = child.second; + Acts::IActsExtension* detExtension = nullptr; try { detExtension = childDetElement.extension<Acts::IActsExtension>(); } catch (std::runtime_error& e) { @@ -510,8 +478,8 @@ collectSubDetectors_dd4hep(dd4hep::DetElement& detElement, continue; } } - if ((detExtension != nullptr) - && (detExtension->isBarrel() || detExtension->isBeampipe())) { + if ((detExtension != nullptr) && + (detExtension->isBarrel() || detExtension->isBeampipe())) { subdetectors.push_back(childDetElement); continue; } @@ -519,14 +487,12 @@ collectSubDetectors_dd4hep(dd4hep::DetElement& detElement, } } -void -collectLayers_dd4hep(dd4hep::DetElement& detElement, - std::vector<dd4hep::DetElement>& layers) -{ +void collectLayers_dd4hep(dd4hep::DetElement& detElement, + std::vector<dd4hep::DetElement>& layers) { const dd4hep::DetElement::Children& children = detElement.children(); for (auto& child : children) { - dd4hep::DetElement childDetElement = child.second; - Acts::IActsExtension* detExtension = nullptr; + dd4hep::DetElement childDetElement = child.second; + Acts::IActsExtension* detExtension = nullptr; try { detExtension = childDetElement.extension<Acts::IActsExtension>(); } catch (std::runtime_error& e) { diff --git a/Plugins/DD4hep/src/DD4hepDetectorElement.cpp b/Plugins/DD4hep/src/DD4hepDetectorElement.cpp index 2895391dc2a9bc1df49ef3b91ac28fd40d76078a..0dffde9e61a7995da0fa9ce62a1983a040f85112 100644 --- a/Plugins/DD4hep/src/DD4hepDetectorElement.cpp +++ b/Plugins/DD4hep/src/DD4hepDetectorElement.cpp @@ -14,20 +14,12 @@ #include "DD4hep/CartesianGridXY.h" Acts::DD4hepDetectorElement::DD4hepDetectorElement( - const dd4hep::DetElement detElement, - const std::string& axes, - double scalor, - bool isDisc, - std::shared_ptr<const Acts::ISurfaceMaterial> material, + const dd4hep::DetElement detElement, const std::string& axes, double scalor, + bool isDisc, std::shared_ptr<const Acts::ISurfaceMaterial> material, std::shared_ptr<const Acts::DigitizationModule> digitizationModule) - : Acts::TGeoDetectorElement(Identifier(detElement.volumeID()), - detElement.nominal().worldTransformation(), - detElement.placement().ptr(), - axes, - scalor, - isDisc, - std::move(material), - std::move(digitizationModule)) - , m_detElement(std::move(detElement)) -{ -} + : Acts::TGeoDetectorElement(Identifier(detElement.volumeID()), + detElement.nominal().worldTransformation(), + detElement.placement().ptr(), axes, scalor, + isDisc, std::move(material), + std::move(digitizationModule)), + m_detElement(std::move(detElement)) {} diff --git a/Plugins/DD4hep/src/DD4hepLayerBuilder.cpp b/Plugins/DD4hep/src/DD4hepLayerBuilder.cpp index 33b68cdbe54e06000b48fa704d7da8ef78f8ed42..14c3036f395135411ec86f9937d6cfc23d721ac8 100644 --- a/Plugins/DD4hep/src/DD4hepLayerBuilder.cpp +++ b/Plugins/DD4hep/src/DD4hepLayerBuilder.cpp @@ -33,30 +33,27 @@ Acts::DD4hepLayerBuilder::DD4hepLayerBuilder( const Acts::DD4hepLayerBuilder::Config& config, - std::unique_ptr<const Logger> logger) - : m_cfg(), m_logger(std::move(logger)) -{ + std::unique_ptr<const Logger> logger) + : m_cfg(), m_logger(std::move(logger)) { setConfiguration(config); } Acts::DD4hepLayerBuilder::~DD4hepLayerBuilder() = default; -void -Acts::DD4hepLayerBuilder::setConfiguration( - const Acts::DD4hepLayerBuilder::Config& config) -{ +void Acts::DD4hepLayerBuilder::setConfiguration( + const Acts::DD4hepLayerBuilder::Config& config) { m_cfg = config; } -const Acts::LayerVector -Acts::DD4hepLayerBuilder::negativeLayers(const GeometryContext& gctx) const -{ +const Acts::LayerVector Acts::DD4hepLayerBuilder::negativeLayers( + const GeometryContext& gctx) const { LayerVector layers; if (m_cfg.negativeLayers.empty()) { ACTS_VERBOSE("[L] No layers handed over for negative volume."); } else { - ACTS_VERBOSE("[L] Received layers for negative volume -> creating " - "disc layers"); + ACTS_VERBOSE( + "[L] Received layers for negative volume -> creating " + "disc layers"); // go through layers for (auto& detElement : m_cfg.negativeLayers) { // prepare the layer surfaces @@ -64,18 +61,18 @@ Acts::DD4hepLayerBuilder::negativeLayers(const GeometryContext& gctx) const // access the extension of the layer // at this stage all layer detElements have extension (checked in // ConvertDD4hepDetector) - Acts::IActsExtension* detExtension - = detElement.extension<Acts::IActsExtension>(); + Acts::IActsExtension* detExtension = + detElement.extension<Acts::IActsExtension>(); // access the axis orienation of the modules std::string axes = detExtension->axes(); // collect the sensitive detector elements possibly contained by the layer resolveSensitive(detElement, layerSurfaces, axes); // access the global transformation matrix of the layer - auto transform - = convertTransform(&(detElement.nominal().worldTransformation())); + auto transform = + convertTransform(&(detElement.nominal().worldTransformation())); // get the shape of the layer - TGeoShape* geoShape - = detElement.placement().ptr()->GetVolume()->GetShape(); + TGeoShape* geoShape = + detElement.placement().ptr()->GetVolume()->GetShape(); // create the proto layer ProtoLayer pl(gctx, layerSurfaces); if (detExtension->buildEnvelope()) { @@ -90,14 +87,14 @@ Acts::DD4hepLayerBuilder::negativeLayers(const GeometryContext& gctx) const // extract the boundaries double rMin = tube->GetRmin() * units::_cm; double rMax = tube->GetRmax() * units::_cm; - double zMin - = (transform->translation() - - transform->rotation().col(2) * tube->GetDz() * units::_cm) - .z(); - double zMax - = (transform->translation() - + transform->rotation().col(2) * tube->GetDz() * units::_cm) - .z(); + double zMin = + (transform->translation() - + transform->rotation().col(2) * tube->GetDz() * units::_cm) + .z(); + double zMax = + (transform->translation() + + transform->rotation().col(2) * tube->GetDz() * units::_cm) + .z(); if (zMin > zMax) { std::swap(zMin, zMax); } @@ -123,10 +120,10 @@ Acts::DD4hepLayerBuilder::negativeLayers(const GeometryContext& gctx) const } } else { throw std::logic_error( - std::string("Layer DetElement: ") + detElement.name() - + std::string(" has neither a shape nor tolerances for envelopes " - "added to itÂ¥s extension. Please check your detector " - "constructor!")); + std::string("Layer DetElement: ") + detElement.name() + + std::string(" has neither a shape nor tolerances for envelopes " + "added to itÂ¥s extension. Please check your detector " + "constructor!")); } // if the layer should carry material it will be marked by assigning a @@ -141,60 +138,53 @@ Acts::DD4hepLayerBuilder::negativeLayers(const GeometryContext& gctx) const // check if layer should have material if (detExtension->hasSupportMaterial()) { std::pair<size_t, size_t> materialBins = detExtension->materialBins(); - size_t bins1 = materialBins.first; - size_t bins2 = materialBins.second; - Acts::BinUtility materialBinUtil( - bins1, -M_PI, M_PI, Acts::closed, Acts::binPhi); - materialBinUtil += Acts::BinUtility( - bins2, pl.minR, pl.maxR, Acts::open, Acts::binR, transform); + size_t bins1 = materialBins.first; + size_t bins2 = materialBins.second; + Acts::BinUtility materialBinUtil(bins1, -M_PI, M_PI, Acts::closed, + Acts::binPhi); + materialBinUtil += Acts::BinUtility(bins2, pl.minR, pl.maxR, Acts::open, + Acts::binR, transform); // and create material proxy to mark layer for material mapping - materialProxy - = std::make_shared<const ProtoSurfaceMaterial>(materialBinUtil); + materialProxy = + std::make_shared<const ProtoSurfaceMaterial>(materialBinUtil); // access the material position layerPos = detExtension->layerMaterialPosition(); ACTS_VERBOSE( "[L] Layer is marked to carry support material on Surface ( " "inner=0 / center=1 / outer=2 ) : " - << layerPos - << " with binning: [" - << bins1 - << ", " - << bins2 + << layerPos << " with binning: [" << bins1 << ", " << bins2 << "]"); // Create an approachdescriptor for the layer // create the new surfaces for the approachdescriptor std::vector<std::shared_ptr<const Acts::Surface>> aSurfaces; // The layer thicknesses - auto layerThickness - = std::fabs(pl.minZ - pl.maxZ) + pl.envZ.first + pl.envZ.second; + auto layerThickness = + std::fabs(pl.minZ - pl.maxZ) + pl.envZ.first + pl.envZ.second; // create the inner and outer boundary surfaces // first create the positions - Vector3D innerPos = transform->translation() - - transform->rotation().col(2) * layerThickness * 0.5; - Vector3D outerPos = transform->translation() - + transform->rotation().col(2) * layerThickness * 0.5; + Vector3D innerPos = transform->translation() - + transform->rotation().col(2) * layerThickness * 0.5; + Vector3D outerPos = transform->translation() + + transform->rotation().col(2) * layerThickness * 0.5; if (innerPos.z() > outerPos.z()) { std::swap(innerPos, outerPos); } - std::shared_ptr<Acts::DiscSurface> innerBoundary - = Surface::makeShared<Acts::DiscSurface>( - std::make_shared<const Transform3D>(Translation3D(innerPos) - * transform->rotation()), - pl.minR, - pl.maxR); + std::shared_ptr<Acts::DiscSurface> innerBoundary = + Surface::makeShared<Acts::DiscSurface>( + std::make_shared<const Transform3D>(Translation3D(innerPos) * + transform->rotation()), + pl.minR, pl.maxR); - std::shared_ptr<Acts::DiscSurface> outerBoundary - = Surface::makeShared<Acts::DiscSurface>( - std::make_shared<const Transform3D>(Translation3D(outerPos) - * transform->rotation()), - pl.minR, - pl.maxR); + std::shared_ptr<Acts::DiscSurface> outerBoundary = + Surface::makeShared<Acts::DiscSurface>( + std::make_shared<const Transform3D>(Translation3D(outerPos) * + transform->rotation()), + pl.minR, pl.maxR); - std::shared_ptr<Acts::DiscSurface> centralSurface - = Surface::makeShared<Acts::DiscSurface>( - transform, pl.minR, pl.maxR); + std::shared_ptr<Acts::DiscSurface> centralSurface = + Surface::makeShared<Acts::DiscSurface>(transform, pl.minR, pl.maxR); // set material surface if (layerPos == Acts::LayerMaterialPos::inner) { @@ -225,29 +215,21 @@ Acts::DD4hepLayerBuilder::negativeLayers(const GeometryContext& gctx) const auto sensitiveSurf = createSensitiveSurface(detElement, true); // Create the surfaceArray - std::unique_ptr<Acts::SurfaceArray> sArray - = std::make_unique<SurfaceArray>(sensitiveSurf); + std::unique_ptr<Acts::SurfaceArray> sArray = + std::make_unique<SurfaceArray>(sensitiveSurf); // create the share disc bounds - auto dBounds = std::make_shared<const RadialBounds>(pl.minR, pl.maxR); + auto dBounds = std::make_shared<const RadialBounds>(pl.minR, pl.maxR); double thickness = std::fabs(pl.maxZ - pl.minZ); // Create the layer containing the sensitive surface - negativeLayer = DiscLayer::create(transform, - dBounds, - std::move(sArray), - thickness, - std::move(approachDescriptor), - Acts::active); + negativeLayer = + DiscLayer::create(transform, dBounds, std::move(sArray), thickness, + std::move(approachDescriptor), Acts::active); } else { - negativeLayer - = m_cfg.layerCreator->discLayer(gctx, - layerSurfaces, - m_cfg.bTypeR, - m_cfg.bTypePhi, - pl, - transform, - std::move(approachDescriptor)); + negativeLayer = m_cfg.layerCreator->discLayer( + gctx, layerSurfaces, m_cfg.bTypeR, m_cfg.bTypePhi, pl, transform, + std::move(approachDescriptor)); } // get the possible material if no surfaces are handed over @@ -257,8 +239,7 @@ Acts::DD4hepLayerBuilder::negativeLayers(const GeometryContext& gctx) const if (!boost::iequals(ddmaterial.name(), "vacuum")) { Material layerMaterial(ddmaterial.radLength() * Acts::units::_cm, ddmaterial.intLength() * Acts::units::_cm, - ddmaterial.A(), - ddmaterial.Z(), + ddmaterial.A(), ddmaterial.Z(), ddmaterial.density() / pow(Acts::units::_cm, 3)); MaterialProperties materialProperties(layerMaterial, @@ -278,15 +259,15 @@ Acts::DD4hepLayerBuilder::negativeLayers(const GeometryContext& gctx) const return layers; } -const Acts::LayerVector -Acts::DD4hepLayerBuilder::centralLayers(const GeometryContext& gctx) const -{ +const Acts::LayerVector Acts::DD4hepLayerBuilder::centralLayers( + const GeometryContext& gctx) const { LayerVector layers; if (m_cfg.centralLayers.empty()) { ACTS_VERBOSE("[L] No layers handed over for central volume!"); } else { - ACTS_VERBOSE("[L] Received layers for central volume -> creating " - "cylindrical layers"); + ACTS_VERBOSE( + "[L] Received layers for central volume -> creating " + "cylindrical layers"); // go through layers for (auto& detElement : m_cfg.centralLayers) { // prepare the layer surfaces @@ -294,18 +275,18 @@ Acts::DD4hepLayerBuilder::centralLayers(const GeometryContext& gctx) const // access the extension of the layer // at this stage all layer detElements have extension (checked in // ConvertDD4hepDetector) - Acts::IActsExtension* detExtension - = detElement.extension<Acts::IActsExtension>(); + Acts::IActsExtension* detExtension = + detElement.extension<Acts::IActsExtension>(); // access the axis orienation of the modules std::string axes = detExtension->axes(); // collect the sensitive detector elements possibly contained by the layer resolveSensitive(detElement, layerSurfaces, axes); // access the global transformation matrix of the layer - auto transform - = convertTransform(&(detElement.nominal().worldTransformation())); + auto transform = + convertTransform(&(detElement.nominal().worldTransformation())); // get the shape of the layer - TGeoShape* geoShape - = detElement.placement().ptr()->GetVolume()->GetShape(); + TGeoShape* geoShape = + detElement.placement().ptr()->GetVolume()->GetShape(); // create the proto layer ProtoLayer pl(gctx, layerSurfaces); if (detExtension->buildEnvelope()) { @@ -321,7 +302,7 @@ Acts::DD4hepLayerBuilder::centralLayers(const GeometryContext& gctx) const // extract the boundaries double rMin = tube->GetRmin() * units::_cm; double rMax = tube->GetRmax() * units::_cm; - double dz = tube->GetDz() * units::_cm; + double dz = tube->GetDz() * units::_cm; // check if layer has surfaces if (layerSurfaces.empty()) { // in case no surfaces are handed over the layer thickness will be set @@ -343,10 +324,10 @@ Acts::DD4hepLayerBuilder::centralLayers(const GeometryContext& gctx) const } } else { throw std::logic_error( - std::string("Layer DetElement: ") + detElement.name() - + std::string(" has neither a shape nor tolerances for envelopes " - "added to itÂ¥s extension. Please check your detector " - "constructor!")); + std::string("Layer DetElement: ") + detElement.name() + + std::string(" has neither a shape nor tolerances for envelopes " + "added to itÂ¥s extension. Please check your detector " + "constructor!")); } double halfZ = (pl.minZ - pl.maxZ) * 0.5; @@ -363,7 +344,6 @@ Acts::DD4hepLayerBuilder::centralLayers(const GeometryContext& gctx) const // check if layer should have material if (detExtension->hasSupportMaterial()) { - // Create an approachdescriptor for the layer // create the new surfaces for the approachdescriptor std::vector<std::shared_ptr<const Acts::Surface>> aSurfaces; @@ -379,25 +359,21 @@ Acts::DD4hepLayerBuilder::centralLayers(const GeometryContext& gctx) const std::pair<size_t, size_t> materialBins = detExtension->materialBins(); - size_t bins1 = materialBins.first; - size_t bins2 = materialBins.second; - Acts::BinUtility materialBinUtil( - bins1, -M_PI, M_PI, Acts::closed, Acts::binPhi); - materialBinUtil += Acts::BinUtility( - bins2, -halfZ, halfZ, Acts::open, Acts::binZ, transform); + size_t bins1 = materialBins.first; + size_t bins2 = materialBins.second; + Acts::BinUtility materialBinUtil(bins1, -M_PI, M_PI, Acts::closed, + Acts::binPhi); + materialBinUtil += Acts::BinUtility(bins2, -halfZ, halfZ, Acts::open, + Acts::binZ, transform); // and create material proxy to mark layer for material mapping - materialProxy - = std::make_shared<const ProtoSurfaceMaterial>(materialBinUtil); + materialProxy = + std::make_shared<const ProtoSurfaceMaterial>(materialBinUtil); // access the material position layerPos = detExtension->layerMaterialPosition(); ACTS_VERBOSE( "[L] Layer is marked to carry support material on Surface ( " "inner=0 / center=1 / outer=2 ) : " - << layerPos - << " with binning: [" - << bins1 - << ", " - << bins2 + << layerPos << " with binning: [" << bins1 << ", " << bins2 << "]"); // check if the material should be set to the inner or outer boundary @@ -431,31 +407,23 @@ Acts::DD4hepLayerBuilder::centralLayers(const GeometryContext& gctx) const // Create the sensitive surface auto sensitiveSurf = createSensitiveSurface(detElement); // Create the surfaceArray - std::unique_ptr<Acts::SurfaceArray> sArray - = std::make_unique<SurfaceArray>(sensitiveSurf); + std::unique_ptr<Acts::SurfaceArray> sArray = + std::make_unique<SurfaceArray>(sensitiveSurf); // create the layer - double layerR = (pl.minR + pl.maxR) * 0.5; + double layerR = (pl.minR + pl.maxR) * 0.5; double thickness = std::fabs(pl.maxR - pl.minR); std::shared_ptr<const CylinderBounds> cBounds( new CylinderBounds(layerR, halfZ)); // Create the layer containing the sensitive surface - centralLayer = CylinderLayer::create(transform, - cBounds, - std::move(sArray), - thickness, - std::move(approachDescriptor), - Acts::active); + centralLayer = CylinderLayer::create( + transform, cBounds, std::move(sArray), thickness, + std::move(approachDescriptor), Acts::active); } else { - centralLayer - = m_cfg.layerCreator->cylinderLayer(gctx, - layerSurfaces, - m_cfg.bTypePhi, - m_cfg.bTypeZ, - pl, - transform, - std::move(approachDescriptor)); + centralLayer = m_cfg.layerCreator->cylinderLayer( + gctx, layerSurfaces, m_cfg.bTypePhi, m_cfg.bTypeZ, pl, transform, + std::move(approachDescriptor)); } // get the possible material if no surfaces are handed over @@ -465,8 +433,7 @@ Acts::DD4hepLayerBuilder::centralLayers(const GeometryContext& gctx) const if (!boost::iequals(ddmaterial.name(), "vacuum")) { Material layerMaterial(ddmaterial.radLength() * Acts::units::_cm, ddmaterial.intLength() * Acts::units::_cm, - ddmaterial.A(), - ddmaterial.Z(), + ddmaterial.A(), ddmaterial.Z(), ddmaterial.density() / pow(Acts::units::_cm, 3)); MaterialProperties materialProperties(layerMaterial, @@ -487,15 +454,15 @@ Acts::DD4hepLayerBuilder::centralLayers(const GeometryContext& gctx) const return layers; } -const Acts::LayerVector -Acts::DD4hepLayerBuilder::positiveLayers(const GeometryContext& gctx) const -{ +const Acts::LayerVector Acts::DD4hepLayerBuilder::positiveLayers( + const GeometryContext& gctx) const { LayerVector layers; if (m_cfg.positiveLayers.empty()) { ACTS_VERBOSE("[L] No layers handed over for positive volume!"); } else { - ACTS_VERBOSE("[L] Received layers for positive volume -> creating " - "disc layers"); + ACTS_VERBOSE( + "[L] Received layers for positive volume -> creating " + "disc layers"); // go through layers for (auto& detElement : m_cfg.positiveLayers) { // prepare the layer surfaces @@ -503,18 +470,18 @@ Acts::DD4hepLayerBuilder::positiveLayers(const GeometryContext& gctx) const // access the extension of the layer // at this stage all layer detElements have extension (checked in // ConvertDD4hepDetector) - Acts::IActsExtension* detExtension - = detElement.extension<Acts::IActsExtension>(); + Acts::IActsExtension* detExtension = + detElement.extension<Acts::IActsExtension>(); // access the axis orienation of the modules std::string axes = detExtension->axes(); // collect the sensitive detector elements possibly contained by the layer resolveSensitive(detElement, layerSurfaces, axes); // access the global transformation matrix of the layer - auto transform - = convertTransform(&(detElement.nominal().worldTransformation())); + auto transform = + convertTransform(&(detElement.nominal().worldTransformation())); // get the shape of the layer - TGeoShape* geoShape - = detElement.placement().ptr()->GetVolume()->GetShape(); + TGeoShape* geoShape = + detElement.placement().ptr()->GetVolume()->GetShape(); // create the proto layer ProtoLayer pl(gctx, layerSurfaces); if (detExtension->buildEnvelope()) { @@ -529,14 +496,14 @@ Acts::DD4hepLayerBuilder::positiveLayers(const GeometryContext& gctx) const // extract the boundaries double rMin = tube->GetRmin() * units::_cm; double rMax = tube->GetRmax() * units::_cm; - double zMin - = (transform->translation() - - transform->rotation().col(2) * tube->GetDz() * units::_cm) - .z(); - double zMax - = (transform->translation() - + transform->rotation().col(2) * tube->GetDz() * units::_cm) - .z(); + double zMin = + (transform->translation() - + transform->rotation().col(2) * tube->GetDz() * units::_cm) + .z(); + double zMax = + (transform->translation() + + transform->rotation().col(2) * tube->GetDz() * units::_cm) + .z(); if (zMin > zMax) { std::swap(zMin, zMax); } @@ -562,10 +529,10 @@ Acts::DD4hepLayerBuilder::positiveLayers(const GeometryContext& gctx) const } } else { throw std::logic_error( - std::string("Layer DetElement: ") + detElement.name() - + std::string(" has neither a shape nor tolerances for envelopes " - "added to itÂ¥s extension. Please check your detector " - "constructor!")); + std::string("Layer DetElement: ") + detElement.name() + + std::string(" has neither a shape nor tolerances for envelopes " + "added to itÂ¥s extension. Please check your detector " + "constructor!")); } // if the layer should carry material it will be marked by assigning a @@ -580,57 +547,51 @@ Acts::DD4hepLayerBuilder::positiveLayers(const GeometryContext& gctx) const // check if layer should have material if (detExtension->hasSupportMaterial()) { std::pair<size_t, size_t> materialBins = detExtension->materialBins(); - size_t bins1 = materialBins.first; - size_t bins2 = materialBins.second; - Acts::BinUtility materialBinUtil( - bins1, -M_PI, M_PI, Acts::closed, Acts::binPhi); - materialBinUtil += Acts::BinUtility( - bins2, pl.minR, pl.maxR, Acts::open, Acts::binR, transform); + size_t bins1 = materialBins.first; + size_t bins2 = materialBins.second; + Acts::BinUtility materialBinUtil(bins1, -M_PI, M_PI, Acts::closed, + Acts::binPhi); + materialBinUtil += Acts::BinUtility(bins2, pl.minR, pl.maxR, Acts::open, + Acts::binR, transform); // and create material proxy to mark layer for material mapping - materialProxy - = std::make_shared<const ProtoSurfaceMaterial>(materialBinUtil); + materialProxy = + std::make_shared<const ProtoSurfaceMaterial>(materialBinUtil); // access the material position layerPos = detExtension->layerMaterialPosition(); ACTS_VERBOSE( "[L] Layer is marked to carry support material on Surface ( " "inner=0 / center=1 / outer=2 ) : " - << layerPos - << " with binning: [" - << bins1 - << ", " - << bins2 + << layerPos << " with binning: [" << bins1 << ", " << bins2 << "]"); // Create an approachdescriptor for the layer // create the new surfaces for the approachdescriptor std::vector<std::shared_ptr<const Acts::Surface>> aSurfaces; // The layer thicknesses - auto layerThickness - = std::fabs(pl.minZ - pl.maxZ) + pl.envZ.first + pl.envZ.second; + auto layerThickness = + std::fabs(pl.minZ - pl.maxZ) + pl.envZ.first + pl.envZ.second; // create the inner and outer boundary surfaces // first create the positions - Vector3D innerPos = transform->translation() - - transform->rotation().col(2) * layerThickness * 0.5; - Vector3D outerPos = transform->translation() - + transform->rotation().col(2) * layerThickness * 0.5; + Vector3D innerPos = transform->translation() - + transform->rotation().col(2) * layerThickness * 0.5; + Vector3D outerPos = transform->translation() + + transform->rotation().col(2) * layerThickness * 0.5; if (innerPos.z() > outerPos.z()) { std::swap(innerPos, outerPos); } auto innerBoundary = Surface::makeShared<Acts::DiscSurface>( - std::make_shared<const Transform3D>(Translation3D(innerPos) - * transform->rotation()), - pl.minR, - pl.maxR); + std::make_shared<const Transform3D>(Translation3D(innerPos) * + transform->rotation()), + pl.minR, pl.maxR); auto outerBoundary = Surface::makeShared<Acts::DiscSurface>( - std::make_shared<const Transform3D>(Translation3D(outerPos) - * transform->rotation()), - pl.minR, - pl.maxR); + std::make_shared<const Transform3D>(Translation3D(outerPos) * + transform->rotation()), + pl.minR, pl.maxR); - auto centralSurface = Surface::makeShared<Acts::DiscSurface>( - transform, pl.minR, pl.maxR); + auto centralSurface = + Surface::makeShared<Acts::DiscSurface>(transform, pl.minR, pl.maxR); // set material surface if (layerPos == Acts::LayerMaterialPos::inner) { @@ -650,8 +611,8 @@ Acts::DD4hepLayerBuilder::positiveLayers(const GeometryContext& gctx) const aSurfaces.push_back(outerBoundary); // create an ApproachDescriptor with standard surfaces - these // will be deleted by the approach descriptor - approachDescriptor - = std::make_unique<Acts::GenericApproachDescriptor>(aSurfaces); + approachDescriptor = + std::make_unique<Acts::GenericApproachDescriptor>(aSurfaces); } std::shared_ptr<Layer> positiveLayer = nullptr; @@ -660,29 +621,21 @@ Acts::DD4hepLayerBuilder::positiveLayers(const GeometryContext& gctx) const // Create the sensitive surface auto sensitiveSurf = createSensitiveSurface(detElement, true); // Create the surfaceArray - std::unique_ptr<Acts::SurfaceArray> sArray - = std::make_unique<SurfaceArray>(sensitiveSurf); + std::unique_ptr<Acts::SurfaceArray> sArray = + std::make_unique<SurfaceArray>(sensitiveSurf); // create the share disc bounds - auto dBounds = std::make_shared<const RadialBounds>(pl.minR, pl.maxR); + auto dBounds = std::make_shared<const RadialBounds>(pl.minR, pl.maxR); double thickness = std::fabs(pl.maxZ - pl.minZ); // Create the layer containing the sensitive surface - positiveLayer = DiscLayer::create(transform, - dBounds, - std::move(sArray), - thickness, - std::move(approachDescriptor), - Acts::active); + positiveLayer = + DiscLayer::create(transform, dBounds, std::move(sArray), thickness, + std::move(approachDescriptor), Acts::active); } else { - positiveLayer - = m_cfg.layerCreator->discLayer(gctx, - layerSurfaces, - m_cfg.bTypeR, - m_cfg.bTypePhi, - pl, - transform, - std::move(approachDescriptor)); + positiveLayer = m_cfg.layerCreator->discLayer( + gctx, layerSurfaces, m_cfg.bTypeR, m_cfg.bTypePhi, pl, transform, + std::move(approachDescriptor)); } // get the possible material if no surfaces are handed over @@ -692,8 +645,7 @@ Acts::DD4hepLayerBuilder::positiveLayers(const GeometryContext& gctx) const if (!boost::iequals(ddmaterial.name(), "vacuum")) { Material layerMaterial(ddmaterial.radLength() * Acts::units::_cm, ddmaterial.intLength() * Acts::units::_cm, - ddmaterial.A(), - ddmaterial.Z(), + ddmaterial.A(), ddmaterial.Z(), ddmaterial.density() / pow(Acts::units::_cm, 3)); MaterialProperties materialProperties(layerMaterial, @@ -712,12 +664,10 @@ Acts::DD4hepLayerBuilder::positiveLayers(const GeometryContext& gctx) const return layers; } -void -Acts::DD4hepLayerBuilder::resolveSensitive( - const dd4hep::DetElement& detElement, +void Acts::DD4hepLayerBuilder::resolveSensitive( + const dd4hep::DetElement& detElement, std::vector<std::shared_ptr<const Acts::Surface>>& surfaces, - const std::string& axes) const -{ + const std::string& axes) const { const dd4hep::DetElement::Children& children = detElement.children(); if (!children.empty()) { for (auto& child : children) { @@ -734,10 +684,8 @@ Acts::DD4hepLayerBuilder::resolveSensitive( std::shared_ptr<const Acts::Surface> Acts::DD4hepLayerBuilder::createSensitiveSurface( - const dd4hep::DetElement& detElement, - bool isDisc, - const std::string& axes) const -{ + const dd4hep::DetElement& detElement, bool isDisc, + const std::string& axes) const { // access the possible material std::shared_ptr<const Acts::ISurfaceMaterial> material = nullptr; // access the possible extension of the DetElement @@ -752,22 +700,21 @@ Acts::DD4hepLayerBuilder::createSensitiveSurface( // Get the digitiztion module and provide it to the detector element auto digiModule = detExtension->digitizationModule(); // create the corresponding detector element - Acts::DD4hepDetectorElement* dd4hepDetElement - = new Acts::DD4hepDetectorElement( - detElement, axes, units::_cm, isDisc, material, digiModule); + Acts::DD4hepDetectorElement* dd4hepDetElement = + new Acts::DD4hepDetectorElement(detElement, axes, units::_cm, isDisc, + material, digiModule); // return the surface return dd4hepDetElement->surface().getSharedPtr(); } std::shared_ptr<const Acts::Transform3D> -Acts::DD4hepLayerBuilder::convertTransform(const TGeoMatrix* tGeoTrans) const -{ +Acts::DD4hepLayerBuilder::convertTransform(const TGeoMatrix* tGeoTrans) const { // get the placement and orientation in respect to its mother - const Double_t* rotation = tGeoTrans->GetRotationMatrix(); + const Double_t* rotation = tGeoTrans->GetRotationMatrix(); const Double_t* translation = tGeoTrans->GetTranslation(); - auto transform = std::make_shared<const Transform3D>( - TGeoPrimitivesHelpers::makeTransform( + auto transform = + std::make_shared<const Transform3D>(TGeoPrimitivesHelpers::makeTransform( Acts::Vector3D(rotation[0], rotation[3], rotation[6]), Acts::Vector3D(rotation[1], rotation[4], rotation[7]), Acts::Vector3D(rotation[2], rotation[5], rotation[8]), diff --git a/Plugins/Digitization/include/Acts/Plugins/Digitization/CartesianSegmentation.hpp b/Plugins/Digitization/include/Acts/Plugins/Digitization/CartesianSegmentation.hpp index f10248fc2d632864ed502713651f2e0ed6f56518..277dd27b9f5e60ddd96a264b65259c426c45d864 100644 --- a/Plugins/Digitization/include/Acts/Plugins/Digitization/CartesianSegmentation.hpp +++ b/Plugins/Digitization/include/Acts/Plugins/Digitization/CartesianSegmentation.hpp @@ -37,9 +37,8 @@ namespace Acts { /// they need to be corrected by the lorentzShift /// for the parameter surface in the center of the surface) /// -class CartesianSegmentation : public Segmentation -{ -public: +class CartesianSegmentation : public Segmentation { + public: /// Constructor for all same-size pixels or strips /// (in cas numCellsY is set to 1) /// @@ -47,8 +46,7 @@ public: /// @param numCellsX is the number of cells in X /// @param numCellsY is the number of cells in Y CartesianSegmentation(const std::shared_ptr<const PlanarBounds>& mBounds, - size_t numCellsX, - size_t numCellsY = 1); + size_t numCellsX, size_t numCellsY = 1); /// @todo contructor from BinUtilities for more complex readouts /// @@ -59,7 +57,7 @@ public: /// /// @note if both RectangleBounds and BinUtility are provided, no check is /// done for consitency - CartesianSegmentation(std::shared_ptr<const BinUtility> bUtility, + CartesianSegmentation(std::shared_ptr<const BinUtility> bUtility, std::shared_ptr<const PlanarBounds> mBounds = nullptr); /// Virtual Destructor @@ -69,99 +67,80 @@ public: /// /// Create the segmentation surfaces in X and Y for rectangular shapes /// These are needed for a full three dimensional module - void - createSegmentationSurfaces(SurfacePtrVector& boundarySurfaces, - SurfacePtrVector& segmentationSurfacesX, - SurfacePtrVector& segmentationSurfacesY, - double halfThickness, - int readoutDirection = 1., - double lorentzAngle = 0.) const final; + void createSegmentationSurfaces(SurfacePtrVector& boundarySurfaces, + SurfacePtrVector& segmentationSurfacesX, + SurfacePtrVector& segmentationSurfacesY, + double halfThickness, + int readoutDirection = 1., + double lorentzAngle = 0.) const final; /// @copydoc Segmentation::cell - DigitizationCell - cell(const Vector3D& position) const final; + DigitizationCell cell(const Vector3D& position) const final; /// @copydoc Segmentation::cell - DigitizationCell - cell(const Vector2D& position) const final; + DigitizationCell cell(const Vector2D& position) const final; /// @copydoc Segmentation::cellPosition - Vector2D - cellPosition(const DigitizationCell& dCell) const final; + Vector2D cellPosition(const DigitizationCell& dCell) const final; /// Fill the associated digitsation cell from this start and end position /// correct for lorentz effect if needed /// /// @copydoc Segmentation::digitizationStep - DigitizationStep - digitizationStep(const Vector3D& startStep, - const Vector3D& endStep, - double halfThickness, - int readoutDirection = 1, - double lorentzAngle = 0.) const final; + DigitizationStep digitizationStep(const Vector3D& startStep, + const Vector3D& endStep, + double halfThickness, + int readoutDirection = 1, + double lorentzAngle = 0.) const final; /// return the surface bounds by reference /// specialization for Rectangle Bounds - const PlanarBounds& - moduleBounds() const final; + const PlanarBounds& moduleBounds() const final; /// return the bin utility that defines the /// readout segmentation - const BinUtility& - binUtility() const final; + const BinUtility& binUtility() const final; /// return the pitch sizes as a pair - std::pair<double, double> - pitch() const; + std::pair<double, double> pitch() const; -private: + private: template <class T> - DigitizationCell - cellT(const T& position) const; + DigitizationCell cellT(const T& position) const; std::shared_ptr<const PlanarBounds> m_activeBounds; /// active area size - std::shared_ptr<const BinUtility> m_binUtility; /// bin Utility + std::shared_ptr<const BinUtility> m_binUtility; /// bin Utility }; -inline const PlanarBounds& -CartesianSegmentation::moduleBounds() const -{ +inline const PlanarBounds& CartesianSegmentation::moduleBounds() const { return (*(m_activeBounds.get())); } -inline const BinUtility& -CartesianSegmentation::binUtility() const -{ +inline const BinUtility& CartesianSegmentation::binUtility() const { return (*(m_binUtility.get())); } template <class T> -DigitizationCell -CartesianSegmentation::cellT(const T& position) const -{ +DigitizationCell CartesianSegmentation::cellT(const T& position) const { return DigitizationCell(m_binUtility->bin(position, 0), m_binUtility->bin(position, 1)); } -inline DigitizationCell -CartesianSegmentation::cell(const Vector3D& position) const -{ +inline DigitizationCell CartesianSegmentation::cell( + const Vector3D& position) const { return cellT<Vector3D>(position); } -inline DigitizationCell -CartesianSegmentation::cell(const Vector2D& position) const -{ +inline DigitizationCell CartesianSegmentation::cell( + const Vector2D& position) const { return cellT<Vector2D>(position); } -inline std::pair<double, double> -CartesianSegmentation::pitch() const -{ - auto boundingBox = m_activeBounds->boundingBox(); - auto values = boundingBox.valueStore(); - double pitchX = 2. * values[0] / m_binUtility->bins(0); - double pitchY = 2. * values[1] / m_binUtility->bins(1); +inline std::pair<double, double> CartesianSegmentation::pitch() const { + auto boundingBox = m_activeBounds->boundingBox(); + auto values = boundingBox.valueStore(); + double pitchX = 2. * values[0] / m_binUtility->bins(0); + double pitchY = 2. * values[1] / m_binUtility->bins(1); return std::pair<double, double>(pitchX, pitchY); } diff --git a/Plugins/Digitization/include/Acts/Plugins/Digitization/Clusterization.hpp b/Plugins/Digitization/include/Acts/Plugins/Digitization/Clusterization.hpp index f42a1da588def721a88b668989a5e0bd21fc1a99..66d8d7bc5fd81ace90675d97cee75d06817948c2 100644 --- a/Plugins/Digitization/include/Acts/Plugins/Digitization/Clusterization.hpp +++ b/Plugins/Digitization/include/Acts/Plugins/Digitization/Clusterization.hpp @@ -30,11 +30,9 @@ namespace Acts { /// @return vector (the different clusters) of vector of digitization cells (the /// cells which belong to each cluster) template <typename cell_t> -std::vector<std::vector<cell_t>> -createClusters(std::unordered_map<size_t, std::pair<cell_t, bool>>& cellMap, - size_t nBins0, - bool commonCorner = true, - double energyCut = 0.); +std::vector<std::vector<cell_t>> createClusters( + std::unordered_map<size_t, std::pair<cell_t, bool>>& cellMap, size_t nBins0, + bool commonCorner = true, double energyCut = 0.); /// @brief fillCluster /// This function is a helper function internally used by Acts::createClusters. @@ -56,13 +54,10 @@ createClusters(std::unordered_map<size_t, std::pair<cell_t, bool>>& cellMap, /// corner should be merged into one cluster /// @param [in] energyCut possible energy cut to be applied template <typename cell_t> -void -fillCluster(std::vector<std::vector<cell_t>>& mergedCells, - std::unordered_map<size_t, std::pair<cell_t, bool>>& cellMap, - size_t index, - size_t nBins0, - bool commonCorner = true, - double energyCut = 0.); -} +void fillCluster(std::vector<std::vector<cell_t>>& mergedCells, + std::unordered_map<size_t, std::pair<cell_t, bool>>& cellMap, + size_t index, size_t nBins0, bool commonCorner = true, + double energyCut = 0.); +} // namespace Acts #include "Acts/Plugins/Digitization/detail/Clusterization.ipp" diff --git a/Plugins/Digitization/include/Acts/Plugins/Digitization/DigitizationCell.hpp b/Plugins/Digitization/include/Acts/Plugins/Digitization/DigitizationCell.hpp index 382d737c0a19c8c21d648fd3d82d083ceac4e5f9..bc88caf534d153c04a652a840b68c2b8e2b251bc 100644 --- a/Plugins/Digitization/include/Acts/Plugins/Digitization/DigitizationCell.hpp +++ b/Plugins/Digitization/include/Acts/Plugins/Digitization/DigitizationCell.hpp @@ -14,20 +14,16 @@ namespace Acts { /// @brief pair of ints for definition of a cell -struct DigitizationCell -{ - +struct DigitizationCell { virtual ~DigitizationCell() = default; // identification and data size_t channel0 = 0; size_t channel1 = 1; - float data = 0.; + float data = 0.; // connstruct them DigitizationCell(size_t ch0, size_t ch1, float d = 0.) - : channel0(ch0), channel1(ch1), data(d) - { - } + : channel0(ch0), channel1(ch1), data(d) {} // copy them DigitizationCell(const DigitizationCell& dc) = default; @@ -38,9 +34,7 @@ struct DigitizationCell /// calculate the energy deposit differently. Furthermore this allows to apply /// an energy cut, because the energy deposit can also be stored for digital /// readout. - virtual void - addCell(const DigitizationCell& dc, bool analogueReadout) - { + virtual void addCell(const DigitizationCell& dc, bool analogueReadout) { if (analogueReadout) { data += dc.data; } @@ -51,35 +45,28 @@ struct DigitizationCell /// calculate the energy deposit differently. Furthermore this allows to apply /// an energy cut, because the energy deposit can also be stored for digital /// readout. - virtual double - depositedEnergy() const - { - return data; - } + virtual double depositedEnergy() const { return data; } }; /// @brief DigitizationStep for further handling -struct DigitizationStep -{ +struct DigitizationStep { double stepLength{0.}; /// this is the path length within the cell double driftLength{0.}; /// this is the path length of the setp center to the /// readout surface DigitizationCell stepCell; /// this is the cell identifier of the segment - Vector3D stepEntry; /// this is the Entry point into the segment - Vector3D stepExit; /// this is the Exit point from the segment + Vector3D stepEntry; /// this is the Entry point into the segment + Vector3D stepExit; /// this is the Exit point from the segment Vector2D stepReadoutProjected; /// this is the projected position at the /// readout surface Vector2D stepCellCenter; /// this is the cell position /// Standard constructor DigitizationStep() - : stepCell(0, 0) - , stepEntry(0., 0., 0.) - , stepExit(0., 0., 0.) - , stepReadoutProjected(0., 0.) - , stepCellCenter(0., 0.) - { - } + : stepCell(0, 0), + stepEntry(0., 0., 0.), + stepExit(0., 0., 0.), + stepReadoutProjected(0., 0.), + stepCellCenter(0., 0.) {} /// Constructor with arguments /// @@ -90,21 +77,16 @@ struct DigitizationStep /// @param exitP is the exit position from the cell /// @param projectedPosition is the position on the readout surface /// @param cellPosition is the nominal position of the cell - DigitizationStep(double sl, - double dl, - const DigitizationCell& dc, - const Vector3D& entryP, - const Vector3D& exitP, - const Vector2D& projectedPosition, - const Vector2D& cellPosition) - : stepLength(sl) - , driftLength(dl) - , stepCell(dc) - , stepEntry(entryP) - , stepExit(exitP) - , stepReadoutProjected(projectedPosition) - , stepCellCenter(cellPosition) - { - } + DigitizationStep(double sl, double dl, const DigitizationCell& dc, + const Vector3D& entryP, const Vector3D& exitP, + const Vector2D& projectedPosition, + const Vector2D& cellPosition) + : stepLength(sl), + driftLength(dl), + stepCell(dc), + stepEntry(entryP), + stepExit(exitP), + stepReadoutProjected(projectedPosition), + stepCellCenter(cellPosition) {} }; -} +} // namespace Acts diff --git a/Plugins/Digitization/include/Acts/Plugins/Digitization/DigitizationModule.hpp b/Plugins/Digitization/include/Acts/Plugins/Digitization/DigitizationModule.hpp index 4ad0cea9c5e9eaec00de081e81a830d4360dd766..bbb08cdc9428c01d4bc964cf940e8e62c02b0282 100644 --- a/Plugins/Digitization/include/Acts/Plugins/Digitization/DigitizationModule.hpp +++ b/Plugins/Digitization/include/Acts/Plugins/Digitization/DigitizationModule.hpp @@ -15,7 +15,7 @@ namespace Acts { class Surface; -using SurfacePtr = std::shared_ptr<const Surface>; +using SurfacePtr = std::shared_ptr<const Surface>; using SurfacePtrVector = std::vector<SurfacePtr>; /// @class DigitizationModule @@ -43,9 +43,8 @@ using SurfacePtrVector = std::vector<SurfacePtr>; /// The lorenzShift is the correction from the readout surface to the parameter /// surface /// -class DigitizationModule -{ -public: +class DigitizationModule { + public: /// Constructor from a Segmentation descriptor /// /// @param gctx The current geometry context object, e.g. alignment @@ -54,11 +53,9 @@ public: /// @param readoutDirection is the readout drift direction /// @param lorentzAngle is the lorentz drift angle DigitizationModule(std::shared_ptr<const Segmentation> moduleSegmentation, - double halfThickness, - int readoutDirection, - double lorentzAngle, - double energyThreshold = 0., - bool analogue = false); + double halfThickness, int readoutDirection, + double lorentzAngle, double energyThreshold = 0., + bool analogue = false); /// Virtual Destructor virtual ~DigitizationModule() = default; @@ -71,37 +68,30 @@ public: /// @param exitCids are the exit digitisation cell ids /// /// @return object is a vector of shared surfaces - const SurfacePtrVector - segmentationSurfaces(const DigitizationCell& entryCids, - const DigitizationCell& exitCids) const; + const SurfacePtrVector segmentationSurfaces( + const DigitizationCell& entryCids, + const DigitizationCell& exitCids) const; /// Get the digitization cell from a position - const DigitizationCell - cell(const Vector2D& position) const; + const DigitizationCell cell(const Vector2D& position) const; /// Return the module thickness - double - halfThickness() const; + double halfThickness() const; /// Return the readout direction - int - readoutDirection() const; + int readoutDirection() const; /// Return the lorentz Angle - double - lorentzAngle() const; + double lorentzAngle() const; /// Return the energy threshold per cell of the module - double - energyThreshold() const; + double energyThreshold() const; /// Indicates if the readout of the module is analogue, default is digital - bool - analogue() const; + bool analogue() const; /// return the segmenation - const Segmentation& - segmentation() const; + const Segmentation& segmentation() const; /// Return the test surfaces between these points /// @@ -109,30 +99,27 @@ public: /// @param end is the end position of the step /// /// @return stepSurfaces are the surfaces to test - const SurfacePtrVector - stepSurfaces(const Vector3D& start, const Vector3D& end) const; + const SurfacePtrVector stepSurfaces(const Vector3D& start, + const Vector3D& end) const; /// Fill the associated digitsation cell from this start and end position, /// correct for lorentz effect if needed /// /// @param start is the start position of the step /// @param end is the end position of the step - const DigitizationStep - digitizationStep(const Vector3D& start, const Vector3D& end) const; + const DigitizationStep digitizationStep(const Vector3D& start, + const Vector3D& end) const; /// Return the bounding surfaces inlcuding top and bottom - const SurfacePtrVector& - boundarySurfaces() const; + const SurfacePtrVector& boundarySurfaces() const; /// Return all surfaces in X - excluding the boundaries - const SurfacePtrVector& - segmentationSurfacesX() const; + const SurfacePtrVector& segmentationSurfacesX() const; /// Return all surfaces in Y - excluding the boundaries - const SurfacePtrVector& - segmentationSurfacesY() const; + const SurfacePtrVector& segmentationSurfacesY() const; -private: + private: /// half thickness of the module double m_halfThickness; /// readout is along (+1) / (-1) wrt local z axis @@ -155,65 +142,47 @@ private: SurfacePtrVector m_segmentationSurfacesY; }; -inline double -DigitizationModule::halfThickness() const -{ +inline double DigitizationModule::halfThickness() const { return m_halfThickness; } -inline int -DigitizationModule::readoutDirection() const -{ +inline int DigitizationModule::readoutDirection() const { return m_readoutDirection; } -inline double -DigitizationModule::lorentzAngle() const -{ +inline double DigitizationModule::lorentzAngle() const { return m_lorentzAngle; } -inline double -DigitizationModule::energyThreshold() const -{ +inline double DigitizationModule::energyThreshold() const { return m_energyThreshold; } -inline bool -DigitizationModule::analogue() const -{ +inline bool DigitizationModule::analogue() const { return m_analogue; } -inline const Segmentation& -DigitizationModule::segmentation() const -{ +inline const Segmentation& DigitizationModule::segmentation() const { return (*(m_segmentation.get())); } -inline const SurfacePtrVector& -DigitizationModule::boundarySurfaces() const -{ +inline const SurfacePtrVector& DigitizationModule::boundarySurfaces() const { return m_boundarySurfaces; } -inline const SurfacePtrVector& -DigitizationModule::segmentationSurfacesX() const -{ +inline const SurfacePtrVector& DigitizationModule::segmentationSurfacesX() + const { return m_segmentationSurfacesX; } -inline const SurfacePtrVector& -DigitizationModule::segmentationSurfacesY() const -{ +inline const SurfacePtrVector& DigitizationModule::segmentationSurfacesY() + const { return m_segmentationSurfacesY; } -inline const DigitizationStep -DigitizationModule::digitizationStep(const Vector3D& start, - const Vector3D& end) const -{ - return m_segmentation->digitizationStep( - start, end, m_halfThickness, m_readoutDirection, m_lorentzAngle); -} +inline const DigitizationStep DigitizationModule::digitizationStep( + const Vector3D& start, const Vector3D& end) const { + return m_segmentation->digitizationStep(start, end, m_halfThickness, + m_readoutDirection, m_lorentzAngle); } +} // namespace Acts diff --git a/Plugins/Digitization/include/Acts/Plugins/Digitization/DoubleHitSpacePointBuilder.hpp b/Plugins/Digitization/include/Acts/Plugins/Digitization/DoubleHitSpacePointBuilder.hpp index eca79f27951e020bdb7c72a6718bae7cb812c9b1..58a0aaacbf158ef2948c846e935b7715f98eb1c1 100644 --- a/Plugins/Digitization/include/Acts/Plugins/Digitization/DoubleHitSpacePointBuilder.hpp +++ b/Plugins/Digitization/include/Acts/Plugins/Digitization/DoubleHitSpacePointBuilder.hpp @@ -15,8 +15,7 @@ namespace Acts { /// @brief Structure for easier bookkeeping of clusters. -struct DoubleHitSpacePoint -{ +struct DoubleHitSpacePoint { /// Storage of the hit cluster on a surface const PlanarModuleCluster* clusterFront; /// Storage of the hit cluster on another surface @@ -26,27 +25,15 @@ struct DoubleHitSpacePoint /// @brief Getter of the first element in @p spacePoint /// @return First element in @p spacePoint - double - x() const - { - return spacePoint(0); - } + double x() const { return spacePoint(0); } /// @brief Getter of the second element in @p spacePoint /// @return Second element in @p spacePoint - double - y() const - { - return spacePoint(1); - } + double y() const { return spacePoint(1); } /// @brief Getter of the third element in @p spacePoint /// @return Third element in @p spacePoint - double - z() const - { - return spacePoint(2); - } + double z() const { return spacePoint(2); } }; /// @class TwoHitsSpacePointBuilder @@ -60,12 +47,10 @@ struct DoubleHitSpacePoint /// @note Used abbreviation: "Strip Detector Element" -> SDE /// template <> -class SpacePointBuilder<DoubleHitSpacePoint> -{ -public: +class SpacePointBuilder<DoubleHitSpacePoint> { + public: /// @brief Configuration of the class to steer its behaviour - struct DoubleHitSpacePointConfig - { + struct DoubleHitSpacePointConfig { /// Accepted difference in eta for two clusters double diffTheta2 = 1.; /// Accepted difference in phi for two clusters @@ -95,9 +80,8 @@ public: /// @param clusterPairs storage of the cluster pairs /// @note The structure of @p clustersFront and @p clustersBack is meant to be /// clusters[Independent clusters on a single surface] - void - makeClusterPairs( - const GeometryContext& gctx, + void makeClusterPairs( + const GeometryContext& gctx, const std::vector<const PlanarModuleCluster*>& clustersFront, const std::vector<const PlanarModuleCluster*>& clustersBack, std::vector<std::pair<const PlanarModuleCluster*, @@ -110,21 +94,19 @@ public: /// @param clusterPairs pairs of clusters that are space point candidates /// @param spacePoints storage of the results /// @note If no configuration is set, the default values will be used - void - calculateSpacePoints( + void calculateSpacePoints( const GeometryContext& gctx, const std::vector<std::pair<const PlanarModuleCluster*, const PlanarModuleCluster*>>& clusterPairs, std::vector<DoubleHitSpacePoint>& spacePoints) const; -private: + private: /// Config DoubleHitSpacePointConfig m_cfg; /// @brief Storage container for variables related to the calculation of space /// points - struct SpacePointParameters - { + struct SpacePointParameters { /// Vector pointing from bottom to top end of first SDE Vector3D q; /// Vector pointing from bottom to top end of second SDE @@ -158,31 +140,28 @@ private: /// @param cluster object related to the cluster that holds the necessary /// information /// @return vector of the local coordinates of the cluster on the surface - Vector2D - localCoords(const PlanarModuleCluster& cluster) const; + Vector2D localCoords(const PlanarModuleCluster& cluster) const; /// @brief Getter method for the global coordinates of a cluster /// @param cluster object related to the cluster that holds the necessary /// information /// @return vector of the global coordinates of the cluster - Vector3D - globalCoords(const GeometryContext& gctx, - const PlanarModuleCluster& cluster) const; + Vector3D globalCoords(const GeometryContext& gctx, + const PlanarModuleCluster& cluster) const; /// @brief Calculates (Delta theta)^2 + (Delta phi)^2 between two clusters /// @param pos1 position of the first cluster /// @param pos2 position the second cluster /// @return the squared sum within configuration parameters, otherwise -1 - double - differenceOfClustersChecked(const Vector3D& pos1, const Vector3D& pos2) const; + double differenceOfClustersChecked(const Vector3D& pos1, + const Vector3D& pos2) const; /// @brief Calculates the top and bottom ends of a SDE /// that corresponds to a given hit /// @param cluster object that stores the information about the hit /// @return vectors to the top and bottom end of the SDE - std::pair<Vector3D, Vector3D> - endsOfStrip(const GeometryContext& gctx, - const PlanarModuleCluster& cluster) const; + std::pair<Vector3D, Vector3D> endsOfStrip( + const GeometryContext& gctx, const PlanarModuleCluster& cluster) const; /// @brief Calculates a space point whithout using the vertex /// @note This is mostly to resolve space points from cosmic data @@ -194,11 +173,8 @@ private: /// 1. if it failed /// @note The meaning of the parameter is explained in more detail in the /// function body - double - calcPerpProj(const Vector3D& a, - const Vector3D& c, - const Vector3D& q, - const Vector3D& r) const; + double calcPerpProj(const Vector3D& a, const Vector3D& c, const Vector3D& q, + const Vector3D& r) const; /// @brief This function tests if a space point can be estimated by a more /// tolerant treatment of construction. In fact, this function indirectly @@ -206,8 +182,7 @@ private: /// @param spaPoPa container that stores geometric parameters and rules of the /// space point formation /// @return indicator if the test was successful - bool - recoverSpacePoint(SpacePointParameters& spaPoPa) const; + bool recoverSpacePoint(SpacePointParameters& spaPoPa) const; }; } // namespace Acts diff --git a/Plugins/Digitization/include/Acts/Plugins/Digitization/PlanarModuleCluster.hpp b/Plugins/Digitization/include/Acts/Plugins/Digitization/PlanarModuleCluster.hpp index c002c906fb2563c0b6bcebec603cf508beac8cc5..ea74558089e1fc40b104f527a4db85988a4b367c 100644 --- a/Plugins/Digitization/include/Acts/Plugins/Digitization/PlanarModuleCluster.hpp +++ b/Plugins/Digitization/include/Acts/Plugins/Digitization/PlanarModuleCluster.hpp @@ -26,9 +26,9 @@ namespace Acts { template <ParID_t... params> using Measurement_t = Measurement<Identifier, params...>; -class PlanarModuleCluster : public Measurement_t<ParDef::eLOC_0, ParDef::eLOC_1> -{ -public: +class PlanarModuleCluster + : public Measurement_t<ParDef::eLOC_0, ParDef::eLOC_1> { + public: /// Constructor from DigitizationCells /// /// @param [in] mSurface is the module surface @@ -38,48 +38,37 @@ public: /// @param [in] loc1 is the local position in the second coordinate /// @param [in] dCells is the vector of digitization cells PlanarModuleCluster(std::shared_ptr<const Surface> mSurface, - const Identifier& cIdentifier, - ActsSymMatrixD<2> cov, - double loc0, - double loc1, - std::vector<DigitizationCell> dCells, - const DigitizationModule* dModule = nullptr) - : Measurement_t<ParDef::eLOC_0, ParDef::eLOC_1>(std::move(mSurface), - cIdentifier, - std::move(cov), - loc0, - loc1) - , m_digitizationCells(std::move(dCells)) - , m_digitizationModule(dModule) - { - } + const Identifier& cIdentifier, ActsSymMatrixD<2> cov, + double loc0, double loc1, + std::vector<DigitizationCell> dCells, + const DigitizationModule* dModule = nullptr) + : Measurement_t<ParDef::eLOC_0, ParDef::eLOC_1>( + std::move(mSurface), cIdentifier, std::move(cov), loc0, loc1), + m_digitizationCells(std::move(dCells)), + m_digitizationModule(dModule) {} /// access to the digitization cells /// /// @return the vector to the digitization cells - const std::vector<DigitizationCell>& - digitizationCells() const; + const std::vector<DigitizationCell>& digitizationCells() const; /// access to the digitization module /// /// @return the pointer to the digitization module - const DigitizationModule* - digitizationModule() const; + const DigitizationModule* digitizationModule() const; -private: + private: std::vector<DigitizationCell> m_digitizationCells; /// the digitization cells const DigitizationModule* m_digitizationModule; /// the digitization module }; inline const std::vector<DigitizationCell>& -PlanarModuleCluster::digitizationCells() const -{ +PlanarModuleCluster::digitizationCells() const { return m_digitizationCells; } -inline const DigitizationModule* -PlanarModuleCluster::digitizationModule() const -{ +inline const DigitizationModule* PlanarModuleCluster::digitizationModule() + const { return m_digitizationModule; } -} +} // namespace Acts diff --git a/Plugins/Digitization/include/Acts/Plugins/Digitization/PlanarModuleStepper.hpp b/Plugins/Digitization/include/Acts/Plugins/Digitization/PlanarModuleStepper.hpp index fa0a0611b09ffe2788cebb37a2da36277edf8465..ed2373c29830d6569f1c587c63f73f8c7f47d030 100644 --- a/Plugins/Digitization/include/Acts/Plugins/Digitization/PlanarModuleStepper.hpp +++ b/Plugins/Digitization/include/Acts/Plugins/Digitization/PlanarModuleStepper.hpp @@ -24,15 +24,14 @@ class DigitizationModule; /// this is a planar module stepper that calculates the step length /// in given segmentations and retrunes digitisation steps -class PlanarModuleStepper -{ -public: +class PlanarModuleStepper { + public: /// Constructor /// /// @param pmsConfig is the configuration /// @param mlogger is the logging istance - PlanarModuleStepper(std::unique_ptr<const Logger> mlogger - = getDefaultLogger("PlanarModuleStepper", Logging::INFO)); + PlanarModuleStepper(std::unique_ptr<const Logger> mlogger = getDefaultLogger( + "PlanarModuleStepper", Logging::INFO)); /// Destructor ~PlanarModuleStepper() = default; @@ -45,11 +44,10 @@ public: /// @param endPoint is the end postion of the stepping /// /// @return is the vector of digitization steps - std::vector<DigitizationStep> - cellSteps(const GeometryContext& gctx, - const DigitizationModule& dmodule, - const Vector3D& startPoint, - const Vector3D& endPoint) const; + std::vector<DigitizationStep> cellSteps(const GeometryContext& gctx, + const DigitizationModule& dmodule, + const Vector3D& startPoint, + const Vector3D& endPoint) const; /// Calculate the steps caused by this track - fast simulation interface /// @@ -59,31 +57,24 @@ public: /// @param trackDirection is the track direction at the instersection /// /// @return is the vector of digitization steps - std::vector<DigitizationStep> - cellSteps(const GeometryContext& gctx, - const DigitizationModule& dmodule, - const Vector2D& moduleIntersection, - const Vector3D& trackDirection) const; + std::vector<DigitizationStep> cellSteps(const GeometryContext& gctx, + const DigitizationModule& dmodule, + const Vector2D& moduleIntersection, + const Vector3D& trackDirection) const; /// Set logging instance /// /// @param logger is the logging instance to be set - void - setLogger(std::unique_ptr<const Logger> logger) - { + void setLogger(std::unique_ptr<const Logger> logger) { m_logger = std::move(logger); } -private: + private: /// Private access method to the logging instance - const Logger& - logger() const - { - return *m_logger; - } + const Logger& logger() const { return *m_logger; } /// logging instance std::unique_ptr<const Logger> m_logger; }; -} // namespace +} // namespace Acts diff --git a/Plugins/Digitization/include/Acts/Plugins/Digitization/Segmentation.hpp b/Plugins/Digitization/include/Acts/Plugins/Digitization/Segmentation.hpp index f847f467493fdac16896134589d51ca3bc992c6d..e6fceb6b8b1da519c091fb20ace28c70e3c2d8fc 100644 --- a/Plugins/Digitization/include/Acts/Plugins/Digitization/Segmentation.hpp +++ b/Plugins/Digitization/include/Acts/Plugins/Digitization/Segmentation.hpp @@ -17,7 +17,7 @@ namespace Acts { class SurfaceBounds; class Surface; class BinUtility; -using SurfacePtr = std::shared_ptr<const Surface>; +using SurfacePtr = std::shared_ptr<const Surface>; using SurfacePtrVector = std::vector<SurfacePtr>; /// @brief Segmentation Base class @@ -33,9 +33,8 @@ using SurfacePtrVector = std::vector<SurfacePtr>; /// module, /// but hosts the binning information. /// -class Segmentation -{ -public: +class Segmentation { + public: /// Virtual Destructor virtual ~Segmentation() = default; @@ -51,13 +50,11 @@ public: /// where the readout is given : -1, 0, 1 possible /// @param lorentzAngle is the lorentz angle measured from the local z /// towards x axis - virtual void - createSegmentationSurfaces(SurfacePtrVector& boundarySurfaces, - SurfacePtrVector& segmentationSurfacesX, - SurfacePtrVector& segmentationSurfacesY, - double halfThickness, - int readoutDirection, - double lorentzAngle) const = 0; + virtual void createSegmentationSurfaces( + SurfacePtrVector& boundarySurfaces, + SurfacePtrVector& segmentationSurfacesX, + SurfacePtrVector& segmentationSurfacesY, double halfThickness, + int readoutDirection, double lorentzAngle) const = 0; /// Get the digitization cell fropm a 3D position /// - ignores the shift, i.e. assumenes in to be in cell frame @@ -65,8 +62,7 @@ public: /// @param position is the position for which the cell is requested /// /// @return is a cell with cell ids - virtual DigitizationCell - cell(const Vector3D& position) const = 0; + virtual DigitizationCell cell(const Vector3D& position) const = 0; /// Get the digitization cell fropm a 2D position /// - ignores the shift, i.e. assumenes in to be in cell frame @@ -74,16 +70,14 @@ public: /// @param position is the position for which the cell is requested /// /// @return is a cell with cell ids - virtual DigitizationCell - cell(const Vector2D& position) const = 0; + virtual DigitizationCell cell(const Vector2D& position) const = 0; /// Calculate the cell Position from the Id /// /// @param cId is the digitization cell /// /// @return the center position of the associated cell - virtual Vector2D - cellPosition(const DigitizationCell& cId) const = 0; + virtual Vector2D cellPosition(const DigitizationCell& cId) const = 0; /// Fill the associated digitsation cell from the start and end position in 3D /// correct for lorentz effect if needed @@ -95,19 +89,16 @@ public: /// @param lorentzAngle is the lorentz angle measured from local z towards x /// /// @return is a fully calculated digitzation step - virtual DigitizationStep - digitizationStep(const Vector3D& start, - const Vector3D& end, - double halfThickness, - int readoutDirection, - double lorentzAngle) const = 0; + virtual DigitizationStep digitizationStep(const Vector3D& start, + const Vector3D& end, + double halfThickness, + int readoutDirection, + double lorentzAngle) const = 0; /// return the surface bounds by reference - virtual const SurfaceBounds& - moduleBounds() const = 0; + virtual const SurfaceBounds& moduleBounds() const = 0; /// return the bin utility that defines the readout - virtual const BinUtility& - binUtility() const = 0; + virtual const BinUtility& binUtility() const = 0; }; } // namespace Acts diff --git a/Plugins/Digitization/include/Acts/Plugins/Digitization/SingleHitSpacePointBuilder.hpp b/Plugins/Digitization/include/Acts/Plugins/Digitization/SingleHitSpacePointBuilder.hpp index 7f1108bc5c8d261e4133aae0f4eedc863c9ce39e..65cb20ea2471baf8850779466f182b10c021748a 100644 --- a/Plugins/Digitization/include/Acts/Plugins/Digitization/SingleHitSpacePointBuilder.hpp +++ b/Plugins/Digitization/include/Acts/Plugins/Digitization/SingleHitSpacePointBuilder.hpp @@ -15,8 +15,7 @@ namespace Acts { /// @brief Structure for easier bookkeeping of clusters. -struct SingleHitSpacePoint -{ +struct SingleHitSpacePoint { /// Storage of the cluster on a surface const PlanarModuleCluster* clusterModule; /// Storage of a space point. @@ -24,27 +23,15 @@ struct SingleHitSpacePoint /// @brief Getter of the first element in @p spacePoint /// @return First element in @p spacePoint - double - x() const - { - return spacePoint(0); - } + double x() const { return spacePoint(0); } /// @brief Getter of the second element in @p spacePoint /// @return Second element in @p spacePoint - double - y() const - { - return spacePoint(1); - } + double y() const { return spacePoint(1); } /// @brief Getter of the third element in @p spacePoint /// @return Third element in @p spacePoint - double - z() const - { - return spacePoint(2); - } + double z() const { return spacePoint(2); } }; /// @class OneHitSpacePointBuilder @@ -55,9 +42,8 @@ struct SingleHitSpacePoint /// corresponding space point. /// template <> -class SpacePointBuilder<SingleHitSpacePoint> -{ -public: +class SpacePointBuilder<SingleHitSpacePoint> { + public: /// Default constructor SpacePointBuilder<SingleHitSpacePoint>() = default; @@ -67,21 +53,19 @@ public: /// @param gctx The current geometry context object, e.g. alignment /// @param cluster vector of clusters /// @param spacePointStorage storage of the results - void - calculateSpacePoints( - const GeometryContext& gctx, + void calculateSpacePoints( + const GeometryContext& gctx, const std::vector<const PlanarModuleCluster*>& clusters, - std::vector<SingleHitSpacePoint>& spacePointStorage) const; + std::vector<SingleHitSpacePoint>& spacePointStorage) const; -protected: + protected: /// @brief Getter method for the local coordinates of a cluster /// on its corresponding surface /// /// @param cluster object related to the cluster that holds the necessary /// information /// @return vector of the local coordinates of the cluster on the surface - Vector2D - localCoords(const PlanarModuleCluster& cluster) const; + Vector2D localCoords(const PlanarModuleCluster& cluster) const; /// @brief Getter method for the global coordinates of a cluster /// @@ -89,9 +73,8 @@ protected: /// @param cluster object related to the cluster that holds the necessary /// information /// @return vector of the global coordinates of the cluster - Vector3D - globalCoords(const GeometryContext& gctx, - const PlanarModuleCluster& cluster) const; + Vector3D globalCoords(const GeometryContext& gctx, + const PlanarModuleCluster& cluster) const; }; } // namespace Acts diff --git a/Plugins/Digitization/include/Acts/Plugins/Digitization/SpacePointBuilder.hpp b/Plugins/Digitization/include/Acts/Plugins/Digitization/SpacePointBuilder.hpp index 6f7b51ff30c65d04e40a0f1f1606d94d2b573ee2..6da3df73374a06c14f5fffeadc3b5e878fde4c13 100644 --- a/Plugins/Digitization/include/Acts/Plugins/Digitization/SpacePointBuilder.hpp +++ b/Plugins/Digitization/include/Acts/Plugins/Digitization/SpacePointBuilder.hpp @@ -29,7 +29,5 @@ namespace Acts { /// corresponding space point. /// template <class S> -class SpacePointBuilder -{ -}; +class SpacePointBuilder {}; } // namespace Acts diff --git a/Plugins/Digitization/include/Acts/Plugins/Digitization/detail/Clusterization.ipp b/Plugins/Digitization/include/Acts/Plugins/Digitization/detail/Clusterization.ipp index ef8777f7be820f72e19e6c6a698c7680fa6c2d27..bbbfe776324dffd01451aaeda82b9f6ee5dd5ecb 100644 --- a/Plugins/Digitization/include/Acts/Plugins/Digitization/detail/Clusterization.ipp +++ b/Plugins/Digitization/include/Acts/Plugins/Digitization/detail/Clusterization.ipp @@ -12,20 +12,16 @@ #include <vector> template <typename cell_t> -std::vector<std::vector<cell_t>> -Acts::createClusters( - std::unordered_map<size_t, std::pair<cell_t, bool>>& cellMap, - size_t nBins0, - bool commonCorner, - double energyCut) -{ +std::vector<std::vector<cell_t>> Acts::createClusters( + std::unordered_map<size_t, std::pair<cell_t, bool>>& cellMap, size_t nBins0, + bool commonCorner, double energyCut) { // the output std::vector<std::vector<cell_t>> mergedCells; // now go through cells and label for (auto& cell : cellMap) { // check if the cell was already used - if (!(cell.second.second) - && (cell.second.first.depositedEnergy() >= energyCut)) { + if (!(cell.second.second) && + (cell.second.first.depositedEnergy() >= energyCut)) { // create new cluster mergedCells.push_back(std::vector<cell_t>()); // add current cell to current cluster @@ -33,8 +29,8 @@ Acts::createClusters( // set cell to be used already cell.second.second = true; // fill all cells belonging to that cluster - fillCluster( - mergedCells, cellMap, cell.first, nBins0, commonCorner, energyCut); + fillCluster(mergedCells, cellMap, cell.first, nBins0, commonCorner, + energyCut); } } // return the grouped together cells @@ -42,20 +38,16 @@ Acts::createClusters( } template <typename cell_t> -void -Acts::fillCluster(std::vector<std::vector<cell_t>>& mergedCells, - std::unordered_map<size_t, std::pair<cell_t, bool>>& cellMap, - size_t index, - size_t nBins0, - bool commonCorner, - double energyCut) -{ +void Acts::fillCluster( + std::vector<std::vector<cell_t>>& mergedCells, + std::unordered_map<size_t, std::pair<cell_t, bool>>& cellMap, size_t index, + size_t nBins0, bool commonCorner, double energyCut) { // go recursively through all neighbours of this cell, if present // calculate neighbour indices first - constexpr int iMin = -1; - int jMin = -nBins0; - constexpr int iMax = 1; - int jMax = nBins0; + constexpr int iMin = -1; + int jMin = -nBins0; + constexpr int iMax = 1; + int jMax = nBins0; std::vector<int> neighbourIndices; // the neighbour indices - filled depending on merging case if ((index % nBins0) == 0) { @@ -74,14 +66,8 @@ Acts::fillCluster(std::vector<std::vector<cell_t>>& mergedCells, } } else { if (commonCorner) { - neighbourIndices = {jMin + iMin, - jMin, - jMin + iMax, - iMin, - iMax, - jMax + iMin, - jMax, - jMax + iMax}; + neighbourIndices = {jMin + iMin, jMin, jMin + iMax, iMin, + iMax, jMax + iMin, jMax, jMax + iMax}; } else { neighbourIndices = {jMin, iMin, iMax, jMax}; } @@ -95,19 +81,19 @@ Acts::fillCluster(std::vector<std::vector<cell_t>>& mergedCells, auto search = cellMap.find(neighbourIndex); if ((search != cellMap.end())) { // get the corresponding index and call function again - auto newIndex = search->first; + auto newIndex = search->first; auto currentCell = search->second.first; // if cell was not already added to cluster & deposited energy is higher // than the energy threshold, add it to the cluster - if (!search->second.second - && currentCell.depositedEnergy() >= energyCut) { + if (!search->second.second && + currentCell.depositedEnergy() >= energyCut) { // add current cell to current cluster mergedCells.back().push_back(currentCell); // set cell to be used already search->second.second = true; // add all neighbours to cluster - fillCluster( - mergedCells, cellMap, newIndex, nBins0, commonCorner, energyCut); + fillCluster(mergedCells, cellMap, newIndex, nBins0, commonCorner, + energyCut); } // check if was used already } // check if neighbour is there } // go through neighbour indics diff --git a/Plugins/Digitization/src/CartesianSegmentation.cpp b/Plugins/Digitization/src/CartesianSegmentation.cpp index e2ebb1b30376ca0abcf7ba17395b1e3ff1464f79..41bc1b5befc9441b2b263e682ff3fbe121d78d08 100644 --- a/Plugins/Digitization/src/CartesianSegmentation.cpp +++ b/Plugins/Digitization/src/CartesianSegmentation.cpp @@ -18,30 +18,22 @@ #include "Acts/Utilities/Helpers.hpp" Acts::CartesianSegmentation::CartesianSegmentation( - const std::shared_ptr<const PlanarBounds>& mBounds, - size_t numCellsX, - size_t numCellsY) - : m_activeBounds(mBounds), m_binUtility(nullptr) -{ - auto mutableBinUtility - = std::make_shared<BinUtility>(numCellsX, - -mBounds->boundingBox().halflengthX(), - mBounds->boundingBox().halflengthX(), - Acts::open, - Acts::binX); - (*mutableBinUtility) += BinUtility(numCellsY, - -mBounds->boundingBox().halflengthY(), - mBounds->boundingBox().halflengthY(), - Acts::open, - Acts::binY); + const std::shared_ptr<const PlanarBounds>& mBounds, size_t numCellsX, + size_t numCellsY) + : m_activeBounds(mBounds), m_binUtility(nullptr) { + auto mutableBinUtility = std::make_shared<BinUtility>( + numCellsX, -mBounds->boundingBox().halflengthX(), + mBounds->boundingBox().halflengthX(), Acts::open, Acts::binX); + (*mutableBinUtility) += + BinUtility(numCellsY, -mBounds->boundingBox().halflengthY(), + mBounds->boundingBox().halflengthY(), Acts::open, Acts::binY); m_binUtility = std::const_pointer_cast<const BinUtility>(mutableBinUtility); } Acts::CartesianSegmentation::CartesianSegmentation( - std::shared_ptr<const BinUtility> bUtility, + std::shared_ptr<const BinUtility> bUtility, std::shared_ptr<const PlanarBounds> mBounds) - : m_activeBounds(std::move(mBounds)), m_binUtility(std::move(bUtility)) -{ + : m_activeBounds(std::move(mBounds)), m_binUtility(std::move(bUtility)) { if (!m_activeBounds) { m_activeBounds = std::make_shared<const RectangleBounds>( m_binUtility->max(0), m_binUtility->max(1)); @@ -50,17 +42,12 @@ Acts::CartesianSegmentation::CartesianSegmentation( Acts::CartesianSegmentation::~CartesianSegmentation() = default; -void -Acts::CartesianSegmentation::createSegmentationSurfaces( - SurfacePtrVector& boundarySurfaces, - SurfacePtrVector& segmentationSurfacesX, - SurfacePtrVector& segmentationSurfacesY, - double halfThickness, - int readoutDirection, - double lorentzAngle) const -{ +void Acts::CartesianSegmentation::createSegmentationSurfaces( + SurfacePtrVector& boundarySurfaces, SurfacePtrVector& segmentationSurfacesX, + SurfacePtrVector& segmentationSurfacesY, double halfThickness, + int readoutDirection, double lorentzAngle) const { // may be needed throughout - double lorentzAngleTan = tan(lorentzAngle); + double lorentzAngleTan = tan(lorentzAngle); double lorentzPlaneShiftX = halfThickness * lorentzAngleTan; // (A) --- top/bottom surfaces @@ -74,26 +61,26 @@ Acts::CartesianSegmentation::createSegmentationSurfaces( new RectangleBounds(m_activeBounds->boundingBox().halflengthX(), m_activeBounds->boundingBox().halflengthY())); // - they are separated by half a thickness in z - auto mutableReadoutPlaneTransform - = std::make_shared<Transform3D>(Transform3D::Identity()); - auto mutableCounterPlaneTransform - = std::make_shared<Transform3D>(Transform3D::Identity()); + auto mutableReadoutPlaneTransform = + std::make_shared<Transform3D>(Transform3D::Identity()); + auto mutableCounterPlaneTransform = + std::make_shared<Transform3D>(Transform3D::Identity()); // readout and counter readout bounds, the bounds of the readout plane are // like the active ones std::shared_ptr<const PlanarBounds> readoutPlaneBounds = moduleBounds; std::shared_ptr<const PlanarBounds> counterPlaneBounds(nullptr); // the transform of the readout plane is always centric - (*mutableReadoutPlaneTransform).translation() - = Vector3D(0., 0., readoutDirection * halfThickness); + (*mutableReadoutPlaneTransform).translation() = + Vector3D(0., 0., readoutDirection * halfThickness); // no lorentz angle and everything is straight-forward if (lorentzAngle == 0.) { counterPlaneBounds = moduleBounds; - (*mutableCounterPlaneTransform).translation() - = Vector3D(0., 0., -readoutDirection * halfThickness); + (*mutableCounterPlaneTransform).translation() = + Vector3D(0., 0., -readoutDirection * halfThickness); } else { // lorentz reduced Bounds - double lorentzReducedHalfX = m_activeBounds->boundingBox().halflengthX() - - fabs(lorentzPlaneShiftX); + double lorentzReducedHalfX = + m_activeBounds->boundingBox().halflengthX() - fabs(lorentzPlaneShiftX); std::shared_ptr<const PlanarBounds> lorentzReducedBounds( new RectangleBounds(lorentzReducedHalfX, m_activeBounds->boundingBox().halflengthY())); @@ -101,14 +88,14 @@ Acts::CartesianSegmentation::createSegmentationSurfaces( // now we shift the counter plane in position - this depends on lorentz // angle double counterPlaneShift = -readoutDirection * lorentzPlaneShiftX; - (*mutableCounterPlaneTransform).translation() - = Vector3D(counterPlaneShift, 0., -readoutDirection * halfThickness); + (*mutableCounterPlaneTransform).translation() = + Vector3D(counterPlaneShift, 0., -readoutDirection * halfThickness); } // - finalize the transforms - auto readoutPlaneTransform = std::const_pointer_cast<const Transform3D>( - mutableReadoutPlaneTransform); - auto counterPlaneTransform = std::const_pointer_cast<const Transform3D>( - mutableCounterPlaneTransform); + auto readoutPlaneTransform = + std::const_pointer_cast<const Transform3D>(mutableReadoutPlaneTransform); + auto counterPlaneTransform = + std::const_pointer_cast<const Transform3D>(mutableCounterPlaneTransform); // - build the readout & counter readout surfaces boundarySurfaces.push_back(Surface::makeShared<PlaneSurface>( readoutPlaneTransform, readoutPlaneBounds)); @@ -118,8 +105,8 @@ Acts::CartesianSegmentation::createSegmentationSurfaces( // (B) - bin X and lorentz surfaces // ----------------------------------------------------------- // easy stuff first, constant pitch size and - double pitchX = 2. * m_activeBounds->boundingBox().halflengthX() - / m_binUtility->bins(0); + double pitchX = + 2. * m_activeBounds->boundingBox().halflengthX() / m_binUtility->bins(0); // now, let's create the shared bounds of all surfaces marking x bins - choice // fixes orientation of the matrix @@ -128,10 +115,12 @@ Acts::CartesianSegmentation::createSegmentationSurfaces( // now, let's create the shared bounds of all surfaces marking lorentz planes double lorentzPlaneHalfX = std::abs(halfThickness / cos(lorentzAngle)); // the bounds of the lorentz plane - std::shared_ptr<const PlanarBounds> lorentzPlaneBounds = (lorentzAngle == 0.) - ? xBinBounds - : std::shared_ptr<const PlanarBounds>(new RectangleBounds( - m_activeBounds->boundingBox().halflengthY(), lorentzPlaneHalfX)); + std::shared_ptr<const PlanarBounds> lorentzPlaneBounds = + (lorentzAngle == 0.) + ? xBinBounds + : std::shared_ptr<const PlanarBounds>( + new RectangleBounds(m_activeBounds->boundingBox().halflengthY(), + lorentzPlaneHalfX)); // now the rotation matrix for the xBins RotationMatrix3D xBinRotationMatrix; @@ -140,9 +129,10 @@ Acts::CartesianSegmentation::createSegmentationSurfaces( xBinRotationMatrix.col(2) = Vector3D::UnitX(); // now the lorentz plane rotation should be the xBin rotation, rotated by the // lorentz angle around y - RotationMatrix3D lorentzPlaneRotationMatrix = (lorentzAngle != 0.) - ? xBinRotationMatrix * AngleAxis3D(lorentzAngle, Vector3D::UnitX()) - : xBinRotationMatrix; + RotationMatrix3D lorentzPlaneRotationMatrix = + (lorentzAngle != 0.) + ? xBinRotationMatrix * AngleAxis3D(lorentzAngle, Vector3D::UnitX()) + : xBinRotationMatrix; // reserve, it's always (number of bins-1) as the boundaries are within the // boundarySurfaces @@ -150,32 +140,33 @@ Acts::CartesianSegmentation::createSegmentationSurfaces( // create and fill them for (size_t ibinx = 0; ibinx <= m_binUtility->bins(0); ++ibinx) { // the current step x position - double cPosX - = -m_activeBounds->boundingBox().halflengthX() + ibinx * pitchX; + double cPosX = + -m_activeBounds->boundingBox().halflengthX() + ibinx * pitchX; // (i) this is the low/high boundary --- ( ibin == 0/m_binUtility->bins(0) ) if ((ibinx == 0u) || ibinx == m_binUtility->bins(0)) { // check if it a straight boundary or not: always straight for no lorentz // angle, // and either the first boundary or the last dependening on lorentz & // readout - bool boundaryStraight - = (lorentzAngle == 0. - || ((ibinx == 0u) && readoutDirection * lorentzAngle > 0.) - || (ibinx == m_binUtility->bins(0) - && readoutDirection * lorentzAngle < 0)); + bool boundaryStraight = + (lorentzAngle == 0. || + ((ibinx == 0u) && readoutDirection * lorentzAngle > 0.) || + (ibinx == m_binUtility->bins(0) && + readoutDirection * lorentzAngle < 0)); // set the low boundary parameters : position & rotation - Vector3D boundaryXPosition = boundaryStraight - ? Vector3D(cPosX, 0., 0.) - : Vector3D(cPosX - readoutDirection * lorentzPlaneShiftX, 0., 0.); + Vector3D boundaryXPosition = + boundaryStraight + ? Vector3D(cPosX, 0., 0.) + : Vector3D(cPosX - readoutDirection * lorentzPlaneShiftX, 0., 0.); // rotation of the boundary: striaght or lorentz - const RotationMatrix3D& boundaryXRotation - = boundaryStraight ? xBinRotationMatrix : lorentzPlaneRotationMatrix; + const RotationMatrix3D& boundaryXRotation = + boundaryStraight ? xBinRotationMatrix : lorentzPlaneRotationMatrix; // build the rotation from it auto boundaryXTransform = std::make_shared<const Transform3D>( Translation3D(boundaryXPosition) * boundaryXRotation); // the correct bounds for this - std::shared_ptr<const PlanarBounds> boundaryXBounds - = boundaryStraight ? xBinBounds : lorentzPlaneBounds; + std::shared_ptr<const PlanarBounds> boundaryXBounds = + boundaryStraight ? xBinBounds : lorentzPlaneBounds; // boundary surfaces boundarySurfaces.push_back(Surface::makeShared<PlaneSurface>( boundaryXTransform, boundaryXBounds)); @@ -200,8 +191,8 @@ Acts::CartesianSegmentation::createSegmentationSurfaces( yBinRotationMatrix.col(1) = Vector3D::UnitZ(); yBinRotationMatrix.col(2) = Vector3D(0., -1., 0.); // easy stuff first, constant pitch in Y - double pitchY = 2. * m_activeBounds->boundingBox().halflengthY() - / m_binUtility->bins(1); + double pitchY = + 2. * m_activeBounds->boundingBox().halflengthY() / m_binUtility->bins(1); // let's create the shared bounds of all surfaces marking y bins std::shared_ptr<const PlanarBounds> yBinBounds(new RectangleBounds( m_activeBounds->boundingBox().halflengthX(), halfThickness)); @@ -210,8 +201,8 @@ Acts::CartesianSegmentation::createSegmentationSurfaces( segmentationSurfacesY.reserve(m_binUtility->bins(1)); for (size_t ibiny = 0; ibiny <= m_binUtility->bins(1); ++ibiny) { // the position of the bin surface - double binPosY - = -m_activeBounds->boundingBox().halflengthY() + ibiny * pitchY; + double binPosY = + -m_activeBounds->boundingBox().halflengthY() + ibiny * pitchY; Vector3D binSurfaceCenter(0., binPosY, 0.); // the binning transform auto binTransform = std::make_shared<const Transform3D>( @@ -227,27 +218,22 @@ Acts::CartesianSegmentation::createSegmentationSurfaces( } } -Acts::Vector2D -Acts::CartesianSegmentation::cellPosition(const DigitizationCell& dCell) const -{ +Acts::Vector2D Acts::CartesianSegmentation::cellPosition( + const DigitizationCell& dCell) const { double bX = m_binUtility->bins(0) > 1 - ? m_binUtility->binningData()[0].center(dCell.channel0) - : 0.; + ? m_binUtility->binningData()[0].center(dCell.channel0) + : 0.; double bY = m_binUtility->bins(1) > 1 - ? m_binUtility->binningData()[1].center(dCell.channel1) - : 0.; + ? m_binUtility->binningData()[1].center(dCell.channel1) + : 0.; return Vector2D(bX, bY); } /** Get the digitization cell from 3D position, it used the projection to the * readout surface to estimate the 2D positon */ -Acts::DigitizationStep -Acts::CartesianSegmentation::digitizationStep(const Vector3D& startStep, - const Vector3D& endStep, - double halfThickness, - int readoutDirection, - double lorentzAngle) const -{ +Acts::DigitizationStep Acts::CartesianSegmentation::digitizationStep( + const Vector3D& startStep, const Vector3D& endStep, double halfThickness, + int readoutDirection, double lorentzAngle) const { Vector3D stepCenter = 0.5 * (startStep + endStep); // take the full drift length // this is the absolute drift in z @@ -259,14 +245,9 @@ Acts::CartesianSegmentation::digitizationStep(const Vector3D& startStep, // the projected center, it has the lorentz shift applied Vector2D stepCenterProjected(stepCenter.x() + lorentzDeltaX, stepCenter.y()); // the cell & its center - Acts::DigitizationCell dCell = cell(stepCenterProjected); - Vector2D cellCenter = cellPosition(dCell); + Acts::DigitizationCell dCell = cell(stepCenterProjected); + Vector2D cellCenter = cellPosition(dCell); // we are ready to return what we have - return DigitizationStep((endStep - startStep).norm(), - driftLength, - dCell, - startStep, - endStep, - stepCenterProjected, - cellCenter); + return DigitizationStep((endStep - startStep).norm(), driftLength, dCell, + startStep, endStep, stepCenterProjected, cellCenter); } diff --git a/Plugins/Digitization/src/DigitizationModule.cpp b/Plugins/Digitization/src/DigitizationModule.cpp index f5fa33ae7e00bb3f3ce1f804cca6acef743d024a..d4de333c6b836de8ffe44880513a2745a81b0f58 100644 --- a/Plugins/Digitization/src/DigitizationModule.cpp +++ b/Plugins/Digitization/src/DigitizationModule.cpp @@ -16,41 +16,32 @@ Acts::DigitizationModule::DigitizationModule( std::shared_ptr<const Segmentation> moduleSegmentation, - double halfThickness, - int readoutDirection, - double lorentzAngle, - double energyThreshold, - bool analogue) - : + double halfThickness, int readoutDirection, double lorentzAngle, + double energyThreshold, bool analogue) + : - m_halfThickness(halfThickness) - , m_readoutDirection(readoutDirection) - , m_lorentzAngle(lorentzAngle) - , m_tanLorentzAngle(tan(lorentzAngle)) - , m_energyThreshold(energyThreshold) - , m_analogue(analogue) - , m_segmentation(std::move(moduleSegmentation)) - , m_boundarySurfaces() - , m_segmentationSurfacesX() - , m_segmentationSurfacesY() -{ - m_segmentation->createSegmentationSurfaces(m_boundarySurfaces, - m_segmentationSurfacesX, - m_segmentationSurfacesY, - halfThickness, - readoutDirection, - lorentzAngle); + m_halfThickness(halfThickness), + m_readoutDirection(readoutDirection), + m_lorentzAngle(lorentzAngle), + m_tanLorentzAngle(tan(lorentzAngle)), + m_energyThreshold(energyThreshold), + m_analogue(analogue), + m_segmentation(std::move(moduleSegmentation)), + m_boundarySurfaces(), + m_segmentationSurfacesX(), + m_segmentationSurfacesY() { + m_segmentation->createSegmentationSurfaces( + m_boundarySurfaces, m_segmentationSurfacesX, m_segmentationSurfacesY, + halfThickness, readoutDirection, lorentzAngle); } -const Acts::SurfacePtrVector -Acts::DigitizationModule::segmentationSurfaces( +const Acts::SurfacePtrVector Acts::DigitizationModule::segmentationSurfaces( const Acts::DigitizationCell& entryCids, - const Acts::DigitizationCell& exitCids) const -{ + const Acts::DigitizationCell& exitCids) const { SurfacePtrVector sSurfaces; auto startbinX = entryCids.channel0; - auto endbinX = exitCids.channel0; + auto endbinX = exitCids.channel0; // swap if needed if (startbinX > endbinX) { std::swap(startbinX, endbinX); @@ -62,7 +53,7 @@ Acts::DigitizationModule::segmentationSurfaces( // start bin, end bin auto startbinY = entryCids.channel1; - auto endbinY = exitCids.channel1; + auto endbinY = exitCids.channel1; // swap if needed if (startbinY > endbinY) { std::swap(startbinY, endbinY); @@ -76,15 +67,13 @@ Acts::DigitizationModule::segmentationSurfaces( return sSurfaces; } -const Acts::SurfacePtrVector -Acts::DigitizationModule::stepSurfaces(const Vector3D& start, - const Vector3D& end) const -{ +const Acts::SurfacePtrVector Acts::DigitizationModule::stepSurfaces( + const Vector3D& start, const Vector3D& end) const { // prepare the return vector SurfacePtrVector stepSurfaces; const DigitizationCell startCell = m_segmentation->cell(start); - const DigitizationCell endCell = m_segmentation->cell(end); + const DigitizationCell endCell = m_segmentation->cell(end); // go along x - first with the naive binning (i.e. w.o lorentz angle) size_t sCellX = startCell.channel0; diff --git a/Plugins/Digitization/src/DoubleHitSpacePointBuilder.cpp b/Plugins/Digitization/src/DoubleHitSpacePointBuilder.cpp index 25ccfc026cf6e52ad00357887891390c4445fa87..686fdc78cce402faebb8e45a17948028bde43c70 100644 --- a/Plugins/Digitization/src/DoubleHitSpacePointBuilder.cpp +++ b/Plugins/Digitization/src/DoubleHitSpacePointBuilder.cpp @@ -15,17 +15,13 @@ /// @note Used abbreviation: "Strip Detector Element" -> SDE /// Acts::SpacePointBuilder<Acts::DoubleHitSpacePoint>::SpacePointBuilder( - Acts::SpacePointBuilder<Acts::DoubleHitSpacePoint>:: - DoubleHitSpacePointConfig cfg) - : m_cfg(std::move(cfg)) -{ -} + Acts::SpacePointBuilder< + Acts::DoubleHitSpacePoint>::DoubleHitSpacePointConfig cfg) + : m_cfg(std::move(cfg)) {} double Acts::SpacePointBuilder<Acts::DoubleHitSpacePoint>::differenceOfClustersChecked( - const Vector3D& pos1, - const Vector3D& pos2) const -{ + const Vector3D& pos1, const Vector3D& pos2) const { // Check if measurements are close enough to each other if ((pos1 - pos2).norm() > m_cfg.diffDist) { return -1.; @@ -33,9 +29,9 @@ Acts::SpacePointBuilder<Acts::DoubleHitSpacePoint>::differenceOfClustersChecked( // Calculate the angles of the vectors double phi1, theta1, phi2, theta2; - phi1 = VectorHelpers::phi(pos1 - m_cfg.vertex); + phi1 = VectorHelpers::phi(pos1 - m_cfg.vertex); theta1 = VectorHelpers::theta(pos1 - m_cfg.vertex); - phi2 = VectorHelpers::phi(pos2 - m_cfg.vertex); + phi2 = VectorHelpers::phi(pos2 - m_cfg.vertex); theta2 = VectorHelpers::theta(pos2 - m_cfg.vertex); // Calculate the squared difference between the theta angles @@ -54,21 +50,16 @@ Acts::SpacePointBuilder<Acts::DoubleHitSpacePoint>::differenceOfClustersChecked( return diffTheta2 + diffPhi2; } -Acts::Vector2D -Acts::SpacePointBuilder<Acts::DoubleHitSpacePoint>::localCoords( - const PlanarModuleCluster& cluster) const -{ +Acts::Vector2D Acts::SpacePointBuilder<Acts::DoubleHitSpacePoint>::localCoords( + const PlanarModuleCluster& cluster) const { // Local position information - auto par = cluster.parameters(); + auto par = cluster.parameters(); Acts::Vector2D local(par[Acts::ParDef::eLOC_0], par[Acts::ParDef::eLOC_1]); return local; } -Acts::Vector3D -Acts::SpacePointBuilder<Acts::DoubleHitSpacePoint>::globalCoords( - const GeometryContext& gctx, - const PlanarModuleCluster& cluster) const -{ +Acts::Vector3D Acts::SpacePointBuilder<Acts::DoubleHitSpacePoint>::globalCoords( + const GeometryContext& gctx, const PlanarModuleCluster& cluster) const { // Receive corresponding surface auto& clusterSurface = cluster.referenceSurface(); @@ -79,22 +70,20 @@ Acts::SpacePointBuilder<Acts::DoubleHitSpacePoint>::globalCoords( return pos; } -void -Acts::SpacePointBuilder<Acts::DoubleHitSpacePoint>::makeClusterPairs( - const GeometryContext& gctx, +void Acts::SpacePointBuilder<Acts::DoubleHitSpacePoint>::makeClusterPairs( + const GeometryContext& gctx, const std::vector<const PlanarModuleCluster*>& clustersFront, const std::vector<const PlanarModuleCluster*>& clustersBack, std::vector<std::pair<const PlanarModuleCluster*, - const PlanarModuleCluster*>>& clusterPairs) const -{ + const PlanarModuleCluster*>>& clusterPairs) const { // Return if no clusters are given in a vector if (clustersFront.empty() || clustersBack.empty()) { return; } // Declare helper variables - double currentDiff; - double diffMin; + double currentDiff; + double diffMin; unsigned int clusterMinDist; // Walk through all clusters on both surfaces @@ -112,7 +101,7 @@ Acts::SpacePointBuilder<Acts::DoubleHitSpacePoint>::makeClusterPairs( globalCoords(gctx, *(clustersBack[iClustersBack]))); // Store the closest clusters (distance and index) calculated so far if (currentDiff < diffMin && currentDiff >= 0.) { - diffMin = currentDiff; + diffMin = currentDiff; clusterMinDist = iClustersBack; } } @@ -131,16 +120,15 @@ Acts::SpacePointBuilder<Acts::DoubleHitSpacePoint>::makeClusterPairs( std::pair<Acts::Vector3D, Acts::Vector3D> Acts::SpacePointBuilder<Acts::DoubleHitSpacePoint>::endsOfStrip( - const GeometryContext& gctx, - const Acts::PlanarModuleCluster& cluster) const -{ + const GeometryContext& gctx, + const Acts::PlanarModuleCluster& cluster) const { // Calculate the local coordinates of the cluster const Acts::Vector2D local = localCoords(cluster); // Receive the binning auto segment = dynamic_cast<const Acts::CartesianSegmentation*>( &(cluster.digitizationModule()->segmentation())); - auto& binData = segment->binUtility().binningData(); + auto& binData = segment->binUtility().binningData(); auto& boundariesX = binData[0].boundaries(); auto& boundariesY = binData[1].boundaries(); @@ -150,24 +138,24 @@ Acts::SpacePointBuilder<Acts::DoubleHitSpacePoint>::endsOfStrip( Acts::Vector2D topLocal, bottomLocal; - if (boundariesX[binX + 1] - boundariesX[binX] - < boundariesY[binY + 1] - boundariesY[binY]) { + if (boundariesX[binX + 1] - boundariesX[binX] < + boundariesY[binY + 1] - boundariesY[binY]) { // Set the top and bottom end of the strip in local coordinates topLocal = {(boundariesX[binX] + boundariesX[binX + 1]) / 2, boundariesY[binY + 1]}; - bottomLocal - = {(boundariesX[binX] + boundariesX[binX + 1]) / 2, boundariesY[binY]}; + bottomLocal = {(boundariesX[binX] + boundariesX[binX + 1]) / 2, + boundariesY[binY]}; } else { // Set the top and bottom end of the strip in local coordinates - topLocal - = {boundariesX[binX], (boundariesY[binY] + boundariesY[binY + 1]) / 2}; + topLocal = {boundariesX[binX], + (boundariesY[binY] + boundariesY[binY + 1]) / 2}; bottomLocal = {boundariesX[binX + 1], (boundariesY[binY] + boundariesY[binY + 1]) / 2}; } // Calculate the global coordinates of the top and bottom end of the strip Acts::Vector3D topGlobal, bottomGlobal, mom; // mom is a dummy variable - const auto* sur = &cluster.referenceSurface(); + const auto* sur = &cluster.referenceSurface(); sur->localToGlobal(gctx, topLocal, mom, topGlobal); sur->localToGlobal(gctx, bottomLocal, mom, bottomGlobal); @@ -175,13 +163,9 @@ Acts::SpacePointBuilder<Acts::DoubleHitSpacePoint>::endsOfStrip( return std::make_pair(topGlobal, bottomGlobal); } -double -Acts::SpacePointBuilder<Acts::DoubleHitSpacePoint>::calcPerpProj( - const Acts::Vector3D& a, - const Acts::Vector3D& c, - const Acts::Vector3D& q, - const Acts::Vector3D& r) const -{ +double Acts::SpacePointBuilder<Acts::DoubleHitSpacePoint>::calcPerpProj( + const Acts::Vector3D& a, const Acts::Vector3D& c, const Acts::Vector3D& q, + const Acts::Vector3D& r) const { /// This approach assumes that no vertex is available. This option aims to /// approximate the space points from cosmic data. /// The underlying assumption is that the best point is given by the closest @@ -192,9 +176,9 @@ Acts::SpacePointBuilder<Acts::DoubleHitSpacePoint>::calcPerpProj( /// lambda1 * r. /// x get resolved by resolving lambda0 from the condition that |x-y| is the /// shortest distance between two skew lines. - Acts::Vector3D ac = c - a; - double qr = q.dot(r); - double denom = q.dot(q) - qr * qr; + Acts::Vector3D ac = c - a; + double qr = q.dot(r); + double denom = q.dot(q) - qr * qr; // Check for numerical stability if (fabs(denom) > 10e-7) { @@ -205,11 +189,9 @@ Acts::SpacePointBuilder<Acts::DoubleHitSpacePoint>::calcPerpProj( return 1.; } -bool -Acts::SpacePointBuilder<Acts::DoubleHitSpacePoint>::recoverSpacePoint( +bool Acts::SpacePointBuilder<Acts::DoubleHitSpacePoint>::recoverSpacePoint( Acts::SpacePointBuilder<DoubleHitSpacePoint>::SpacePointParameters& spaPoPa) - const -{ + const { /// Consider some cases that would allow an easy exit // Check if the limits are allowed to be increased if (m_cfg.stripLengthGapTolerance <= 0.) { @@ -218,8 +200,8 @@ Acts::SpacePointBuilder<Acts::DoubleHitSpacePoint>::recoverSpacePoint( spaPoPa.qmag = spaPoPa.q.norm(); // Increase the limits. This allows a check if the point is just slightly // outside the SDE - spaPoPa.limitExtended - = spaPoPa.limit + m_cfg.stripLengthGapTolerance / spaPoPa.qmag; + spaPoPa.limitExtended = + spaPoPa.limit + m_cfg.stripLengthGapTolerance / spaPoPa.qmag; // Check if m is just slightly outside if (fabs(spaPoPa.m) > spaPoPa.limitExtended) { return false; @@ -253,14 +235,14 @@ Acts::SpacePointBuilder<Acts::DoubleHitSpacePoint>::recoverSpacePoint( // Calculate the scaling factor to project lengths of the second SDE on the // first SDE - double secOnFirstScale - = spaPoPa.q.dot(spaPoPa.r) / (spaPoPa.qmag * spaPoPa.qmag); + double secOnFirstScale = + spaPoPa.q.dot(spaPoPa.r) / (spaPoPa.qmag * spaPoPa.qmag); // Check if both overshoots are in the same direction if (spaPoPa.m > 1. && spaPoPa.n > 1.) { // Calculate the overshoots double mOvershoot = spaPoPa.m - 1.; - double nOvershoot - = (spaPoPa.n - 1.) * secOnFirstScale; // Perform projection + double nOvershoot = + (spaPoPa.n - 1.) * secOnFirstScale; // Perform projection // Resolve worse overshoot double biggerOvershoot = std::max(mOvershoot, nOvershoot); // Move m and n towards 0 @@ -273,8 +255,8 @@ Acts::SpacePointBuilder<Acts::DoubleHitSpacePoint>::recoverSpacePoint( if (spaPoPa.m < -1. && spaPoPa.n < -1.) { // Calculate the overshoots double mOvershoot = -(spaPoPa.m + 1.); - double nOvershoot - = -(spaPoPa.n + 1.) * secOnFirstScale; // Perform projection + double nOvershoot = + -(spaPoPa.n + 1.) * secOnFirstScale; // Perform projection // Resolve worse overshoot double biggerOvershoot = std::max(mOvershoot, nOvershoot); // Move m and n towards 0 @@ -287,22 +269,18 @@ Acts::SpacePointBuilder<Acts::DoubleHitSpacePoint>::recoverSpacePoint( return false; } -void -Acts::SpacePointBuilder<Acts::DoubleHitSpacePoint>::calculateSpacePoints( +void Acts::SpacePointBuilder<Acts::DoubleHitSpacePoint>::calculateSpacePoints( const GeometryContext& gctx, const std::vector<std::pair<const Acts::PlanarModuleCluster*, const Acts::PlanarModuleCluster*>>& - clusterPairs, - std::vector<Acts::DoubleHitSpacePoint>& spacePoints) const -{ - + clusterPairs, + std::vector<Acts::DoubleHitSpacePoint>& spacePoints) const { /// Source of algorithm: Athena, SiSpacePointMakerTool::makeSCT_SpacePoint() Acts::SpacePointBuilder<DoubleHitSpacePoint>::SpacePointParameters spaPoPa; // Walk over every found candidate pair for (const auto& cp : clusterPairs) { - // Calculate the ends of the SDEs const auto& ends1 = endsOfStrip(gctx, *(cp.first)); const auto& ends2 = endsOfStrip(gctx, *(cp.second)); @@ -334,23 +312,23 @@ Acts::SpacePointBuilder<Acts::DoubleHitSpacePoint>::calculateSpacePoints( // Fast skipping if a perpendicular projection should be used double resultPerpProj; if (m_cfg.usePerpProj) { - resultPerpProj - = calcPerpProj(ends1.first, ends2.first, spaPoPa.q, spaPoPa.r); + resultPerpProj = + calcPerpProj(ends1.first, ends2.first, spaPoPa.q, spaPoPa.r); if (resultPerpProj <= 0.) { Acts::DoubleHitSpacePoint sp; sp.clusterFront = cp.first; - sp.clusterBack = cp.second; - sp.spacePoint = ends1.first + resultPerpProj * spaPoPa.q; + sp.clusterBack = cp.second; + sp.spacePoint = ends1.first + resultPerpProj * spaPoPa.q; spacePoints.push_back(std::move(sp)); continue; } } - spaPoPa.s = ends1.first + ends1.second - 2 * m_cfg.vertex; - spaPoPa.t = ends2.first + ends2.second - 2 * m_cfg.vertex; + spaPoPa.s = ends1.first + ends1.second - 2 * m_cfg.vertex; + spaPoPa.t = ends2.first + ends2.second - 2 * m_cfg.vertex; spaPoPa.qs = spaPoPa.q.cross(spaPoPa.s); spaPoPa.rt = spaPoPa.r.cross(spaPoPa.t); - spaPoPa.m = -spaPoPa.s.dot(spaPoPa.rt) / spaPoPa.q.dot(spaPoPa.rt); + spaPoPa.m = -spaPoPa.s.dot(spaPoPa.rt) / spaPoPa.q.dot(spaPoPa.rt); // Set the limit for the parameter if (spaPoPa.limit == 1. && m_cfg.stripLengthTolerance != 0.) { @@ -358,16 +336,15 @@ Acts::SpacePointBuilder<Acts::DoubleHitSpacePoint>::calculateSpacePoints( } // Check if m and n can be resolved in the interval (-1, 1) - if (fabs(spaPoPa.m) <= spaPoPa.limit - && fabs(spaPoPa.n - = -spaPoPa.t.dot(spaPoPa.qs) / spaPoPa.r.dot(spaPoPa.qs)) - <= spaPoPa.limit) { + if (fabs(spaPoPa.m) <= spaPoPa.limit && + fabs(spaPoPa.n = -spaPoPa.t.dot(spaPoPa.qs) / + spaPoPa.r.dot(spaPoPa.qs)) <= spaPoPa.limit) { // Store the space point Acts::DoubleHitSpacePoint sp; sp.clusterFront = cp.first; - sp.clusterBack = cp.second; - sp.spacePoint - = 0.5 * (ends1.first + ends1.second + spaPoPa.m * spaPoPa.q); + sp.clusterBack = cp.second; + sp.spacePoint = + 0.5 * (ends1.first + ends1.second + spaPoPa.m * spaPoPa.q); spacePoints.push_back(std::move(sp)); } else { /// If this point is reached then it was not possible to resolve both @@ -380,9 +357,9 @@ Acts::SpacePointBuilder<Acts::DoubleHitSpacePoint>::calculateSpacePoints( if (recoverSpacePoint(spaPoPa)) { Acts::DoubleHitSpacePoint sp; sp.clusterFront = cp.first; - sp.clusterBack = cp.second; - sp.spacePoint - = 0.5 * (ends1.first + ends1.second + spaPoPa.m * spaPoPa.q); + sp.clusterBack = cp.second; + sp.spacePoint = + 0.5 * (ends1.first + ends1.second + spaPoPa.m * spaPoPa.q); spacePoints.push_back(std::move(sp)); } } diff --git a/Plugins/Digitization/src/PlanarModuleStepper.cpp b/Plugins/Digitization/src/PlanarModuleStepper.cpp index ae656e0e5704a870166c7d127d26044d0a49e770..dba25b0ff4063a09152f5a234f3890e7df84101b 100644 --- a/Plugins/Digitization/src/PlanarModuleStepper.cpp +++ b/Plugins/Digitization/src/PlanarModuleStepper.cpp @@ -18,16 +18,11 @@ Acts::PlanarModuleStepper::PlanarModuleStepper( std::unique_ptr<const Logger> mlogger) - : m_logger(std::move(mlogger)) -{ -} + : m_logger(std::move(mlogger)) {} -std::vector<Acts::DigitizationStep> -Acts::PlanarModuleStepper::cellSteps(const GeometryContext& gctx, - const DigitizationModule& dmodule, - const Vector3D& startPoint, - const Vector3D& endPoint) const -{ +std::vector<Acts::DigitizationStep> Acts::PlanarModuleStepper::cellSteps( + const GeometryContext& gctx, const DigitizationModule& dmodule, + const Vector3D& startPoint, const Vector3D& endPoint) const { // create the return vector std::vector<DigitizationStep> cSteps; @@ -50,10 +45,8 @@ Acts::PlanarModuleStepper::cellSteps(const GeometryContext& gctx, // now record stepIntersections.push_back(sIntersection); ACTS_VERBOSE("Boundary Surface intersected with = " - << sIntersection.position.x() - << ", " - << sIntersection.position.y() - << ", " + << sIntersection.position.x() << ", " + << sIntersection.position.y() << ", " << sIntersection.position.z()); } } @@ -76,18 +69,15 @@ Acts::PlanarModuleStepper::cellSteps(const GeometryContext& gctx, } // calculate the steps caused by this track - fast simulation interface -std::vector<Acts::DigitizationStep> -Acts::PlanarModuleStepper::cellSteps(const GeometryContext& gctx, - const Acts::DigitizationModule& dmodule, - const Vector2D& moduleIntersection, - const Vector3D& trackDirection) const -{ +std::vector<Acts::DigitizationStep> Acts::PlanarModuleStepper::cellSteps( + const GeometryContext& gctx, const Acts::DigitizationModule& dmodule, + const Vector2D& moduleIntersection, const Vector3D& trackDirection) const { // first, intersect the boundary surfaces auto boundarySurfaces = dmodule.boundarySurfaces(); // intersect them - fast exit for cases where // readout and counter readout are hit Vector3D intersection3D(moduleIntersection.x(), moduleIntersection.y(), 0.); - size_t attempts = 0; + size_t attempts = 0; // the collected intersections std::vector<Acts::Intersection> boundaryIntersections; // run them - and check for the fast exit @@ -101,10 +91,8 @@ Acts::PlanarModuleStepper::cellSteps(const GeometryContext& gctx, // now record boundaryIntersections.push_back(bIntersection); ACTS_VERBOSE("Boundary Surface intersected with = " - << bIntersection.position.x() - << ", " - << bIntersection.position.y() - << ", " + << bIntersection.position.x() << ", " + << bIntersection.position.y() << ", " << bIntersection.position.z()); } // fast break in case of readout/counter surface hit @@ -117,8 +105,9 @@ Acts::PlanarModuleStepper::cellSteps(const GeometryContext& gctx, // Post-process if we have more than 2 intersections // only first or last can be wrong after resorting if (boundaryIntersections.size() > 2) { - ACTS_VERBOSE("More than 2 Boundary Surfaces intersected, this is an edge " - "case, resolving ... "); + ACTS_VERBOSE( + "More than 2 Boundary Surfaces intersected, this is an edge " + "case, resolving ... "); std::sort(boundaryIntersections.begin(), boundaryIntersections.end()); } // if for some reason the intersection does not work @@ -126,8 +115,6 @@ Acts::PlanarModuleStepper::cellSteps(const GeometryContext& gctx, return std::vector<Acts::DigitizationStep>(); } // return - return cellSteps(gctx, - dmodule, - boundaryIntersections[0].position, + return cellSteps(gctx, dmodule, boundaryIntersections[0].position, boundaryIntersections[1].position); } diff --git a/Plugins/Digitization/src/SingleHitSpacePointBuilder.cpp b/Plugins/Digitization/src/SingleHitSpacePointBuilder.cpp index 0986da859e9c1452276c439388ee1526184204e1..bea18a4b41fb4c202e2e65fb97cd7f23dc7c6599 100644 --- a/Plugins/Digitization/src/SingleHitSpacePointBuilder.cpp +++ b/Plugins/Digitization/src/SingleHitSpacePointBuilder.cpp @@ -8,21 +8,16 @@ #include "Acts/Plugins/Digitization/SingleHitSpacePointBuilder.hpp" -Acts::Vector2D -Acts::SpacePointBuilder<Acts::SingleHitSpacePoint>::localCoords( - const PlanarModuleCluster& cluster) const -{ +Acts::Vector2D Acts::SpacePointBuilder<Acts::SingleHitSpacePoint>::localCoords( + const PlanarModuleCluster& cluster) const { // Local position information - auto par = cluster.parameters(); + auto par = cluster.parameters(); Acts::Vector2D local(par[Acts::ParDef::eLOC_0], par[Acts::ParDef::eLOC_1]); return local; } -Acts::Vector3D -Acts::SpacePointBuilder<Acts::SingleHitSpacePoint>::globalCoords( - const GeometryContext& gctx, - const PlanarModuleCluster& cluster) const -{ +Acts::Vector3D Acts::SpacePointBuilder<Acts::SingleHitSpacePoint>::globalCoords( + const GeometryContext& gctx, const PlanarModuleCluster& cluster) const { // Receive corresponding surface auto& clusterSurface = cluster.referenceSurface(); @@ -33,16 +28,14 @@ Acts::SpacePointBuilder<Acts::SingleHitSpacePoint>::globalCoords( return pos; } -void -Acts::SpacePointBuilder<Acts::SingleHitSpacePoint>::calculateSpacePoints( - const GeometryContext& gctx, +void Acts::SpacePointBuilder<Acts::SingleHitSpacePoint>::calculateSpacePoints( + const GeometryContext& gctx, const std::vector<const Acts::PlanarModuleCluster*>& clusters, - std::vector<Acts::SingleHitSpacePoint>& spacePointStorage) const -{ + std::vector<Acts::SingleHitSpacePoint>& spacePointStorage) const { // Set the space point for all stored hits for (const auto& c : clusters) { Acts::SingleHitSpacePoint spacePoint; - spacePoint.spacePoint = globalCoords(gctx, *c); + spacePoint.spacePoint = globalCoords(gctx, *c); spacePoint.clusterModule = c; spacePointStorage.push_back(std::move(spacePoint)); } diff --git a/Plugins/Geant4/include/Acts/Plugins/Geant4/Geant4DetectorElement.hpp b/Plugins/Geant4/include/Acts/Plugins/Geant4/Geant4DetectorElement.hpp index 0436131f0690e05b2141124fe0ca010bc1c42e0c..5b5786d269195f8c8706765fa27b15323f29799c 100644 --- a/Plugins/Geant4/include/Acts/Plugins/Geant4/Geant4DetectorElement.hpp +++ b/Plugins/Geant4/include/Acts/Plugins/Geant4/Geant4DetectorElement.hpp @@ -17,14 +17,13 @@ namespace Acts { */ -class Geant4DetElement -{ -public: +class Geant4DetElement { + public: /** Constructor */ Geant4DetElement(); /** Desctructor */ virtual ~Geant4DetElement(); -private: + private: }; -} \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Plugins/Identification/include/Acts/Plugins/Identification/IdentifiedDetectorElement.hpp b/Plugins/Identification/include/Acts/Plugins/Identification/IdentifiedDetectorElement.hpp index b19edf5b9e6425ba067c1c30a4fe7f6fc695ef79..47802a04af065c142c0c7e4e4a2a769d68e8f63e 100644 --- a/Plugins/Identification/include/Acts/Plugins/Identification/IdentifiedDetectorElement.hpp +++ b/Plugins/Identification/include/Acts/Plugins/Identification/IdentifiedDetectorElement.hpp @@ -27,16 +27,14 @@ class DigitizationModule; /// /// The identifier can be overwritten with by the use of /// the ACTS_CORE_IDENTIFIER_PLUGIN -class IdentifiedDetectorElement : public DetectorElementBase -{ -public: +class IdentifiedDetectorElement : public DetectorElementBase { + public: /// Retrieve the Identifier - virtual Identifier - identifier() const = 0; + virtual Identifier identifier() const = 0; /// Retrieve the DigitizationModule - virtual const std::shared_ptr<const DigitizationModule> - digitizationModule() const = 0; + virtual const std::shared_ptr<const DigitizationModule> digitizationModule() + const = 0; }; } // end of namespace Acts diff --git a/Plugins/Identification/include/Acts/Plugins/Identification/Identifier.hpp b/Plugins/Identification/include/Acts/Plugins/Identification/Identifier.hpp index 3fd74c37f7ee60efb5ebfee47fdcfde6409f49fa..ff2db2bc1f4c8feb7107c5b7a24130e868c99a4e 100644 --- a/Plugins/Identification/include/Acts/Plugins/Identification/Identifier.hpp +++ b/Plugins/Identification/include/Acts/Plugins/Identification/Identifier.hpp @@ -18,5 +18,5 @@ #else using identifier_type = unsigned long long; using identifier_diff = long long; -using Identifier = identifier_type; +using Identifier = identifier_type; #endif diff --git a/Plugins/TGeo/include/Acts/Plugins/TGeo/TGeoDetectorElement.hpp b/Plugins/TGeo/include/Acts/Plugins/TGeo/TGeoDetectorElement.hpp index 35ce5c25603f6b52fb149f7bb40017e4aeb191ad..79a895b1ee8b6ee1ad8e34e89f285017b6e01c14 100644 --- a/Plugins/TGeo/include/Acts/Plugins/TGeo/TGeoDetectorElement.hpp +++ b/Plugins/TGeo/include/Acts/Plugins/TGeo/TGeoDetectorElement.hpp @@ -33,9 +33,8 @@ class DigitizationModule; /// what /// if not used with DD4hep? /// -class TGeoDetectorElement : public IdentifiedDetectorElement -{ -public: +class TGeoDetectorElement : public IdentifiedDetectorElement { + public: /// Broadcast the context type using ContextType = GeometryContext; @@ -71,15 +70,12 @@ public: /// @param digitizationModule Shared pointer to the geometric digitization /// description TGeoDetectorElement( - const Identifier& identifier, - TGeoNode* tGeoDetElement, - const TGeoMatrix* mGlobal = nullptr, - const std::string& axes = "XYZ", - double scalor = 1., - bool isDisc = false, - std::shared_ptr<const Acts::ISurfaceMaterial> material = nullptr, - std::shared_ptr<const Acts::DigitizationModule> digitizationModule - = nullptr); + const Identifier& identifier, TGeoNode* tGeoDetElement, + const TGeoMatrix* mGlobal = nullptr, const std::string& axes = "XYZ", + double scalor = 1., bool isDisc = false, + std::shared_ptr<const Acts::ISurfaceMaterial> material = nullptr, + std::shared_ptr<const Acts::DigitizationModule> digitizationModule = + nullptr); /// Alternative Constructor /// when the localToGlobal transform is already known for the detector element @@ -118,42 +114,35 @@ public: /// @param digitizationModule Shared pointer to the geometric digitization /// description TGeoDetectorElement( - const Identifier& identifier, - const TGeoMatrix& transform, - TGeoNode* tGeoDetElement, - const std::string& axes = "XYZ", - double scalor = 1., - bool isDisc = false, - std::shared_ptr<const Acts::ISurfaceMaterial> material = nullptr, - std::shared_ptr<const Acts::DigitizationModule> digitizationModule - = nullptr); + const Identifier& identifier, const TGeoMatrix& transform, + TGeoNode* tGeoDetElement, const std::string& axes = "XYZ", + double scalor = 1., bool isDisc = false, + std::shared_ptr<const Acts::ISurfaceMaterial> material = nullptr, + std::shared_ptr<const Acts::DigitizationModule> digitizationModule = + nullptr); /// Destructor ~TGeoDetectorElement() override; /// Identifier - Identifier - identifier() const final; + Identifier identifier() const final; /// Return local to global transform associated with this identifier /// /// @param gctx The current geometry context object, e.g. alignment - const Transform3D& - transform(const GeometryContext& gctx) const final; + const Transform3D& transform(const GeometryContext& gctx) const final; /// Return surface associated with this identifier, which should come from the - const Surface& - surface() const final; + const Surface& surface() const final; /// Returns the thickness of the module - double - thickness() const final; + double thickness() const final; /// Retrieve the DigitizationModule - const std::shared_ptr<const Acts::DigitizationModule> - digitizationModule() const final; + const std::shared_ptr<const Acts::DigitizationModule> digitizationModule() + const final; -private: + private: /// DD4hep detector element, just linked - not owned TGeoNode* m_detElement{nullptr}; /// Transformation of the detector element @@ -174,33 +163,25 @@ private: std::shared_ptr<const Acts::DigitizationModule> m_digitizationModule{nullptr}; }; -inline Identifier -TGeoDetectorElement::identifier() const -{ +inline Identifier TGeoDetectorElement::identifier() const { return m_identifier; } -inline const Transform3D& -TGeoDetectorElement::transform(const GeometryContext& /*gctx*/) const -{ +inline const Transform3D& TGeoDetectorElement::transform( + const GeometryContext& /*gctx*/) const { return (*m_transform); } -inline const Surface& -TGeoDetectorElement::surface() const -{ +inline const Surface& TGeoDetectorElement::surface() const { return (*m_surface); } -inline double -TGeoDetectorElement::thickness() const -{ +inline double TGeoDetectorElement::thickness() const { return m_thickness; } inline const std::shared_ptr<const Acts::DigitizationModule> -TGeoDetectorElement::digitizationModule() const -{ +TGeoDetectorElement::digitizationModule() const { return m_digitizationModule; } -} +} // namespace Acts diff --git a/Plugins/TGeo/include/Acts/Plugins/TGeo/TGeoLayerBuilder.hpp b/Plugins/TGeo/include/Acts/Plugins/TGeo/TGeoLayerBuilder.hpp index 22c7b544007a7af0f18332e57ec04d34aca81430..d99cbd5263773fc22eff3b2c981e1b04715892f5 100644 --- a/Plugins/TGeo/include/Acts/Plugins/TGeo/TGeoLayerBuilder.hpp +++ b/Plugins/TGeo/include/Acts/Plugins/TGeo/TGeoLayerBuilder.hpp @@ -30,13 +30,11 @@ using NodeTransform = std::pair<TGeoNode*, std::shared_ptr<const Transform3D>>; /// @class TGeoLayerBuilder /// works on the gGeoManager, as this is filled from GDML -class TGeoLayerBuilder : public ILayerBuilder -{ -public: +class TGeoLayerBuilder : public ILayerBuilder { + public: /// Helper config structs for volume parsin - struct LayerConfig - { - public: + struct LayerConfig { + public: /// identify the layer by name std::string layerName = ""; /// identify the sensor by name @@ -51,18 +49,15 @@ public: size_t binsLoc1{100}; LayerConfig() - : layerName("") - , sensorName("") - , localAxes("XZY") - , envelope(std::pair<double, double>(1., 1.)) - { - } + : layerName(""), + sensorName(""), + localAxes("XZY"), + envelope(std::pair<double, double>(1., 1.)) {} }; /// @struct Config /// nested configuration struct for steering of the layer builder - struct Config - { + struct Config { /// string based identification std::string configurationName = "undefined"; // unit conversion @@ -80,9 +75,9 @@ public: /// Constructor /// @param config is the configuration struct /// @param logger the local logging instance - TGeoLayerBuilder(const Config& config, - std::unique_ptr<const Logger> logger - = getDefaultLogger("LayerArrayCreator", Logging::INFO)); + TGeoLayerBuilder(const Config& config, + std::unique_ptr<const Logger> logger = + getDefaultLogger("LayerArrayCreator", Logging::INFO)); /// Destructor ~TGeoLayerBuilder() override; @@ -91,54 +86,43 @@ public: /// /// @param gctx the geometry context for this build call /// - const LayerVector - negativeLayers(const GeometryContext& gctx) const final; + const LayerVector negativeLayers(const GeometryContext& gctx) const final; /// LayerBuilder interface method - returning the central layers /// /// @param gctx the geometry context for this build call /// - const LayerVector - centralLayers(const GeometryContext& gctx) const final; + const LayerVector centralLayers(const GeometryContext& gctx) const final; /// LayerBuilder interface method - returning the layers at negative side /// /// @param gctx the geometry context for this build call /// - const LayerVector - positiveLayers(const GeometryContext& gctx) const final; + const LayerVector positiveLayers(const GeometryContext& gctx) const final; /// Name identification - const std::string& - identification() const final; + const std::string& identification() const final; /// set the configuration object /// @param config is the configuration struct - void - setConfiguration(const Config& config); + void setConfiguration(const Config& config); /// get the configuration object - Config - getConfiguration() const; + Config getConfiguration() const; /// set logging instance - void - setLogger(std::unique_ptr<const Logger> newLogger); + void setLogger(std::unique_ptr<const Logger> newLogger); /// Return the created detector elements const std::vector<std::shared_ptr<const TGeoDetectorElement>>& detectorElements() const; -private: + private: /// configruation object Config m_cfg; /// Private access to the logger - const Logger& - logger() const - { - return *m_logger; - } + const Logger& logger() const { return *m_logger; } /// logging instance std::unique_ptr<const Logger> m_logger; @@ -149,54 +133,43 @@ private: /// Private helper function to parse the geometry tree /// @param gcts the geometry context of this call /// @param layerSurfaces are the surfaces that build the layer - void - resolveSensitive(const GeometryContext& gctx, - std::vector<std::shared_ptr<const Surface>>& layerSurfaces, - TGeoVolume* tgVolume, - TGeoNode* tgNode, - const TGeoMatrix& tgTransform, - const LayerConfig& layerConfig, - int type, - bool correctBranch = false, - const std::string& offset = ""); + void resolveSensitive( + const GeometryContext& gctx, + std::vector<std::shared_ptr<const Surface>>& layerSurfaces, + TGeoVolume* tgVolume, TGeoNode* tgNode, const TGeoMatrix& tgTransform, + const LayerConfig& layerConfig, int type, bool correctBranch = false, + const std::string& offset = ""); /// Private helper method : build layers /// @param gcts the geometry context of this call /// @param layers is goint to be filled /// @param type is the indication which ones to build -1 | 0 | 1 - void - buildLayers(const GeometryContext& gctx, LayerVector& layers, int type = 0); + void buildLayers(const GeometryContext& gctx, LayerVector& layers, + int type = 0); /// Private helper method : match string with wildcards /// @param wc is the one with the potential wildcard /// @param test is the test string - bool - match(const char* first, const char* second) const; + bool match(const char* first, const char* second) const; }; -inline TGeoLayerBuilder::Config -TGeoLayerBuilder::getConfiguration() const -{ +inline TGeoLayerBuilder::Config TGeoLayerBuilder::getConfiguration() const { return m_cfg; } inline const std::vector<std::shared_ptr<const TGeoDetectorElement>>& -TGeoLayerBuilder::detectorElements() const -{ +TGeoLayerBuilder::detectorElements() const { return m_elementStore; } -inline const std::string& -TGeoLayerBuilder::identification() const -{ +inline const std::string& TGeoLayerBuilder::identification() const { return m_cfg.configurationName; } // The main function that checks if two given strings // match. The first string may contain wildcard characters -inline bool -TGeoLayerBuilder::match(const char* first, const char* second) const -{ +inline bool TGeoLayerBuilder::match(const char* first, + const char* second) const { // If we reach at the end of both strings, we are done if (*first == '\0' && *second == '\0') { return true; @@ -223,4 +196,4 @@ TGeoLayerBuilder::match(const char* first, const char* second) const } return false; } -} +} // namespace Acts diff --git a/Plugins/TGeo/include/Acts/Plugins/TGeo/TGeoPrimitivesHelpers.hpp b/Plugins/TGeo/include/Acts/Plugins/TGeo/TGeoPrimitivesHelpers.hpp index b7bc4d1519522ab71737b5bf9572c403f0da31d4..c0c01836ec3a34a0472e8edd28c6b7610bd1df17 100644 --- a/Plugins/TGeo/include/Acts/Plugins/TGeo/TGeoPrimitivesHelpers.hpp +++ b/Plugins/TGeo/include/Acts/Plugins/TGeo/TGeoPrimitivesHelpers.hpp @@ -14,19 +14,17 @@ namespace Acts { namespace TGeoPrimitivesHelpers { - Transform3D - makeTransform(const Eigen::Vector3d& rotationMatrixCol0, - const Eigen::Vector3d& rotationMatrixCol1, - const Eigen::Vector3d& rotationMatrixCol2, - const Eigen::Vector3d& translation) - { - Transform3D trf; - trf.matrix().block(0, 0, 3, 1) = rotationMatrixCol0; - trf.matrix().block(0, 1, 3, 1) = rotationMatrixCol1; - trf.matrix().block(0, 2, 3, 1) = rotationMatrixCol2; - trf.matrix().block(0, 3, 3, 1) = translation; - return trf; - } +Transform3D makeTransform(const Eigen::Vector3d& rotationMatrixCol0, + const Eigen::Vector3d& rotationMatrixCol1, + const Eigen::Vector3d& rotationMatrixCol2, + const Eigen::Vector3d& translation) { + Transform3D trf; + trf.matrix().block(0, 0, 3, 1) = rotationMatrixCol0; + trf.matrix().block(0, 1, 3, 1) = rotationMatrixCol1; + trf.matrix().block(0, 2, 3, 1) = rotationMatrixCol2; + trf.matrix().block(0, 3, 3, 1) = translation; + return trf; +} } // namespace TGeoPrimitivesHelpers } // namespace Acts diff --git a/Plugins/TGeo/src/TGeoDetectorElement.cpp b/Plugins/TGeo/src/TGeoDetectorElement.cpp index 4355b3fb20a7c57d3792d9b4d36bbc6c86d24f4b..2970d41ff5a0ba1943dd29ded75f8854a00337d4 100644 --- a/Plugins/TGeo/src/TGeoDetectorElement.cpp +++ b/Plugins/TGeo/src/TGeoDetectorElement.cpp @@ -26,82 +26,76 @@ #include "TGeoTube.h" Acts::TGeoDetectorElement::TGeoDetectorElement( - const Identifier& identifier, - TGeoNode* tGeoDetElement, - const TGeoMatrix* mGlobal, - const std::string& axes, - double scalor, - bool isDisc, - std::shared_ptr<const Acts::ISurfaceMaterial> material, + const Identifier& identifier, TGeoNode* tGeoDetElement, + const TGeoMatrix* mGlobal, const std::string& axes, double scalor, + bool isDisc, std::shared_ptr<const Acts::ISurfaceMaterial> material, std::shared_ptr<const Acts::DigitizationModule> digitizationModule) - : Acts::IdentifiedDetectorElement() - , m_detElement(tGeoDetElement) - , m_identifier(identifier) - , m_digitizationModule(std::move(digitizationModule)) -{ + : Acts::IdentifiedDetectorElement(), + m_detElement(tGeoDetElement), + m_identifier(identifier), + m_digitizationModule(std::move(digitizationModule)) { using namespace TGeoPrimitivesHelpers; // create temporary local non const surface (to allow setting the material) std::shared_ptr<Surface> surface = nullptr; // get the placement and orientation in respect to its mother const TGeoMatrix* nodeTransform = (m_detElement->GetMatrix()); - const Double_t* rotation = nullptr; - const Double_t* translation = nullptr; + const Double_t* rotation = nullptr; + const Double_t* translation = nullptr; if (mGlobal != nullptr) { // the new combined translation // TGeoHMatrix nTransform = (*mGlobal) * (*nodeTransform); - TGeoHMatrix nTransform - = TGeoCombiTrans(*mGlobal) * TGeoCombiTrans(*nodeTransform); + TGeoHMatrix nTransform = + TGeoCombiTrans(*mGlobal) * TGeoCombiTrans(*nodeTransform); // TGeoHMatrix nTransform = mGlobal->operator*(*nodeTransform); - std::string nName = tGeoDetElement->GetName(); + std::string nName = tGeoDetElement->GetName(); std::string suffix = "_transform"; nTransform.SetName((nName + suffix).c_str()); translation = nTransform.GetTranslation(); - rotation = nTransform.GetRotationMatrix(); + rotation = nTransform.GetRotationMatrix(); } else { translation = (nodeTransform->GetTranslation()); - rotation = (nodeTransform->GetRotationMatrix()); + rotation = (nodeTransform->GetRotationMatrix()); } // create the translation - Vector3D colT(scalor * translation[0], - scalor * translation[1], + Vector3D colT(scalor * translation[0], scalor * translation[1], scalor * translation[2]); Vector3D colX(rotation[0], rotation[3], rotation[6]); Vector3D colY(rotation[1], rotation[4], rotation[7]); Vector3D colZ(rotation[2], rotation[5], rotation[8]); // check if it's a box - always true ... - TGeoBBox* box - = dynamic_cast<TGeoBBox*>(m_detElement->GetVolume()->GetShape()); + TGeoBBox* box = + dynamic_cast<TGeoBBox*>(m_detElement->GetVolume()->GetShape()); // check if it's a trapezoid - unfortunately box is the base of everything - TGeoTrd2* trapezoid - = dynamic_cast<TGeoTrd2*>(m_detElement->GetVolume()->GetShape()); + TGeoTrd2* trapezoid = + dynamic_cast<TGeoTrd2*>(m_detElement->GetVolume()->GetShape()); // check if it's a tube segment - TGeoTubeSeg* tube - = dynamic_cast<TGeoTubeSeg*>(m_detElement->GetVolume()->GetShape()); + TGeoTubeSeg* tube = + dynamic_cast<TGeoTubeSeg*>(m_detElement->GetVolume()->GetShape()); if (tube != nullptr) { m_transform = std::make_shared<const Transform3D>( makeTransform(colX, colY, colZ, colT)); - double rMin = tube->GetRmin() * scalor; - double rMax = tube->GetRmax() * scalor; + double rMin = tube->GetRmin() * scalor; + double rMax = tube->GetRmax() * scalor; double halfZ = tube->GetDz() * scalor; if (isDisc) { // create disc surface - m_thickness = halfZ; + m_thickness = halfZ; auto radialBounds = std::make_shared<const RadialBounds>(rMin, rMax); - m_bounds = radialBounds; - surface = Surface::makeShared<DiscSurface>(radialBounds, *this); + m_bounds = radialBounds; + surface = Surface::makeShared<DiscSurface>(radialBounds, *this); } else { // create a cylinder surface - m_thickness = std::fabs(rMax - rMin); + m_thickness = std::fabs(rMax - rMin); double radius = (rMin + rMax) * 0.5; - auto cylinderBounds - = std::make_shared<const CylinderBounds>(radius, halfZ); + auto cylinderBounds = + std::make_shared<const CylinderBounds>(radius, halfZ); m_bounds = cylinderBounds; - surface = Surface::makeShared<CylinderSurface>(cylinderBounds, *this); + surface = Surface::makeShared<CylinderSurface>(cylinderBounds, *this); } } else { if (boost::iequals(axes, "XYZ")) { @@ -127,8 +121,7 @@ Acts::TGeoDetectorElement::TGeoDetectorElement( if (trapezoid != nullptr) { // bounds with x/y auto trapezoidBounds = std::make_shared<const TrapezoidBounds>( - scalor * trapezoid->GetDx1(), - scalor * trapezoid->GetDx2(), + scalor * trapezoid->GetDx1(), scalor * trapezoid->GetDx2(), scalor * 0.5 * (trapezoid->GetDy1() + trapezoid->GetDy2())); // thickness m_thickness = scalor * trapezoid->GetDz(); @@ -171,12 +164,11 @@ Acts::TGeoDetectorElement::TGeoDetectorElement( if (trapezoid != nullptr) { // bounds with x/z auto trapezoidBounds = std::make_shared<const TrapezoidBounds>( - scalor * trapezoid->GetDx1(), - scalor * trapezoid->GetDx2(), + scalor * trapezoid->GetDx1(), scalor * trapezoid->GetDx2(), scalor * trapezoid->GetDz()); // thickness - m_thickness - = scalor * 0.5 * (trapezoid->GetDy1() + trapezoid->GetDy2()); + m_thickness = + scalor * 0.5 * (trapezoid->GetDy1() + trapezoid->GetDy2()); // assign them m_bounds = trapezoidBounds; // create the surface @@ -217,12 +209,11 @@ Acts::TGeoDetectorElement::TGeoDetectorElement( if (trapezoid != nullptr) { // bounds with y/z auto trapezoidBounds = std::make_shared<const TrapezoidBounds>( - scalor * trapezoid->GetDy1(), - scalor * trapezoid->GetDy2(), + scalor * trapezoid->GetDy1(), scalor * trapezoid->GetDy2(), scalor * trapezoid->GetDz()); // thickness - m_thickness - = scalor * 0.5 * (trapezoid->GetDx1() + trapezoid->GetDx2()); + m_thickness = + scalor * 0.5 * (trapezoid->GetDx1() + trapezoid->GetDx2()); // assign them m_bounds = trapezoidBounds; // create the surface @@ -262,8 +253,7 @@ Acts::TGeoDetectorElement::TGeoDetectorElement( if (trapezoid != nullptr) { // bounds with y/x auto trapezoidBounds = std::make_shared<const TrapezoidBounds>( - scalor * trapezoid->GetDy1(), - scalor * trapezoid->GetDy2(), + scalor * trapezoid->GetDy1(), scalor * trapezoid->GetDy2(), scalor * 0.5 * (trapezoid->GetDx1() + trapezoid->GetDx2())); // thickness m_thickness = scalor * trapezoid->GetDz(); @@ -306,12 +296,11 @@ Acts::TGeoDetectorElement::TGeoDetectorElement( if (trapezoid != nullptr) { // bounds with z/y auto trapezoidBounds = std::make_shared<const TrapezoidBounds>( - scalor * trapezoid->GetDz(), - scalor * trapezoid->GetDz(), + scalor * trapezoid->GetDz(), scalor * trapezoid->GetDz(), scalor * 0.5 * (trapezoid->GetDy1() + trapezoid->GetDy2())); // thickness - m_thickness - = scalor * 0.5 * (trapezoid->GetDx1() + trapezoid->GetDx2()); + m_thickness = + scalor * 0.5 * (trapezoid->GetDx1() + trapezoid->GetDx2()); // assign them m_bounds = trapezoidBounds; // create the surface @@ -352,12 +341,11 @@ Acts::TGeoDetectorElement::TGeoDetectorElement( if (trapezoid != nullptr) { // bounds with z/x auto trapezoidBounds = std::make_shared<const TrapezoidBounds>( - scalor * trapezoid->GetDz(), - scalor * trapezoid->GetDz(), + scalor * trapezoid->GetDz(), scalor * trapezoid->GetDz(), scalor * 0.5 * (trapezoid->GetDx1() + trapezoid->GetDx2())); // thickness - m_thickness - = scalor * 0.5 * (trapezoid->GetDy1() + trapezoid->GetDy2()); + m_thickness = + scalor * 0.5 * (trapezoid->GetDy1() + trapezoid->GetDy2()); // assign them m_bounds = trapezoidBounds; // create the surface @@ -384,69 +372,63 @@ Acts::TGeoDetectorElement::TGeoDetectorElement( } Acts::TGeoDetectorElement::TGeoDetectorElement( - const Identifier& identifier, - const TGeoMatrix& transform, - TGeoNode* tGeoDetElement, - const std::string& axes, - double scalor, - bool isDisc, - std::shared_ptr<const Acts::ISurfaceMaterial> material, + const Identifier& identifier, const TGeoMatrix& transform, + TGeoNode* tGeoDetElement, const std::string& axes, double scalor, + bool isDisc, std::shared_ptr<const Acts::ISurfaceMaterial> material, std::shared_ptr<const Acts::DigitizationModule> digitizationModule) - : Acts::IdentifiedDetectorElement() - , m_detElement(tGeoDetElement) - , m_identifier(identifier) - , m_digitizationModule(std::move(digitizationModule)) -{ + : Acts::IdentifiedDetectorElement(), + m_detElement(tGeoDetElement), + m_identifier(identifier), + m_digitizationModule(std::move(digitizationModule)) { using namespace TGeoPrimitivesHelpers; // create temporary local non const surface (to allow setting the material) std::shared_ptr<Surface> surface = nullptr; // get the placement and orientation in respect to its mother - const Double_t* rotation = nullptr; + const Double_t* rotation = nullptr; const Double_t* translation = nullptr; // the new combined translation translation = transform.GetTranslation(); - rotation = transform.GetRotationMatrix(); + rotation = transform.GetRotationMatrix(); // create the translation - Vector3D colT(scalor * translation[0], - scalor * translation[1], + Vector3D colT(scalor * translation[0], scalor * translation[1], scalor * translation[2]); Vector3D colX(rotation[0], rotation[3], rotation[6]); Vector3D colY(rotation[1], rotation[4], rotation[7]); Vector3D colZ(rotation[2], rotation[5], rotation[8]); // check if it's a box - always true ... - TGeoBBox* box - = dynamic_cast<TGeoBBox*>(m_detElement->GetVolume()->GetShape()); + TGeoBBox* box = + dynamic_cast<TGeoBBox*>(m_detElement->GetVolume()->GetShape()); // check if it's a trapezoid - unfortunately box is the base of everything - TGeoTrd2* trapezoid - = dynamic_cast<TGeoTrd2*>(m_detElement->GetVolume()->GetShape()); + TGeoTrd2* trapezoid = + dynamic_cast<TGeoTrd2*>(m_detElement->GetVolume()->GetShape()); // check if it's a tube segment - TGeoTubeSeg* tube - = dynamic_cast<TGeoTubeSeg*>(m_detElement->GetVolume()->GetShape()); + TGeoTubeSeg* tube = + dynamic_cast<TGeoTubeSeg*>(m_detElement->GetVolume()->GetShape()); if (tube != nullptr) { m_transform = std::make_shared<const Transform3D>( makeTransform(colX, colY, colZ, colT)); - double rMin = tube->GetRmin() * scalor; - double rMax = tube->GetRmax() * scalor; + double rMin = tube->GetRmin() * scalor; + double rMax = tube->GetRmax() * scalor; double halfZ = tube->GetDz() * scalor; if (isDisc) { // create disc surface - m_thickness = halfZ; + m_thickness = halfZ; auto radialBounds = std::make_shared<const RadialBounds>(rMin, rMax); - m_bounds = radialBounds; - surface = Surface::makeShared<DiscSurface>(radialBounds, *this); + m_bounds = radialBounds; + surface = Surface::makeShared<DiscSurface>(radialBounds, *this); } else { // create a cylinder surface - m_thickness = std::fabs(rMax - rMin); + m_thickness = std::fabs(rMax - rMin); double radius = (rMin + rMax) * 0.5; - auto cylinderBounds - = std::make_shared<const CylinderBounds>(radius, halfZ); + auto cylinderBounds = + std::make_shared<const CylinderBounds>(radius, halfZ); m_bounds = cylinderBounds; - surface = Surface::makeShared<CylinderSurface>(cylinderBounds, *this); + surface = Surface::makeShared<CylinderSurface>(cylinderBounds, *this); } } else { if (boost::iequals(axes, "XYZ")) { @@ -472,8 +454,7 @@ Acts::TGeoDetectorElement::TGeoDetectorElement( if (trapezoid != nullptr) { // bounds with x/y auto trapezoidBounds = std::make_shared<const TrapezoidBounds>( - scalor * trapezoid->GetDx1(), - scalor * trapezoid->GetDx2(), + scalor * trapezoid->GetDx1(), scalor * trapezoid->GetDx2(), scalor * 0.5 * (trapezoid->GetDy1() + trapezoid->GetDy2())); // thickness m_thickness = scalor * trapezoid->GetDz(); @@ -516,12 +497,11 @@ Acts::TGeoDetectorElement::TGeoDetectorElement( if (trapezoid != nullptr) { // bounds with x/z auto trapezoidBounds = std::make_shared<const TrapezoidBounds>( - scalor * trapezoid->GetDx1(), - scalor * trapezoid->GetDx2(), + scalor * trapezoid->GetDx1(), scalor * trapezoid->GetDx2(), scalor * trapezoid->GetDz()); // thickness - m_thickness - = scalor * 0.5 * (trapezoid->GetDy1() + trapezoid->GetDy2()); + m_thickness = + scalor * 0.5 * (trapezoid->GetDy1() + trapezoid->GetDy2()); // assign them m_bounds = trapezoidBounds; // create the surface @@ -562,12 +542,11 @@ Acts::TGeoDetectorElement::TGeoDetectorElement( if (trapezoid != nullptr) { // bounds with y/z auto trapezoidBounds = std::make_shared<const TrapezoidBounds>( - scalor * trapezoid->GetDy1(), - scalor * trapezoid->GetDy2(), + scalor * trapezoid->GetDy1(), scalor * trapezoid->GetDy2(), scalor * trapezoid->GetDz()); // thickness - m_thickness - = scalor * 0.5 * (trapezoid->GetDx1() + trapezoid->GetDx2()); + m_thickness = + scalor * 0.5 * (trapezoid->GetDx1() + trapezoid->GetDx2()); // assign them m_bounds = trapezoidBounds; // create the surface @@ -607,8 +586,7 @@ Acts::TGeoDetectorElement::TGeoDetectorElement( if (trapezoid != nullptr) { // bounds with y/x auto trapezoidBounds = std::make_shared<const TrapezoidBounds>( - scalor * trapezoid->GetDy1(), - scalor * trapezoid->GetDy2(), + scalor * trapezoid->GetDy1(), scalor * trapezoid->GetDy2(), scalor * 0.5 * (trapezoid->GetDx1() + trapezoid->GetDx2())); // thickness m_thickness = scalor * trapezoid->GetDz(); @@ -651,12 +629,11 @@ Acts::TGeoDetectorElement::TGeoDetectorElement( if (trapezoid != nullptr) { // bounds with z/y auto trapezoidBounds = std::make_shared<const TrapezoidBounds>( - scalor * trapezoid->GetDz(), - scalor * trapezoid->GetDz(), + scalor * trapezoid->GetDz(), scalor * trapezoid->GetDz(), scalor * 0.5 * (trapezoid->GetDy1() + trapezoid->GetDy2())); // thickness - m_thickness - = scalor * 0.5 * (trapezoid->GetDx1() + trapezoid->GetDx2()); + m_thickness = + scalor * 0.5 * (trapezoid->GetDx1() + trapezoid->GetDx2()); // assign them m_bounds = trapezoidBounds; // create the surface @@ -697,12 +674,11 @@ Acts::TGeoDetectorElement::TGeoDetectorElement( if (trapezoid != nullptr) { // bounds with z/x auto trapezoidBounds = std::make_shared<const TrapezoidBounds>( - scalor * trapezoid->GetDz(), - scalor * trapezoid->GetDz(), + scalor * trapezoid->GetDz(), scalor * trapezoid->GetDz(), scalor * 0.5 * (trapezoid->GetDx1() + trapezoid->GetDx2())); // thickness - m_thickness - = scalor * 0.5 * (trapezoid->GetDy1() + trapezoid->GetDy2()); + m_thickness = + scalor * 0.5 * (trapezoid->GetDy1() + trapezoid->GetDy2()); // assign them m_bounds = trapezoidBounds; // create the surface diff --git a/Plugins/TGeo/src/TGeoLayerBuilder.cpp b/Plugins/TGeo/src/TGeoLayerBuilder.cpp index 444b61fb7f46adf5f6aebebf52c0ea050a2c9ef4..0cb91bce65b285636d69981b8be9a293f06b9abb 100644 --- a/Plugins/TGeo/src/TGeoLayerBuilder.cpp +++ b/Plugins/TGeo/src/TGeoLayerBuilder.cpp @@ -15,63 +15,52 @@ Acts::TGeoLayerBuilder::TGeoLayerBuilder( const Acts::TGeoLayerBuilder::Config& config, - std::unique_ptr<const Logger> logger) - : m_cfg(), m_logger(std::move(logger)) -{ + std::unique_ptr<const Logger> logger) + : m_cfg(), m_logger(std::move(logger)) { setConfiguration(config); } Acts::TGeoLayerBuilder::~TGeoLayerBuilder() = default; -void -Acts::TGeoLayerBuilder::setConfiguration( - const Acts::TGeoLayerBuilder::Config& config) -{ +void Acts::TGeoLayerBuilder::setConfiguration( + const Acts::TGeoLayerBuilder::Config& config) { m_cfg = config; } -void -Acts::TGeoLayerBuilder::setLogger(std::unique_ptr<const Logger> newLogger) -{ +void Acts::TGeoLayerBuilder::setLogger( + std::unique_ptr<const Logger> newLogger) { m_logger = std::move(newLogger); } -const Acts::LayerVector -Acts::TGeoLayerBuilder::negativeLayers(const GeometryContext& gctx) const -{ +const Acts::LayerVector Acts::TGeoLayerBuilder::negativeLayers( + const GeometryContext& gctx) const { // @todo Remove this hack once the m_elementStore mess is sorted out - auto mutableThis = const_cast<TGeoLayerBuilder*>(this); + auto mutableThis = const_cast<TGeoLayerBuilder*>(this); LayerVector nVector; mutableThis->buildLayers(gctx, nVector, -1); return nVector; } -const Acts::LayerVector -Acts::TGeoLayerBuilder::centralLayers(const GeometryContext& gctx) const -{ +const Acts::LayerVector Acts::TGeoLayerBuilder::centralLayers( + const GeometryContext& gctx) const { // @todo Remove this hack once the m_elementStore mess is sorted out - auto mutableThis = const_cast<TGeoLayerBuilder*>(this); + auto mutableThis = const_cast<TGeoLayerBuilder*>(this); LayerVector cVector; mutableThis->buildLayers(gctx, cVector, 0); return cVector; } -const Acts::LayerVector -Acts::TGeoLayerBuilder::positiveLayers(const GeometryContext& gctx) const -{ +const Acts::LayerVector Acts::TGeoLayerBuilder::positiveLayers( + const GeometryContext& gctx) const { // @todo Remove this hack once the m_elementStore mess is sorted out - auto mutableThis = const_cast<TGeoLayerBuilder*>(this); + auto mutableThis = const_cast<TGeoLayerBuilder*>(this); LayerVector pVector; mutableThis->buildLayers(gctx, pVector, -1); return pVector; } -void -Acts::TGeoLayerBuilder::buildLayers(const GeometryContext& gctx, - LayerVector& layers, - int type) -{ - +void Acts::TGeoLayerBuilder::buildLayers(const GeometryContext& gctx, + LayerVector& layers, int type) { // bail out if you have no gGeoManager if (gGeoManager == nullptr) { return; @@ -79,20 +68,20 @@ Acts::TGeoLayerBuilder::buildLayers(const GeometryContext& gctx, // Prepare which ones to build std::vector<LayerConfig> layerConfigs; - std::string layerType = "No"; + std::string layerType = "No"; switch (type) { - case -1: { - layerConfigs = m_cfg.negativeLayerConfigs; - layerType = "Negative"; - } break; - case 0: { - layerConfigs = m_cfg.centralLayerConfigs; - layerType = "Central"; - } break; - case 1: { - layerConfigs = m_cfg.positiveLayerConfigs; - layerType = "Positive"; - } break; + case -1: { + layerConfigs = m_cfg.negativeLayerConfigs; + layerType = "Negative"; + } break; + case 0: { + layerConfigs = m_cfg.centralLayerConfigs; + layerType = "Central"; + } break; + case 1: { + layerConfigs = m_cfg.positiveLayerConfigs; + layerType = "Positive"; + } break; } // screen output ACTS_DEBUG(layerType << " Layers : found " << layerConfigs.size() @@ -101,21 +90,15 @@ Acts::TGeoLayerBuilder::buildLayers(const GeometryContext& gctx, // prepare the layer surfaces std::vector<std::shared_ptr<const Surface>> layerSurfaces; - ACTS_DEBUG("- layer configuration found for layer " << layerCfg.layerName - << " with sensor " - << layerCfg.sensorName); + ACTS_DEBUG("- layer configuration found for layer " + << layerCfg.layerName << " with sensor " << layerCfg.sensorName); // we have to step down from the top volume each time to collect the logical // tree TGeoVolume* tvolume = gGeoManager->GetTopVolume(); if (tvolume != nullptr) { // recursively step down - resolveSensitive(gctx, - layerSurfaces, - tvolume, - nullptr, - TGeoIdentity(), - layerCfg, - type); + resolveSensitive(gctx, layerSurfaces, tvolume, nullptr, TGeoIdentity(), + layerCfg, type); // screen output ACTS_DEBUG( "- number of senstive sensors found : " << layerSurfaces.size()); @@ -137,18 +120,12 @@ Acts::TGeoLayerBuilder::buildLayers(const GeometryContext& gctx, } } -void -Acts::TGeoLayerBuilder::resolveSensitive( - const GeometryContext& gctx, +void Acts::TGeoLayerBuilder::resolveSensitive( + const GeometryContext& gctx, std::vector<std::shared_ptr<const Acts::Surface>>& layerSurfaces, - TGeoVolume* tgVolume, - TGeoNode* tgNode, - const TGeoMatrix& tgTransform, - const LayerConfig& layerConfig, - int type, - bool correctBranch, - const std::string& offset) -{ + TGeoVolume* tgVolume, TGeoNode* tgNode, const TGeoMatrix& tgTransform, + const LayerConfig& layerConfig, int type, bool correctBranch, + const std::string& offset) { /// some screen output for disk debugging if (type != 0) { const Double_t* ctranslation = tgTransform.GetTranslation(); @@ -164,9 +141,9 @@ Acts::TGeoLayerBuilder::resolveSensitive( // once in the current branch, always in the current branch bool correctVolume = correctBranch; - if (!correctVolume - && (volumeName.find(layerConfig.layerName) != std::string::npos - || match(layerConfig.layerName.c_str(), volumeName.c_str()))) { + if (!correctVolume && + (volumeName.find(layerConfig.layerName) != std::string::npos || + match(layerConfig.layerName.c_str(), volumeName.c_str()))) { correctVolume = true; ACTS_VERBOSE(offset << " triggered current branch!"); } @@ -182,15 +159,8 @@ Acts::TGeoLayerBuilder::resolveSensitive( // dynamic_cast to a node TGeoNode* node = dynamic_cast<TGeoNode*>(obj); if (node != nullptr) { - resolveSensitive(gctx, - layerSurfaces, - nullptr, - node, - tgTransform, - layerConfig, - type, - correctVolume, - offset + " "); + resolveSensitive(gctx, layerSurfaces, nullptr, node, tgTransform, + layerConfig, type, correctVolume, offset + " "); } } } else { @@ -212,12 +182,11 @@ Acts::TGeoLayerBuilder::resolveSensitive( << layerConfig.sensorName); // find out the branch hit - single layer depth is supported by // sensor==layer - bool branchHit - = correctBranch || (layerConfig.sensorName == layerConfig.layerName); - if (branchHit - && (tNodeName.find(layerConfig.sensorName) != std::string::npos - || match(layerConfig.sensorName.c_str(), tNodeName.c_str()))) { - + bool branchHit = + correctBranch || (layerConfig.sensorName == layerConfig.layerName); + if (branchHit && + (tNodeName.find(layerConfig.sensorName) != std::string::npos || + match(layerConfig.sensorName.c_str(), tNodeName.c_str()))) { ACTS_VERBOSE(offset << "Sensor name found in correct branch."); // set the visibility to kTrue @@ -230,10 +199,7 @@ Acts::TGeoLayerBuilder::resolveSensitive( ACTS_VERBOSE(offset << "[>>] accepted !"); // create the element auto tgElement = std::make_shared<const Acts::TGeoDetectorElement>( - Identifier(), - tgNode, - &tgTransform, - layerConfig.localAxes, + Identifier(), tgNode, &tgTransform, layerConfig.localAxes, m_cfg.unit); // record the element @todo solve with provided cache m_elementStore.push_back(tgElement); @@ -254,22 +220,15 @@ Acts::TGeoLayerBuilder::resolveSensitive( ACTS_VERBOSE(offset << " node translation in z = " << z); } // build the matrix - TGeoHMatrix nTransform - = TGeoCombiTrans(tgTransform) * TGeoCombiTrans(*tgMatrix); + TGeoHMatrix nTransform = + TGeoCombiTrans(tgTransform) * TGeoCombiTrans(*tgMatrix); std::string suffix = "_transform"; nTransform.SetName((tNodeName + suffix).c_str()); // if it's not accepted, get the associated volume TGeoVolume* nodeVolume = tgNode->GetVolume(); // step down one further - resolveSensitive(gctx, - layerSurfaces, - nodeVolume, - nullptr, - nTransform, - layerConfig, - type, - correctBranch, - offset + " "); + resolveSensitive(gctx, layerSurfaces, nodeVolume, nullptr, nTransform, + layerConfig, type, correctBranch, offset + " "); } } else { ACTS_VERBOSE("No node present."); diff --git a/Tests/Core/CommonHelpers/include/Acts/Tests/CommonHelpers/CubicTrackingGeometry.hpp b/Tests/Core/CommonHelpers/include/Acts/Tests/CommonHelpers/CubicTrackingGeometry.hpp index 56a281eab158e8e91cbd53d4509b95523e184539..b5d0ea624fa669a54a547a8552f62a800dbe65d2 100644 --- a/Tests/Core/CommonHelpers/include/Acts/Tests/CommonHelpers/CubicTrackingGeometry.hpp +++ b/Tests/Core/CommonHelpers/include/Acts/Tests/CommonHelpers/CubicTrackingGeometry.hpp @@ -27,194 +27,167 @@ namespace Acts { namespace Test { - struct CubicTrackingGeometry - { - - /// Default constructor for the Cubit tracking geometry - /// - /// @param gctx the geometry context for this geometry at building time - CubicTrackingGeometry(std::reference_wrapper<const GeometryContext> gctx) - : geoContext(gctx) - { - // Construct the rotation - double rotationAngle = M_PI * 0.5; - Vector3D xPos(cos(rotationAngle), 0., sin(rotationAngle)); - Vector3D yPos(0., 1., 0.); - Vector3D zPos(-sin(rotationAngle), 0., cos(rotationAngle)); - rotation.col(0) = xPos; - rotation.col(1) = yPos; - rotation.col(2) = zPos; - - // Boundaries of the surfaces - rBounds = std::make_shared<const RectangleBounds>( - RectangleBounds(0.5 * units::_m, 0.5 * units::_m)); - - // Material of the surfaces - MaterialProperties matProp( - 352.8, 407., 9.012, 4., 1.848e-3, 0.5 * units::_mm); - surfaceMaterial = std::shared_ptr<const ISurfaceMaterial>( - new HomogeneousSurfaceMaterial(matProp)); +struct CubicTrackingGeometry { + /// Default constructor for the Cubit tracking geometry + /// + /// @param gctx the geometry context for this geometry at building time + CubicTrackingGeometry(std::reference_wrapper<const GeometryContext> gctx) + : geoContext(gctx) { + // Construct the rotation + double rotationAngle = M_PI * 0.5; + Vector3D xPos(cos(rotationAngle), 0., sin(rotationAngle)); + Vector3D yPos(0., 1., 0.); + Vector3D zPos(-sin(rotationAngle), 0., cos(rotationAngle)); + rotation.col(0) = xPos; + rotation.col(1) = yPos; + rotation.col(2) = zPos; + + // Boundaries of the surfaces + rBounds = std::make_shared<const RectangleBounds>( + RectangleBounds(0.5 * units::_m, 0.5 * units::_m)); + + // Material of the surfaces + MaterialProperties matProp(352.8, 407., 9.012, 4., 1.848e-3, + 0.5 * units::_mm); + surfaceMaterial = std::shared_ptr<const ISurfaceMaterial>( + new HomogeneousSurfaceMaterial(matProp)); + } + + /// Call operator to build the standard cubic tracking geometry + std::shared_ptr<const TrackingGeometry> operator()() { + // Set translation vectors + double eps = 1. * units::_mm; + std::vector<Vector3D> translations; + translations.push_back({-2. * units::_m, 0., 0.}); + translations.push_back({-1. * units::_m, 0., 0.}); + translations.push_back({1. * units::_m - eps, 0., 0.}); + translations.push_back({1. * units::_m + eps, 0., 0.}); + translations.push_back({2. * units::_m - eps, 0., 0.}); + translations.push_back({2. * units::_m + eps, 0., 0.}); + + // Construct surfaces + std::array<std::shared_ptr<const Surface>, 6> surfaces; + unsigned int i; + for (i = 0; i < translations.size(); i++) { + Transform3D trafo(Transform3D::Identity() * rotation); + trafo.translation() = translations[i]; + // Create the detector element + auto detElement = std::make_unique<const DetectorElementStub>( + std::make_shared<const Transform3D>(trafo), rBounds, 1. * units::_um, + surfaceMaterial); + // And remember the surface + surfaces[i] = detElement->surface().getSharedPtr(); + // Add it to the event store + detectorStore.push_back(std::move(detElement)); } - /// Call operator to build the standard cubic tracking geometry - std::shared_ptr<const TrackingGeometry> - operator()() - { - // Set translation vectors - double eps = 1. * units::_mm; - std::vector<Vector3D> translations; - translations.push_back({-2. * units::_m, 0., 0.}); - translations.push_back({-1. * units::_m, 0., 0.}); - translations.push_back({1. * units::_m - eps, 0., 0.}); - translations.push_back({1. * units::_m + eps, 0., 0.}); - translations.push_back({2. * units::_m - eps, 0., 0.}); - translations.push_back({2. * units::_m + eps, 0., 0.}); - - // Construct surfaces - std::array<std::shared_ptr<const Surface>, 6> surfaces; - unsigned int i; - for (i = 0; i < translations.size(); i++) { - Transform3D trafo(Transform3D::Identity() * rotation); - trafo.translation() = translations[i]; - // Create the detector element - auto detElement = std::make_unique<const DetectorElementStub>( - std::make_shared<const Transform3D>(trafo), - rBounds, - 1. * units::_um, - surfaceMaterial); - // And remember the surface - surfaces[i] = detElement->surface().getSharedPtr(); - // Add it to the event store - detectorStore.push_back(std::move(detElement)); - } - - // Construct layers - std::array<LayerPtr, 6> layers; - for (i = 0; i < 6; i++) { - Transform3D trafo(Transform3D::Identity() * rotation); - trafo.translation() = translations[i]; - - std::unique_ptr<SurfaceArray> surArray(new SurfaceArray(surfaces[i])); - - layers[i] - = PlaneLayer::create(std::make_shared<const Transform3D>(trafo), - rBounds, - std::move(surArray), - 1. * units::_mm); - - auto mutableSurface = const_cast<Surface*>(surfaces[i].get()); - mutableSurface->associateLayer(*layers[i]); - } - - // Build volume for surfaces with negative x-values - Transform3D trafoVol1(Transform3D::Identity()); - trafoVol1.translation() = Vector3D(-1.5 * units::_m, 0., 0.); - - auto boundsVol = std::make_shared<const CuboidVolumeBounds>( - 1.5 * units::_m, 0.5 * units::_m, 0.5 * units::_m); - - LayerArrayCreator::Config lacConfig; - LayerArrayCreator layArrCreator( - lacConfig, getDefaultLogger("LayerArrayCreator", Logging::INFO)); - - LayerVector layVec; - layVec.push_back(layers[0]); - layVec.push_back(layers[1]); - std::unique_ptr<const LayerArray> layArr1( - layArrCreator.layerArray(geoContext, - layVec, - -2. * units::_m - 1. * units::_mm, - -1. * units::_m + 1. * units::_mm, - BinningType::arbitrary, - BinningValue::binX)); - - auto trackVolume1 = TrackingVolume::create( - std::make_shared<const Transform3D>(trafoVol1), - boundsVol, - nullptr, - std::move(layArr1), - nullptr, - "Volume 1"); - trackVolume1->sign(GeometrySignature::Global); - - // Build volume for surfaces with positive x-values - Transform3D trafoVol2(Transform3D::Identity()); - trafoVol2.translation() = Vector3D(1.5 * units::_m, 0., 0.); - - layVec.clear(); - for (i = 2; i < 6; i++) layVec.push_back(layers[i]); - std::unique_ptr<const LayerArray> layArr2( - layArrCreator.layerArray(geoContext, - layVec, - 1. * units::_m - 2. * units::_mm, - 2. * units::_m + 2. * units::_mm, - BinningType::arbitrary, - BinningValue::binX)); - - auto trackVolume2 = TrackingVolume::create( - std::make_shared<const Transform3D>(trafoVol2), - boundsVol, - nullptr, - std::move(layArr2), - nullptr, - "Volume 2"); - - trackVolume2->sign(GeometrySignature::Global); - - // Glue volumes - trackVolume2->glueTrackingVolume(geoContext, - BoundarySurfaceFace::negativeFaceYZ, - trackVolume1, - BoundarySurfaceFace::positiveFaceYZ); - - trackVolume1->glueTrackingVolume(geoContext, - BoundarySurfaceFace::positiveFaceYZ, - trackVolume2, - BoundarySurfaceFace::negativeFaceYZ); - - // Build world volume - Transform3D trafoWorld(Transform3D::Identity()); - trafoWorld.translation() = Vector3D(0., 0., 0.); - - auto worldVol = std::make_shared<const CuboidVolumeBounds>( - 3. * units::_m, 0.5 * units::_m, 0.5 * units::_m); - - std::vector<std::pair<TrackingVolumePtr, Vector3D>> tapVec; - - tapVec.push_back( - std::make_pair(trackVolume1, Vector3D(-1.5 * units::_m, 0., 0.))); - tapVec.push_back( - std::make_pair(trackVolume2, Vector3D(1.5 * units::_m, 0., 0.))); - - std::vector<float> binBoundaries = {-3. * units::_m, 0., 3. * units::_m}; - - BinningData binData( - BinningOption::open, BinningValue::binX, binBoundaries); - std::unique_ptr<const BinUtility> bu(new BinUtility(binData)); - - std::shared_ptr<const TrackingVolumeArray> trVolArr( - new BinnedArrayXD<TrackingVolumePtr>(tapVec, std::move(bu))); - - MutableTrackingVolumePtr mtvpWorld(TrackingVolume::create( - std::make_shared<const Transform3D>(trafoWorld), - worldVol, - trVolArr, - "World")); - - mtvpWorld->sign(GeometrySignature::Global); - - // Build and return tracking geometry - return std::shared_ptr<TrackingGeometry>( - new Acts::TrackingGeometry(mtvpWorld)); + // Construct layers + std::array<LayerPtr, 6> layers; + for (i = 0; i < 6; i++) { + Transform3D trafo(Transform3D::Identity() * rotation); + trafo.translation() = translations[i]; + + std::unique_ptr<SurfaceArray> surArray(new SurfaceArray(surfaces[i])); + + layers[i] = + PlaneLayer::create(std::make_shared<const Transform3D>(trafo), + rBounds, std::move(surArray), 1. * units::_mm); + + auto mutableSurface = const_cast<Surface*>(surfaces[i].get()); + mutableSurface->associateLayer(*layers[i]); } - RotationMatrix3D rotation = RotationMatrix3D::Identity(); - std::shared_ptr<const RectangleBounds> rBounds = nullptr; - std::shared_ptr<const ISurfaceMaterial> surfaceMaterial = nullptr; + // Build volume for surfaces with negative x-values + Transform3D trafoVol1(Transform3D::Identity()); + trafoVol1.translation() = Vector3D(-1.5 * units::_m, 0., 0.); + + auto boundsVol = std::make_shared<const CuboidVolumeBounds>( + 1.5 * units::_m, 0.5 * units::_m, 0.5 * units::_m); + + LayerArrayCreator::Config lacConfig; + LayerArrayCreator layArrCreator( + lacConfig, getDefaultLogger("LayerArrayCreator", Logging::INFO)); + + LayerVector layVec; + layVec.push_back(layers[0]); + layVec.push_back(layers[1]); + std::unique_ptr<const LayerArray> layArr1(layArrCreator.layerArray( + geoContext, layVec, -2. * units::_m - 1. * units::_mm, + -1. * units::_m + 1. * units::_mm, BinningType::arbitrary, + BinningValue::binX)); + + auto trackVolume1 = TrackingVolume::create( + std::make_shared<const Transform3D>(trafoVol1), boundsVol, nullptr, + std::move(layArr1), nullptr, "Volume 1"); + trackVolume1->sign(GeometrySignature::Global); + + // Build volume for surfaces with positive x-values + Transform3D trafoVol2(Transform3D::Identity()); + trafoVol2.translation() = Vector3D(1.5 * units::_m, 0., 0.); + + layVec.clear(); + for (i = 2; i < 6; i++) + layVec.push_back(layers[i]); + std::unique_ptr<const LayerArray> layArr2(layArrCreator.layerArray( + geoContext, layVec, 1. * units::_m - 2. * units::_mm, + 2. * units::_m + 2. * units::_mm, BinningType::arbitrary, + BinningValue::binX)); + + auto trackVolume2 = TrackingVolume::create( + std::make_shared<const Transform3D>(trafoVol2), boundsVol, nullptr, + std::move(layArr2), nullptr, "Volume 2"); + + trackVolume2->sign(GeometrySignature::Global); + + // Glue volumes + trackVolume2->glueTrackingVolume( + geoContext, BoundarySurfaceFace::negativeFaceYZ, trackVolume1, + BoundarySurfaceFace::positiveFaceYZ); + + trackVolume1->glueTrackingVolume( + geoContext, BoundarySurfaceFace::positiveFaceYZ, trackVolume2, + BoundarySurfaceFace::negativeFaceYZ); + + // Build world volume + Transform3D trafoWorld(Transform3D::Identity()); + trafoWorld.translation() = Vector3D(0., 0., 0.); + + auto worldVol = std::make_shared<const CuboidVolumeBounds>( + 3. * units::_m, 0.5 * units::_m, 0.5 * units::_m); + + std::vector<std::pair<TrackingVolumePtr, Vector3D>> tapVec; + + tapVec.push_back( + std::make_pair(trackVolume1, Vector3D(-1.5 * units::_m, 0., 0.))); + tapVec.push_back( + std::make_pair(trackVolume2, Vector3D(1.5 * units::_m, 0., 0.))); + + std::vector<float> binBoundaries = {-3. * units::_m, 0., 3. * units::_m}; + + BinningData binData(BinningOption::open, BinningValue::binX, binBoundaries); + std::unique_ptr<const BinUtility> bu(new BinUtility(binData)); + + std::shared_ptr<const TrackingVolumeArray> trVolArr( + new BinnedArrayXD<TrackingVolumePtr>(tapVec, std::move(bu))); + + MutableTrackingVolumePtr mtvpWorld( + TrackingVolume::create(std::make_shared<const Transform3D>(trafoWorld), + worldVol, trVolArr, "World")); + + mtvpWorld->sign(GeometrySignature::Global); + + // Build and return tracking geometry + return std::shared_ptr<TrackingGeometry>( + new Acts::TrackingGeometry(mtvpWorld)); + } + + RotationMatrix3D rotation = RotationMatrix3D::Identity(); + std::shared_ptr<const RectangleBounds> rBounds = nullptr; + std::shared_ptr<const ISurfaceMaterial> surfaceMaterial = nullptr; - std::vector<std::unique_ptr<const DetectorElementStub>> detectorStore = {}; + std::vector<std::unique_ptr<const DetectorElementStub>> detectorStore = {}; - std::reference_wrapper<const GeometryContext> geoContext; - }; + std::reference_wrapper<const GeometryContext> geoContext; +}; } // namespace Test } // namespace Acts diff --git a/Tests/Core/CommonHelpers/include/Acts/Tests/CommonHelpers/CylindricalTrackingGeometry.hpp b/Tests/Core/CommonHelpers/include/Acts/Tests/CommonHelpers/CylindricalTrackingGeometry.hpp index 7227413cf60c8cf8f50828f1a0e1dd72614ffd7d..9346841aa03f72b7d5b45abb5bcc9e3ab1c63abb 100644 --- a/Tests/Core/CommonHelpers/include/Acts/Tests/CommonHelpers/CylindricalTrackingGeometry.hpp +++ b/Tests/Core/CommonHelpers/include/Acts/Tests/CommonHelpers/CylindricalTrackingGeometry.hpp @@ -36,238 +36,211 @@ namespace Acts { namespace Test { - struct CylindricalTrackingGeometry - { - - std::reference_wrapper<const GeometryContext> geoContext; - - /// Only allowed constructor with reference wrapper - CylindricalTrackingGeometry( - std::reference_wrapper<const GeometryContext> gctx) - : geoContext(gctx) - { - } - - /// The detector store for memory management - std::vector<std::unique_ptr<const DetectorElementStub>> detectorStore = {}; - - /// helper method for cylinder layer - /// create the positions for module surfaces on a cylinder - std::vector<Vector3D> - modulePositionsCylinder(double radius, - double zStagger, - double moduleHalfLength, - double lOverlap, - const std::pair<int, int>& binningSchema) - { - int nPhiBins = binningSchema.first; - int nZbins = binningSchema.second; - // prepare the return value - std::vector<Vector3D> mPositions; - mPositions.reserve(nPhiBins * nZbins); - // prep work - double phiStep = 2 * M_PI / (nPhiBins); - double minPhi = -M_PI + 0.5 * phiStep; - double zStart = -0.5 * (nZbins - 1) * (2 * moduleHalfLength - lOverlap); - double zStep = 2 * std::abs(zStart) / (nZbins - 1); - // loop over the bins - for (size_t zBin = 0; zBin < size_t(nZbins); ++zBin) { - // prepare z and r - double moduleZ = zStart + zBin * zStep; - double moduleR = (zBin % 2) != 0u ? radius - 0.5 * zStagger - : radius + 0.5 * zStagger; - for (size_t phiBin = 0; phiBin < size_t(nPhiBins); ++phiBin) { - // calculate the current phi value - double modulePhi = minPhi + phiBin * phiStep; - mPositions.push_back(Vector3D( - moduleR * cos(modulePhi), moduleR * sin(modulePhi), moduleZ)); - } +struct CylindricalTrackingGeometry { + std::reference_wrapper<const GeometryContext> geoContext; + + /// Only allowed constructor with reference wrapper + CylindricalTrackingGeometry( + std::reference_wrapper<const GeometryContext> gctx) + : geoContext(gctx) {} + + /// The detector store for memory management + std::vector<std::unique_ptr<const DetectorElementStub>> detectorStore = {}; + + /// helper method for cylinder layer + /// create the positions for module surfaces on a cylinder + std::vector<Vector3D> modulePositionsCylinder( + double radius, double zStagger, double moduleHalfLength, double lOverlap, + const std::pair<int, int>& binningSchema) { + int nPhiBins = binningSchema.first; + int nZbins = binningSchema.second; + // prepare the return value + std::vector<Vector3D> mPositions; + mPositions.reserve(nPhiBins * nZbins); + // prep work + double phiStep = 2 * M_PI / (nPhiBins); + double minPhi = -M_PI + 0.5 * phiStep; + double zStart = -0.5 * (nZbins - 1) * (2 * moduleHalfLength - lOverlap); + double zStep = 2 * std::abs(zStart) / (nZbins - 1); + // loop over the bins + for (size_t zBin = 0; zBin < size_t(nZbins); ++zBin) { + // prepare z and r + double moduleZ = zStart + zBin * zStep; + double moduleR = + (zBin % 2) != 0u ? radius - 0.5 * zStagger : radius + 0.5 * zStagger; + for (size_t phiBin = 0; phiBin < size_t(nPhiBins); ++phiBin) { + // calculate the current phi value + double modulePhi = minPhi + phiBin * phiStep; + mPositions.push_back(Vector3D(moduleR * cos(modulePhi), + moduleR * sin(modulePhi), moduleZ)); } - return mPositions; - } - - // @brief Call operator for the creation method of the tracking geometry - std::shared_ptr<const TrackingGeometry> - operator()() - { - - Logging::Level surfaceLLevel = Logging::INFO; - Logging::Level layerLLevel = Logging::INFO; - Logging::Level volumeLLevel = Logging::INFO; - - // configure surface array creator - auto surfaceArrayCreator = std::make_shared<const SurfaceArrayCreator>( - getDefaultLogger("SurfaceArrayCreator", surfaceLLevel)); - // configure the layer creator that uses the surface array creator - LayerCreator::Config lcConfig; - lcConfig.surfaceArrayCreator = surfaceArrayCreator; - auto layerCreator = std::make_shared<const LayerCreator>( - lcConfig, getDefaultLogger("LayerCreator", layerLLevel)); - // configure the layer array creator - LayerArrayCreator::Config lacConfig; - auto layerArrayCreator = std::make_shared<const LayerArrayCreator>( - lacConfig, getDefaultLogger("LayerArrayCreator", layerLLevel)); - - // tracking volume array creator - TrackingVolumeArrayCreator::Config tvacConfig; - auto tVolumeArrayCreator - = std::make_shared<const TrackingVolumeArrayCreator>( - tvacConfig, - getDefaultLogger("TrackingVolumeArrayCreator", volumeLLevel)); - // configure the cylinder volume helper - CylinderVolumeHelper::Config cvhConfig; - cvhConfig.layerArrayCreator = layerArrayCreator; - cvhConfig.trackingVolumeArrayCreator = tVolumeArrayCreator; - auto cylinderVolumeHelper = std::make_shared<const CylinderVolumeHelper>( - cvhConfig, getDefaultLogger("CylinderVolumeHelper", volumeLLevel)); - - // ----------------- build a beam pipe ----------------------------------- - MaterialProperties beamPipeMaterial{ - 352.8, 407., 9.012, 4., 1.848e-3, 0.8}; - PassiveLayerBuilder::Config bplConfig; - bplConfig.layerIdentification = "BeamPipe"; - bplConfig.centralLayerRadii = std::vector<double>(1, 19.); - bplConfig.centralLayerHalflengthZ = std::vector<double>(1, 1000.); - bplConfig.centralLayerThickness = std::vector<double>(1, 0.8); - bplConfig.centralLayerMaterial = { - std::make_shared<const HomogeneousSurfaceMaterial>(beamPipeMaterial)}; - auto beamPipeBuilder = std::make_shared<const PassiveLayerBuilder>( - bplConfig, getDefaultLogger("BeamPipeLayerBuilder", layerLLevel)); - // create the volume for the beam pipe - CylinderVolumeBuilder::Config bpvConfig; - bpvConfig.trackingVolumeHelper = cylinderVolumeHelper; - bpvConfig.volumeName = "BeamPipe"; - bpvConfig.layerBuilder = beamPipeBuilder; - bpvConfig.layerEnvelopeR = {1. * units::_mm, 1. * units::_mm}; - bpvConfig.buildToRadiusZero = true; - bpvConfig.volumeSignature = 0; - auto beamPipeVolumeBuilder - = std::make_shared<const CylinderVolumeBuilder>( - bpvConfig, - getDefaultLogger("BeamPipeVolumeBuilder", volumeLLevel)); - - // create the bounds and the volume - auto beamPipeBounds - = std::make_shared<const CylinderVolumeBounds>(0., 25., 1100.); - auto beamPipeVolume = beamPipeVolumeBuilder->trackingVolume( - geoContext, nullptr, beamPipeBounds); - - //------------------------------------------------------------------------------------- - // some prep work for the material - // Layer material properties - thickness, X0, L0, A, Z, Rho - MaterialProperties lProperties( - 95.7, 465.2, 28.03, 14., 2.32e-3, 1.5 * units::_mm); - - std::shared_ptr<const ISurfaceMaterial> layerMaterialPtr - = std::shared_ptr<const ISurfaceMaterial>( - new Acts::HomogeneousSurfaceMaterial(lProperties)); - - // Module material - X0, L0, A, Z, Rho - Material pcMaterial(95.7, 465.2, 28.03, 14., 2.32e-3); - - std::vector<double> pLayerRadii = {32., 72., 116., 172.}; - std::vector<std::pair<int, int>> pLayerBinning - = {{16, 14}, {32, 14}, {52, 14}, {78, 14}}; - std::vector<double> pModuleTiltPhi = {0.145, 0.145, 0.145, 0.145}; - std::vector<double> pModuleHalfX = {8.4, 8.4, 8.4, 8.4}; - std::vector<double> pModuleHalfY = {36., 36., 36., 36.}; - std::vector<double> pModuleThickness = {0.15, 0.15, 0.15, 0.15}; - - std::vector<LayerPtr> pLayers; - - for (size_t ilp = 0; ilp < pLayerRadii.size(); ++ilp) { - - std::vector<std::shared_ptr<const Surface>> layerModules; - - // Module material from input - MaterialProperties moduleMaterialProperties(pcMaterial, - pModuleThickness[ilp]); - // Create a new surface material - std::shared_ptr<const ISurfaceMaterial> moduleMaterialPtr - = std::shared_ptr<const ISurfaceMaterial>( - new Acts::HomogeneousSurfaceMaterial(moduleMaterialProperties)); - - // The rectangle bounds for all modules - auto mBounds = std::make_shared<RectangleBounds>(pModuleHalfX[ilp], - pModuleHalfY[ilp]); - // Create the module centers - auto moduleCenters = modulePositionsCylinder(pLayerRadii[ilp], - 2. * units::_mm, - pModuleHalfY[ilp], - 5. * units::_mm, - pLayerBinning[ilp]); - - for (auto& mCenter : moduleCenters) { - // The association transform - double modulePhi = VectorHelpers::phi(mCenter); - // Local z axis is the normal vector - Vector3D moduleLocalZ(cos(modulePhi + pModuleTiltPhi[ilp]), - sin(modulePhi + pModuleTiltPhi[ilp]), - 0.); - // Local y axis is the global z axis - Vector3D moduleLocalY(0., 0., 1); - // Local x axis the normal to local y,z - Vector3D moduleLocalX(-sin(modulePhi + pModuleTiltPhi[ilp]), - cos(modulePhi + pModuleTiltPhi[ilp]), - 0.); - // Create the RotationMatrix - RotationMatrix3D moduleRotation; - moduleRotation.col(0) = moduleLocalX; - moduleRotation.col(1) = moduleLocalY; - moduleRotation.col(2) = moduleLocalZ; - // Get the moduleTransform - std::shared_ptr<Transform3D> mModuleTransform - = std::make_shared<Transform3D>(Translation3D(mCenter) - * moduleRotation); - // Create the detector element - auto detElement = std::make_unique<const DetectorElementStub>( - mModuleTransform, - mBounds, - pModuleThickness[ilp], - moduleMaterialPtr); - - layerModules.push_back(detElement->surface().getSharedPtr()); - detectorStore.push_back(std::move(detElement)); - } - // create the layer and store it - ProtoLayer protoLayer(geoContext, layerModules); - protoLayer.envR = {0.5, 0.5}; - auto pLayer = layerCreator->cylinderLayer(geoContext, - std::move(layerModules), - pLayerBinning[ilp].first, - pLayerBinning[ilp].second, - protoLayer); - auto approachSurfaces - = pLayer->approachDescriptor()->containedSurfaces(); - auto mutableOuterSurface - = const_cast<Acts::Surface*>(approachSurfaces.at(1)); - mutableOuterSurface->assignSurfaceMaterial(layerMaterialPtr); - /// now push back the layer - pLayers.push_back(pLayer); - - } // loop over layers - - // layer array - auto pLayerArray = layerArrayCreator->layerArray( - geoContext, pLayers, 25., 300., arbitrary, binR); - auto pVolumeBounds - = std::make_shared<const CylinderVolumeBounds>(25., 300., 1100.); - // create the Tracking volume - auto pVolume = TrackingVolume::create(nullptr, - pVolumeBounds, - nullptr, - std::move(pLayerArray), - nullptr, - "Pixel::Barrel"); - - // The combined volume - auto detectorVolume = cylinderVolumeHelper->createContainerTrackingVolume( - geoContext, {beamPipeVolume, pVolume}); - - // create and return the geometry - return std::make_shared<const TrackingGeometry>(detectorVolume); } - }; + return mPositions; + } + + // @brief Call operator for the creation method of the tracking geometry + std::shared_ptr<const TrackingGeometry> operator()() { + Logging::Level surfaceLLevel = Logging::INFO; + Logging::Level layerLLevel = Logging::INFO; + Logging::Level volumeLLevel = Logging::INFO; + + // configure surface array creator + auto surfaceArrayCreator = std::make_shared<const SurfaceArrayCreator>( + getDefaultLogger("SurfaceArrayCreator", surfaceLLevel)); + // configure the layer creator that uses the surface array creator + LayerCreator::Config lcConfig; + lcConfig.surfaceArrayCreator = surfaceArrayCreator; + auto layerCreator = std::make_shared<const LayerCreator>( + lcConfig, getDefaultLogger("LayerCreator", layerLLevel)); + // configure the layer array creator + LayerArrayCreator::Config lacConfig; + auto layerArrayCreator = std::make_shared<const LayerArrayCreator>( + lacConfig, getDefaultLogger("LayerArrayCreator", layerLLevel)); + + // tracking volume array creator + TrackingVolumeArrayCreator::Config tvacConfig; + auto tVolumeArrayCreator = + std::make_shared<const TrackingVolumeArrayCreator>( + tvacConfig, + getDefaultLogger("TrackingVolumeArrayCreator", volumeLLevel)); + // configure the cylinder volume helper + CylinderVolumeHelper::Config cvhConfig; + cvhConfig.layerArrayCreator = layerArrayCreator; + cvhConfig.trackingVolumeArrayCreator = tVolumeArrayCreator; + auto cylinderVolumeHelper = std::make_shared<const CylinderVolumeHelper>( + cvhConfig, getDefaultLogger("CylinderVolumeHelper", volumeLLevel)); + + // ----------------- build a beam pipe ----------------------------------- + MaterialProperties beamPipeMaterial{352.8, 407., 9.012, 4., 1.848e-3, 0.8}; + PassiveLayerBuilder::Config bplConfig; + bplConfig.layerIdentification = "BeamPipe"; + bplConfig.centralLayerRadii = std::vector<double>(1, 19.); + bplConfig.centralLayerHalflengthZ = std::vector<double>(1, 1000.); + bplConfig.centralLayerThickness = std::vector<double>(1, 0.8); + bplConfig.centralLayerMaterial = { + std::make_shared<const HomogeneousSurfaceMaterial>(beamPipeMaterial)}; + auto beamPipeBuilder = std::make_shared<const PassiveLayerBuilder>( + bplConfig, getDefaultLogger("BeamPipeLayerBuilder", layerLLevel)); + // create the volume for the beam pipe + CylinderVolumeBuilder::Config bpvConfig; + bpvConfig.trackingVolumeHelper = cylinderVolumeHelper; + bpvConfig.volumeName = "BeamPipe"; + bpvConfig.layerBuilder = beamPipeBuilder; + bpvConfig.layerEnvelopeR = {1. * units::_mm, 1. * units::_mm}; + bpvConfig.buildToRadiusZero = true; + bpvConfig.volumeSignature = 0; + auto beamPipeVolumeBuilder = std::make_shared<const CylinderVolumeBuilder>( + bpvConfig, getDefaultLogger("BeamPipeVolumeBuilder", volumeLLevel)); + + // create the bounds and the volume + auto beamPipeBounds = + std::make_shared<const CylinderVolumeBounds>(0., 25., 1100.); + auto beamPipeVolume = beamPipeVolumeBuilder->trackingVolume( + geoContext, nullptr, beamPipeBounds); + + //------------------------------------------------------------------------------------- + // some prep work for the material + // Layer material properties - thickness, X0, L0, A, Z, Rho + MaterialProperties lProperties(95.7, 465.2, 28.03, 14., 2.32e-3, + 1.5 * units::_mm); + + std::shared_ptr<const ISurfaceMaterial> layerMaterialPtr = + std::shared_ptr<const ISurfaceMaterial>( + new Acts::HomogeneousSurfaceMaterial(lProperties)); + + // Module material - X0, L0, A, Z, Rho + Material pcMaterial(95.7, 465.2, 28.03, 14., 2.32e-3); + + std::vector<double> pLayerRadii = {32., 72., 116., 172.}; + std::vector<std::pair<int, int>> pLayerBinning = { + {16, 14}, {32, 14}, {52, 14}, {78, 14}}; + std::vector<double> pModuleTiltPhi = {0.145, 0.145, 0.145, 0.145}; + std::vector<double> pModuleHalfX = {8.4, 8.4, 8.4, 8.4}; + std::vector<double> pModuleHalfY = {36., 36., 36., 36.}; + std::vector<double> pModuleThickness = {0.15, 0.15, 0.15, 0.15}; + + std::vector<LayerPtr> pLayers; + + for (size_t ilp = 0; ilp < pLayerRadii.size(); ++ilp) { + std::vector<std::shared_ptr<const Surface>> layerModules; + + // Module material from input + MaterialProperties moduleMaterialProperties(pcMaterial, + pModuleThickness[ilp]); + // Create a new surface material + std::shared_ptr<const ISurfaceMaterial> moduleMaterialPtr = + std::shared_ptr<const ISurfaceMaterial>( + new Acts::HomogeneousSurfaceMaterial(moduleMaterialProperties)); + + // The rectangle bounds for all modules + auto mBounds = std::make_shared<RectangleBounds>(pModuleHalfX[ilp], + pModuleHalfY[ilp]); + // Create the module centers + auto moduleCenters = modulePositionsCylinder( + pLayerRadii[ilp], 2. * units::_mm, pModuleHalfY[ilp], 5. * units::_mm, + pLayerBinning[ilp]); + + for (auto& mCenter : moduleCenters) { + // The association transform + double modulePhi = VectorHelpers::phi(mCenter); + // Local z axis is the normal vector + Vector3D moduleLocalZ(cos(modulePhi + pModuleTiltPhi[ilp]), + sin(modulePhi + pModuleTiltPhi[ilp]), 0.); + // Local y axis is the global z axis + Vector3D moduleLocalY(0., 0., 1); + // Local x axis the normal to local y,z + Vector3D moduleLocalX(-sin(modulePhi + pModuleTiltPhi[ilp]), + cos(modulePhi + pModuleTiltPhi[ilp]), 0.); + // Create the RotationMatrix + RotationMatrix3D moduleRotation; + moduleRotation.col(0) = moduleLocalX; + moduleRotation.col(1) = moduleLocalY; + moduleRotation.col(2) = moduleLocalZ; + // Get the moduleTransform + std::shared_ptr<Transform3D> mModuleTransform = + std::make_shared<Transform3D>(Translation3D(mCenter) * + moduleRotation); + // Create the detector element + auto detElement = std::make_unique<const DetectorElementStub>( + mModuleTransform, mBounds, pModuleThickness[ilp], + moduleMaterialPtr); + + layerModules.push_back(detElement->surface().getSharedPtr()); + detectorStore.push_back(std::move(detElement)); + } + // create the layer and store it + ProtoLayer protoLayer(geoContext, layerModules); + protoLayer.envR = {0.5, 0.5}; + auto pLayer = layerCreator->cylinderLayer( + geoContext, std::move(layerModules), pLayerBinning[ilp].first, + pLayerBinning[ilp].second, protoLayer); + auto approachSurfaces = pLayer->approachDescriptor()->containedSurfaces(); + auto mutableOuterSurface = + const_cast<Acts::Surface*>(approachSurfaces.at(1)); + mutableOuterSurface->assignSurfaceMaterial(layerMaterialPtr); + /// now push back the layer + pLayers.push_back(pLayer); + + } // loop over layers + + // layer array + auto pLayerArray = layerArrayCreator->layerArray(geoContext, pLayers, 25., + 300., arbitrary, binR); + auto pVolumeBounds = + std::make_shared<const CylinderVolumeBounds>(25., 300., 1100.); + // create the Tracking volume + auto pVolume = TrackingVolume::create(nullptr, pVolumeBounds, nullptr, + std::move(pLayerArray), nullptr, + "Pixel::Barrel"); + + // The combined volume + auto detectorVolume = cylinderVolumeHelper->createContainerTrackingVolume( + geoContext, {beamPipeVolume, pVolume}); + + // create and return the geometry + return std::make_shared<const TrackingGeometry>(detectorVolume); + } +}; } // namespace Test } // namespace Acts diff --git a/Tests/Core/CommonHelpers/include/Acts/Tests/CommonHelpers/DetectorElementStub.hpp b/Tests/Core/CommonHelpers/include/Acts/Tests/CommonHelpers/DetectorElementStub.hpp index bd03e55b2c7f8555a83f583a2110e59ef7f6c076..ed353d91a7cdbba19cb45fbff4b8ab1142dc9c56 100644 --- a/Tests/Core/CommonHelpers/include/Acts/Tests/CommonHelpers/DetectorElementStub.hpp +++ b/Tests/Core/CommonHelpers/include/Acts/Tests/CommonHelpers/DetectorElementStub.hpp @@ -29,107 +29,92 @@ class LineBounds; namespace Test { - /// @class DetectorElementStub +/// @class DetectorElementStub +/// +/// This is a lightweight type of detector element, +/// it simply implements the base class. +class DetectorElementStub : public DetectorElementBase { + public: + DetectorElementStub() : DetectorElementBase() {} + + DetectorElementStub(std::shared_ptr<const Transform3D> transform) + : DetectorElementBase(), m_elementTransform(std::move(transform)) {} + + /// Constructor for single sided detector element + /// - bound to a Plane Surface /// - /// This is a lightweight type of detector element, - /// it simply implements the base class. - class DetectorElementStub : public DetectorElementBase - { - public: - DetectorElementStub() : DetectorElementBase() {} - - DetectorElementStub(std::shared_ptr<const Transform3D> transform) - : DetectorElementBase(), m_elementTransform(std::move(transform)) - { - } - - /// Constructor for single sided detector element - /// - bound to a Plane Surface - /// - /// @param transform is the transform that element the layer in 3D frame - /// @param pBounds is the planar bounds for the planar detector element - /// @param thickness is the module thickness - /// @param material is the (optional) Surface material associated to it - DetectorElementStub(std::shared_ptr<const Transform3D> transform, - std::shared_ptr<const PlanarBounds> pBounds, - double thickness, - std::shared_ptr<const ISurfaceMaterial> material - = nullptr) - : DetectorElementBase() - , m_elementTransform(std::move(transform)) - , m_elementThickness(thickness) - { - auto mutableSurface = Surface::makeShared<PlaneSurface>(pBounds, *this); - mutableSurface->assignSurfaceMaterial(material); - m_elementSurface = mutableSurface; - } - - /// Constructor for single sided detector element - /// - bound to a Line Surface - /// - /// @param transform is the transform that element the layer in 3D frame - /// @param dBounds is the line bounds for the line like detector element - /// @param thickness is the module thickness - /// @param material is the (optional) Surface material associated to it - DetectorElementStub(std::shared_ptr<const Transform3D> transform, - std::shared_ptr<const LineBounds> lBounds, - double thickness, - std::shared_ptr<const ISurfaceMaterial> material - = nullptr) - : DetectorElementBase() - , m_elementTransform(std::move(transform)) - , m_elementThickness(thickness) - { - auto mutableSurface - = Surface::makeShared<LineSurfaceStub>(lBounds, *this); - mutableSurface->assignSurfaceMaterial(material); - m_elementSurface = mutableSurface; - } - - /// Destructor - ~DetectorElementStub() override { /*nop */} - - /// Return local to global transform associated with this identifier - /// - /// @param gctx The current geometry context object, e.g. alignment - /// - /// @note this is called from the surface().transform() in the PROXY mode - const Transform3D& - transform(const GeometryContext& gctx) const override; - - /// Return surface associated with this detector element - const Surface& - surface() const override; - - /// The maximal thickness of the detector element wrt normal axis - double - thickness() const override; - - private: - /// the transform for positioning in 3D space - std::shared_ptr<const Transform3D> m_elementTransform; - /// the surface represented by it - std::shared_ptr<const Surface> m_elementSurface{nullptr}; - /// the element thickness - double m_elementThickness{0.}; - }; - - inline const Transform3D& - DetectorElementStub::transform(const GeometryContext& /*gctx*/) const - { - return *m_elementTransform; + /// @param transform is the transform that element the layer in 3D frame + /// @param pBounds is the planar bounds for the planar detector element + /// @param thickness is the module thickness + /// @param material is the (optional) Surface material associated to it + DetectorElementStub( + std::shared_ptr<const Transform3D> transform, + std::shared_ptr<const PlanarBounds> pBounds, double thickness, + std::shared_ptr<const ISurfaceMaterial> material = nullptr) + : DetectorElementBase(), + m_elementTransform(std::move(transform)), + m_elementThickness(thickness) { + auto mutableSurface = Surface::makeShared<PlaneSurface>(pBounds, *this); + mutableSurface->assignSurfaceMaterial(material); + m_elementSurface = mutableSurface; } - inline const Surface& - DetectorElementStub::surface() const - { - return *m_elementSurface; + /// Constructor for single sided detector element + /// - bound to a Line Surface + /// + /// @param transform is the transform that element the layer in 3D frame + /// @param dBounds is the line bounds for the line like detector element + /// @param thickness is the module thickness + /// @param material is the (optional) Surface material associated to it + DetectorElementStub( + std::shared_ptr<const Transform3D> transform, + std::shared_ptr<const LineBounds> lBounds, double thickness, + std::shared_ptr<const ISurfaceMaterial> material = nullptr) + : DetectorElementBase(), + m_elementTransform(std::move(transform)), + m_elementThickness(thickness) { + auto mutableSurface = Surface::makeShared<LineSurfaceStub>(lBounds, *this); + mutableSurface->assignSurfaceMaterial(material); + m_elementSurface = mutableSurface; } - inline double - DetectorElementStub::thickness() const - { - return m_elementThickness; + /// Destructor + ~DetectorElementStub() override { /*nop */ } + + /// Return local to global transform associated with this identifier + /// + /// @param gctx The current geometry context object, e.g. alignment + /// + /// @note this is called from the surface().transform() in the PROXY mode + const Transform3D& transform(const GeometryContext& gctx) const override; + + /// Return surface associated with this detector element + const Surface& surface() const override; + + /// The maximal thickness of the detector element wrt normal axis + double thickness() const override; + + private: + /// the transform for positioning in 3D space + std::shared_ptr<const Transform3D> m_elementTransform; + /// the surface represented by it + std::shared_ptr<const Surface> m_elementSurface{nullptr}; + /// the element thickness + double m_elementThickness{0.}; +}; + +inline const Transform3D& DetectorElementStub::transform( + const GeometryContext& /*gctx*/) const { + return *m_elementTransform; +} + +inline const Surface& DetectorElementStub::surface() const { + return *m_elementSurface; +} + +inline double DetectorElementStub::thickness() const { + return m_elementThickness; } -} // end of ns +} // namespace Test +} // namespace Acts diff --git a/Tests/Core/CommonHelpers/include/Acts/Tests/CommonHelpers/FloatComparisons.hpp b/Tests/Core/CommonHelpers/include/Acts/Tests/CommonHelpers/FloatComparisons.hpp index 673d699efaf29831c5a9f97b8303022b08f76a61..089d1152e3e2173963e5712c677b9703bf63007b 100644 --- a/Tests/Core/CommonHelpers/include/Acts/Tests/CommonHelpers/FloatComparisons.hpp +++ b/Tests/Core/CommonHelpers/include/Acts/Tests/CommonHelpers/FloatComparisons.hpp @@ -27,23 +27,23 @@ // failure occured (container contents if applicable, source file & line...). // Check if "val" and "ref" are within relative tolerance "tol" of each other. -#define CHECK_CLOSE_REL(val, ref, reltol) \ +#define CHECK_CLOSE_REL(val, ref, reltol) \ BOOST_CHECK(Acts::Test::checkCloseRel((val), (ref), (reltol))) // Check if "val" and "ref" are within absolute tolerance "tol" of each other. // Equivalent to CHECK_SMALL(val - ref), but does not require an operator-(). -#define CHECK_CLOSE_ABS(val, ref, abstol) \ +#define CHECK_CLOSE_ABS(val, ref, abstol) \ BOOST_CHECK(Acts::Test::checkCloseAbs((val), (ref), (abstol))) // Check if "val" is below absolute threshold "small". // Equivalent to CHECK_CLOSE_ABS(val, 0), but does not require a zero value. -#define CHECK_SMALL(val, small) \ +#define CHECK_SMALL(val, small) \ BOOST_CHECK(Acts::Test::checkSmall((val), (small))) // Start with a relative comparison, but tolerate failures when both the value // and the reference are below "small". This assertion is useful when comparing // containers of values and the reference container has zeroes. -#define CHECK_CLOSE_OR_SMALL(val, ref, reltol, small) \ +#define CHECK_CLOSE_OR_SMALL(val, ref, reltol, small) \ BOOST_CHECK(Acts::Test::checkCloseOrSmall((val), (ref), (reltol), (small))) // Covariance matrices require special logic and care because while relative @@ -51,275 +51,247 @@ // inappropriate on off-diagonal terms, which represent correlations and are // therefore best compared with respect to the order of magnitude of the // corresponding diagonal elements. -#define CHECK_CLOSE_COVARIANCE(val, ref, tol) \ +#define CHECK_CLOSE_COVARIANCE(val, ref, tol) \ BOOST_CHECK(Acts::Test::checkCloseCovariance((val), (ref), (tol))) // The relevant infrastructure is implemented below namespace Acts { namespace Test { - namespace float_compare_internal { - - // Under the hood, various scalar comparison logics may be used - - using predicate_result = boost::test_tools::predicate_result; - - using ScalarComparison = std::function<predicate_result(double, double)>; - - ScalarComparison - closeOrSmall(double reltol, double small) - { - return [=](double val, double ref) -> predicate_result { - // Perform the comparison, exit on success - if (std::abs(ref) >= small) { - // Reference is large enough for a relative comparison - if (std::abs(val - ref) < reltol * std::abs(ref)) { - return true; - } - } else if (std::abs(val) < small) { - // Reference is small and value is small too - return true; - } - - // Comparison failed, report why - predicate_result res(false); - res.message() << "The floating point value " << val; - if ((std::abs(ref) < small) || (reltol == 0.)) { - res.message() << " is above small-ness threshold " << small; - } else { - res.message() << " is not within relative tolerance " << reltol - << " of reference " << ref; - } - res.message() << '.'; - return res; - }; - } +namespace float_compare_internal { - ScalarComparison - closeAbs(double abstol) - { - return [=](double val, double ref) -> predicate_result { - // Perform the comparison, exit on success - if (std::abs(ref - val) <= abstol) { - return true; - } - - // Comparison failed, report why - predicate_result res(false); - res.message() << "The floating point value " << val - << " is not within absolute tolerance " << abstol - << " of reference " << ref << '.'; - return res; - }; - } +// Under the hood, various scalar comparison logics may be used - // Container comparison is then implemented on top of scalar comparison - - // Matrix comparison backend (called by Eigen-related compare() overloads) - template <typename Derived1, typename Derived2> - predicate_result - matrixCompare(const Eigen::DenseBase<Derived1>& val, - const Eigen::DenseBase<Derived2>& ref, - ScalarComparison&& compareImpl) - { - constexpr int rows1 = Eigen::DenseBase<Derived1>::RowsAtCompileTime; - constexpr int rows2 = Eigen::DenseBase<Derived2>::RowsAtCompileTime; - constexpr int cols1 = Eigen::DenseBase<Derived1>::ColsAtCompileTime; - constexpr int cols2 = Eigen::DenseBase<Derived2>::ColsAtCompileTime; - - if - constexpr(rows1 != Eigen::Dynamic && rows2 != Eigen::Dynamic - && cols1 != Eigen::Dynamic - && cols2 != Eigen::Dynamic) - { - // All dimensions on both are static. Static assert compatibility. - static_assert(rows1 == rows2, - "Input matrices do not have the same number of rows"); - static_assert( - cols1 == cols2, - "Input matrices do not have the same number of columns"); - } - else { - // some are dynamic, do runtime check - if (val.rows() != ref.rows() || val.cols() != ref.cols()) { - predicate_result res{false}; - res.message() << "Mismatch in matrix dimensions:\n" - << val << "\n" - << ref; - return res; - } - } +using predicate_result = boost::test_tools::predicate_result; + +using ScalarComparison = std::function<predicate_result(double, double)>; - // for looping, always use runtime values - for (int col = 0; col < val.cols(); ++col) { - for (int row = 0; row < val.rows(); ++row) { - predicate_result res = compareImpl(val(row, col), ref(row, col)); - if (!res) { - res.message() << " The failure occured during a matrix comparison," - << " at index (" << row << ", " << col << ")." - << " The value was\n" - << val << '\n' - << "and the reference was\n" - << ref << '\n'; - return res; - } - } +ScalarComparison closeOrSmall(double reltol, double small) { + return [=](double val, double ref) -> predicate_result { + // Perform the comparison, exit on success + if (std::abs(ref) >= small) { + // Reference is large enough for a relative comparison + if (std::abs(val - ref) < reltol * std::abs(ref)) { + return true; } + } else if (std::abs(val) < small) { + // Reference is small and value is small too return true; } - // STL container frontend - // - // FIXME: The algorithm only supports ordered containers, so the API should - // only accept them. Does someone know a clean way to do that in C++? - // - template <typename Container, - typename Enable = typename Container::const_iterator> - predicate_result - compare(const Container& val, - const Container& ref, - ScalarComparison&& compareImpl) - { - // Make sure that the two input containers have the same number of items - // (in order to provide better error reporting when they don't) - size_t numVals = std::distance(std::cbegin(val), std::cend(val)); - size_t numRefs = std::distance(std::cbegin(ref), std::cend(ref)); - if (numVals != numRefs) { - predicate_result res(false); - res.message() << "The container size does not match (value has " - << numVals << " elements, reference has " << numRefs - << " elements)."; - return res; - } - - // Compare the container's contents, bubbling assertion results up. Sadly, - // this means that we cannot use std::equal. - auto valBeg = std::cbegin(val); - auto valIter = valBeg; - auto valEnd = std::cend(val); - auto refIter = std::cbegin(ref); - while (valIter != valEnd) { - predicate_result res = compareImpl(*valIter, *refIter); - if (!res) { - // If content comparison failed, report the container's contents - res.message() << " The failure occured during a container comparison," - << " at index " << std::distance(valBeg, valIter) << '.' - << " The value contained {"; - for (const auto& item : val) { - res.message() << ' ' << item << ' '; - } - res.message() << "} and the reference contained {"; - for (const auto& item : ref) { - res.message() << ' ' << item << ' '; - } - res.message() << "}."; - return res; - } - ++valIter; - ++refIter; - } + // Comparison failed, report why + predicate_result res(false); + res.message() << "The floating point value " << val; + if ((std::abs(ref) < small) || (reltol == 0.)) { + res.message() << " is above small-ness threshold " << small; + } else { + res.message() << " is not within relative tolerance " << reltol + << " of reference " << ref; + } + res.message() << '.'; + return res; + }; +} - // If the size and contents match, we're good +ScalarComparison closeAbs(double abstol) { + return [=](double val, double ref) -> predicate_result { + // Perform the comparison, exit on success + if (std::abs(ref - val) <= abstol) { return true; } - // Eigen expression template frontend - template <typename T, typename U> - predicate_result - compare(const Eigen::DenseBase<T>& val, - const Eigen::DenseBase<U>& ref, - ScalarComparison&& compareImpl) - { - return matrixCompare(val.eval(), ref.eval(), std::move(compareImpl)); - } + // Comparison failed, report why + predicate_result res(false); + res.message() << "The floating point value " << val + << " is not within absolute tolerance " << abstol + << " of reference " << ref << '.'; + return res; + }; +} - // Eigen transform frontend - predicate_result - compare(const Transform3D& val, - const Transform3D& ref, - ScalarComparison&& compareImpl) - { - return matrixCompare(val.matrix(), ref.matrix(), std::move(compareImpl)); +// Container comparison is then implemented on top of scalar comparison + +// Matrix comparison backend (called by Eigen-related compare() overloads) +template <typename Derived1, typename Derived2> +predicate_result matrixCompare(const Eigen::DenseBase<Derived1>& val, + const Eigen::DenseBase<Derived2>& ref, + ScalarComparison&& compareImpl) { + constexpr int rows1 = Eigen::DenseBase<Derived1>::RowsAtCompileTime; + constexpr int rows2 = Eigen::DenseBase<Derived2>::RowsAtCompileTime; + constexpr int cols1 = Eigen::DenseBase<Derived1>::ColsAtCompileTime; + constexpr int cols2 = Eigen::DenseBase<Derived2>::ColsAtCompileTime; + + if constexpr (rows1 != Eigen::Dynamic && rows2 != Eigen::Dynamic && + cols1 != Eigen::Dynamic && cols2 != Eigen::Dynamic) { + // All dimensions on both are static. Static assert compatibility. + static_assert(rows1 == rows2, + "Input matrices do not have the same number of rows"); + static_assert(cols1 == cols2, + "Input matrices do not have the same number of columns"); + } else { + // some are dynamic, do runtime check + if (val.rows() != ref.rows() || val.cols() != ref.cols()) { + predicate_result res{false}; + res.message() << "Mismatch in matrix dimensions:\n" << val << "\n" << ref; + return res; } + } - // Scalar frontend - predicate_result - compare(double val, double ref, ScalarComparison&& compareImpl) - { - return compareImpl(val, ref); + // for looping, always use runtime values + for (int col = 0; col < val.cols(); ++col) { + for (int row = 0; row < val.rows(); ++row) { + predicate_result res = compareImpl(val(row, col), ref(row, col)); + if (!res) { + res.message() << " The failure occured during a matrix comparison," + << " at index (" << row << ", " << col << ")." + << " The value was\n" + << val << '\n' + << "and the reference was\n" + << ref << '\n'; + return res; + } } } + return true; +} - // ...and with all that, we can implement the CHECK_XYZ macros - - template <typename T, typename U> - boost::test_tools::predicate_result - checkCloseRel(const T& val, const U& ref, double reltol) - { - using namespace float_compare_internal; - return compare(val, ref, closeOrSmall(reltol, 0.)); +// STL container frontend +// +// FIXME: The algorithm only supports ordered containers, so the API should +// only accept them. Does someone know a clean way to do that in C++? +// +template <typename Container, + typename Enable = typename Container::const_iterator> +predicate_result compare(const Container& val, const Container& ref, + ScalarComparison&& compareImpl) { + // Make sure that the two input containers have the same number of items + // (in order to provide better error reporting when they don't) + size_t numVals = std::distance(std::cbegin(val), std::cend(val)); + size_t numRefs = std::distance(std::cbegin(ref), std::cend(ref)); + if (numVals != numRefs) { + predicate_result res(false); + res.message() << "The container size does not match (value has " << numVals + << " elements, reference has " << numRefs << " elements)."; + return res; } - template <typename T, typename U> - boost::test_tools::predicate_result - checkCloseAbs(const T& val, const U& ref, double abstol) - { - using namespace float_compare_internal; - return compare(val, ref, closeAbs(abstol)); + // Compare the container's contents, bubbling assertion results up. Sadly, + // this means that we cannot use std::equal. + auto valBeg = std::cbegin(val); + auto valIter = valBeg; + auto valEnd = std::cend(val); + auto refIter = std::cbegin(ref); + while (valIter != valEnd) { + predicate_result res = compareImpl(*valIter, *refIter); + if (!res) { + // If content comparison failed, report the container's contents + res.message() << " The failure occured during a container comparison," + << " at index " << std::distance(valBeg, valIter) << '.' + << " The value contained {"; + for (const auto& item : val) { + res.message() << ' ' << item << ' '; + } + res.message() << "} and the reference contained {"; + for (const auto& item : ref) { + res.message() << ' ' << item << ' '; + } + res.message() << "}."; + return res; + } + ++valIter; + ++refIter; } - template <typename T> - boost::test_tools::predicate_result - checkSmall(const T& val, double small) - { - using namespace float_compare_internal; - return compare(val, val, closeOrSmall(0., small)); - } + // If the size and contents match, we're good + return true; +} - template <typename T, typename U> - boost::test_tools::predicate_result - checkCloseOrSmall(const T& val, const U& ref, double reltol, double small) - { - using namespace float_compare_internal; - return compare(val, ref, closeOrSmall(reltol, small)); - } +// Eigen expression template frontend +template <typename T, typename U> +predicate_result compare(const Eigen::DenseBase<T>& val, + const Eigen::DenseBase<U>& ref, + ScalarComparison&& compareImpl) { + return matrixCompare(val.eval(), ref.eval(), std::move(compareImpl)); +} + +// Eigen transform frontend +predicate_result compare(const Transform3D& val, const Transform3D& ref, + ScalarComparison&& compareImpl) { + return matrixCompare(val.matrix(), ref.matrix(), std::move(compareImpl)); +} + +// Scalar frontend +predicate_result compare(double val, double ref, + ScalarComparison&& compareImpl) { + return compareImpl(val, ref); +} +} // namespace float_compare_internal + +// ...and with all that, we can implement the CHECK_XYZ macros - template <typename Scalar, int dim> - boost::test_tools::predicate_result - checkCloseCovariance(const ActsSymMatrix<Scalar, dim>& val, - const ActsSymMatrix<Scalar, dim>& ref, - double tol) - { - static_assert(dim != Eigen::Dynamic, - "Dynamic-size matrices are currently unsupported."); - - for (int col = 0; col < dim; ++col) { - for (int row = col; row < dim; ++row) { - // For diagonal elements, this is just a regular relative comparison. - // But for off-diagonal correlation terms, the tolerance scales with the - // geometric mean of the variance terms that are being correlated. - // - // This accounts for the fact that a relatively large correlation - // difference means little if the overall correlation has a tiny weight - // with respect to the diagonal variance elements anyway. - // - auto orderOfMagnitude = std::sqrt(ref(row, row) * ref(col, col)); - if (std::abs(val(row, col) - ref(row, col)) >= tol * orderOfMagnitude) { - boost::test_tools::predicate_result res(false); - res.message() << "The difference between the covariance matrix term " - << val(row, col) << " and its reference " - << ref(row, col) << "," - << " at index (" << row << ", " << col << ")," - << " is not within tolerance " << tol << '.' - << " The covariance matrix being tested was\n" - << val << '\n' - << "and the reference covariance matrix was\n" - << ref << '\n'; - return res; - } +template <typename T, typename U> +boost::test_tools::predicate_result checkCloseRel(const T& val, const U& ref, + double reltol) { + using namespace float_compare_internal; + return compare(val, ref, closeOrSmall(reltol, 0.)); +} + +template <typename T, typename U> +boost::test_tools::predicate_result checkCloseAbs(const T& val, const U& ref, + double abstol) { + using namespace float_compare_internal; + return compare(val, ref, closeAbs(abstol)); +} + +template <typename T> +boost::test_tools::predicate_result checkSmall(const T& val, double small) { + using namespace float_compare_internal; + return compare(val, val, closeOrSmall(0., small)); +} + +template <typename T, typename U> +boost::test_tools::predicate_result checkCloseOrSmall(const T& val, + const U& ref, + double reltol, + double small) { + using namespace float_compare_internal; + return compare(val, ref, closeOrSmall(reltol, small)); +} + +template <typename Scalar, int dim> +boost::test_tools::predicate_result checkCloseCovariance( + const ActsSymMatrix<Scalar, dim>& val, + const ActsSymMatrix<Scalar, dim>& ref, double tol) { + static_assert(dim != Eigen::Dynamic, + "Dynamic-size matrices are currently unsupported."); + + for (int col = 0; col < dim; ++col) { + for (int row = col; row < dim; ++row) { + // For diagonal elements, this is just a regular relative comparison. + // But for off-diagonal correlation terms, the tolerance scales with the + // geometric mean of the variance terms that are being correlated. + // + // This accounts for the fact that a relatively large correlation + // difference means little if the overall correlation has a tiny weight + // with respect to the diagonal variance elements anyway. + // + auto orderOfMagnitude = std::sqrt(ref(row, row) * ref(col, col)); + if (std::abs(val(row, col) - ref(row, col)) >= tol * orderOfMagnitude) { + boost::test_tools::predicate_result res(false); + res.message() << "The difference between the covariance matrix term " + << val(row, col) << " and its reference " << ref(row, col) + << "," + << " at index (" << row << ", " << col << ")," + << " is not within tolerance " << tol << '.' + << " The covariance matrix being tested was\n" + << val << '\n' + << "and the reference covariance matrix was\n" + << ref << '\n'; + return res; } } - return true; } + return true; } -} +} // namespace Test +} // namespace Acts diff --git a/Tests/Core/CommonHelpers/include/Acts/Tests/CommonHelpers/LineSurfaceStub.hpp b/Tests/Core/CommonHelpers/include/Acts/Tests/CommonHelpers/LineSurfaceStub.hpp index 5108482886ab880c59658e9416f981d3ac0d8079..c53b5643dee229a3b0a5fe1f2636942ae1a98194 100644 --- a/Tests/Core/CommonHelpers/include/Acts/Tests/CommonHelpers/LineSurfaceStub.hpp +++ b/Tests/Core/CommonHelpers/include/Acts/Tests/CommonHelpers/LineSurfaceStub.hpp @@ -16,72 +16,53 @@ namespace Acts { namespace Test { - class LineSurfaceStub : public LineSurface - { - public: - LineSurfaceStub() = delete; - // - LineSurfaceStub(std::shared_ptr<const Transform3D> htrans, - double radius, - double halfz) - : GeometryObject(), LineSurface(htrans, radius, halfz) - { /* nop */ - } - // - LineSurfaceStub(std::shared_ptr<const Transform3D> htrans, - std::shared_ptr<const LineBounds> lbounds = nullptr) - : GeometryObject(), LineSurface(htrans, lbounds) - { /*nop */ - } - // - LineSurfaceStub(std::shared_ptr<const LineBounds> lbounds, - const DetectorElementBase& detelement) - : GeometryObject(), LineSurface(lbounds, detelement) - { /* nop */ - } +class LineSurfaceStub : public LineSurface { + public: + LineSurfaceStub() = delete; + // + LineSurfaceStub(std::shared_ptr<const Transform3D> htrans, double radius, + double halfz) + : GeometryObject(), LineSurface(htrans, radius, halfz) { /* nop */ + } + // + LineSurfaceStub(std::shared_ptr<const Transform3D> htrans, + std::shared_ptr<const LineBounds> lbounds = nullptr) + : GeometryObject(), LineSurface(htrans, lbounds) { /*nop */ + } + // + LineSurfaceStub(std::shared_ptr<const LineBounds> lbounds, + const DetectorElementBase& detelement) + : GeometryObject(), LineSurface(lbounds, detelement) { /* nop */ + } - // - LineSurfaceStub(const LineSurfaceStub& ls) - : GeometryObject(), LineSurface(ls) - { /* nop */ - } - // - LineSurfaceStub(const GeometryContext& gctx, - const LineSurfaceStub& ls, - const Transform3D& t) - : GeometryObject(), LineSurface(gctx, ls, t) - { /* nop */ - } - /// pure virtual functions of baseclass implemented here - std::shared_ptr<LineSurfaceStub> - clone(const GeometryContext& /*gctx*/, const Transform3D& /*unused*/) const - { - return nullptr; - } + // + LineSurfaceStub(const LineSurfaceStub& ls) + : GeometryObject(), LineSurface(ls) { /* nop */ + } + // + LineSurfaceStub(const GeometryContext& gctx, const LineSurfaceStub& ls, + const Transform3D& t) + : GeometryObject(), LineSurface(gctx, ls, t) { /* nop */ + } + /// pure virtual functions of baseclass implemented here + std::shared_ptr<LineSurfaceStub> clone(const GeometryContext& /*gctx*/, + const Transform3D& /*unused*/) const { + return nullptr; + } - /// Return method for the Surface type to avoid dynamic casts - SurfaceType - type() const final - { - return Surface::Straw; - } + /// Return method for the Surface type to avoid dynamic casts + SurfaceType type() const final { return Surface::Straw; } - /// Simply return true to show object exists and is callable - bool - constructedOk() const - { - return true; - } + /// Simply return true to show object exists and is callable + bool constructedOk() const { return true; } - using Surface::normal; + using Surface::normal; - private: - Surface* - clone_impl(const GeometryContext& /*gctx*/, - const Transform3D& /*unused*/) const - { - return nullptr; - } - }; -} // end of ns -} + private: + Surface* clone_impl(const GeometryContext& /*gctx*/, + const Transform3D& /*unused*/) const { + return nullptr; + } +}; +} // namespace Test +} // namespace Acts diff --git a/Tests/Core/EventData/BoundParametersTests.cpp b/Tests/Core/EventData/BoundParametersTests.cpp index 91978dc5525446f069fed598a48c91bebba36228..671cfb55779c73c039c0739d629887ea12caef40 100644 --- a/Tests/Core/EventData/BoundParametersTests.cpp +++ b/Tests/Core/EventData/BoundParametersTests.cpp @@ -30,484 +30,442 @@ #include "ParametersTestHelper.hpp" namespace bdata = boost::unit_test::data; -namespace tt = boost::test_tools; +namespace tt = boost::test_tools; namespace Acts { namespace Test { - // Create a test context - GeometryContext tgContext = GeometryContext(); - - /// @brief Unit test for parameters at a plane - /// - BOOST_DATA_TEST_CASE( - bound_to_plane_test, - bdata::random((bdata::seed = 1240, - bdata::distribution - = std::uniform_real_distribution<>(-1000., 1000.))) - ^ bdata::random((bdata::seed = 2351, - bdata::distribution - = std::uniform_real_distribution<>(-1000., 1000.))) - ^ bdata::random((bdata::seed = 3412, - bdata::distribution - = std::uniform_real_distribution<>(-1000., 1000.))) - ^ bdata::random((bdata::seed = 5732, - bdata::distribution - = std::uniform_real_distribution<>(0., M_PI))) - ^ bdata::random((bdata::seed = 8941, - bdata::distribution - = std::uniform_real_distribution<>(0., M_PI))) - ^ bdata::random((bdata::seed = 1295, - bdata::distribution - = std::uniform_real_distribution<>(0., M_PI))) - ^ bdata::xrange(100), - x, - y, - z, - a, - b, - c, - index) - { - (void)index; - Vector3D center{x, y, z}; - auto transform = std::make_shared<Transform3D>(); - transform->setIdentity(); - RotationMatrix3D rot; - rot = AngleAxis3D(a, Vector3D::UnitX()) * AngleAxis3D(b, Vector3D::UnitY()) - * AngleAxis3D(c, Vector3D::UnitZ()); - transform->prerotate(rot); - transform->pretranslate(center); - // create the surfacex - auto bounds = std::make_shared<RectangleBounds>(100., 100.); - auto pSurface = Surface::makeShared<PlaneSurface>(transform, bounds); - - // now create parameters on this surface - // l_x, l_y, phi, theta, q/p (1/p) - std::array<double, 5> pars_array = {{-0.1234, 9.8765, 0.45, 0.888, 0.001}}; - TrackParametersBase::ParVector_t pars; - pars << pars_array[0], pars_array[1], pars_array[2], pars_array[3], - pars_array[4]; - - const double phi = pars_array[2]; - const double theta = pars_array[3]; - double p = fabs(1. / pars_array[4]); - Vector3D direction( - cos(phi) * sin(theta), sin(phi) * sin(theta), cos(theta)); - Vector3D mom = p * direction; - // the global position - Vector3D pos - = center + pars_array[0] * rot.col(0) + pars_array[1] * rot.col(1); - // constructor from parameter vector - BoundParameters ataPlane_from_pars(tgContext, nullptr, pars, pSurface); - consistencyCheck(ataPlane_from_pars, pos, mom, 1., pars_array); - // constructor from global parameters - BoundParameters ataPlane_from_global( - tgContext, nullptr, pos, mom, 1., pSurface); - consistencyCheck(ataPlane_from_global, pos, mom, 1., pars_array); - // constructor for neutral parameters - NeutralBoundParameters n_ataPlane_from_pars( - tgContext, nullptr, pars, pSurface); - consistencyCheck(n_ataPlane_from_pars, pos, mom, 0., pars_array); - // constructor for neutral global parameters - NeutralBoundParameters n_ataPlane_from_global( - tgContext, nullptr, pos, mom, pSurface); - consistencyCheck(n_ataPlane_from_global, pos, mom, 0., pars_array); - - // check shared ownership of same surface - BOOST_CHECK_EQUAL(&ataPlane_from_pars.referenceSurface(), pSurface.get()); - BOOST_CHECK_EQUAL(&ataPlane_from_pars.referenceSurface(), - &ataPlane_from_global.referenceSurface()); - BOOST_CHECK_EQUAL(&n_ataPlane_from_pars.referenceSurface(), pSurface.get()); - BOOST_CHECK_EQUAL(&n_ataPlane_from_pars.referenceSurface(), - &n_ataPlane_from_global.referenceSurface()); - BOOST_CHECK_EQUAL(pSurface.use_count(), 5); - - // check that the reference frame is the rotation matrix - CHECK_CLOSE_REL(ataPlane_from_pars.referenceFrame(tgContext), rot, 1e-6); - - /// modification test via setter functions - double ux = 0.3; - double uy = 0.4; - - ataPlane_from_pars.set<Acts::eLOC_X>(tgContext, ux); - ataPlane_from_pars.set<Acts::eLOC_Y>(tgContext, uy); - // we should have a new updated position - Vector3D lPosition3D(ux, uy, 0.); - Vector3D uposition = rot * lPosition3D + center; - CHECK_CLOSE_REL(uposition, ataPlane_from_pars.position(), 1e-6); - - double uphi = 1.2; - double utheta = 0.2; - double uqop = 0.025; - - ataPlane_from_pars.set<Acts::ePHI>(tgContext, uphi); - ataPlane_from_pars.set<Acts::eTHETA>(tgContext, utheta); - ataPlane_from_pars.set<Acts::eQOP>(tgContext, uqop); - // we should have a new updated momentum - Vector3D umomentum = 40. * Vector3D(cos(uphi) * sin(utheta), - sin(uphi) * sin(utheta), - cos(utheta)); - - CHECK_CLOSE_REL(umomentum, ataPlane_from_pars.momentum(), 1e-6); - } - - /// @brief Unit test for parameters at a disc - /// - BOOST_DATA_TEST_CASE( - bound_to_disc_test, - bdata::random((bdata::seed = 9810, - bdata::distribution - = std::uniform_real_distribution<>(-1000., 1000.))) - ^ bdata::random((bdata::seed = 1221, - bdata::distribution - = std::uniform_real_distribution<>(-1000., 1000.))) - ^ bdata::random((bdata::seed = 12132, - bdata::distribution - = std::uniform_real_distribution<>(-1000., 1000.))) - ^ bdata::random((bdata::seed = 16783, - bdata::distribution - = std::uniform_real_distribution<>(0., M_PI))) - ^ bdata::random((bdata::seed = 13984, - bdata::distribution - = std::uniform_real_distribution<>(0., M_PI))) - ^ bdata::random((bdata::seed = 77615, - bdata::distribution - = std::uniform_real_distribution<>(0., M_PI))) - ^ bdata::xrange(100), - x, - y, - z, - a, - b, - c, - index) - { - (void)index; - Vector3D center{x, y, z}; - auto transform = std::make_shared<Transform3D>(); - transform->setIdentity(); - RotationMatrix3D rot; - rot = AngleAxis3D(a, Vector3D::UnitX()) * AngleAxis3D(b, Vector3D::UnitY()) - * AngleAxis3D(c, Vector3D::UnitZ()); - transform->prerotate(rot); - transform->pretranslate(center); - - auto bounds = std::make_shared<RadialBounds>(100., 1200.); - auto dSurface = Surface::makeShared<DiscSurface>(transform, bounds); - - // now create parameters on this surface - // r, phi, phi, theta, q/p (1/p) - std::array<double, 5> pars_array = {{125., 0.345, 0.45, 0.888, 0.001}}; - TrackParametersBase::ParVector_t pars; - pars << pars_array[0], pars_array[1], pars_array[2], pars_array[3], - pars_array[4]; - - const double phi = pars_array[2]; - const double theta = pars_array[3]; - double p = fabs(1. / pars_array[4]); - Vector3D direction( - cos(phi) * sin(theta), sin(phi) * sin(theta), cos(theta)); - Vector3D mom = p * direction; - Vector3D pos = (pars_array[0] * cos(pars_array[1])) * rot.col(0) - + (pars_array[0] * sin(pars_array[1])) * rot.col(1) + center; - // constructor from parameter vector - BoundParameters ataDisc_from_pars(tgContext, nullptr, pars, dSurface); - consistencyCheck(ataDisc_from_pars, pos, mom, 1., pars_array); - // constructor from global parameters - BoundParameters ataDisc_from_global( - tgContext, nullptr, pos, mom, 1., dSurface); - consistencyCheck(ataDisc_from_global, pos, mom, 1., pars_array); - // constructor for neutral parameters - NeutralBoundParameters n_ataDisc_from_pars( - tgContext, nullptr, pars, dSurface); - consistencyCheck(n_ataDisc_from_pars, pos, mom, 0., pars_array); - // constructor for neutral global parameters - NeutralBoundParameters n_ataDisc_from_global( - tgContext, nullptr, pos, mom, dSurface); - consistencyCheck(n_ataDisc_from_global, pos, mom, 0., pars_array); - - // check shared ownership of same surface - BOOST_CHECK_EQUAL(&ataDisc_from_pars.referenceSurface(), dSurface.get()); - BOOST_CHECK_EQUAL(&ataDisc_from_pars.referenceSurface(), - &ataDisc_from_global.referenceSurface()); - BOOST_CHECK_EQUAL(&n_ataDisc_from_pars.referenceSurface(), dSurface.get()); - BOOST_CHECK_EQUAL(&n_ataDisc_from_pars.referenceSurface(), - &n_ataDisc_from_global.referenceSurface()); - BOOST_CHECK_EQUAL(dSurface.use_count(), 5); - - // check that the reference frame is the - // rotation matrix of the surface - const auto& dRotation - = dSurface->transform(tgContext).matrix().block<3, 3>(0, 0); - CHECK_CLOSE_REL( - ataDisc_from_pars.referenceFrame(tgContext), dRotation, 1e-6); - } - - /// @brief Unit test for parameters at a cylinder - /// - BOOST_DATA_TEST_CASE( - bound_to_cylinder_test, - bdata::random((bdata::seed = 39810, - bdata::distribution - = std::uniform_real_distribution<>(-1000., 1000.))) - ^ bdata::random((bdata::seed = 21221, - bdata::distribution - = std::uniform_real_distribution<>(-1000., 1000.))) - ^ bdata::random((bdata::seed = 62132, - bdata::distribution - = std::uniform_real_distribution<>(-1000., 1000.))) - ^ bdata::random((bdata::seed = 91683, - bdata::distribution - = std::uniform_real_distribution<>(0., M_PI))) - ^ bdata::random((bdata::seed = 39847, - bdata::distribution - = std::uniform_real_distribution<>(0., M_PI))) - ^ bdata::random((bdata::seed = 72615, - bdata::distribution - = std::uniform_real_distribution<>(0., M_PI))) - ^ bdata::xrange(100), - x, - y, - z, - a, - b, - c, - index) - { - (void)index; - - Vector3D center{x, y, z}; - auto transform = std::make_shared<Transform3D>(); - transform->setIdentity(); - RotationMatrix3D rot; - rot = AngleAxis3D(a, Vector3D::UnitX()) * AngleAxis3D(b, Vector3D::UnitY()) - * AngleAxis3D(c, Vector3D::UnitZ()); - transform->prerotate(rot); - transform->pretranslate(center); - - auto bounds = std::make_shared<CylinderBounds>(100., 1200.); - std::shared_ptr<const Surface> cSurface - = Surface::makeShared<CylinderSurface>(transform, bounds); - - // now create parameters on this surface - // rPhi, a, phi, theta, q/p (1/p) - std::array<double, 5> pars_array = {{125., 343., 0.45, 0.888, 0.001}}; - TrackParametersBase::ParVector_t pars; - pars << pars_array[0], pars_array[1], pars_array[2], pars_array[3], - pars_array[4]; - - const double phi = pars_array[2]; - const double theta = pars_array[3]; - double p = fabs(1. / pars_array[4]); - Vector3D direction( - cos(phi) * sin(theta), sin(phi) * sin(theta), cos(theta)); - Vector3D mom = p * direction; - - // 3D position in local frame - const double phi_l = pars_array[0] / bounds->r(); - Vector3D pos = (bounds->r() * cos(phi_l)) * rot.col(0) - + (bounds->r() * sin(phi_l)) * rot.col(1) + (pars_array[1]) * rot.col(2) - + center; - - // constructor from parameter vector - BoundParameters ataCylinder_from_pars(tgContext, nullptr, pars, cSurface); - consistencyCheck(ataCylinder_from_pars, pos, mom, 1., pars_array); - // constructor from global parameters - BoundParameters ataCylinder_from_global( - tgContext, nullptr, pos, mom, 1., cSurface); - consistencyCheck(ataCylinder_from_global, pos, mom, 1., pars_array); - // constructor for neutral parameters - NeutralBoundParameters n_ataCylinder_from_pars( - tgContext, nullptr, pars, cSurface); - consistencyCheck(n_ataCylinder_from_pars, pos, mom, 0., pars_array); - // constructor for neutral global parameters - NeutralBoundParameters n_ataCylinder_from_global( - tgContext, nullptr, pos, mom, cSurface); - consistencyCheck(n_ataCylinder_from_global, pos, mom, 0., pars_array); - - // check shared ownership of same surface - BOOST_CHECK_EQUAL(&ataCylinder_from_pars.referenceSurface(), - cSurface.get()); - BOOST_CHECK_EQUAL(&ataCylinder_from_pars.referenceSurface(), - &ataCylinder_from_global.referenceSurface()); - BOOST_CHECK_EQUAL(&n_ataCylinder_from_pars.referenceSurface(), - cSurface.get()); - BOOST_CHECK_EQUAL(&n_ataCylinder_from_pars.referenceSurface(), - &n_ataCylinder_from_global.referenceSurface()); - BOOST_CHECK_EQUAL(cSurface.use_count(), 5); - - auto pPosition = ataCylinder_from_pars.position(); - // the reference frame is - // transverse plane to the cylinder at the intersect - Vector3D normal_at_intersect = cSurface->normal(tgContext, pPosition); - Vector3D transverse_y = rot.col(2); - Vector3D transverse_x = transverse_y.cross(normal_at_intersect); - RotationMatrix3D refframe; - refframe.col(0) = transverse_x; - refframe.col(1) = transverse_y; - refframe.col(2) = normal_at_intersect; - // check if the manually constructed reference frame is the provided one - CHECK_CLOSE_REL( - ataCylinder_from_pars.referenceFrame(tgContext), refframe, 1e-6); - } - - /// @brief Unit test for parameters at the perigee - /// - BOOST_DATA_TEST_CASE( - bound_to_perigee_test, - bdata::random((bdata::seed = 3980, - bdata::distribution - = std::uniform_real_distribution<>(-10., 10.))) - ^ bdata::random((bdata::seed = 2221, - bdata::distribution - = std::uniform_real_distribution<>(-10., 10.))) - ^ bdata::random((bdata::seed = 2132, - bdata::distribution - = std::uniform_real_distribution<>(-10., 10.))) - ^ bdata::random((bdata::seed = 9183, - bdata::distribution - = std::uniform_real_distribution<>(0., 0.05))) - ^ bdata::random((bdata::seed = 3947, - bdata::distribution - = std::uniform_real_distribution<>(0., 0.05))) - ^ bdata::xrange(100), - x, - y, - z, - a, - b, - index) - { - (void)index; - Vector3D center{x, y, z}; - auto transform = std::make_shared<Transform3D>(); - transform->setIdentity(); - RotationMatrix3D rot; - rot = AngleAxis3D(a, Vector3D::UnitX()) * AngleAxis3D(b, Vector3D::UnitY()); - transform->prerotate(rot); - transform->pretranslate(center); - - // the straw surface - std::shared_ptr<const Surface> pSurface - = Surface::makeShared<PerigeeSurface>( - std::make_shared<const Transform3D>(*transform)); - - // now create parameters on this surface - // d0, z0, phi, theta, q/p (1/p) - std::array<double, 5> pars_array = {{-0.7321, 22.5, 0.45, 0.888, 0.001}}; - TrackParametersBase::ParVector_t pars; - pars << pars_array[0], pars_array[1], pars_array[2], pars_array[3], - pars_array[4]; - - BoundParameters ataPerigee_from_pars(tgContext, nullptr, pars, pSurface); - auto pos = ataPerigee_from_pars.position(); - auto mom = ataPerigee_from_pars.momentum(); - consistencyCheck(ataPerigee_from_pars, pos, mom, 1., pars_array); - // constructor from global parameters - BoundParameters ataPerigee_from_global( - tgContext, nullptr, pos, mom, 1., pSurface); - consistencyCheck(ataPerigee_from_global, pos, mom, 1., pars_array); - // constructor for neutral parameters - NeutralBoundParameters n_ataPerigee_from_pars( - tgContext, nullptr, pars, pSurface); - consistencyCheck(n_ataPerigee_from_pars, pos, mom, 0., pars_array); - // constructor for neutral global parameters - NeutralBoundParameters n_ataPerigee_from_global( - tgContext, nullptr, pos, mom, pSurface); - consistencyCheck(n_ataPerigee_from_global, pos, mom, 0., pars_array); - - // check shared ownership of same surface - BOOST_CHECK_EQUAL(&ataPerigee_from_pars.referenceSurface(), pSurface.get()); - BOOST_CHECK_EQUAL(&ataPerigee_from_pars.referenceSurface(), - &ataPerigee_from_global.referenceSurface()); - BOOST_CHECK_EQUAL(&n_ataPerigee_from_pars.referenceSurface(), - pSurface.get()); - BOOST_CHECK_EQUAL(&n_ataPerigee_from_pars.referenceSurface(), - &n_ataPerigee_from_global.referenceSurface()); - BOOST_CHECK_EQUAL(pSurface.use_count(), 5); - } - - /// @brief Unit test for parameters at a line - /// - BOOST_DATA_TEST_CASE( - bound_to_line_test, - bdata::random((bdata::seed = 73980, - bdata::distribution - = std::uniform_real_distribution<>(-1000., 1000.))) - ^ bdata::random((bdata::seed = 21221, - bdata::distribution - = std::uniform_real_distribution<>(-1000., 1000.))) - ^ bdata::random((bdata::seed = 62992, - bdata::distribution - = std::uniform_real_distribution<>(-1000., 1000.))) - ^ bdata::random((bdata::seed = 900683, - bdata::distribution - = std::uniform_real_distribution<>(0., M_PI))) - ^ bdata::random((bdata::seed = 5439847, - bdata::distribution - = std::uniform_real_distribution<>(0., M_PI))) - ^ bdata::random((bdata::seed = 1972615, - bdata::distribution - = std::uniform_real_distribution<>(0., M_PI))) - ^ bdata::xrange(100), - x, - y, - z, - a, - b, - c, - index) - { - (void)index; - - Vector3D center{x, y, z}; - auto transform = std::make_shared<Transform3D>(); - transform->setIdentity(); - RotationMatrix3D rot; - rot = AngleAxis3D(a, Vector3D::UnitX()) * AngleAxis3D(b, Vector3D::UnitY()) - * AngleAxis3D(c, Vector3D::UnitZ()); - transform->prerotate(rot); - transform->pretranslate(center); - - // the straw surface - auto sSurface = Surface::makeShared<StrawSurface>( - transform, 2. * Acts::units::_mm, 1. * Acts::units::_m); - - // now create parameters on this surface - // r, z, phi, theta, q/p (1/p) - std::array<double, 5> pars_array = {{0.2321, 22.5, 0.45, 0.888, 0.001}}; - TrackParametersBase::ParVector_t pars; - pars << pars_array[0], pars_array[1], pars_array[2], pars_array[3], - pars_array[4]; - - // constructor from parameter vector - BoundParameters ataLine_from_pars(tgContext, nullptr, pars, sSurface); - auto pos = ataLine_from_pars.position(); - auto mom = ataLine_from_pars.momentum(); - consistencyCheck(ataLine_from_pars, pos, mom, 1., pars_array); - // constructor from global parameters - BoundParameters ataLine_from_global( - tgContext, nullptr, pos, mom, 1., sSurface); - consistencyCheck(ataLine_from_global, pos, mom, 1., pars_array); - // constructor for neutral parameters - NeutralBoundParameters n_ataLine_from_pars( - tgContext, nullptr, pars, sSurface); - consistencyCheck(n_ataLine_from_pars, pos, mom, 0., pars_array); - // constructor for neutral global parameters - NeutralBoundParameters n_ataLine_from_global( - tgContext, nullptr, pos, mom, sSurface); - consistencyCheck(n_ataLine_from_global, pos, mom, 0., pars_array); - - // check shared ownership of same surface - BOOST_CHECK_EQUAL(&ataLine_from_pars.referenceSurface(), sSurface.get()); - BOOST_CHECK_EQUAL(&ataLine_from_pars.referenceSurface(), - &ataLine_from_global.referenceSurface()); - BOOST_CHECK_EQUAL(&n_ataLine_from_pars.referenceSurface(), sSurface.get()); - BOOST_CHECK_EQUAL(&n_ataLine_from_pars.referenceSurface(), - &n_ataLine_from_global.referenceSurface()); - BOOST_CHECK_EQUAL(sSurface.use_count(), 5); - } +// Create a test context +GeometryContext tgContext = GeometryContext(); + +/// @brief Unit test for parameters at a plane +/// +BOOST_DATA_TEST_CASE( + bound_to_plane_test, + bdata::random((bdata::seed = 1240, + bdata::distribution = + std::uniform_real_distribution<>(-1000., 1000.))) ^ + bdata::random((bdata::seed = 2351, + bdata::distribution = + std::uniform_real_distribution<>(-1000., 1000.))) ^ + bdata::random((bdata::seed = 3412, + bdata::distribution = + std::uniform_real_distribution<>(-1000., 1000.))) ^ + bdata::random(( + bdata::seed = 5732, + bdata::distribution = std::uniform_real_distribution<>(0., M_PI))) ^ + bdata::random(( + bdata::seed = 8941, + bdata::distribution = std::uniform_real_distribution<>(0., M_PI))) ^ + bdata::random(( + bdata::seed = 1295, + bdata::distribution = std::uniform_real_distribution<>(0., M_PI))) ^ + bdata::xrange(100), + x, y, z, a, b, c, index) { + (void)index; + Vector3D center{x, y, z}; + auto transform = std::make_shared<Transform3D>(); + transform->setIdentity(); + RotationMatrix3D rot; + rot = AngleAxis3D(a, Vector3D::UnitX()) * AngleAxis3D(b, Vector3D::UnitY()) * + AngleAxis3D(c, Vector3D::UnitZ()); + transform->prerotate(rot); + transform->pretranslate(center); + // create the surfacex + auto bounds = std::make_shared<RectangleBounds>(100., 100.); + auto pSurface = Surface::makeShared<PlaneSurface>(transform, bounds); + + // now create parameters on this surface + // l_x, l_y, phi, theta, q/p (1/p) + std::array<double, 5> pars_array = {{-0.1234, 9.8765, 0.45, 0.888, 0.001}}; + TrackParametersBase::ParVector_t pars; + pars << pars_array[0], pars_array[1], pars_array[2], pars_array[3], + pars_array[4]; + + const double phi = pars_array[2]; + const double theta = pars_array[3]; + double p = fabs(1. / pars_array[4]); + Vector3D direction(cos(phi) * sin(theta), sin(phi) * sin(theta), cos(theta)); + Vector3D mom = p * direction; + // the global position + Vector3D pos = + center + pars_array[0] * rot.col(0) + pars_array[1] * rot.col(1); + // constructor from parameter vector + BoundParameters ataPlane_from_pars(tgContext, nullptr, pars, pSurface); + consistencyCheck(ataPlane_from_pars, pos, mom, 1., pars_array); + // constructor from global parameters + BoundParameters ataPlane_from_global(tgContext, nullptr, pos, mom, 1., + pSurface); + consistencyCheck(ataPlane_from_global, pos, mom, 1., pars_array); + // constructor for neutral parameters + NeutralBoundParameters n_ataPlane_from_pars(tgContext, nullptr, pars, + pSurface); + consistencyCheck(n_ataPlane_from_pars, pos, mom, 0., pars_array); + // constructor for neutral global parameters + NeutralBoundParameters n_ataPlane_from_global(tgContext, nullptr, pos, mom, + pSurface); + consistencyCheck(n_ataPlane_from_global, pos, mom, 0., pars_array); + + // check shared ownership of same surface + BOOST_CHECK_EQUAL(&ataPlane_from_pars.referenceSurface(), pSurface.get()); + BOOST_CHECK_EQUAL(&ataPlane_from_pars.referenceSurface(), + &ataPlane_from_global.referenceSurface()); + BOOST_CHECK_EQUAL(&n_ataPlane_from_pars.referenceSurface(), pSurface.get()); + BOOST_CHECK_EQUAL(&n_ataPlane_from_pars.referenceSurface(), + &n_ataPlane_from_global.referenceSurface()); + BOOST_CHECK_EQUAL(pSurface.use_count(), 5); + + // check that the reference frame is the rotation matrix + CHECK_CLOSE_REL(ataPlane_from_pars.referenceFrame(tgContext), rot, 1e-6); + + /// modification test via setter functions + double ux = 0.3; + double uy = 0.4; + + ataPlane_from_pars.set<Acts::eLOC_X>(tgContext, ux); + ataPlane_from_pars.set<Acts::eLOC_Y>(tgContext, uy); + // we should have a new updated position + Vector3D lPosition3D(ux, uy, 0.); + Vector3D uposition = rot * lPosition3D + center; + CHECK_CLOSE_REL(uposition, ataPlane_from_pars.position(), 1e-6); + + double uphi = 1.2; + double utheta = 0.2; + double uqop = 0.025; + + ataPlane_from_pars.set<Acts::ePHI>(tgContext, uphi); + ataPlane_from_pars.set<Acts::eTHETA>(tgContext, utheta); + ataPlane_from_pars.set<Acts::eQOP>(tgContext, uqop); + // we should have a new updated momentum + Vector3D umomentum = 40. * Vector3D(cos(uphi) * sin(utheta), + sin(uphi) * sin(utheta), cos(utheta)); + + CHECK_CLOSE_REL(umomentum, ataPlane_from_pars.momentum(), 1e-6); } + +/// @brief Unit test for parameters at a disc +/// +BOOST_DATA_TEST_CASE( + bound_to_disc_test, + bdata::random((bdata::seed = 9810, + bdata::distribution = + std::uniform_real_distribution<>(-1000., 1000.))) ^ + bdata::random((bdata::seed = 1221, + bdata::distribution = + std::uniform_real_distribution<>(-1000., 1000.))) ^ + bdata::random((bdata::seed = 12132, + bdata::distribution = + std::uniform_real_distribution<>(-1000., 1000.))) ^ + bdata::random(( + bdata::seed = 16783, + bdata::distribution = std::uniform_real_distribution<>(0., M_PI))) ^ + bdata::random(( + bdata::seed = 13984, + bdata::distribution = std::uniform_real_distribution<>(0., M_PI))) ^ + bdata::random(( + bdata::seed = 77615, + bdata::distribution = std::uniform_real_distribution<>(0., M_PI))) ^ + bdata::xrange(100), + x, y, z, a, b, c, index) { + (void)index; + Vector3D center{x, y, z}; + auto transform = std::make_shared<Transform3D>(); + transform->setIdentity(); + RotationMatrix3D rot; + rot = AngleAxis3D(a, Vector3D::UnitX()) * AngleAxis3D(b, Vector3D::UnitY()) * + AngleAxis3D(c, Vector3D::UnitZ()); + transform->prerotate(rot); + transform->pretranslate(center); + + auto bounds = std::make_shared<RadialBounds>(100., 1200.); + auto dSurface = Surface::makeShared<DiscSurface>(transform, bounds); + + // now create parameters on this surface + // r, phi, phi, theta, q/p (1/p) + std::array<double, 5> pars_array = {{125., 0.345, 0.45, 0.888, 0.001}}; + TrackParametersBase::ParVector_t pars; + pars << pars_array[0], pars_array[1], pars_array[2], pars_array[3], + pars_array[4]; + + const double phi = pars_array[2]; + const double theta = pars_array[3]; + double p = fabs(1. / pars_array[4]); + Vector3D direction(cos(phi) * sin(theta), sin(phi) * sin(theta), cos(theta)); + Vector3D mom = p * direction; + Vector3D pos = (pars_array[0] * cos(pars_array[1])) * rot.col(0) + + (pars_array[0] * sin(pars_array[1])) * rot.col(1) + center; + // constructor from parameter vector + BoundParameters ataDisc_from_pars(tgContext, nullptr, pars, dSurface); + consistencyCheck(ataDisc_from_pars, pos, mom, 1., pars_array); + // constructor from global parameters + BoundParameters ataDisc_from_global(tgContext, nullptr, pos, mom, 1., + dSurface); + consistencyCheck(ataDisc_from_global, pos, mom, 1., pars_array); + // constructor for neutral parameters + NeutralBoundParameters n_ataDisc_from_pars(tgContext, nullptr, pars, + dSurface); + consistencyCheck(n_ataDisc_from_pars, pos, mom, 0., pars_array); + // constructor for neutral global parameters + NeutralBoundParameters n_ataDisc_from_global(tgContext, nullptr, pos, mom, + dSurface); + consistencyCheck(n_ataDisc_from_global, pos, mom, 0., pars_array); + + // check shared ownership of same surface + BOOST_CHECK_EQUAL(&ataDisc_from_pars.referenceSurface(), dSurface.get()); + BOOST_CHECK_EQUAL(&ataDisc_from_pars.referenceSurface(), + &ataDisc_from_global.referenceSurface()); + BOOST_CHECK_EQUAL(&n_ataDisc_from_pars.referenceSurface(), dSurface.get()); + BOOST_CHECK_EQUAL(&n_ataDisc_from_pars.referenceSurface(), + &n_ataDisc_from_global.referenceSurface()); + BOOST_CHECK_EQUAL(dSurface.use_count(), 5); + + // check that the reference frame is the + // rotation matrix of the surface + const auto& dRotation = + dSurface->transform(tgContext).matrix().block<3, 3>(0, 0); + CHECK_CLOSE_REL(ataDisc_from_pars.referenceFrame(tgContext), dRotation, 1e-6); +} + +/// @brief Unit test for parameters at a cylinder +/// +BOOST_DATA_TEST_CASE( + bound_to_cylinder_test, + bdata::random((bdata::seed = 39810, + bdata::distribution = + std::uniform_real_distribution<>(-1000., 1000.))) ^ + bdata::random((bdata::seed = 21221, + bdata::distribution = + std::uniform_real_distribution<>(-1000., 1000.))) ^ + bdata::random((bdata::seed = 62132, + bdata::distribution = + std::uniform_real_distribution<>(-1000., 1000.))) ^ + bdata::random(( + bdata::seed = 91683, + bdata::distribution = std::uniform_real_distribution<>(0., M_PI))) ^ + bdata::random(( + bdata::seed = 39847, + bdata::distribution = std::uniform_real_distribution<>(0., M_PI))) ^ + bdata::random(( + bdata::seed = 72615, + bdata::distribution = std::uniform_real_distribution<>(0., M_PI))) ^ + bdata::xrange(100), + x, y, z, a, b, c, index) { + (void)index; + + Vector3D center{x, y, z}; + auto transform = std::make_shared<Transform3D>(); + transform->setIdentity(); + RotationMatrix3D rot; + rot = AngleAxis3D(a, Vector3D::UnitX()) * AngleAxis3D(b, Vector3D::UnitY()) * + AngleAxis3D(c, Vector3D::UnitZ()); + transform->prerotate(rot); + transform->pretranslate(center); + + auto bounds = std::make_shared<CylinderBounds>(100., 1200.); + std::shared_ptr<const Surface> cSurface = + Surface::makeShared<CylinderSurface>(transform, bounds); + + // now create parameters on this surface + // rPhi, a, phi, theta, q/p (1/p) + std::array<double, 5> pars_array = {{125., 343., 0.45, 0.888, 0.001}}; + TrackParametersBase::ParVector_t pars; + pars << pars_array[0], pars_array[1], pars_array[2], pars_array[3], + pars_array[4]; + + const double phi = pars_array[2]; + const double theta = pars_array[3]; + double p = fabs(1. / pars_array[4]); + Vector3D direction(cos(phi) * sin(theta), sin(phi) * sin(theta), cos(theta)); + Vector3D mom = p * direction; + + // 3D position in local frame + const double phi_l = pars_array[0] / bounds->r(); + Vector3D pos = (bounds->r() * cos(phi_l)) * rot.col(0) + + (bounds->r() * sin(phi_l)) * rot.col(1) + + (pars_array[1]) * rot.col(2) + center; + + // constructor from parameter vector + BoundParameters ataCylinder_from_pars(tgContext, nullptr, pars, cSurface); + consistencyCheck(ataCylinder_from_pars, pos, mom, 1., pars_array); + // constructor from global parameters + BoundParameters ataCylinder_from_global(tgContext, nullptr, pos, mom, 1., + cSurface); + consistencyCheck(ataCylinder_from_global, pos, mom, 1., pars_array); + // constructor for neutral parameters + NeutralBoundParameters n_ataCylinder_from_pars(tgContext, nullptr, pars, + cSurface); + consistencyCheck(n_ataCylinder_from_pars, pos, mom, 0., pars_array); + // constructor for neutral global parameters + NeutralBoundParameters n_ataCylinder_from_global(tgContext, nullptr, pos, mom, + cSurface); + consistencyCheck(n_ataCylinder_from_global, pos, mom, 0., pars_array); + + // check shared ownership of same surface + BOOST_CHECK_EQUAL(&ataCylinder_from_pars.referenceSurface(), cSurface.get()); + BOOST_CHECK_EQUAL(&ataCylinder_from_pars.referenceSurface(), + &ataCylinder_from_global.referenceSurface()); + BOOST_CHECK_EQUAL(&n_ataCylinder_from_pars.referenceSurface(), + cSurface.get()); + BOOST_CHECK_EQUAL(&n_ataCylinder_from_pars.referenceSurface(), + &n_ataCylinder_from_global.referenceSurface()); + BOOST_CHECK_EQUAL(cSurface.use_count(), 5); + + auto pPosition = ataCylinder_from_pars.position(); + // the reference frame is + // transverse plane to the cylinder at the intersect + Vector3D normal_at_intersect = cSurface->normal(tgContext, pPosition); + Vector3D transverse_y = rot.col(2); + Vector3D transverse_x = transverse_y.cross(normal_at_intersect); + RotationMatrix3D refframe; + refframe.col(0) = transverse_x; + refframe.col(1) = transverse_y; + refframe.col(2) = normal_at_intersect; + // check if the manually constructed reference frame is the provided one + CHECK_CLOSE_REL(ataCylinder_from_pars.referenceFrame(tgContext), refframe, + 1e-6); +} + +/// @brief Unit test for parameters at the perigee +/// +BOOST_DATA_TEST_CASE( + bound_to_perigee_test, + bdata::random( + (bdata::seed = 3980, + bdata::distribution = std::uniform_real_distribution<>(-10., 10.))) ^ + bdata::random((bdata::seed = 2221, + bdata::distribution = + std::uniform_real_distribution<>(-10., 10.))) ^ + bdata::random((bdata::seed = 2132, + bdata::distribution = + std::uniform_real_distribution<>(-10., 10.))) ^ + bdata::random(( + bdata::seed = 9183, + bdata::distribution = std::uniform_real_distribution<>(0., 0.05))) ^ + bdata::random(( + bdata::seed = 3947, + bdata::distribution = std::uniform_real_distribution<>(0., 0.05))) ^ + bdata::xrange(100), + x, y, z, a, b, index) { + (void)index; + Vector3D center{x, y, z}; + auto transform = std::make_shared<Transform3D>(); + transform->setIdentity(); + RotationMatrix3D rot; + rot = AngleAxis3D(a, Vector3D::UnitX()) * AngleAxis3D(b, Vector3D::UnitY()); + transform->prerotate(rot); + transform->pretranslate(center); + + // the straw surface + std::shared_ptr<const Surface> pSurface = Surface::makeShared<PerigeeSurface>( + std::make_shared<const Transform3D>(*transform)); + + // now create parameters on this surface + // d0, z0, phi, theta, q/p (1/p) + std::array<double, 5> pars_array = {{-0.7321, 22.5, 0.45, 0.888, 0.001}}; + TrackParametersBase::ParVector_t pars; + pars << pars_array[0], pars_array[1], pars_array[2], pars_array[3], + pars_array[4]; + + BoundParameters ataPerigee_from_pars(tgContext, nullptr, pars, pSurface); + auto pos = ataPerigee_from_pars.position(); + auto mom = ataPerigee_from_pars.momentum(); + consistencyCheck(ataPerigee_from_pars, pos, mom, 1., pars_array); + // constructor from global parameters + BoundParameters ataPerigee_from_global(tgContext, nullptr, pos, mom, 1., + pSurface); + consistencyCheck(ataPerigee_from_global, pos, mom, 1., pars_array); + // constructor for neutral parameters + NeutralBoundParameters n_ataPerigee_from_pars(tgContext, nullptr, pars, + pSurface); + consistencyCheck(n_ataPerigee_from_pars, pos, mom, 0., pars_array); + // constructor for neutral global parameters + NeutralBoundParameters n_ataPerigee_from_global(tgContext, nullptr, pos, mom, + pSurface); + consistencyCheck(n_ataPerigee_from_global, pos, mom, 0., pars_array); + + // check shared ownership of same surface + BOOST_CHECK_EQUAL(&ataPerigee_from_pars.referenceSurface(), pSurface.get()); + BOOST_CHECK_EQUAL(&ataPerigee_from_pars.referenceSurface(), + &ataPerigee_from_global.referenceSurface()); + BOOST_CHECK_EQUAL(&n_ataPerigee_from_pars.referenceSurface(), pSurface.get()); + BOOST_CHECK_EQUAL(&n_ataPerigee_from_pars.referenceSurface(), + &n_ataPerigee_from_global.referenceSurface()); + BOOST_CHECK_EQUAL(pSurface.use_count(), 5); +} + +/// @brief Unit test for parameters at a line +/// +BOOST_DATA_TEST_CASE( + bound_to_line_test, + bdata::random((bdata::seed = 73980, + bdata::distribution = + std::uniform_real_distribution<>(-1000., 1000.))) ^ + bdata::random((bdata::seed = 21221, + bdata::distribution = + std::uniform_real_distribution<>(-1000., 1000.))) ^ + bdata::random((bdata::seed = 62992, + bdata::distribution = + std::uniform_real_distribution<>(-1000., 1000.))) ^ + bdata::random(( + bdata::seed = 900683, + bdata::distribution = std::uniform_real_distribution<>(0., M_PI))) ^ + bdata::random(( + bdata::seed = 5439847, + bdata::distribution = std::uniform_real_distribution<>(0., M_PI))) ^ + bdata::random(( + bdata::seed = 1972615, + bdata::distribution = std::uniform_real_distribution<>(0., M_PI))) ^ + bdata::xrange(100), + x, y, z, a, b, c, index) { + (void)index; + + Vector3D center{x, y, z}; + auto transform = std::make_shared<Transform3D>(); + transform->setIdentity(); + RotationMatrix3D rot; + rot = AngleAxis3D(a, Vector3D::UnitX()) * AngleAxis3D(b, Vector3D::UnitY()) * + AngleAxis3D(c, Vector3D::UnitZ()); + transform->prerotate(rot); + transform->pretranslate(center); + + // the straw surface + auto sSurface = Surface::makeShared<StrawSurface>( + transform, 2. * Acts::units::_mm, 1. * Acts::units::_m); + + // now create parameters on this surface + // r, z, phi, theta, q/p (1/p) + std::array<double, 5> pars_array = {{0.2321, 22.5, 0.45, 0.888, 0.001}}; + TrackParametersBase::ParVector_t pars; + pars << pars_array[0], pars_array[1], pars_array[2], pars_array[3], + pars_array[4]; + + // constructor from parameter vector + BoundParameters ataLine_from_pars(tgContext, nullptr, pars, sSurface); + auto pos = ataLine_from_pars.position(); + auto mom = ataLine_from_pars.momentum(); + consistencyCheck(ataLine_from_pars, pos, mom, 1., pars_array); + // constructor from global parameters + BoundParameters ataLine_from_global(tgContext, nullptr, pos, mom, 1., + sSurface); + consistencyCheck(ataLine_from_global, pos, mom, 1., pars_array); + // constructor for neutral parameters + NeutralBoundParameters n_ataLine_from_pars(tgContext, nullptr, pars, + sSurface); + consistencyCheck(n_ataLine_from_pars, pos, mom, 0., pars_array); + // constructor for neutral global parameters + NeutralBoundParameters n_ataLine_from_global(tgContext, nullptr, pos, mom, + sSurface); + consistencyCheck(n_ataLine_from_global, pos, mom, 0., pars_array); + + // check shared ownership of same surface + BOOST_CHECK_EQUAL(&ataLine_from_pars.referenceSurface(), sSurface.get()); + BOOST_CHECK_EQUAL(&ataLine_from_pars.referenceSurface(), + &ataLine_from_global.referenceSurface()); + BOOST_CHECK_EQUAL(&n_ataLine_from_pars.referenceSurface(), sSurface.get()); + BOOST_CHECK_EQUAL(&n_ataLine_from_pars.referenceSurface(), + &n_ataLine_from_global.referenceSurface()); + BOOST_CHECK_EQUAL(sSurface.use_count(), 5); } +} // namespace Test +} // namespace Acts diff --git a/Tests/Core/EventData/CurvilinearParametersTests.cpp b/Tests/Core/EventData/CurvilinearParametersTests.cpp index 61d72f08d02f5532a25dd99bbf12588970f98bb7..a75e878844629aa5b82f8c07622b68251278a1c8 100644 --- a/Tests/Core/EventData/CurvilinearParametersTests.cpp +++ b/Tests/Core/EventData/CurvilinearParametersTests.cpp @@ -24,116 +24,112 @@ using VectorHelpers::phi; using VectorHelpers::theta; namespace Test { - /// @brief Unit test for Curvilinear parameters - /// - BOOST_AUTO_TEST_CASE(curvilinear_initialization) - { - - // Create a test context - GeometryContext tgContext = GeometryContext(); - - // some position and momentum - Vector3D pos(1.34, 2.34, 3.45); - Vector3D mom(1000., 1000., -0.100); - Vector3D dir(mom.normalized()); - Vector3D z_axis_global(0., 0., 1.); - /// create curvilinear parameters without covariance +1/-1 charge - CurvilinearParameters curvilinear_pos(nullptr, pos, mom, 1.); - CurvilinearParameters curvilinear_neg(nullptr, pos, mom, -1.); - NeutralCurvilinearParameters curvilinear_neut(nullptr, pos, mom); - - /// check local coordinates - const auto fphi = phi(mom); - const auto ftheta = theta(mom); - const double oOp = 1. / mom.norm(); - - // check parameters - consistencyCheck( - curvilinear_pos, pos, mom, +1., {{0., 0., fphi, ftheta, oOp}}); - consistencyCheck( - curvilinear_neg, pos, mom, -1., {{0., 0., fphi, ftheta, -oOp}}); - consistencyCheck( - curvilinear_neut, pos, mom, 0., {{0., 0., fphi, ftheta, oOp}}); - - // check that the created surface is at the position - CHECK_CLOSE_REL( - curvilinear_pos.referenceSurface().center(tgContext), pos, 1e-6); - CHECK_CLOSE_REL( - curvilinear_neg.referenceSurface().center(tgContext), pos, 1e-6); - CHECK_CLOSE_REL( - curvilinear_neut.referenceSurface().center(tgContext), pos, 1e-6); - - // check that the z-axis of the created surface is along momentum direction - CHECK_CLOSE_REL( - curvilinear_pos.referenceSurface().normal(tgContext, pos), dir, 1e-6); - CHECK_CLOSE_REL( - curvilinear_neg.referenceSurface().normal(tgContext, pos), dir, 1e-6); - CHECK_CLOSE_REL( - curvilinear_neut.referenceSurface().normal(tgContext, pos), dir, 1e-6); - - // check the reference frame of curvilinear parameters - // it is the x-y frame of the created surface - RotationMatrix3D mFrame = RotationMatrix3D::Zero(); - Vector3D tAxis = dir; - Vector3D uAxis = (z_axis_global.cross(tAxis)).normalized(); - Vector3D vAxis = tAxis.cross(uAxis); - mFrame.col(0) = uAxis; - mFrame.col(1) = vAxis; - mFrame.col(2) = tAxis; - CHECK_CLOSE_OR_SMALL( - mFrame, curvilinear_pos.referenceFrame(tgContext), 1e-6, 1e-9); - CHECK_CLOSE_OR_SMALL( - mFrame, curvilinear_neg.referenceFrame(tgContext), 1e-6, 1e-9); - CHECK_CLOSE_OR_SMALL( - mFrame, curvilinear_neut.referenceFrame(tgContext), 1e-6, 1e-9); - - /// copy construction test - CurvilinearParameters curvilinear_pos_copy(curvilinear_pos); - CurvilinearParameters curvilinear_neg_copy(curvilinear_neg); - NeutralCurvilinearParameters curvilinear_neut_copy(curvilinear_neut); - - BOOST_CHECK_EQUAL(curvilinear_pos_copy, curvilinear_pos); - BOOST_CHECK_EQUAL(curvilinear_neg_copy, curvilinear_neg); - BOOST_CHECK_EQUAL(curvilinear_neut_copy, curvilinear_neut); - - /// modification test with set methods - double ux = 0.1; - double uy = 0.5; - curvilinear_pos_copy.set<eLOC_0>(tgContext, ux); - curvilinear_pos_copy.set<eLOC_1>(tgContext, uy); - // the local parameter should still be (0,0) for Curvilinear - BOOST_CHECK_EQUAL(curvilinear_pos_copy.parameters()[eLOC_0], 0); - BOOST_CHECK_EQUAL(curvilinear_pos_copy.parameters()[eLOC_1], 0); - // the position should be updated though - Vector3D uposition - = curvilinear_neg_copy.referenceSurface().transform(tgContext) - * Vector3D(ux, uy, 0.); - // the position should be updated - CHECK_CLOSE_REL(curvilinear_pos_copy.position(), uposition, 1e-6); - // it should be the position of the surface - CHECK_CLOSE_REL(curvilinear_pos_copy.referenceSurface().center(tgContext), - uposition, - 1e-6); - - double uphi = 1.2; - double utheta = 0.2; - double uqop = 0.025; - - curvilinear_pos_copy.set<ePHI>(tgContext, uphi); - curvilinear_pos_copy.set<eTHETA>(tgContext, utheta); - curvilinear_pos_copy.set<eQOP>(tgContext, uqop); - // we should have a new updated momentum - Vector3D umomentum = 40. * Vector3D(cos(uphi) * sin(utheta), - sin(uphi) * sin(utheta), - cos(utheta)); - CHECK_CLOSE_REL(umomentum, curvilinear_pos_copy.momentum(), 1e-6); - // the updated momentum should be the col(2) of the transform - CHECK_CLOSE_REL(umomentum.normalized(), - curvilinear_pos_copy.referenceSurface() - .transform(tgContext) - .rotation() - .col(2), - 1e-6); - } +/// @brief Unit test for Curvilinear parameters +/// +BOOST_AUTO_TEST_CASE(curvilinear_initialization) { + // Create a test context + GeometryContext tgContext = GeometryContext(); + + // some position and momentum + Vector3D pos(1.34, 2.34, 3.45); + Vector3D mom(1000., 1000., -0.100); + Vector3D dir(mom.normalized()); + Vector3D z_axis_global(0., 0., 1.); + /// create curvilinear parameters without covariance +1/-1 charge + CurvilinearParameters curvilinear_pos(nullptr, pos, mom, 1.); + CurvilinearParameters curvilinear_neg(nullptr, pos, mom, -1.); + NeutralCurvilinearParameters curvilinear_neut(nullptr, pos, mom); + + /// check local coordinates + const auto fphi = phi(mom); + const auto ftheta = theta(mom); + const double oOp = 1. / mom.norm(); + + // check parameters + consistencyCheck(curvilinear_pos, pos, mom, +1., + {{0., 0., fphi, ftheta, oOp}}); + consistencyCheck(curvilinear_neg, pos, mom, -1., + {{0., 0., fphi, ftheta, -oOp}}); + consistencyCheck(curvilinear_neut, pos, mom, 0., + {{0., 0., fphi, ftheta, oOp}}); + + // check that the created surface is at the position + CHECK_CLOSE_REL(curvilinear_pos.referenceSurface().center(tgContext), pos, + 1e-6); + CHECK_CLOSE_REL(curvilinear_neg.referenceSurface().center(tgContext), pos, + 1e-6); + CHECK_CLOSE_REL(curvilinear_neut.referenceSurface().center(tgContext), pos, + 1e-6); + + // check that the z-axis of the created surface is along momentum direction + CHECK_CLOSE_REL(curvilinear_pos.referenceSurface().normal(tgContext, pos), + dir, 1e-6); + CHECK_CLOSE_REL(curvilinear_neg.referenceSurface().normal(tgContext, pos), + dir, 1e-6); + CHECK_CLOSE_REL(curvilinear_neut.referenceSurface().normal(tgContext, pos), + dir, 1e-6); + + // check the reference frame of curvilinear parameters + // it is the x-y frame of the created surface + RotationMatrix3D mFrame = RotationMatrix3D::Zero(); + Vector3D tAxis = dir; + Vector3D uAxis = (z_axis_global.cross(tAxis)).normalized(); + Vector3D vAxis = tAxis.cross(uAxis); + mFrame.col(0) = uAxis; + mFrame.col(1) = vAxis; + mFrame.col(2) = tAxis; + CHECK_CLOSE_OR_SMALL(mFrame, curvilinear_pos.referenceFrame(tgContext), 1e-6, + 1e-9); + CHECK_CLOSE_OR_SMALL(mFrame, curvilinear_neg.referenceFrame(tgContext), 1e-6, + 1e-9); + CHECK_CLOSE_OR_SMALL(mFrame, curvilinear_neut.referenceFrame(tgContext), 1e-6, + 1e-9); + + /// copy construction test + CurvilinearParameters curvilinear_pos_copy(curvilinear_pos); + CurvilinearParameters curvilinear_neg_copy(curvilinear_neg); + NeutralCurvilinearParameters curvilinear_neut_copy(curvilinear_neut); + + BOOST_CHECK_EQUAL(curvilinear_pos_copy, curvilinear_pos); + BOOST_CHECK_EQUAL(curvilinear_neg_copy, curvilinear_neg); + BOOST_CHECK_EQUAL(curvilinear_neut_copy, curvilinear_neut); + + /// modification test with set methods + double ux = 0.1; + double uy = 0.5; + curvilinear_pos_copy.set<eLOC_0>(tgContext, ux); + curvilinear_pos_copy.set<eLOC_1>(tgContext, uy); + // the local parameter should still be (0,0) for Curvilinear + BOOST_CHECK_EQUAL(curvilinear_pos_copy.parameters()[eLOC_0], 0); + BOOST_CHECK_EQUAL(curvilinear_pos_copy.parameters()[eLOC_1], 0); + // the position should be updated though + Vector3D uposition = + curvilinear_neg_copy.referenceSurface().transform(tgContext) * + Vector3D(ux, uy, 0.); + // the position should be updated + CHECK_CLOSE_REL(curvilinear_pos_copy.position(), uposition, 1e-6); + // it should be the position of the surface + CHECK_CLOSE_REL(curvilinear_pos_copy.referenceSurface().center(tgContext), + uposition, 1e-6); + + double uphi = 1.2; + double utheta = 0.2; + double uqop = 0.025; + + curvilinear_pos_copy.set<ePHI>(tgContext, uphi); + curvilinear_pos_copy.set<eTHETA>(tgContext, utheta); + curvilinear_pos_copy.set<eQOP>(tgContext, uqop); + // we should have a new updated momentum + Vector3D umomentum = 40. * Vector3D(cos(uphi) * sin(utheta), + sin(uphi) * sin(utheta), cos(utheta)); + CHECK_CLOSE_REL(umomentum, curvilinear_pos_copy.momentum(), 1e-6); + // the updated momentum should be the col(2) of the transform + CHECK_CLOSE_REL(umomentum.normalized(), + curvilinear_pos_copy.referenceSurface() + .transform(tgContext) + .rotation() + .col(2), + 1e-6); +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/EventData/FittableTypeTests.cpp b/Tests/Core/EventData/FittableTypeTests.cpp index c39761f4fe084c206b4eeafa2c20904de5914a19..632527f13cc449326adfb154460982004b29fc57 100644 --- a/Tests/Core/EventData/FittableTypeTests.cpp +++ b/Tests/Core/EventData/FittableTypeTests.cpp @@ -36,177 +36,128 @@ using namespace hana::literals; namespace Acts { namespace Test { - BOOST_AUTO_TEST_CASE(index_combination_generation_test) +BOOST_AUTO_TEST_CASE(index_combination_generation_test) { { - { - constexpr auto result = detail::unique_ordered_sublists<1>(); - constexpr auto expected = hana::make_tuple(_T(0)); - static_assert(result == expected, "At size 1 is not equal"); - } - { - constexpr auto result = detail::unique_ordered_sublists<2>(); - constexpr auto expected = hana::make_tuple(_T(0), _T(1), _T(0, 1)); - static_assert(result == expected, "At size 2 is not equal"); - } - { - constexpr auto result = detail::unique_ordered_sublists<3>(); - constexpr auto expected = hana::make_tuple( - _T(0), _T(1), _T(0, 1), _T(2), _T(0, 2), _T(1, 2), _T(0, 1, 2)); - static_assert(result == expected, "At size 3 is not equal"); - } - { - constexpr auto result = detail::unique_ordered_sublists<4>(); - constexpr auto expected = hana::make_tuple(_T(0), - _T(1), - _T(0, 1), - _T(2), - _T(0, 2), - _T(1, 2), - _T(0, 1, 2), - _T(3), - _T(0, 3), - _T(1, 3), - _T(0, 1, 3), - _T(2, 3), - _T(0, 2, 3), - _T(1, 2, 3), - _T(0, 1, 2, 3)); - static_assert(result == expected, "At size 4 is not equal"); - } - { - constexpr auto result = detail::unique_ordered_sublists<5>(); - constexpr auto expected = hana::make_tuple(_T(0), - _T(1), - _T(0, 1), - _T(2), - _T(0, 2), - _T(1, 2), - _T(0, 1, 2), - _T(3), - _T(0, 3), - _T(1, 3), - _T(0, 1, 3), - _T(2, 3), - _T(0, 2, 3), - _T(1, 2, 3), - _T(0, 1, 2, 3), - _T(4), - _T(0, 4), - _T(1, 4), - _T(0, 1, 4), - _T(2, 4), - _T(0, 2, 4), - _T(1, 2, 4), - _T(0, 1, 2, 4), - _T(3, 4), - _T(0, 3, 4), - _T(1, 3, 4), - _T(0, 1, 3, 4), - _T(2, 3, 4), - _T(0, 2, 3, 4), - _T(1, 2, 3, 4), - _T(0, 1, 2, 3, 4)); - static_assert(result == expected, "At size 5 is not equal"); - } + constexpr auto result = detail::unique_ordered_sublists<1>(); + constexpr auto expected = hana::make_tuple(_T(0)); + static_assert(result == expected, "At size 1 is not equal"); } + { + constexpr auto result = detail::unique_ordered_sublists<2>(); + constexpr auto expected = hana::make_tuple(_T(0), _T(1), _T(0, 1)); + static_assert(result == expected, "At size 2 is not equal"); + } + { + constexpr auto result = detail::unique_ordered_sublists<3>(); + constexpr auto expected = hana::make_tuple(_T(0), _T(1), _T(0, 1), _T(2), + _T(0, 2), _T(1, 2), _T(0, 1, 2)); + static_assert(result == expected, "At size 3 is not equal"); + } + { + constexpr auto result = detail::unique_ordered_sublists<4>(); + constexpr auto expected = + hana::make_tuple(_T(0), _T(1), _T(0, 1), _T(2), _T(0, 2), _T(1, 2), + _T(0, 1, 2), _T(3), _T(0, 3), _T(1, 3), _T(0, 1, 3), + _T(2, 3), _T(0, 2, 3), _T(1, 2, 3), _T(0, 1, 2, 3)); + static_assert(result == expected, "At size 4 is not equal"); + } + { + constexpr auto result = detail::unique_ordered_sublists<5>(); + constexpr auto expected = hana::make_tuple( + _T(0), _T(1), _T(0, 1), _T(2), _T(0, 2), _T(1, 2), _T(0, 1, 2), _T(3), + _T(0, 3), _T(1, 3), _T(0, 1, 3), _T(2, 3), _T(0, 2, 3), _T(1, 2, 3), + _T(0, 1, 2, 3), _T(4), _T(0, 4), _T(1, 4), _T(0, 1, 4), _T(2, 4), + _T(0, 2, 4), _T(1, 2, 4), _T(0, 1, 2, 4), _T(3, 4), _T(0, 3, 4), + _T(1, 3, 4), _T(0, 1, 3, 4), _T(2, 3, 4), _T(0, 2, 3, 4), + _T(1, 2, 3, 4), _T(0, 1, 2, 3, 4)); + static_assert(result == expected, "At size 5 is not equal"); + } +} - using par_t = ParID_t; - using Identifier = long; +using par_t = ParID_t; +using Identifier = long; - template <par_t... pars> - struct meas_factory - { - using type = Measurement<Identifier, pars...>; - }; +template <par_t... pars> +struct meas_factory { + using type = Measurement<Identifier, pars...>; +}; - constexpr par_t operator"" _p(unsigned long long i) { return par_t(i); } +constexpr par_t operator"" _p(unsigned long long i) { + return par_t(i); +} - BOOST_AUTO_TEST_CASE(variant_measurement_generation_test) +BOOST_AUTO_TEST_CASE(variant_measurement_generation_test) { + { + using actual = detail::type_generator_t<meas_factory, 1>; + using expected = std::variant<Measurement<Identifier, 0_p>>; + static_assert(std::is_same<actual, expected>::value, + "Variant is not identical"); + } + { + using actual = detail::type_generator_t<meas_factory, 2>; + using expected = + std::variant<Measurement<Identifier, 0_p>, Measurement<Identifier, 1_p>, + Measurement<Identifier, 0_p, 1_p>>; + static_assert(std::is_same<actual, expected>::value, + "Variant is not identical"); + } + { + using actual = detail::type_generator_t<meas_factory, 3>; + using expected = std::variant< + Measurement<Identifier, 0_p>, Measurement<Identifier, 1_p>, + Measurement<Identifier, 0_p, 1_p>, Measurement<Identifier, 2_p>, + Measurement<Identifier, 0_p, 2_p>, Measurement<Identifier, 1_p, 2_p>, + Measurement<Identifier, 0_p, 1_p, 2_p>>; + static_assert(std::is_same<actual, expected>::value, + "Variant is not identical"); + } + { + using actual = detail::type_generator_t<meas_factory, 4>; + using expected = std::variant< + Measurement<Identifier, 0_p>, Measurement<Identifier, 1_p>, + Measurement<Identifier, 0_p, 1_p>, Measurement<Identifier, 2_p>, + Measurement<Identifier, 0_p, 2_p>, Measurement<Identifier, 1_p, 2_p>, + Measurement<Identifier, 0_p, 1_p, 2_p>, Measurement<Identifier, 3_p>, + Measurement<Identifier, 0_p, 3_p>, Measurement<Identifier, 1_p, 3_p>, + Measurement<Identifier, 0_p, 1_p, 3_p>, + Measurement<Identifier, 2_p, 3_p>, + Measurement<Identifier, 0_p, 2_p, 3_p>, + Measurement<Identifier, 1_p, 2_p, 3_p>, + Measurement<Identifier, 0_p, 1_p, 2_p, 3_p>>; + static_assert(std::is_same<actual, expected>::value, + "Variant is not identical"); + } { - { - using actual = detail::type_generator_t<meas_factory, 1>; - using expected = std::variant<Measurement<Identifier, 0_p>>; - static_assert(std::is_same<actual, expected>::value, - "Variant is not identical"); - } - { - using actual = detail::type_generator_t<meas_factory, 2>; - using expected = std::variant<Measurement<Identifier, 0_p>, - Measurement<Identifier, 1_p>, - Measurement<Identifier, 0_p, 1_p>>; - static_assert(std::is_same<actual, expected>::value, - "Variant is not identical"); - } - { - using actual = detail::type_generator_t<meas_factory, 3>; - using expected = std::variant<Measurement<Identifier, 0_p>, - Measurement<Identifier, 1_p>, - Measurement<Identifier, 0_p, 1_p>, - Measurement<Identifier, 2_p>, - Measurement<Identifier, 0_p, 2_p>, - Measurement<Identifier, 1_p, 2_p>, - Measurement<Identifier, 0_p, 1_p, 2_p>>; - static_assert(std::is_same<actual, expected>::value, - "Variant is not identical"); - } - { - using actual = detail::type_generator_t<meas_factory, 4>; - using expected - = std::variant<Measurement<Identifier, 0_p>, - Measurement<Identifier, 1_p>, - Measurement<Identifier, 0_p, 1_p>, - Measurement<Identifier, 2_p>, - Measurement<Identifier, 0_p, 2_p>, - Measurement<Identifier, 1_p, 2_p>, - Measurement<Identifier, 0_p, 1_p, 2_p>, - Measurement<Identifier, 3_p>, - Measurement<Identifier, 0_p, 3_p>, - Measurement<Identifier, 1_p, 3_p>, - Measurement<Identifier, 0_p, 1_p, 3_p>, - Measurement<Identifier, 2_p, 3_p>, - Measurement<Identifier, 0_p, 2_p, 3_p>, - Measurement<Identifier, 1_p, 2_p, 3_p>, - Measurement<Identifier, 0_p, 1_p, 2_p, 3_p>>; - static_assert(std::is_same<actual, expected>::value, - "Variant is not identical"); - } - { - using actual = detail::type_generator_t<meas_factory, 5>; - using expected - = std::variant<Measurement<Identifier, 0_p>, - Measurement<Identifier, 1_p>, - Measurement<Identifier, 0_p, 1_p>, - Measurement<Identifier, 2_p>, - Measurement<Identifier, 0_p, 2_p>, - Measurement<Identifier, 1_p, 2_p>, - Measurement<Identifier, 0_p, 1_p, 2_p>, - Measurement<Identifier, 3_p>, - Measurement<Identifier, 0_p, 3_p>, - Measurement<Identifier, 1_p, 3_p>, - Measurement<Identifier, 0_p, 1_p, 3_p>, - Measurement<Identifier, 2_p, 3_p>, - Measurement<Identifier, 0_p, 2_p, 3_p>, - Measurement<Identifier, 1_p, 2_p, 3_p>, - Measurement<Identifier, 0_p, 1_p, 2_p, 3_p>, - Measurement<Identifier, 4_p>, - Measurement<Identifier, 0_p, 4_p>, - Measurement<Identifier, 1_p, 4_p>, - Measurement<Identifier, 0_p, 1_p, 4_p>, - Measurement<Identifier, 2_p, 4_p>, - Measurement<Identifier, 0_p, 2_p, 4_p>, - Measurement<Identifier, 1_p, 2_p, 4_p>, - Measurement<Identifier, 0_p, 1_p, 2_p, 4_p>, - Measurement<Identifier, 3_p, 4_p>, - Measurement<Identifier, 0_p, 3_p, 4_p>, - Measurement<Identifier, 1_p, 3_p, 4_p>, - Measurement<Identifier, 0_p, 1_p, 3_p, 4_p>, - Measurement<Identifier, 2_p, 3_p, 4_p>, - Measurement<Identifier, 0_p, 2_p, 3_p, 4_p>, - Measurement<Identifier, 1_p, 2_p, 3_p, 4_p>, - Measurement<Identifier, 0_p, 1_p, 2_p, 3_p, 4_p>>; - static_assert(std::is_same<actual, expected>::value, - "Variant is not identical"); - } + using actual = detail::type_generator_t<meas_factory, 5>; + using expected = std::variant< + Measurement<Identifier, 0_p>, Measurement<Identifier, 1_p>, + Measurement<Identifier, 0_p, 1_p>, Measurement<Identifier, 2_p>, + Measurement<Identifier, 0_p, 2_p>, Measurement<Identifier, 1_p, 2_p>, + Measurement<Identifier, 0_p, 1_p, 2_p>, Measurement<Identifier, 3_p>, + Measurement<Identifier, 0_p, 3_p>, Measurement<Identifier, 1_p, 3_p>, + Measurement<Identifier, 0_p, 1_p, 3_p>, + Measurement<Identifier, 2_p, 3_p>, + Measurement<Identifier, 0_p, 2_p, 3_p>, + Measurement<Identifier, 1_p, 2_p, 3_p>, + Measurement<Identifier, 0_p, 1_p, 2_p, 3_p>, + Measurement<Identifier, 4_p>, Measurement<Identifier, 0_p, 4_p>, + Measurement<Identifier, 1_p, 4_p>, + Measurement<Identifier, 0_p, 1_p, 4_p>, + Measurement<Identifier, 2_p, 4_p>, + Measurement<Identifier, 0_p, 2_p, 4_p>, + Measurement<Identifier, 1_p, 2_p, 4_p>, + Measurement<Identifier, 0_p, 1_p, 2_p, 4_p>, + Measurement<Identifier, 3_p, 4_p>, + Measurement<Identifier, 0_p, 3_p, 4_p>, + Measurement<Identifier, 1_p, 3_p, 4_p>, + Measurement<Identifier, 0_p, 1_p, 3_p, 4_p>, + Measurement<Identifier, 2_p, 3_p, 4_p>, + Measurement<Identifier, 0_p, 2_p, 3_p, 4_p>, + Measurement<Identifier, 1_p, 2_p, 3_p, 4_p>, + Measurement<Identifier, 0_p, 1_p, 2_p, 3_p, 4_p>>; + static_assert(std::is_same<actual, expected>::value, + "Variant is not identical"); } +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/EventData/MeasurementTests.cpp b/Tests/Core/EventData/MeasurementTests.cpp index 97584bc9f0363105adc10345f9fb7f83a8456480..e8faa9d326bcc56af4e5ebd6e41bb3930adb9dcf 100644 --- a/Tests/Core/EventData/MeasurementTests.cpp +++ b/Tests/Core/EventData/MeasurementTests.cpp @@ -19,67 +19,65 @@ namespace Acts { namespace Test { - using Identifier = unsigned long int; - - template <ParID_t... params> - using MeasurementType = Measurement<Identifier, params...>; - - /// @brief Unit test for creation of Measurement object - /// - BOOST_AUTO_TEST_CASE(measurement_initialization) - { - - auto cylinder = Surface::makeShared<CylinderSurface>(nullptr, 3, 10); - - ActsSymMatrixD<2> cov; - cov << 0.04, 0, 0, 0.1; - MeasurementType<ParDef::eLOC_0, ParDef::eLOC_1> m( - cylinder, 0, std::move(cov), -0.1, 0.45); - - std::default_random_engine generator(42); - - // Create a measurement on a cylinder - ActsSymMatrixD<2> covc; - covc << 0.04, 0, 0, 0.1; - MeasurementType<ParDef::eLOC_0, ParDef::eLOC_1> mc( - cylinder, 0, std::move(covc), -0.1, 0.45); - - // Check the copy constructor - auto mcCopy(mc); - - // The surface should be not null and point to the same - const Surface* sfCopy = &mcCopy.referenceSurface(); - BOOST_CHECK_NE(sfCopy, nullptr); - BOOST_CHECK_EQUAL(sfCopy, cylinder.get()); - // The parameters should be identical though - BOOST_CHECK_EQUAL(mc.parameters(), mcCopy.parameters()); - - // check the assignment operator - auto mcAssigned = mc; - - // The surface should be not null and point to the same - const Surface* sfAssigned = &mcAssigned.referenceSurface(); - BOOST_CHECK_NE(sfAssigned, nullptr); - BOOST_CHECK_EQUAL(sfAssigned, cylinder.get()); - // The parameters should be identical though - BOOST_CHECK_EQUAL(mc.parameters(), mcAssigned.parameters()); - - std::vector<MeasurementType<ParDef::eLOC_0, ParDef::eLOC_1>> caMeasurements{ - std::move(mcCopy), std::move(mcAssigned)}; - - auto plane = Surface::makeShared<PlaneSurface>(Vector3D(0., 0., 0.), - Vector3D(1., 0., 0.)); - ActsSymMatrixD<1> covp; - covp << 0.01; - MeasurementType<ParDef::eLOC_0> mp(plane, 1, std::move(covp), 0.1); - - ActsSymMatrixD<2> covpp; - covpp << 0.01, 0., 0., 0.02; - MeasurementType<ParDef::eLOC_0, ParDef::eLOC_1> mpp( - plane, 2, std::move(covpp), 0.1, 0.2); - - std::vector<FittableMeasurement<Identifier>> measurements{ - std::move(mc), std::move(mp), std::move(mpp)}; - } +using Identifier = unsigned long int; + +template <ParID_t... params> +using MeasurementType = Measurement<Identifier, params...>; + +/// @brief Unit test for creation of Measurement object +/// +BOOST_AUTO_TEST_CASE(measurement_initialization) { + auto cylinder = Surface::makeShared<CylinderSurface>(nullptr, 3, 10); + + ActsSymMatrixD<2> cov; + cov << 0.04, 0, 0, 0.1; + MeasurementType<ParDef::eLOC_0, ParDef::eLOC_1> m(cylinder, 0, std::move(cov), + -0.1, 0.45); + + std::default_random_engine generator(42); + + // Create a measurement on a cylinder + ActsSymMatrixD<2> covc; + covc << 0.04, 0, 0, 0.1; + MeasurementType<ParDef::eLOC_0, ParDef::eLOC_1> mc( + cylinder, 0, std::move(covc), -0.1, 0.45); + + // Check the copy constructor + auto mcCopy(mc); + + // The surface should be not null and point to the same + const Surface* sfCopy = &mcCopy.referenceSurface(); + BOOST_CHECK_NE(sfCopy, nullptr); + BOOST_CHECK_EQUAL(sfCopy, cylinder.get()); + // The parameters should be identical though + BOOST_CHECK_EQUAL(mc.parameters(), mcCopy.parameters()); + + // check the assignment operator + auto mcAssigned = mc; + + // The surface should be not null and point to the same + const Surface* sfAssigned = &mcAssigned.referenceSurface(); + BOOST_CHECK_NE(sfAssigned, nullptr); + BOOST_CHECK_EQUAL(sfAssigned, cylinder.get()); + // The parameters should be identical though + BOOST_CHECK_EQUAL(mc.parameters(), mcAssigned.parameters()); + + std::vector<MeasurementType<ParDef::eLOC_0, ParDef::eLOC_1>> caMeasurements{ + std::move(mcCopy), std::move(mcAssigned)}; + + auto plane = Surface::makeShared<PlaneSurface>(Vector3D(0., 0., 0.), + Vector3D(1., 0., 0.)); + ActsSymMatrixD<1> covp; + covp << 0.01; + MeasurementType<ParDef::eLOC_0> mp(plane, 1, std::move(covp), 0.1); + + ActsSymMatrixD<2> covpp; + covpp << 0.01, 0., 0., 0.02; + MeasurementType<ParDef::eLOC_0, ParDef::eLOC_1> mpp( + plane, 2, std::move(covpp), 0.1, 0.2); + + std::vector<FittableMeasurement<Identifier>> measurements{ + std::move(mc), std::move(mp), std::move(mpp)}; +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/EventData/ParameterSetTests.cpp b/Tests/Core/EventData/ParameterSetTests.cpp index 1982d5c9dba4c29f4c241fbd011ca4d92f7af38c..746f18d0ea586a5e5422d5184504c8618b9e382c 100644 --- a/Tests/Core/EventData/ParameterSetTests.cpp +++ b/Tests/Core/EventData/ParameterSetTests.cpp @@ -30,631 +30,605 @@ namespace Acts { /// @brief Namespace for ATS unit tests /// namespace Test { - /// @cond - namespace { - // tolerance used for floating point comparison in this translation unit - const double tol = 1e-6; - - double - get_cyclic_value(double value, double min, double max) - { - return value - (max - min) * std::floor((value - min) / (max - min)); - } - - double - get_cyclic_difference(double a, double b, double min, double max) - { - const double period = max - min; - const double half_period = period / 2; - a = get_cyclic_value(a, min, max); - b = get_cyclic_value(b, min, max); - double raw_diff = a - b; - double diff = (raw_diff > half_period) +/// @cond +namespace { +// tolerance used for floating point comparison in this translation unit +const double tol = 1e-6; + +double get_cyclic_value(double value, double min, double max) { + return value - (max - min) * std::floor((value - min) / (max - min)); +} + +double get_cyclic_difference(double a, double b, double min, double max) { + const double period = max - min; + const double half_period = period / 2; + a = get_cyclic_value(a, min, max); + b = get_cyclic_value(b, min, max); + double raw_diff = a - b; + double diff = + (raw_diff > half_period) ? raw_diff - period : ((raw_diff < -half_period) ? period + raw_diff : raw_diff); - return diff; + return diff; +} + +void check_residuals_for_bound_parameters() { + const double max = par_type_t<ParID_t::eTHETA>::max; + const double min = par_type_t<ParID_t::eTHETA>::min; + double theta_1 = 0.7 * M_PI; + double theta_2 = 0.4 * M_PI; + ActsVectorD<1> dTheta; + dTheta << (theta_1 - theta_2); + + // both parameters inside bounds, difference is positive + ParameterSet<ParID_t::eTHETA> bound1(nullptr, theta_1); + ParameterSet<ParID_t::eTHETA> bound2(nullptr, theta_2); + CHECK_CLOSE_REL(bound1.residual(bound2), dTheta, tol); + + // both parameters inside bound, difference negative + dTheta << (theta_2 - theta_1); + CHECK_CLOSE_REL(bound2.residual(bound1), dTheta, tol); + + // one parameter above upper bound, difference positive + theta_1 = max + 1; + bound1.setParameter<ParID_t::eTHETA>(theta_1); + dTheta << max - theta_2; + CHECK_CLOSE_REL(bound1.residual(bound2), dTheta, tol); + + // one parameter above upper bound, difference negative + dTheta << theta_2 - max; + CHECK_CLOSE_REL(bound2.residual(bound1), dTheta, tol); + + // one parameter below lower bound, difference positive + theta_1 = min - 1; + bound1.setParameter<ParID_t::eTHETA>(theta_1); + dTheta << theta_2 - min; + CHECK_CLOSE_REL(bound2.residual(bound1), dTheta, tol); + + // one parameter below lower bound, difference negative + dTheta << min - theta_2; + CHECK_CLOSE_REL(bound1.residual(bound2), dTheta, tol); + + // both parameters outside bounds, both below + theta_1 = min - 1; + theta_2 = min - 2; + bound1.setParameter<ParID_t::eTHETA>(theta_1); + bound2.setParameter<ParID_t::eTHETA>(theta_2); + CHECK_SMALL(bound1.residual(bound2), tol); + + // both parameters outside bounds, both above + theta_1 = max + 1; + theta_2 = max + 2; + bound1.setParameter<ParID_t::eTHETA>(theta_1); + bound2.setParameter<ParID_t::eTHETA>(theta_2); + CHECK_SMALL(bound1.residual(bound2), tol); + + // both parameters outside bounds, one above, one below + theta_1 = max + 1; + theta_2 = min - 2; + bound1.setParameter<ParID_t::eTHETA>(theta_1); + bound2.setParameter<ParID_t::eTHETA>(theta_2); + dTheta << max - min; + CHECK_CLOSE_REL(bound1.residual(bound2), dTheta, tol); + dTheta << min - max; + CHECK_CLOSE_REL(bound2.residual(bound1), dTheta, tol); +} + +void check_residuals_for_cyclic_parameters() { + const double max = par_type_t<ParID_t::ePHI>::max; + const double min = par_type_t<ParID_t::ePHI>::min; + + double phi_1 = 0.7 * M_PI; + double phi_2 = 0.4 * M_PI; + ActsVectorD<1> dPhi; + dPhi << (phi_1 - phi_2); + + ParameterSet<ParID_t::ePHI> cyclic1(nullptr, phi_1); + ParameterSet<ParID_t::ePHI> cyclic2(nullptr, phi_2); + + // no boundary crossing, difference is positive + CHECK_CLOSE_REL(cyclic1.residual(cyclic2), dPhi, tol); + + // no boundary crossing, difference is negative + CHECK_CLOSE_REL(cyclic2.residual(cyclic1), -dPhi, tol); + + // forward boundary crossing + phi_1 = -0.9 * M_PI; + cyclic1.setParameter<ParID_t::ePHI>(phi_1); + dPhi << get_cyclic_difference(phi_1, phi_2, min, max); + CHECK_CLOSE_REL(cyclic1.residual(cyclic2), dPhi, tol); + CHECK_CLOSE_REL(cyclic2.residual(cyclic1), -dPhi, tol); + + // backward boundary crossing + phi_1 = 0.7 * M_PI; + phi_2 = -0.9 * M_PI; + cyclic1.setParameter<ParID_t::ePHI>(phi_1); + cyclic2.setParameter<ParID_t::ePHI>(phi_2); + dPhi << get_cyclic_difference(phi_1, phi_2, min, max); + CHECK_CLOSE_REL(cyclic1.residual(cyclic2), dPhi, tol); + CHECK_CLOSE_REL(cyclic2.residual(cyclic1), -dPhi, tol); +} + +void random_residual_tests() { + // random number generators + std::default_random_engine e; + std::uniform_real_distribution<float> uniform_dist(-1000, 300); + + const double theta_max = par_type_t<ParID_t::eTHETA>::max; + const double theta_min = par_type_t<ParID_t::eTHETA>::min; + const double phi_max = par_type_t<ParID_t::ePHI>::max; + const double phi_min = par_type_t<ParID_t::ePHI>::min; + + ActsVectorD<5> parValues_1; + ActsVectorD<5> parValues_2; + FullParameterSet parSet_1(nullptr, parValues_1); + FullParameterSet parSet_2(nullptr, parValues_2); + ActsVectorD<5> residual; + const unsigned int toys = 1000; + for (unsigned int i = 0; i < toys; ++i) { + const double loc0_1 = uniform_dist(e); + const double loc1_1 = uniform_dist(e); + const double phi_1 = uniform_dist(e); + const double theta_1 = uniform_dist(e); + const double qop_1 = uniform_dist(e); + parValues_1 << loc0_1, loc1_1, phi_1, theta_1, qop_1; + parSet_1.setParameters(parValues_1); + + const double loc0_2 = uniform_dist(e); + const double loc1_2 = uniform_dist(e); + const double phi_2 = uniform_dist(e); + const double theta_2 = uniform_dist(e); + const double qop_2 = uniform_dist(e); + parValues_2 << loc0_2, loc1_2, phi_2, theta_2, qop_2; + parSet_2.setParameters(parValues_2); + + const double delta_loc0 = loc0_1 - loc0_2; + const double delta_loc1 = loc1_1 - loc1_2; + // for theta make sure that the difference calculation considers the + // restricted value range + const double delta_theta = + (theta_1 > theta_max ? theta_max + : (theta_1 < theta_min ? theta_min : theta_1)) - + (theta_2 > theta_max ? theta_max + : (theta_2 < theta_min ? theta_min : theta_2)); + const double delta_qop = qop_1 - qop_2; + residual = parSet_1.residual(parSet_2); + + // local parameters are unbound -> check for usual difference + if (std::abs(residual(0) - delta_loc0) > tol) { + BOOST_CHECK(false); + break; } - - void - check_residuals_for_bound_parameters() - { - const double max = par_type_t<ParID_t::eTHETA>::max; - const double min = par_type_t<ParID_t::eTHETA>::min; - double theta_1 = 0.7 * M_PI; - double theta_2 = 0.4 * M_PI; - ActsVectorD<1> dTheta; - dTheta << (theta_1 - theta_2); - - // both parameters inside bounds, difference is positive - ParameterSet<ParID_t::eTHETA> bound1(nullptr, theta_1); - ParameterSet<ParID_t::eTHETA> bound2(nullptr, theta_2); - CHECK_CLOSE_REL(bound1.residual(bound2), dTheta, tol); - - // both parameters inside bound, difference negative - dTheta << (theta_2 - theta_1); - CHECK_CLOSE_REL(bound2.residual(bound1), dTheta, tol); - - // one parameter above upper bound, difference positive - theta_1 = max + 1; - bound1.setParameter<ParID_t::eTHETA>(theta_1); - dTheta << max - theta_2; - CHECK_CLOSE_REL(bound1.residual(bound2), dTheta, tol); - - // one parameter above upper bound, difference negative - dTheta << theta_2 - max; - CHECK_CLOSE_REL(bound2.residual(bound1), dTheta, tol); - - // one parameter below lower bound, difference positive - theta_1 = min - 1; - bound1.setParameter<ParID_t::eTHETA>(theta_1); - dTheta << theta_2 - min; - CHECK_CLOSE_REL(bound2.residual(bound1), dTheta, tol); - - // one parameter below lower bound, difference negative - dTheta << min - theta_2; - CHECK_CLOSE_REL(bound1.residual(bound2), dTheta, tol); - - // both parameters outside bounds, both below - theta_1 = min - 1; - theta_2 = min - 2; - bound1.setParameter<ParID_t::eTHETA>(theta_1); - bound2.setParameter<ParID_t::eTHETA>(theta_2); - CHECK_SMALL(bound1.residual(bound2), tol); - - // both parameters outside bounds, both above - theta_1 = max + 1; - theta_2 = max + 2; - bound1.setParameter<ParID_t::eTHETA>(theta_1); - bound2.setParameter<ParID_t::eTHETA>(theta_2); - CHECK_SMALL(bound1.residual(bound2), tol); - - // both parameters outside bounds, one above, one below - theta_1 = max + 1; - theta_2 = min - 2; - bound1.setParameter<ParID_t::eTHETA>(theta_1); - bound2.setParameter<ParID_t::eTHETA>(theta_2); - dTheta << max - min; - CHECK_CLOSE_REL(bound1.residual(bound2), dTheta, tol); - dTheta << min - max; - CHECK_CLOSE_REL(bound2.residual(bound1), dTheta, tol); + if (std::abs(residual(1) - delta_loc1) > tol) { + BOOST_CHECK(false); + break; } - - void - check_residuals_for_cyclic_parameters() - { - const double max = par_type_t<ParID_t::ePHI>::max; - const double min = par_type_t<ParID_t::ePHI>::min; - - double phi_1 = 0.7 * M_PI; - double phi_2 = 0.4 * M_PI; - ActsVectorD<1> dPhi; - dPhi << (phi_1 - phi_2); - - ParameterSet<ParID_t::ePHI> cyclic1(nullptr, phi_1); - ParameterSet<ParID_t::ePHI> cyclic2(nullptr, phi_2); - - // no boundary crossing, difference is positive - CHECK_CLOSE_REL(cyclic1.residual(cyclic2), dPhi, tol); - - // no boundary crossing, difference is negative - CHECK_CLOSE_REL(cyclic2.residual(cyclic1), -dPhi, tol); - - // forward boundary crossing - phi_1 = -0.9 * M_PI; - cyclic1.setParameter<ParID_t::ePHI>(phi_1); - dPhi << get_cyclic_difference(phi_1, phi_2, min, max); - CHECK_CLOSE_REL(cyclic1.residual(cyclic2), dPhi, tol); - CHECK_CLOSE_REL(cyclic2.residual(cyclic1), -dPhi, tol); - - // backward boundary crossing - phi_1 = 0.7 * M_PI; - phi_2 = -0.9 * M_PI; - cyclic1.setParameter<ParID_t::ePHI>(phi_1); - cyclic2.setParameter<ParID_t::ePHI>(phi_2); - dPhi << get_cyclic_difference(phi_1, phi_2, min, max); - CHECK_CLOSE_REL(cyclic1.residual(cyclic2), dPhi, tol); - CHECK_CLOSE_REL(cyclic2.residual(cyclic1), -dPhi, tol); + // phi is a cyclic parameter -> check that (unsigned) difference is not + // larger than half period + // check that corrected(corrected(phi_2) + residual) == corrected(phi_1) + if (std::abs(get_cyclic_value( + get_cyclic_value(phi_2, phi_min, phi_max) + residual(2), + phi_min, phi_max) - + get_cyclic_value(phi_1, phi_min, phi_max)) > tol or + std::abs(residual(2)) > (phi_max - phi_min) / 2) { + BOOST_CHECK(false); + break; } - - void - random_residual_tests() - { - // random number generators - std::default_random_engine e; - std::uniform_real_distribution<float> uniform_dist(-1000, 300); - - const double theta_max = par_type_t<ParID_t::eTHETA>::max; - const double theta_min = par_type_t<ParID_t::eTHETA>::min; - const double phi_max = par_type_t<ParID_t::ePHI>::max; - const double phi_min = par_type_t<ParID_t::ePHI>::min; - - ActsVectorD<5> parValues_1; - ActsVectorD<5> parValues_2; - FullParameterSet parSet_1(nullptr, parValues_1); - FullParameterSet parSet_2(nullptr, parValues_2); - ActsVectorD<5> residual; - const unsigned int toys = 1000; - for (unsigned int i = 0; i < toys; ++i) { - const double loc0_1 = uniform_dist(e); - const double loc1_1 = uniform_dist(e); - const double phi_1 = uniform_dist(e); - const double theta_1 = uniform_dist(e); - const double qop_1 = uniform_dist(e); - parValues_1 << loc0_1, loc1_1, phi_1, theta_1, qop_1; - parSet_1.setParameters(parValues_1); - - const double loc0_2 = uniform_dist(e); - const double loc1_2 = uniform_dist(e); - const double phi_2 = uniform_dist(e); - const double theta_2 = uniform_dist(e); - const double qop_2 = uniform_dist(e); - parValues_2 << loc0_2, loc1_2, phi_2, theta_2, qop_2; - parSet_2.setParameters(parValues_2); - - const double delta_loc0 = loc0_1 - loc0_2; - const double delta_loc1 = loc1_1 - loc1_2; - // for theta make sure that the difference calculation considers the - // restricted value range - const double delta_theta - = (theta_1 > theta_max - ? theta_max - : (theta_1 < theta_min ? theta_min : theta_1)) - - (theta_2 > theta_max - ? theta_max - : (theta_2 < theta_min ? theta_min : theta_2)); - const double delta_qop = qop_1 - qop_2; - residual = parSet_1.residual(parSet_2); - - // local parameters are unbound -> check for usual difference - if (std::abs(residual(0) - delta_loc0) > tol) { - BOOST_CHECK(false); - break; - } - if (std::abs(residual(1) - delta_loc1) > tol) { - BOOST_CHECK(false); - break; - } - // phi is a cyclic parameter -> check that (unsigned) difference is not - // larger than half period - // check that corrected(corrected(phi_2) + residual) == corrected(phi_1) - if (std::abs(get_cyclic_value(get_cyclic_value(phi_2, phi_min, phi_max) - + residual(2), - phi_min, - phi_max) - - get_cyclic_value(phi_1, phi_min, phi_max)) - > tol - or std::abs(residual(2)) > (phi_max - phi_min) / 2) { - BOOST_CHECK(false); - break; - } - // theta is bound -> check that (unsigned) difference is not larger then - // allowed range, check corrected difference - if (std::abs(residual(3) - delta_theta) > tol - or std::abs(residual(3)) > (theta_max - theta_min)) { - BOOST_CHECK(false); - break; - } - // qop is unbound -> check usual difference - if (std::abs(residual(4) - delta_qop) > tol) { - BOOST_CHECK(false); - break; - } - } + // theta is bound -> check that (unsigned) difference is not larger then + // allowed range, check corrected difference + if (std::abs(residual(3) - delta_theta) > tol or + std::abs(residual(3)) > (theta_max - theta_min)) { + BOOST_CHECK(false); + break; + } + // qop is unbound -> check usual difference + if (std::abs(residual(4) - delta_qop) > tol) { + BOOST_CHECK(false); + break; } } - /// @endcond - - /** - * @brief Unit test for checking consistency of ParameterSet class - * - * The following functions are tested to yield the expected result/behavior: - * -# ParameterSet::size - * -# ParameterSet::contains - * -# ParameterSet::getParameter - * -# ParameterSet::getParameters - * -# ParameterSet::getCovariance - * -# ParameterSet::setCovariance - * -# ParameterSet::setParameter - * -# ParameterSet::getUncertainty - */ - BOOST_AUTO_TEST_CASE(parset_consistency_tests) - { - // check template parameter based information - BOOST_CHECK((ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1>::size() == 2)); - - // covariance matrix - ActsSymMatrixD<3> cov; - cov << 1, 0, 0, 0, 1.2, 0.2, 0, 0.2, 0.7; - auto pCovMatrix = std::make_unique<const ActsSymMatrixD<3>>(cov); - - // parameter values - double loc0 = 0.5; - double loc1 = -0.2; - double phi = 0.3 * M_PI; // this should be within [-M_PI,M_PI) to avoid - // failed tests due to angle range corrections - ActsVectorD<3> parValues(loc0, loc1, phi); - - // parameter set with covariance matrix - ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1, ParID_t::ePHI> - parSet_with_cov(std::move(pCovMatrix), loc0, loc1, phi); - - // check number and type of stored parameters - BOOST_CHECK(parSet_with_cov.size() == 3); - BOOST_CHECK(parSet_with_cov.contains<ParID_t::eLOC_0>()); - BOOST_CHECK(parSet_with_cov.contains<ParID_t::eLOC_1>()); - BOOST_CHECK(parSet_with_cov.contains<ParID_t::ePHI>()); - BOOST_CHECK(not parSet_with_cov.contains<ParID_t::eTHETA>()); - BOOST_CHECK(not parSet_with_cov.contains<ParID_t::eQOP>()); - - // check stored parameter values - BOOST_CHECK(parSet_with_cov.getParameter<ParID_t::eLOC_0>() == loc0); - BOOST_CHECK(parSet_with_cov.getParameter<ParID_t::eLOC_1>() == loc1); - BOOST_CHECK(parSet_with_cov.getParameter<ParID_t::ePHI>() == phi); - BOOST_CHECK(parSet_with_cov.getParameters() == parValues); - - // check stored covariance - BOOST_CHECK(parSet_with_cov.getCovariance() != 0); - BOOST_CHECK(*parSet_with_cov.getCovariance() == cov); - BOOST_CHECK(parSet_with_cov.getUncertainty<ParID_t::eLOC_0>() - == sqrt(cov(0, 0))); - BOOST_CHECK(parSet_with_cov.getUncertainty<ParID_t::eLOC_1>() - == sqrt(cov(1, 1))); - BOOST_CHECK(parSet_with_cov.getUncertainty<ParID_t::ePHI>() - == sqrt(cov(2, 2))); - - // same parameter set without covariance matrix - ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1, ParID_t::ePHI> - parSet_without_cov(nullptr, parValues); - - BOOST_CHECK(parSet_without_cov.getCovariance() == 0); - BOOST_CHECK(parSet_without_cov.getUncertainty<ParID_t::eLOC_0>() < 0); - BOOST_CHECK(parSet_without_cov.getUncertainty<ParID_t::eLOC_1>() < 0); - BOOST_CHECK(parSet_without_cov.getUncertainty<ParID_t::ePHI>() < 0); - BOOST_CHECK(parSet_without_cov.getParameters() - == parSet_with_cov.getParameters()); - - // set new covariance matrix - parSet_without_cov.setCovariance( - std::make_unique<const ActsSymMatrixD<3>>(cov)); - - BOOST_CHECK(parSet_without_cov.getCovariance() != 0); - BOOST_CHECK(*parSet_without_cov.getCovariance() == cov); - - // set new parameter values - double newLoc0 = 0.1; - double newLoc1 = 0.6; - double newPhi = -0.15 * M_PI; - parValues << newLoc0, newLoc1, newPhi; - parSet_with_cov.setParameter<ParID_t::eLOC_0>(newLoc0); - parSet_with_cov.setParameter<ParID_t::eLOC_1>(newLoc1); - parSet_with_cov.setParameter<ParID_t::ePHI>(newPhi); - - BOOST_CHECK(parSet_with_cov.getParameter<ParID_t::eLOC_0>() == newLoc0); - BOOST_CHECK(parSet_with_cov.getParameter<ParID_t::eLOC_1>() == newLoc1); - BOOST_CHECK(parSet_with_cov.getParameter<ParID_t::ePHI>() == newPhi); - BOOST_CHECK(parSet_with_cov.getParameters() == parValues); - } - - /** - * @brief Unit test for copy/assignment/swap in ParameterSet class - * - * The behavior of the following functions is checked: - * -# ParameterSet::ParameterSet - * -# ParameterSet::operator= - * -# ParameterSet::swap - */ - BOOST_AUTO_TEST_CASE(parset_copy_assignment_tests) - { - // covariance matrix - ActsSymMatrixD<3> cov; - cov << 1, 0, 0, 0, 1.2, 0.2, 0, 0.2, 0.7; - auto pCovMatrix = std::make_unique<const ActsSymMatrixD<3>>(cov); - - // parameter values - double loc0 = 0.5; - double loc1 = -0.2; - double phi = 0.3 * M_PI; // this should be within [-M_PI,M_PI) to avoid - // failed tests due to angle range corrections - ActsVectorD<3> first_parValues(loc0, loc1, phi); - - // parameter set with covariance matrix - ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1, ParID_t::ePHI> first( - std::move(pCovMatrix), loc0, loc1, phi); - - // check copy constructor - ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1, ParID_t::ePHI> copy(first); - BOOST_CHECK(first == copy); - - // check move constructor - ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1, ParID_t::ePHI> moved( - std::move(copy)); - BOOST_CHECK(first == moved); - - // check assignment operator - ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1, ParID_t::ePHI> assigned - = moved; - BOOST_CHECK(assigned == moved); - - ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1, ParID_t::ePHI> other( - nullptr, 0, 1.7, -0.15); - BOOST_CHECK(assigned != other); - assigned = other; - BOOST_CHECK(assigned == other); - - // check move assignment - BOOST_CHECK(first != assigned); - first = ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1, ParID_t::ePHI>( - assigned); - BOOST_CHECK(first == assigned); - - // check swap method - ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1, ParID_t::ePHI> lhs( - std::move(pCovMatrix), loc0, loc1, phi); - ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1, ParID_t::ePHI> rhs( - nullptr, 2 * loc0, 2 * loc1, 2 * phi); - ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1, ParID_t::ePHI> lhs_copy - = lhs; - ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1, ParID_t::ePHI> rhs_copy - = rhs; - - BOOST_CHECK(lhs != rhs && lhs == lhs_copy && rhs == rhs_copy); - using std::swap; - swap(lhs, rhs); - BOOST_CHECK(lhs != rhs && rhs == lhs_copy && lhs == rhs_copy); - } - - /** - * @brief Unit test for comparison operators in ParameterSet - * - * @sa ParameterSet::operator==, ParameterSet::operator!= - */ - BOOST_AUTO_TEST_CASE(parset_comparison_tests) - { - // covariance matrix - ActsSymMatrixD<3> cov; - cov << 1, 0, 0, 0, 1.2, 0.2, 0, 0.2, 0.7; - auto pCovMatrix = std::make_unique<const ActsSymMatrixD<3>>(cov); - - // parameter values - double loc0 = 0.5; - double loc1 = -0.2; - double phi = 0.3 * M_PI; // this should be within [-M_PI,M_PI) to avoid - // failed tests due to angle range corrections - - // parameter set with covariance matrix - ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1, ParID_t::ePHI> first( - std::move(pCovMatrix), loc0, loc1, phi); - ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1, ParID_t::ePHI> second( - nullptr, 2 * loc0, 2 * loc1, 2 * phi); - - // check self comparison - BOOST_CHECK(first == first); - BOOST_CHECK(not(first != first)); - - // check mutual exclusivity - BOOST_CHECK(first != second); - BOOST_CHECK(not(first == second)); - first = second; - BOOST_CHECK(first == second); - - // check that comparison fails for unequal parameter values - second.setParameter<ParID_t::eLOC_0>(3 * loc0); - BOOST_CHECK(first != second); - first = second; - BOOST_CHECK(first == second); - - second.setParameter<ParID_t::eLOC_1>(3 * loc1); - BOOST_CHECK(first != second); - first = second; - BOOST_CHECK(first == second); - - second.setParameter<ParID_t::ePHI>(3 * phi); - BOOST_CHECK(first != second); - first = second; - BOOST_CHECK(first == second); - - // check that comparison fails for unequal covariance matrices - second.setCovariance(std::make_unique<const ActsSymMatrixD<3>>(cov)); - BOOST_CHECK(first != second); - first = second; - BOOST_CHECK(first == second); - - cov(0, 0) = 2 * cov(0, 0); - second.setCovariance(std::make_unique<const ActsSymMatrixD<3>>(cov)); - BOOST_CHECK(first != second); - first = second; - BOOST_CHECK(first == second); - } - - /** - * @brief Unit test for projection matrices in ParameterSet - * - * Checks the correctness of the projection matrices from the full parameter - * space - * onto different parameter sub-spaces - * - * @sa ParameterSet::projector - */ - BOOST_AUTO_TEST_CASE(parset_projection_tests) - { - ActsMatrixD<1, 5> phi_proj; - phi_proj << 0, 0, 1, 0, 0; - - ActsMatrixD<2, 5> loc0_qop_proj; - loc0_qop_proj << 1, 0, 0, 0, 0, 0, 0, 0, 0, 1; - - ActsMatrixD<2, 5> loc1_theta_proj; - loc1_theta_proj << 0, 1, 0, 0, 0, 0, 0, 0, 1, 0; - - ActsMatrixD<3, 5> loc0_loc1_phi_proj; - loc0_loc1_phi_proj << 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0; - - ActsMatrixD<4, 5> loc0_phi_theta_qop_proj; - loc0_phi_theta_qop_proj << 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, - 0, 0, 0, 1; - - ActsMatrixD<5, 5> loc0_loc1_phi_theta_qop_proj; - loc0_loc1_phi_theta_qop_proj << 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, - 0, 0, 0, 1, 0, 0, 0, 0, 0, 1; - - BOOST_CHECK((ParameterSet<ParID_t::ePHI>::projector() == phi_proj)); - BOOST_CHECK((ParameterSet<ParID_t::eLOC_0, ParID_t::eQOP>::projector() - == loc0_qop_proj)); - BOOST_CHECK((ParameterSet<ParID_t::eLOC_1, ParID_t::eTHETA>::projector() - == loc1_theta_proj)); - BOOST_CHECK((ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1, ParID_t::ePHI>:: - projector() - == loc0_loc1_phi_proj)); - BOOST_CHECK((ParameterSet<ParID_t::eLOC_0, - ParID_t::ePHI, - ParID_t::eTHETA, - ParID_t::eQOP>::projector() - == loc0_phi_theta_qop_proj)); - BOOST_CHECK((ParameterSet<ParID_t::eLOC_0, - ParID_t::eLOC_1, - ParID_t::ePHI, - ParID_t::eTHETA, - ParID_t::eQOP>::projector() - == loc0_loc1_phi_theta_qop_proj)); - } - - /** - * @brief Unit test for residuals between different ParameterSet objects - * - * The result of the residual calculation between two ParameterSet objects is - * checked. - * A test of the automatic correction of stored parameter values for - * out-of-bounds/cyclic - * corrections is also implemented. - * - * @sa ParameterSet::residual, ParameterSet::getParameter - */ - BOOST_AUTO_TEST_CASE(parset_residual_tests) - { - // check unbound parameter type - const double large_number = 12443534120; - const double small_number = -924342675; - const double normal_number = 1.234; - ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1, ParID_t::eQOP> unbound( - nullptr, small_number, large_number, normal_number); - BOOST_CHECK(unbound.getParameter<ParID_t::eLOC_0>() == small_number); - BOOST_CHECK(unbound.getParameter<ParID_t::eLOC_1>() == large_number); - BOOST_CHECK(unbound.getParameter<ParID_t::eQOP>() == normal_number); - - // check bound parameter type - ParameterSet<ParID_t::eTHETA> bound(nullptr, small_number); - BOOST_CHECK((bound.getParameter<ParID_t::eTHETA>() - == par_type_t<ParID_t::eTHETA>::min)); - bound.setParameter<ParID_t::eTHETA>(large_number); - BOOST_CHECK((bound.getParameter<ParID_t::eTHETA>() - == par_type_t<ParID_t::eTHETA>::max)); - bound.setParameter<ParID_t::eTHETA>(normal_number); - BOOST_CHECK((bound.getParameter<ParID_t::eTHETA>() == normal_number)); - - // check cyclic parameter type - ParameterSet<ParID_t::ePHI> cyclic(nullptr, small_number); - // calculate expected results - const double min = par_type_t<ParID_t::ePHI>::min; - const double max = par_type_t<ParID_t::ePHI>::max; - // check that difference between original phi and stored phi is a multiple - // of the cyclic period - double multiple - = (cyclic.getParameter<ParID_t::ePHI>() - small_number) / (max - min); - BOOST_CHECK(cyclic.getParameter<ParID_t::ePHI>() >= min); - BOOST_CHECK(cyclic.getParameter<ParID_t::ePHI>() < max); - BOOST_CHECK(std::abs(multiple - std::floor(multiple + 0.5)) < tol); - - cyclic.setParameter<ParID_t::ePHI>(large_number); - multiple - = (cyclic.getParameter<ParID_t::ePHI>() - large_number) / (max - min); - BOOST_CHECK(cyclic.getParameter<ParID_t::ePHI>() >= min); - BOOST_CHECK(cyclic.getParameter<ParID_t::ePHI>() < max); - BOOST_CHECK(std::abs(multiple - std::floor(multiple + 0.5)) < tol); - - cyclic.setParameter<ParID_t::ePHI>(normal_number); - multiple - = (cyclic.getParameter<ParID_t::ePHI>() - normal_number) / (max - min); - BOOST_CHECK(cyclic.getParameter<ParID_t::ePHI>() >= min); - BOOST_CHECK(cyclic.getParameter<ParID_t::ePHI>() < max); - BOOST_CHECK(std::abs(multiple - std::floor(multiple + 0.5)) < tol); - - // check residual calculation - - // input numbers - const double first_loc0 = 0.3; - const double first_phi = 0.9 * M_PI; - const double first_theta = 0.7 * M_PI; - - const double second_loc0 = 2.7; - const double second_phi = -0.9 * M_PI; - const double second_theta = 0.35 * M_PI; - - // expected results for residual second wrt first - const double delta_loc0 = second_loc0 - first_loc0; - const double delta_phi - = get_cyclic_difference(second_phi, first_phi, min, max); - const double delta_theta = second_theta - first_theta; - ActsVectorD<3> residuals(delta_loc0, delta_phi, delta_theta); - - ParameterSet<ParID_t::eLOC_0, ParID_t::ePHI, ParID_t::eTHETA> first( - nullptr, first_loc0, first_phi, first_theta); - ParameterSet<ParID_t::eLOC_0, ParID_t::ePHI, ParID_t::eTHETA> second( - nullptr, second_loc0, second_phi, second_theta); - CHECK_CLOSE_REL(residuals, second.residual(first), 1e-6); - - // some more checks for bound variables - check_residuals_for_bound_parameters(); - - // some more checks for cyclic variables - check_residuals_for_cyclic_parameters(); - - // inspecific residual tests with random numbers - random_residual_tests(); - } - - template <ParID_t... params> - using ParSet = ParameterSet<params...>; - - /** - * @brief Unit test for index-/type-based access of coordinates - * - * @sa ParameterSet::getIndex - * @sa ParameterSet::getParID - */ - BOOST_AUTO_TEST_CASE(parset_parID_mapping) - { - // check logic for type-based access - BOOST_CHECK((ParSet<eLOC_0, eLOC_1, ePHI, eQOP>::getIndex<eLOC_0>() == 0)); - BOOST_CHECK((ParSet<eLOC_0, eLOC_1, ePHI, eQOP>::getIndex<eLOC_1>() == 1)); - BOOST_CHECK((ParSet<eLOC_0, eLOC_1, ePHI, eQOP>::getIndex<ePHI>() == 2)); - BOOST_CHECK((ParSet<eLOC_0, eLOC_1, ePHI, eQOP>::getIndex<eQOP>() == 3)); - - // check logic for index-based access - BOOST_CHECK((ParSet<eLOC_0, eLOC_1, ePHI, eQOP>::getParID<0>() == eLOC_0)); - BOOST_CHECK((ParSet<eLOC_0, eLOC_1, ePHI, eQOP>::getParID<1>() == eLOC_1)); - BOOST_CHECK((ParSet<eLOC_0, eLOC_1, ePHI, eQOP>::getParID<2>() == ePHI)); - BOOST_CHECK((ParSet<eLOC_0, eLOC_1, ePHI, eQOP>::getParID<3>() == eQOP)); - - // check consistency - using FullSet = FullParameterSet; - BOOST_CHECK((FullSet::getIndex<FullSet::getParID<0>()>() == 0)); - BOOST_CHECK((FullSet::getIndex<FullSet::getParID<1>()>() == 1)); - BOOST_CHECK((FullSet::getIndex<FullSet::getParID<2>()>() == 2)); - BOOST_CHECK((FullSet::getIndex<FullSet::getParID<3>()>() == 3)); - BOOST_CHECK((FullSet::getIndex<FullSet::getParID<4>()>() == 4)); - - BOOST_CHECK((FullSet::getParID<FullSet::getIndex<eLOC_0>()>() == eLOC_0)); - BOOST_CHECK((FullSet::getParID<FullSet::getIndex<eLOC_1>()>() == eLOC_1)); - BOOST_CHECK((FullSet::getParID<FullSet::getIndex<ePHI>()>() == ePHI)); - BOOST_CHECK((FullSet::getParID<FullSet::getIndex<eTHETA>()>() == eTHETA)); - BOOST_CHECK((FullSet::getParID<FullSet::getIndex<eQOP>()>() == eQOP)); - - // consistency of types - BOOST_CHECK((std::is_same<std::remove_cv<decltype( - at_index<ParID_t, 0, eLOC_0>::value)>::type, - decltype(eLOC_0)>::value)); - BOOST_CHECK((std::is_same<decltype(FullSet::getParID<0>()), - decltype(eLOC_0)>::value)); - } +} +} // namespace +/// @endcond + +/** + * @brief Unit test for checking consistency of ParameterSet class + * + * The following functions are tested to yield the expected result/behavior: + * -# ParameterSet::size + * -# ParameterSet::contains + * -# ParameterSet::getParameter + * -# ParameterSet::getParameters + * -# ParameterSet::getCovariance + * -# ParameterSet::setCovariance + * -# ParameterSet::setParameter + * -# ParameterSet::getUncertainty + */ +BOOST_AUTO_TEST_CASE(parset_consistency_tests) { + // check template parameter based information + BOOST_CHECK((ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1>::size() == 2)); + + // covariance matrix + ActsSymMatrixD<3> cov; + cov << 1, 0, 0, 0, 1.2, 0.2, 0, 0.2, 0.7; + auto pCovMatrix = std::make_unique<const ActsSymMatrixD<3>>(cov); + + // parameter values + double loc0 = 0.5; + double loc1 = -0.2; + double phi = 0.3 * M_PI; // this should be within [-M_PI,M_PI) to avoid + // failed tests due to angle range corrections + ActsVectorD<3> parValues(loc0, loc1, phi); + + // parameter set with covariance matrix + ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1, ParID_t::ePHI> parSet_with_cov( + std::move(pCovMatrix), loc0, loc1, phi); + + // check number and type of stored parameters + BOOST_CHECK(parSet_with_cov.size() == 3); + BOOST_CHECK(parSet_with_cov.contains<ParID_t::eLOC_0>()); + BOOST_CHECK(parSet_with_cov.contains<ParID_t::eLOC_1>()); + BOOST_CHECK(parSet_with_cov.contains<ParID_t::ePHI>()); + BOOST_CHECK(not parSet_with_cov.contains<ParID_t::eTHETA>()); + BOOST_CHECK(not parSet_with_cov.contains<ParID_t::eQOP>()); + + // check stored parameter values + BOOST_CHECK(parSet_with_cov.getParameter<ParID_t::eLOC_0>() == loc0); + BOOST_CHECK(parSet_with_cov.getParameter<ParID_t::eLOC_1>() == loc1); + BOOST_CHECK(parSet_with_cov.getParameter<ParID_t::ePHI>() == phi); + BOOST_CHECK(parSet_with_cov.getParameters() == parValues); + + // check stored covariance + BOOST_CHECK(parSet_with_cov.getCovariance() != 0); + BOOST_CHECK(*parSet_with_cov.getCovariance() == cov); + BOOST_CHECK(parSet_with_cov.getUncertainty<ParID_t::eLOC_0>() == + sqrt(cov(0, 0))); + BOOST_CHECK(parSet_with_cov.getUncertainty<ParID_t::eLOC_1>() == + sqrt(cov(1, 1))); + BOOST_CHECK(parSet_with_cov.getUncertainty<ParID_t::ePHI>() == + sqrt(cov(2, 2))); + + // same parameter set without covariance matrix + ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1, ParID_t::ePHI> + parSet_without_cov(nullptr, parValues); + + BOOST_CHECK(parSet_without_cov.getCovariance() == 0); + BOOST_CHECK(parSet_without_cov.getUncertainty<ParID_t::eLOC_0>() < 0); + BOOST_CHECK(parSet_without_cov.getUncertainty<ParID_t::eLOC_1>() < 0); + BOOST_CHECK(parSet_without_cov.getUncertainty<ParID_t::ePHI>() < 0); + BOOST_CHECK(parSet_without_cov.getParameters() == + parSet_with_cov.getParameters()); + + // set new covariance matrix + parSet_without_cov.setCovariance( + std::make_unique<const ActsSymMatrixD<3>>(cov)); + + BOOST_CHECK(parSet_without_cov.getCovariance() != 0); + BOOST_CHECK(*parSet_without_cov.getCovariance() == cov); + + // set new parameter values + double newLoc0 = 0.1; + double newLoc1 = 0.6; + double newPhi = -0.15 * M_PI; + parValues << newLoc0, newLoc1, newPhi; + parSet_with_cov.setParameter<ParID_t::eLOC_0>(newLoc0); + parSet_with_cov.setParameter<ParID_t::eLOC_1>(newLoc1); + parSet_with_cov.setParameter<ParID_t::ePHI>(newPhi); + + BOOST_CHECK(parSet_with_cov.getParameter<ParID_t::eLOC_0>() == newLoc0); + BOOST_CHECK(parSet_with_cov.getParameter<ParID_t::eLOC_1>() == newLoc1); + BOOST_CHECK(parSet_with_cov.getParameter<ParID_t::ePHI>() == newPhi); + BOOST_CHECK(parSet_with_cov.getParameters() == parValues); +} + +/** + * @brief Unit test for copy/assignment/swap in ParameterSet class + * + * The behavior of the following functions is checked: + * -# ParameterSet::ParameterSet + * -# ParameterSet::operator= + * -# ParameterSet::swap + */ +BOOST_AUTO_TEST_CASE(parset_copy_assignment_tests) { + // covariance matrix + ActsSymMatrixD<3> cov; + cov << 1, 0, 0, 0, 1.2, 0.2, 0, 0.2, 0.7; + auto pCovMatrix = std::make_unique<const ActsSymMatrixD<3>>(cov); + + // parameter values + double loc0 = 0.5; + double loc1 = -0.2; + double phi = 0.3 * M_PI; // this should be within [-M_PI,M_PI) to avoid + // failed tests due to angle range corrections + ActsVectorD<3> first_parValues(loc0, loc1, phi); + + // parameter set with covariance matrix + ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1, ParID_t::ePHI> first( + std::move(pCovMatrix), loc0, loc1, phi); + + // check copy constructor + ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1, ParID_t::ePHI> copy(first); + BOOST_CHECK(first == copy); + + // check move constructor + ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1, ParID_t::ePHI> moved( + std::move(copy)); + BOOST_CHECK(first == moved); + + // check assignment operator + ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1, ParID_t::ePHI> assigned = + moved; + BOOST_CHECK(assigned == moved); + + ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1, ParID_t::ePHI> other( + nullptr, 0, 1.7, -0.15); + BOOST_CHECK(assigned != other); + assigned = other; + BOOST_CHECK(assigned == other); + + // check move assignment + BOOST_CHECK(first != assigned); + first = + ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1, ParID_t::ePHI>(assigned); + BOOST_CHECK(first == assigned); + + // check swap method + ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1, ParID_t::ePHI> lhs( + std::move(pCovMatrix), loc0, loc1, phi); + ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1, ParID_t::ePHI> rhs( + nullptr, 2 * loc0, 2 * loc1, 2 * phi); + ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1, ParID_t::ePHI> lhs_copy = lhs; + ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1, ParID_t::ePHI> rhs_copy = rhs; + + BOOST_CHECK(lhs != rhs && lhs == lhs_copy && rhs == rhs_copy); + using std::swap; + swap(lhs, rhs); + BOOST_CHECK(lhs != rhs && rhs == lhs_copy && lhs == rhs_copy); +} + +/** + * @brief Unit test for comparison operators in ParameterSet + * + * @sa ParameterSet::operator==, ParameterSet::operator!= + */ +BOOST_AUTO_TEST_CASE(parset_comparison_tests) { + // covariance matrix + ActsSymMatrixD<3> cov; + cov << 1, 0, 0, 0, 1.2, 0.2, 0, 0.2, 0.7; + auto pCovMatrix = std::make_unique<const ActsSymMatrixD<3>>(cov); + + // parameter values + double loc0 = 0.5; + double loc1 = -0.2; + double phi = 0.3 * M_PI; // this should be within [-M_PI,M_PI) to avoid + // failed tests due to angle range corrections + + // parameter set with covariance matrix + ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1, ParID_t::ePHI> first( + std::move(pCovMatrix), loc0, loc1, phi); + ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1, ParID_t::ePHI> second( + nullptr, 2 * loc0, 2 * loc1, 2 * phi); + + // check self comparison + BOOST_CHECK(first == first); + BOOST_CHECK(not(first != first)); + + // check mutual exclusivity + BOOST_CHECK(first != second); + BOOST_CHECK(not(first == second)); + first = second; + BOOST_CHECK(first == second); + + // check that comparison fails for unequal parameter values + second.setParameter<ParID_t::eLOC_0>(3 * loc0); + BOOST_CHECK(first != second); + first = second; + BOOST_CHECK(first == second); + + second.setParameter<ParID_t::eLOC_1>(3 * loc1); + BOOST_CHECK(first != second); + first = second; + BOOST_CHECK(first == second); + + second.setParameter<ParID_t::ePHI>(3 * phi); + BOOST_CHECK(first != second); + first = second; + BOOST_CHECK(first == second); + + // check that comparison fails for unequal covariance matrices + second.setCovariance(std::make_unique<const ActsSymMatrixD<3>>(cov)); + BOOST_CHECK(first != second); + first = second; + BOOST_CHECK(first == second); + + cov(0, 0) = 2 * cov(0, 0); + second.setCovariance(std::make_unique<const ActsSymMatrixD<3>>(cov)); + BOOST_CHECK(first != second); + first = second; + BOOST_CHECK(first == second); +} + +/** + * @brief Unit test for projection matrices in ParameterSet + * + * Checks the correctness of the projection matrices from the full parameter + * space + * onto different parameter sub-spaces + * + * @sa ParameterSet::projector + */ +BOOST_AUTO_TEST_CASE(parset_projection_tests) { + ActsMatrixD<1, 5> phi_proj; + phi_proj << 0, 0, 1, 0, 0; + + ActsMatrixD<2, 5> loc0_qop_proj; + loc0_qop_proj << 1, 0, 0, 0, 0, 0, 0, 0, 0, 1; + + ActsMatrixD<2, 5> loc1_theta_proj; + loc1_theta_proj << 0, 1, 0, 0, 0, 0, 0, 0, 1, 0; + + ActsMatrixD<3, 5> loc0_loc1_phi_proj; + loc0_loc1_phi_proj << 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0; + + ActsMatrixD<4, 5> loc0_phi_theta_qop_proj; + loc0_phi_theta_qop_proj << 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, + 0, 0, 1; + + ActsMatrixD<5, 5> loc0_loc1_phi_theta_qop_proj; + loc0_loc1_phi_theta_qop_proj << 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, + 0, 0, 0, 1, 0, 0, 0, 0, 0, 1; + + BOOST_CHECK((ParameterSet<ParID_t::ePHI>::projector() == phi_proj)); + BOOST_CHECK((ParameterSet<ParID_t::eLOC_0, ParID_t::eQOP>::projector() == + loc0_qop_proj)); + BOOST_CHECK((ParameterSet<ParID_t::eLOC_1, ParID_t::eTHETA>::projector() == + loc1_theta_proj)); + BOOST_CHECK((ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1, + ParID_t::ePHI>::projector() == loc0_loc1_phi_proj)); + BOOST_CHECK( + (ParameterSet<ParID_t::eLOC_0, ParID_t::ePHI, ParID_t::eTHETA, + ParID_t::eQOP>::projector() == loc0_phi_theta_qop_proj)); + BOOST_CHECK((ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1, ParID_t::ePHI, + ParID_t::eTHETA, ParID_t::eQOP>::projector() == + loc0_loc1_phi_theta_qop_proj)); +} + +/** + * @brief Unit test for residuals between different ParameterSet objects + * + * The result of the residual calculation between two ParameterSet objects is + * checked. + * A test of the automatic correction of stored parameter values for + * out-of-bounds/cyclic + * corrections is also implemented. + * + * @sa ParameterSet::residual, ParameterSet::getParameter + */ +BOOST_AUTO_TEST_CASE(parset_residual_tests) { + // check unbound parameter type + const double large_number = 12443534120; + const double small_number = -924342675; + const double normal_number = 1.234; + ParameterSet<ParID_t::eLOC_0, ParID_t::eLOC_1, ParID_t::eQOP> unbound( + nullptr, small_number, large_number, normal_number); + BOOST_CHECK(unbound.getParameter<ParID_t::eLOC_0>() == small_number); + BOOST_CHECK(unbound.getParameter<ParID_t::eLOC_1>() == large_number); + BOOST_CHECK(unbound.getParameter<ParID_t::eQOP>() == normal_number); + + // check bound parameter type + ParameterSet<ParID_t::eTHETA> bound(nullptr, small_number); + BOOST_CHECK((bound.getParameter<ParID_t::eTHETA>() == + par_type_t<ParID_t::eTHETA>::min)); + bound.setParameter<ParID_t::eTHETA>(large_number); + BOOST_CHECK((bound.getParameter<ParID_t::eTHETA>() == + par_type_t<ParID_t::eTHETA>::max)); + bound.setParameter<ParID_t::eTHETA>(normal_number); + BOOST_CHECK((bound.getParameter<ParID_t::eTHETA>() == normal_number)); + + // check cyclic parameter type + ParameterSet<ParID_t::ePHI> cyclic(nullptr, small_number); + // calculate expected results + const double min = par_type_t<ParID_t::ePHI>::min; + const double max = par_type_t<ParID_t::ePHI>::max; + // check that difference between original phi and stored phi is a multiple + // of the cyclic period + double multiple = + (cyclic.getParameter<ParID_t::ePHI>() - small_number) / (max - min); + BOOST_CHECK(cyclic.getParameter<ParID_t::ePHI>() >= min); + BOOST_CHECK(cyclic.getParameter<ParID_t::ePHI>() < max); + BOOST_CHECK(std::abs(multiple - std::floor(multiple + 0.5)) < tol); + + cyclic.setParameter<ParID_t::ePHI>(large_number); + multiple = + (cyclic.getParameter<ParID_t::ePHI>() - large_number) / (max - min); + BOOST_CHECK(cyclic.getParameter<ParID_t::ePHI>() >= min); + BOOST_CHECK(cyclic.getParameter<ParID_t::ePHI>() < max); + BOOST_CHECK(std::abs(multiple - std::floor(multiple + 0.5)) < tol); + + cyclic.setParameter<ParID_t::ePHI>(normal_number); + multiple = + (cyclic.getParameter<ParID_t::ePHI>() - normal_number) / (max - min); + BOOST_CHECK(cyclic.getParameter<ParID_t::ePHI>() >= min); + BOOST_CHECK(cyclic.getParameter<ParID_t::ePHI>() < max); + BOOST_CHECK(std::abs(multiple - std::floor(multiple + 0.5)) < tol); + + // check residual calculation + + // input numbers + const double first_loc0 = 0.3; + const double first_phi = 0.9 * M_PI; + const double first_theta = 0.7 * M_PI; + + const double second_loc0 = 2.7; + const double second_phi = -0.9 * M_PI; + const double second_theta = 0.35 * M_PI; + + // expected results for residual second wrt first + const double delta_loc0 = second_loc0 - first_loc0; + const double delta_phi = + get_cyclic_difference(second_phi, first_phi, min, max); + const double delta_theta = second_theta - first_theta; + ActsVectorD<3> residuals(delta_loc0, delta_phi, delta_theta); + + ParameterSet<ParID_t::eLOC_0, ParID_t::ePHI, ParID_t::eTHETA> first( + nullptr, first_loc0, first_phi, first_theta); + ParameterSet<ParID_t::eLOC_0, ParID_t::ePHI, ParID_t::eTHETA> second( + nullptr, second_loc0, second_phi, second_theta); + CHECK_CLOSE_REL(residuals, second.residual(first), 1e-6); + + // some more checks for bound variables + check_residuals_for_bound_parameters(); + + // some more checks for cyclic variables + check_residuals_for_cyclic_parameters(); + + // inspecific residual tests with random numbers + random_residual_tests(); +} + +template <ParID_t... params> +using ParSet = ParameterSet<params...>; + +/** + * @brief Unit test for index-/type-based access of coordinates + * + * @sa ParameterSet::getIndex + * @sa ParameterSet::getParID + */ +BOOST_AUTO_TEST_CASE(parset_parID_mapping) { + // check logic for type-based access + BOOST_CHECK((ParSet<eLOC_0, eLOC_1, ePHI, eQOP>::getIndex<eLOC_0>() == 0)); + BOOST_CHECK((ParSet<eLOC_0, eLOC_1, ePHI, eQOP>::getIndex<eLOC_1>() == 1)); + BOOST_CHECK((ParSet<eLOC_0, eLOC_1, ePHI, eQOP>::getIndex<ePHI>() == 2)); + BOOST_CHECK((ParSet<eLOC_0, eLOC_1, ePHI, eQOP>::getIndex<eQOP>() == 3)); + + // check logic for index-based access + BOOST_CHECK((ParSet<eLOC_0, eLOC_1, ePHI, eQOP>::getParID<0>() == eLOC_0)); + BOOST_CHECK((ParSet<eLOC_0, eLOC_1, ePHI, eQOP>::getParID<1>() == eLOC_1)); + BOOST_CHECK((ParSet<eLOC_0, eLOC_1, ePHI, eQOP>::getParID<2>() == ePHI)); + BOOST_CHECK((ParSet<eLOC_0, eLOC_1, ePHI, eQOP>::getParID<3>() == eQOP)); + + // check consistency + using FullSet = FullParameterSet; + BOOST_CHECK((FullSet::getIndex<FullSet::getParID<0>()>() == 0)); + BOOST_CHECK((FullSet::getIndex<FullSet::getParID<1>()>() == 1)); + BOOST_CHECK((FullSet::getIndex<FullSet::getParID<2>()>() == 2)); + BOOST_CHECK((FullSet::getIndex<FullSet::getParID<3>()>() == 3)); + BOOST_CHECK((FullSet::getIndex<FullSet::getParID<4>()>() == 4)); + + BOOST_CHECK((FullSet::getParID<FullSet::getIndex<eLOC_0>()>() == eLOC_0)); + BOOST_CHECK((FullSet::getParID<FullSet::getIndex<eLOC_1>()>() == eLOC_1)); + BOOST_CHECK((FullSet::getParID<FullSet::getIndex<ePHI>()>() == ePHI)); + BOOST_CHECK((FullSet::getParID<FullSet::getIndex<eTHETA>()>() == eTHETA)); + BOOST_CHECK((FullSet::getParID<FullSet::getIndex<eQOP>()>() == eQOP)); + + // consistency of types + BOOST_CHECK( + (std::is_same< + std::remove_cv<decltype(at_index<ParID_t, 0, eLOC_0>::value)>::type, + decltype(eLOC_0)>::value)); + BOOST_CHECK(( + std::is_same<decltype(FullSet::getParID<0>()), decltype(eLOC_0)>::value)); +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/EventData/ParametersTestHelper.hpp b/Tests/Core/EventData/ParametersTestHelper.hpp index fd365887af3fc027bdd5406123c21e13a995b828..e165e128ebe3faf4219e5c81f136d990462b99a6 100644 --- a/Tests/Core/EventData/ParametersTestHelper.hpp +++ b/Tests/Core/EventData/ParametersTestHelper.hpp @@ -17,24 +17,20 @@ namespace Acts { namespace Test { - template <typename Parameter> - void - consistencyCheck(const Parameter& pars, - const Vector3D& position, - const Vector3D& momentum, - double charge, - std::array<double, 5> values) - { - // check parameter vector - CHECK_CLOSE_ABS(pars.parameters()[eLOC_0], values[0], s_onSurfaceTolerance); - CHECK_CLOSE_ABS(pars.parameters()[eLOC_1], values[1], s_onSurfaceTolerance); - CHECK_CLOSE_REL(pars.parameters()[ePHI], values[2], 1e-6); - CHECK_CLOSE_REL(pars.parameters()[eTHETA], values[3], 1e-6); - CHECK_CLOSE_REL(pars.parameters()[eQOP], values[4], 1e-6); - // check global parameters - CHECK_CLOSE_REL(pars.position(), position, 1e-6); - CHECK_CLOSE_REL(pars.momentum(), momentum, 1e-6); - BOOST_CHECK_EQUAL(pars.charge(), charge); - } -} +template <typename Parameter> +void consistencyCheck(const Parameter& pars, const Vector3D& position, + const Vector3D& momentum, double charge, + std::array<double, 5> values) { + // check parameter vector + CHECK_CLOSE_ABS(pars.parameters()[eLOC_0], values[0], s_onSurfaceTolerance); + CHECK_CLOSE_ABS(pars.parameters()[eLOC_1], values[1], s_onSurfaceTolerance); + CHECK_CLOSE_REL(pars.parameters()[ePHI], values[2], 1e-6); + CHECK_CLOSE_REL(pars.parameters()[eTHETA], values[3], 1e-6); + CHECK_CLOSE_REL(pars.parameters()[eQOP], values[4], 1e-6); + // check global parameters + CHECK_CLOSE_REL(pars.position(), position, 1e-6); + CHECK_CLOSE_REL(pars.momentum(), momentum, 1e-6); + BOOST_CHECK_EQUAL(pars.charge(), charge); } +} // namespace Test +} // namespace Acts diff --git a/Tests/Core/EventData/TrackStateTests.cpp b/Tests/Core/EventData/TrackStateTests.cpp index 4abc2fce1dbf5d12ee1b428483afa5bc0122255d..de69f13a7b29751bf936ba692994fce3891765ab 100644 --- a/Tests/Core/EventData/TrackStateTests.cpp +++ b/Tests/Core/EventData/TrackStateTests.cpp @@ -23,166 +23,164 @@ namespace Acts { namespace Test { - // Create a test context - GeometryContext tgContext = GeometryContext(); +// Create a test context +GeometryContext tgContext = GeometryContext(); - using Jacobian = ActsMatrixD<5, 5>; - using Identifier = unsigned long int; +using Jacobian = ActsMatrixD<5, 5>; +using Identifier = unsigned long int; - template <ParID_t... params> - using MeasurementType = Measurement<Identifier, params...>; - using BoundTrackState = TrackState<Identifier, BoundParameters>; - /// - /// @brief Unit test for creation of Measurement object - /// - BOOST_AUTO_TEST_CASE(track_state_initialization) - { +template <ParID_t... params> +using MeasurementType = Measurement<Identifier, params...>; +using BoundTrackState = TrackState<Identifier, BoundParameters>; +/// +/// @brief Unit test for creation of Measurement object +/// +BOOST_AUTO_TEST_CASE(track_state_initialization) { + std::default_random_engine generator(42); - std::default_random_engine generator(42); + // The plane surface + auto plane = Surface::makeShared<PlaneSurface>(Vector3D{0., 0., 0.}, + Vector3D{1., 0., 0.}); - // The plane surface - auto plane = Surface::makeShared<PlaneSurface>(Vector3D{0., 0., 0.}, - Vector3D{1., 0., 0.}); + // Construct the 1D measurement + ActsSymMatrixD<1> cov1D; + cov1D << 0.04; - // Construct the 1D measurement - ActsSymMatrixD<1> cov1D; - cov1D << 0.04; + MeasurementType<ParDef::eLOC_0> m1D(plane, 0, std::move(cov1D), 0.02); - MeasurementType<ParDef::eLOC_0> m1D(plane, 0, std::move(cov1D), 0.02); + // Construct the 2D measurement + ActsSymMatrixD<2> cov2D; + cov2D << 0.04, 0., 0.09, 0.; - // Construct the 2D measurement - ActsSymMatrixD<2> cov2D; - cov2D << 0.04, 0., 0.09, 0.; + MeasurementType<ParDef::eLOC_0, ParDef::eLOC_1> m2D( + plane, 0, std::move(cov2D), 0.02, 0.03); - MeasurementType<ParDef::eLOC_0, ParDef::eLOC_1> m2D( - plane, 0, std::move(cov2D), 0.02, 0.03); + // The 1D track state from the measurement + BoundTrackState mts1D(std::move(m1D)); - // The 1D track state from the measurement - BoundTrackState mts1D(std::move(m1D)); + BOOST_CHECK_EQUAL(*mts1D.size(), 1); - BOOST_CHECK_EQUAL(*mts1D.size(), 1); + // Test the copy construtor + BoundTrackState mts1DCopy(mts1D); - // Test the copy construtor - BoundTrackState mts1DCopy(mts1D); + // Test the copy move constructor + BoundTrackState mts1DCopyMoved(std::move(mts1DCopy)); - // Test the copy move constructor - BoundTrackState mts1DCopyMoved(std::move(mts1DCopy)); + // Test the copy assignment operator + BoundTrackState mts1DCopyAssigned = mts1DCopyMoved; - // Test the copy assignment operator - BoundTrackState mts1DCopyAssigned = mts1DCopyMoved; + // Test the comovepy assignment operator + BoundTrackState mts1DMoveAssigned = std::move(mts1DCopyAssigned); - // Test the comovepy assignment operator - BoundTrackState mts1DMoveAssigned = std::move(mts1DCopyAssigned); + // Swap the measurements + std::swap(mts1DMoveAssigned, mts1D); - // Swap the measurements - std::swap(mts1DMoveAssigned, mts1D); + // The 2D track state from the measurement + BoundTrackState mts2D(std::move(m2D)); - // The 2D track state from the measurement - BoundTrackState mts2D(std::move(m2D)); + BOOST_CHECK_EQUAL(*mts2D.size(), 2); - BOOST_CHECK_EQUAL(*mts2D.size(), 2); + // Construct the parameter + std::array<double, 5> pars_array = {{-0.1234, 9.8765, 0.45, 0.888, 0.001}}; + TrackParametersBase::ParVector_t pars; + pars << pars_array[0], pars_array[1], pars_array[2], pars_array[3], + pars_array[4]; - // Construct the parameter - std::array<double, 5> pars_array = {{-0.1234, 9.8765, 0.45, 0.888, 0.001}}; - TrackParametersBase::ParVector_t pars; - pars << pars_array[0], pars_array[1], pars_array[2], pars_array[3], - pars_array[4]; + // constructor from parameter vector: predicted filtered, smoothed + BoundParameters ataPlane(tgContext, nullptr, pars, plane); - // constructor from parameter vector: predicted filtered, smoothed - BoundParameters ataPlane(tgContext, nullptr, pars, plane); + // The parameter track state from the parameters + BoundTrackState pts(std::move(ataPlane)); - // The parameter track state from the parameters - BoundTrackState pts(std::move(ataPlane)); + // Test the copy constructor for a parameter state + BoundTrackState ptsCopy(pts); - // Test the copy constructor for a parameter state - BoundTrackState ptsCopy(pts); + // Test the copy move constructor for a parameter state + BoundTrackState ptsCopyMove(std::move(ptsCopy)); - // Test the copy move constructor for a parameter state - BoundTrackState ptsCopyMove(std::move(ptsCopy)); + // Test the copy assignment for a parameter state + BoundTrackState ptsCopyAssigned = ptsCopyMove; - // Test the copy assignment for a parameter state - BoundTrackState ptsCopyAssigned = ptsCopyMove; + // Test the move assignment for a parameter state + BoundTrackState ptsMoveAssigned = std::move(ptsCopyAssigned); - // Test the move assignment for a parameter state - BoundTrackState ptsMoveAssigned = std::move(ptsCopyAssigned); + std::vector<BoundTrackState> trackStates = {std::move(mts1DMoveAssigned), + std::move(mts2D), std::move(pts)}; - std::vector<BoundTrackState> trackStates - = {std::move(mts1DMoveAssigned), std::move(mts2D), std::move(pts)}; + BOOST_CHECK_EQUAL(trackStates.size(), 3); - BOOST_CHECK_EQUAL(trackStates.size(), 3); - - // Test is we can shuffle the track states - // Test to extract the surface of these guys - for (auto& ts : trackStates) { - const Surface* sf = &ts.referenceSurface(); - BOOST_CHECK_EQUAL(sf, plane.get()); - } + // Test is we can shuffle the track states + // Test to extract the surface of these guys + for (auto& ts : trackStates) { + const Surface* sf = &ts.referenceSurface(); + BOOST_CHECK_EQUAL(sf, plane.get()); + } - // Create predicted, filtered and smoothed parameters - BoundParameters ataPlaneUpdt(tgContext, nullptr, pars, plane); - BoundParameters ataPlanePred(tgContext, nullptr, pars, plane); - BoundParameters ataPlaneSmth(tgContext, nullptr, pars, plane); + // Create predicted, filtered and smoothed parameters + BoundParameters ataPlaneUpdt(tgContext, nullptr, pars, plane); + BoundParameters ataPlanePred(tgContext, nullptr, pars, plane); + BoundParameters ataPlaneSmth(tgContext, nullptr, pars, plane); - // Get the predicted parameters back from the trackState - auto& ptsfList = trackStates[2]; - auto& ataPlanefListPred = ptsfList.parameter.predicted; - BOOST_CHECK(ataPlanefListPred); + // Get the predicted parameters back from the trackState + auto& ptsfList = trackStates[2]; + auto& ataPlanefListPred = ptsfList.parameter.predicted; + BOOST_CHECK(ataPlanefListPred); - // Check that the other parameters are empty - auto& ataPlanefListUpdt = ptsfList.parameter.filtered; - BOOST_CHECK(!ataPlanefListUpdt); + // Check that the other parameters are empty + auto& ataPlanefListUpdt = ptsfList.parameter.filtered; + BOOST_CHECK(!ataPlanefListUpdt); - auto& ataPlanefListSmthd = ptsfList.parameter.smoothed; - BOOST_CHECK(!ataPlanefListSmthd); + auto& ataPlanefListSmthd = ptsfList.parameter.smoothed; + BOOST_CHECK(!ataPlanefListSmthd); - // Get the track States from the list - auto& m2DfList = trackStates[1]; + // Get the track States from the list + auto& m2DfList = trackStates[1]; - m2DfList.parameter.filtered = std::move(ataPlaneUpdt); - auto& ataPlanefListUpdtM2D = m2DfList.parameter.filtered; - BOOST_CHECK(ataPlanefListUpdtM2D); + m2DfList.parameter.filtered = std::move(ataPlaneUpdt); + auto& ataPlanefListUpdtM2D = m2DfList.parameter.filtered; + BOOST_CHECK(ataPlanefListUpdtM2D); - m2DfList.parameter.predicted = std::move(ataPlanePred); - auto& ataPlanefListPred2D = m2DfList.parameter.predicted; - BOOST_CHECK(ataPlanefListPred2D); + m2DfList.parameter.predicted = std::move(ataPlanePred); + auto& ataPlanefListPred2D = m2DfList.parameter.predicted; + BOOST_CHECK(ataPlanefListPred2D); - // Test the sorting helper - BoundParameters ataPlaneAt1(tgContext, nullptr, pars, plane); - BoundTrackState ataPlaneState1(std::move(ataPlaneAt1)); - ataPlaneState1.parameter.pathLength = 1.; + // Test the sorting helper + BoundParameters ataPlaneAt1(tgContext, nullptr, pars, plane); + BoundTrackState ataPlaneState1(std::move(ataPlaneAt1)); + ataPlaneState1.parameter.pathLength = 1.; - BoundParameters ataPlaneAt2(tgContext, nullptr, pars, plane); - BoundTrackState ataPlaneState2(std::move(ataPlaneAt2)); - ataPlaneState2.parameter.pathLength = 2.; + BoundParameters ataPlaneAt2(tgContext, nullptr, pars, plane); + BoundTrackState ataPlaneState2(std::move(ataPlaneAt2)); + ataPlaneState2.parameter.pathLength = 2.; - std::vector<BoundTrackState> unorderedStates - = {std::move(ataPlaneState2), std::move(ataPlaneState1)}; + std::vector<BoundTrackState> unorderedStates = {std::move(ataPlaneState2), + std::move(ataPlaneState1)}; - // Sort the variant track state - TrackStatePathLengthSorter plSorter; - std::sort(unorderedStates.begin(), unorderedStates.end(), plSorter); + // Sort the variant track state + TrackStatePathLengthSorter plSorter; + std::sort(unorderedStates.begin(), unorderedStates.end(), plSorter); - auto firstOrdered = unorderedStates[0]; - BOOST_CHECK_EQUAL(firstOrdered.parameter.pathLength, 1.); + auto firstOrdered = unorderedStates[0]; + BOOST_CHECK_EQUAL(firstOrdered.parameter.pathLength, 1.); - auto secondOrdered = unorderedStates[1]; - BOOST_CHECK_EQUAL(secondOrdered.parameter.pathLength, 2.); + auto secondOrdered = unorderedStates[1]; + BOOST_CHECK_EQUAL(secondOrdered.parameter.pathLength, 2.); - auto& pState = firstOrdered.parameter; + auto& pState = firstOrdered.parameter; - BOOST_CHECK_EQUAL(pState.pathLength, 1.); + BOOST_CHECK_EQUAL(pState.pathLength, 1.); - std::shuffle(unorderedStates.begin(), unorderedStates.end(), generator); + std::shuffle(unorderedStates.begin(), unorderedStates.end(), generator); - // Copy the TrackStates into a new vector - std::vector<BoundTrackState> copiedStates - = {unorderedStates[0], unorderedStates[1]}; + // Copy the TrackStates into a new vector + std::vector<BoundTrackState> copiedStates = {unorderedStates[0], + unorderedStates[1]}; - // Shuffle - std::shuffle(copiedStates.begin(), copiedStates.end(), generator); - // And sort again - std::sort(copiedStates.begin(), copiedStates.end(), plSorter); - } + // Shuffle + std::shuffle(copiedStates.begin(), copiedStates.end(), generator); + // And sort again + std::sort(copiedStates.begin(), copiedStates.end(), plSorter); +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/Fitter/GainMatrixTests.cpp b/Tests/Core/Fitter/GainMatrixTests.cpp index 2d546ce614a5b503c7d65492b8b0f8a37bcee148..3ea1a0d0732495c506656490b7f4eb0aee6242ab 100644 --- a/Tests/Core/Fitter/GainMatrixTests.cpp +++ b/Tests/Core/Fitter/GainMatrixTests.cpp @@ -24,62 +24,60 @@ namespace Acts { namespace Test { - using Identifier = unsigned long int; - using Jacobian = BoundParameters::CovMatrix_t; +using Identifier = unsigned long int; +using Jacobian = BoundParameters::CovMatrix_t; - template <ParID_t... params> - using MeasurementType = Measurement<Identifier, params...>; - using TrackState = TrackState<Identifier, BoundParameters>; +template <ParID_t... params> +using MeasurementType = Measurement<Identifier, params...>; +using TrackState = TrackState<Identifier, BoundParameters>; - // Create a test context - GeometryContext tgContext = GeometryContext(); +// Create a test context +GeometryContext tgContext = GeometryContext(); - BOOST_AUTO_TEST_CASE(gain_matrix_updator) - { - // Make dummy measurement - auto cylinder = Surface::makeShared<CylinderSurface>(nullptr, 3, 10); +BOOST_AUTO_TEST_CASE(gain_matrix_updator) { + // Make dummy measurement + auto cylinder = Surface::makeShared<CylinderSurface>(nullptr, 3, 10); - ActsSymMatrixD<2> cov; - cov << 0.04, 0, 0, 0.1; - TrackState mState(MeasurementType<ParDef::eLOC_0, ParDef::eLOC_1>( - cylinder, 0, std::move(cov), -0.1, 0.45)); + ActsSymMatrixD<2> cov; + cov << 0.04, 0, 0, 0.1; + TrackState mState(MeasurementType<ParDef::eLOC_0, ParDef::eLOC_1>( + cylinder, 0, std::move(cov), -0.1, 0.45)); - // Make dummy track parameter - ActsSymMatrixD<Acts::NGlobalPars> covTrk; - covTrk << 0.08, 0, 0, 0, 0, 0, 0.3, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, - 0, 0, 0, 0, 1; - ActsVectorD<Acts::NGlobalPars> parValues; - parValues << 0.3, 0.5, 0.5 * M_PI, 0.3 * M_PI, 0.01; - BoundParameters pars( - tgContext, - std::make_unique<const BoundParameters::CovMatrix_t>(std::move(covTrk)), - parValues, - cylinder); + // Make dummy track parameter + ActsSymMatrixD<Acts::NGlobalPars> covTrk; + covTrk << 0.08, 0, 0, 0, 0, 0, 0.3, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, + 0, 0, 0, 1; + ActsVectorD<Acts::NGlobalPars> parValues; + parValues << 0.3, 0.5, 0.5 * M_PI, 0.3 * M_PI, 0.01; + BoundParameters pars( + tgContext, + std::make_unique<const BoundParameters::CovMatrix_t>(std::move(covTrk)), + parValues, cylinder); - // "update" track state with "prediction" - mState.parameter.predicted = std::move(pars); - mState.parameter.jacobian = Jacobian::Identity(); - mState.parameter.pathLength = 0.; + // "update" track state with "prediction" + mState.parameter.predicted = std::move(pars); + mState.parameter.jacobian = Jacobian::Identity(); + mState.parameter.pathLength = 0.; - // Gain matrix update and filtered state - GainMatrixUpdator<BoundParameters> gmu; + // Gain matrix update and filtered state + GainMatrixUpdator<BoundParameters> gmu; - BOOST_CHECK(!mState.parameter.filtered); - BOOST_CHECK(!mState.measurement.calibrated); - BOOST_CHECK(gmu(tgContext, mState)); - // filtered is set now - BOOST_CHECK(!!mState.parameter.filtered); - // measurement was calibrated - BOOST_CHECK(!!mState.measurement.calibrated); - // ref surface is same on measurements and parameters - BOOST_CHECK_EQUAL( - MeasurementHelpers::getSurface(*mState.measurement.calibrated), - cylinder.get()); - BOOST_CHECK_EQUAL(&(*mState.parameter.filtered).referenceSurface(), - cylinder.get()); + BOOST_CHECK(!mState.parameter.filtered); + BOOST_CHECK(!mState.measurement.calibrated); + BOOST_CHECK(gmu(tgContext, mState)); + // filtered is set now + BOOST_CHECK(!!mState.parameter.filtered); + // measurement was calibrated + BOOST_CHECK(!!mState.measurement.calibrated); + // ref surface is same on measurements and parameters + BOOST_CHECK_EQUAL( + MeasurementHelpers::getSurface(*mState.measurement.calibrated), + cylinder.get()); + BOOST_CHECK_EQUAL(&(*mState.parameter.filtered).referenceSurface(), + cylinder.get()); - // assert contents of mState were updated - } + // assert contents of mState were updated +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/Fitter/KalmanFilterTestUtils.hpp b/Tests/Core/Fitter/KalmanFilterTestUtils.hpp index 80b8c23f129510cf316162accaf8de3c51ed7ea6..30ad771a79cf80de287eae23792d559f7abe64ad 100644 --- a/Tests/Core/Fitter/KalmanFilterTestUtils.hpp +++ b/Tests/Core/Fitter/KalmanFilterTestUtils.hpp @@ -37,78 +37,69 @@ template <ParID_t... pars> using Meas_t = Measurement<long int, pars...>; /// fit cache -struct MyCache -{ +struct MyCache { std::unique_ptr<const KF::Step<long int>::JacobianMatrix> jacobian; - std::unique_ptr<const BoundParameters> parameters; + std::unique_ptr<const BoundParameters> parameters; - MyCache() = default; + MyCache() = default; MyCache(const MyCache&) = delete; - MyCache(MyCache&&) = default; + MyCache(MyCache&&) = default; }; /// extrapolation wrapper -class MyExtrapolator -{ -public: - MyExtrapolator(std::shared_ptr<const IExtrapolationEngine> exEngine - = nullptr); +class MyExtrapolator { + public: + MyExtrapolator( + std::shared_ptr<const IExtrapolationEngine> exEngine = nullptr); - MyCache - operator()(const FitMeas_t& m, const TrackParameters& tp) const; + MyCache operator()(const FitMeas_t& m, const TrackParameters& tp) const; -private: + private: std::shared_ptr<const IExtrapolationEngine> m_exEngine; }; /// dummy class, returns measurement unchanged -class NoCalibration -{ -public: - std::unique_ptr<const FitMeas_t> - operator()(const FitMeas_t& m, const BoundParameters&) const; +class NoCalibration { + public: + std::unique_ptr<const FitMeas_t> operator()(const FitMeas_t& m, + const BoundParameters&) const; }; -class CacheGenerator -{ -public: - std::unique_ptr<KF::Step<long int>> - operator()(MyCache m) const; +class CacheGenerator { + public: + std::unique_ptr<KF::Step<long int>> operator()(MyCache m) const; }; MyExtrapolator::MyExtrapolator( std::shared_ptr<const IExtrapolationEngine> exEngine) - : m_exEngine(std::move(exEngine)){}; + : m_exEngine(std::move(exEngine)){}; /// wrapper around extrapolate call to exEngine, setting the right flags -MyCache -MyExtrapolator::operator()(const FitMeas_t& m, const TrackParameters& tp) const -{ +MyCache MyExtrapolator::operator()(const FitMeas_t& m, + const TrackParameters& tp) const { auto exCell = std::make_unique<ExtrapolationCell<TrackParameters>>(tp); exCell->addConfigurationMode(ExtrapolationMode::CollectJacobians); (*exCell).pathLimit = 500; - const Surface& sf = getSurface(m); + const Surface& sf = getSurface(m); m_exEngine->extrapolate(*exCell, &sf); MyCache c; - auto j = exCell->extrapolationSteps.back().transportJacobian.release(); + auto j = exCell->extrapolationSteps.back().transportJacobian.release(); c.jacobian.reset(new KF::Step<long int>::JacobianMatrix(*j)); - auto pars - = static_cast<const BoundParameters*>(exCell->leadParameters->clone()); + auto pars = + static_cast<const BoundParameters*>(exCell->leadParameters->clone()); c.parameters.reset(pars); return c; }; -std::unique_ptr<const FitMeas_t> -NoCalibration::operator()(const FitMeas_t& m, const BoundParameters&) const -{ +std::unique_ptr<const FitMeas_t> NoCalibration::operator()( + const FitMeas_t& m, const BoundParameters&) const { return std::make_unique<const FitMeas_t>(m); }; -std::unique_ptr<KF::Step<long int>> -CacheGenerator::operator()(MyCache m) const -{ +std::unique_ptr<KF::Step<long int>> CacheGenerator::operator()( + MyCache m) const { auto step = std::make_unique<KF::Step<long int>>(); step->setPredictedState(std::move(m.parameters)); step->setJacobian(std::move(m.jacobian)); @@ -117,33 +108,32 @@ CacheGenerator::operator()(MyCache m) const }; /// set up extrapolation -std::shared_ptr<IExtrapolationEngine> -initExtrapolator(const std::shared_ptr<const TrackingGeometry>& geo) -{ +std::shared_ptr<IExtrapolationEngine> initExtrapolator( + const std::shared_ptr<const TrackingGeometry>& geo) { auto propConfig = RungeKuttaEngine<>::Config(); - propConfig.fieldService - = std::make_shared<ConstantBField>(0, 0, 2 * Acts::units::_T); + propConfig.fieldService = + std::make_shared<ConstantBField>(0, 0, 2 * Acts::units::_T); auto propEngine = std::make_shared<RungeKuttaEngine<>>(propConfig); - auto matConfig = MaterialEffectsEngine::Config(); + auto matConfig = MaterialEffectsEngine::Config(); auto materialEngine = std::make_shared<MaterialEffectsEngine>(matConfig); - auto navConfig = StaticNavigationEngine::Config(); - navConfig.propagationEngine = propEngine; + auto navConfig = StaticNavigationEngine::Config(); + navConfig.propagationEngine = propEngine; navConfig.materialEffectsEngine = materialEngine; - navConfig.trackingGeometry = geo; + navConfig.trackingGeometry = geo; auto navEngine = std::make_shared<StaticNavigationEngine>(navConfig); - auto statConfig = StaticEngine::Config(); - statConfig.propagationEngine = propEngine; - statConfig.navigationEngine = navEngine; + auto statConfig = StaticEngine::Config(); + statConfig.propagationEngine = propEngine; + statConfig.navigationEngine = navEngine; statConfig.materialEffectsEngine = materialEngine; - auto statEngine = std::make_shared<StaticEngine>(statConfig); + auto statEngine = std::make_shared<StaticEngine>(statConfig); - auto exEngineConfig = ExtrapolationEngine::Config(); - exEngineConfig.trackingGeometry = geo; - exEngineConfig.propagationEngine = propEngine; - exEngineConfig.navigationEngine = navEngine; + auto exEngineConfig = ExtrapolationEngine::Config(); + exEngineConfig.trackingGeometry = geo; + exEngineConfig.propagationEngine = propEngine; + exEngineConfig.navigationEngine = navEngine; exEngineConfig.extrapolationEngines = {statEngine}; auto exEngine = std::make_shared<ExtrapolationEngine>(exEngineConfig); exEngine->setLogger(getDefaultLogger("ExtrapolationEngine", Logging::INFO)); diff --git a/Tests/Core/Fitter/KalmanFitterTests.cpp b/Tests/Core/Fitter/KalmanFitterTests.cpp index 20bc098eef45bbd752f7f3d49de118ede2aa726c..70e73bf77e1ac5f98a545e3402149c2a4882e0a0 100644 --- a/Tests/Core/Fitter/KalmanFitterTests.cpp +++ b/Tests/Core/Fitter/KalmanFitterTests.cpp @@ -45,328 +45,306 @@ namespace Acts { namespace Test { - // A few initialisations and definitionas - using Identifier = GeometryID; - using Jacobian = BoundParameters::CovMatrix_t; +// A few initialisations and definitionas +using Identifier = GeometryID; +using Jacobian = BoundParameters::CovMatrix_t; - using TrackState = TrackState<Identifier, BoundParameters>; - using Resolution = std::pair<ParID_t, double>; - using ElementResolution = std::vector<Resolution>; - using VolumeResolution = std::map<geo_id_value, ElementResolution>; - using DetectorResolution = std::map<geo_id_value, VolumeResolution>; +using TrackState = TrackState<Identifier, BoundParameters>; +using Resolution = std::pair<ParID_t, double>; +using ElementResolution = std::vector<Resolution>; +using VolumeResolution = std::map<geo_id_value, ElementResolution>; +using DetectorResolution = std::map<geo_id_value, VolumeResolution>; - using DebugOutput = detail::DebugOutputActor; +using DebugOutput = detail::DebugOutputActor; - std::normal_distribution<double> gauss(0., 1.); - std::default_random_engine generator(42); +std::normal_distribution<double> gauss(0., 1.); +std::default_random_engine generator(42); - ActsSymMatrixD<1> cov1D; - ActsSymMatrixD<2> cov2D; +ActsSymMatrixD<1> cov1D; +ActsSymMatrixD<2> cov2D; - bool debugMode = false; +bool debugMode = false; - // Create a test context - GeometryContext tgContext = GeometryContext(); - MagneticFieldContext mfContext = MagneticFieldContext(); - CalibrationContext calContext = CalibrationContext(); +// Create a test context +GeometryContext tgContext = GeometryContext(); +MagneticFieldContext mfContext = MagneticFieldContext(); +CalibrationContext calContext = CalibrationContext(); - /// @brief This struct creates FittableMeasurements on the - /// detector surfaces, according to the given smearing xxparameters +/// @brief This struct creates FittableMeasurements on the +/// detector surfaces, according to the given smearing xxparameters +/// +struct MeasurementCreator { + /// @brief Constructor + MeasurementCreator() = default; + + /// The detector resolution + DetectorResolution detectorResolution; + + using result_type = std::vector<TrackState>; + + /// @brief Operater that is callable by an ActionList. The function collects + /// the surfaces /// - struct MeasurementCreator - { - /// @brief Constructor - MeasurementCreator() = default; - - /// The detector resolution - DetectorResolution detectorResolution; - - using result_type = std::vector<TrackState>; - - /// @brief Operater that is callable by an ActionList. The function collects - /// the surfaces - /// - /// @tparam propagator_state_t Type of the propagator state - /// @tparam stepper_t Type of the stepper - /// @param [in] state State of the propagator - /// @param [out] result Vector of matching surfaces - template <typename propagator_state_t, typename stepper_t> - void - operator()(propagator_state_t& state, - const stepper_t& stepper, - result_type& result) const - { - // monitor the current surface - auto surface = state.navigation.currentSurface; - if (surface and surface->associatedDetectorElement()) { - auto geoID = surface->geoID(); - geo_id_value volumeID = geoID.value(GeometryID::volume_mask); - geo_id_value layerID = geoID.value(GeometryID::layer_mask); - // find volume and layer information for this - auto vResolution = detectorResolution.find(volumeID); - if (vResolution != detectorResolution.end()) { - // find layer resolutions - auto lResolution = vResolution->second.find(layerID); - if (lResolution != vResolution->second.end()) { - // Apply global to local - Acts::Vector2D lPos; - surface->globalToLocal(state.geoContext, - stepper.position(state.stepping), - stepper.direction(state.stepping), - lPos); - if (lResolution->second.size() == 1) { - double sp = lResolution->second[0].second; - cov1D << sp * sp; - double dp = sp * gauss(generator); - if (lResolution->second[0].first == eLOC_0) { - // push back & move a LOC_0 measurement - Measurement<Identifier, eLOC_0> m0( - surface->getSharedPtr(), geoID, cov1D, lPos[eLOC_0] + dp); - result.push_back(TrackState(std::move(m0))); - } else { - // push back & move a LOC_1 measurement - Measurement<Identifier, eLOC_1> m1( - surface->getSharedPtr(), geoID, cov1D, lPos[eLOC_1] + dp); - result.push_back(TrackState(std::move(m1))); - } - } else if (lResolution->second.size() == 2) { - // Create the measurment and move it - double sx = lResolution->second[eLOC_0].second; - double sy = lResolution->second[eLOC_1].second; - cov2D << sx * sx, 0., 0., sy * sy; - double dx = sx * gauss(generator); - double dy = sy * gauss(generator); - // push back & move a LOC_0, LOC_1 measurement - Measurement<Identifier, eLOC_0, eLOC_1> m01( - surface->getSharedPtr(), - geoID, - cov2D, - lPos[eLOC_0] + dx, - lPos[eLOC_1] + dy); - result.push_back(TrackState(std::move(m01))); + /// @tparam propagator_state_t Type of the propagator state + /// @tparam stepper_t Type of the stepper + /// @param [in] state State of the propagator + /// @param [out] result Vector of matching surfaces + template <typename propagator_state_t, typename stepper_t> + void operator()(propagator_state_t& state, const stepper_t& stepper, + result_type& result) const { + // monitor the current surface + auto surface = state.navigation.currentSurface; + if (surface and surface->associatedDetectorElement()) { + auto geoID = surface->geoID(); + geo_id_value volumeID = geoID.value(GeometryID::volume_mask); + geo_id_value layerID = geoID.value(GeometryID::layer_mask); + // find volume and layer information for this + auto vResolution = detectorResolution.find(volumeID); + if (vResolution != detectorResolution.end()) { + // find layer resolutions + auto lResolution = vResolution->second.find(layerID); + if (lResolution != vResolution->second.end()) { + // Apply global to local + Acts::Vector2D lPos; + surface->globalToLocal(state.geoContext, + stepper.position(state.stepping), + stepper.direction(state.stepping), lPos); + if (lResolution->second.size() == 1) { + double sp = lResolution->second[0].second; + cov1D << sp * sp; + double dp = sp * gauss(generator); + if (lResolution->second[0].first == eLOC_0) { + // push back & move a LOC_0 measurement + Measurement<Identifier, eLOC_0> m0(surface->getSharedPtr(), geoID, + cov1D, lPos[eLOC_0] + dp); + result.push_back(TrackState(std::move(m0))); + } else { + // push back & move a LOC_1 measurement + Measurement<Identifier, eLOC_1> m1(surface->getSharedPtr(), geoID, + cov1D, lPos[eLOC_1] + dp); + result.push_back(TrackState(std::move(m1))); } + } else if (lResolution->second.size() == 2) { + // Create the measurment and move it + double sx = lResolution->second[eLOC_0].second; + double sy = lResolution->second[eLOC_1].second; + cov2D << sx * sx, 0., 0., sy * sy; + double dx = sx * gauss(generator); + double dy = sy * gauss(generator); + // push back & move a LOC_0, LOC_1 measurement + Measurement<Identifier, eLOC_0, eLOC_1> m01( + surface->getSharedPtr(), geoID, cov2D, lPos[eLOC_0] + dx, + lPos[eLOC_1] + dy); + result.push_back(TrackState(std::move(m01))); } } } } - }; + } +}; - double dX, dY; - Vector3D pos; - Surface const* sur; +double dX, dY; +Vector3D pos; +Surface const* sur; - /// - /// @brief Simplified material interaction effect by pure gaussian deflection - /// - struct MaterialScattering - { - /// @brief Constructor - MaterialScattering() = default; - - /// @brief Main action list call operator for the scattering on material - /// - /// @todo deal momentum in a gaussian way properly - /// - /// @tparam propagator_state_t State of the propagator - /// @param stepper_t Type of the stepper - /// @param [in] state State of the propagation - /// @param [in] stepper Stepper of the propagation - template <typename propagator_state_t, typename stepper_t> - void - operator()(propagator_state_t& state, const stepper_t& stepper) const - { - // Check if there is a surface with material and a covariance is existing - if (state.navigation.currentSurface - && state.navigation.currentSurface->surfaceMaterial() - && state.stepping.cov != ActsSymMatrixD<5>::Zero()) { - // Sample angles - std::normal_distribution<double> scatterAngle( - 0., 0.017); //< \approx 1 degree - double dPhi = scatterAngle(generator), dTheta = scatterAngle(generator); - - // Update the covariance - state.stepping.cov(ePHI, ePHI) += dPhi * dPhi; - state.stepping.cov(eTHETA, eTHETA) += dTheta * dTheta; - - // Update the angles - auto direction = stepper.direction(state.stepping); - double theta = std::acos(direction.z()); - double phi = std::atan2(direction.y(), direction.x()); - - state.stepping.update( - stepper.position(state.stepping), - {std::sin(theta + dTheta) * std::cos(phi + dPhi), - std::sin(theta + dTheta) * std::sin(phi + dPhi), - std::cos(theta + dTheta)}, - std::max(stepper.momentum(state.stepping) - - std::abs(gauss(generator)) * units::_MeV, - 0.)); - } - } - }; +/// +/// @brief Simplified material interaction effect by pure gaussian deflection +/// +struct MaterialScattering { + /// @brief Constructor + MaterialScattering() = default; + /// @brief Main action list call operator for the scattering on material /// - /// @brief Unit test for Kalman fitter with measurements along the x-axis + /// @todo deal momentum in a gaussian way properly /// - BOOST_AUTO_TEST_CASE(kalman_fitter_zero_field) - { - // Build detector - CubicTrackingGeometry cGeometry(tgContext); - auto detector = cGeometry(); - - // Build navigator for the measurement creatoin - Navigator mNavigator(detector); - mNavigator.resolvePassive = false; - mNavigator.resolveMaterial = true; - mNavigator.resolveSensitive = true; - - // Use straingt line stepper to create the measurements - StraightLineStepper mStepper; - - // Define the measurement propagator - using MeasurementPropagator = Propagator<StraightLineStepper, Navigator>; - - // Build propagator for the measurement creation - MeasurementPropagator mPropagator(mStepper, mNavigator); - Vector3D mPos(-3. * units::_m, 0., 0.), mMom(1. * units::_GeV, 0., 0); - SingleCurvilinearTrackParameters<NeutralPolicy> mStart(nullptr, mPos, mMom); - - // Create action list for the measurement creation - using MeasurementActions = ActionList<MeasurementCreator, DebugOutput>; - using MeasurementAborters = AbortList<detail::EndOfWorldReached>; - - auto pixelResX = Resolution(eLOC_0, 25. * units::_um); - auto pixelResY = Resolution(eLOC_1, 50. * units::_um); - auto stripResX = Resolution(eLOC_0, 100. * units::_um); - auto stripResY = Resolution(eLOC_1, 150. * units::_um); - - ElementResolution pixelElementRes = {pixelResX, pixelResY}; - ElementResolution stripElementResI = {stripResX}; - ElementResolution stripElementResO = {stripResY}; - - VolumeResolution pixelVolumeRes; - pixelVolumeRes[2] = pixelElementRes; - pixelVolumeRes[4] = pixelElementRes; - - VolumeResolution stripVolumeRes; - stripVolumeRes[2] = stripElementResI; - stripVolumeRes[4] = stripElementResO; - stripVolumeRes[6] = stripElementResI; - stripVolumeRes[8] = stripElementResO; - - DetectorResolution detRes; - detRes[2] = pixelVolumeRes; - detRes[3] = stripVolumeRes; - - // Set options for propagator - PropagatorOptions<MeasurementActions, MeasurementAborters> mOptions( - tgContext, mfContext); - mOptions.debug = debugMode; - auto& mCreator = mOptions.actionList.get<MeasurementCreator>(); - mCreator.detectorResolution = detRes; - - // Launch and collect - the measurements - auto mResult = mPropagator.propagate(mStart, mOptions).value(); - if (debugMode) { - const auto debugString - = mResult.template get<DebugOutput::result_type>().debugString; - std::cout << ">>>> Measurement creation: " << std::endl; - std::cout << debugString; + /// @tparam propagator_state_t State of the propagator + /// @param stepper_t Type of the stepper + /// @param [in] state State of the propagation + /// @param [in] stepper Stepper of the propagation + template <typename propagator_state_t, typename stepper_t> + void operator()(propagator_state_t& state, const stepper_t& stepper) const { + // Check if there is a surface with material and a covariance is existing + if (state.navigation.currentSurface && + state.navigation.currentSurface->surfaceMaterial() && + state.stepping.cov != ActsSymMatrixD<5>::Zero()) { + // Sample angles + std::normal_distribution<double> scatterAngle( + 0., 0.017); //< \approx 1 degree + double dPhi = scatterAngle(generator), dTheta = scatterAngle(generator); + + // Update the covariance + state.stepping.cov(ePHI, ePHI) += dPhi * dPhi; + state.stepping.cov(eTHETA, eTHETA) += dTheta * dTheta; + + // Update the angles + auto direction = stepper.direction(state.stepping); + double theta = std::acos(direction.z()); + double phi = std::atan2(direction.y(), direction.x()); + + state.stepping.update( + stepper.position(state.stepping), + {std::sin(theta + dTheta) * std::cos(phi + dPhi), + std::sin(theta + dTheta) * std::sin(phi + dPhi), + std::cos(theta + dTheta)}, + std::max(stepper.momentum(state.stepping) - + std::abs(gauss(generator)) * units::_MeV, + 0.)); } - - auto measurements = mResult.template get<MeasurementCreator::result_type>(); - BOOST_CHECK_EQUAL(measurements.size(), 6); - - // The KalmanFitter - we use the eigen stepper for covariance transport - // Build navigator for the measurement creatoin - Navigator rNavigator(detector); - rNavigator.resolvePassive = false; - rNavigator.resolveMaterial = true; - rNavigator.resolveSensitive = true; - - // Configure propagation with deactivated B-field - ConstantBField bField(Vector3D(0., 0., 0.)); - using RecoStepper = EigenStepper<ConstantBField>; - RecoStepper rStepper(bField); - using RecoPropagator = Propagator<RecoStepper, Navigator>; - RecoPropagator rPropagator(rStepper, rNavigator); - - // Set initial parameters for the particle track - ActsSymMatrixD<5> cov; - cov << 1000. * units::_um, 0., 0., 0., 0., 0., 1000. * units::_um, 0., 0., - 0., 0., 0., 0.05, 0., 0., 0., 0., 0., 0.05, 0., 0., 0., 0., 0., 0.01; - - auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); - - Vector3D rPos(-3. * units::_m, - 10. * units::_um * gauss(generator), - 100. * units::_um * gauss(generator)); - Vector3D rMom(1. * units::_GeV, - 0.025 * units::_GeV * gauss(generator), - 0.025 * units::_GeV * gauss(generator)); - - SingleCurvilinearTrackParameters<ChargedPolicy> rStart( - std::move(covPtr), rPos, rMom, 1.); - - const Surface* rSurface = &rStart.referenceSurface(); - - using Updator = GainMatrixUpdator<BoundParameters>; - using Smoother = GainMatrixSmoother<BoundParameters>; - using KalmanFitter = KalmanFitter<RecoPropagator, Updator, Smoother>; - - KalmanFitter kFitter(rPropagator); - - KalmanFitterOptions kfOptions(tgContext, mfContext, calContext, rSurface); - - // Fit the track - auto fittedTrack = kFitter.fit(measurements, rStart, kfOptions); - auto fittedParameters = fittedTrack.fittedParameters.get(); - - // Make sure it is deterministic - auto fittedAgainTrack = kFitter.fit(measurements, rStart, kfOptions); - auto fittedAgainParameters = fittedAgainTrack.fittedParameters.get(); - - CHECK_CLOSE_REL(fittedParameters.parameters(), - fittedAgainParameters.parameters(), - 1e-5); - - // Change the order of the measurements - std::vector<TrackState> shuffledMeasurements = {measurements[3], - measurements[2], - measurements[1], - measurements[4], - measurements[5], - measurements[0]}; - - // Make sure it works for shuffled measurements as well - auto fittedShuffledTrack - = kFitter.fit(shuffledMeasurements, rStart, kfOptions); - auto fittedShuffledParameters = fittedShuffledTrack.fittedParameters.get(); - - CHECK_CLOSE_REL(fittedParameters.parameters(), - fittedShuffledParameters.parameters(), - 1e-5); - - // Remove one measurement and find a hole - std::vector<TrackState> measurementsWithHole = {measurements[0], - measurements[1], - measurements[2], - measurements[4], - measurements[5]}; - - // Make sure it works for shuffled measurements as well - auto fittedWithHoleTrack - = kFitter.fit(measurementsWithHole, rStart, kfOptions); - auto fittedWithHoleParameters = fittedWithHoleTrack.fittedParameters.get(); - - // Count one hole - BOOST_CHECK_EQUAL(fittedWithHoleTrack.missedActiveSurfaces.size(), 1); - // And the parameters should be different - BOOST_CHECK( - !Acts::Test::checkCloseRel(fittedParameters.parameters(), - fittedWithHoleParameters.parameters(), - 1e-6)); } +}; + +/// +/// @brief Unit test for Kalman fitter with measurements along the x-axis +/// +BOOST_AUTO_TEST_CASE(kalman_fitter_zero_field) { + // Build detector + CubicTrackingGeometry cGeometry(tgContext); + auto detector = cGeometry(); + + // Build navigator for the measurement creatoin + Navigator mNavigator(detector); + mNavigator.resolvePassive = false; + mNavigator.resolveMaterial = true; + mNavigator.resolveSensitive = true; + + // Use straingt line stepper to create the measurements + StraightLineStepper mStepper; + + // Define the measurement propagator + using MeasurementPropagator = Propagator<StraightLineStepper, Navigator>; + + // Build propagator for the measurement creation + MeasurementPropagator mPropagator(mStepper, mNavigator); + Vector3D mPos(-3. * units::_m, 0., 0.), mMom(1. * units::_GeV, 0., 0); + SingleCurvilinearTrackParameters<NeutralPolicy> mStart(nullptr, mPos, mMom); + + // Create action list for the measurement creation + using MeasurementActions = ActionList<MeasurementCreator, DebugOutput>; + using MeasurementAborters = AbortList<detail::EndOfWorldReached>; + + auto pixelResX = Resolution(eLOC_0, 25. * units::_um); + auto pixelResY = Resolution(eLOC_1, 50. * units::_um); + auto stripResX = Resolution(eLOC_0, 100. * units::_um); + auto stripResY = Resolution(eLOC_1, 150. * units::_um); + + ElementResolution pixelElementRes = {pixelResX, pixelResY}; + ElementResolution stripElementResI = {stripResX}; + ElementResolution stripElementResO = {stripResY}; + + VolumeResolution pixelVolumeRes; + pixelVolumeRes[2] = pixelElementRes; + pixelVolumeRes[4] = pixelElementRes; + + VolumeResolution stripVolumeRes; + stripVolumeRes[2] = stripElementResI; + stripVolumeRes[4] = stripElementResO; + stripVolumeRes[6] = stripElementResI; + stripVolumeRes[8] = stripElementResO; + + DetectorResolution detRes; + detRes[2] = pixelVolumeRes; + detRes[3] = stripVolumeRes; + + // Set options for propagator + PropagatorOptions<MeasurementActions, MeasurementAborters> mOptions( + tgContext, mfContext); + mOptions.debug = debugMode; + auto& mCreator = mOptions.actionList.get<MeasurementCreator>(); + mCreator.detectorResolution = detRes; + + // Launch and collect - the measurements + auto mResult = mPropagator.propagate(mStart, mOptions).value(); + if (debugMode) { + const auto debugString = + mResult.template get<DebugOutput::result_type>().debugString; + std::cout << ">>>> Measurement creation: " << std::endl; + std::cout << debugString; + } + + auto measurements = mResult.template get<MeasurementCreator::result_type>(); + BOOST_CHECK_EQUAL(measurements.size(), 6); + + // The KalmanFitter - we use the eigen stepper for covariance transport + // Build navigator for the measurement creatoin + Navigator rNavigator(detector); + rNavigator.resolvePassive = false; + rNavigator.resolveMaterial = true; + rNavigator.resolveSensitive = true; + + // Configure propagation with deactivated B-field + ConstantBField bField(Vector3D(0., 0., 0.)); + using RecoStepper = EigenStepper<ConstantBField>; + RecoStepper rStepper(bField); + using RecoPropagator = Propagator<RecoStepper, Navigator>; + RecoPropagator rPropagator(rStepper, rNavigator); + + // Set initial parameters for the particle track + ActsSymMatrixD<5> cov; + cov << 1000. * units::_um, 0., 0., 0., 0., 0., 1000. * units::_um, 0., 0., 0., + 0., 0., 0.05, 0., 0., 0., 0., 0., 0.05, 0., 0., 0., 0., 0., 0.01; + + auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); + + Vector3D rPos(-3. * units::_m, 10. * units::_um * gauss(generator), + 100. * units::_um * gauss(generator)); + Vector3D rMom(1. * units::_GeV, 0.025 * units::_GeV * gauss(generator), + 0.025 * units::_GeV * gauss(generator)); + + SingleCurvilinearTrackParameters<ChargedPolicy> rStart(std::move(covPtr), + rPos, rMom, 1.); + + const Surface* rSurface = &rStart.referenceSurface(); + + using Updator = GainMatrixUpdator<BoundParameters>; + using Smoother = GainMatrixSmoother<BoundParameters>; + using KalmanFitter = KalmanFitter<RecoPropagator, Updator, Smoother>; + + KalmanFitter kFitter(rPropagator); + + KalmanFitterOptions kfOptions(tgContext, mfContext, calContext, rSurface); + + // Fit the track + auto fittedTrack = kFitter.fit(measurements, rStart, kfOptions); + auto fittedParameters = fittedTrack.fittedParameters.get(); + + // Make sure it is deterministic + auto fittedAgainTrack = kFitter.fit(measurements, rStart, kfOptions); + auto fittedAgainParameters = fittedAgainTrack.fittedParameters.get(); + + CHECK_CLOSE_REL(fittedParameters.parameters(), + fittedAgainParameters.parameters(), 1e-5); + + // Change the order of the measurements + std::vector<TrackState> shuffledMeasurements = { + measurements[3], measurements[2], measurements[1], + measurements[4], measurements[5], measurements[0]}; + + // Make sure it works for shuffled measurements as well + auto fittedShuffledTrack = + kFitter.fit(shuffledMeasurements, rStart, kfOptions); + auto fittedShuffledParameters = fittedShuffledTrack.fittedParameters.get(); + + CHECK_CLOSE_REL(fittedParameters.parameters(), + fittedShuffledParameters.parameters(), 1e-5); + + // Remove one measurement and find a hole + std::vector<TrackState> measurementsWithHole = { + measurements[0], measurements[1], measurements[2], measurements[4], + measurements[5]}; + + // Make sure it works for shuffled measurements as well + auto fittedWithHoleTrack = + kFitter.fit(measurementsWithHole, rStart, kfOptions); + auto fittedWithHoleParameters = fittedWithHoleTrack.fittedParameters.get(); + + // Count one hole + BOOST_CHECK_EQUAL(fittedWithHoleTrack.missedActiveSurfaces.size(), 1); + // And the parameters should be different + BOOST_CHECK(!Acts::Test::checkCloseRel(fittedParameters.parameters(), + fittedWithHoleParameters.parameters(), + 1e-6)); +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/Geometry/AlingmentContextTests.cpp b/Tests/Core/Geometry/AlingmentContextTests.cpp index f86aedfff1b55433f1a99058d4c92e0db3604df8..6dd3ec9971fb7ef8c633e159cd885ec56e9d50e5 100644 --- a/Tests/Core/Geometry/AlingmentContextTests.cpp +++ b/Tests/Core/Geometry/AlingmentContextTests.cpp @@ -26,198 +26,183 @@ namespace Acts { namespace Test { - /// @class AlignmentContext - struct AlignmentContext - { - - /// We have 2 different transforms - std::shared_ptr<const std::array<Transform3D, 2>> alignmentStore = nullptr; - - /// Context index - unsigned int alignmentIndex{0}; - - /// Default contructor - AlignmentContext() {} - - /// Constructor with Store and context index - AlignmentContext(std::shared_ptr<const std::array<Transform3D, 2>> aStore, - unsigned int aIndex = 0) - : alignmentStore(std::move(aStore)), alignmentIndex(aIndex) - { - } - }; - - /// @class AlignableDetectorElement +/// @class AlignmentContext +struct AlignmentContext { + /// We have 2 different transforms + std::shared_ptr<const std::array<Transform3D, 2>> alignmentStore = nullptr; + + /// Context index + unsigned int alignmentIndex{0}; + + /// Default contructor + AlignmentContext() {} + + /// Constructor with Store and context index + AlignmentContext(std::shared_ptr<const std::array<Transform3D, 2>> aStore, + unsigned int aIndex = 0) + : alignmentStore(std::move(aStore)), alignmentIndex(aIndex) {} +}; + +/// @class AlignableDetectorElement +/// +/// This is a lightweight type of detector element, +/// it simply implements the base class. +class AlignableDetectorElement : public DetectorElementBase { + public: + // Deleted default constructor + AlignableDetectorElement() = delete; + + /// Constructor for single sided detector element + /// - bound to a Plane Surface /// - /// This is a lightweight type of detector element, - /// it simply implements the base class. - class AlignableDetectorElement : public DetectorElementBase - { - public: - // Deleted default constructor - AlignableDetectorElement() = delete; - - /// Constructor for single sided detector element - /// - bound to a Plane Surface - /// - /// @param transform is the transform that element the layer in 3D frame - /// @param pBounds is the planar bounds for the planar detector element - /// @param thickness is the module thickness - AlignableDetectorElement(std::shared_ptr<const Transform3D> transform, - std::shared_ptr<const PlanarBounds> pBounds, - double thickness) - : DetectorElementBase() - , m_elementTransform(std::move(transform)) - , m_elementThickness(thickness) - { - auto mutableSurface = Surface::makeShared<PlaneSurface>(pBounds, *this); - m_elementSurface = mutableSurface; - } - - /// Destructor - ~AlignableDetectorElement() override { /*nop */} - - /// Return local to global transform associated with this identifier - /// - /// @param gctx The current geometry context object, e.g. alignment - /// - /// @note this is called from the surface().transform() in the PROXY mode - const Transform3D& - transform(const GeometryContext& gctx) const override; - - /// Return surface associated with this detector element - const Surface& - surface() const override; - - /// The maximal thickness of the detector element wrt normal axis - double - thickness() const override; - - private: - /// the transform for positioning in 3D space - std::shared_ptr<const Transform3D> m_elementTransform; - /// the surface represented by it - std::shared_ptr<const Surface> m_elementSurface{nullptr}; - /// the element thickness - double m_elementThickness{0.}; - }; - - inline const Transform3D& - AlignableDetectorElement::transform(const GeometryContext& gctx) const - { - auto alignContext = std::any_cast<AlignmentContext>(gctx); - if (alignContext.alignmentStore != nullptr - and alignContext.alignmentIndex < 2) { - return (*(alignContext.alignmentStore))[alignContext.alignmentIndex]; - } - return (*m_elementTransform); + /// @param transform is the transform that element the layer in 3D frame + /// @param pBounds is the planar bounds for the planar detector element + /// @param thickness is the module thickness + AlignableDetectorElement(std::shared_ptr<const Transform3D> transform, + std::shared_ptr<const PlanarBounds> pBounds, + double thickness) + : DetectorElementBase(), + m_elementTransform(std::move(transform)), + m_elementThickness(thickness) { + auto mutableSurface = Surface::makeShared<PlaneSurface>(pBounds, *this); + m_elementSurface = mutableSurface; } - inline const Surface& - AlignableDetectorElement::surface() const - { - return *m_elementSurface; + /// Destructor + ~AlignableDetectorElement() override { /*nop */ } - inline double - AlignableDetectorElement::thickness() const - { - return m_elementThickness; - } - - /// Unit test for creating compliant/non-compliant Surface object - BOOST_AUTO_TEST_CASE(AlignmentContextTests) - { - - // The nominal and alingments - // - Vector3D nominalCenter(0., 0., 0.); - Vector3D negativeCenter(0., 0., -1.); - Vector3D positiveCenter(0., 0., 1.); - - // Checkpoints - // - Vector3D onNominal(3., 3., 0.); - Vector3D onNegative(3., 3., -1.); - Vector3D onPositive(3., 3., 1.); - - // Local position - Vector2D localPosition(3., 3.); - - // A position place holder and dymmy momentum - // - Vector3D globalPosition(100., 100., 100.); - Vector3D dummyMomentum(4., 4., 4.); - - Transform3D negativeTransform = Transform3D::Identity(); - negativeTransform.translation() = negativeCenter; - - Transform3D positiveTransform = Transform3D::Identity(); - positiveTransform.translation() = positiveCenter; - - std::array<Transform3D, 2> alignmentArray - = {negativeTransform, positiveTransform}; - - std::shared_ptr<const std::array<Transform3D, 2>> alignmentStore - = std::make_shared<const std::array<Transform3D, 2>>(alignmentArray); - - // The detector element at nominal position - AlignableDetectorElement alignedElement( - std::make_shared<const Transform3D>(Transform3D::Identity()), - std::make_shared<const RectangleBounds>(100. * units::_cm, - 100. * units::_cm), - 1. * units::_mm); - - const auto& alignedSurface = alignedElement.surface(); - - // The alignment centexts - AlignmentContext defaultContext{}; - AlignmentContext negativeContext(alignmentStore, 0); - AlignmentContext positiveContext(alignmentStore, 1); - - // Test the transforms - BOOST_CHECK(alignedSurface.transform(defaultContext) - .isApprox(Transform3D::Identity())); - BOOST_CHECK( - alignedSurface.transform(negativeContext).isApprox(negativeTransform)); - BOOST_CHECK( - alignedSurface.transform(positiveContext).isApprox(positiveTransform)); - - // Test the centers - BOOST_CHECK_EQUAL(alignedSurface.center(defaultContext), nominalCenter); - BOOST_CHECK_EQUAL(alignedSurface.center(negativeContext), negativeCenter); - BOOST_CHECK_EQUAL(alignedSurface.center(positiveContext), positiveCenter); - - // Test OnSurface - BOOST_CHECK( - alignedSurface.isOnSurface(defaultContext, onNominal, dummyMomentum)); - BOOST_CHECK( - alignedSurface.isOnSurface(negativeContext, onNegative, dummyMomentum)); - BOOST_CHECK( - alignedSurface.isOnSurface(positiveContext, onPositive, dummyMomentum)); - - // Test local to Global and vice versa - alignedSurface.localToGlobal( - defaultContext, localPosition, dummyMomentum, globalPosition); - BOOST_CHECK_EQUAL(globalPosition, onNominal); - alignedSurface.globalToLocal( - defaultContext, onNominal, dummyMomentum, localPosition); - BOOST_CHECK_EQUAL(localPosition, Vector2D(3., 3.)); - - alignedSurface.localToGlobal( - negativeContext, localPosition, dummyMomentum, globalPosition); - BOOST_CHECK_EQUAL(globalPosition, onNegative); - alignedSurface.globalToLocal( - negativeContext, onNegative, dummyMomentum, localPosition); - BOOST_CHECK_EQUAL(localPosition, Vector2D(3., 3.)); - - alignedSurface.localToGlobal( - positiveContext, localPosition, dummyMomentum, globalPosition); - BOOST_CHECK_EQUAL(globalPosition, onPositive); - alignedSurface.globalToLocal( - positiveContext, onPositive, dummyMomentum, localPosition); - BOOST_CHECK_EQUAL(localPosition, Vector2D(3., 3.)); + /// Return local to global transform associated with this identifier + /// + /// @param gctx The current geometry context object, e.g. alignment + /// + /// @note this is called from the surface().transform() in the PROXY mode + const Transform3D& transform(const GeometryContext& gctx) const override; + + /// Return surface associated with this detector element + const Surface& surface() const override; + + /// The maximal thickness of the detector element wrt normal axis + double thickness() const override; + + private: + /// the transform for positioning in 3D space + std::shared_ptr<const Transform3D> m_elementTransform; + /// the surface represented by it + std::shared_ptr<const Surface> m_elementSurface{nullptr}; + /// the element thickness + double m_elementThickness{0.}; +}; + +inline const Transform3D& AlignableDetectorElement::transform( + const GeometryContext& gctx) const { + auto alignContext = std::any_cast<AlignmentContext>(gctx); + if (alignContext.alignmentStore != nullptr and + alignContext.alignmentIndex < 2) { + return (*(alignContext.alignmentStore))[alignContext.alignmentIndex]; } + return (*m_elementTransform); +} + +inline const Surface& AlignableDetectorElement::surface() const { + return *m_elementSurface; +} + +inline double AlignableDetectorElement::thickness() const { + return m_elementThickness; +} + +/// Unit test for creating compliant/non-compliant Surface object +BOOST_AUTO_TEST_CASE(AlignmentContextTests) { + // The nominal and alingments + // + Vector3D nominalCenter(0., 0., 0.); + Vector3D negativeCenter(0., 0., -1.); + Vector3D positiveCenter(0., 0., 1.); + + // Checkpoints + // + Vector3D onNominal(3., 3., 0.); + Vector3D onNegative(3., 3., -1.); + Vector3D onPositive(3., 3., 1.); + + // Local position + Vector2D localPosition(3., 3.); + + // A position place holder and dymmy momentum + // + Vector3D globalPosition(100., 100., 100.); + Vector3D dummyMomentum(4., 4., 4.); + + Transform3D negativeTransform = Transform3D::Identity(); + negativeTransform.translation() = negativeCenter; + + Transform3D positiveTransform = Transform3D::Identity(); + positiveTransform.translation() = positiveCenter; + + std::array<Transform3D, 2> alignmentArray = {negativeTransform, + positiveTransform}; + + std::shared_ptr<const std::array<Transform3D, 2>> alignmentStore = + std::make_shared<const std::array<Transform3D, 2>>(alignmentArray); + + // The detector element at nominal position + AlignableDetectorElement alignedElement( + std::make_shared<const Transform3D>(Transform3D::Identity()), + std::make_shared<const RectangleBounds>(100. * units::_cm, + 100. * units::_cm), + 1. * units::_mm); + + const auto& alignedSurface = alignedElement.surface(); + + // The alignment centexts + AlignmentContext defaultContext{}; + AlignmentContext negativeContext(alignmentStore, 0); + AlignmentContext positiveContext(alignmentStore, 1); + + // Test the transforms + BOOST_CHECK(alignedSurface.transform(defaultContext) + .isApprox(Transform3D::Identity())); + BOOST_CHECK( + alignedSurface.transform(negativeContext).isApprox(negativeTransform)); + BOOST_CHECK( + alignedSurface.transform(positiveContext).isApprox(positiveTransform)); + + // Test the centers + BOOST_CHECK_EQUAL(alignedSurface.center(defaultContext), nominalCenter); + BOOST_CHECK_EQUAL(alignedSurface.center(negativeContext), negativeCenter); + BOOST_CHECK_EQUAL(alignedSurface.center(positiveContext), positiveCenter); + + // Test OnSurface + BOOST_CHECK( + alignedSurface.isOnSurface(defaultContext, onNominal, dummyMomentum)); + BOOST_CHECK( + alignedSurface.isOnSurface(negativeContext, onNegative, dummyMomentum)); + BOOST_CHECK( + alignedSurface.isOnSurface(positiveContext, onPositive, dummyMomentum)); + + // Test local to Global and vice versa + alignedSurface.localToGlobal(defaultContext, localPosition, dummyMomentum, + globalPosition); + BOOST_CHECK_EQUAL(globalPosition, onNominal); + alignedSurface.globalToLocal(defaultContext, onNominal, dummyMomentum, + localPosition); + BOOST_CHECK_EQUAL(localPosition, Vector2D(3., 3.)); + + alignedSurface.localToGlobal(negativeContext, localPosition, dummyMomentum, + globalPosition); + BOOST_CHECK_EQUAL(globalPosition, onNegative); + alignedSurface.globalToLocal(negativeContext, onNegative, dummyMomentum, + localPosition); + BOOST_CHECK_EQUAL(localPosition, Vector2D(3., 3.)); + + alignedSurface.localToGlobal(positiveContext, localPosition, dummyMomentum, + globalPosition); + BOOST_CHECK_EQUAL(globalPosition, onPositive); + alignedSurface.globalToLocal(positiveContext, onPositive, dummyMomentum, + localPosition); + BOOST_CHECK_EQUAL(localPosition, Vector2D(3., 3.)); +} } // namespace Test } // namespace Acts \ No newline at end of file diff --git a/Tests/Core/Geometry/ConeLayerTests.cpp b/Tests/Core/Geometry/ConeLayerTests.cpp index ab5bece15e9d378d96509a1c9fd001cb10a4769e..3a2b589c721c6609e5f34e373df4fac61b1e159d 100644 --- a/Tests/Core/Geometry/ConeLayerTests.cpp +++ b/Tests/Core/Geometry/ConeLayerTests.cpp @@ -36,83 +36,74 @@ namespace utf = boost::unit_test; namespace Acts { namespace Test { - namespace Layers { - BOOST_AUTO_TEST_SUITE(Layers) +namespace Layers { +BOOST_AUTO_TEST_SUITE(Layers) - /// Unit test for creating compliant/non-compliant ConeLayer object - BOOST_AUTO_TEST_CASE(ConeLayerConstruction) - { - // default constructor, copy and assignment are all deleted - // minimally need a Transform3D and a PlanarBounds object (e.g. - // ConeBounds) to construct - Translation3D translation{0., 1., 2.}; - auto pTransform = std::make_shared<const Transform3D>(translation); - double alpha(M_PI / 8.0); - const bool symmetric(false); - auto pCone = std::make_shared<const ConeBounds>(alpha, symmetric); - // for some reason, this one doesnt exist - // auto pConeLayer = ConeLayer::create(pTransform, pCone); - // BOOST_CHECK_EQUAL(pConeLayer->layerType(), LayerType::passive); - // next level: need an array of Surfaces; - // bounds object, rectangle type - auto rBounds = std::make_shared<const RectangleBounds>(1., 1.); - /// Constructor with transform pointer - auto pNullTransform = std::make_shared<const Transform3D>(); - const std::vector<std::shared_ptr<const Surface>> aSurfaces{ - Surface::makeShared<PlaneSurface>(pNullTransform, rBounds), - Surface::makeShared<PlaneSurface>(pNullTransform, rBounds)}; - const double thickness(1.0); - auto pConeLayerFromSurfaces - = ConeLayer::create(pTransform, pCone, nullptr); - BOOST_CHECK_EQUAL(pConeLayerFromSurfaces->layerType(), LayerType::active); - // construct with thickness: - auto pConeLayerWithThickness - = ConeLayer::create(pTransform, pCone, nullptr, thickness); - BOOST_CHECK_EQUAL(pConeLayerWithThickness->thickness(), thickness); - // with an approach descriptor... - std::unique_ptr<ApproachDescriptor> ad( - new GenericApproachDescriptor(aSurfaces)); - auto adPtr = ad.get(); - auto pConeLayerWithApproachDescriptor = ConeLayer::create( - pTransform, pCone, nullptr, thickness, std::move(ad)); - BOOST_CHECK_EQUAL(pConeLayerWithApproachDescriptor->approachDescriptor(), - adPtr); - // with the layerType specified... - auto pConeLayerWithLayerType = ConeLayer::create(pTransform, - pCone, - nullptr, - thickness, - std::move(ad), - LayerType::passive); - BOOST_CHECK_EQUAL(pConeLayerWithLayerType->layerType(), - LayerType::passive); - } +/// Unit test for creating compliant/non-compliant ConeLayer object +BOOST_AUTO_TEST_CASE(ConeLayerConstruction) { + // default constructor, copy and assignment are all deleted + // minimally need a Transform3D and a PlanarBounds object (e.g. + // ConeBounds) to construct + Translation3D translation{0., 1., 2.}; + auto pTransform = std::make_shared<const Transform3D>(translation); + double alpha(M_PI / 8.0); + const bool symmetric(false); + auto pCone = std::make_shared<const ConeBounds>(alpha, symmetric); + // for some reason, this one doesnt exist + // auto pConeLayer = ConeLayer::create(pTransform, pCone); + // BOOST_CHECK_EQUAL(pConeLayer->layerType(), LayerType::passive); + // next level: need an array of Surfaces; + // bounds object, rectangle type + auto rBounds = std::make_shared<const RectangleBounds>(1., 1.); + /// Constructor with transform pointer + auto pNullTransform = std::make_shared<const Transform3D>(); + const std::vector<std::shared_ptr<const Surface>> aSurfaces{ + Surface::makeShared<PlaneSurface>(pNullTransform, rBounds), + Surface::makeShared<PlaneSurface>(pNullTransform, rBounds)}; + const double thickness(1.0); + auto pConeLayerFromSurfaces = ConeLayer::create(pTransform, pCone, nullptr); + BOOST_CHECK_EQUAL(pConeLayerFromSurfaces->layerType(), LayerType::active); + // construct with thickness: + auto pConeLayerWithThickness = + ConeLayer::create(pTransform, pCone, nullptr, thickness); + BOOST_CHECK_EQUAL(pConeLayerWithThickness->thickness(), thickness); + // with an approach descriptor... + std::unique_ptr<ApproachDescriptor> ad( + new GenericApproachDescriptor(aSurfaces)); + auto adPtr = ad.get(); + auto pConeLayerWithApproachDescriptor = + ConeLayer::create(pTransform, pCone, nullptr, thickness, std::move(ad)); + BOOST_CHECK_EQUAL(pConeLayerWithApproachDescriptor->approachDescriptor(), + adPtr); + // with the layerType specified... + auto pConeLayerWithLayerType = ConeLayer::create( + pTransform, pCone, nullptr, thickness, std::move(ad), LayerType::passive); + BOOST_CHECK_EQUAL(pConeLayerWithLayerType->layerType(), LayerType::passive); +} - /// Unit test for testing Layer properties - BOOST_AUTO_TEST_CASE(ConeLayerProperties /*, *utf::expected_failures(1)*/) - { - Translation3D translation{0., 1., 2.}; - auto pTransform = std::make_shared<const Transform3D>(translation); - double alpha(M_PI / 8.0); - const bool symmetric(false); - // bounds object, rectangle type - auto rBounds = std::make_shared<const RectangleBounds>(1., 1.); - /// Constructor with transform pointer - auto pNullTransform = std::make_shared<const Transform3D>(); - auto pCone = std::make_shared<const ConeBounds>(alpha, symmetric); - const std::vector<std::shared_ptr<const Surface>> aSurfaces{ - Surface::makeShared<PlaneSurface>(pNullTransform, rBounds), - Surface::makeShared<PlaneSurface>(pNullTransform, rBounds)}; - // const double thickness(1.0); - auto pConeLayerFromSurfaces - = ConeLayer::create(pTransform, pCone, nullptr); - // auto planeSurface = pConeLayer->surfaceRepresentation(); - BOOST_CHECK_EQUAL(pConeLayerFromSurfaces->surfaceRepresentation().name(), - std::string("Acts::ConeSurface")); - } +/// Unit test for testing Layer properties +BOOST_AUTO_TEST_CASE(ConeLayerProperties /*, *utf::expected_failures(1)*/) { + Translation3D translation{0., 1., 2.}; + auto pTransform = std::make_shared<const Transform3D>(translation); + double alpha(M_PI / 8.0); + const bool symmetric(false); + // bounds object, rectangle type + auto rBounds = std::make_shared<const RectangleBounds>(1., 1.); + /// Constructor with transform pointer + auto pNullTransform = std::make_shared<const Transform3D>(); + auto pCone = std::make_shared<const ConeBounds>(alpha, symmetric); + const std::vector<std::shared_ptr<const Surface>> aSurfaces{ + Surface::makeShared<PlaneSurface>(pNullTransform, rBounds), + Surface::makeShared<PlaneSurface>(pNullTransform, rBounds)}; + // const double thickness(1.0); + auto pConeLayerFromSurfaces = ConeLayer::create(pTransform, pCone, nullptr); + // auto planeSurface = pConeLayer->surfaceRepresentation(); + BOOST_CHECK_EQUAL(pConeLayerFromSurfaces->surfaceRepresentation().name(), + std::string("Acts::ConeSurface")); +} - BOOST_AUTO_TEST_SUITE_END() - } // namespace Layers +BOOST_AUTO_TEST_SUITE_END() +} // namespace Layers } // namespace Test } // namespace Acts diff --git a/Tests/Core/Geometry/CuboidVolumeBuilderTests.cpp b/Tests/Core/Geometry/CuboidVolumeBuilderTests.cpp index c6e9c36862ce1616d930f273e31a361295efde66..c91af09a724e6fef0cae87838de630d1d017894f 100644 --- a/Tests/Core/Geometry/CuboidVolumeBuilderTests.cpp +++ b/Tests/Core/Geometry/CuboidVolumeBuilderTests.cpp @@ -32,210 +32,206 @@ namespace Acts { namespace Test { - BOOST_AUTO_TEST_CASE(CuboidVolumeBuilderTest) - { - - // Construct builder - CuboidVolumeBuilder cvb; - - // Create a test context - GeometryContext tgContext = GeometryContext(); - - // Create configurations for surfaces - std::vector<CuboidVolumeBuilder::SurfaceConfig> surfaceConfig; - for (unsigned int i = 1; i < 5; i++) { - // Position of the surfaces - CuboidVolumeBuilder::SurfaceConfig cfg; - cfg.position = {i * units::_m, 0., 0.}; - - // Rotation of the surfaces - double rotationAngle = M_PI * 0.5; - Vector3D xPos(cos(rotationAngle), 0., sin(rotationAngle)); - Vector3D yPos(0., 1., 0.); - Vector3D zPos(-sin(rotationAngle), 0., cos(rotationAngle)); - cfg.rotation.col(0) = xPos; - cfg.rotation.col(1) = yPos; - cfg.rotation.col(2) = zPos; - - // Boundaries of the surfaces - cfg.rBounds = std::make_shared<const RectangleBounds>( - RectangleBounds(0.5 * units::_m, 0.5 * units::_m)); - - // Material of the surfaces - MaterialProperties matProp( - 352.8, 407., 9.012, 4., 1.848e-3, 0.5 * units::_mm); - cfg.surMat = std::shared_ptr<const ISurfaceMaterial>( - new HomogeneousSurfaceMaterial(matProp)); - - // Thickness of the detector element - cfg.thickness = 1. * units::_um; - - cfg.detElementConstructor - = [](std::shared_ptr<const Transform3D> trans, - std::shared_ptr<const RectangleBounds> bounds, - double thickness) { - return new DetectorElementStub(trans, bounds, thickness); - }; - surfaceConfig.push_back(cfg); - } - - // Test that there are actually 4 surface configurations - BOOST_CHECK_EQUAL(surfaceConfig.size(), 4); - - // Test that 4 surfaces can be built - for (const auto& cfg : surfaceConfig) { - std::shared_ptr<const PlaneSurface> pSur - = cvb.buildSurface(tgContext, cfg); - BOOST_CHECK_NE(pSur, nullptr); - CHECK_CLOSE_ABS(pSur->center(tgContext), cfg.position, 1e-9); - BOOST_CHECK_NE(pSur->surfaceMaterial(), nullptr); - BOOST_CHECK_NE(pSur->associatedDetectorElement(), nullptr); - } - - //////////////////////////////////////////////////////////////////// - // Build layer configurations - std::vector<CuboidVolumeBuilder::LayerConfig> layerConfig; - for (auto& sCfg : surfaceConfig) { - CuboidVolumeBuilder::LayerConfig cfg; - cfg.surfaceCfg = sCfg; - layerConfig.push_back(cfg); - } - - // Test that there are actually 4 layer configurations - BOOST_CHECK_EQUAL(layerConfig.size(), 4); - - // Test that 4 layers with surfaces can be built - for (auto& cfg : layerConfig) { - LayerPtr layer = cvb.buildLayer(tgContext, cfg); - BOOST_CHECK_NE(layer, nullptr); - BOOST_CHECK_NE(cfg.surface, nullptr); - BOOST_CHECK_EQUAL(layer->surfaceArray()->surfaces().size(), 1); - BOOST_CHECK_EQUAL(layer->layerType(), LayerType::active); - } - - for (auto& cfg : layerConfig) { - cfg.surface = nullptr; - } - - // Build volume configuration - CuboidVolumeBuilder::VolumeConfig volumeConfig; - volumeConfig.position = {2.5 * units::_m, 0., 0.}; - volumeConfig.length = {5. * units::_m, 1. * units::_m, 1. * units::_m}; - volumeConfig.layerCfg = layerConfig; - volumeConfig.name = "Test volume"; - volumeConfig.volumeMaterial - = std::make_shared<const HomogeneousVolumeMaterial>( - Material(352.8, 407., 9.012, 4., 1.848e-3)); - - // Test the building - std::shared_ptr<TrackingVolume> trVol - = cvb.buildVolume(tgContext, volumeConfig); - BOOST_CHECK_EQUAL(volumeConfig.layers.size(), 4); - BOOST_CHECK_EQUAL(trVol->confinedLayers()->arrayObjects().size(), - volumeConfig.layers.size() * 2 - + 1); // #layers = navigation + material layers - BOOST_CHECK_EQUAL(trVol->volumeName(), volumeConfig.name); - BOOST_CHECK_NE(trVol->volumeMaterial(), nullptr); - - // Test the building - volumeConfig.layers.clear(); - trVol = cvb.buildVolume(tgContext, volumeConfig); - BOOST_CHECK_EQUAL(volumeConfig.layers.size(), 4); - BOOST_CHECK_EQUAL(trVol->confinedLayers()->arrayObjects().size(), - volumeConfig.layers.size() * 2 - + 1); // #layers = navigation + material layers - BOOST_CHECK_EQUAL(trVol->volumeName(), volumeConfig.name); - - volumeConfig.layers.clear(); - for (auto& lay : volumeConfig.layerCfg) { - lay.surface = nullptr; - lay.active = true; - } - trVol = cvb.buildVolume(tgContext, volumeConfig); - BOOST_CHECK_EQUAL(volumeConfig.layers.size(), 4); - for (auto& lay : volumeConfig.layers) { - BOOST_CHECK_EQUAL(lay->layerType(), LayerType::active); - } - - volumeConfig.layers.clear(); - for (auto& lay : volumeConfig.layerCfg) { - lay.active = true; - } - trVol = cvb.buildVolume(tgContext, volumeConfig); - BOOST_CHECK_EQUAL(volumeConfig.layers.size(), 4); - for (auto& lay : volumeConfig.layers) { - BOOST_CHECK_EQUAL(lay->layerType(), LayerType::active); - } - - //////////////////////////////////////////////////////////////////// - // Build TrackingGeometry configuration - - // Build second volume - std::vector<CuboidVolumeBuilder::SurfaceConfig> surfaceConfig2; - for (int i = 1; i < 5; i++) { - // Position of the surfaces - CuboidVolumeBuilder::SurfaceConfig cfg; - cfg.position = {-i * units::_m, 0., 0.}; - - // Rotation of the surfaces - double rotationAngle = M_PI * 0.5; - Vector3D xPos(cos(rotationAngle), 0., sin(rotationAngle)); - Vector3D yPos(0., 1., 0.); - Vector3D zPos(-sin(rotationAngle), 0., cos(rotationAngle)); - cfg.rotation.col(0) = xPos; - cfg.rotation.col(1) = yPos; - cfg.rotation.col(2) = zPos; - - // Boundaries of the surfaces - cfg.rBounds = std::make_shared<const RectangleBounds>( - RectangleBounds(0.5 * units::_m, 0.5 * units::_m)); - - // Material of the surfaces - MaterialProperties matProp( - 352.8, 407., 9.012, 4., 1.848e-3, 0.5 * units::_mm); - cfg.surMat = std::shared_ptr<const ISurfaceMaterial>( - new HomogeneousSurfaceMaterial(matProp)); - - // Thickness of the detector element - cfg.thickness = 1. * units::_um; - surfaceConfig2.push_back(cfg); - } - - std::vector<CuboidVolumeBuilder::LayerConfig> layerConfig2; - for (auto& sCfg : surfaceConfig2) { - CuboidVolumeBuilder::LayerConfig cfg; - cfg.surfaceCfg = sCfg; - layerConfig2.push_back(cfg); - } - CuboidVolumeBuilder::VolumeConfig volumeConfig2; - volumeConfig2.position = {-2.5 * units::_m, 0., 0.}; - volumeConfig2.length = {5. * units::_m, 1. * units::_m, 1. * units::_m}; - volumeConfig2.layerCfg = layerConfig2; - volumeConfig2.name = "Test volume2"; - - CuboidVolumeBuilder::Config config; - config.position = {0., 0., 0.}; - config.length = {10. * units::_m, 1. * units::_m, 1. * units::_m}; - config.volumeCfg = {volumeConfig2, volumeConfig}; - - cvb.setConfig(config); - TrackingGeometryBuilder::Config tgbCfg; - tgbCfg.trackingVolumeBuilders.push_back( - [=](const auto& context, const auto& inner, const auto&) { - return cvb.trackingVolume(context, inner, nullptr); - }); - TrackingGeometryBuilder tgb(tgbCfg); - - std::unique_ptr<const TrackingGeometry> detector - = tgb.trackingGeometry(tgContext); - BOOST_CHECK_EQUAL( - detector->lowestTrackingVolume(tgContext, Vector3D(1., 0., 0.)) - ->volumeName(), - volumeConfig.name); - BOOST_CHECK_EQUAL( - detector->lowestTrackingVolume(tgContext, Vector3D(-1., 0., 0.)) - ->volumeName(), - volumeConfig2.name); +BOOST_AUTO_TEST_CASE(CuboidVolumeBuilderTest) { + // Construct builder + CuboidVolumeBuilder cvb; + + // Create a test context + GeometryContext tgContext = GeometryContext(); + + // Create configurations for surfaces + std::vector<CuboidVolumeBuilder::SurfaceConfig> surfaceConfig; + for (unsigned int i = 1; i < 5; i++) { + // Position of the surfaces + CuboidVolumeBuilder::SurfaceConfig cfg; + cfg.position = {i * units::_m, 0., 0.}; + + // Rotation of the surfaces + double rotationAngle = M_PI * 0.5; + Vector3D xPos(cos(rotationAngle), 0., sin(rotationAngle)); + Vector3D yPos(0., 1., 0.); + Vector3D zPos(-sin(rotationAngle), 0., cos(rotationAngle)); + cfg.rotation.col(0) = xPos; + cfg.rotation.col(1) = yPos; + cfg.rotation.col(2) = zPos; + + // Boundaries of the surfaces + cfg.rBounds = std::make_shared<const RectangleBounds>( + RectangleBounds(0.5 * units::_m, 0.5 * units::_m)); + + // Material of the surfaces + MaterialProperties matProp(352.8, 407., 9.012, 4., 1.848e-3, + 0.5 * units::_mm); + cfg.surMat = std::shared_ptr<const ISurfaceMaterial>( + new HomogeneousSurfaceMaterial(matProp)); + + // Thickness of the detector element + cfg.thickness = 1. * units::_um; + + cfg.detElementConstructor = + [](std::shared_ptr<const Transform3D> trans, + std::shared_ptr<const RectangleBounds> bounds, double thickness) { + return new DetectorElementStub(trans, bounds, thickness); + }; + surfaceConfig.push_back(cfg); } + + // Test that there are actually 4 surface configurations + BOOST_CHECK_EQUAL(surfaceConfig.size(), 4); + + // Test that 4 surfaces can be built + for (const auto& cfg : surfaceConfig) { + std::shared_ptr<const PlaneSurface> pSur = cvb.buildSurface(tgContext, cfg); + BOOST_CHECK_NE(pSur, nullptr); + CHECK_CLOSE_ABS(pSur->center(tgContext), cfg.position, 1e-9); + BOOST_CHECK_NE(pSur->surfaceMaterial(), nullptr); + BOOST_CHECK_NE(pSur->associatedDetectorElement(), nullptr); + } + + //////////////////////////////////////////////////////////////////// + // Build layer configurations + std::vector<CuboidVolumeBuilder::LayerConfig> layerConfig; + for (auto& sCfg : surfaceConfig) { + CuboidVolumeBuilder::LayerConfig cfg; + cfg.surfaceCfg = sCfg; + layerConfig.push_back(cfg); + } + + // Test that there are actually 4 layer configurations + BOOST_CHECK_EQUAL(layerConfig.size(), 4); + + // Test that 4 layers with surfaces can be built + for (auto& cfg : layerConfig) { + LayerPtr layer = cvb.buildLayer(tgContext, cfg); + BOOST_CHECK_NE(layer, nullptr); + BOOST_CHECK_NE(cfg.surface, nullptr); + BOOST_CHECK_EQUAL(layer->surfaceArray()->surfaces().size(), 1); + BOOST_CHECK_EQUAL(layer->layerType(), LayerType::active); + } + + for (auto& cfg : layerConfig) { + cfg.surface = nullptr; + } + + // Build volume configuration + CuboidVolumeBuilder::VolumeConfig volumeConfig; + volumeConfig.position = {2.5 * units::_m, 0., 0.}; + volumeConfig.length = {5. * units::_m, 1. * units::_m, 1. * units::_m}; + volumeConfig.layerCfg = layerConfig; + volumeConfig.name = "Test volume"; + volumeConfig.volumeMaterial = + std::make_shared<const HomogeneousVolumeMaterial>( + Material(352.8, 407., 9.012, 4., 1.848e-3)); + + // Test the building + std::shared_ptr<TrackingVolume> trVol = + cvb.buildVolume(tgContext, volumeConfig); + BOOST_CHECK_EQUAL(volumeConfig.layers.size(), 4); + BOOST_CHECK_EQUAL(trVol->confinedLayers()->arrayObjects().size(), + volumeConfig.layers.size() * 2 + + 1); // #layers = navigation + material layers + BOOST_CHECK_EQUAL(trVol->volumeName(), volumeConfig.name); + BOOST_CHECK_NE(trVol->volumeMaterial(), nullptr); + + // Test the building + volumeConfig.layers.clear(); + trVol = cvb.buildVolume(tgContext, volumeConfig); + BOOST_CHECK_EQUAL(volumeConfig.layers.size(), 4); + BOOST_CHECK_EQUAL(trVol->confinedLayers()->arrayObjects().size(), + volumeConfig.layers.size() * 2 + + 1); // #layers = navigation + material layers + BOOST_CHECK_EQUAL(trVol->volumeName(), volumeConfig.name); + + volumeConfig.layers.clear(); + for (auto& lay : volumeConfig.layerCfg) { + lay.surface = nullptr; + lay.active = true; + } + trVol = cvb.buildVolume(tgContext, volumeConfig); + BOOST_CHECK_EQUAL(volumeConfig.layers.size(), 4); + for (auto& lay : volumeConfig.layers) { + BOOST_CHECK_EQUAL(lay->layerType(), LayerType::active); + } + + volumeConfig.layers.clear(); + for (auto& lay : volumeConfig.layerCfg) { + lay.active = true; + } + trVol = cvb.buildVolume(tgContext, volumeConfig); + BOOST_CHECK_EQUAL(volumeConfig.layers.size(), 4); + for (auto& lay : volumeConfig.layers) { + BOOST_CHECK_EQUAL(lay->layerType(), LayerType::active); + } + + //////////////////////////////////////////////////////////////////// + // Build TrackingGeometry configuration + + // Build second volume + std::vector<CuboidVolumeBuilder::SurfaceConfig> surfaceConfig2; + for (int i = 1; i < 5; i++) { + // Position of the surfaces + CuboidVolumeBuilder::SurfaceConfig cfg; + cfg.position = {-i * units::_m, 0., 0.}; + + // Rotation of the surfaces + double rotationAngle = M_PI * 0.5; + Vector3D xPos(cos(rotationAngle), 0., sin(rotationAngle)); + Vector3D yPos(0., 1., 0.); + Vector3D zPos(-sin(rotationAngle), 0., cos(rotationAngle)); + cfg.rotation.col(0) = xPos; + cfg.rotation.col(1) = yPos; + cfg.rotation.col(2) = zPos; + + // Boundaries of the surfaces + cfg.rBounds = std::make_shared<const RectangleBounds>( + RectangleBounds(0.5 * units::_m, 0.5 * units::_m)); + + // Material of the surfaces + MaterialProperties matProp(352.8, 407., 9.012, 4., 1.848e-3, + 0.5 * units::_mm); + cfg.surMat = std::shared_ptr<const ISurfaceMaterial>( + new HomogeneousSurfaceMaterial(matProp)); + + // Thickness of the detector element + cfg.thickness = 1. * units::_um; + surfaceConfig2.push_back(cfg); + } + + std::vector<CuboidVolumeBuilder::LayerConfig> layerConfig2; + for (auto& sCfg : surfaceConfig2) { + CuboidVolumeBuilder::LayerConfig cfg; + cfg.surfaceCfg = sCfg; + layerConfig2.push_back(cfg); + } + CuboidVolumeBuilder::VolumeConfig volumeConfig2; + volumeConfig2.position = {-2.5 * units::_m, 0., 0.}; + volumeConfig2.length = {5. * units::_m, 1. * units::_m, 1. * units::_m}; + volumeConfig2.layerCfg = layerConfig2; + volumeConfig2.name = "Test volume2"; + + CuboidVolumeBuilder::Config config; + config.position = {0., 0., 0.}; + config.length = {10. * units::_m, 1. * units::_m, 1. * units::_m}; + config.volumeCfg = {volumeConfig2, volumeConfig}; + + cvb.setConfig(config); + TrackingGeometryBuilder::Config tgbCfg; + tgbCfg.trackingVolumeBuilders.push_back( + [=](const auto& context, const auto& inner, const auto&) { + return cvb.trackingVolume(context, inner, nullptr); + }); + TrackingGeometryBuilder tgb(tgbCfg); + + std::unique_ptr<const TrackingGeometry> detector = + tgb.trackingGeometry(tgContext); + BOOST_CHECK_EQUAL( + detector->lowestTrackingVolume(tgContext, Vector3D(1., 0., 0.)) + ->volumeName(), + volumeConfig.name); + BOOST_CHECK_EQUAL( + detector->lowestTrackingVolume(tgContext, Vector3D(-1., 0., 0.)) + ->volumeName(), + volumeConfig2.name); +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/Geometry/CutoutCylinderVolumeBoundsTest.cpp b/Tests/Core/Geometry/CutoutCylinderVolumeBoundsTest.cpp index e4cadfff16abcb307ca86894a3ef8765a88b8df7..93b8b60295476569c192edc0adc80cfe1cc0557b 100644 --- a/Tests/Core/Geometry/CutoutCylinderVolumeBoundsTest.cpp +++ b/Tests/Core/Geometry/CutoutCylinderVolumeBoundsTest.cpp @@ -23,94 +23,91 @@ namespace Acts { namespace Test { - BOOST_AUTO_TEST_SUITE(Volumes) +BOOST_AUTO_TEST_SUITE(Volumes) - BOOST_AUTO_TEST_CASE(construction_test) - { - CutoutCylinderVolumeBounds ccvb(5, 10, 15, 30, 25); - ccvb.toStream(std::cout); - } +BOOST_AUTO_TEST_CASE(construction_test) { + CutoutCylinderVolumeBounds ccvb(5, 10, 15, 30, 25); + ccvb.toStream(std::cout); +} - BOOST_AUTO_TEST_CASE(decomposeToSurfaces_test) - { - CutoutCylinderVolumeBounds ccvb(5, 10, 15, 30, 25); - PlyHelper<double> ply; - ccvb.draw(ply); +BOOST_AUTO_TEST_CASE(decomposeToSurfaces_test) { + CutoutCylinderVolumeBounds ccvb(5, 10, 15, 30, 25); + PlyHelper<double> ply; + ccvb.draw(ply); - std::ofstream os("ccvb.ply"); - os << ply; - } + std::ofstream os("ccvb.ply"); + os << ply; +} - BOOST_AUTO_TEST_CASE(inside_test) - { - CutoutCylinderVolumeBounds ccvb(5, 10, 15, 30, 25); +BOOST_AUTO_TEST_CASE(inside_test) { + CutoutCylinderVolumeBounds ccvb(5, 10, 15, 30, 25); - BOOST_CHECK(!ccvb.inside({0, 0, 0})); - BOOST_CHECK(!ccvb.inside({0, 3, 0})); - BOOST_CHECK(!ccvb.inside({3, 0, 0})); - BOOST_CHECK(!ccvb.inside({0, 7, 0})); - BOOST_CHECK(!ccvb.inside({7, 0, 0})); - BOOST_CHECK(ccvb.inside({0, 13, 0})); - BOOST_CHECK(ccvb.inside({13, 0, 0})); - BOOST_CHECK(!ccvb.inside({0, 17, 0})); - BOOST_CHECK(!ccvb.inside({17, 0, 0})); + BOOST_CHECK(!ccvb.inside({0, 0, 0})); + BOOST_CHECK(!ccvb.inside({0, 3, 0})); + BOOST_CHECK(!ccvb.inside({3, 0, 0})); + BOOST_CHECK(!ccvb.inside({0, 7, 0})); + BOOST_CHECK(!ccvb.inside({7, 0, 0})); + BOOST_CHECK(ccvb.inside({0, 13, 0})); + BOOST_CHECK(ccvb.inside({13, 0, 0})); + BOOST_CHECK(!ccvb.inside({0, 17, 0})); + BOOST_CHECK(!ccvb.inside({17, 0, 0})); - // outside in z - BOOST_CHECK(!ccvb.inside({0, 0, 35})); - BOOST_CHECK(!ccvb.inside({0, 0, -35})); - BOOST_CHECK(!ccvb.inside({0, 3, 35})); - BOOST_CHECK(!ccvb.inside({0, 3, -35})); - BOOST_CHECK(!ccvb.inside({3, 0, 35})); - BOOST_CHECK(!ccvb.inside({3, 0, -35})); - BOOST_CHECK(!ccvb.inside({0, 10, 35})); - BOOST_CHECK(!ccvb.inside({0, 10, -35})); - BOOST_CHECK(!ccvb.inside({10, 0, 35})); - BOOST_CHECK(!ccvb.inside({10, 0, -35})); - BOOST_CHECK(!ccvb.inside({0, 20, 35})); - BOOST_CHECK(!ccvb.inside({0, 20, -35})); - BOOST_CHECK(!ccvb.inside({20, 0, 35})); - BOOST_CHECK(!ccvb.inside({20, 0, -35})); + // outside in z + BOOST_CHECK(!ccvb.inside({0, 0, 35})); + BOOST_CHECK(!ccvb.inside({0, 0, -35})); + BOOST_CHECK(!ccvb.inside({0, 3, 35})); + BOOST_CHECK(!ccvb.inside({0, 3, -35})); + BOOST_CHECK(!ccvb.inside({3, 0, 35})); + BOOST_CHECK(!ccvb.inside({3, 0, -35})); + BOOST_CHECK(!ccvb.inside({0, 10, 35})); + BOOST_CHECK(!ccvb.inside({0, 10, -35})); + BOOST_CHECK(!ccvb.inside({10, 0, 35})); + BOOST_CHECK(!ccvb.inside({10, 0, -35})); + BOOST_CHECK(!ccvb.inside({0, 20, 35})); + BOOST_CHECK(!ccvb.inside({0, 20, -35})); + BOOST_CHECK(!ccvb.inside({20, 0, 35})); + BOOST_CHECK(!ccvb.inside({20, 0, -35})); - // in the choke point in z - BOOST_CHECK(!ccvb.inside({0, 0, 27})); - BOOST_CHECK(!ccvb.inside({0, 0, -27})); - BOOST_CHECK(!ccvb.inside({0, 3, 27})); - BOOST_CHECK(!ccvb.inside({0, 3, -27})); - BOOST_CHECK(!ccvb.inside({3, 0, 27})); - BOOST_CHECK(!ccvb.inside({3, 0, -27})); - BOOST_CHECK(ccvb.inside({0, 7, 27})); - BOOST_CHECK(ccvb.inside({0, 7, -27})); - BOOST_CHECK(ccvb.inside({7, 0, 27})); - BOOST_CHECK(ccvb.inside({7, 0, -27})); - BOOST_CHECK(ccvb.inside({0, 13, 27})); - BOOST_CHECK(ccvb.inside({0, 13, -27})); - BOOST_CHECK(ccvb.inside({13, 0, 27})); - BOOST_CHECK(ccvb.inside({13, 0, -27})); - BOOST_CHECK(!ccvb.inside({0, 17, 27})); - BOOST_CHECK(!ccvb.inside({0, 17, -27})); - BOOST_CHECK(!ccvb.inside({17, 0, 27})); - BOOST_CHECK(!ccvb.inside({17, 0, -27})); + // in the choke point in z + BOOST_CHECK(!ccvb.inside({0, 0, 27})); + BOOST_CHECK(!ccvb.inside({0, 0, -27})); + BOOST_CHECK(!ccvb.inside({0, 3, 27})); + BOOST_CHECK(!ccvb.inside({0, 3, -27})); + BOOST_CHECK(!ccvb.inside({3, 0, 27})); + BOOST_CHECK(!ccvb.inside({3, 0, -27})); + BOOST_CHECK(ccvb.inside({0, 7, 27})); + BOOST_CHECK(ccvb.inside({0, 7, -27})); + BOOST_CHECK(ccvb.inside({7, 0, 27})); + BOOST_CHECK(ccvb.inside({7, 0, -27})); + BOOST_CHECK(ccvb.inside({0, 13, 27})); + BOOST_CHECK(ccvb.inside({0, 13, -27})); + BOOST_CHECK(ccvb.inside({13, 0, 27})); + BOOST_CHECK(ccvb.inside({13, 0, -27})); + BOOST_CHECK(!ccvb.inside({0, 17, 27})); + BOOST_CHECK(!ccvb.inside({0, 17, -27})); + BOOST_CHECK(!ccvb.inside({17, 0, 27})); + BOOST_CHECK(!ccvb.inside({17, 0, -27})); - // right inside the choke point in z - BOOST_CHECK(!ccvb.inside({0, 0, 23})); - BOOST_CHECK(!ccvb.inside({0, 0, -23})); - BOOST_CHECK(!ccvb.inside({0, 3, 23})); - BOOST_CHECK(!ccvb.inside({0, 3, -23})); - BOOST_CHECK(!ccvb.inside({3, 0, 23})); - BOOST_CHECK(!ccvb.inside({3, 0, -23})); - BOOST_CHECK(!ccvb.inside({0, 7, 23})); - BOOST_CHECK(!ccvb.inside({0, 7, -23})); - BOOST_CHECK(!ccvb.inside({7, 0, 23})); - BOOST_CHECK(!ccvb.inside({7, 0, -23})); - BOOST_CHECK(ccvb.inside({0, 13, 23})); - BOOST_CHECK(ccvb.inside({0, 13, -23})); - BOOST_CHECK(ccvb.inside({13, 0, 23})); - BOOST_CHECK(ccvb.inside({13, 0, -23})); - BOOST_CHECK(!ccvb.inside({0, 17, 23})); - BOOST_CHECK(!ccvb.inside({0, 17, -23})); - BOOST_CHECK(!ccvb.inside({17, 0, 23})); - BOOST_CHECK(!ccvb.inside({17, 0, -23})); - } - BOOST_AUTO_TEST_SUITE_END() -} + // right inside the choke point in z + BOOST_CHECK(!ccvb.inside({0, 0, 23})); + BOOST_CHECK(!ccvb.inside({0, 0, -23})); + BOOST_CHECK(!ccvb.inside({0, 3, 23})); + BOOST_CHECK(!ccvb.inside({0, 3, -23})); + BOOST_CHECK(!ccvb.inside({3, 0, 23})); + BOOST_CHECK(!ccvb.inside({3, 0, -23})); + BOOST_CHECK(!ccvb.inside({0, 7, 23})); + BOOST_CHECK(!ccvb.inside({0, 7, -23})); + BOOST_CHECK(!ccvb.inside({7, 0, 23})); + BOOST_CHECK(!ccvb.inside({7, 0, -23})); + BOOST_CHECK(ccvb.inside({0, 13, 23})); + BOOST_CHECK(ccvb.inside({0, 13, -23})); + BOOST_CHECK(ccvb.inside({13, 0, 23})); + BOOST_CHECK(ccvb.inside({13, 0, -23})); + BOOST_CHECK(!ccvb.inside({0, 17, 23})); + BOOST_CHECK(!ccvb.inside({0, 17, -23})); + BOOST_CHECK(!ccvb.inside({17, 0, 23})); + BOOST_CHECK(!ccvb.inside({17, 0, -23})); } +BOOST_AUTO_TEST_SUITE_END() +} // namespace Test +} // namespace Acts diff --git a/Tests/Core/Geometry/CylinderLayerTests.cpp b/Tests/Core/Geometry/CylinderLayerTests.cpp index 169ca10a4320fe978a0bacfbe529fbdcdb7a5650..2dc297399f881802c53cac90f3c4a9880334a82f 100644 --- a/Tests/Core/Geometry/CylinderLayerTests.cpp +++ b/Tests/Core/Geometry/CylinderLayerTests.cpp @@ -34,78 +34,70 @@ namespace Acts { namespace Test { - // Create a test context - GeometryContext tgContext = GeometryContext(); +// Create a test context +GeometryContext tgContext = GeometryContext(); - namespace Layers { - BOOST_AUTO_TEST_SUITE(Layers) +namespace Layers { +BOOST_AUTO_TEST_SUITE(Layers) - /// Unit test for creating compliant/non-compliant CylinderLayer object - BOOST_AUTO_TEST_CASE(CylinderLayerConstruction) - { - // default constructor, copy and assignment are all deleted - // minimally need a Transform3D and a PlanarBounds object (e.g. - // CylinderBounds) to construct - Translation3D translation{0., 1., 2.}; - auto pTransform = std::make_shared<const Transform3D>(translation); - double radius(0.5), halfz(10.); - auto pCylinder = std::make_shared<const CylinderBounds>(radius, halfz); - auto pCylinderLayer = CylinderLayer::create(pTransform, pCylinder); - BOOST_CHECK_EQUAL(pCylinderLayer->layerType(), LayerType::passive); - // next level: need an array of Surfaces; - // bounds object, rectangle type - auto rBounds = std::make_shared<const RectangleBounds>(1., 1.); - /// Constructor with transform pointer - auto pNullTransform = std::make_shared<const Transform3D>(); - const std::vector<std::shared_ptr<const Surface>> aSurfaces{ - Surface::makeShared<PlaneSurface>(pNullTransform, rBounds), - Surface::makeShared<PlaneSurface>(pNullTransform, rBounds)}; - const double thickness(1.0); - auto pCylinderLayerFromSurfaces - = CylinderLayer::create(pTransform, pCylinder, nullptr); - BOOST_CHECK_EQUAL(pCylinderLayerFromSurfaces->layerType(), - LayerType::passive); - // construct with thickness: - auto pCylinderLayerWithThickness - = CylinderLayer::create(pTransform, pCylinder, nullptr, thickness); - CHECK_CLOSE_REL( - pCylinderLayerWithThickness->thickness(), thickness, 1e-6); - // with an approach descriptor... - std::unique_ptr<ApproachDescriptor> ad( - new GenericApproachDescriptor(aSurfaces)); - auto adPtr = ad.get(); - auto pCylinderLayerWithApproachDescriptor = CylinderLayer::create( - pTransform, pCylinder, nullptr, thickness, std::move(ad)); - BOOST_CHECK_EQUAL( - pCylinderLayerWithApproachDescriptor->approachDescriptor(), adPtr); - // with the layerType specified... - auto pCylinderLayerWithLayerType - = CylinderLayer::create(pTransform, - pCylinder, - nullptr, - thickness, - std::move(ad), - LayerType::passive); - BOOST_CHECK_EQUAL(pCylinderLayerWithLayerType->layerType(), - LayerType::passive); - } +/// Unit test for creating compliant/non-compliant CylinderLayer object +BOOST_AUTO_TEST_CASE(CylinderLayerConstruction) { + // default constructor, copy and assignment are all deleted + // minimally need a Transform3D and a PlanarBounds object (e.g. + // CylinderBounds) to construct + Translation3D translation{0., 1., 2.}; + auto pTransform = std::make_shared<const Transform3D>(translation); + double radius(0.5), halfz(10.); + auto pCylinder = std::make_shared<const CylinderBounds>(radius, halfz); + auto pCylinderLayer = CylinderLayer::create(pTransform, pCylinder); + BOOST_CHECK_EQUAL(pCylinderLayer->layerType(), LayerType::passive); + // next level: need an array of Surfaces; + // bounds object, rectangle type + auto rBounds = std::make_shared<const RectangleBounds>(1., 1.); + /// Constructor with transform pointer + auto pNullTransform = std::make_shared<const Transform3D>(); + const std::vector<std::shared_ptr<const Surface>> aSurfaces{ + Surface::makeShared<PlaneSurface>(pNullTransform, rBounds), + Surface::makeShared<PlaneSurface>(pNullTransform, rBounds)}; + const double thickness(1.0); + auto pCylinderLayerFromSurfaces = + CylinderLayer::create(pTransform, pCylinder, nullptr); + BOOST_CHECK_EQUAL(pCylinderLayerFromSurfaces->layerType(), + LayerType::passive); + // construct with thickness: + auto pCylinderLayerWithThickness = + CylinderLayer::create(pTransform, pCylinder, nullptr, thickness); + CHECK_CLOSE_REL(pCylinderLayerWithThickness->thickness(), thickness, 1e-6); + // with an approach descriptor... + std::unique_ptr<ApproachDescriptor> ad( + new GenericApproachDescriptor(aSurfaces)); + auto adPtr = ad.get(); + auto pCylinderLayerWithApproachDescriptor = CylinderLayer::create( + pTransform, pCylinder, nullptr, thickness, std::move(ad)); + BOOST_CHECK_EQUAL(pCylinderLayerWithApproachDescriptor->approachDescriptor(), + adPtr); + // with the layerType specified... + auto pCylinderLayerWithLayerType = + CylinderLayer::create(pTransform, pCylinder, nullptr, thickness, + std::move(ad), LayerType::passive); + BOOST_CHECK_EQUAL(pCylinderLayerWithLayerType->layerType(), + LayerType::passive); +} - /// Unit test for testing Layer properties - BOOST_AUTO_TEST_CASE( - CylinderLayerProperties /*, *utf::expected_failures(1)*/) - { - Translation3D translation{0., 1., 2.}; - auto pTransform = std::make_shared<const Transform3D>(translation); - double radius(0.5), halfz(10.); - auto pCylinder = std::make_shared<const CylinderBounds>(radius, halfz); - auto pCylinderLayer = CylinderLayer::create(pTransform, pCylinder); - // auto planeSurface = pCylinderLayer->surfaceRepresentation(); - BOOST_CHECK_EQUAL(pCylinderLayer->surfaceRepresentation().name(), - std::string("Acts::CylinderSurface")); - } +/// Unit test for testing Layer properties +BOOST_AUTO_TEST_CASE(CylinderLayerProperties /*, *utf::expected_failures(1)*/) { + Translation3D translation{0., 1., 2.}; + auto pTransform = std::make_shared<const Transform3D>(translation); + double radius(0.5), halfz(10.); + auto pCylinder = std::make_shared<const CylinderBounds>(radius, halfz); + auto pCylinderLayer = CylinderLayer::create(pTransform, pCylinder); + // auto planeSurface = pCylinderLayer->surfaceRepresentation(); + BOOST_CHECK_EQUAL(pCylinderLayer->surfaceRepresentation().name(), + std::string("Acts::CylinderSurface")); +} - BOOST_AUTO_TEST_SUITE_END() - } // namespace Layers +BOOST_AUTO_TEST_SUITE_END() +} // namespace Layers } // namespace Test } // namespace Acts diff --git a/Tests/Core/Geometry/CylinderVolumeBoundsTests.cpp b/Tests/Core/Geometry/CylinderVolumeBoundsTests.cpp index 2cf988d777ffde514dcd8d20fb89455340c37e6b..728810356d75f3ca8a7f6e6ea6e81cc3c8d87915 100644 --- a/Tests/Core/Geometry/CylinderVolumeBoundsTests.cpp +++ b/Tests/Core/Geometry/CylinderVolumeBoundsTests.cpp @@ -20,101 +20,85 @@ #include "Acts/Geometry/CylinderVolumeBounds.hpp" namespace bdata = boost::unit_test::data; -namespace tt = boost::test_tools; +namespace tt = boost::test_tools; namespace Acts { namespace Test { - BOOST_AUTO_TEST_SUITE(Volumes) +BOOST_AUTO_TEST_SUITE(Volumes) - /// Unit test for testing the decomposeToSurfaces() function - BOOST_DATA_TEST_CASE(CylinderVolumeBounds_decomposeToSurfaces, - bdata::random(-M_PI, M_PI) ^ bdata::random(-M_PI, M_PI) - ^ bdata::random(-M_PI, M_PI) - ^ bdata::random(-10., 10.) - ^ bdata::random(-10., 10.) - ^ bdata::random(-10., 10.) - ^ bdata::xrange(100), - alpha, - beta, - gamma, - posX, - posY, - posZ, - index) - { - (void)index; +/// Unit test for testing the decomposeToSurfaces() function +BOOST_DATA_TEST_CASE(CylinderVolumeBounds_decomposeToSurfaces, + bdata::random(-M_PI, M_PI) ^ bdata::random(-M_PI, M_PI) ^ + bdata::random(-M_PI, M_PI) ^ bdata::random(-10., 10.) ^ + bdata::random(-10., 10.) ^ bdata::random(-10., 10.) ^ + bdata::xrange(100), + alpha, beta, gamma, posX, posY, posZ, index) { + (void)index; - // Create a test context - GeometryContext tgContext = GeometryContext(); + // Create a test context + GeometryContext tgContext = GeometryContext(); - // position of volume - const Vector3D pos(posX, posY, posZ); - // rotation around x axis - AngleAxis3D rotX(alpha, Vector3D(1., 0., 0.)); - // rotation around y axis - AngleAxis3D rotY(beta, Vector3D(0., 1., 0.)); - // rotation around z axis - AngleAxis3D rotZ(gamma, Vector3D(0., 0., 1.)); + // position of volume + const Vector3D pos(posX, posY, posZ); + // rotation around x axis + AngleAxis3D rotX(alpha, Vector3D(1., 0., 0.)); + // rotation around y axis + AngleAxis3D rotY(beta, Vector3D(0., 1., 0.)); + // rotation around z axis + AngleAxis3D rotZ(gamma, Vector3D(0., 0., 1.)); - // create the cylinder bounds - CylinderVolumeBounds cylBounds(1., 2., 3.); - // create the transformation matrix - auto mutableTransformPtr - = std::make_shared<Transform3D>(Translation3D(pos)); - (*mutableTransformPtr) *= rotZ; - (*mutableTransformPtr) *= rotY; - (*mutableTransformPtr) *= rotX; - auto transformPtr - = std::const_pointer_cast<const Transform3D>(mutableTransformPtr); - // get the boundary surfaces - std::vector<std::shared_ptr<const Acts::Surface>> boundarySurfaces - = cylBounds.decomposeToSurfaces(transformPtr.get()); - // Test + // create the cylinder bounds + CylinderVolumeBounds cylBounds(1., 2., 3.); + // create the transformation matrix + auto mutableTransformPtr = std::make_shared<Transform3D>(Translation3D(pos)); + (*mutableTransformPtr) *= rotZ; + (*mutableTransformPtr) *= rotY; + (*mutableTransformPtr) *= rotX; + auto transformPtr = + std::const_pointer_cast<const Transform3D>(mutableTransformPtr); + // get the boundary surfaces + std::vector<std::shared_ptr<const Acts::Surface>> boundarySurfaces = + cylBounds.decomposeToSurfaces(transformPtr.get()); + // Test - // check if difference is halfZ - sign and direction independent - CHECK_CLOSE_REL((pos - boundarySurfaces.at(0)->center(tgContext)).norm(), - cylBounds.halflengthZ(), - 1e-12); - CHECK_CLOSE_REL((pos - boundarySurfaces.at(1)->center(tgContext)).norm(), - cylBounds.halflengthZ(), - 1e-12); - // transform to local - double posDiscPosZ - = (transformPtr->inverse() * boundarySurfaces.at(1)->center(tgContext)) - .z(); - double centerPosZ = (transformPtr->inverse() * pos).z(); - double negDiscPosZ - = (transformPtr->inverse() * boundarySurfaces.at(0)->center(tgContext)) - .z(); - // check if center of disc boundaries lies in the middle in z - BOOST_CHECK_LT(centerPosZ, posDiscPosZ); - BOOST_CHECK_GT(centerPosZ, negDiscPosZ); - // check positions of disc boundarysurfaces - // checks for zero value. double precision value is not exact. - CHECK_CLOSE_ABS(negDiscPosZ + cylBounds.halflengthZ(), centerPosZ, 1e-12); - CHECK_CLOSE_ABS(posDiscPosZ - cylBounds.halflengthZ(), centerPosZ, 1e-12); - // orientation of disc surfaces - // positive disc durface should point in positive direction in the frame of - // the volume - CHECK_CLOSE_REL( - transformPtr->rotation().col(2).dot( - boundarySurfaces.at(1)->normal(tgContext, Acts::Vector2D(0., 0.))), - 1., - 1e-12); - // negative disc durface should point in negative direction in the frame of - // the volume - CHECK_CLOSE_REL( - transformPtr->rotation().col(2).dot( - boundarySurfaces.at(0)->normal(tgContext, Acts::Vector2D(0., 0.))), - -1., - 1e-12); - // test in r - CHECK_CLOSE_REL(boundarySurfaces.at(3)->center(tgContext), pos, 1e-12); - CHECK_CLOSE_REL(boundarySurfaces.at(2)->center(tgContext), pos, 1e-12); - } + // check if difference is halfZ - sign and direction independent + CHECK_CLOSE_REL((pos - boundarySurfaces.at(0)->center(tgContext)).norm(), + cylBounds.halflengthZ(), 1e-12); + CHECK_CLOSE_REL((pos - boundarySurfaces.at(1)->center(tgContext)).norm(), + cylBounds.halflengthZ(), 1e-12); + // transform to local + double posDiscPosZ = + (transformPtr->inverse() * boundarySurfaces.at(1)->center(tgContext)).z(); + double centerPosZ = (transformPtr->inverse() * pos).z(); + double negDiscPosZ = + (transformPtr->inverse() * boundarySurfaces.at(0)->center(tgContext)).z(); + // check if center of disc boundaries lies in the middle in z + BOOST_CHECK_LT(centerPosZ, posDiscPosZ); + BOOST_CHECK_GT(centerPosZ, negDiscPosZ); + // check positions of disc boundarysurfaces + // checks for zero value. double precision value is not exact. + CHECK_CLOSE_ABS(negDiscPosZ + cylBounds.halflengthZ(), centerPosZ, 1e-12); + CHECK_CLOSE_ABS(posDiscPosZ - cylBounds.halflengthZ(), centerPosZ, 1e-12); + // orientation of disc surfaces + // positive disc durface should point in positive direction in the frame of + // the volume + CHECK_CLOSE_REL( + transformPtr->rotation().col(2).dot( + boundarySurfaces.at(1)->normal(tgContext, Acts::Vector2D(0., 0.))), + 1., 1e-12); + // negative disc durface should point in negative direction in the frame of + // the volume + CHECK_CLOSE_REL( + transformPtr->rotation().col(2).dot( + boundarySurfaces.at(0)->normal(tgContext, Acts::Vector2D(0., 0.))), + -1., 1e-12); + // test in r + CHECK_CLOSE_REL(boundarySurfaces.at(3)->center(tgContext), pos, 1e-12); + CHECK_CLOSE_REL(boundarySurfaces.at(2)->center(tgContext), pos, 1e-12); +} - BOOST_AUTO_TEST_SUITE_END() +BOOST_AUTO_TEST_SUITE_END() } // namespace Test diff --git a/Tests/Core/Geometry/CylinderVolumeBuilderTests.cpp b/Tests/Core/Geometry/CylinderVolumeBuilderTests.cpp index e0c43765344b23cf1aa96d344994f90618f63b18..cdc9a6b32ab29b5059187fa98ece938a208bc32e 100644 --- a/Tests/Core/Geometry/CylinderVolumeBuilderTests.cpp +++ b/Tests/Core/Geometry/CylinderVolumeBuilderTests.cpp @@ -15,339 +15,313 @@ #include "Acts/Utilities/Definitions.hpp" namespace bdata = boost::unit_test::data; -namespace tt = boost::test_tools; +namespace tt = boost::test_tools; namespace Acts { namespace Test { - /// Unit test for testing the wraps() function of the CylinderVolumeBuilder - BOOST_DATA_TEST_CASE(CylinderVolumeBuilder_wraps, - bdata::random(-11., -15.) ^ bdata::random(11., 15.) - ^ bdata::random(-10., 10.) - ^ bdata::random(0., 4.) - ^ bdata::random(11., 15.) - ^ bdata::random(10., 15.) - ^ bdata::xrange(100), - left, - right, - central, - inner, - outer, - length, - index) - { - (void)index; - // inner volume - VolumeConfig innerConfig; - innerConfig.rMin = 0.; - innerConfig.rMax = 10.; - innerConfig.zMin = -10.; - innerConfig.zMax = 10.; - - // volume to the left of the inner volume - VolumeConfig outerConfig1; - outerConfig1.rMin = inner; - outerConfig1.rMax = inner + 5.; - outerConfig1.zMin = left - 5.; - outerConfig1.zMax = left; - - // volume to the right of the inner volume - VolumeConfig outerConfig2; - outerConfig2.rMin = inner; - outerConfig2.rMax = inner + 5.; - outerConfig2.zMin = right; - outerConfig2.zMax = right + 5.; - - // volume around the inner volume - VolumeConfig outerConfig3; - outerConfig3.rMin = outer; - outerConfig3.rMax = outer + 5.; - outerConfig3.zMin = central - 5.; - outerConfig3.zMax = central + 5.; - - // volume inside the inner volume - VolumeConfig outerConfig4; - outerConfig4.rMin = inner; - outerConfig4.rMax = inner + 5.; - outerConfig4.zMin = central - 5.; - outerConfig4.zMax = central + 5.; - - // volume around the inner volume config - VolumeConfig outerConfig5; - outerConfig5.rMin = outer; - outerConfig5.rMax = outer + 5.; - outerConfig5.zMin = -length; - outerConfig5.zMax = length; - - // volume around inner volume with same z boundaries - VolumeConfig outerConfig6; - outerConfig6.rMin = outer; - outerConfig6.rMax = outer + 5.; - outerConfig6.zMin = -10.; - outerConfig6.zMax = 10.; - - // check if first volume wraps around the inner volume (wrapping in z) - BOOST_CHECK(outerConfig1.wraps(innerConfig)); - // check if second volume wraps around the inner volume (wrapping in z) - BOOST_CHECK(outerConfig2.wraps(innerConfig)); - // check if third volume wraps around the inner volume (wrapping in r) - BOOST_CHECK(outerConfig3.wraps(innerConfig)); - // check if volume at inside the inner volume can not be wrapped - BOOST_CHECK(!outerConfig4.wraps(innerConfig)); - // check if outside volume can not be wrapped around inside volume - BOOST_CHECK(!innerConfig.wraps(outerConfig3)); - // check if outside volume containes inside volume - BOOST_CHECK(outerConfig5.wraps(innerConfig)); - // check if inside volume is not contained by outside volume - BOOST_CHECK(!innerConfig.wraps(outerConfig5)); - // check if outside volume wraps around the inside volume - BOOST_CHECK(outerConfig6.wraps(innerConfig)); - } - - /// Unit test for testing the contains(), containsInR() and containsInZ() - /// function of the CylinderVolumeBuilder - BOOST_DATA_TEST_CASE(CylinderVolumeBuilder_containes, - bdata::random(-11., -15.) ^ bdata::random(11., 15.) - ^ bdata::random(-10., 10.) - ^ bdata::random(0., 4.) - ^ bdata::random(10., 15.) - ^ bdata::random(10., 15.) - ^ bdata::xrange(100), - left, - right, - central, - inner, - outer, - length, - index) - { - (void)index; - // inner volume - VolumeConfig innerConfig; - innerConfig.rMin = 0.; - innerConfig.rMax = 10.; - innerConfig.zMin = -10.; - innerConfig.zMax = 10.; - - // volume to the left of the inner volume - VolumeConfig outerConfig1; - outerConfig1.rMin = inner; - outerConfig1.rMax = inner + 5.; - outerConfig1.zMin = left - 5.; - outerConfig1.zMax = left; - - // volume to the right of the inner volume - VolumeConfig outerConfig2; - outerConfig2.rMin = inner; - outerConfig2.rMax = inner + 5.; - outerConfig2.zMin = right; - outerConfig2.zMax = right + 5.; - - // volume around the inner volume in r - VolumeConfig outerConfig3; - outerConfig3.rMin = outer; - outerConfig3.rMax = outer + 5.; - outerConfig3.zMin = central - 5.; - outerConfig3.zMax = central + 5.; - - // volume inside the inner volume - VolumeConfig outerConfig4; - outerConfig4.rMin = inner; - outerConfig4.rMax = inner + 5.; - outerConfig4.zMin = central - 5.; - outerConfig4.zMax = central + 5.; - - // volume around the inner volume config - VolumeConfig outerConfig5; - outerConfig5.rMin = outer; - outerConfig5.rMax = outer + 5.; - outerConfig5.zMin = -length; - outerConfig5.zMax = length; - - // volume around inner volume with same z boundaries - VolumeConfig outerConfig6; - outerConfig6.rMin = outer; - outerConfig6.rMax = outer + 5.; - outerConfig6.zMin = -10.; - outerConfig6.zMax = 10.; - - // volume inside the inner volume config in z - VolumeConfig innerConfig1; - innerConfig1.rMin = outer; - innerConfig1.rMax = outer + 5.; - innerConfig1.zMin = inner - 5.; - innerConfig1.zMax = inner + 5.; - - // check if first volume wraps around the inner volume (wrapping in z) - BOOST_CHECK(!outerConfig1.contains(innerConfig)); - // check if second volume wraps around the inner volume (wrapping in z) - BOOST_CHECK(!outerConfig2.contains(innerConfig)); - // check if volume at inside the inner volume can not be wrapped - BOOST_CHECK(!outerConfig4.contains(innerConfig)); - // check if outside volume can not be wrapped around inside volume - BOOST_CHECK(!innerConfig.contains(outerConfig3)); - // check if outside volume containes inside volume - BOOST_CHECK(outerConfig5.contains(innerConfig)); - // check if inside volume is not contained by outside volume - BOOST_CHECK(!innerConfig.contains(outerConfig5)); - // check if inside volume is not contained by outside volume - BOOST_CHECK(!outerConfig6.contains(innerConfig)); - - // containment checks in r and z for volumes which either contain in r or z - BOOST_CHECK(innerConfig.containsInZ(innerConfig1)); - BOOST_CHECK(!innerConfig.containsInR(innerConfig1)); - BOOST_CHECK(innerConfig1.containsInR(innerConfig)); - BOOST_CHECK(!innerConfig1.containsInZ(innerConfig)); - } - - /// Unit test for testing the coverlapsInR() - /// function of the CylinderVolumeBuilder - BOOST_DATA_TEST_CASE(CylinderVolumeBuilder_overlapsInR, - bdata::random(0., 4.) ^ bdata::random(11., 15.) - ^ bdata::xrange(100), - inner, - outer, - index) - { - (void)index; - // reference volume - VolumeConfig Config0; - Config0.rMin = 5.; - Config0.rMax = 10.; - Config0.zMin = -10.; - Config0.zMax = 10.; - Config0.present = true; - - // volume inside volume0 - VolumeConfig Config1; - Config1.rMin = 0.; - Config1.rMax = inner; - Config1.zMin = -10.; - Config1.zMax = 10.; - - // volume outside volume0 - VolumeConfig Config2; - Config2.rMin = outer; - Config2.rMax = outer + 5.; - Config2.zMin = -10.; - Config2.zMax = 10.; - - // volume overlapping with rMin - VolumeConfig Config3; - Config3.rMin = inner + 5; - Config3.rMax = outer + 5.; - Config3.zMin = -10.; - Config3.zMax = 10.; - - // volume overlapping with rMax - VolumeConfig Config4; - Config4.rMin = inner; - Config4.rMax = inner + 5.; - Config4.zMin = -10.; - Config4.zMax = 10.; - - // volume overlapping with rMin and rMax - VolumeConfig Config5; - Config5.rMin = 5.; - Config5.rMax = inner + 5.; - Config5.zMin = -10.; - Config5.zMax = 10.; - - // volume does not overlap with volume completely inside - BOOST_CHECK(!Config0.overlapsInR(Config1)); - // volume does not overlap with volume completely outside - BOOST_CHECK(!Config0.overlapsInR(Config2)); - // volume overlaps with rMin - BOOST_CHECK(Config0.overlapsInR(Config3)); - // volume overlaps with rMax - BOOST_CHECK(Config0.overlapsInR(Config4)); - // volume overlaps with rMin and rMax - BOOST_CHECK(Config0.overlapsInR(Config5)); - } - - /// Unit test for testing the coverlapsInZ() - /// function of the CylinderVolumeBuilder - BOOST_DATA_TEST_CASE(CylinderVolumeBuilder_overlapsInZ, - bdata::random(-11., -15.) ^ bdata::random(11., 15.) - ^ bdata::random(0., 4.) - ^ bdata::xrange(100), - left, - right, - inner, - index) - { - (void)index; - // inner volume - VolumeConfig Config0; - Config0.rMin = 0.; - Config0.rMax = 10.; - Config0.zMin = -10.; - Config0.zMax = 10.; - Config0.present = true; - - // volume to the left of volume0 - VolumeConfig Config1; - Config1.rMin = 10.; - Config1.rMax = 20.; - Config1.zMin = left - 5.; - Config1.zMax = left; - - // volume to the right of volume0 - VolumeConfig Config2; - Config2.rMin = 10.; - Config2.rMax = 20.; - Config2.zMin = right; - Config2.zMax = right + 5.; - - // volume around volume0 with same z boundaries - VolumeConfig Config3; - Config3.rMin = 10.; - Config3.rMax = 20.; - Config3.zMin = -10.; - Config3.zMax = 10.; - - // volume inside volume0 config in z - VolumeConfig Config4; - Config4.rMin = 10.; - Config4.rMax = 20.; - Config4.zMin = inner - 5.; - Config4.zMax = inner + 5.; - - // volume around volume0 config in z - VolumeConfig Config5; - Config5.rMin = 10.; - Config5.rMax = 20.; - Config5.zMin = left; - Config5.zMax = right; - - // volume overlapping on the left - VolumeConfig Config6; - Config6.rMin = 10.; - Config6.rMax = 20.; - Config6.zMin = left; - Config6.zMax = left + 10.; - - // volume overlapping on the right - VolumeConfig Config7; - Config7.rMin = 10.; - Config7.rMax = 20.; - Config7.zMin = right - 10.; - Config7.zMax = right; - - // volume to the right and left do not overlap - BOOST_CHECK(!Config0.overlapsInZ(Config1)); - BOOST_CHECK(!Config0.overlapsInZ(Config2)); - // volume with same boundaries overlaps - BOOST_CHECK(Config0.overlapsInZ(Config3)); - // inside volume overlaps - BOOST_CHECK(Config0.overlapsInZ(Config4)); - // volume around overlaps - BOOST_CHECK(Config0.overlapsInZ(Config5)); - // volume overlaps on the sides - BOOST_CHECK(Config0.overlapsInZ(Config6)); - BOOST_CHECK(Config0.overlapsInZ(Config7)); - } +/// Unit test for testing the wraps() function of the CylinderVolumeBuilder +BOOST_DATA_TEST_CASE(CylinderVolumeBuilder_wraps, + bdata::random(-11., -15.) ^ bdata::random(11., 15.) ^ + bdata::random(-10., 10.) ^ bdata::random(0., 4.) ^ + bdata::random(11., 15.) ^ bdata::random(10., 15.) ^ + bdata::xrange(100), + left, right, central, inner, outer, length, index) { + (void)index; + // inner volume + VolumeConfig innerConfig; + innerConfig.rMin = 0.; + innerConfig.rMax = 10.; + innerConfig.zMin = -10.; + innerConfig.zMax = 10.; + + // volume to the left of the inner volume + VolumeConfig outerConfig1; + outerConfig1.rMin = inner; + outerConfig1.rMax = inner + 5.; + outerConfig1.zMin = left - 5.; + outerConfig1.zMax = left; + + // volume to the right of the inner volume + VolumeConfig outerConfig2; + outerConfig2.rMin = inner; + outerConfig2.rMax = inner + 5.; + outerConfig2.zMin = right; + outerConfig2.zMax = right + 5.; + + // volume around the inner volume + VolumeConfig outerConfig3; + outerConfig3.rMin = outer; + outerConfig3.rMax = outer + 5.; + outerConfig3.zMin = central - 5.; + outerConfig3.zMax = central + 5.; + + // volume inside the inner volume + VolumeConfig outerConfig4; + outerConfig4.rMin = inner; + outerConfig4.rMax = inner + 5.; + outerConfig4.zMin = central - 5.; + outerConfig4.zMax = central + 5.; + + // volume around the inner volume config + VolumeConfig outerConfig5; + outerConfig5.rMin = outer; + outerConfig5.rMax = outer + 5.; + outerConfig5.zMin = -length; + outerConfig5.zMax = length; + + // volume around inner volume with same z boundaries + VolumeConfig outerConfig6; + outerConfig6.rMin = outer; + outerConfig6.rMax = outer + 5.; + outerConfig6.zMin = -10.; + outerConfig6.zMax = 10.; + + // check if first volume wraps around the inner volume (wrapping in z) + BOOST_CHECK(outerConfig1.wraps(innerConfig)); + // check if second volume wraps around the inner volume (wrapping in z) + BOOST_CHECK(outerConfig2.wraps(innerConfig)); + // check if third volume wraps around the inner volume (wrapping in r) + BOOST_CHECK(outerConfig3.wraps(innerConfig)); + // check if volume at inside the inner volume can not be wrapped + BOOST_CHECK(!outerConfig4.wraps(innerConfig)); + // check if outside volume can not be wrapped around inside volume + BOOST_CHECK(!innerConfig.wraps(outerConfig3)); + // check if outside volume containes inside volume + BOOST_CHECK(outerConfig5.wraps(innerConfig)); + // check if inside volume is not contained by outside volume + BOOST_CHECK(!innerConfig.wraps(outerConfig5)); + // check if outside volume wraps around the inside volume + BOOST_CHECK(outerConfig6.wraps(innerConfig)); +} + +/// Unit test for testing the contains(), containsInR() and containsInZ() +/// function of the CylinderVolumeBuilder +BOOST_DATA_TEST_CASE(CylinderVolumeBuilder_containes, + bdata::random(-11., -15.) ^ bdata::random(11., 15.) ^ + bdata::random(-10., 10.) ^ bdata::random(0., 4.) ^ + bdata::random(10., 15.) ^ bdata::random(10., 15.) ^ + bdata::xrange(100), + left, right, central, inner, outer, length, index) { + (void)index; + // inner volume + VolumeConfig innerConfig; + innerConfig.rMin = 0.; + innerConfig.rMax = 10.; + innerConfig.zMin = -10.; + innerConfig.zMax = 10.; + + // volume to the left of the inner volume + VolumeConfig outerConfig1; + outerConfig1.rMin = inner; + outerConfig1.rMax = inner + 5.; + outerConfig1.zMin = left - 5.; + outerConfig1.zMax = left; + + // volume to the right of the inner volume + VolumeConfig outerConfig2; + outerConfig2.rMin = inner; + outerConfig2.rMax = inner + 5.; + outerConfig2.zMin = right; + outerConfig2.zMax = right + 5.; + + // volume around the inner volume in r + VolumeConfig outerConfig3; + outerConfig3.rMin = outer; + outerConfig3.rMax = outer + 5.; + outerConfig3.zMin = central - 5.; + outerConfig3.zMax = central + 5.; + + // volume inside the inner volume + VolumeConfig outerConfig4; + outerConfig4.rMin = inner; + outerConfig4.rMax = inner + 5.; + outerConfig4.zMin = central - 5.; + outerConfig4.zMax = central + 5.; + + // volume around the inner volume config + VolumeConfig outerConfig5; + outerConfig5.rMin = outer; + outerConfig5.rMax = outer + 5.; + outerConfig5.zMin = -length; + outerConfig5.zMax = length; + + // volume around inner volume with same z boundaries + VolumeConfig outerConfig6; + outerConfig6.rMin = outer; + outerConfig6.rMax = outer + 5.; + outerConfig6.zMin = -10.; + outerConfig6.zMax = 10.; + + // volume inside the inner volume config in z + VolumeConfig innerConfig1; + innerConfig1.rMin = outer; + innerConfig1.rMax = outer + 5.; + innerConfig1.zMin = inner - 5.; + innerConfig1.zMax = inner + 5.; + + // check if first volume wraps around the inner volume (wrapping in z) + BOOST_CHECK(!outerConfig1.contains(innerConfig)); + // check if second volume wraps around the inner volume (wrapping in z) + BOOST_CHECK(!outerConfig2.contains(innerConfig)); + // check if volume at inside the inner volume can not be wrapped + BOOST_CHECK(!outerConfig4.contains(innerConfig)); + // check if outside volume can not be wrapped around inside volume + BOOST_CHECK(!innerConfig.contains(outerConfig3)); + // check if outside volume containes inside volume + BOOST_CHECK(outerConfig5.contains(innerConfig)); + // check if inside volume is not contained by outside volume + BOOST_CHECK(!innerConfig.contains(outerConfig5)); + // check if inside volume is not contained by outside volume + BOOST_CHECK(!outerConfig6.contains(innerConfig)); + + // containment checks in r and z for volumes which either contain in r or z + BOOST_CHECK(innerConfig.containsInZ(innerConfig1)); + BOOST_CHECK(!innerConfig.containsInR(innerConfig1)); + BOOST_CHECK(innerConfig1.containsInR(innerConfig)); + BOOST_CHECK(!innerConfig1.containsInZ(innerConfig)); +} + +/// Unit test for testing the coverlapsInR() +/// function of the CylinderVolumeBuilder +BOOST_DATA_TEST_CASE(CylinderVolumeBuilder_overlapsInR, + bdata::random(0., 4.) ^ bdata::random(11., 15.) ^ + bdata::xrange(100), + inner, outer, index) { + (void)index; + // reference volume + VolumeConfig Config0; + Config0.rMin = 5.; + Config0.rMax = 10.; + Config0.zMin = -10.; + Config0.zMax = 10.; + Config0.present = true; + + // volume inside volume0 + VolumeConfig Config1; + Config1.rMin = 0.; + Config1.rMax = inner; + Config1.zMin = -10.; + Config1.zMax = 10.; + + // volume outside volume0 + VolumeConfig Config2; + Config2.rMin = outer; + Config2.rMax = outer + 5.; + Config2.zMin = -10.; + Config2.zMax = 10.; + + // volume overlapping with rMin + VolumeConfig Config3; + Config3.rMin = inner + 5; + Config3.rMax = outer + 5.; + Config3.zMin = -10.; + Config3.zMax = 10.; + + // volume overlapping with rMax + VolumeConfig Config4; + Config4.rMin = inner; + Config4.rMax = inner + 5.; + Config4.zMin = -10.; + Config4.zMax = 10.; + + // volume overlapping with rMin and rMax + VolumeConfig Config5; + Config5.rMin = 5.; + Config5.rMax = inner + 5.; + Config5.zMin = -10.; + Config5.zMax = 10.; + + // volume does not overlap with volume completely inside + BOOST_CHECK(!Config0.overlapsInR(Config1)); + // volume does not overlap with volume completely outside + BOOST_CHECK(!Config0.overlapsInR(Config2)); + // volume overlaps with rMin + BOOST_CHECK(Config0.overlapsInR(Config3)); + // volume overlaps with rMax + BOOST_CHECK(Config0.overlapsInR(Config4)); + // volume overlaps with rMin and rMax + BOOST_CHECK(Config0.overlapsInR(Config5)); +} + +/// Unit test for testing the coverlapsInZ() +/// function of the CylinderVolumeBuilder +BOOST_DATA_TEST_CASE(CylinderVolumeBuilder_overlapsInZ, + bdata::random(-11., -15.) ^ bdata::random(11., 15.) ^ + bdata::random(0., 4.) ^ bdata::xrange(100), + left, right, inner, index) { + (void)index; + // inner volume + VolumeConfig Config0; + Config0.rMin = 0.; + Config0.rMax = 10.; + Config0.zMin = -10.; + Config0.zMax = 10.; + Config0.present = true; + + // volume to the left of volume0 + VolumeConfig Config1; + Config1.rMin = 10.; + Config1.rMax = 20.; + Config1.zMin = left - 5.; + Config1.zMax = left; + + // volume to the right of volume0 + VolumeConfig Config2; + Config2.rMin = 10.; + Config2.rMax = 20.; + Config2.zMin = right; + Config2.zMax = right + 5.; + + // volume around volume0 with same z boundaries + VolumeConfig Config3; + Config3.rMin = 10.; + Config3.rMax = 20.; + Config3.zMin = -10.; + Config3.zMax = 10.; + + // volume inside volume0 config in z + VolumeConfig Config4; + Config4.rMin = 10.; + Config4.rMax = 20.; + Config4.zMin = inner - 5.; + Config4.zMax = inner + 5.; + + // volume around volume0 config in z + VolumeConfig Config5; + Config5.rMin = 10.; + Config5.rMax = 20.; + Config5.zMin = left; + Config5.zMax = right; + + // volume overlapping on the left + VolumeConfig Config6; + Config6.rMin = 10.; + Config6.rMax = 20.; + Config6.zMin = left; + Config6.zMax = left + 10.; + + // volume overlapping on the right + VolumeConfig Config7; + Config7.rMin = 10.; + Config7.rMax = 20.; + Config7.zMin = right - 10.; + Config7.zMax = right; + + // volume to the right and left do not overlap + BOOST_CHECK(!Config0.overlapsInZ(Config1)); + BOOST_CHECK(!Config0.overlapsInZ(Config2)); + // volume with same boundaries overlaps + BOOST_CHECK(Config0.overlapsInZ(Config3)); + // inside volume overlaps + BOOST_CHECK(Config0.overlapsInZ(Config4)); + // volume around overlaps + BOOST_CHECK(Config0.overlapsInZ(Config5)); + // volume overlaps on the sides + BOOST_CHECK(Config0.overlapsInZ(Config6)); + BOOST_CHECK(Config0.overlapsInZ(Config7)); +} } // namespace Test diff --git a/Tests/Core/Geometry/DiscLayerTests.cpp b/Tests/Core/Geometry/DiscLayerTests.cpp index 395574ce8f1670f0712ec62f7d2ed3db770925d3..339c3fcc27fb6152a3927159fd3074d1ca783112 100644 --- a/Tests/Core/Geometry/DiscLayerTests.cpp +++ b/Tests/Core/Geometry/DiscLayerTests.cpp @@ -35,75 +35,66 @@ namespace Acts { namespace Test { - // Create a test context - GeometryContext tgContext = GeometryContext(); +// Create a test context +GeometryContext tgContext = GeometryContext(); - namespace Layers { - BOOST_AUTO_TEST_SUITE(Layers) +namespace Layers { +BOOST_AUTO_TEST_SUITE(Layers) - /// Unit test for creating compliant/non-compliant DiscLayer object - BOOST_AUTO_TEST_CASE(DiscLayerConstruction) - { - // default constructor, copy and assignment are all deleted - // minimally need a Transform3D and a PlanarBounds object (e.g. - // RadialBounds) to construct - Translation3D translation{0., 1., 2.}; - auto pTransform = std::make_shared<const Transform3D>(translation); - const double minRad(10.), maxRad(5.); // 20 x 10 disc - auto pDisc = std::make_shared<const RadialBounds>(minRad, maxRad); - auto pDiscLayer = DiscLayer::create(pTransform, pDisc); - BOOST_CHECK_EQUAL(pDiscLayer->layerType(), LayerType::passive); - // next level: need an array of Surfaces; - // bounds object, rectangle type - auto rBounds = std::make_shared<const RectangleBounds>(1., 1.); - /// Constructor with transform pointer - auto pNullTransform = std::make_shared<const Transform3D>(); - const std::vector<std::shared_ptr<const Surface>> aSurfaces{ - Surface::makeShared<PlaneSurface>(pNullTransform, rBounds), - Surface::makeShared<PlaneSurface>(pNullTransform, rBounds)}; - const double thickness(1.0); - auto pDiscLayerFromSurfaces - = DiscLayer::create(pTransform, pDisc, nullptr); - BOOST_CHECK_EQUAL(pDiscLayerFromSurfaces->layerType(), - LayerType::passive); - // construct with thickness: - auto pDiscLayerWithThickness - = DiscLayer::create(pTransform, pDisc, nullptr, thickness); - BOOST_CHECK_EQUAL(pDiscLayerWithThickness->thickness(), thickness); - // with an approach descriptor... - std::unique_ptr<ApproachDescriptor> ad( - new GenericApproachDescriptor(aSurfaces)); - auto adPtr = ad.get(); - auto pDiscLayerWithApproachDescriptor = DiscLayer::create( - pTransform, pDisc, nullptr, thickness, std::move(ad)); - BOOST_CHECK_EQUAL(pDiscLayerWithApproachDescriptor->approachDescriptor(), - adPtr); - // with the layerType specified... - auto pDiscLayerWithLayerType = DiscLayer::create(pTransform, - pDisc, - nullptr, - thickness, - std::move(ad), - LayerType::passive); - BOOST_CHECK_EQUAL(pDiscLayerWithLayerType->layerType(), - LayerType::passive); - } +/// Unit test for creating compliant/non-compliant DiscLayer object +BOOST_AUTO_TEST_CASE(DiscLayerConstruction) { + // default constructor, copy and assignment are all deleted + // minimally need a Transform3D and a PlanarBounds object (e.g. + // RadialBounds) to construct + Translation3D translation{0., 1., 2.}; + auto pTransform = std::make_shared<const Transform3D>(translation); + const double minRad(10.), maxRad(5.); // 20 x 10 disc + auto pDisc = std::make_shared<const RadialBounds>(minRad, maxRad); + auto pDiscLayer = DiscLayer::create(pTransform, pDisc); + BOOST_CHECK_EQUAL(pDiscLayer->layerType(), LayerType::passive); + // next level: need an array of Surfaces; + // bounds object, rectangle type + auto rBounds = std::make_shared<const RectangleBounds>(1., 1.); + /// Constructor with transform pointer + auto pNullTransform = std::make_shared<const Transform3D>(); + const std::vector<std::shared_ptr<const Surface>> aSurfaces{ + Surface::makeShared<PlaneSurface>(pNullTransform, rBounds), + Surface::makeShared<PlaneSurface>(pNullTransform, rBounds)}; + const double thickness(1.0); + auto pDiscLayerFromSurfaces = DiscLayer::create(pTransform, pDisc, nullptr); + BOOST_CHECK_EQUAL(pDiscLayerFromSurfaces->layerType(), LayerType::passive); + // construct with thickness: + auto pDiscLayerWithThickness = + DiscLayer::create(pTransform, pDisc, nullptr, thickness); + BOOST_CHECK_EQUAL(pDiscLayerWithThickness->thickness(), thickness); + // with an approach descriptor... + std::unique_ptr<ApproachDescriptor> ad( + new GenericApproachDescriptor(aSurfaces)); + auto adPtr = ad.get(); + auto pDiscLayerWithApproachDescriptor = + DiscLayer::create(pTransform, pDisc, nullptr, thickness, std::move(ad)); + BOOST_CHECK_EQUAL(pDiscLayerWithApproachDescriptor->approachDescriptor(), + adPtr); + // with the layerType specified... + auto pDiscLayerWithLayerType = DiscLayer::create( + pTransform, pDisc, nullptr, thickness, std::move(ad), LayerType::passive); + BOOST_CHECK_EQUAL(pDiscLayerWithLayerType->layerType(), LayerType::passive); +} - /// Unit test for testing Layer properties - BOOST_AUTO_TEST_CASE(DiscLayerProperties /*, *utf::expected_failures(1)*/) - { - Translation3D translation{0., 1., 2.}; - auto pTransform = std::make_shared<const Transform3D>(translation); - const double minRad(10.), maxRad(5.); // 20 x 10 disc - auto pDisc = std::make_shared<const RadialBounds>(minRad, maxRad); - auto pDiscLayer = DiscLayer::create(pTransform, pDisc); - // auto planeSurface = pDiscLayer->surfaceRepresentation(); - BOOST_CHECK_EQUAL(pDiscLayer->surfaceRepresentation().name(), - std::string("Acts::DiscSurface")); - } +/// Unit test for testing Layer properties +BOOST_AUTO_TEST_CASE(DiscLayerProperties /*, *utf::expected_failures(1)*/) { + Translation3D translation{0., 1., 2.}; + auto pTransform = std::make_shared<const Transform3D>(translation); + const double minRad(10.), maxRad(5.); // 20 x 10 disc + auto pDisc = std::make_shared<const RadialBounds>(minRad, maxRad); + auto pDiscLayer = DiscLayer::create(pTransform, pDisc); + // auto planeSurface = pDiscLayer->surfaceRepresentation(); + BOOST_CHECK_EQUAL(pDiscLayer->surfaceRepresentation().name(), + std::string("Acts::DiscSurface")); +} - BOOST_AUTO_TEST_SUITE_END() - } // namespace Layers +BOOST_AUTO_TEST_SUITE_END() +} // namespace Layers } // namespace Test } // namespace Acts diff --git a/Tests/Core/Geometry/GenericApproachDescriptorTests.cpp b/Tests/Core/Geometry/GenericApproachDescriptorTests.cpp index acd225d55aa19e6e9d7fa2aa7e0856de6d432a53..790c91e1d087ebd47eb5b0740f1b8e5f166c322b 100644 --- a/Tests/Core/Geometry/GenericApproachDescriptorTests.cpp +++ b/Tests/Core/Geometry/GenericApproachDescriptorTests.cpp @@ -27,68 +27,65 @@ namespace utf = boost::unit_test; namespace Acts { namespace Test { - namespace Layers { +namespace Layers { - // Build a default context for testing - GeometryContext tgContext = GeometryContext(); +// Build a default context for testing +GeometryContext tgContext = GeometryContext(); - BOOST_AUTO_TEST_SUITE(Layers) +BOOST_AUTO_TEST_SUITE(Layers) - /// Unit test for creating compliant/non-compliant GenericApproachDescriptor - /// object - BOOST_AUTO_TEST_CASE(GenericApproachDescriptorConstruction) - { - std::vector<std::shared_ptr<const Surface>> someSurfaces{ - Surface::makeShared<SurfaceStub>(), - Surface::makeShared<SurfaceStub>()}; - BOOST_CHECK_NO_THROW( - GenericApproachDescriptor minimallyConstructedApproachDescriptor( - someSurfaces)); - // - std::vector<std::shared_ptr<const Layer>> sharedLayers{ - std::make_shared<LayerStub>(nullptr), - std::make_shared<LayerStub>(nullptr)}; - BOOST_CHECK_NO_THROW( - GenericApproachDescriptor sharedLayerApproachDescriptor( - {sharedLayers.at(0)->surfaceRepresentation().getSharedPtr(), - sharedLayers.at(1)->surfaceRepresentation().getSharedPtr()})); - } +/// Unit test for creating compliant/non-compliant GenericApproachDescriptor +/// object +BOOST_AUTO_TEST_CASE(GenericApproachDescriptorConstruction) { + std::vector<std::shared_ptr<const Surface>> someSurfaces{ + Surface::makeShared<SurfaceStub>(), Surface::makeShared<SurfaceStub>()}; + BOOST_CHECK_NO_THROW( + GenericApproachDescriptor minimallyConstructedApproachDescriptor( + someSurfaces)); + // + std::vector<std::shared_ptr<const Layer>> sharedLayers{ + std::make_shared<LayerStub>(nullptr), + std::make_shared<LayerStub>(nullptr)}; + BOOST_CHECK_NO_THROW(GenericApproachDescriptor sharedLayerApproachDescriptor( + {sharedLayers.at(0)->surfaceRepresentation().getSharedPtr(), + sharedLayers.at(1)->surfaceRepresentation().getSharedPtr()})); +} - /// Unit test for testing GenericApproachDescriptor properties - BOOST_AUTO_TEST_CASE(GenericApproachDescriptorProperties, - *utf::expected_failures(1)) - { - Vector3D origin{ - 0., 0., 0., - }; - Vector3D zDir{0., 0., 1.}; - BoundaryCheck bcheck{true}; - // - std::vector<std::shared_ptr<const Surface>> someSurfaces{ - Surface::makeShared<SurfaceStub>(), - Surface::makeShared<SurfaceStub>()}; - GenericApproachDescriptor approachDescriptor(someSurfaces); - LayerStub aLayer(nullptr); - // registerLayer() - BOOST_CHECK_NO_THROW(approachDescriptor.registerLayer(aLayer)); - // approachSurface - SurfaceIntersection surfIntersection = approachDescriptor.approachSurface( - tgContext, origin, zDir, forward, bcheck); - double expectedIntersection = 20.0; // property of SurfaceStub - CHECK_CLOSE_REL( - surfIntersection.intersection.pathLength, expectedIntersection, 1e-6); - // containedSurfaces() - BOOST_CHECK_EQUAL(approachDescriptor.containedSurfaces().size(), - someSurfaces.size()); +/// Unit test for testing GenericApproachDescriptor properties +BOOST_AUTO_TEST_CASE(GenericApproachDescriptorProperties, + *utf::expected_failures(1)) { + Vector3D origin{ + 0., + 0., + 0., + }; + Vector3D zDir{0., 0., 1.}; + BoundaryCheck bcheck{true}; + // + std::vector<std::shared_ptr<const Surface>> someSurfaces{ + Surface::makeShared<SurfaceStub>(), Surface::makeShared<SurfaceStub>()}; + GenericApproachDescriptor approachDescriptor(someSurfaces); + LayerStub aLayer(nullptr); + // registerLayer() + BOOST_CHECK_NO_THROW(approachDescriptor.registerLayer(aLayer)); + // approachSurface + SurfaceIntersection surfIntersection = approachDescriptor.approachSurface( + tgContext, origin, zDir, forward, bcheck); + double expectedIntersection = 20.0; // property of SurfaceStub + CHECK_CLOSE_REL(surfIntersection.intersection.pathLength, + expectedIntersection, 1e-6); + // containedSurfaces() + BOOST_CHECK_EQUAL(approachDescriptor.containedSurfaces().size(), + someSurfaces.size()); - for (size_t i = 0; i < someSurfaces.size(); i++) { - BOOST_CHECK_EQUAL(approachDescriptor.containedSurfaces().at(i), - someSurfaces.at(i).get()); - } - } + for (size_t i = 0; i < someSurfaces.size(); i++) { + BOOST_CHECK_EQUAL(approachDescriptor.containedSurfaces().at(i), + someSurfaces.at(i).get()); + } +} - BOOST_AUTO_TEST_SUITE_END() - } // namespace Layers +BOOST_AUTO_TEST_SUITE_END() +} // namespace Layers } // namespace Test } // namespace Acts diff --git a/Tests/Core/Geometry/GenericCuboidVolumeBoundsTest.cpp b/Tests/Core/Geometry/GenericCuboidVolumeBoundsTest.cpp index bfe88f5d890f2bbfb34c03f37c56f3a0d7c4675a..9a9aec16415f310101d3b30ec0b0cc8dc36559f6 100644 --- a/Tests/Core/Geometry/GenericCuboidVolumeBoundsTest.cpp +++ b/Tests/Core/Geometry/GenericCuboidVolumeBoundsTest.cpp @@ -26,127 +26,122 @@ namespace Acts { namespace Test { - GeometryContext gctx = GeometryContext(); - - BOOST_AUTO_TEST_SUITE(Volumes) - - BOOST_AUTO_TEST_CASE(construction_test) - { - - std::array<Vector3D, 8> vertices; - vertices = {{{0, 0, 0}, - {2, 0, 0}, - {2, 1, 0}, - {0, 1, 0}, - {0, 0, 1}, - {2, 0, 1}, - {2, 1, 1}, - {0, 1, 1}}}; - GenericCuboidVolumeBounds cubo(vertices); - - BOOST_CHECK(cubo.inside({0.5, 0.5, 0.5})); - BOOST_CHECK(cubo.inside({1.5, 0.5, 0.5})); - BOOST_CHECK(!cubo.inside({2.5, 0.5, 0.5})); - BOOST_CHECK(!cubo.inside({0.5, 1.5, 0.5})); - BOOST_CHECK(!cubo.inside({0.5, 0.5, 1.5})); - BOOST_CHECK(!cubo.inside({-0.5, 0.5, 0.5})); - - BOOST_CHECK(!cubo.inside({2.2, 1, 1}, 0.1)); - BOOST_CHECK(cubo.inside({2.2, 1, 1}, 0.21)); - BOOST_CHECK(cubo.inside({2.2, 1, 1}, 0.3)); - } +GeometryContext gctx = GeometryContext(); + +BOOST_AUTO_TEST_SUITE(Volumes) + +BOOST_AUTO_TEST_CASE(construction_test) { + std::array<Vector3D, 8> vertices; + vertices = {{{0, 0, 0}, + {2, 0, 0}, + {2, 1, 0}, + {0, 1, 0}, + {0, 0, 1}, + {2, 0, 1}, + {2, 1, 1}, + {0, 1, 1}}}; + GenericCuboidVolumeBounds cubo(vertices); + + BOOST_CHECK(cubo.inside({0.5, 0.5, 0.5})); + BOOST_CHECK(cubo.inside({1.5, 0.5, 0.5})); + BOOST_CHECK(!cubo.inside({2.5, 0.5, 0.5})); + BOOST_CHECK(!cubo.inside({0.5, 1.5, 0.5})); + BOOST_CHECK(!cubo.inside({0.5, 0.5, 1.5})); + BOOST_CHECK(!cubo.inside({-0.5, 0.5, 0.5})); + + BOOST_CHECK(!cubo.inside({2.2, 1, 1}, 0.1)); + BOOST_CHECK(cubo.inside({2.2, 1, 1}, 0.21)); + BOOST_CHECK(cubo.inside({2.2, 1, 1}, 0.3)); +} - BOOST_AUTO_TEST_CASE(decomposeToSurfaces) - { - - std::array<Vector3D, 8> vertices; - vertices = {{{0, 0, 0}, - {2, 0, 0}, - {2, 1, 0}, - {0, 1, 0}, - {0, 0, 1}, - {2, 0, 1}, - {2, 1, 1}, - {0, 1, 1}}}; - GenericCuboidVolumeBounds cubo(vertices); - - auto is_in = [](const auto& tvtx, const auto& vertices_) { - for (const auto& vtx : vertices_) { - if (checkCloseAbs(vtx, tvtx, 1e-9)) { - return true; - } - } - return false; - }; - - auto surfaces = cubo.decomposeToSurfaces(nullptr); - for (const auto& srf : surfaces) { - auto pbounds = dynamic_cast<const PlanarBounds*>(&srf->bounds()); - for (const auto& vtx : pbounds->vertices()) { - Vector3D glob; - srf->localToGlobal(gctx, vtx, {}, glob); - // check if glob is in actual vertex list - BOOST_CHECK(is_in(glob, vertices)); +BOOST_AUTO_TEST_CASE(decomposeToSurfaces) { + std::array<Vector3D, 8> vertices; + vertices = {{{0, 0, 0}, + {2, 0, 0}, + {2, 1, 0}, + {0, 1, 0}, + {0, 0, 1}, + {2, 0, 1}, + {2, 1, 1}, + {0, 1, 1}}}; + GenericCuboidVolumeBounds cubo(vertices); + + auto is_in = [](const auto& tvtx, const auto& vertices_) { + for (const auto& vtx : vertices_) { + if (checkCloseAbs(vtx, tvtx, 1e-9)) { + return true; } } - - vertices = {{{0, 0, 0}, - {2, 0, 0.4}, - {2, 1, 0.4}, - {0, 1, 0}, - {0, 0, 1}, - {1.8, 0, 1}, - {1.8, 1, 1}, - {0, 1, 1}}}; - cubo = GenericCuboidVolumeBounds(vertices); - - surfaces = cubo.decomposeToSurfaces(nullptr); - for (const auto& srf : surfaces) { - auto pbounds = dynamic_cast<const PlanarBounds*>(&srf->bounds()); - for (const auto& vtx : pbounds->vertices()) { - Vector3D glob; - srf->localToGlobal(gctx, vtx, {}, glob); - // check if glob is in actual vertex list - BOOST_CHECK(is_in(glob, vertices)); - } + return false; + }; + + auto surfaces = cubo.decomposeToSurfaces(nullptr); + for (const auto& srf : surfaces) { + auto pbounds = dynamic_cast<const PlanarBounds*>(&srf->bounds()); + for (const auto& vtx : pbounds->vertices()) { + Vector3D glob; + srf->localToGlobal(gctx, vtx, {}, glob); + // check if glob is in actual vertex list + BOOST_CHECK(is_in(glob, vertices)); } + } - Transform3D trf; - trf = Translation3D(Vector3D(0, 8, -5)) - * AngleAxis3D(M_PI / 3., Vector3D(1, -3, 9).normalized()); - - surfaces = cubo.decomposeToSurfaces(&trf); - for (const auto& srf : surfaces) { - auto pbounds = dynamic_cast<const PlanarBounds*>(&srf->bounds()); - for (const auto& vtx : pbounds->vertices()) { - Vector3D glob; - srf->localToGlobal(gctx, vtx, {}, glob); - // check if glob is in actual vertex list - BOOST_CHECK(is_in(trf.inverse() * glob, vertices)); - } + vertices = {{{0, 0, 0}, + {2, 0, 0.4}, + {2, 1, 0.4}, + {0, 1, 0}, + {0, 0, 1}, + {1.8, 0, 1}, + {1.8, 1, 1}, + {0, 1, 1}}}; + cubo = GenericCuboidVolumeBounds(vertices); + + surfaces = cubo.decomposeToSurfaces(nullptr); + for (const auto& srf : surfaces) { + auto pbounds = dynamic_cast<const PlanarBounds*>(&srf->bounds()); + for (const auto& vtx : pbounds->vertices()) { + Vector3D glob; + srf->localToGlobal(gctx, vtx, {}, glob); + // check if glob is in actual vertex list + BOOST_CHECK(is_in(glob, vertices)); } } - BOOST_AUTO_TEST_CASE(ply_test) - { - std::array<Vector3D, 8> vertices; - vertices = {{{0, 0, 0}, - {2, 0, 0}, - {2, 1, 0}, - {0, 1, 0}, - {0, 0, 1}, - {2, 0, 1}, - {2, 1, 1}, - {0, 1, 1}}}; - GenericCuboidVolumeBounds cubo(vertices); - PlyHelper<double> ply; - cubo.draw(ply); - - std::ofstream os("cuboid.ply"); - os << ply << std::flush; - os.close(); + Transform3D trf; + trf = Translation3D(Vector3D(0, 8, -5)) * + AngleAxis3D(M_PI / 3., Vector3D(1, -3, 9).normalized()); + + surfaces = cubo.decomposeToSurfaces(&trf); + for (const auto& srf : surfaces) { + auto pbounds = dynamic_cast<const PlanarBounds*>(&srf->bounds()); + for (const auto& vtx : pbounds->vertices()) { + Vector3D glob; + srf->localToGlobal(gctx, vtx, {}, glob); + // check if glob is in actual vertex list + BOOST_CHECK(is_in(trf.inverse() * glob, vertices)); + } } - - BOOST_AUTO_TEST_SUITE_END() } + +BOOST_AUTO_TEST_CASE(ply_test) { + std::array<Vector3D, 8> vertices; + vertices = {{{0, 0, 0}, + {2, 0, 0}, + {2, 1, 0}, + {0, 1, 0}, + {0, 0, 1}, + {2, 0, 1}, + {2, 1, 1}, + {0, 1, 1}}}; + GenericCuboidVolumeBounds cubo(vertices); + PlyHelper<double> ply; + cubo.draw(ply); + + std::ofstream os("cuboid.ply"); + os << ply << std::flush; + os.close(); } + +BOOST_AUTO_TEST_SUITE_END() +} // namespace Test +} // namespace Acts diff --git a/Tests/Core/Geometry/LayerCreatorTests.cpp b/Tests/Core/Geometry/LayerCreatorTests.cpp index 0b29c9278ec708f12dd65fee33db7eaa007eec37..c0f19542873626722a454534d8984ecbf9d1f50f 100644 --- a/Tests/Core/Geometry/LayerCreatorTests.cpp +++ b/Tests/Core/Geometry/LayerCreatorTests.cpp @@ -32,476 +32,440 @@ #include "Acts/Geometry/GeometryContext.hpp" namespace bdata = boost::unit_test::data; -namespace tt = boost::test_tools; +namespace tt = boost::test_tools; namespace Acts { namespace Test { - // Create a test context - GeometryContext tgContext = GeometryContext(); +// Create a test context +GeometryContext tgContext = GeometryContext(); -#define CHECK_ROTATION_ANGLE(t, a, tolerance) \ - { \ - Vector3D v = (*t) * Vector3D(1, 0, 0); \ - CHECK_CLOSE_ABS(VectorHelpers::phi(v), (a), tolerance); \ +#define CHECK_ROTATION_ANGLE(t, a, tolerance) \ + { \ + Vector3D v = (*t) * Vector3D(1, 0, 0); \ + CHECK_CLOSE_ABS(VectorHelpers::phi(v), (a), tolerance); \ } - using SrfVec = std::vector<std::shared_ptr<const Surface>>; +using SrfVec = std::vector<std::shared_ptr<const Surface>>; - void - draw_surfaces(const SrfVec& surfaces, const std::string& fname) - { +void draw_surfaces(const SrfVec& surfaces, const std::string& fname) { + std::ofstream os; + os.open(fname); - std::ofstream os; - os.open(fname); + os << std::fixed << std::setprecision(4); - os << std::fixed << std::setprecision(4); + size_t nVtx = 0; + for (const auto& srfx : surfaces) { + std::shared_ptr<const PlaneSurface> srf = + std::dynamic_pointer_cast<const PlaneSurface>(srfx); + const PlanarBounds* bounds = + dynamic_cast<const PlanarBounds*>(&srf->bounds()); - size_t nVtx = 0; - for (const auto& srfx : surfaces) { - std::shared_ptr<const PlaneSurface> srf - = std::dynamic_pointer_cast<const PlaneSurface>(srfx); - const PlanarBounds* bounds - = dynamic_cast<const PlanarBounds*>(&srf->bounds()); + for (const auto& vtxloc : bounds->vertices()) { + Vector3D vtx = + srf->transform(tgContext) * Vector3D(vtxloc.x(), vtxloc.y(), 0); + os << "v " << vtx.x() << " " << vtx.y() << " " << vtx.z() << "\n"; + } - for (const auto& vtxloc : bounds->vertices()) { - Vector3D vtx - = srf->transform(tgContext) * Vector3D(vtxloc.x(), vtxloc.y(), 0); - os << "v " << vtx.x() << " " << vtx.y() << " " << vtx.z() << "\n"; - } + // connect them + os << "f"; + for (size_t i = 1; i <= bounds->vertices().size(); ++i) { + os << " " << nVtx + i; + } + os << "\n"; - // connect them - os << "f"; - for (size_t i = 1; i <= bounds->vertices().size(); ++i) { - os << " " << nVtx + i; - } - os << "\n"; + nVtx += bounds->vertices().size(); + } - nVtx += bounds->vertices().size(); - } + os.close(); +} + +struct LayerCreatorFixture { + std::shared_ptr<const SurfaceArrayCreator> p_SAC; + std::shared_ptr<LayerCreator> p_LC; + std::vector<std::shared_ptr<const Surface>> m_surfaces; + + LayerCreatorFixture() { + p_SAC = std::make_shared<const SurfaceArrayCreator>( + SurfaceArrayCreator::Config(), + Acts::getDefaultLogger("SurfaceArrayCreator", Acts::Logging::VERBOSE)); + LayerCreator::Config cfg; + cfg.surfaceArrayCreator = p_SAC; + p_LC = std::make_shared<LayerCreator>( + cfg, Acts::getDefaultLogger("LayerCreator", Acts::Logging::VERBOSE)); + } - os.close(); + template <typename... Args> + bool checkBinning(Args&&... args) { + return p_LC->checkBinning(std::forward<Args>(args)...); } - struct LayerCreatorFixture - { - std::shared_ptr<const SurfaceArrayCreator> p_SAC; - std::shared_ptr<LayerCreator> p_LC; - std::vector<std::shared_ptr<const Surface>> m_surfaces; - - LayerCreatorFixture() - { - p_SAC = std::make_shared<const SurfaceArrayCreator>( - SurfaceArrayCreator::Config(), - Acts::getDefaultLogger("SurfaceArrayCreator", - Acts::Logging::VERBOSE)); - LayerCreator::Config cfg; - cfg.surfaceArrayCreator = p_SAC; - p_LC = std::make_shared<LayerCreator>( - cfg, Acts::getDefaultLogger("LayerCreator", Acts::Logging::VERBOSE)); + bool checkBinContentSize(const SurfaceArray* sArray, size_t n) { + size_t nBins = sArray->size(); + bool result = true; + for (size_t i = 0; i < nBins; ++i) { + if (!sArray->isValidBin(i)) { + continue; + } + std::vector<const Surface*> binContent = sArray->at(i); + BOOST_TEST_INFO("Bin: " << i); + BOOST_CHECK_EQUAL(binContent.size(), n); + result = result && binContent.size() == n; } - template <typename... Args> - bool - checkBinning(Args&&... args) - { - return p_LC->checkBinning(std::forward<Args>(args)...); - } + return result; + } - bool - checkBinContentSize(const SurfaceArray* sArray, size_t n) - { - size_t nBins = sArray->size(); - bool result = true; - for (size_t i = 0; i < nBins; ++i) { - if (!sArray->isValidBin(i)) { - continue; - } - std::vector<const Surface*> binContent = sArray->at(i); - BOOST_TEST_INFO("Bin: " << i); - BOOST_CHECK_EQUAL(binContent.size(), n); - result = result && binContent.size() == n; - } + SrfVec fullPhiTestSurfacesEC(size_t n = 10, double shift = 0, + double zbase = 0, double r = 10) { + SrfVec res; + + double phiStep = 2 * M_PI / n; + for (size_t i = 0; i < n; ++i) { + double z = zbase + ((i % 2 == 0) ? 1 : -1) * 0.2; + + Transform3D trans; + trans.setIdentity(); + trans.rotate(Eigen::AngleAxisd(i * phiStep + shift, Vector3D(0, 0, 1))); + trans.translate(Vector3D(r, 0, z)); - return result; + auto bounds = std::make_shared<const RectangleBounds>(2, 1); + + auto transptr = std::make_shared<const Transform3D>(trans); + std::shared_ptr<PlaneSurface> srf = + Surface::makeShared<PlaneSurface>(transptr, bounds); + + res.push_back(srf); + m_surfaces.push_back( + std::move(srf)); // keep shared, will get destroyed at the end } - SrfVec - fullPhiTestSurfacesEC(size_t n = 10, - double shift = 0, - double zbase = 0, - double r = 10) - { + return res; + } - SrfVec res; + SrfVec fullPhiTestSurfacesBRL(int n = 10, double shift = 0, double zbase = 0, + double incl = M_PI / 9., double w = 2, + double h = 1.5) { + SrfVec res; - double phiStep = 2 * M_PI / n; - for (size_t i = 0; i < n; ++i) { + double phiStep = 2 * M_PI / n; + for (int i = 0; i < n; ++i) { + double z = zbase; - double z = zbase + ((i % 2 == 0) ? 1 : -1) * 0.2; + Transform3D trans; + trans.setIdentity(); + trans.rotate(Eigen::AngleAxisd(i * phiStep + shift, Vector3D(0, 0, 1))); + trans.translate(Vector3D(10, 0, z)); + trans.rotate(Eigen::AngleAxisd(incl, Vector3D(0, 0, 1))); + trans.rotate(Eigen::AngleAxisd(M_PI / 2., Vector3D(0, 1, 0))); - Transform3D trans; - trans.setIdentity(); - trans.rotate(Eigen::AngleAxisd(i * phiStep + shift, Vector3D(0, 0, 1))); - trans.translate(Vector3D(r, 0, z)); + auto bounds = std::make_shared<const RectangleBounds>(w, h); - auto bounds = std::make_shared<const RectangleBounds>(2, 1); + auto transptr = std::make_shared<const Transform3D>(trans); + std::shared_ptr<PlaneSurface> srf = + Surface::makeShared<PlaneSurface>(transptr, bounds); - auto transptr = std::make_shared<const Transform3D>(trans); - std::shared_ptr<PlaneSurface> srf - = Surface::makeShared<PlaneSurface>(transptr, bounds); + res.push_back(srf); + m_surfaces.push_back( + std::move(srf)); // keep shared, will get destroyed at the end + } - res.push_back(srf); - m_surfaces.push_back( - std::move(srf)); // keep shared, will get destroyed at the end - } + return res; + } + + SrfVec makeBarrel(int nPhi, int nZ, double w, double h) { + double z0 = -(nZ - 1) * w; + SrfVec res; - return res; + for (int i = 0; i < nZ; i++) { + double z = i * w * 2 + z0; + std::cout << "z=" << z << std::endl; + SrfVec ring = fullPhiTestSurfacesBRL(nPhi, 0, z, M_PI / 9., w, h); + res.insert(res.end(), ring.begin(), ring.end()); } - SrfVec - fullPhiTestSurfacesBRL(int n = 10, - double shift = 0, - double zbase = 0, - double incl = M_PI / 9., - double w = 2, - double h = 1.5) - { + return res; + } - SrfVec res; + std::pair<SrfVec, std::vector<std::pair<const Surface*, const Surface*>>> + makeBarrelStagger(int nPhi, int nZ, double shift = 0, double incl = M_PI / 9., + double w = 2, double h = 1.5) { + double z0 = -(nZ - 1) * w; + SrfVec res; - double phiStep = 2 * M_PI / n; - for (int i = 0; i < n; ++i) { + std::vector<std::pair<const Surface*, const Surface*>> pairs; - double z = zbase; + for (int i = 0; i < nZ; i++) { + double z = i * w * 2 + z0; + double phiStep = 2 * M_PI / nPhi; + for (int j = 0; j < nPhi; ++j) { Transform3D trans; trans.setIdentity(); - trans.rotate(Eigen::AngleAxisd(i * phiStep + shift, Vector3D(0, 0, 1))); + trans.rotate(Eigen::AngleAxisd(j * phiStep + shift, Vector3D(0, 0, 1))); trans.translate(Vector3D(10, 0, z)); trans.rotate(Eigen::AngleAxisd(incl, Vector3D(0, 0, 1))); trans.rotate(Eigen::AngleAxisd(M_PI / 2., Vector3D(0, 1, 0))); auto bounds = std::make_shared<const RectangleBounds>(w, h); - auto transptr = std::make_shared<const Transform3D>(trans); - std::shared_ptr<PlaneSurface> srf - = Surface::makeShared<PlaneSurface>(transptr, bounds); + auto transAptr = std::make_shared<const Transform3D>(trans); - res.push_back(srf); - m_surfaces.push_back( - std::move(srf)); // keep shared, will get destroyed at the end - } + std::shared_ptr<PlaneSurface> srfA = + Surface::makeShared<PlaneSurface>(transAptr, bounds); - return res; - } + Vector3D nrm = srfA->normal(tgContext); + Transform3D transB = trans; + transB.pretranslate(nrm * 0.1); + auto transBptr = std::make_shared<const Transform3D>(transB); + std::shared_ptr<PlaneSurface> srfB = + Surface::makeShared<PlaneSurface>(transBptr, bounds); - SrfVec - makeBarrel(int nPhi, int nZ, double w, double h) - { - double z0 = -(nZ - 1) * w; - SrfVec res; - - for (int i = 0; i < nZ; i++) { - double z = i * w * 2 + z0; - std::cout << "z=" << z << std::endl; - SrfVec ring = fullPhiTestSurfacesBRL(nPhi, 0, z, M_PI / 9., w, h); - res.insert(res.end(), ring.begin(), ring.end()); - } + pairs.push_back(std::make_pair(srfA.get(), srfB.get())); - return res; - } - - std::pair<SrfVec, std::vector<std::pair<const Surface*, const Surface*>>> - makeBarrelStagger(int nPhi, - int nZ, - double shift = 0, - double incl = M_PI / 9., - double w = 2, - double h = 1.5) - { - double z0 = -(nZ - 1) * w; - SrfVec res; - - std::vector<std::pair<const Surface*, const Surface*>> pairs; - - for (int i = 0; i < nZ; i++) { - double z = i * w * 2 + z0; - - double phiStep = 2 * M_PI / nPhi; - for (int j = 0; j < nPhi; ++j) { - - Transform3D trans; - trans.setIdentity(); - trans.rotate( - Eigen::AngleAxisd(j * phiStep + shift, Vector3D(0, 0, 1))); - trans.translate(Vector3D(10, 0, z)); - trans.rotate(Eigen::AngleAxisd(incl, Vector3D(0, 0, 1))); - trans.rotate(Eigen::AngleAxisd(M_PI / 2., Vector3D(0, 1, 0))); - - auto bounds = std::make_shared<const RectangleBounds>(w, h); - - auto transAptr = std::make_shared<const Transform3D>(trans); - - std::shared_ptr<PlaneSurface> srfA - = Surface::makeShared<PlaneSurface>(transAptr, bounds); - - Vector3D nrm = srfA->normal(tgContext); - Transform3D transB = trans; - transB.pretranslate(nrm * 0.1); - auto transBptr = std::make_shared<const Transform3D>(transB); - std::shared_ptr<PlaneSurface> srfB - = Surface::makeShared<PlaneSurface>(transBptr, bounds); - - pairs.push_back(std::make_pair(srfA.get(), srfB.get())); - - res.push_back(srfA); - res.push_back(srfB); - m_surfaces.push_back(std::move(srfA)); - m_surfaces.push_back(std::move(srfB)); - } + res.push_back(srfA); + res.push_back(srfB); + m_surfaces.push_back(std::move(srfA)); + m_surfaces.push_back(std::move(srfB)); } - - return std::make_pair(res, pairs); } - }; - - BOOST_AUTO_TEST_SUITE(Tools) - - BOOST_FIXTURE_TEST_CASE(LayerCreator_createCylinderLayer, LayerCreatorFixture) - { - std::vector<std::shared_ptr<const Surface>> srf; - - srf = makeBarrel(30, 7, 2, 1.5); - draw_surfaces(srf, "LayerCreator_createCylinderLayer_BRL_1.obj"); - - // CASE I - double envR = 0.1, envZ = 0.5; - ProtoLayer pl(tgContext, srf); - pl.envR = {envR, envR}; - pl.envZ = {envZ, envZ}; - std::shared_ptr<CylinderLayer> layer - = std::dynamic_pointer_cast<CylinderLayer>( - p_LC->cylinderLayer(tgContext, srf, equidistant, equidistant, pl)); - - double rMax = 10.6071, rMin = 9.59111; // empirical - CHECK_CLOSE_REL(layer->thickness(), (rMax - rMin) + 2 * envR, 1e-3); - - const CylinderBounds* bounds = &layer->bounds(); - CHECK_CLOSE_REL(bounds->r(), (rMax + rMin) / 2., 1e-3); - CHECK_CLOSE_REL(bounds->halflengthZ(), 14 + envZ, 1e-3); - BOOST_CHECK(checkBinning(tgContext, *layer->surfaceArray())); - auto axes = layer->surfaceArray()->getAxes(); - BOOST_CHECK_EQUAL(axes.at(0)->getNBins(), 30); - BOOST_CHECK_EQUAL(axes.at(1)->getNBins(), 7); - CHECK_CLOSE_REL(axes.at(0)->getMin(), -M_PI, 1e-3); - CHECK_CLOSE_REL(axes.at(0)->getMax(), M_PI, 1e-3); - CHECK_CLOSE_REL(axes.at(1)->getMin(), -14, 1e-3); - CHECK_CLOSE_REL(axes.at(1)->getMax(), 14, 1e-3); - - // CASE II - - ProtoLayer pl2(tgContext, srf); - pl2.envR = {envR, envR}; - pl2.envZ = {envZ, envZ}; - layer = std::dynamic_pointer_cast<CylinderLayer>( - p_LC->cylinderLayer(tgContext, srf, 30, 7, pl2)); - CHECK_CLOSE_REL(layer->thickness(), (rMax - rMin) + 2 * envR, 1e-3); - bounds = &layer->bounds(); - CHECK_CLOSE_REL(bounds->r(), (rMax + rMin) / 2., 1e-3); - CHECK_CLOSE_REL(bounds->halflengthZ(), 14 + envZ, 1e-3); - BOOST_CHECK(checkBinning(tgContext, *layer->surfaceArray())); - axes = layer->surfaceArray()->getAxes(); - BOOST_CHECK_EQUAL(axes.at(0)->getNBins(), 30); - BOOST_CHECK_EQUAL(axes.at(1)->getNBins(), 7); - CHECK_CLOSE_REL(axes.at(0)->getMin(), -M_PI, 1e-3); - CHECK_CLOSE_REL(axes.at(0)->getMax(), M_PI, 1e-3); - CHECK_CLOSE_REL(axes.at(1)->getMin(), -14, 1e-3); - CHECK_CLOSE_REL(axes.at(1)->getMax(), 14, 1e-3); - - layer = std::dynamic_pointer_cast<CylinderLayer>( - p_LC->cylinderLayer(tgContext, srf, 13, 3, pl2)); - CHECK_CLOSE_REL(layer->thickness(), (rMax - rMin) + 2 * envR, 1e-3); - bounds = &layer->bounds(); - CHECK_CLOSE_REL(bounds->r(), (rMax + rMin) / 2., 1e-3); - CHECK_CLOSE_REL(bounds->halflengthZ(), 14 + envZ, 1e-3); - // this succeeds despite sub-optimal binning - // since we now have multientry bins - BOOST_CHECK(checkBinning(tgContext, *layer->surfaceArray())); - axes = layer->surfaceArray()->getAxes(); - BOOST_CHECK_EQUAL(axes.at(0)->getNBins(), 13); - BOOST_CHECK_EQUAL(axes.at(1)->getNBins(), 3); - CHECK_CLOSE_REL(axes.at(0)->getMin(), -M_PI, 1e-3); - CHECK_CLOSE_REL(axes.at(0)->getMax(), M_PI, 1e-3); - CHECK_CLOSE_REL(axes.at(1)->getMin(), -14, 1e-3); - CHECK_CLOSE_REL(axes.at(1)->getMax(), 14, 1e-3); - - // CASE III - ProtoLayer pl3; - pl3.minR = 1; - pl3.maxR = 20; - pl3.minZ = -25; - pl3.maxZ = 25; - layer = std::dynamic_pointer_cast<CylinderLayer>( - p_LC->cylinderLayer(tgContext, srf, equidistant, equidistant, pl3)); - CHECK_CLOSE_REL(layer->thickness(), 19, 1e-3); - bounds = &layer->bounds(); - CHECK_CLOSE_REL(bounds->r(), 10.5, 1e-3); - CHECK_CLOSE_REL(bounds->halflengthZ(), 25, 1e-3); - - // this should fail, b/c it's a completely inconvenient binning - // but it succeeds despite sub-optimal binning - // since we now have multientry bins - BOOST_CHECK(checkBinning(tgContext, *layer->surfaceArray())); - - axes = layer->surfaceArray()->getAxes(); - BOOST_CHECK_EQUAL(axes.at(0)->getNBins(), 30); - BOOST_CHECK_EQUAL(axes.at(1)->getNBins(), 7); - CHECK_CLOSE_REL(axes.at(0)->getMin(), -M_PI, 1e-3); - CHECK_CLOSE_REL(axes.at(0)->getMax(), M_PI, 1e-3); - CHECK_CLOSE_REL(axes.at(1)->getMin(), -25, 1e-3); - CHECK_CLOSE_REL(axes.at(1)->getMax(), 25, 1e-3); - } - BOOST_FIXTURE_TEST_CASE(LayerCreator_createDiscLayer, LayerCreatorFixture) - { - std::vector<std::shared_ptr<const Surface>> surfaces; - auto ringa = fullPhiTestSurfacesEC(30, 0, 0, 10); - surfaces.insert(surfaces.end(), ringa.begin(), ringa.end()); - auto ringb = fullPhiTestSurfacesEC(30, 0, 0, 15); - surfaces.insert(surfaces.end(), ringb.begin(), ringb.end()); - auto ringc = fullPhiTestSurfacesEC(30, 0, 0, 20); - surfaces.insert(surfaces.end(), ringc.begin(), ringc.end()); - draw_surfaces(surfaces, "LayerCreator_createDiscLayer_EC_1.obj"); - - ProtoLayer pl(tgContext, surfaces); - pl.minZ = -10; - pl.maxZ = 10; - pl.minR = 5; - pl.maxR = 25; - std::shared_ptr<DiscLayer> layer = std::dynamic_pointer_cast<DiscLayer>( - p_LC->discLayer(tgContext, surfaces, equidistant, equidistant, pl)); - CHECK_CLOSE_REL(layer->thickness(), 20, 1e-3); - const RadialBounds* bounds - = dynamic_cast<const RadialBounds*>(&layer->bounds()); - CHECK_CLOSE_REL(bounds->rMin(), 5, 1e-3); - CHECK_CLOSE_REL(bounds->rMax(), 25, 1e-3); - BOOST_CHECK(checkBinning(tgContext, *layer->surfaceArray())); - auto axes = layer->surfaceArray()->getAxes(); - BOOST_CHECK_EQUAL(axes.at(0)->getNBins(), 3); - BOOST_CHECK_EQUAL(axes.at(1)->getNBins(), 30); - CHECK_CLOSE_REL(axes.at(0)->getMin(), 5, 1e-3); - CHECK_CLOSE_REL(axes.at(0)->getMax(), 25, 1e-3); - CHECK_CLOSE_REL(axes.at(1)->getMin(), -M_PI, 1e-3); - CHECK_CLOSE_REL(axes.at(1)->getMax(), M_PI, 1e-3); - checkBinContentSize(layer->surfaceArray(), 1); - - // check that it's applying a rotation transform to improve phi binning - // BOOST_CHECK_NE(bu->transform(), nullptr); - // double actAngle = ((*bu->transform()) * Vector3D(1, 0, 0)).phi(); - // double expAngle = -2 * M_PI / 30 / 2.; - // CHECK_CLOSE_REL(actAngle, expAngle, 1e-3); - - double envMinR = 1, envMaxR = 1, envZ = 5; - size_t nBinsR = 3, nBinsPhi = 30; - ProtoLayer pl2(tgContext, surfaces); - pl2.envR = {envMinR, envMaxR}; - pl2.envZ = {envZ, envZ}; - layer = std::dynamic_pointer_cast<DiscLayer>( - p_LC->discLayer(tgContext, surfaces, nBinsR, nBinsPhi, pl2)); - - double rMin = 8, rMax = 22.0227; - CHECK_CLOSE_REL(layer->thickness(), 0.4 + 2 * envZ, 1e-3); - bounds = dynamic_cast<const RadialBounds*>(&layer->bounds()); - CHECK_CLOSE_REL(bounds->rMin(), rMin - envMinR, 1e-3); - CHECK_CLOSE_REL(bounds->rMax(), rMax + envMaxR, 1e-3); - BOOST_CHECK(checkBinning(tgContext, *layer->surfaceArray())); - axes = layer->surfaceArray()->getAxes(); - BOOST_CHECK_EQUAL(axes.at(0)->getNBins(), nBinsR); - BOOST_CHECK_EQUAL(axes.at(1)->getNBins(), nBinsPhi); - CHECK_CLOSE_REL(axes.at(0)->getMin(), rMin, 1e-3); - CHECK_CLOSE_REL(axes.at(0)->getMax(), rMax, 1e-3); - CHECK_CLOSE_REL(axes.at(1)->getMin(), -M_PI, 1e-3); - CHECK_CLOSE_REL(axes.at(1)->getMax(), M_PI, 1e-3); - checkBinContentSize(layer->surfaceArray(), 1); - - // check that it's applying a rotation transform to improve phi binning - // BOOST_CHECK_NE(bu->transform(), nullptr); - // actAngle = ((*bu->transform()) * Vector3D(1, 0, 0)).phi(); - // expAngle = -2 * M_PI / 30 / 2.; - // CHECK_CLOSE_REL(actAngle, expAngle, 1e-3); - - layer = std::dynamic_pointer_cast<DiscLayer>( - p_LC->discLayer(tgContext, surfaces, equidistant, equidistant, pl2)); - CHECK_CLOSE_REL(layer->thickness(), 0.4 + 2 * envZ, 1e-3); - bounds = dynamic_cast<const RadialBounds*>(&layer->bounds()); - CHECK_CLOSE_REL(bounds->rMin(), rMin - envMinR, 1e-3); - CHECK_CLOSE_REL(bounds->rMax(), rMax + envMaxR, 1e-3); - BOOST_CHECK(checkBinning(tgContext, *layer->surfaceArray())); - axes = layer->surfaceArray()->getAxes(); - BOOST_CHECK_EQUAL(axes.at(0)->getNBins(), nBinsR); - BOOST_CHECK_EQUAL(axes.at(1)->getNBins(), nBinsPhi); - CHECK_CLOSE_REL(axes.at(0)->getMin(), rMin, 1e-3); - CHECK_CLOSE_REL(axes.at(0)->getMax(), rMax, 1e-3); - CHECK_CLOSE_REL(axes.at(1)->getMin(), -M_PI, 1e-3); - CHECK_CLOSE_REL(axes.at(1)->getMax(), M_PI, 1e-3); - checkBinContentSize(layer->surfaceArray(), 1); - - // check that it's applying a rotation transform to improve phi binning - // BOOST_CHECK_NE(bu->transform(), nullptr); - // actAngle = ((*bu->transform()) * Vector3D(1, 0, 0)).phi(); - // expAngle = -2 * M_PI / 30 / 2.; - // CHECK_CLOSE_REL(actAngle, expAngle, 1e-3); + return std::make_pair(res, pairs); } - - BOOST_FIXTURE_TEST_CASE(LayerCreator_barrelStagger, LayerCreatorFixture) - { - - auto barrel = makeBarrelStagger(30, 7, 0, M_PI / 9.); - auto brl = barrel.first; - draw_surfaces(brl, "LayerCreator_barrelStagger.obj"); - - double envR = 0, envZ = 0; - ProtoLayer pl(tgContext, brl); - pl.envR = {envR, envR}; - pl.envZ = {envZ, envZ}; - std::shared_ptr<CylinderLayer> layer - = std::dynamic_pointer_cast<CylinderLayer>( - p_LC->cylinderLayer(tgContext, brl, equidistant, equidistant, pl)); - - auto axes = layer->surfaceArray()->getAxes(); - BOOST_CHECK_EQUAL(axes.at(0)->getNBins(), 30); - BOOST_CHECK_EQUAL(axes.at(1)->getNBins(), 7); - - // check if binning is good! - for (const auto& pr : barrel.second) { - auto A = pr.first; - auto B = pr.second; - - // std::cout << A->center().phi() << " "; - // std::cout << B->center().phi() << std::endl; - // std::cout << "dPHi = " << A->center().phi() - B->center().phi() << - // std::endl; - - Vector3D ctr = A->binningPosition(tgContext, binR); - auto binContent = layer->surfaceArray()->at(ctr); - BOOST_CHECK_EQUAL(binContent.size(), 2); - std::set<const Surface*> act; - act.insert(binContent[0]); - act.insert(binContent[1]); - - std::set<const Surface*> exp; - exp.insert(A); - exp.insert(B); - BOOST_CHECK(exp == act); - } - - // checkBinning should also report everything is fine - checkBinning(tgContext, *layer->surfaceArray()); +}; + +BOOST_AUTO_TEST_SUITE(Tools) + +BOOST_FIXTURE_TEST_CASE(LayerCreator_createCylinderLayer, LayerCreatorFixture) { + std::vector<std::shared_ptr<const Surface>> srf; + + srf = makeBarrel(30, 7, 2, 1.5); + draw_surfaces(srf, "LayerCreator_createCylinderLayer_BRL_1.obj"); + + // CASE I + double envR = 0.1, envZ = 0.5; + ProtoLayer pl(tgContext, srf); + pl.envR = {envR, envR}; + pl.envZ = {envZ, envZ}; + std::shared_ptr<CylinderLayer> layer = + std::dynamic_pointer_cast<CylinderLayer>( + p_LC->cylinderLayer(tgContext, srf, equidistant, equidistant, pl)); + + double rMax = 10.6071, rMin = 9.59111; // empirical + CHECK_CLOSE_REL(layer->thickness(), (rMax - rMin) + 2 * envR, 1e-3); + + const CylinderBounds* bounds = &layer->bounds(); + CHECK_CLOSE_REL(bounds->r(), (rMax + rMin) / 2., 1e-3); + CHECK_CLOSE_REL(bounds->halflengthZ(), 14 + envZ, 1e-3); + BOOST_CHECK(checkBinning(tgContext, *layer->surfaceArray())); + auto axes = layer->surfaceArray()->getAxes(); + BOOST_CHECK_EQUAL(axes.at(0)->getNBins(), 30); + BOOST_CHECK_EQUAL(axes.at(1)->getNBins(), 7); + CHECK_CLOSE_REL(axes.at(0)->getMin(), -M_PI, 1e-3); + CHECK_CLOSE_REL(axes.at(0)->getMax(), M_PI, 1e-3); + CHECK_CLOSE_REL(axes.at(1)->getMin(), -14, 1e-3); + CHECK_CLOSE_REL(axes.at(1)->getMax(), 14, 1e-3); + + // CASE II + + ProtoLayer pl2(tgContext, srf); + pl2.envR = {envR, envR}; + pl2.envZ = {envZ, envZ}; + layer = std::dynamic_pointer_cast<CylinderLayer>( + p_LC->cylinderLayer(tgContext, srf, 30, 7, pl2)); + CHECK_CLOSE_REL(layer->thickness(), (rMax - rMin) + 2 * envR, 1e-3); + bounds = &layer->bounds(); + CHECK_CLOSE_REL(bounds->r(), (rMax + rMin) / 2., 1e-3); + CHECK_CLOSE_REL(bounds->halflengthZ(), 14 + envZ, 1e-3); + BOOST_CHECK(checkBinning(tgContext, *layer->surfaceArray())); + axes = layer->surfaceArray()->getAxes(); + BOOST_CHECK_EQUAL(axes.at(0)->getNBins(), 30); + BOOST_CHECK_EQUAL(axes.at(1)->getNBins(), 7); + CHECK_CLOSE_REL(axes.at(0)->getMin(), -M_PI, 1e-3); + CHECK_CLOSE_REL(axes.at(0)->getMax(), M_PI, 1e-3); + CHECK_CLOSE_REL(axes.at(1)->getMin(), -14, 1e-3); + CHECK_CLOSE_REL(axes.at(1)->getMax(), 14, 1e-3); + + layer = std::dynamic_pointer_cast<CylinderLayer>( + p_LC->cylinderLayer(tgContext, srf, 13, 3, pl2)); + CHECK_CLOSE_REL(layer->thickness(), (rMax - rMin) + 2 * envR, 1e-3); + bounds = &layer->bounds(); + CHECK_CLOSE_REL(bounds->r(), (rMax + rMin) / 2., 1e-3); + CHECK_CLOSE_REL(bounds->halflengthZ(), 14 + envZ, 1e-3); + // this succeeds despite sub-optimal binning + // since we now have multientry bins + BOOST_CHECK(checkBinning(tgContext, *layer->surfaceArray())); + axes = layer->surfaceArray()->getAxes(); + BOOST_CHECK_EQUAL(axes.at(0)->getNBins(), 13); + BOOST_CHECK_EQUAL(axes.at(1)->getNBins(), 3); + CHECK_CLOSE_REL(axes.at(0)->getMin(), -M_PI, 1e-3); + CHECK_CLOSE_REL(axes.at(0)->getMax(), M_PI, 1e-3); + CHECK_CLOSE_REL(axes.at(1)->getMin(), -14, 1e-3); + CHECK_CLOSE_REL(axes.at(1)->getMax(), 14, 1e-3); + + // CASE III + ProtoLayer pl3; + pl3.minR = 1; + pl3.maxR = 20; + pl3.minZ = -25; + pl3.maxZ = 25; + layer = std::dynamic_pointer_cast<CylinderLayer>( + p_LC->cylinderLayer(tgContext, srf, equidistant, equidistant, pl3)); + CHECK_CLOSE_REL(layer->thickness(), 19, 1e-3); + bounds = &layer->bounds(); + CHECK_CLOSE_REL(bounds->r(), 10.5, 1e-3); + CHECK_CLOSE_REL(bounds->halflengthZ(), 25, 1e-3); + + // this should fail, b/c it's a completely inconvenient binning + // but it succeeds despite sub-optimal binning + // since we now have multientry bins + BOOST_CHECK(checkBinning(tgContext, *layer->surfaceArray())); + + axes = layer->surfaceArray()->getAxes(); + BOOST_CHECK_EQUAL(axes.at(0)->getNBins(), 30); + BOOST_CHECK_EQUAL(axes.at(1)->getNBins(), 7); + CHECK_CLOSE_REL(axes.at(0)->getMin(), -M_PI, 1e-3); + CHECK_CLOSE_REL(axes.at(0)->getMax(), M_PI, 1e-3); + CHECK_CLOSE_REL(axes.at(1)->getMin(), -25, 1e-3); + CHECK_CLOSE_REL(axes.at(1)->getMax(), 25, 1e-3); +} + +BOOST_FIXTURE_TEST_CASE(LayerCreator_createDiscLayer, LayerCreatorFixture) { + std::vector<std::shared_ptr<const Surface>> surfaces; + auto ringa = fullPhiTestSurfacesEC(30, 0, 0, 10); + surfaces.insert(surfaces.end(), ringa.begin(), ringa.end()); + auto ringb = fullPhiTestSurfacesEC(30, 0, 0, 15); + surfaces.insert(surfaces.end(), ringb.begin(), ringb.end()); + auto ringc = fullPhiTestSurfacesEC(30, 0, 0, 20); + surfaces.insert(surfaces.end(), ringc.begin(), ringc.end()); + draw_surfaces(surfaces, "LayerCreator_createDiscLayer_EC_1.obj"); + + ProtoLayer pl(tgContext, surfaces); + pl.minZ = -10; + pl.maxZ = 10; + pl.minR = 5; + pl.maxR = 25; + std::shared_ptr<DiscLayer> layer = std::dynamic_pointer_cast<DiscLayer>( + p_LC->discLayer(tgContext, surfaces, equidistant, equidistant, pl)); + CHECK_CLOSE_REL(layer->thickness(), 20, 1e-3); + const RadialBounds* bounds = + dynamic_cast<const RadialBounds*>(&layer->bounds()); + CHECK_CLOSE_REL(bounds->rMin(), 5, 1e-3); + CHECK_CLOSE_REL(bounds->rMax(), 25, 1e-3); + BOOST_CHECK(checkBinning(tgContext, *layer->surfaceArray())); + auto axes = layer->surfaceArray()->getAxes(); + BOOST_CHECK_EQUAL(axes.at(0)->getNBins(), 3); + BOOST_CHECK_EQUAL(axes.at(1)->getNBins(), 30); + CHECK_CLOSE_REL(axes.at(0)->getMin(), 5, 1e-3); + CHECK_CLOSE_REL(axes.at(0)->getMax(), 25, 1e-3); + CHECK_CLOSE_REL(axes.at(1)->getMin(), -M_PI, 1e-3); + CHECK_CLOSE_REL(axes.at(1)->getMax(), M_PI, 1e-3); + checkBinContentSize(layer->surfaceArray(), 1); + + // check that it's applying a rotation transform to improve phi binning + // BOOST_CHECK_NE(bu->transform(), nullptr); + // double actAngle = ((*bu->transform()) * Vector3D(1, 0, 0)).phi(); + // double expAngle = -2 * M_PI / 30 / 2.; + // CHECK_CLOSE_REL(actAngle, expAngle, 1e-3); + + double envMinR = 1, envMaxR = 1, envZ = 5; + size_t nBinsR = 3, nBinsPhi = 30; + ProtoLayer pl2(tgContext, surfaces); + pl2.envR = {envMinR, envMaxR}; + pl2.envZ = {envZ, envZ}; + layer = std::dynamic_pointer_cast<DiscLayer>( + p_LC->discLayer(tgContext, surfaces, nBinsR, nBinsPhi, pl2)); + + double rMin = 8, rMax = 22.0227; + CHECK_CLOSE_REL(layer->thickness(), 0.4 + 2 * envZ, 1e-3); + bounds = dynamic_cast<const RadialBounds*>(&layer->bounds()); + CHECK_CLOSE_REL(bounds->rMin(), rMin - envMinR, 1e-3); + CHECK_CLOSE_REL(bounds->rMax(), rMax + envMaxR, 1e-3); + BOOST_CHECK(checkBinning(tgContext, *layer->surfaceArray())); + axes = layer->surfaceArray()->getAxes(); + BOOST_CHECK_EQUAL(axes.at(0)->getNBins(), nBinsR); + BOOST_CHECK_EQUAL(axes.at(1)->getNBins(), nBinsPhi); + CHECK_CLOSE_REL(axes.at(0)->getMin(), rMin, 1e-3); + CHECK_CLOSE_REL(axes.at(0)->getMax(), rMax, 1e-3); + CHECK_CLOSE_REL(axes.at(1)->getMin(), -M_PI, 1e-3); + CHECK_CLOSE_REL(axes.at(1)->getMax(), M_PI, 1e-3); + checkBinContentSize(layer->surfaceArray(), 1); + + // check that it's applying a rotation transform to improve phi binning + // BOOST_CHECK_NE(bu->transform(), nullptr); + // actAngle = ((*bu->transform()) * Vector3D(1, 0, 0)).phi(); + // expAngle = -2 * M_PI / 30 / 2.; + // CHECK_CLOSE_REL(actAngle, expAngle, 1e-3); + + layer = std::dynamic_pointer_cast<DiscLayer>( + p_LC->discLayer(tgContext, surfaces, equidistant, equidistant, pl2)); + CHECK_CLOSE_REL(layer->thickness(), 0.4 + 2 * envZ, 1e-3); + bounds = dynamic_cast<const RadialBounds*>(&layer->bounds()); + CHECK_CLOSE_REL(bounds->rMin(), rMin - envMinR, 1e-3); + CHECK_CLOSE_REL(bounds->rMax(), rMax + envMaxR, 1e-3); + BOOST_CHECK(checkBinning(tgContext, *layer->surfaceArray())); + axes = layer->surfaceArray()->getAxes(); + BOOST_CHECK_EQUAL(axes.at(0)->getNBins(), nBinsR); + BOOST_CHECK_EQUAL(axes.at(1)->getNBins(), nBinsPhi); + CHECK_CLOSE_REL(axes.at(0)->getMin(), rMin, 1e-3); + CHECK_CLOSE_REL(axes.at(0)->getMax(), rMax, 1e-3); + CHECK_CLOSE_REL(axes.at(1)->getMin(), -M_PI, 1e-3); + CHECK_CLOSE_REL(axes.at(1)->getMax(), M_PI, 1e-3); + checkBinContentSize(layer->surfaceArray(), 1); + + // check that it's applying a rotation transform to improve phi binning + // BOOST_CHECK_NE(bu->transform(), nullptr); + // actAngle = ((*bu->transform()) * Vector3D(1, 0, 0)).phi(); + // expAngle = -2 * M_PI / 30 / 2.; + // CHECK_CLOSE_REL(actAngle, expAngle, 1e-3); +} + +BOOST_FIXTURE_TEST_CASE(LayerCreator_barrelStagger, LayerCreatorFixture) { + auto barrel = makeBarrelStagger(30, 7, 0, M_PI / 9.); + auto brl = barrel.first; + draw_surfaces(brl, "LayerCreator_barrelStagger.obj"); + + double envR = 0, envZ = 0; + ProtoLayer pl(tgContext, brl); + pl.envR = {envR, envR}; + pl.envZ = {envZ, envZ}; + std::shared_ptr<CylinderLayer> layer = + std::dynamic_pointer_cast<CylinderLayer>( + p_LC->cylinderLayer(tgContext, brl, equidistant, equidistant, pl)); + + auto axes = layer->surfaceArray()->getAxes(); + BOOST_CHECK_EQUAL(axes.at(0)->getNBins(), 30); + BOOST_CHECK_EQUAL(axes.at(1)->getNBins(), 7); + + // check if binning is good! + for (const auto& pr : barrel.second) { + auto A = pr.first; + auto B = pr.second; + + // std::cout << A->center().phi() << " "; + // std::cout << B->center().phi() << std::endl; + // std::cout << "dPHi = " << A->center().phi() - B->center().phi() << + // std::endl; + + Vector3D ctr = A->binningPosition(tgContext, binR); + auto binContent = layer->surfaceArray()->at(ctr); + BOOST_CHECK_EQUAL(binContent.size(), 2); + std::set<const Surface*> act; + act.insert(binContent[0]); + act.insert(binContent[1]); + + std::set<const Surface*> exp; + exp.insert(A); + exp.insert(B); + BOOST_CHECK(exp == act); } - BOOST_AUTO_TEST_SUITE_END() + // checkBinning should also report everything is fine + checkBinning(tgContext, *layer->surfaceArray()); +} + +BOOST_AUTO_TEST_SUITE_END() } // namespace Test } // namespace Acts diff --git a/Tests/Core/Geometry/LayerStub.hpp b/Tests/Core/Geometry/LayerStub.hpp index 6804733a72494810c5a0e504c64edd1c52aad0f4..8873f89f73cd778b726fdb0d3a47c54f0816cc5b 100644 --- a/Tests/Core/Geometry/LayerStub.hpp +++ b/Tests/Core/Geometry/LayerStub.hpp @@ -14,53 +14,35 @@ namespace Acts { /// Note: Layer classes in general have a static 'create' factory method, but /// nothing /// in the baseclasses mandates this. -class LayerStub : virtual public SurfaceStub, public Layer -{ -public: +class LayerStub : virtual public SurfaceStub, public Layer { + public: /// constructor (deleted in Surface baseclass) LayerStub() = delete; /// copy constructor (deleted in Surface baseclass) LayerStub(const LayerStub& otherLayer) = delete; /// constructor with pointer to SurfaceArray (protected in Layer baseclass) - LayerStub(std::unique_ptr<SurfaceArray> surfaceArray, - double thickness = 0, - std::unique_ptr<ApproachDescriptor> ad = nullptr, - LayerType ltype = passive) - : SurfaceStub() - , Layer(std::move(surfaceArray), thickness, std::move(ad), ltype) - { - } + LayerStub(std::unique_ptr<SurfaceArray> surfaceArray, double thickness = 0, + std::unique_ptr<ApproachDescriptor> ad = nullptr, + LayerType ltype = passive) + : SurfaceStub(), + Layer(std::move(surfaceArray), thickness, std::move(ad), ltype) {} /// Destructor ~LayerStub() override {} /// Assignment is deleted in the Layer baseclass - LayerStub& - operator=(const LayerStub& lay) - = delete; + LayerStub& operator=(const LayerStub& lay) = delete; /// surfaceRepresentation is pure virtual in baseclass - const Surface& - surfaceRepresentation() const override - { - return (*this); - } + const Surface& surfaceRepresentation() const override { return (*this); } - Surface& - surfaceRepresentation() override - { - return (*this); - } + Surface& surfaceRepresentation() override { return (*this); } /// simply return true to show a method can be called on the constructed /// object - bool - constructedOk() const - { - return true; - } + bool constructedOk() const { return true; } /// Other methods have implementation in baseclass /// templated 'onLayer()' from baseclass ? }; -} \ No newline at end of file +} // namespace Acts \ No newline at end of file diff --git a/Tests/Core/Geometry/LayerTests.cpp b/Tests/Core/Geometry/LayerTests.cpp index eb096a50df9ea7f3ba47eac436c46bc41172afab..8e70ca753b39b898d92424e3f466e417d4b7584a 100644 --- a/Tests/Core/Geometry/LayerTests.cpp +++ b/Tests/Core/Geometry/LayerTests.cpp @@ -36,83 +36,79 @@ namespace Acts { namespace Test { - // Create a test context - GeometryContext tgContext = GeometryContext(); +// Create a test context +GeometryContext tgContext = GeometryContext(); - namespace Layers { +namespace Layers { - BOOST_AUTO_TEST_SUITE(Layers) +BOOST_AUTO_TEST_SUITE(Layers) - /// Unit test for creating compliant/non-compliant Layer object - BOOST_AUTO_TEST_CASE(LayerConstruction) - { - // Descendant Layer objects also inherit from Surface objects, which - // delete the default constructor - // - /// Minimum possible construction (default constructor is deleted) - LayerStub minallyConstructed(nullptr); - BOOST_CHECK(minallyConstructed.constructedOk()); - /// Need an approach descriptor for the next level of complexity: - std::vector<std::shared_ptr<const Surface>> aSurfaces{ - Surface::makeShared<SurfaceStub>(), - Surface::makeShared<SurfaceStub>()}; - std::unique_ptr<ApproachDescriptor> ad( - new GenericApproachDescriptor(aSurfaces)); - const double thickness(1.0); - LayerStub approachDescriptorConstructed( - nullptr, thickness, std::move(ad)); - /// Construction with (minimal) approach descriptor - BOOST_CHECK(approachDescriptorConstructed.constructedOk()); - // Copy construction is deleted - } +/// Unit test for creating compliant/non-compliant Layer object +BOOST_AUTO_TEST_CASE(LayerConstruction) { + // Descendant Layer objects also inherit from Surface objects, which + // delete the default constructor + // + /// Minimum possible construction (default constructor is deleted) + LayerStub minallyConstructed(nullptr); + BOOST_CHECK(minallyConstructed.constructedOk()); + /// Need an approach descriptor for the next level of complexity: + std::vector<std::shared_ptr<const Surface>> aSurfaces{ + Surface::makeShared<SurfaceStub>(), Surface::makeShared<SurfaceStub>()}; + std::unique_ptr<ApproachDescriptor> ad( + new GenericApproachDescriptor(aSurfaces)); + const double thickness(1.0); + LayerStub approachDescriptorConstructed(nullptr, thickness, std::move(ad)); + /// Construction with (minimal) approach descriptor + BOOST_CHECK(approachDescriptorConstructed.constructedOk()); + // Copy construction is deleted +} - /// Unit test for testing Layer properties - BOOST_AUTO_TEST_CASE(LayerProperties, *utf::expected_failures(1)) - { - // Make a dummy layer to play with - // bounds object, rectangle type - auto rBounds = std::make_shared<const RectangleBounds>(1., 1.); - /// Constructor with transform pointer - auto pNullTransform = std::make_shared<const Transform3D>(); - const std::vector<std::shared_ptr<const Surface>> aSurfaces{ - Surface::makeShared<PlaneSurface>(pNullTransform, rBounds), - Surface::makeShared<PlaneSurface>(pNullTransform, rBounds)}; - std::unique_ptr<ApproachDescriptor> ad( - new GenericApproachDescriptor(aSurfaces)); - auto adPtr = ad.get(); - const double thickness(1.0); - LayerStub layerStub(nullptr, thickness, std::move(ad)); - // - /// surfaceArray() - BOOST_CHECK_EQUAL(layerStub.surfaceArray(), nullptr); - /// thickness() - BOOST_CHECK_EQUAL(layerStub.thickness(), thickness); - // onLayer() is templated; can't find implementation! - /// isOnLayer() (delegates to the Surface 'isOnSurface()') - const Vector3D pos{0.0, 0.0, 0.0}; - const Vector3D pos2{100., 100., std::nan("")}; - BOOST_CHECK(layerStub.isOnLayer(tgContext, pos)); - // this should fail, but does not, but possibly my fault in SurfaceStub - // implementation: - BOOST_CHECK(!layerStub.isOnLayer(tgContext, pos2)); - /// approachDescriptor(), retrieved as a pointer. - BOOST_CHECK_EQUAL(layerStub.approachDescriptor(), adPtr); - const Vector3D gpos{0., 0., 1.0}; - const Vector3D direction{0., 0., -1.}; - /// nextLayer() - BOOST_CHECK(!(layerStub.nextLayer(tgContext, gpos, direction))); - /// trackingVolume() - BOOST_CHECK(!layerStub.trackingVolume()); - // BOOST_TEST_CHECKPOINT("Before ending test"); - // deletion results in "memory access violation at address: 0x00000071: no - // mapping at fault address" - // delete abstractVolumePtr; - /// layerType() - BOOST_CHECK_EQUAL(layerStub.layerType(), LayerType::passive); - } +/// Unit test for testing Layer properties +BOOST_AUTO_TEST_CASE(LayerProperties, *utf::expected_failures(1)) { + // Make a dummy layer to play with + // bounds object, rectangle type + auto rBounds = std::make_shared<const RectangleBounds>(1., 1.); + /// Constructor with transform pointer + auto pNullTransform = std::make_shared<const Transform3D>(); + const std::vector<std::shared_ptr<const Surface>> aSurfaces{ + Surface::makeShared<PlaneSurface>(pNullTransform, rBounds), + Surface::makeShared<PlaneSurface>(pNullTransform, rBounds)}; + std::unique_ptr<ApproachDescriptor> ad( + new GenericApproachDescriptor(aSurfaces)); + auto adPtr = ad.get(); + const double thickness(1.0); + LayerStub layerStub(nullptr, thickness, std::move(ad)); + // + /// surfaceArray() + BOOST_CHECK_EQUAL(layerStub.surfaceArray(), nullptr); + /// thickness() + BOOST_CHECK_EQUAL(layerStub.thickness(), thickness); + // onLayer() is templated; can't find implementation! + /// isOnLayer() (delegates to the Surface 'isOnSurface()') + const Vector3D pos{0.0, 0.0, 0.0}; + const Vector3D pos2{100., 100., std::nan("")}; + BOOST_CHECK(layerStub.isOnLayer(tgContext, pos)); + // this should fail, but does not, but possibly my fault in SurfaceStub + // implementation: + BOOST_CHECK(!layerStub.isOnLayer(tgContext, pos2)); + /// approachDescriptor(), retrieved as a pointer. + BOOST_CHECK_EQUAL(layerStub.approachDescriptor(), adPtr); + const Vector3D gpos{0., 0., 1.0}; + const Vector3D direction{0., 0., -1.}; + /// nextLayer() + BOOST_CHECK(!(layerStub.nextLayer(tgContext, gpos, direction))); + /// trackingVolume() + BOOST_CHECK(!layerStub.trackingVolume()); + // BOOST_TEST_CHECKPOINT("Before ending test"); + // deletion results in "memory access violation at address: 0x00000071: no + // mapping at fault address" + // delete abstractVolumePtr; + /// layerType() + BOOST_CHECK_EQUAL(layerStub.layerType(), LayerType::passive); +} - BOOST_AUTO_TEST_SUITE_END() - } // namespace Layers +BOOST_AUTO_TEST_SUITE_END() +} // namespace Layers } // namespace Test } // namespace Acts diff --git a/Tests/Core/Geometry/NavigationLayerTests.cpp b/Tests/Core/Geometry/NavigationLayerTests.cpp index e86aab6fae736537aad45b5e00ee74aecb6e1ed0..9a9d8dcd9815247d4385f0616c83951e2181eee2 100644 --- a/Tests/Core/Geometry/NavigationLayerTests.cpp +++ b/Tests/Core/Geometry/NavigationLayerTests.cpp @@ -30,57 +30,51 @@ namespace Acts { namespace Test { - // Create a test context - GeometryContext tgContext = GeometryContext(); +// Create a test context +GeometryContext tgContext = GeometryContext(); - namespace Layers { - BOOST_AUTO_TEST_SUITE(Layers) +namespace Layers { +BOOST_AUTO_TEST_SUITE(Layers) - /// Unit test for creating compliant/non-compliant NavigationLayer object - BOOST_AUTO_TEST_CASE(NavigationLayerConstruction) - { - // default constructor, copy and assignment are all deleted - std::shared_ptr<const Surface> pSurface - = Surface::makeShared<SurfaceStub>(); - auto pNavigationLayer = NavigationLayer::create(std::move(pSurface)); - BOOST_CHECK_EQUAL(pNavigationLayer->layerType(), LayerType::navigation); - // next level: with thickness - const double thickness = 0.1; - auto pSurface2 = Surface::makeShared<SurfaceStub>(); - auto pThickNavigationLayer - = NavigationLayer::create(std::move(pSurface2), thickness); - BOOST_CHECK_EQUAL(pThickNavigationLayer->layerType(), - LayerType::navigation); - } +/// Unit test for creating compliant/non-compliant NavigationLayer object +BOOST_AUTO_TEST_CASE(NavigationLayerConstruction) { + // default constructor, copy and assignment are all deleted + std::shared_ptr<const Surface> pSurface = Surface::makeShared<SurfaceStub>(); + auto pNavigationLayer = NavigationLayer::create(std::move(pSurface)); + BOOST_CHECK_EQUAL(pNavigationLayer->layerType(), LayerType::navigation); + // next level: with thickness + const double thickness = 0.1; + auto pSurface2 = Surface::makeShared<SurfaceStub>(); + auto pThickNavigationLayer = + NavigationLayer::create(std::move(pSurface2), thickness); + BOOST_CHECK_EQUAL(pThickNavigationLayer->layerType(), LayerType::navigation); +} - /// Unit test for testing NavigationLayer properties - BOOST_AUTO_TEST_CASE(NavigationLayerProperties, *utf::expected_failures(1)) - { - const double thickness = 0.1; - std::shared_ptr<const Surface> pSurface - = Surface::makeShared<SurfaceStub>(); - auto rawSurfacePtr = pSurface.get(); - auto pNavigationLayer - = NavigationLayer::create(std::move(pSurface), thickness); - BinningValue b{BinningValue::binZ}; - Vector3D origin{0., 0., 0.}; - // binningPosition(), needs a better test - BOOST_CHECK_EQUAL(pNavigationLayer->binningPosition(tgContext, b), - origin); - // surfaceRepresentation() [looks dangerous] - BOOST_CHECK_EQUAL(rawSurfacePtr, - &(pNavigationLayer->surfaceRepresentation())); - // isOnLayer() - BOOST_CHECK(pNavigationLayer->isOnLayer(tgContext, origin, true)); - // isOnLayer() - Vector3D crazyPosition{1000., 10000., std::nan("")}; - BOOST_CHECK(!pNavigationLayer->isOnLayer(tgContext, crazyPosition, true)); - // resolve() - BOOST_CHECK(!pNavigationLayer->resolve(true, true, true)); - } +/// Unit test for testing NavigationLayer properties +BOOST_AUTO_TEST_CASE(NavigationLayerProperties, *utf::expected_failures(1)) { + const double thickness = 0.1; + std::shared_ptr<const Surface> pSurface = Surface::makeShared<SurfaceStub>(); + auto rawSurfacePtr = pSurface.get(); + auto pNavigationLayer = + NavigationLayer::create(std::move(pSurface), thickness); + BinningValue b{BinningValue::binZ}; + Vector3D origin{0., 0., 0.}; + // binningPosition(), needs a better test + BOOST_CHECK_EQUAL(pNavigationLayer->binningPosition(tgContext, b), origin); + // surfaceRepresentation() [looks dangerous] + BOOST_CHECK_EQUAL(rawSurfacePtr, + &(pNavigationLayer->surfaceRepresentation())); + // isOnLayer() + BOOST_CHECK(pNavigationLayer->isOnLayer(tgContext, origin, true)); + // isOnLayer() + Vector3D crazyPosition{1000., 10000., std::nan("")}; + BOOST_CHECK(!pNavigationLayer->isOnLayer(tgContext, crazyPosition, true)); + // resolve() + BOOST_CHECK(!pNavigationLayer->resolve(true, true, true)); +} - BOOST_AUTO_TEST_SUITE_END() - } // namespace Layers +BOOST_AUTO_TEST_SUITE_END() +} // namespace Layers } // namespace Test } // namespace Acts diff --git a/Tests/Core/Geometry/PlaneLayerTests.cpp b/Tests/Core/Geometry/PlaneLayerTests.cpp index c321257a7159220d5e3e82953981b1e69ab13486..1d1bb49cc3ae509c4a904164c10ed3424c489d4a 100644 --- a/Tests/Core/Geometry/PlaneLayerTests.cpp +++ b/Tests/Core/Geometry/PlaneLayerTests.cpp @@ -36,84 +36,73 @@ namespace Acts { namespace Test { - // Create a test context - GeometryContext tgContext = GeometryContext(); +// Create a test context +GeometryContext tgContext = GeometryContext(); - namespace Layers { - BOOST_AUTO_TEST_SUITE(Layers) +namespace Layers { +BOOST_AUTO_TEST_SUITE(Layers) - /// Unit test for creating compliant/non-compliant PlaneLayer object - BOOST_AUTO_TEST_CASE(PlaneLayerConstruction) - { - // default constructor, copy and assignment are all deleted - // minimally need a Transform3D and a PlanarBounds object (e.g. - // RectangleBounds) to construct - Translation3D translation{0., 1., 2.}; - auto pTransform = std::make_shared<const Transform3D>(translation); - const double halfX(10.), halfY(5.); // 20 x 10 rectangle - auto pRectangle = std::make_shared<const RectangleBounds>(halfX, halfY); - auto pPlaneLayer = PlaneLayer::create(pTransform, pRectangle); - BOOST_CHECK_EQUAL(pPlaneLayer->layerType(), LayerType::active); - // next level: need an array of Surfaces; - // bounds object, rectangle type - auto rBounds = std::make_shared<const RectangleBounds>(1., 1.); - /// Constructor with transform pointer - auto pNullTransform = std::make_shared<const Transform3D>(); - const std::vector<std::shared_ptr<const Surface>> aSurfaces{ - Surface::makeShared<PlaneSurface>(pNullTransform, rBounds), - Surface::makeShared<PlaneSurface>(pNullTransform, rBounds)}; - const double thickness(1.0); - SurfaceArrayCreator sac; - size_t binsX(2), binsY(4); - auto pSurfaceArray - = sac.surfaceArrayOnPlane(tgContext, aSurfaces, binsX, binsY); - auto pPlaneLayerFromSurfaces = PlaneLayer::create( - pTransform, pRectangle, std::move(pSurfaceArray)); - BOOST_CHECK_EQUAL(pPlaneLayerFromSurfaces->layerType(), - LayerType::active); - // construct with thickness: - auto pPlaneLayerWithThickness = PlaneLayer::create( - pTransform, pRectangle, std::move(pSurfaceArray), thickness); - BOOST_CHECK_EQUAL(pPlaneLayerWithThickness->thickness(), thickness); - // with an approach descriptor... - std::unique_ptr<ApproachDescriptor> ad( - new GenericApproachDescriptor(aSurfaces)); - auto adPtr = ad.get(); - auto pPlaneLayerWithApproachDescriptor - = PlaneLayer::create(pTransform, - pRectangle, - std::move(pSurfaceArray), - thickness, - std::move(ad)); - BOOST_CHECK_EQUAL(pPlaneLayerWithApproachDescriptor->approachDescriptor(), - adPtr); - // with the layerType specified... - auto pPlaneLayerWithLayerType - = PlaneLayer::create(pTransform, - pRectangle, - std::move(pSurfaceArray), - thickness, - std::move(ad), - LayerType::passive); - BOOST_CHECK_EQUAL(pPlaneLayerWithLayerType->layerType(), - LayerType::passive); - } +/// Unit test for creating compliant/non-compliant PlaneLayer object +BOOST_AUTO_TEST_CASE(PlaneLayerConstruction) { + // default constructor, copy and assignment are all deleted + // minimally need a Transform3D and a PlanarBounds object (e.g. + // RectangleBounds) to construct + Translation3D translation{0., 1., 2.}; + auto pTransform = std::make_shared<const Transform3D>(translation); + const double halfX(10.), halfY(5.); // 20 x 10 rectangle + auto pRectangle = std::make_shared<const RectangleBounds>(halfX, halfY); + auto pPlaneLayer = PlaneLayer::create(pTransform, pRectangle); + BOOST_CHECK_EQUAL(pPlaneLayer->layerType(), LayerType::active); + // next level: need an array of Surfaces; + // bounds object, rectangle type + auto rBounds = std::make_shared<const RectangleBounds>(1., 1.); + /// Constructor with transform pointer + auto pNullTransform = std::make_shared<const Transform3D>(); + const std::vector<std::shared_ptr<const Surface>> aSurfaces{ + Surface::makeShared<PlaneSurface>(pNullTransform, rBounds), + Surface::makeShared<PlaneSurface>(pNullTransform, rBounds)}; + const double thickness(1.0); + SurfaceArrayCreator sac; + size_t binsX(2), binsY(4); + auto pSurfaceArray = + sac.surfaceArrayOnPlane(tgContext, aSurfaces, binsX, binsY); + auto pPlaneLayerFromSurfaces = + PlaneLayer::create(pTransform, pRectangle, std::move(pSurfaceArray)); + BOOST_CHECK_EQUAL(pPlaneLayerFromSurfaces->layerType(), LayerType::active); + // construct with thickness: + auto pPlaneLayerWithThickness = PlaneLayer::create( + pTransform, pRectangle, std::move(pSurfaceArray), thickness); + BOOST_CHECK_EQUAL(pPlaneLayerWithThickness->thickness(), thickness); + // with an approach descriptor... + std::unique_ptr<ApproachDescriptor> ad( + new GenericApproachDescriptor(aSurfaces)); + auto adPtr = ad.get(); + auto pPlaneLayerWithApproachDescriptor = + PlaneLayer::create(pTransform, pRectangle, std::move(pSurfaceArray), + thickness, std::move(ad)); + BOOST_CHECK_EQUAL(pPlaneLayerWithApproachDescriptor->approachDescriptor(), + adPtr); + // with the layerType specified... + auto pPlaneLayerWithLayerType = + PlaneLayer::create(pTransform, pRectangle, std::move(pSurfaceArray), + thickness, std::move(ad), LayerType::passive); + BOOST_CHECK_EQUAL(pPlaneLayerWithLayerType->layerType(), LayerType::passive); +} - /// Unit test for testing Layer properties - BOOST_AUTO_TEST_CASE(PlaneLayerProperties /*, *utf::expected_failures(1)*/) - { - Translation3D translation{0., 1., 2.}; - auto pTransform = std::make_shared<const Transform3D>(translation); - const double halfX(10.), halfY(5.); // 20 x 10 rectangle - auto pRectangle = std::make_shared<const RectangleBounds>(halfX, halfY); - auto pPlaneLayer = PlaneLayer::create(pTransform, pRectangle); - // auto planeSurface = pPlaneLayer->surfaceRepresentation(); - BOOST_CHECK_EQUAL(pPlaneLayer->surfaceRepresentation().name(), - std::string("Acts::PlaneSurface")); - } +/// Unit test for testing Layer properties +BOOST_AUTO_TEST_CASE(PlaneLayerProperties /*, *utf::expected_failures(1)*/) { + Translation3D translation{0., 1., 2.}; + auto pTransform = std::make_shared<const Transform3D>(translation); + const double halfX(10.), halfY(5.); // 20 x 10 rectangle + auto pRectangle = std::make_shared<const RectangleBounds>(halfX, halfY); + auto pPlaneLayer = PlaneLayer::create(pTransform, pRectangle); + // auto planeSurface = pPlaneLayer->surfaceRepresentation(); + BOOST_CHECK_EQUAL(pPlaneLayer->surfaceRepresentation().name(), + std::string("Acts::PlaneSurface")); +} - BOOST_AUTO_TEST_SUITE_END() - } // namespace Layers +BOOST_AUTO_TEST_SUITE_END() +} // namespace Layers } // namespace Test } // namespace Acts diff --git a/Tests/Core/Geometry/ProtoLayerTests.cpp b/Tests/Core/Geometry/ProtoLayerTests.cpp index 253c3dc585ca87a5f6540a865d9021de6f657414..609dafb845b936c4d35b3b34c7565b48d8d5590c 100644 --- a/Tests/Core/Geometry/ProtoLayerTests.cpp +++ b/Tests/Core/Geometry/ProtoLayerTests.cpp @@ -21,36 +21,35 @@ namespace Acts { namespace Test { - namespace Layers { - BOOST_AUTO_TEST_SUITE(Layers) +namespace Layers { +BOOST_AUTO_TEST_SUITE(Layers) - BOOST_AUTO_TEST_CASE(ProtoLayer_radialDistance) - { - ProtoLayer pl; +BOOST_AUTO_TEST_CASE(ProtoLayer_radialDistance) { + ProtoLayer pl; - Vector3D p1(10, 0, 0); - Vector3D p2(0, 10, 0); - CHECK_CLOSE_REL(pl.radialDistance(p1, p2), sqrt(50), 1e-6); + Vector3D p1(10, 0, 0); + Vector3D p2(0, 10, 0); + CHECK_CLOSE_REL(pl.radialDistance(p1, p2), sqrt(50), 1e-6); - Vector3D p3(-5, 5, 0); - Vector3D p4(5, 5, 0); - CHECK_CLOSE_REL(pl.radialDistance(p3, p4), 5, 1e-6); + Vector3D p3(-5, 5, 0); + Vector3D p4(5, 5, 0); + CHECK_CLOSE_REL(pl.radialDistance(p3, p4), 5, 1e-6); - Vector3D p5(6, 6, 0); - Vector3D p6(8, 9, 0); - CHECK_CLOSE_REL(pl.radialDistance(p5, p6), sqrt(6 * 6 + 6 * 6), 1e-6); + Vector3D p5(6, 6, 0); + Vector3D p6(8, 9, 0); + CHECK_CLOSE_REL(pl.radialDistance(p5, p6), sqrt(6 * 6 + 6 * 6), 1e-6); - Vector3D p7(0, 10, 0); - Vector3D p8(5, 5, 0); - CHECK_CLOSE_REL(pl.radialDistance(p7, p8), sqrt(50), 1e-6); + Vector3D p7(0, 10, 0); + Vector3D p8(5, 5, 0); + CHECK_CLOSE_REL(pl.radialDistance(p7, p8), sqrt(50), 1e-6); - Vector3D p9(13, 2, 0); - Vector3D p10(13, -2, 0); - CHECK_CLOSE_REL(pl.radialDistance(p9, p10), 13, 1e-6); - } + Vector3D p9(13, 2, 0); + Vector3D p10(13, -2, 0); + CHECK_CLOSE_REL(pl.radialDistance(p9, p10), 13, 1e-6); +} - BOOST_AUTO_TEST_SUITE_END() - } // namespace Layers +BOOST_AUTO_TEST_SUITE_END() +} // namespace Layers } // namespace Test } // namespace Acts diff --git a/Tests/Core/Geometry/SimpleGeometryTests.cpp b/Tests/Core/Geometry/SimpleGeometryTests.cpp index 49d16936bb9fe6a6ab822f6fea13ea6fa126daf3..71dcbda8e8d98bd9421bd34a78fdf79cc8abf2d1 100644 --- a/Tests/Core/Geometry/SimpleGeometryTests.cpp +++ b/Tests/Core/Geometry/SimpleGeometryTests.cpp @@ -24,104 +24,99 @@ namespace Acts { namespace Test { - // Create a test context - GeometryContext tgContext = GeometryContext(); +// Create a test context +GeometryContext tgContext = GeometryContext(); - /// @brief Unit test for a three layer detector parameters - /// Testing the Tool chain in the geometry building process - /// - BOOST_AUTO_TEST_CASE(SimpleGeometryTest) - { +/// @brief Unit test for a three layer detector parameters +/// Testing the Tool chain in the geometry building process +/// +BOOST_AUTO_TEST_CASE(SimpleGeometryTest) { + Logging::Level surfaceLLevel = Logging::INFO; + Logging::Level layerLLevel = Logging::INFO; + Logging::Level volumeLLevel = Logging::INFO; - Logging::Level surfaceLLevel = Logging::INFO; - Logging::Level layerLLevel = Logging::INFO; - Logging::Level volumeLLevel = Logging::INFO; + // configure surface array creator + SurfaceArrayCreator::Config sacConfig; + auto surfaceArrayCreator = std::make_shared<const SurfaceArrayCreator>( + sacConfig, getDefaultLogger("SurfaceArrayCreator", surfaceLLevel)); + // configure the layer creator that uses the surface array creator + LayerCreator::Config lcConfig; + lcConfig.surfaceArrayCreator = surfaceArrayCreator; + auto layerCreator = std::make_shared<const LayerCreator>( + lcConfig, getDefaultLogger("LayerCreator", layerLLevel)); + // configure the layer array creator + LayerArrayCreator::Config lacConfig; + auto layerArrayCreator = std::make_shared<const LayerArrayCreator>( + lacConfig, getDefaultLogger("LayerArrayCreator", layerLLevel)); - // configure surface array creator - SurfaceArrayCreator::Config sacConfig; - auto surfaceArrayCreator = std::make_shared<const SurfaceArrayCreator>( - sacConfig, getDefaultLogger("SurfaceArrayCreator", surfaceLLevel)); - // configure the layer creator that uses the surface array creator - LayerCreator::Config lcConfig; - lcConfig.surfaceArrayCreator = surfaceArrayCreator; - auto layerCreator = std::make_shared<const LayerCreator>( - lcConfig, getDefaultLogger("LayerCreator", layerLLevel)); - // configure the layer array creator - LayerArrayCreator::Config lacConfig; - auto layerArrayCreator = std::make_shared<const LayerArrayCreator>( - lacConfig, getDefaultLogger("LayerArrayCreator", layerLLevel)); + // tracking volume array creator + TrackingVolumeArrayCreator::Config tvacConfig; + auto tVolumeArrayCreator = std::make_shared<const TrackingVolumeArrayCreator>( + tvacConfig, getDefaultLogger("TrackingVolumeArrayCreator", volumeLLevel)); + // configure the cylinder volume helper + CylinderVolumeHelper::Config cvhConfig; + cvhConfig.layerArrayCreator = layerArrayCreator; + cvhConfig.trackingVolumeArrayCreator = tVolumeArrayCreator; + auto cylinderVolumeHelper = std::make_shared<const CylinderVolumeHelper>( + cvhConfig, getDefaultLogger("CylinderVolumeHelper", volumeLLevel)); - // tracking volume array creator - TrackingVolumeArrayCreator::Config tvacConfig; - auto tVolumeArrayCreator - = std::make_shared<const TrackingVolumeArrayCreator>( - tvacConfig, - getDefaultLogger("TrackingVolumeArrayCreator", volumeLLevel)); - // configure the cylinder volume helper - CylinderVolumeHelper::Config cvhConfig; - cvhConfig.layerArrayCreator = layerArrayCreator; - cvhConfig.trackingVolumeArrayCreator = tVolumeArrayCreator; - auto cylinderVolumeHelper = std::make_shared<const CylinderVolumeHelper>( - cvhConfig, getDefaultLogger("CylinderVolumeHelper", volumeLLevel)); + // ----------------- build a beam pipe ----------------------------------- + PassiveLayerBuilder::Config bplConfig; + bplConfig.layerIdentification = "BeamPipe"; + bplConfig.centralLayerRadii = std::vector<double>(1, 3. * units::_mm); + bplConfig.centralLayerHalflengthZ = std::vector<double>(1, 40. * units::_mm); + bplConfig.centralLayerThickness = std::vector<double>(1, 0.8 * units::_mm); + auto beamPipeBuilder = std::make_shared<const PassiveLayerBuilder>( + bplConfig, getDefaultLogger("BeamPipeLayerBuilder", layerLLevel)); + // create the volume for the beam pipe + CylinderVolumeBuilder::Config bpvConfig; + bpvConfig.trackingVolumeHelper = cylinderVolumeHelper; + bpvConfig.volumeName = "BeamPipe"; + bpvConfig.layerBuilder = beamPipeBuilder; + bpvConfig.layerEnvelopeR = {1. * units::_mm, 1. * units::_mm}; + bpvConfig.buildToRadiusZero = true; + bpvConfig.volumeSignature = 0; + auto beamPipeVolumeBuilder = std::make_shared<const CylinderVolumeBuilder>( + bpvConfig, getDefaultLogger("BeamPipeVolumeBuilder", volumeLLevel)); - // ----------------- build a beam pipe ----------------------------------- - PassiveLayerBuilder::Config bplConfig; - bplConfig.layerIdentification = "BeamPipe"; - bplConfig.centralLayerRadii = std::vector<double>(1, 3. * units::_mm); - bplConfig.centralLayerHalflengthZ - = std::vector<double>(1, 40. * units::_mm); - bplConfig.centralLayerThickness = std::vector<double>(1, 0.8 * units::_mm); - auto beamPipeBuilder = std::make_shared<const PassiveLayerBuilder>( - bplConfig, getDefaultLogger("BeamPipeLayerBuilder", layerLLevel)); - // create the volume for the beam pipe - CylinderVolumeBuilder::Config bpvConfig; - bpvConfig.trackingVolumeHelper = cylinderVolumeHelper; - bpvConfig.volumeName = "BeamPipe"; - bpvConfig.layerBuilder = beamPipeBuilder; - bpvConfig.layerEnvelopeR = {1. * units::_mm, 1. * units::_mm}; - bpvConfig.buildToRadiusZero = true; - bpvConfig.volumeSignature = 0; - auto beamPipeVolumeBuilder = std::make_shared<const CylinderVolumeBuilder>( - bpvConfig, getDefaultLogger("BeamPipeVolumeBuilder", volumeLLevel)); + PassiveLayerBuilder::Config layerBuilderConfig; + layerBuilderConfig.layerIdentification = "CentralBarrel"; + layerBuilderConfig.centralLayerRadii = {10. * units::_mm, 20. * units::_mm, + 30. * units::_mm}; + layerBuilderConfig.centralLayerHalflengthZ = { + 40. * units::_mm, 40. * units::_mm, 40. * units::_mm}; + layerBuilderConfig.centralLayerThickness = {1. * units::_mm, 1. * units::_mm, + 1. * units::_mm}; + auto layerBuilder = std::make_shared<const PassiveLayerBuilder>( + layerBuilderConfig, + getDefaultLogger("CentralBarrelBuilder", layerLLevel)); + // create the volume for the central barrel + CylinderVolumeBuilder::Config cvbConfig; + cvbConfig.trackingVolumeHelper = cylinderVolumeHelper; + cvbConfig.volumeName = "CentralBarrel"; + cvbConfig.layerBuilder = layerBuilder; + cvbConfig.layerEnvelopeR = {1. * units::_mm, 1. * units::_mm}; + cvbConfig.buildToRadiusZero = false; + cvbConfig.volumeSignature = 0; + auto centralVolumeBuilder = std::make_shared<const CylinderVolumeBuilder>( + cvbConfig, getDefaultLogger("CentralVolumeBuilder", volumeLLevel)); - PassiveLayerBuilder::Config layerBuilderConfig; - layerBuilderConfig.layerIdentification = "CentralBarrel"; - layerBuilderConfig.centralLayerRadii - = {10. * units::_mm, 20. * units::_mm, 30. * units::_mm}; - layerBuilderConfig.centralLayerHalflengthZ - = {40. * units::_mm, 40. * units::_mm, 40. * units::_mm}; - layerBuilderConfig.centralLayerThickness - = {1. * units::_mm, 1. * units::_mm, 1. * units::_mm}; - auto layerBuilder = std::make_shared<const PassiveLayerBuilder>( - layerBuilderConfig, - getDefaultLogger("CentralBarrelBuilder", layerLLevel)); - // create the volume for the central barrel - CylinderVolumeBuilder::Config cvbConfig; - cvbConfig.trackingVolumeHelper = cylinderVolumeHelper; - cvbConfig.volumeName = "CentralBarrel"; - cvbConfig.layerBuilder = layerBuilder; - cvbConfig.layerEnvelopeR = {1. * units::_mm, 1. * units::_mm}; - cvbConfig.buildToRadiusZero = false; - cvbConfig.volumeSignature = 0; - auto centralVolumeBuilder = std::make_shared<const CylinderVolumeBuilder>( - cvbConfig, getDefaultLogger("CentralVolumeBuilder", volumeLLevel)); + // Make the TrackingGeometry Builder + TrackingGeometryBuilder::Config tgbConfig; + tgbConfig.trackingVolumeBuilders.push_back( + [=](const auto& context, const auto& inner, const auto&) { + return beamPipeVolumeBuilder->trackingVolume(context, inner); + }); + tgbConfig.trackingVolumeBuilders.push_back( + [=](const auto& context, const auto& inner, const auto&) { + return centralVolumeBuilder->trackingVolume(context, inner); + }); + tgbConfig.trackingVolumeHelper = cylinderVolumeHelper; - // Make the TrackingGeometry Builder - TrackingGeometryBuilder::Config tgbConfig; - tgbConfig.trackingVolumeBuilders.push_back( - [=](const auto& context, const auto& inner, const auto&) { - return beamPipeVolumeBuilder->trackingVolume(context, inner); - }); - tgbConfig.trackingVolumeBuilders.push_back( - [=](const auto& context, const auto& inner, const auto&) { - return centralVolumeBuilder->trackingVolume(context, inner); - }); - tgbConfig.trackingVolumeHelper = cylinderVolumeHelper; + TrackingGeometryBuilder tgBuilder(tgbConfig); + auto tGeometry = tgBuilder.trackingGeometry(tgContext); - TrackingGeometryBuilder tgBuilder(tgbConfig); - auto tGeometry = tgBuilder.trackingGeometry(tgContext); - - BOOST_CHECK(tGeometry != nullptr); - } + BOOST_CHECK(tGeometry != nullptr); +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/Geometry/SurfaceArrayCreatorTests.cpp b/Tests/Core/Geometry/SurfaceArrayCreatorTests.cpp index ac2939be5dae45b55c64984f7b6df9aaabd5c594..440b8bcddc3d4019456c4402863441d73c2e4e46 100644 --- a/Tests/Core/Geometry/SurfaceArrayCreatorTests.cpp +++ b/Tests/Core/Geometry/SurfaceArrayCreatorTests.cpp @@ -25,118 +25,173 @@ #include "Acts/Utilities/Definitions.hpp" #include "Acts/Geometry/GeometryContext.hpp" -using Acts::VectorHelpers::phi; using Acts::VectorHelpers::perp; +using Acts::VectorHelpers::phi; namespace bdata = boost::unit_test::data; -namespace tt = boost::test_tools; +namespace tt = boost::test_tools; namespace Acts { namespace Test { - // Create a test context - GeometryContext tgContext = GeometryContext(); +// Create a test context +GeometryContext tgContext = GeometryContext(); -#define CHECK_ROTATION_ANGLE(t, a, tolerance) \ - { \ - Vector3D v = (*t) * Vector3D(1, 0, 0); \ - CHECK_CLOSE_ABS(phi(v), (a), tolerance); \ +#define CHECK_ROTATION_ANGLE(t, a, tolerance) \ + { \ + Vector3D v = (*t) * Vector3D(1, 0, 0); \ + CHECK_CLOSE_ABS(phi(v), (a), tolerance); \ } - using SrfVec = std::vector<std::shared_ptr<const Surface>>; +using SrfVec = std::vector<std::shared_ptr<const Surface>>; - struct SurfaceArrayCreatorFixture - { - SurfaceArrayCreator m_SAC; - std::vector<std::shared_ptr<const Surface>> m_surfaces; +struct SurfaceArrayCreatorFixture { + SurfaceArrayCreator m_SAC; + std::vector<std::shared_ptr<const Surface>> m_surfaces; - SurfaceArrayCreatorFixture() + SurfaceArrayCreatorFixture() : m_SAC(SurfaceArrayCreator::Config(), Acts::getDefaultLogger("SurfaceArrayCreator", - Acts::Logging::VERBOSE)) - { - BOOST_TEST_MESSAGE("setup fixture"); - } - ~SurfaceArrayCreatorFixture() { BOOST_TEST_MESSAGE("teardown fixture"); } + Acts::Logging::VERBOSE)) { + BOOST_TEST_MESSAGE("setup fixture"); + } + ~SurfaceArrayCreatorFixture() { BOOST_TEST_MESSAGE("teardown fixture"); } - template <typename... Args> - SurfaceArrayCreator::ProtoAxis - createEquidistantAxis(Args&&... args) - { - return m_SAC.createEquidistantAxis(std::forward<Args>(args)...); - } + template <typename... Args> + SurfaceArrayCreator::ProtoAxis createEquidistantAxis(Args&&... args) { + return m_SAC.createEquidistantAxis(std::forward<Args>(args)...); + } - template <typename... Args> - SurfaceArrayCreator::ProtoAxis - createVariableAxis(Args&&... args) - { - return m_SAC.createVariableAxis(std::forward<Args>(args)...); - } + template <typename... Args> + SurfaceArrayCreator::ProtoAxis createVariableAxis(Args&&... args) { + return m_SAC.createVariableAxis(std::forward<Args>(args)...); + } + + template <detail::AxisBoundaryType bdtA, detail::AxisBoundaryType bdtB, + typename... Args> + std::unique_ptr<SurfaceArray::ISurfaceGridLookup> makeSurfaceGridLookup2D( + Args&&... args) { + return m_SAC.makeSurfaceGridLookup2D<bdtA, bdtB>( + std::forward<Args>(args)...); + } - template <detail::AxisBoundaryType bdtA, - detail::AxisBoundaryType bdtB, - typename... Args> - std::unique_ptr<SurfaceArray::ISurfaceGridLookup> - makeSurfaceGridLookup2D(Args&&... args) - { - return m_SAC.makeSurfaceGridLookup2D<bdtA, bdtB>( - std::forward<Args>(args)...); + SrfVec fullPhiTestSurfacesEC(size_t n = 10, double shift = 0, + double zbase = 0, double r = 10, double w = 2, + double h = 1) { + SrfVec res; + // TODO: The test is extremely numerically unstable in the face of upward + // rounding in this multiplication and division. Find out why. + double phiStep = 2 * M_PI / n; + for (size_t i = 0; i < n; ++i) { + double z = zbase + ((i % 2 == 0) ? 1 : -1) * 0.2; + double phi = std::fma(i, phiStep, shift); + + Transform3D trans; + trans.setIdentity(); + trans.rotate(Eigen::AngleAxisd(phi, Vector3D(0, 0, 1))); + trans.translate(Vector3D(r, 0, z)); + + auto bounds = std::make_shared<const RectangleBounds>(w, h); + + auto transptr = std::make_shared<const Transform3D>(trans); + std::shared_ptr<Surface> srf = + Surface::makeShared<PlaneSurface>(transptr, bounds); + + res.push_back(srf); + m_surfaces.push_back( + std::move(srf)); // keep shared, will get destroyed at the end } - SrfVec - fullPhiTestSurfacesEC(size_t n = 10, - double shift = 0, - double zbase = 0, - double r = 10, - double w = 2, - double h = 1) - { - - SrfVec res; - // TODO: The test is extremely numerically unstable in the face of upward - // rounding in this multiplication and division. Find out why. - double phiStep = 2 * M_PI / n; - for (size_t i = 0; i < n; ++i) { - double z = zbase + ((i % 2 == 0) ? 1 : -1) * 0.2; - double phi = std::fma(i, phiStep, shift); + return res; + } - Transform3D trans; - trans.setIdentity(); - trans.rotate(Eigen::AngleAxisd(phi, Vector3D(0, 0, 1))); - trans.translate(Vector3D(r, 0, z)); + SrfVec fullPhiTestSurfacesBRL(size_t n = 10, double shift = 0, + double zbase = 0, double incl = M_PI / 9., + double w = 2, double h = 1.5) { + SrfVec res; + // TODO: The test is extremely numerically unstable in the face of upward + // rounding in this multiplication and division. Find out why. + double phiStep = 2 * M_PI / n; + for (size_t i = 0; i < n; ++i) { + double z = zbase; + double phi = std::fma(i, phiStep, shift); + + Transform3D trans; + trans.setIdentity(); + trans.rotate(Eigen::AngleAxisd(phi, Vector3D(0, 0, 1))); + trans.translate(Vector3D(10, 0, z)); + trans.rotate(Eigen::AngleAxisd(incl, Vector3D(0, 0, 1))); + trans.rotate(Eigen::AngleAxisd(M_PI / 2., Vector3D(0, 1, 0))); + + auto bounds = std::make_shared<const RectangleBounds>(w, h); + + auto transptr = std::make_shared<const Transform3D>(trans); + std::shared_ptr<Surface> srf = + Surface::makeShared<PlaneSurface>(transptr, bounds); + + res.push_back(srf); + m_surfaces.push_back( + std::move(srf)); // keep shared, will get destroyed at the end + } - auto bounds = std::make_shared<const RectangleBounds>(w, h); + return res; + } - auto transptr = std::make_shared<const Transform3D>(trans); - std::shared_ptr<Surface> srf - = Surface::makeShared<PlaneSurface>(transptr, bounds); + SrfVec straightLineSurfaces( + size_t n = 10., double step = 3, const Vector3D& origin = {0, 0, 1.5}, + const Transform3D& pretrans = Transform3D::Identity(), + const Vector3D& dir = {0, 0, 1}) { + SrfVec res; + for (size_t i = 0; i < n; ++i) { + Transform3D trans; + trans.setIdentity(); + trans.translate(origin + dir * step * i); + // trans.rotate(AngleAxis3D(M_PI/9., Vector3D(0, 0, 1))); + trans.rotate(AngleAxis3D(M_PI / 2., Vector3D(1, 0, 0))); + trans = trans * pretrans; + + auto bounds = std::make_shared<const RectangleBounds>(2, 1.5); + + auto transptr = std::make_shared<const Transform3D>(trans); + std::shared_ptr<Surface> srf = + Surface::makeShared<PlaneSurface>(transptr, bounds); + + res.push_back(srf); + m_surfaces.push_back( + std::move(srf)); // keep shared, will get destroyed at the end + } - res.push_back(srf); - m_surfaces.push_back( - std::move(srf)); // keep shared, will get destroyed at the end - } + return res; + } - return res; + SrfVec makeBarrel(int nPhi, int nZ, double w, double h) { + double z0 = -(nZ - 1) * w; + SrfVec res; + + for (int i = 0; i < nZ; i++) { + double z = i * w * 2 + z0; + // std::cout << "z=" << z << std::endl; + SrfVec ring = fullPhiTestSurfacesBRL(nPhi, 0, z, M_PI / 9., w, h); + res.insert(res.end(), ring.begin(), ring.end()); } - SrfVec - fullPhiTestSurfacesBRL(size_t n = 10, - double shift = 0, - double zbase = 0, - double incl = M_PI / 9., - double w = 2, - double h = 1.5) - { - - SrfVec res; - // TODO: The test is extremely numerically unstable in the face of upward - // rounding in this multiplication and division. Find out why. - double phiStep = 2 * M_PI / n; - for (size_t i = 0; i < n; ++i) { - double z = zbase; - double phi = std::fma(i, phiStep, shift); + return res; + } + std::pair<SrfVec, std::vector<std::pair<const Surface*, const Surface*>>> + makeBarrelStagger(int nPhi, int nZ, double shift = 0, double incl = M_PI / 9., + double w = 2, double h = 1.5) { + double z0 = -(nZ - 1) * w; + SrfVec res; + std::vector<std::pair<const Surface*, const Surface*>> pairs; + // TODO: The test is extremely numerically unstable in the face of upward + // rounding in this multiplication and division. Find out why. + double phiStep = 2 * M_PI / nPhi; + for (int i = 0; i < nZ; i++) { + double z = i * w * 2 + z0; + for (int j = 0; j < nPhi; ++j) { + double phi = std::fma(j, phiStep, shift); Transform3D trans; trans.setIdentity(); trans.rotate(Eigen::AngleAxisd(phi, Vector3D(0, 0, 1))); @@ -146,541 +201,507 @@ namespace Test { auto bounds = std::make_shared<const RectangleBounds>(w, h); - auto transptr = std::make_shared<const Transform3D>(trans); - std::shared_ptr<Surface> srf - = Surface::makeShared<PlaneSurface>(transptr, bounds); + auto transAptr = std::make_shared<const Transform3D>(trans); - res.push_back(srf); - m_surfaces.push_back( - std::move(srf)); // keep shared, will get destroyed at the end - } + std::shared_ptr<Surface> srfA = + Surface::makeShared<PlaneSurface>(transAptr, bounds); - return res; - } + Vector3D nrm = srfA->normal(tgContext); + Transform3D transB = trans; + transB.pretranslate(nrm * 0.1); + auto transBptr = std::make_shared<const Transform3D>(transB); + std::shared_ptr<Surface> srfB = + Surface::makeShared<PlaneSurface>(transBptr, bounds); - SrfVec - straightLineSurfaces(size_t n = 10., - double step = 3, - const Vector3D& origin = {0, 0, 1.5}, - const Transform3D& pretrans = Transform3D::Identity(), - const Vector3D& dir = {0, 0, 1}) - { - SrfVec res; - for (size_t i = 0; i < n; ++i) { - Transform3D trans; - trans.setIdentity(); - trans.translate(origin + dir * step * i); - // trans.rotate(AngleAxis3D(M_PI/9., Vector3D(0, 0, 1))); - trans.rotate(AngleAxis3D(M_PI / 2., Vector3D(1, 0, 0))); - trans = trans * pretrans; + pairs.push_back(std::make_pair(srfA.get(), srfB.get())); - auto bounds = std::make_shared<const RectangleBounds>(2, 1.5); - - auto transptr = std::make_shared<const Transform3D>(trans); - std::shared_ptr<Surface> srf - = Surface::makeShared<PlaneSurface>(transptr, bounds); - - res.push_back(srf); - m_surfaces.push_back( - std::move(srf)); // keep shared, will get destroyed at the end + res.push_back(srfA); + res.push_back(srfB); + m_surfaces.push_back(std::move(srfA)); + m_surfaces.push_back(std::move(srfB)); } - - return res; - } - - SrfVec - makeBarrel(int nPhi, int nZ, double w, double h) - { - double z0 = -(nZ - 1) * w; - SrfVec res; - - for (int i = 0; i < nZ; i++) { - double z = i * w * 2 + z0; - // std::cout << "z=" << z << std::endl; - SrfVec ring = fullPhiTestSurfacesBRL(nPhi, 0, z, M_PI / 9., w, h); - res.insert(res.end(), ring.begin(), ring.end()); - } - - return res; } - std::pair<SrfVec, std::vector<std::pair<const Surface*, const Surface*>>> - makeBarrelStagger(int nPhi, - int nZ, - double shift = 0, - double incl = M_PI / 9., - double w = 2, - double h = 1.5) - { - double z0 = -(nZ - 1) * w; - SrfVec res; - std::vector<std::pair<const Surface*, const Surface*>> pairs; - // TODO: The test is extremely numerically unstable in the face of upward - // rounding in this multiplication and division. Find out why. - double phiStep = 2 * M_PI / nPhi; - for (int i = 0; i < nZ; i++) { - double z = i * w * 2 + z0; - for (int j = 0; j < nPhi; ++j) { - double phi = std::fma(j, phiStep, shift); - Transform3D trans; - trans.setIdentity(); - trans.rotate(Eigen::AngleAxisd(phi, Vector3D(0, 0, 1))); - trans.translate(Vector3D(10, 0, z)); - trans.rotate(Eigen::AngleAxisd(incl, Vector3D(0, 0, 1))); - trans.rotate(Eigen::AngleAxisd(M_PI / 2., Vector3D(0, 1, 0))); - - auto bounds = std::make_shared<const RectangleBounds>(w, h); - - auto transAptr = std::make_shared<const Transform3D>(trans); - - std::shared_ptr<Surface> srfA - = Surface::makeShared<PlaneSurface>(transAptr, bounds); - - Vector3D nrm = srfA->normal(tgContext); - Transform3D transB = trans; - transB.pretranslate(nrm * 0.1); - auto transBptr = std::make_shared<const Transform3D>(transB); - std::shared_ptr<Surface> srfB - = Surface::makeShared<PlaneSurface>(transBptr, bounds); - - pairs.push_back(std::make_pair(srfA.get(), srfB.get())); - - res.push_back(srfA); - res.push_back(srfB); - m_surfaces.push_back(std::move(srfA)); - m_surfaces.push_back(std::move(srfB)); - } - } - - return std::make_pair(res, pairs); - } - }; - - void - draw_surfaces(SrfVec surfaces, const std::string& fname) - { - - std::ofstream os; - os.open(fname); - - os << std::fixed << std::setprecision(4); + return std::make_pair(res, pairs); + } +}; - size_t nVtx = 0; - for (const auto& srfx : surfaces) { - std::shared_ptr<const PlaneSurface> srf - = std::dynamic_pointer_cast<const PlaneSurface>(srfx); - const PlanarBounds* bounds - = dynamic_cast<const PlanarBounds*>(&srf->bounds()); +void draw_surfaces(SrfVec surfaces, const std::string& fname) { + std::ofstream os; + os.open(fname); - for (const auto& vtxloc : bounds->vertices()) { - Vector3D vtx - = srf->transform(tgContext) * Vector3D(vtxloc.x(), vtxloc.y(), 0); - os << "v " << vtx.x() << " " << vtx.y() << " " << vtx.z() << "\n"; - } + os << std::fixed << std::setprecision(4); - // connect them - os << "f"; - for (size_t i = 1; i <= bounds->vertices().size(); ++i) { - os << " " << nVtx + i; - } - os << "\n"; + size_t nVtx = 0; + for (const auto& srfx : surfaces) { + std::shared_ptr<const PlaneSurface> srf = + std::dynamic_pointer_cast<const PlaneSurface>(srfx); + const PlanarBounds* bounds = + dynamic_cast<const PlanarBounds*>(&srf->bounds()); - nVtx += bounds->vertices().size(); + for (const auto& vtxloc : bounds->vertices()) { + Vector3D vtx = + srf->transform(tgContext) * Vector3D(vtxloc.x(), vtxloc.y(), 0); + os << "v " << vtx.x() << " " << vtx.y() << " " << vtx.z() << "\n"; } - os.close(); - } - - BOOST_AUTO_TEST_SUITE(Tools) - - BOOST_FIXTURE_TEST_CASE(SurfaceArrayCreator_createEquidistantAxis_Phi, - SurfaceArrayCreatorFixture) - { - // fail on empty srf vector - std::vector<const Surface*> emptyRaw; - ProtoLayer pl(tgContext, emptyRaw); - auto tr = Transform3D::Identity(); - BOOST_CHECK_THROW(createEquidistantAxis( - tgContext, emptyRaw, BinningValue::binPhi, pl, tr), - std::logic_error); - - std::vector<float> bdExp = { - -3.14159, -2.93215, -2.72271, -2.51327, -2.30383, -2.0944, -1.88496, - -1.67552, -1.46608, -1.25664, -1.0472, -0.837758, -0.628319, -0.418879, - -0.20944, 0, 0.20944, 0.418879, 0.628319, 0.837758, 1.0472, - 1.25664, 1.46608, 1.67552, 1.88496, 2.09439, 2.30383, 2.51327, - 2.72271, 2.93215, 3.14159}; - - double step = 2 * M_PI / 30.; - - // endcap style modules - - for (int i = -1; i <= 2; i += 2) { - double z = 10 * i; - // case 1: one module sits at pi / -pi - double angleShift = step / 2.; - auto surfaces = fullPhiTestSurfacesEC(30, angleShift, z); - std::vector<const Surface*> surfacesRaw = unpack_shared_vector(surfaces); - pl = ProtoLayer(tgContext, surfacesRaw); - tr = Transform3D::Identity(); - auto axis = createEquidistantAxis( - tgContext, surfacesRaw, BinningValue::binPhi, pl, tr); - - BOOST_CHECK_EQUAL(axis.nBins, 30); - CHECK_CLOSE_REL(axis.max, M_PI, 1e-6); - CHECK_CLOSE_REL(axis.min, -M_PI, 1e-6); - BOOST_CHECK_EQUAL(axis.bType, equidistant); - CHECK_SMALL(phi(tr * Vector3D::UnitX()), 1e-6); - - // case 2: two modules sit symmetrically around pi / -pi - angleShift = 0.; - surfaces = fullPhiTestSurfacesEC(30, angleShift, z); - surfacesRaw = unpack_shared_vector(surfaces); - pl = ProtoLayer(tgContext, surfacesRaw); - tr = Transform3D::Identity(); - axis = createEquidistantAxis( - tgContext, surfacesRaw, BinningValue::binPhi, pl, tr); - draw_surfaces(surfaces, - "SurfaceArrayCreator_createEquidistantAxis_EC_2.obj"); - BOOST_CHECK_EQUAL(axis.nBins, 30); - CHECK_CLOSE_REL(axis.max, M_PI, 1e-6); - CHECK_CLOSE_REL(axis.min, -M_PI, 1e-6); - BOOST_CHECK_EQUAL(axis.bType, equidistant); - // CHECK_CLOSE_REL(bdExp, axis.binEdges, 0.001); - CHECK_CLOSE_REL(phi(tr * Vector3D::UnitX()), -0.5 * step, 1e-3); - // case 3: two modules sit asymmetrically around pi / -pi shifted up - angleShift = step / -4.; - surfaces = fullPhiTestSurfacesEC(30, angleShift, z); - surfacesRaw = unpack_shared_vector(surfaces); - pl = ProtoLayer(tgContext, surfacesRaw); - tr = Transform3D::Identity(); - axis = createEquidistantAxis( - tgContext, surfacesRaw, BinningValue::binPhi, pl, tr); - draw_surfaces(surfaces, - "SurfaceArrayCreator_createEquidistantAxis_EC_3.obj"); - BOOST_CHECK_EQUAL(axis.nBins, 30); - CHECK_CLOSE_REL(axis.max, M_PI, 1e-6); - CHECK_CLOSE_REL(axis.min, -M_PI, 1e-6); - BOOST_CHECK_EQUAL(axis.bType, equidistant); - CHECK_CLOSE_REL(phi(tr * Vector3D::UnitX()), step / -4., 1e-3); - - // case 4: two modules sit asymmetrically around pi / -pi shifted down - angleShift = step / 4.; - surfaces = fullPhiTestSurfacesEC(30, angleShift, z); - surfacesRaw = unpack_shared_vector(surfaces); - pl = ProtoLayer(tgContext, surfaces); - surfacesRaw = unpack_shared_vector(surfaces); - tr = Transform3D::Identity(); - axis = createEquidistantAxis( - tgContext, surfacesRaw, BinningValue::binPhi, pl, tr); - surfacesRaw = unpack_shared_vector(surfaces); - draw_surfaces(surfaces, - "SurfaceArrayCreator_createEquidistantAxis_EC_4.obj"); - BOOST_CHECK_EQUAL(axis.nBins, 30); - CHECK_CLOSE_REL(axis.max, M_PI, 1e-6); - CHECK_CLOSE_REL(axis.min, -M_PI, 1e-6); - BOOST_CHECK_EQUAL(axis.bType, equidistant); - CHECK_CLOSE_REL(phi(tr * Vector3D::UnitX()), step / 4., 1e-3); + // connect them + os << "f"; + for (size_t i = 1; i <= bounds->vertices().size(); ++i) { + os << " " << nVtx + i; } + os << "\n"; - for (int i = -1; i <= 2; i += 2) { - double z = 10 * i; - // case 1: one module sits at pi / -pi - double angleShift = step / 2.; - auto surfaces = fullPhiTestSurfacesBRL(30, angleShift, z); - auto surfacesRaw = unpack_shared_vector(surfaces); - pl = ProtoLayer(tgContext, surfacesRaw); - tr = Transform3D::Identity(); - auto axis = createEquidistantAxis( - tgContext, surfacesRaw, BinningValue::binPhi, pl, tr); - draw_surfaces(surfaces, - "SurfaceArrayCreator_createEquidistantAxis_BRL_1.obj"); - BOOST_CHECK_EQUAL(axis.nBins, 30); - CHECK_CLOSE_REL(axis.max, M_PI, 1e-6); - CHECK_CLOSE_REL(axis.min, -M_PI, 1e-6); - BOOST_CHECK_EQUAL(axis.bType, equidistant); - CHECK_SMALL(phi(tr * Vector3D::UnitX()), 1e-6); - - // case 2: two modules sit symmetrically around pi / -pi - angleShift = 0.; - surfaces = fullPhiTestSurfacesBRL(30, angleShift, z); - surfacesRaw = unpack_shared_vector(surfaces); - pl = ProtoLayer(tgContext, surfacesRaw); - tr = Transform3D::Identity(); - axis = createEquidistantAxis( - tgContext, surfacesRaw, BinningValue::binPhi, pl, tr); - draw_surfaces(surfaces, - "SurfaceArrayCreator_createEquidistantAxis_BRL_2.obj"); - BOOST_CHECK_EQUAL(axis.nBins, 30); - CHECK_CLOSE_REL(axis.max, M_PI, 1e-6); - CHECK_CLOSE_REL(axis.min, -M_PI, 1e-6); - BOOST_CHECK_EQUAL(axis.bType, equidistant); - // CHECK_CLOSE_REL(bdExp, axis.binEdges, 0.001); - CHECK_CLOSE_REL(phi(tr * Vector3D::UnitX()), -0.5 * step, 1e-3); - - // case 3: two modules sit asymmetrically around pi / -pi shifted up - angleShift = step / -4.; - surfaces = fullPhiTestSurfacesBRL(30, angleShift, z); - surfacesRaw = unpack_shared_vector(surfaces); - pl = ProtoLayer(tgContext, surfacesRaw); - tr = Transform3D::Identity(); - axis = createEquidistantAxis( - tgContext, surfacesRaw, BinningValue::binPhi, pl, tr); - draw_surfaces(surfaces, - "SurfaceArrayCreator_createEquidistantAxis_BRL_3.obj"); - BOOST_CHECK_EQUAL(axis.nBins, 30); - CHECK_CLOSE_REL(axis.max, M_PI, 1e-6); - CHECK_CLOSE_REL(axis.min, -M_PI, 1e-6); - BOOST_CHECK_EQUAL(axis.bType, equidistant); - // CHECK_CLOSE_REL(bdExp, axis.binEdges, 0.001); - CHECK_CLOSE_REL(phi(tr * Vector3D::UnitX()), step / -4., 1e-3); - - // case 4: two modules sit asymmetrically around pi / -pi shifted down - angleShift = step / 4.; - surfaces = fullPhiTestSurfacesBRL(30, angleShift, z); - surfacesRaw = unpack_shared_vector(surfaces); - pl = ProtoLayer(tgContext, surfacesRaw); - tr = Transform3D::Identity(); - axis = createEquidistantAxis( - tgContext, surfacesRaw, BinningValue::binPhi, pl, tr); - draw_surfaces(surfaces, - "SurfaceArrayCreator_createEquidistantAxis_BRL_4.obj"); - BOOST_CHECK_EQUAL(axis.nBins, 30); - CHECK_CLOSE_REL(axis.max, M_PI, 1e-6); - CHECK_CLOSE_REL(axis.min, -M_PI, 1e-6); - BOOST_CHECK_EQUAL(axis.bType, equidistant); - // CHECK_CLOSE_REL(bdExp, axis.binEdges, 0.001); - CHECK_CLOSE_REL(phi(tr * Vector3D::UnitX()), step / 4., 1e-3); - } + nVtx += bounds->vertices().size(); + } - SrfVec surfaces; + os.close(); +} + +BOOST_AUTO_TEST_SUITE(Tools) + +BOOST_FIXTURE_TEST_CASE(SurfaceArrayCreator_createEquidistantAxis_Phi, + SurfaceArrayCreatorFixture) { + // fail on empty srf vector + std::vector<const Surface*> emptyRaw; + ProtoLayer pl(tgContext, emptyRaw); + auto tr = Transform3D::Identity(); + BOOST_CHECK_THROW( + createEquidistantAxis(tgContext, emptyRaw, BinningValue::binPhi, pl, tr), + std::logic_error); + + std::vector<float> bdExp = { + -3.14159, -2.93215, -2.72271, -2.51327, -2.30383, -2.0944, -1.88496, + -1.67552, -1.46608, -1.25664, -1.0472, -0.837758, -0.628319, -0.418879, + -0.20944, 0, 0.20944, 0.418879, 0.628319, 0.837758, 1.0472, + 1.25664, 1.46608, 1.67552, 1.88496, 2.09439, 2.30383, 2.51327, + 2.72271, 2.93215, 3.14159}; + + double step = 2 * M_PI / 30.; + + // endcap style modules + + for (int i = -1; i <= 2; i += 2) { + double z = 10 * i; + // case 1: one module sits at pi / -pi + double angleShift = step / 2.; + auto surfaces = fullPhiTestSurfacesEC(30, angleShift, z); + std::vector<const Surface*> surfacesRaw = unpack_shared_vector(surfaces); + pl = ProtoLayer(tgContext, surfacesRaw); + tr = Transform3D::Identity(); + auto axis = createEquidistantAxis(tgContext, surfacesRaw, + BinningValue::binPhi, pl, tr); + + BOOST_CHECK_EQUAL(axis.nBins, 30); + CHECK_CLOSE_REL(axis.max, M_PI, 1e-6); + CHECK_CLOSE_REL(axis.min, -M_PI, 1e-6); + BOOST_CHECK_EQUAL(axis.bType, equidistant); + CHECK_SMALL(phi(tr * Vector3D::UnitX()), 1e-6); - // single element in phi - surfaces = fullPhiTestSurfacesEC(1); - auto surfacesRaw = unpack_shared_vector(surfaces); + // case 2: two modules sit symmetrically around pi / -pi + angleShift = 0.; + surfaces = fullPhiTestSurfacesEC(30, angleShift, z); + surfacesRaw = unpack_shared_vector(surfaces); + pl = ProtoLayer(tgContext, surfacesRaw); + tr = Transform3D::Identity(); + axis = createEquidistantAxis(tgContext, surfacesRaw, BinningValue::binPhi, + pl, tr); draw_surfaces(surfaces, - "SurfaceArrayCreator_createEquidistantAxis_EC_Single.obj"); - - pl = ProtoLayer(tgContext, surfacesRaw); - tr = Transform3D::Identity(); - auto axis = createEquidistantAxis( - tgContext, surfacesRaw, BinningValue::binPhi, pl, tr); - BOOST_CHECK_EQUAL(axis.nBins, 1); - - CHECK_CLOSE_ABS(axis.max, phi(Vector3D(8, 1, 0)), 1e-3); - CHECK_CLOSE_ABS(axis.min, phi(Vector3D(8, -1, 0)), 1e-3); + "SurfaceArrayCreator_createEquidistantAxis_EC_2.obj"); + BOOST_CHECK_EQUAL(axis.nBins, 30); + CHECK_CLOSE_REL(axis.max, M_PI, 1e-6); + CHECK_CLOSE_REL(axis.min, -M_PI, 1e-6); BOOST_CHECK_EQUAL(axis.bType, equidistant); - } - - BOOST_FIXTURE_TEST_CASE(SurfaceArrayCreator_createEquidistantAxis_Z, - SurfaceArrayCreatorFixture) - { - - // single element in z - auto surfaces = straightLineSurfaces(1); - auto surfacesRaw = unpack_shared_vector(surfaces); - ProtoLayer pl = ProtoLayer(tgContext, surfacesRaw); - auto trf = Transform3D::Identity(); - auto axis = createEquidistantAxis( - tgContext, surfacesRaw, BinningValue::binZ, pl, trf); + // CHECK_CLOSE_REL(bdExp, axis.binEdges, 0.001); + CHECK_CLOSE_REL(phi(tr * Vector3D::UnitX()), -0.5 * step, 1e-3); + // case 3: two modules sit asymmetrically around pi / -pi shifted up + angleShift = step / -4.; + surfaces = fullPhiTestSurfacesEC(30, angleShift, z); + surfacesRaw = unpack_shared_vector(surfaces); + pl = ProtoLayer(tgContext, surfacesRaw); + tr = Transform3D::Identity(); + axis = createEquidistantAxis(tgContext, surfacesRaw, BinningValue::binPhi, + pl, tr); draw_surfaces(surfaces, - "SurfaceArrayCreator_createEquidistantAxis_Z_1.obj"); - BOOST_CHECK_EQUAL(axis.nBins, 1); - CHECK_CLOSE_ABS(axis.max, 3, 1e-6); - CHECK_CLOSE_ABS(axis.min, 0, 1e-6); + "SurfaceArrayCreator_createEquidistantAxis_EC_3.obj"); + BOOST_CHECK_EQUAL(axis.nBins, 30); + CHECK_CLOSE_REL(axis.max, M_PI, 1e-6); + CHECK_CLOSE_REL(axis.min, -M_PI, 1e-6); BOOST_CHECK_EQUAL(axis.bType, equidistant); + CHECK_CLOSE_REL(phi(tr * Vector3D::UnitX()), step / -4., 1e-3); - // z rows with varying starting point - for (size_t i = 0; i <= 20; i++) { - double z0 = -10 + 1. * i; - surfaces = straightLineSurfaces(10, 3, Vector3D(0, 0, z0 + 1.5)); - surfacesRaw = unpack_shared_vector(surfaces); - pl = ProtoLayer(tgContext, surfacesRaw); - trf = Transform3D::Identity(); - axis = createEquidistantAxis( - tgContext, surfacesRaw, BinningValue::binZ, pl, trf); - draw_surfaces( - surfaces, - (boost::format( - "SurfaceArrayCreator_createEquidistantAxis_Z_2_%1%.obj") - % i) - .str()); - BOOST_CHECK_EQUAL(axis.nBins, 10); - CHECK_CLOSE_ABS(axis.max, 30 + z0, 1e-6); - CHECK_CLOSE_ABS(axis.min, z0, 1e-6); - BOOST_CHECK_EQUAL(axis.bType, equidistant); - } - - // z row where elements are rotated around y - Transform3D tr = Transform3D::Identity(); - tr.rotate(AngleAxis3D(M_PI / 4., Vector3D(0, 0, 1))); - surfaces = straightLineSurfaces(10, 3, Vector3D(0, 0, 0 + 1.5), tr); + // case 4: two modules sit asymmetrically around pi / -pi shifted down + angleShift = step / 4.; + surfaces = fullPhiTestSurfacesEC(30, angleShift, z); + surfacesRaw = unpack_shared_vector(surfaces); + pl = ProtoLayer(tgContext, surfaces); + surfacesRaw = unpack_shared_vector(surfaces); + tr = Transform3D::Identity(); + axis = createEquidistantAxis(tgContext, surfacesRaw, BinningValue::binPhi, + pl, tr); surfacesRaw = unpack_shared_vector(surfaces); - pl = ProtoLayer(tgContext, surfacesRaw); - trf = Transform3D::Identity(); - axis = createEquidistantAxis( - tgContext, surfacesRaw, BinningValue::binZ, pl, trf); draw_surfaces(surfaces, - "SurfaceArrayCreator_createEquidistantAxis_Z_3.obj"); - BOOST_CHECK_EQUAL(axis.nBins, 10); - CHECK_CLOSE_ABS(axis.max, 30.9749, 1e-3); - CHECK_CLOSE_ABS(axis.min, -0.974873, 1e-3); + "SurfaceArrayCreator_createEquidistantAxis_EC_4.obj"); + BOOST_CHECK_EQUAL(axis.nBins, 30); + CHECK_CLOSE_REL(axis.max, M_PI, 1e-6); + CHECK_CLOSE_REL(axis.min, -M_PI, 1e-6); BOOST_CHECK_EQUAL(axis.bType, equidistant); + CHECK_CLOSE_REL(phi(tr * Vector3D::UnitX()), step / 4., 1e-3); } - BOOST_FIXTURE_TEST_CASE(SurfaceArrayCreator_createEquidistantAxis_R, - SurfaceArrayCreatorFixture) - { - - // single element in r - auto surfaces = fullPhiTestSurfacesEC(1, 0, 0, 15); + for (int i = -1; i <= 2; i += 2) { + double z = 10 * i; + // case 1: one module sits at pi / -pi + double angleShift = step / 2.; + auto surfaces = fullPhiTestSurfacesBRL(30, angleShift, z); auto surfacesRaw = unpack_shared_vector(surfaces); + pl = ProtoLayer(tgContext, surfacesRaw); + tr = Transform3D::Identity(); + auto axis = createEquidistantAxis(tgContext, surfacesRaw, + BinningValue::binPhi, pl, tr); + draw_surfaces(surfaces, + "SurfaceArrayCreator_createEquidistantAxis_BRL_1.obj"); + BOOST_CHECK_EQUAL(axis.nBins, 30); + CHECK_CLOSE_REL(axis.max, M_PI, 1e-6); + CHECK_CLOSE_REL(axis.min, -M_PI, 1e-6); + BOOST_CHECK_EQUAL(axis.bType, equidistant); + CHECK_SMALL(phi(tr * Vector3D::UnitX()), 1e-6); + + // case 2: two modules sit symmetrically around pi / -pi + angleShift = 0.; + surfaces = fullPhiTestSurfacesBRL(30, angleShift, z); + surfacesRaw = unpack_shared_vector(surfaces); + pl = ProtoLayer(tgContext, surfacesRaw); + tr = Transform3D::Identity(); + axis = createEquidistantAxis(tgContext, surfacesRaw, BinningValue::binPhi, + pl, tr); draw_surfaces(surfaces, - "SurfaceArrayCreator_createEquidistantAxis_R_1.obj"); - auto trf = Transform3D::Identity(); - ProtoLayer pl = ProtoLayer(tgContext, surfacesRaw); - auto axis = createEquidistantAxis( - tgContext, surfacesRaw, BinningValue::binR, pl, trf); - BOOST_CHECK_EQUAL(axis.nBins, 1); - CHECK_CLOSE_ABS(axis.max, perp(Vector3D(17, 1, 0)), 1e-3); - CHECK_CLOSE_ABS(axis.min, 13, 1e-3); + "SurfaceArrayCreator_createEquidistantAxis_BRL_2.obj"); + BOOST_CHECK_EQUAL(axis.nBins, 30); + CHECK_CLOSE_REL(axis.max, M_PI, 1e-6); + CHECK_CLOSE_REL(axis.min, -M_PI, 1e-6); BOOST_CHECK_EQUAL(axis.bType, equidistant); + // CHECK_CLOSE_REL(bdExp, axis.binEdges, 0.001); + CHECK_CLOSE_REL(phi(tr * Vector3D::UnitX()), -0.5 * step, 1e-3); - // multiple rings - surfaces.resize(0); - auto ringa = fullPhiTestSurfacesEC(30, 0, 0, 10); - surfaces.insert(surfaces.end(), ringa.begin(), ringa.end()); - auto ringb = fullPhiTestSurfacesEC(30, 0, 0, 15); - surfaces.insert(surfaces.end(), ringb.begin(), ringb.end()); - auto ringc = fullPhiTestSurfacesEC(30, 0, 0, 20); - surfaces.insert(surfaces.end(), ringc.begin(), ringc.end()); + // case 3: two modules sit asymmetrically around pi / -pi shifted up + angleShift = step / -4.; + surfaces = fullPhiTestSurfacesBRL(30, angleShift, z); + surfacesRaw = unpack_shared_vector(surfaces); + pl = ProtoLayer(tgContext, surfacesRaw); + tr = Transform3D::Identity(); + axis = createEquidistantAxis(tgContext, surfacesRaw, BinningValue::binPhi, + pl, tr); draw_surfaces(surfaces, - "SurfaceArrayCreator_createEquidistantAxis_R_2.obj"); + "SurfaceArrayCreator_createEquidistantAxis_BRL_3.obj"); + BOOST_CHECK_EQUAL(axis.nBins, 30); + CHECK_CLOSE_REL(axis.max, M_PI, 1e-6); + CHECK_CLOSE_REL(axis.min, -M_PI, 1e-6); + BOOST_CHECK_EQUAL(axis.bType, equidistant); + // CHECK_CLOSE_REL(bdExp, axis.binEdges, 0.001); + CHECK_CLOSE_REL(phi(tr * Vector3D::UnitX()), step / -4., 1e-3); + // case 4: two modules sit asymmetrically around pi / -pi shifted down + angleShift = step / 4.; + surfaces = fullPhiTestSurfacesBRL(30, angleShift, z); surfacesRaw = unpack_shared_vector(surfaces); - pl = ProtoLayer(tgContext, surfacesRaw); - trf = Transform3D::Identity(); - axis = createEquidistantAxis( - tgContext, surfacesRaw, BinningValue::binR, pl, trf); - - BOOST_CHECK_EQUAL(axis.nBins, 3); - CHECK_CLOSE_REL(axis.max, perp(Vector3D(20 + 2, 1, 0)), 1e-3); - CHECK_CLOSE_ABS(axis.min, 8, 1e-3); + pl = ProtoLayer(tgContext, surfacesRaw); + tr = Transform3D::Identity(); + axis = createEquidistantAxis(tgContext, surfacesRaw, BinningValue::binPhi, + pl, tr); + draw_surfaces(surfaces, + "SurfaceArrayCreator_createEquidistantAxis_BRL_4.obj"); + BOOST_CHECK_EQUAL(axis.nBins, 30); + CHECK_CLOSE_REL(axis.max, M_PI, 1e-6); + CHECK_CLOSE_REL(axis.min, -M_PI, 1e-6); BOOST_CHECK_EQUAL(axis.bType, equidistant); + // CHECK_CLOSE_REL(bdExp, axis.binEdges, 0.001); + CHECK_CLOSE_REL(phi(tr * Vector3D::UnitX()), step / 4., 1e-3); } - // if there are concentring disc or barrel modules, the bin count might be off - // we want to create _as few bins_ as possible, meaning the r-ring with - // the lowest number of surfaces should be used for the bin count or - // as basis for the variable edge procedure - // double filling will make sure no surfaces are dropped - BOOST_FIXTURE_TEST_CASE(SurfaceArrayCreator_dependentBinCounts, - SurfaceArrayCreatorFixture) - { - auto ringA = fullPhiTestSurfacesEC(10, 0, 0, 10, 2, 3); - auto ringB = fullPhiTestSurfacesEC(15, 0, 0, 15, 2, 3.5); - auto ringC = fullPhiTestSurfacesEC(20, 0, 0, 20, 2, 3.8); - - std::vector<std::shared_ptr<const Surface>> surfaces; - std::copy(ringA.begin(), ringA.end(), std::back_inserter(surfaces)); - std::copy(ringB.begin(), ringB.end(), std::back_inserter(surfaces)); - std::copy(ringC.begin(), ringC.end(), std::back_inserter(surfaces)); - draw_surfaces(surfaces, "SurfaceArrayCreator_dependentBinCounts.obj"); - - std::unique_ptr<SurfaceArray> sArray = m_SAC.surfaceArrayOnDisc( - tgContext, surfaces, equidistant, equidistant); - auto axes = sArray->getAxes(); - BOOST_CHECK_EQUAL(axes.at(0)->getNBins(), 3); - BOOST_CHECK_EQUAL(axes.at(1)->getNBins(), 10); + SrfVec surfaces; + + // single element in phi + surfaces = fullPhiTestSurfacesEC(1); + auto surfacesRaw = unpack_shared_vector(surfaces); + draw_surfaces(surfaces, + "SurfaceArrayCreator_createEquidistantAxis_EC_Single.obj"); + + pl = ProtoLayer(tgContext, surfacesRaw); + tr = Transform3D::Identity(); + auto axis = createEquidistantAxis(tgContext, surfacesRaw, + BinningValue::binPhi, pl, tr); + BOOST_CHECK_EQUAL(axis.nBins, 1); + + CHECK_CLOSE_ABS(axis.max, phi(Vector3D(8, 1, 0)), 1e-3); + CHECK_CLOSE_ABS(axis.min, phi(Vector3D(8, -1, 0)), 1e-3); + BOOST_CHECK_EQUAL(axis.bType, equidistant); +} + +BOOST_FIXTURE_TEST_CASE(SurfaceArrayCreator_createEquidistantAxis_Z, + SurfaceArrayCreatorFixture) { + // single element in z + auto surfaces = straightLineSurfaces(1); + auto surfacesRaw = unpack_shared_vector(surfaces); + ProtoLayer pl = ProtoLayer(tgContext, surfacesRaw); + auto trf = Transform3D::Identity(); + auto axis = createEquidistantAxis(tgContext, surfacesRaw, BinningValue::binZ, + pl, trf); + draw_surfaces(surfaces, "SurfaceArrayCreator_createEquidistantAxis_Z_1.obj"); + BOOST_CHECK_EQUAL(axis.nBins, 1); + CHECK_CLOSE_ABS(axis.max, 3, 1e-6); + CHECK_CLOSE_ABS(axis.min, 0, 1e-6); + BOOST_CHECK_EQUAL(axis.bType, equidistant); + + // z rows with varying starting point + for (size_t i = 0; i <= 20; i++) { + double z0 = -10 + 1. * i; + surfaces = straightLineSurfaces(10, 3, Vector3D(0, 0, z0 + 1.5)); + surfacesRaw = unpack_shared_vector(surfaces); + pl = ProtoLayer(tgContext, surfacesRaw); + trf = Transform3D::Identity(); + axis = createEquidistantAxis(tgContext, surfacesRaw, BinningValue::binZ, pl, + trf); + draw_surfaces( + surfaces, + (boost::format( + "SurfaceArrayCreator_createEquidistantAxis_Z_2_%1%.obj") % + i) + .str()); + BOOST_CHECK_EQUAL(axis.nBins, 10); + CHECK_CLOSE_ABS(axis.max, 30 + z0, 1e-6); + CHECK_CLOSE_ABS(axis.min, z0, 1e-6); + BOOST_CHECK_EQUAL(axis.bType, equidistant); } - BOOST_FIXTURE_TEST_CASE(SurfaceArrayCreator_completeBinning, - SurfaceArrayCreatorFixture) - { - SrfVec brl = makeBarrel(30, 7, 2, 1); - std::vector<const Surface*> brlRaw = unpack_shared_vector(brl); - draw_surfaces(brl, "SurfaceArrayCreator_completeBinning_BRL.obj"); - - detail::Axis<detail::AxisType::Equidistant, - detail::AxisBoundaryType::Closed> - phiAxis(-M_PI, M_PI, 30u); - detail::Axis<detail::AxisType::Equidistant, detail::AxisBoundaryType::Bound> - zAxis(-14, 14, 7u); - - double R = 10.; - auto globalToLocal = [](const Vector3D& pos) { - return Vector2D(phi(pos) + 2 * M_PI / 30 / 2, pos.z()); - }; - auto localToGlobal = [R](const Vector2D& loc) { - double phi = loc[0] - 2 * M_PI / 30 / 2; - return Vector3D(R * std::cos(phi), R * std::sin(phi), loc[1]); - }; + // z row where elements are rotated around y + Transform3D tr = Transform3D::Identity(); + tr.rotate(AngleAxis3D(M_PI / 4., Vector3D(0, 0, 1))); + surfaces = straightLineSurfaces(10, 3, Vector3D(0, 0, 0 + 1.5), tr); + surfacesRaw = unpack_shared_vector(surfaces); + pl = ProtoLayer(tgContext, surfacesRaw); + trf = Transform3D::Identity(); + axis = createEquidistantAxis(tgContext, surfacesRaw, BinningValue::binZ, pl, + trf); + draw_surfaces(surfaces, "SurfaceArrayCreator_createEquidistantAxis_Z_3.obj"); + BOOST_CHECK_EQUAL(axis.nBins, 10); + CHECK_CLOSE_ABS(axis.max, 30.9749, 1e-3); + CHECK_CLOSE_ABS(axis.min, -0.974873, 1e-3); + BOOST_CHECK_EQUAL(axis.bType, equidistant); +} + +BOOST_FIXTURE_TEST_CASE(SurfaceArrayCreator_createEquidistantAxis_R, + SurfaceArrayCreatorFixture) { + // single element in r + auto surfaces = fullPhiTestSurfacesEC(1, 0, 0, 15); + auto surfacesRaw = unpack_shared_vector(surfaces); + draw_surfaces(surfaces, "SurfaceArrayCreator_createEquidistantAxis_R_1.obj"); + auto trf = Transform3D::Identity(); + ProtoLayer pl = ProtoLayer(tgContext, surfacesRaw); + auto axis = createEquidistantAxis(tgContext, surfacesRaw, BinningValue::binR, + pl, trf); + BOOST_CHECK_EQUAL(axis.nBins, 1); + CHECK_CLOSE_ABS(axis.max, perp(Vector3D(17, 1, 0)), 1e-3); + CHECK_CLOSE_ABS(axis.min, 13, 1e-3); + BOOST_CHECK_EQUAL(axis.bType, equidistant); + + // multiple rings + surfaces.resize(0); + auto ringa = fullPhiTestSurfacesEC(30, 0, 0, 10); + surfaces.insert(surfaces.end(), ringa.begin(), ringa.end()); + auto ringb = fullPhiTestSurfacesEC(30, 0, 0, 15); + surfaces.insert(surfaces.end(), ringb.begin(), ringb.end()); + auto ringc = fullPhiTestSurfacesEC(30, 0, 0, 20); + surfaces.insert(surfaces.end(), ringc.begin(), ringc.end()); + draw_surfaces(surfaces, "SurfaceArrayCreator_createEquidistantAxis_R_2.obj"); + + surfacesRaw = unpack_shared_vector(surfaces); + pl = ProtoLayer(tgContext, surfacesRaw); + trf = Transform3D::Identity(); + axis = createEquidistantAxis(tgContext, surfacesRaw, BinningValue::binR, pl, + trf); + + BOOST_CHECK_EQUAL(axis.nBins, 3); + CHECK_CLOSE_REL(axis.max, perp(Vector3D(20 + 2, 1, 0)), 1e-3); + CHECK_CLOSE_ABS(axis.min, 8, 1e-3); + BOOST_CHECK_EQUAL(axis.bType, equidistant); +} + +// if there are concentring disc or barrel modules, the bin count might be off +// we want to create _as few bins_ as possible, meaning the r-ring with +// the lowest number of surfaces should be used for the bin count or +// as basis for the variable edge procedure +// double filling will make sure no surfaces are dropped +BOOST_FIXTURE_TEST_CASE(SurfaceArrayCreator_dependentBinCounts, + SurfaceArrayCreatorFixture) { + auto ringA = fullPhiTestSurfacesEC(10, 0, 0, 10, 2, 3); + auto ringB = fullPhiTestSurfacesEC(15, 0, 0, 15, 2, 3.5); + auto ringC = fullPhiTestSurfacesEC(20, 0, 0, 20, 2, 3.8); + + std::vector<std::shared_ptr<const Surface>> surfaces; + std::copy(ringA.begin(), ringA.end(), std::back_inserter(surfaces)); + std::copy(ringB.begin(), ringB.end(), std::back_inserter(surfaces)); + std::copy(ringC.begin(), ringC.end(), std::back_inserter(surfaces)); + draw_surfaces(surfaces, "SurfaceArrayCreator_dependentBinCounts.obj"); + + std::unique_ptr<SurfaceArray> sArray = + m_SAC.surfaceArrayOnDisc(tgContext, surfaces, equidistant, equidistant); + auto axes = sArray->getAxes(); + BOOST_CHECK_EQUAL(axes.at(0)->getNBins(), 3); + BOOST_CHECK_EQUAL(axes.at(1)->getNBins(), 10); +} + +BOOST_FIXTURE_TEST_CASE(SurfaceArrayCreator_completeBinning, + SurfaceArrayCreatorFixture) { + SrfVec brl = makeBarrel(30, 7, 2, 1); + std::vector<const Surface*> brlRaw = unpack_shared_vector(brl); + draw_surfaces(brl, "SurfaceArrayCreator_completeBinning_BRL.obj"); + + detail::Axis<detail::AxisType::Equidistant, detail::AxisBoundaryType::Closed> + phiAxis(-M_PI, M_PI, 30u); + detail::Axis<detail::AxisType::Equidistant, detail::AxisBoundaryType::Bound> + zAxis(-14, 14, 7u); + + double R = 10.; + auto globalToLocal = [](const Vector3D& pos) { + return Vector2D(phi(pos) + 2 * M_PI / 30 / 2, pos.z()); + }; + auto localToGlobal = [R](const Vector2D& loc) { + double phi = loc[0] - 2 * M_PI / 30 / 2; + return Vector3D(R * std::cos(phi), R * std::sin(phi), loc[1]); + }; - auto sl - = std::make_unique<SurfaceArray::SurfaceGridLookup<decltype(phiAxis), - decltype(zAxis)>>( - globalToLocal, - localToGlobal, - std::make_tuple(std::move(phiAxis), std::move(zAxis))); - sl->fill(tgContext, brlRaw); - SurfaceArray sa(std::move(sl), brl); - - // actually filled SA - for (const auto& srf : brl) { - Vector3D ctr = srf->binningPosition(tgContext, binR); - auto binContent = sa.at(ctr); - - BOOST_CHECK_EQUAL(binContent.size(), 1); - BOOST_CHECK_EQUAL(srf.get(), binContent.at(0)); - } + auto sl = std::make_unique< + SurfaceArray::SurfaceGridLookup<decltype(phiAxis), decltype(zAxis)>>( + globalToLocal, localToGlobal, + std::make_tuple(std::move(phiAxis), std::move(zAxis))); + sl->fill(tgContext, brlRaw); + SurfaceArray sa(std::move(sl), brl); + + // actually filled SA + for (const auto& srf : brl) { + Vector3D ctr = srf->binningPosition(tgContext, binR); + auto binContent = sa.at(ctr); + + BOOST_CHECK_EQUAL(binContent.size(), 1); + BOOST_CHECK_EQUAL(srf.get(), binContent.at(0)); } +} + +BOOST_FIXTURE_TEST_CASE(SurfaceArrayCreator_barrelStagger, + SurfaceArrayCreatorFixture) { + auto barrel = makeBarrelStagger(30, 7, 0, M_PI / 9.); + auto brl = barrel.first; + std::vector<const Surface*> brlRaw = unpack_shared_vector(brl); + draw_surfaces(brl, "SurfaceArrayCreator_barrelStagger.obj"); + + ProtoLayer pl(tgContext, brl); + + // EQUIDISTANT + Transform3D tr = Transform3D::Identity(); - BOOST_FIXTURE_TEST_CASE(SurfaceArrayCreator_barrelStagger, - SurfaceArrayCreatorFixture) - { + auto pAxisPhi = + createEquidistantAxis(tgContext, brlRaw, BinningValue::binPhi, pl, tr); + auto pAxisZ = + createEquidistantAxis(tgContext, brlRaw, BinningValue::binZ, pl, tr); - auto barrel = makeBarrelStagger(30, 7, 0, M_PI / 9.); - auto brl = barrel.first; - std::vector<const Surface*> brlRaw = unpack_shared_vector(brl); - draw_surfaces(brl, "SurfaceArrayCreator_barrelStagger.obj"); + double R = 10.; + Transform3D itr = tr.inverse(); + + auto globalToLocal = [tr](const Vector3D& pos) { + Vector3D rot = tr * pos; + return Vector2D(phi(rot), rot.z()); + }; + auto localToGlobal = [R, itr](const Vector2D& loc) { + return itr * Vector3D(R * std::cos(loc[0]), R * std::sin(loc[0]), loc[1]); + }; - ProtoLayer pl(tgContext, brl); + auto sl = makeSurfaceGridLookup2D<detail::AxisBoundaryType::Closed, + detail::AxisBoundaryType::Bound>( + globalToLocal, localToGlobal, pAxisPhi, pAxisZ); + + sl->fill(tgContext, brlRaw); + SurfaceArray sa(std::move(sl), brl); + auto axes = sa.getAxes(); + BOOST_CHECK_EQUAL(axes.at(0)->getNBins(), 30); + BOOST_CHECK_EQUAL(axes.at(1)->getNBins(), 7); + + for (const auto& pr : barrel.second) { + auto A = pr.first; + auto B = pr.second; + + Vector3D ctr = A->binningPosition(tgContext, binR); + auto binContent = sa.at(ctr); + BOOST_CHECK_EQUAL(binContent.size(), 2); + std::set<const Surface*> act; + act.insert(binContent[0]); + act.insert(binContent[1]); + + std::set<const Surface*> exp; + exp.insert(A); + exp.insert(B); + + BOOST_CHECK(act == exp); + } - // EQUIDISTANT - Transform3D tr = Transform3D::Identity(); + // VARIABLE + BOOST_TEST_CONTEXT("Barrel Stagger Variable binning") { + tr = Transform3D::Identity(); - auto pAxisPhi = createEquidistantAxis( - tgContext, brlRaw, BinningValue::binPhi, pl, tr); - auto pAxisZ - = createEquidistantAxis(tgContext, brlRaw, BinningValue::binZ, pl, tr); + auto pAxisPhiVar = + createVariableAxis(tgContext, brlRaw, BinningValue::binPhi, pl, tr); + auto pAxisZVar = + createVariableAxis(tgContext, brlRaw, BinningValue::binZ, pl, tr); - double R = 10.; - Transform3D itr = tr.inverse(); + itr = tr.inverse(); - auto globalToLocal = [tr](const Vector3D& pos) { + auto globalToLocalVar = [tr](const Vector3D& pos) { Vector3D rot = tr * pos; return Vector2D(phi(rot), rot.z()); }; - auto localToGlobal = [R, itr](const Vector2D& loc) { + auto localToGlobalVar = [R, itr](const Vector2D& loc) { return itr * Vector3D(R * std::cos(loc[0]), R * std::sin(loc[0]), loc[1]); }; - auto sl = makeSurfaceGridLookup2D<detail::AxisBoundaryType::Closed, - detail::AxisBoundaryType::Bound>( - globalToLocal, localToGlobal, pAxisPhi, pAxisZ); + auto sl2 = makeSurfaceGridLookup2D<detail::AxisBoundaryType::Closed, + detail::AxisBoundaryType::Bound>( + globalToLocalVar, localToGlobalVar, pAxisPhiVar, pAxisZVar); - sl->fill(tgContext, brlRaw); - SurfaceArray sa(std::move(sl), brl); - auto axes = sa.getAxes(); + sl2->fill(tgContext, brlRaw); + SurfaceArray sa2(std::move(sl2), brl); + axes = sa2.getAxes(); BOOST_CHECK_EQUAL(axes.at(0)->getNBins(), 30); BOOST_CHECK_EQUAL(axes.at(1)->getNBins(), 7); + // check bin edges + std::vector<double> phiEdgesExp = { + -3.14159, -2.93215, -2.72271, -2.51327, -2.30383, -2.0944, + -1.88496, -1.67552, -1.46608, -1.25664, -1.0472, -0.837758, + -0.628319, -0.418879, -0.20944, 4.44089e-16, 0.20944, 0.418879, + 0.628319, 0.837758, 1.0472, 1.25664, 1.46608, 1.67552, + 1.88496, 2.0944, 2.30383, 2.51327, 2.72271, 3.00831, + 3.14159}; + std::vector<double> zEdgesExp = {-14, -10, -6, -2, 2, 6, 10, 14}; + size_t i = 0; + for (const auto& edge : axes.at(0)->getBinEdges()) { + BOOST_TEST_INFO("phi edge index " << i); + auto phiEdge = phiEdgesExp.at(i); + CHECK_CLOSE_ABS(edge, phiEdge, 1e-5 * M_PI); + i++; + } + i = 0; + for (const auto& edge : axes.at(1)->getBinEdges()) { + BOOST_TEST_INFO("z edge index " << i); + CHECK_CLOSE_ABS(edge, zEdgesExp.at(i), 1e-6); + i++; + } + for (const auto& pr : barrel.second) { auto A = pr.first; auto B = pr.second; - Vector3D ctr = A->binningPosition(tgContext, binR); - auto binContent = sa.at(ctr); + Vector3D ctr = A->binningPosition(tgContext, binR); + auto binContent = sa2.at(ctr); BOOST_CHECK_EQUAL(binContent.size(), 2); std::set<const Surface*> act; act.insert(binContent[0]); @@ -692,82 +713,10 @@ namespace Test { BOOST_CHECK(act == exp); } - - // VARIABLE - BOOST_TEST_CONTEXT("Barrel Stagger Variable binning") - { - tr = Transform3D::Identity(); - - auto pAxisPhiVar - = createVariableAxis(tgContext, brlRaw, BinningValue::binPhi, pl, tr); - auto pAxisZVar - = createVariableAxis(tgContext, brlRaw, BinningValue::binZ, pl, tr); - - itr = tr.inverse(); - - auto globalToLocalVar = [tr](const Vector3D& pos) { - Vector3D rot = tr * pos; - return Vector2D(phi(rot), rot.z()); - }; - auto localToGlobalVar = [R, itr](const Vector2D& loc) { - return itr - * Vector3D(R * std::cos(loc[0]), R * std::sin(loc[0]), loc[1]); - }; - - auto sl2 = makeSurfaceGridLookup2D<detail::AxisBoundaryType::Closed, - detail::AxisBoundaryType::Bound>( - globalToLocalVar, localToGlobalVar, pAxisPhiVar, pAxisZVar); - - sl2->fill(tgContext, brlRaw); - SurfaceArray sa2(std::move(sl2), brl); - axes = sa2.getAxes(); - BOOST_CHECK_EQUAL(axes.at(0)->getNBins(), 30); - BOOST_CHECK_EQUAL(axes.at(1)->getNBins(), 7); - - // check bin edges - std::vector<double> phiEdgesExp - = {-3.14159, -2.93215, -2.72271, -2.51327, -2.30383, -2.0944, - -1.88496, -1.67552, -1.46608, -1.25664, -1.0472, -0.837758, - -0.628319, -0.418879, -0.20944, 4.44089e-16, 0.20944, 0.418879, - 0.628319, 0.837758, 1.0472, 1.25664, 1.46608, 1.67552, - 1.88496, 2.0944, 2.30383, 2.51327, 2.72271, 3.00831, - 3.14159}; - std::vector<double> zEdgesExp = {-14, -10, -6, -2, 2, 6, 10, 14}; - size_t i = 0; - for (const auto& edge : axes.at(0)->getBinEdges()) { - BOOST_TEST_INFO("phi edge index " << i); - auto phiEdge = phiEdgesExp.at(i); - CHECK_CLOSE_ABS(edge, phiEdge, 1e-5 * M_PI); - i++; - } - i = 0; - for (const auto& edge : axes.at(1)->getBinEdges()) { - BOOST_TEST_INFO("z edge index " << i); - CHECK_CLOSE_ABS(edge, zEdgesExp.at(i), 1e-6); - i++; - } - - for (const auto& pr : barrel.second) { - auto A = pr.first; - auto B = pr.second; - - Vector3D ctr = A->binningPosition(tgContext, binR); - auto binContent = sa2.at(ctr); - BOOST_CHECK_EQUAL(binContent.size(), 2); - std::set<const Surface*> act; - act.insert(binContent[0]); - act.insert(binContent[1]); - - std::set<const Surface*> exp; - exp.insert(A); - exp.insert(B); - - BOOST_CHECK(act == exp); - } - } } +} - BOOST_AUTO_TEST_SUITE_END() +BOOST_AUTO_TEST_SUITE_END() } // namespace Test } // namespace Acts diff --git a/Tests/Core/Geometry/TrackingGeometryClosureTests.cpp b/Tests/Core/Geometry/TrackingGeometryClosureTests.cpp index 8ee019037dc3d8aff804ef3c18abef21c5b5a798..b3c320e33681f770b626fd5a17c2fdb1a0431057 100644 --- a/Tests/Core/Geometry/TrackingGeometryClosureTests.cpp +++ b/Tests/Core/Geometry/TrackingGeometryClosureTests.cpp @@ -21,202 +21,174 @@ namespace Acts { namespace Test { - // Create a test context - GeometryContext tgContext = GeometryContext(); - - /// we test a two-level hierarchy - /// every deeper level hierarchy is a a derivate of this - /// - /// WorldVolume with volumeID == 1 - /// - InnerVolume with volumeID == 2 - /// -- InnerInnerVolume with volumeID == 3 - /// -- InnerOuterVolume with volumeID == 4 - /// - OuterVolume with volumeID == 5 - - // sensitive surface definitions - double surfaceHalfLengthZ = 50 * Acts::units::_mm; - double surfaceRstagger = 5. * Acts::units::_mm; - double surfaceZoverlap = 10. * Acts::units::_mm; - double layerEnvelope = 0.5 * Acts::units::_mm; - double volumeEnvelope = 10. * Acts::units::_mm; - - // inner inner volume definitions - double iiv_surfaceRadius = 25. * Acts::units::_mm; - double iiv_volumeRadius = iiv_surfaceRadius + 0.5 * surfaceRstagger - + layerEnvelope + volumeEnvelope; - - /// inner outer volume defininitions - double iov_surfaceRadius = 100. * Acts::units::_mm; - double iov_volumeRadius = iov_surfaceRadius + 0.5 * surfaceRstagger - + layerEnvelope + volumeEnvelope; - - /// inner inner volume - auto iiVolume = constructCylinderVolume(tgContext, - surfaceHalfLengthZ, - iiv_surfaceRadius, - surfaceRstagger, - surfaceZoverlap, - layerEnvelope, - volumeEnvelope, - 0., - iiv_volumeRadius, - "InnerInnerVolume"); - /// inner outer volume - auto ioVolume = constructCylinderVolume(tgContext, - surfaceHalfLengthZ, - iov_surfaceRadius, - surfaceRstagger, - surfaceZoverlap, - layerEnvelope, - volumeEnvelope, - iiv_volumeRadius, - iov_volumeRadius, - "InnerOuterVolume"); - - // now create the Inner Container volume - double volumeHalfZ - = (4 * surfaceHalfLengthZ - surfaceZoverlap) + volumeEnvelope; - /// the inner volume - auto iVolume = constructContainerVolume(tgContext, - iiVolume, - ioVolume, - iov_volumeRadius, - volumeHalfZ, - "InnerVolume"); - - // outer volume definitions - double ov_surfaceRadius = 150. * Acts::units::_mm; - double ov_volumeRadius = ov_surfaceRadius + 0.5 * surfaceRstagger - + layerEnvelope + volumeEnvelope; - - /// inner outer volume - auto oVolume = constructCylinderVolume(tgContext, - surfaceHalfLengthZ, - ov_surfaceRadius, - surfaceRstagger, - surfaceZoverlap, - layerEnvelope, - volumeEnvelope, - iov_volumeRadius, - ov_volumeRadius, - "OuterVolume"); - /// the inner volume - auto volume = constructContainerVolume(tgContext, - iVolume, - oVolume, - ov_volumeRadius, - volumeHalfZ, - "WorldVolume"); - - // creating a TrackingGeometry - // -> closs the geometry, this should set the GeometryID - TrackingGeometry tGeometry(volume); - // get the world back - auto world = tGeometry.highestTrackingVolume(); - - BOOST_AUTO_TEST_CASE(GeometryID_closeGeometry_test) - { - - // the lambda for checking - auto check_vol = [](const TrackingVolume& vol, geo_id_value geoid) -> void { - // check the geometry id of the volume - BOOST_CHECK_EQUAL(geoid, vol.geoID().value(GeometryID::volume_mask)); - // check the geometry id of all boundary surfaces of the volume - // - this is strictly only possible when glueing if OFF - geo_id_value bsurface_id = 0; - for (auto bSf : vol.boundarySurfaces()) { - // check the bsurface volume id - geo_id_value bs_vol_id = bSf->surfaceRepresentation().geoID().value( - GeometryID::volume_mask); - BOOST_CHECK_EQUAL(geoid, bs_vol_id); - // check the bsurface boundary id - geo_id_value bs_bsf_id = bSf->surfaceRepresentation().geoID().value( - GeometryID::boundary_mask); - BOOST_CHECK_EQUAL(++bsurface_id, bs_bsf_id); - } - // testing the layer and it's approach surfaces - if (vol.confinedLayers() != nullptr) { - // layers start are counted from 1 - n - geo_id_value layer_id = 0; - for (auto lay : vol.confinedLayers()->arrayObjects()) { - // check the layer volume id and layer layer id - geo_id_value lay_vol_id = lay->geoID().value(GeometryID::volume_mask); - geo_id_value lay_lay_id = lay->geoID().value(GeometryID::layer_mask); - BOOST_CHECK_EQUAL(++layer_id, lay_lay_id); - BOOST_CHECK_EQUAL(geoid, lay_vol_id); - // test the layer approach surfaces - if (lay->approachDescriptor() != nullptr) { - // approach surfacesare counted from 1 - n - geo_id_value asurface_id = 0; - for (auto asf : lay->approachDescriptor()->containedSurfaces()) { - // check the approach volume id, approach layer id, approach - // approach - // id - geo_id_value asf_vol_id - = asf->geoID().value(GeometryID::volume_mask); - geo_id_value asf_lay_id - = asf->geoID().value(GeometryID::layer_mask); - geo_id_value asf_asf_id - = asf->geoID().value(GeometryID::approach_mask); - BOOST_CHECK_EQUAL(layer_id, asf_lay_id); - BOOST_CHECK_EQUAL(geoid, asf_vol_id); - BOOST_CHECK_EQUAL(++asurface_id, asf_asf_id); - } +// Create a test context +GeometryContext tgContext = GeometryContext(); + +/// we test a two-level hierarchy +/// every deeper level hierarchy is a a derivate of this +/// +/// WorldVolume with volumeID == 1 +/// - InnerVolume with volumeID == 2 +/// -- InnerInnerVolume with volumeID == 3 +/// -- InnerOuterVolume with volumeID == 4 +/// - OuterVolume with volumeID == 5 + +// sensitive surface definitions +double surfaceHalfLengthZ = 50 * Acts::units::_mm; +double surfaceRstagger = 5. * Acts::units::_mm; +double surfaceZoverlap = 10. * Acts::units::_mm; +double layerEnvelope = 0.5 * Acts::units::_mm; +double volumeEnvelope = 10. * Acts::units::_mm; + +// inner inner volume definitions +double iiv_surfaceRadius = 25. * Acts::units::_mm; +double iiv_volumeRadius = + iiv_surfaceRadius + 0.5 * surfaceRstagger + layerEnvelope + volumeEnvelope; + +/// inner outer volume defininitions +double iov_surfaceRadius = 100. * Acts::units::_mm; +double iov_volumeRadius = + iov_surfaceRadius + 0.5 * surfaceRstagger + layerEnvelope + volumeEnvelope; + +/// inner inner volume +auto iiVolume = constructCylinderVolume( + tgContext, surfaceHalfLengthZ, iiv_surfaceRadius, surfaceRstagger, + surfaceZoverlap, layerEnvelope, volumeEnvelope, 0., iiv_volumeRadius, + "InnerInnerVolume"); +/// inner outer volume +auto ioVolume = constructCylinderVolume( + tgContext, surfaceHalfLengthZ, iov_surfaceRadius, surfaceRstagger, + surfaceZoverlap, layerEnvelope, volumeEnvelope, iiv_volumeRadius, + iov_volumeRadius, "InnerOuterVolume"); + +// now create the Inner Container volume +double volumeHalfZ = + (4 * surfaceHalfLengthZ - surfaceZoverlap) + volumeEnvelope; +/// the inner volume +auto iVolume = + constructContainerVolume(tgContext, iiVolume, ioVolume, iov_volumeRadius, + volumeHalfZ, "InnerVolume"); + +// outer volume definitions +double ov_surfaceRadius = 150. * Acts::units::_mm; +double ov_volumeRadius = + ov_surfaceRadius + 0.5 * surfaceRstagger + layerEnvelope + volumeEnvelope; + +/// inner outer volume +auto oVolume = constructCylinderVolume( + tgContext, surfaceHalfLengthZ, ov_surfaceRadius, surfaceRstagger, + surfaceZoverlap, layerEnvelope, volumeEnvelope, iov_volumeRadius, + ov_volumeRadius, "OuterVolume"); +/// the inner volume +auto volume = constructContainerVolume( + tgContext, iVolume, oVolume, ov_volumeRadius, volumeHalfZ, "WorldVolume"); + +// creating a TrackingGeometry +// -> closs the geometry, this should set the GeometryID +TrackingGeometry tGeometry(volume); +// get the world back +auto world = tGeometry.highestTrackingVolume(); + +BOOST_AUTO_TEST_CASE(GeometryID_closeGeometry_test) { + // the lambda for checking + auto check_vol = [](const TrackingVolume& vol, geo_id_value geoid) -> void { + // check the geometry id of the volume + BOOST_CHECK_EQUAL(geoid, vol.geoID().value(GeometryID::volume_mask)); + // check the geometry id of all boundary surfaces of the volume + // - this is strictly only possible when glueing if OFF + geo_id_value bsurface_id = 0; + for (auto bSf : vol.boundarySurfaces()) { + // check the bsurface volume id + geo_id_value bs_vol_id = + bSf->surfaceRepresentation().geoID().value(GeometryID::volume_mask); + BOOST_CHECK_EQUAL(geoid, bs_vol_id); + // check the bsurface boundary id + geo_id_value bs_bsf_id = + bSf->surfaceRepresentation().geoID().value(GeometryID::boundary_mask); + BOOST_CHECK_EQUAL(++bsurface_id, bs_bsf_id); + } + // testing the layer and it's approach surfaces + if (vol.confinedLayers() != nullptr) { + // layers start are counted from 1 - n + geo_id_value layer_id = 0; + for (auto lay : vol.confinedLayers()->arrayObjects()) { + // check the layer volume id and layer layer id + geo_id_value lay_vol_id = lay->geoID().value(GeometryID::volume_mask); + geo_id_value lay_lay_id = lay->geoID().value(GeometryID::layer_mask); + BOOST_CHECK_EQUAL(++layer_id, lay_lay_id); + BOOST_CHECK_EQUAL(geoid, lay_vol_id); + // test the layer approach surfaces + if (lay->approachDescriptor() != nullptr) { + // approach surfacesare counted from 1 - n + geo_id_value asurface_id = 0; + for (auto asf : lay->approachDescriptor()->containedSurfaces()) { + // check the approach volume id, approach layer id, approach + // approach + // id + geo_id_value asf_vol_id = + asf->geoID().value(GeometryID::volume_mask); + geo_id_value asf_lay_id = + asf->geoID().value(GeometryID::layer_mask); + geo_id_value asf_asf_id = + asf->geoID().value(GeometryID::approach_mask); + BOOST_CHECK_EQUAL(layer_id, asf_lay_id); + BOOST_CHECK_EQUAL(geoid, asf_vol_id); + BOOST_CHECK_EQUAL(++asurface_id, asf_asf_id); } - // test the sensitive surfaces - if (lay->surfaceArray() != nullptr) { - // sensitive surfaces are counted from 1 - n - geo_id_value ssurface_id = 0; - for (auto ssf : lay->surfaceArray()->surfaces()) { - // check the approach volume id, approach layer id, approach - // approach - // id - geo_id_value ssf_vol_id - = ssf->geoID().value(GeometryID::volume_mask); - geo_id_value ssf_lay_id - = ssf->geoID().value(GeometryID::layer_mask); - geo_id_value ssf_ssf_id - = ssf->geoID().value(GeometryID::sensitive_mask); - BOOST_CHECK_EQUAL(layer_id, ssf_lay_id); - BOOST_CHECK_EQUAL(geoid, ssf_vol_id); - BOOST_CHECK_EQUAL(++ssurface_id, ssf_ssf_id); - } + } + // test the sensitive surfaces + if (lay->surfaceArray() != nullptr) { + // sensitive surfaces are counted from 1 - n + geo_id_value ssurface_id = 0; + for (auto ssf : lay->surfaceArray()->surfaces()) { + // check the approach volume id, approach layer id, approach + // approach + // id + geo_id_value ssf_vol_id = + ssf->geoID().value(GeometryID::volume_mask); + geo_id_value ssf_lay_id = + ssf->geoID().value(GeometryID::layer_mask); + geo_id_value ssf_ssf_id = + ssf->geoID().value(GeometryID::sensitive_mask); + BOOST_CHECK_EQUAL(layer_id, ssf_lay_id); + BOOST_CHECK_EQUAL(geoid, ssf_vol_id); + BOOST_CHECK_EQUAL(++ssurface_id, ssf_ssf_id); } } } - }; - - // get the two volumes the world is built of - auto ioVolumes = world->confinedVolumes()->arrayObjects(); - // check the size - has to be two volumes - BOOST_CHECK_EQUAL(2ul, ioVolumes.size()); - // get the innermost volumes - auto iioVolumes = ioVolumes[0]->confinedVolumes()->arrayObjects(); - // check the size - has to be two volumes - BOOST_CHECK_EQUAL(2ul, iioVolumes.size()); - - // check the world - check_vol(*world, 1); - // - check InnerVolume - check_vol(*ioVolumes[0], 2); - // -- check the InnerInnerVolume - check_vol(*iioVolumes[0], 3); - // -- check the InenerOuterVolume - check_vol(*iioVolumes[1], 4); - // - check the OuterVolume - check_vol(*ioVolumes[1], 5); - } - - BOOST_AUTO_TEST_CASE(TrackingGeometry_testVisitSurfaces) - { - // this will also cover TrackingVolume::visitSurfaces - // its a pretty bare bones test, and only asserts that the - // method is called on the expected number of surfaces - size_t nSurfaces = 0; - tGeometry.visitSurfaces([&nSurfaces](const auto*) { nSurfaces++; }); - - BOOST_CHECK_EQUAL(nSurfaces, 9); - } + } + }; + + // get the two volumes the world is built of + auto ioVolumes = world->confinedVolumes()->arrayObjects(); + // check the size - has to be two volumes + BOOST_CHECK_EQUAL(2ul, ioVolumes.size()); + // get the innermost volumes + auto iioVolumes = ioVolumes[0]->confinedVolumes()->arrayObjects(); + // check the size - has to be two volumes + BOOST_CHECK_EQUAL(2ul, iioVolumes.size()); + + // check the world + check_vol(*world, 1); + // - check InnerVolume + check_vol(*ioVolumes[0], 2); + // -- check the InnerInnerVolume + check_vol(*iioVolumes[0], 3); + // -- check the InenerOuterVolume + check_vol(*iioVolumes[1], 4); + // - check the OuterVolume + check_vol(*ioVolumes[1], 5); +} + +BOOST_AUTO_TEST_CASE(TrackingGeometry_testVisitSurfaces) { + // this will also cover TrackingVolume::visitSurfaces + // its a pretty bare bones test, and only asserts that the + // method is called on the expected number of surfaces + size_t nSurfaces = 0; + tGeometry.visitSurfaces([&nSurfaces](const auto*) { nSurfaces++; }); + + BOOST_CHECK_EQUAL(nSurfaces, 9); +} } // end of namespace Test } // end of namespace Acts diff --git a/Tests/Core/Geometry/TrackingGeometryCreationTests.cpp b/Tests/Core/Geometry/TrackingGeometryCreationTests.cpp index 07ca2d4ef20245deac10c7fafcc3206fabf2bfd6..ee976e52ee1e363098275df1f56f576d1e936242 100644 --- a/Tests/Core/Geometry/TrackingGeometryCreationTests.cpp +++ b/Tests/Core/Geometry/TrackingGeometryCreationTests.cpp @@ -18,22 +18,20 @@ namespace Acts { namespace Test { - // Create a test context - GeometryContext tgContext = GeometryContext(); +// Create a test context +GeometryContext tgContext = GeometryContext(); - BOOST_AUTO_TEST_CASE(CylindricalTrackingGeometryTest) - { - CylindricalTrackingGeometry cGeometry(tgContext); - auto tGeometry = cGeometry(); - BOOST_CHECK_NE(tGeometry, nullptr); - } +BOOST_AUTO_TEST_CASE(CylindricalTrackingGeometryTest) { + CylindricalTrackingGeometry cGeometry(tgContext); + auto tGeometry = cGeometry(); + BOOST_CHECK_NE(tGeometry, nullptr); +} - BOOST_AUTO_TEST_CASE(CubicTrackingGeometryTest) - { - CubicTrackingGeometry cGeometry(tgContext); - auto tGeometry = cGeometry(); - BOOST_CHECK_NE(tGeometry, nullptr); - } +BOOST_AUTO_TEST_CASE(CubicTrackingGeometryTest) { + CubicTrackingGeometry cGeometry(tgContext); + auto tGeometry = cGeometry(); + BOOST_CHECK_NE(tGeometry, nullptr); +} -} // namespace Acts } // namespace Test +} // namespace Acts diff --git a/Tests/Core/Geometry/TrackingGeometryGeoIDTests.cpp b/Tests/Core/Geometry/TrackingGeometryGeoIDTests.cpp index d2b1ff780b532686396239b9738095f385babb9d..12cb31b4d34158cac7a4b0ff955d05492b8a3482 100644 --- a/Tests/Core/Geometry/TrackingGeometryGeoIDTests.cpp +++ b/Tests/Core/Geometry/TrackingGeometryGeoIDTests.cpp @@ -19,133 +19,114 @@ namespace Acts { namespace Test { - // Create a test context - GeometryContext tgContext = GeometryContext(); +// Create a test context +GeometryContext tgContext = GeometryContext(); - /// create three cylinder surfaces - /// the surface radius (will also be the layer radius) - double iVsurfaceHalfLengthZ = 50 * Acts::units::_mm; - double iVsurfaceRadius = 25. * Acts::units::_mm; - double iVsurfaceRstagger = 5. * Acts::units::_mm; - double iVsurfaceZoverlap = 10. * Acts::units::_mm; - double iVlayerEnvelope = 0.5 * Acts::units::_mm; - double iVvolumeEnvelope = 10. * Acts::units::_mm; - double iVvolumeRadius = iVsurfaceRadius + 0.5 * iVsurfaceRstagger - + iVlayerEnvelope + iVvolumeEnvelope; +/// create three cylinder surfaces +/// the surface radius (will also be the layer radius) +double iVsurfaceHalfLengthZ = 50 * Acts::units::_mm; +double iVsurfaceRadius = 25. * Acts::units::_mm; +double iVsurfaceRstagger = 5. * Acts::units::_mm; +double iVsurfaceZoverlap = 10. * Acts::units::_mm; +double iVlayerEnvelope = 0.5 * Acts::units::_mm; +double iVvolumeEnvelope = 10. * Acts::units::_mm; +double iVvolumeRadius = iVsurfaceRadius + 0.5 * iVsurfaceRstagger + + iVlayerEnvelope + iVvolumeEnvelope; - /// the surface radius (will also be the layer radius) - double oVsurfaceHalfLengthZ = 50. * Acts::units::_mm; - double oVsurfaceRadius = 100. * Acts::units::_mm; - double oVsurfaceRstagger = 5. * Acts::units::_mm; - double oVsurfaceZoverlap = 10. * Acts::units::_mm; - double oVlayerEnvelope = 0.5 * Acts::units::_mm; - double oVvolumeEnvelope = 10. * Acts::units::_mm; - double oVvolumeRadius = oVsurfaceRadius + 0.5 * oVsurfaceRstagger - + oVlayerEnvelope + oVvolumeEnvelope; +/// the surface radius (will also be the layer radius) +double oVsurfaceHalfLengthZ = 50. * Acts::units::_mm; +double oVsurfaceRadius = 100. * Acts::units::_mm; +double oVsurfaceRstagger = 5. * Acts::units::_mm; +double oVsurfaceZoverlap = 10. * Acts::units::_mm; +double oVlayerEnvelope = 0.5 * Acts::units::_mm; +double oVvolumeEnvelope = 10. * Acts::units::_mm; +double oVvolumeRadius = oVsurfaceRadius + 0.5 * oVsurfaceRstagger + + oVlayerEnvelope + oVvolumeEnvelope; - /// inner volume - auto iVolume = constructCylinderVolume(tgContext, - iVsurfaceHalfLengthZ, - iVsurfaceRadius, - iVsurfaceRstagger, - iVsurfaceZoverlap, - iVlayerEnvelope, - iVvolumeEnvelope, - 0., - iVvolumeRadius, - "InnerVolume"); +/// inner volume +auto iVolume = constructCylinderVolume( + tgContext, iVsurfaceHalfLengthZ, iVsurfaceRadius, iVsurfaceRstagger, + iVsurfaceZoverlap, iVlayerEnvelope, iVvolumeEnvelope, 0., iVvolumeRadius, + "InnerVolume"); - BOOST_AUTO_TEST_CASE(GeometryID_innervolume_test) - { - BOOST_CHECK_EQUAL(0ul, iVolume->geoID().value()); - // check the boundary surfaces - for (auto bSf : iVolume->boundarySurfaces()) { - BOOST_CHECK_EQUAL(0ul, bSf->surfaceRepresentation().geoID().value()); - for (auto lay : iVolume->confinedLayers()->arrayObjects()) { - BOOST_CHECK_EQUAL(0ul, lay->geoID().value()); - // check the approach surfaces - for (auto asf : lay->approachDescriptor()->containedSurfaces()) { - BOOST_CHECK_EQUAL(0ul, asf->geoID().value()); - } - // check the layer surface array - for (auto ssf : lay->surfaceArray()->surfaces()) { - BOOST_CHECK_EQUAL(0ul, ssf->geoID().value()); - } +BOOST_AUTO_TEST_CASE(GeometryID_innervolume_test) { + BOOST_CHECK_EQUAL(0ul, iVolume->geoID().value()); + // check the boundary surfaces + for (auto bSf : iVolume->boundarySurfaces()) { + BOOST_CHECK_EQUAL(0ul, bSf->surfaceRepresentation().geoID().value()); + for (auto lay : iVolume->confinedLayers()->arrayObjects()) { + BOOST_CHECK_EQUAL(0ul, lay->geoID().value()); + // check the approach surfaces + for (auto asf : lay->approachDescriptor()->containedSurfaces()) { + BOOST_CHECK_EQUAL(0ul, asf->geoID().value()); + } + // check the layer surface array + for (auto ssf : lay->surfaceArray()->surfaces()) { + BOOST_CHECK_EQUAL(0ul, ssf->geoID().value()); } } } +} - /// outer volume - auto oVolume = constructCylinderVolume(tgContext, - oVsurfaceHalfLengthZ, - oVsurfaceRadius, - oVsurfaceRstagger, - oVsurfaceZoverlap, - oVlayerEnvelope, - oVvolumeEnvelope, - iVvolumeRadius, - oVvolumeRadius, - "OuterVolume"); +/// outer volume +auto oVolume = constructCylinderVolume( + tgContext, oVsurfaceHalfLengthZ, oVsurfaceRadius, oVsurfaceRstagger, + oVsurfaceZoverlap, oVlayerEnvelope, oVvolumeEnvelope, iVvolumeRadius, + oVvolumeRadius, "OuterVolume"); - BOOST_AUTO_TEST_CASE(GeometryID_outervolume_test) - { - BOOST_CHECK_EQUAL(0ul, oVolume->geoID().value()); - // check the boundary surfaces - for (auto bSf : iVolume->boundarySurfaces()) { - BOOST_CHECK_EQUAL(0ul, bSf->surfaceRepresentation().geoID().value()); - for (auto lay : oVolume->confinedLayers()->arrayObjects()) { - BOOST_CHECK_EQUAL(0ul, lay->geoID().value()); - // check the approach surfaces - for (auto asf : lay->approachDescriptor()->containedSurfaces()) { - BOOST_CHECK_EQUAL(0ul, asf->geoID().value()); - } - // check the layer surface array - for (auto ssf : lay->surfaceArray()->surfaces()) { - BOOST_CHECK_EQUAL(0ul, ssf->geoID().value()); - } +BOOST_AUTO_TEST_CASE(GeometryID_outervolume_test) { + BOOST_CHECK_EQUAL(0ul, oVolume->geoID().value()); + // check the boundary surfaces + for (auto bSf : iVolume->boundarySurfaces()) { + BOOST_CHECK_EQUAL(0ul, bSf->surfaceRepresentation().geoID().value()); + for (auto lay : oVolume->confinedLayers()->arrayObjects()) { + BOOST_CHECK_EQUAL(0ul, lay->geoID().value()); + // check the approach surfaces + for (auto asf : lay->approachDescriptor()->containedSurfaces()) { + BOOST_CHECK_EQUAL(0ul, asf->geoID().value()); + } + // check the layer surface array + for (auto ssf : lay->surfaceArray()->surfaces()) { + BOOST_CHECK_EQUAL(0ul, ssf->geoID().value()); } } } - // - double oVvolumeHalfZ - = (4 * oVsurfaceHalfLengthZ - oVsurfaceZoverlap) + oVvolumeEnvelope; - // now create the container volume - auto hVolume = constructContainerVolume(tgContext, - iVolume, - oVolume, - oVvolumeRadius, - oVvolumeHalfZ, - "Container"); +} +// +double oVvolumeHalfZ = + (4 * oVsurfaceHalfLengthZ - oVsurfaceZoverlap) + oVvolumeEnvelope; +// now create the container volume +auto hVolume = constructContainerVolume( + tgContext, iVolume, oVolume, oVvolumeRadius, oVvolumeHalfZ, "Container"); - /// pre-check on GeometryID - BOOST_AUTO_TEST_CASE(GeometryID_containervolume_test) - { - /// let's check that the geometry ID values are all 0 - BOOST_CHECK_EQUAL(0ul, hVolume->geoID().value()); - /// check the boundaries of the hVolume, should also be 0 - for (auto hbsf : hVolume->boundarySurfaces()) { - BOOST_CHECK_EQUAL(0ul, hbsf->surfaceRepresentation().geoID().value()); +/// pre-check on GeometryID +BOOST_AUTO_TEST_CASE(GeometryID_containervolume_test) { + /// let's check that the geometry ID values are all 0 + BOOST_CHECK_EQUAL(0ul, hVolume->geoID().value()); + /// check the boundaries of the hVolume, should also be 0 + for (auto hbsf : hVolume->boundarySurfaces()) { + BOOST_CHECK_EQUAL(0ul, hbsf->surfaceRepresentation().geoID().value()); + } + for (auto cVol : hVolume->confinedVolumes()->arrayObjects()) { + /// let's check everything is set to 0 + BOOST_CHECK_EQUAL(0ul, cVol->geoID().value()); + // check the boundary surfaces + for (auto bSf : cVol->boundarySurfaces()) { + BOOST_CHECK_EQUAL(0ul, bSf->surfaceRepresentation().geoID().value()); } - for (auto cVol : hVolume->confinedVolumes()->arrayObjects()) { - /// let's check everything is set to 0 - BOOST_CHECK_EQUAL(0ul, cVol->geoID().value()); - // check the boundary surfaces - for (auto bSf : cVol->boundarySurfaces()) { - BOOST_CHECK_EQUAL(0ul, bSf->surfaceRepresentation().geoID().value()); + for (auto lay : cVol->confinedLayers()->arrayObjects()) { + BOOST_CHECK_EQUAL(0ul, lay->geoID().value()); + // check the approach surfaces + for (auto asf : lay->approachDescriptor()->containedSurfaces()) { + BOOST_CHECK_EQUAL(0ul, asf->geoID().value()); } - for (auto lay : cVol->confinedLayers()->arrayObjects()) { - BOOST_CHECK_EQUAL(0ul, lay->geoID().value()); - // check the approach surfaces - for (auto asf : lay->approachDescriptor()->containedSurfaces()) { - BOOST_CHECK_EQUAL(0ul, asf->geoID().value()); - } - // check the layer surface array - for (auto ssf : lay->surfaceArray()->surfaces()) { - BOOST_CHECK_EQUAL(0ul, ssf->geoID().value()); - } + // check the layer surface array + for (auto ssf : lay->surfaceArray()->surfaces()) { + BOOST_CHECK_EQUAL(0ul, ssf->geoID().value()); } } } +} } // end of namespace Test } // end of namespace Acts diff --git a/Tests/Core/Geometry/TrackingVolumeCreation.hpp b/Tests/Core/Geometry/TrackingVolumeCreation.hpp index ffe637d4ac47f2fee262c5c3fae1d8f2bb0d9195..c38327ebe3f07adedb605b665b0a4463bd4c5932 100644 --- a/Tests/Core/Geometry/TrackingVolumeCreation.hpp +++ b/Tests/Core/Geometry/TrackingVolumeCreation.hpp @@ -20,27 +20,20 @@ namespace Acts { /// helper function to create a cylinder -TrackingVolumePtr -constructCylinderVolume(const GeometryContext& gctx, - double surfaceHalfLengthZ, - double surfaceRadius, - double surfaceRstagger, - double surfaceZoverlap, - double layerEnvelope, - double volumeEnvelope, - double innerVolumeR, - double outerVolumeR, - const std::string& name) -{ +TrackingVolumePtr constructCylinderVolume( + const GeometryContext& gctx, double surfaceHalfLengthZ, + double surfaceRadius, double surfaceRstagger, double surfaceZoverlap, + double layerEnvelope, double volumeEnvelope, double innerVolumeR, + double outerVolumeR, const std::string& name) { /// the surface transforms - auto sfnPosition - = Vector3D(0., 0., -3 * surfaceHalfLengthZ - surfaceZoverlap); - auto sfnTransform - = std::make_shared<const Transform3D>(Translation3D(sfnPosition)); + auto sfnPosition = + Vector3D(0., 0., -3 * surfaceHalfLengthZ - surfaceZoverlap); + auto sfnTransform = + std::make_shared<const Transform3D>(Translation3D(sfnPosition)); auto sfcTransform = nullptr; auto sfpPosition = Vector3D(0., 0., 3 * surfaceHalfLengthZ - surfaceZoverlap); - auto sfpTransform - = std::make_shared<const Transform3D>(Translation3D(sfpPosition)); + auto sfpTransform = + std::make_shared<const Transform3D>(Translation3D(sfpPosition)); /// the surfaces auto sfn = Surface::makeShared<CylinderSurface>( sfnTransform, surfaceRadius - 0.5 * surfaceRstagger, surfaceHalfLengthZ); @@ -56,30 +49,29 @@ constructCylinderVolume(const GeometryContext& gctx, double bUmax = sfpPosition.z() + surfaceHalfLengthZ; std::vector<std::shared_ptr<const Surface>> surfaces_only = {{sfn, sfc, sfp}}; - std::vector<const Surface*> surfaces_only_raw - = {{sfn.get(), sfc.get(), sfp.get()}}; + std::vector<const Surface*> surfaces_only_raw = { + {sfn.get(), sfc.get(), sfp.get()}}; detail::Axis<detail::AxisType::Equidistant, detail::AxisBoundaryType::Bound> - axis(bUmin, bUmax, surfaces_only.size()); + axis(bUmin, bUmax, surfaces_only.size()); auto g2l = [](const Vector3D& glob) { return std::array<double, 1>({{glob.z()}}); }; - auto l2g - = [](const std::array<double, 1>& loc) { return Vector3D(0, 0, loc[0]); }; + auto l2g = [](const std::array<double, 1>& loc) { + return Vector3D(0, 0, loc[0]); + }; auto sl = std::make_unique<SurfaceArray::SurfaceGridLookup<decltype(axis)>>( g2l, l2g, std::make_tuple(axis)); sl->fill(gctx, surfaces_only_raw); auto bArray = std::make_unique<SurfaceArray>(std::move(sl), surfaces_only); /// now create the Layer - auto layer0bounds - = std::make_shared<const CylinderBounds>(surfaceRadius, bUmax); - auto layer0 = CylinderLayer::create(nullptr, - layer0bounds, - std::move(bArray), + auto layer0bounds = + std::make_shared<const CylinderBounds>(surfaceRadius, bUmax); + auto layer0 = CylinderLayer::create(nullptr, layer0bounds, std::move(bArray), surfaceRstagger + 2 * layerEnvelope); - std::unique_ptr<const LayerArray> layerArray - = std::make_unique<const BinnedArrayXD<LayerPtr>>(layer0); + std::unique_ptr<const LayerArray> layerArray = + std::make_unique<const BinnedArrayXD<LayerPtr>>(layer0); /// create the volume auto volumeBounds = std::make_shared<const CylinderVolumeBounds>( @@ -92,30 +84,28 @@ constructCylinderVolume(const GeometryContext& gctx, } /// helper function to create a container -MutableTrackingVolumePtr -constructContainerVolume(const GeometryContext& gctx, - TrackingVolumePtr iVolume, - TrackingVolumePtr oVolume, - double hVolumeRadius, - double hVolumeHalflength, - const std::string& name) -{ +MutableTrackingVolumePtr constructContainerVolume(const GeometryContext& gctx, + TrackingVolumePtr iVolume, + TrackingVolumePtr oVolume, + double hVolumeRadius, + double hVolumeHalflength, + const std::string& name) { /// create the volume array - using VAP = std::pair<TrackingVolumePtr, Vector3D>; + using VAP = std::pair<TrackingVolumePtr, Vector3D>; std::vector<VAP> volumes = {{iVolume, iVolume->binningPosition(gctx, binR)}, {oVolume, oVolume->binningPosition(gctx, binR)}}; /// the bounds for the container auto hVolumeBounds = std::make_shared<const CylinderVolumeBounds>( 0., hVolumeRadius, hVolumeHalflength); /// create the BinUtility & the BinnedArray - auto vUtility = std::make_unique<const BinUtility>( - volumes.size(), 0., hVolumeRadius, open, binR); - std::shared_ptr<const TrackingVolumeArray> vArray - = std::make_shared<const BinnedArrayXD<TrackingVolumePtr>>( + auto vUtility = std::make_unique<const BinUtility>(volumes.size(), 0., + hVolumeRadius, open, binR); + std::shared_ptr<const TrackingVolumeArray> vArray = + std::make_shared<const BinnedArrayXD<TrackingVolumePtr>>( volumes, std::move(vUtility)); /// create the container volume auto hVolume = TrackingVolume::create(nullptr, hVolumeBounds, vArray, name); // return the container return hVolume; } -} +} // namespace Acts diff --git a/Tests/Core/MagneticField/ConstantBFieldTests.cpp b/Tests/Core/MagneticField/ConstantBFieldTests.cpp index 1d735d845c33e71a74c43c18abdb44a71114bebb..5bf67c53a5bcbac568b97cecec91fa8b1d8379fd 100644 --- a/Tests/Core/MagneticField/ConstantBFieldTests.cpp +++ b/Tests/Core/MagneticField/ConstantBFieldTests.cpp @@ -20,134 +20,116 @@ // clang-format on namespace bdata = boost::unit_test::data; -namespace tt = boost::test_tools; +namespace tt = boost::test_tools; namespace Acts { namespace Test { - // Create a test context - MagneticFieldContext mfContext = MagneticFieldContext(); - - /// @brief unit test for construction of constant magnetic field - /// - /// Tests the correct behavior and consistency of - /// -# ConstantBField::ConstantBField(double Bx,double By,double Bz) - /// -# ConstantBField::ConstantBField(Vector3D B) - /// -# ConstantBField::getField(const double* xyz, double* B) const - /// -# ConstantBField::getField(const Vector3D& pos) const - BOOST_DATA_TEST_CASE(ConstantBField_components, - bdata::random(-2. * units::_T, 2. * units::_T) - ^ bdata::random(-1. * units::_T, 4. * units::_T) - ^ bdata::random(0. * units::_T, 10. * units::_T) - ^ bdata::random(-10. * units::_m, 10. * units::_m) - ^ bdata::random(-10. * units::_m, 10. * units::_m) - ^ bdata::random(-10. * units::_m, 10. * units::_m) - ^ bdata::xrange(10), - x, - y, - z, - bx, - by, - bz, - index) - { - (void)index; - BOOST_TEST_CONTEXT("Eigen interface") - { - const Vector3D Btrue(bx, by, bz); - const Vector3D pos(x, y, z); - const ConstantBField BField(Btrue); - - ConstantBField::Cache bCache(mfContext); - - BOOST_CHECK_EQUAL(Btrue, BField.getField(pos)); - BOOST_CHECK_EQUAL(Btrue, BField.getField(Vector3D(0, 0, 0))); - BOOST_CHECK_EQUAL(Btrue, BField.getField(-2 * pos)); - - BOOST_CHECK_EQUAL(Btrue, BField.getField(pos, bCache)); - BOOST_CHECK_EQUAL(Btrue, BField.getField(Vector3D(0, 0, 0), bCache)); - BOOST_CHECK_EQUAL(Btrue, BField.getField(-2 * pos, bCache)); - } - - BOOST_TEST_CONTEXT("C-array initialised - Eigen retrieved") - { - const ConstantBField BField(bx, by, bz); - const Vector3D Btrue(bx, by, bz); - const Vector3D pos(x, y, z); - - ConstantBField::Cache bCache(mfContext); - - BOOST_CHECK_EQUAL(Btrue, BField.getField(pos)); - BOOST_CHECK_EQUAL(Btrue, BField.getField(Vector3D(0, 0, 0))); - BOOST_CHECK_EQUAL(Btrue, BField.getField(-2 * pos)); - - BOOST_CHECK_EQUAL(Btrue, BField.getField(pos, bCache)); - BOOST_CHECK_EQUAL(Btrue, BField.getField(Vector3D(0, 0, 0), bCache)); - BOOST_CHECK_EQUAL(Btrue, BField.getField(-2 * pos, bCache)); - } +// Create a test context +MagneticFieldContext mfContext = MagneticFieldContext(); + +/// @brief unit test for construction of constant magnetic field +/// +/// Tests the correct behavior and consistency of +/// -# ConstantBField::ConstantBField(double Bx,double By,double Bz) +/// -# ConstantBField::ConstantBField(Vector3D B) +/// -# ConstantBField::getField(const double* xyz, double* B) const +/// -# ConstantBField::getField(const Vector3D& pos) const +BOOST_DATA_TEST_CASE(ConstantBField_components, + bdata::random(-2. * units::_T, 2. * units::_T) ^ + bdata::random(-1. * units::_T, 4. * units::_T) ^ + bdata::random(0. * units::_T, 10. * units::_T) ^ + bdata::random(-10. * units::_m, 10. * units::_m) ^ + bdata::random(-10. * units::_m, 10. * units::_m) ^ + bdata::random(-10. * units::_m, 10. * units::_m) ^ + bdata::xrange(10), + x, y, z, bx, by, bz, index) { + (void)index; + BOOST_TEST_CONTEXT("Eigen interface") { + const Vector3D Btrue(bx, by, bz); + const Vector3D pos(x, y, z); + const ConstantBField BField(Btrue); + + ConstantBField::Cache bCache(mfContext); + + BOOST_CHECK_EQUAL(Btrue, BField.getField(pos)); + BOOST_CHECK_EQUAL(Btrue, BField.getField(Vector3D(0, 0, 0))); + BOOST_CHECK_EQUAL(Btrue, BField.getField(-2 * pos)); + + BOOST_CHECK_EQUAL(Btrue, BField.getField(pos, bCache)); + BOOST_CHECK_EQUAL(Btrue, BField.getField(Vector3D(0, 0, 0), bCache)); + BOOST_CHECK_EQUAL(Btrue, BField.getField(-2 * pos, bCache)); } - /// @brief unit test for update of constant magnetic field - /// - /// Tests the correct behavior and consistency of - /// -# ConstantBField::setField(double Bx, double By, double Bz) - /// -# ConstantBField::setField(const Vector3D& B) - /// -# ConstantBField::getField(const double* xyz, double* B) const - /// -# ConstantBField::getField(const Vector3D& pos) const - BOOST_DATA_TEST_CASE(ConstantBField_update, - bdata::random(-2. * units::_T, 2. * units::_T) - ^ bdata::random(-1. * units::_T, 4. * units::_T) - ^ bdata::random(0. * units::_T, 10. * units::_T) - ^ bdata::random(-10. * units::_m, 10. * units::_m) - ^ bdata::random(-10. * units::_m, 10. * units::_m) - ^ bdata::random(-10. * units::_m, 10. * units::_m) - ^ bdata::xrange(10), - x, - y, - z, - bx, - by, - bz, - index) - { - (void)index; - ConstantBField BField(0, 0, 0); - - BOOST_TEST_CONTEXT("Eigen interface") - { - const Vector3D Btrue(bx, by, bz); - const Vector3D pos(x, y, z); - BField.setField(Btrue); - - ConstantBField::Cache bCache(mfContext); - - BOOST_CHECK_EQUAL(Btrue, BField.getField(pos)); - BOOST_CHECK_EQUAL(Btrue, BField.getField(Vector3D(0, 0, 0))); - BOOST_CHECK_EQUAL(Btrue, BField.getField(-2 * pos)); - - BOOST_CHECK_EQUAL(Btrue, BField.getField(pos, bCache)); - BOOST_CHECK_EQUAL(Btrue, BField.getField(Vector3D(0, 0, 0), bCache)); - BOOST_CHECK_EQUAL(Btrue, BField.getField(-2 * pos, bCache)); - } - - BOOST_TEST_CONTEXT("C-array initialised - Eigen retrieved") - { - const Vector3D Btrue(bx, by, bz); - const Vector3D pos(x, y, z); - BField.setField(bx, by, bz); - - ConstantBField::Cache bCache(mfContext); - - BOOST_CHECK_EQUAL(Btrue, BField.getField(pos)); - BOOST_CHECK_EQUAL(Btrue, BField.getField(Vector3D(0, 0, 0))); - BOOST_CHECK_EQUAL(Btrue, BField.getField(-2 * pos)); - - BOOST_CHECK_EQUAL(Btrue, BField.getField(pos, bCache)); - BOOST_CHECK_EQUAL(Btrue, BField.getField(Vector3D(0, 0, 0), bCache)); - BOOST_CHECK_EQUAL(Btrue, BField.getField(-2 * pos, bCache)); - } + BOOST_TEST_CONTEXT("C-array initialised - Eigen retrieved") { + const ConstantBField BField(bx, by, bz); + const Vector3D Btrue(bx, by, bz); + const Vector3D pos(x, y, z); + + ConstantBField::Cache bCache(mfContext); + + BOOST_CHECK_EQUAL(Btrue, BField.getField(pos)); + BOOST_CHECK_EQUAL(Btrue, BField.getField(Vector3D(0, 0, 0))); + BOOST_CHECK_EQUAL(Btrue, BField.getField(-2 * pos)); + + BOOST_CHECK_EQUAL(Btrue, BField.getField(pos, bCache)); + BOOST_CHECK_EQUAL(Btrue, BField.getField(Vector3D(0, 0, 0), bCache)); + BOOST_CHECK_EQUAL(Btrue, BField.getField(-2 * pos, bCache)); + } +} + +/// @brief unit test for update of constant magnetic field +/// +/// Tests the correct behavior and consistency of +/// -# ConstantBField::setField(double Bx, double By, double Bz) +/// -# ConstantBField::setField(const Vector3D& B) +/// -# ConstantBField::getField(const double* xyz, double* B) const +/// -# ConstantBField::getField(const Vector3D& pos) const +BOOST_DATA_TEST_CASE(ConstantBField_update, + bdata::random(-2. * units::_T, 2. * units::_T) ^ + bdata::random(-1. * units::_T, 4. * units::_T) ^ + bdata::random(0. * units::_T, 10. * units::_T) ^ + bdata::random(-10. * units::_m, 10. * units::_m) ^ + bdata::random(-10. * units::_m, 10. * units::_m) ^ + bdata::random(-10. * units::_m, 10. * units::_m) ^ + bdata::xrange(10), + x, y, z, bx, by, bz, index) { + (void)index; + ConstantBField BField(0, 0, 0); + + BOOST_TEST_CONTEXT("Eigen interface") { + const Vector3D Btrue(bx, by, bz); + const Vector3D pos(x, y, z); + BField.setField(Btrue); + + ConstantBField::Cache bCache(mfContext); + + BOOST_CHECK_EQUAL(Btrue, BField.getField(pos)); + BOOST_CHECK_EQUAL(Btrue, BField.getField(Vector3D(0, 0, 0))); + BOOST_CHECK_EQUAL(Btrue, BField.getField(-2 * pos)); + + BOOST_CHECK_EQUAL(Btrue, BField.getField(pos, bCache)); + BOOST_CHECK_EQUAL(Btrue, BField.getField(Vector3D(0, 0, 0), bCache)); + BOOST_CHECK_EQUAL(Btrue, BField.getField(-2 * pos, bCache)); + } + + BOOST_TEST_CONTEXT("C-array initialised - Eigen retrieved") { + const Vector3D Btrue(bx, by, bz); + const Vector3D pos(x, y, z); + BField.setField(bx, by, bz); + + ConstantBField::Cache bCache(mfContext); + + BOOST_CHECK_EQUAL(Btrue, BField.getField(pos)); + BOOST_CHECK_EQUAL(Btrue, BField.getField(Vector3D(0, 0, 0))); + BOOST_CHECK_EQUAL(Btrue, BField.getField(-2 * pos)); + + BOOST_CHECK_EQUAL(Btrue, BField.getField(pos, bCache)); + BOOST_CHECK_EQUAL(Btrue, BField.getField(Vector3D(0, 0, 0), bCache)); + BOOST_CHECK_EQUAL(Btrue, BField.getField(-2 * pos, bCache)); } +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/MagneticField/InterpolatedBFieldMapTests.cpp b/Tests/Core/MagneticField/InterpolatedBFieldMapTests.cpp index 1ebb410b6e38419b5d440b7fdcac9dbdd1f4053e..771c3e20553a9ddb9b7bcf67a767c3daeeae4b38 100644 --- a/Tests/Core/MagneticField/InterpolatedBFieldMapTests.cpp +++ b/Tests/Core/MagneticField/InterpolatedBFieldMapTests.cpp @@ -29,100 +29,94 @@ namespace Acts { namespace Test { - // Create a test context - MagneticFieldContext mfContext = MagneticFieldContext(); - - BOOST_AUTO_TEST_CASE(InterpolatedBFieldMap_rz) - { - // definition of dummy BField - struct BField - { - static Vector3D - value(const std::array<double, 2>& rz) - { - double r = rz.at(0); - double z = rz.at(1); - // linear in r and z so interpolation should be exact - return Vector3D(r * z, 3 * r, -2 * z); - } - }; - - // map (x,y,z) -> (r,z) - auto transformPos = [](const Vector3D& pos) { - return ActsVectorD<2>(perp(pos), pos.z()); - }; - - // map (Bx,By,Bz) -> (Bx,By,Bz) - auto transformBField - = [](const Vector3D& field, const Vector3D&) { return field; }; - - // magnetic field known on grid in (r,z) - detail::EquidistantAxis r(0.0, 4.0, 4u); - detail::EquidistantAxis z(-5, 5, 5u); - - using Grid_t = detail:: - Grid<Vector3D, detail::EquidistantAxis, detail::EquidistantAxis>; - using Mapper_t = InterpolatedBFieldMapper<Grid_t>; - using BField_t = InterpolatedBFieldMap<Mapper_t>; - - Grid_t g(std::make_tuple(std::move(r), std::move(z))); - - // set grid values - for (size_t i = 1; i <= g.numLocalBins().at(0) + 1; ++i) { - for (size_t j = 1; j <= g.numLocalBins().at(1) + 1; ++j) { - Grid_t::index_t indices = {{i, j}}; - const auto& llCorner = g.lowerLeftBinEdge(indices); - g.atLocalBins(indices) = BField::value(llCorner); - } +// Create a test context +MagneticFieldContext mfContext = MagneticFieldContext(); + +BOOST_AUTO_TEST_CASE(InterpolatedBFieldMap_rz) { + // definition of dummy BField + struct BField { + static Vector3D value(const std::array<double, 2>& rz) { + double r = rz.at(0); + double z = rz.at(1); + // linear in r and z so interpolation should be exact + return Vector3D(r * z, 3 * r, -2 * z); + } + }; + + // map (x,y,z) -> (r,z) + auto transformPos = [](const Vector3D& pos) { + return ActsVectorD<2>(perp(pos), pos.z()); + }; + + // map (Bx,By,Bz) -> (Bx,By,Bz) + auto transformBField = [](const Vector3D& field, const Vector3D&) { + return field; + }; + + // magnetic field known on grid in (r,z) + detail::EquidistantAxis r(0.0, 4.0, 4u); + detail::EquidistantAxis z(-5, 5, 5u); + + using Grid_t = + detail::Grid<Vector3D, detail::EquidistantAxis, detail::EquidistantAxis>; + using Mapper_t = InterpolatedBFieldMapper<Grid_t>; + using BField_t = InterpolatedBFieldMap<Mapper_t>; + + Grid_t g(std::make_tuple(std::move(r), std::move(z))); + + // set grid values + for (size_t i = 1; i <= g.numLocalBins().at(0) + 1; ++i) { + for (size_t j = 1; j <= g.numLocalBins().at(1) + 1; ++j) { + Grid_t::index_t indices = {{i, j}}; + const auto& llCorner = g.lowerLeftBinEdge(indices); + g.atLocalBins(indices) = BField::value(llCorner); } - - // create field mapping - Mapper_t mapper(transformPos, transformBField, std::move(g)); - BField_t::Config config(std::move(mapper)); - config.scale = 1.; - - // create BField service - BField_t b(std::move(config)); - - Vector3D pos; - pos << -3, 2.5, 1.7; - // test the cache interface - BField_t::Cache bCache(mfContext); - CHECK_CLOSE_REL( - b.getField(pos, bCache), BField::value({{perp(pos), pos.z()}}), 1e-6); - - CHECK_CLOSE_REL( - b.getField(pos, bCache), BField::value({{perp(pos), pos.z()}}), 1e-6); - auto& c = *bCache.fieldCell; - BOOST_CHECK(c.isInside(pos)); - CHECK_CLOSE_REL( - c.getField(pos), BField::value({{perp(pos), pos.z()}}), 1e-6); - - pos << 0, 1.5, -2.5; - BField_t::Cache bCache2(mfContext); - CHECK_CLOSE_REL( - b.getField(pos, bCache2), BField::value({{perp(pos), pos.z()}}), 1e-6); - c = *bCache2.fieldCell; - BOOST_CHECK(c.isInside(pos)); - CHECK_CLOSE_REL( - c.getField(pos), BField::value({{perp(pos), pos.z()}}), 1e-6); - - pos << 2, 3, -4; - BField_t::Cache bCache3(mfContext); - CHECK_CLOSE_REL( - b.getField(pos, bCache3), BField::value({{perp(pos), pos.z()}}), 1e-6); - c = *bCache3.fieldCell; - BOOST_CHECK(c.isInside(pos)); - CHECK_CLOSE_REL( - c.getField(pos), BField::value({{perp(pos), pos.z()}}), 1e-6); - - // some field cell tests - BOOST_CHECK(c.isInside((pos << 3, 2, -3.7).finished())); - BOOST_CHECK(c.isInside((pos << -2, 3, -4.7).finished())); - BOOST_CHECK(not c.isInside((pos << -2, 3, 4.7).finished())); - BOOST_CHECK(not c.isInside((pos << 0, 2, -4.7).finished())); - BOOST_CHECK(not c.isInside((pos << 5, 2, 14.).finished())); } + + // create field mapping + Mapper_t mapper(transformPos, transformBField, std::move(g)); + BField_t::Config config(std::move(mapper)); + config.scale = 1.; + + // create BField service + BField_t b(std::move(config)); + + Vector3D pos; + pos << -3, 2.5, 1.7; + // test the cache interface + BField_t::Cache bCache(mfContext); + CHECK_CLOSE_REL(b.getField(pos, bCache), + BField::value({{perp(pos), pos.z()}}), 1e-6); + + CHECK_CLOSE_REL(b.getField(pos, bCache), + BField::value({{perp(pos), pos.z()}}), 1e-6); + auto& c = *bCache.fieldCell; + BOOST_CHECK(c.isInside(pos)); + CHECK_CLOSE_REL(c.getField(pos), BField::value({{perp(pos), pos.z()}}), 1e-6); + + pos << 0, 1.5, -2.5; + BField_t::Cache bCache2(mfContext); + CHECK_CLOSE_REL(b.getField(pos, bCache2), + BField::value({{perp(pos), pos.z()}}), 1e-6); + c = *bCache2.fieldCell; + BOOST_CHECK(c.isInside(pos)); + CHECK_CLOSE_REL(c.getField(pos), BField::value({{perp(pos), pos.z()}}), 1e-6); + + pos << 2, 3, -4; + BField_t::Cache bCache3(mfContext); + CHECK_CLOSE_REL(b.getField(pos, bCache3), + BField::value({{perp(pos), pos.z()}}), 1e-6); + c = *bCache3.fieldCell; + BOOST_CHECK(c.isInside(pos)); + CHECK_CLOSE_REL(c.getField(pos), BField::value({{perp(pos), pos.z()}}), 1e-6); + + // some field cell tests + BOOST_CHECK(c.isInside((pos << 3, 2, -3.7).finished())); + BOOST_CHECK(c.isInside((pos << -2, 3, -4.7).finished())); + BOOST_CHECK(not c.isInside((pos << -2, 3, 4.7).finished())); + BOOST_CHECK(not c.isInside((pos << 0, 2, -4.7).finished())); + BOOST_CHECK(not c.isInside((pos << 5, 2, 14.).finished())); +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/MagneticField/MagneticFieldInterfaceConsistencyTests.cpp b/Tests/Core/MagneticField/MagneticFieldInterfaceConsistencyTests.cpp index 823eb9b77a84872aab96c485fedf8eb6efc618db..759afcf993f06315a266dab29d33c3dab4f8d59f 100644 --- a/Tests/Core/MagneticField/MagneticFieldInterfaceConsistencyTests.cpp +++ b/Tests/Core/MagneticField/MagneticFieldInterfaceConsistencyTests.cpp @@ -25,112 +25,82 @@ // clang-format on namespace bdata = boost::unit_test::data; -namespace tt = boost::test_tools; +namespace tt = boost::test_tools; namespace Acts { namespace Test { - // Create a test context - MagneticFieldContext mfContext = MagneticFieldContext(); - - /// This is the canonical interface that all field implementations - /// need to comply with. - /// This test group is should include ALL field implementations, - /// to make sure they conform to the interface, even if they are - /// not implicitly tested by some of the other tests (e.g. Propagation) - /// The function does not assert any functionality, it just ensures - /// the interface compiles - template <class BField_t> - void - testInterfaceConsistency(const BField_t& field) - { - using Cache_t = typename BField_t::Cache; - Vector3D pos(0, 0, 0); - Vector3D B; - ActsMatrixD<3, 3> gradient; - - // test interface method without cache - field.getField(pos); - field.getFieldGradient(pos, gradient); - - // test interface method with cache - Cache_t cache(mfContext); - field.getField(pos, cache); - field.getFieldGradient(pos, gradient, cache); - } - - BOOST_AUTO_TEST_CASE(TestConstantBFieldInterfaceConsistency) - { - ConstantBField field(1, 1, 1); - testInterfaceConsistency(field); - } - - BOOST_AUTO_TEST_CASE(TestSolenoidBFieldInterfaceConsistency) - { - SolenoidBField field({100, 1000, 20, 5}); - testInterfaceConsistency(field); - } - - BOOST_AUTO_TEST_CASE(TestInterpolatedBFieldMapInterfaceConsistency) - { - // define dummy mapper and field cell, we don't need them to do anything - struct DummyFieldCell - { - Vector3D - getField(const Vector3D&) const - { - return {0, 0, 0}; - } - bool - isInside(const Vector3D&) const - { - return true; - } - }; - - struct DummyMapper : DummyFieldCell - { - using FieldCell = DummyFieldCell; - - DummyFieldCell - getFieldCell(const Vector3D&) const - { - return DummyFieldCell(); - } - std::vector<size_t> - getNBins() const - { - return {42}; - } - std::vector<double> - getMin() const - { - return {5}; - } - std::vector<double> - getMax() const - { - return {15}; - } - }; - - DummyMapper m; - InterpolatedBFieldMap<DummyMapper>::Config config(std::move(m)); - config.scale = 1.; - - // create BField service - InterpolatedBFieldMap<DummyMapper> b(std::move(config)); - - testInterfaceConsistency(b); - } - - BOOST_AUTO_TEST_CASE(TestSharedBFieldInterfaceConsistency) - { - SharedBField<ConstantBField> field( - std::make_shared<ConstantBField>(Vector3D(1, 1, 1))); - testInterfaceConsistency(field); - } +// Create a test context +MagneticFieldContext mfContext = MagneticFieldContext(); + +/// This is the canonical interface that all field implementations +/// need to comply with. +/// This test group is should include ALL field implementations, +/// to make sure they conform to the interface, even if they are +/// not implicitly tested by some of the other tests (e.g. Propagation) +/// The function does not assert any functionality, it just ensures +/// the interface compiles +template <class BField_t> +void testInterfaceConsistency(const BField_t& field) { + using Cache_t = typename BField_t::Cache; + Vector3D pos(0, 0, 0); + Vector3D B; + ActsMatrixD<3, 3> gradient; + + // test interface method without cache + field.getField(pos); + field.getFieldGradient(pos, gradient); + + // test interface method with cache + Cache_t cache(mfContext); + field.getField(pos, cache); + field.getFieldGradient(pos, gradient, cache); +} + +BOOST_AUTO_TEST_CASE(TestConstantBFieldInterfaceConsistency) { + ConstantBField field(1, 1, 1); + testInterfaceConsistency(field); +} + +BOOST_AUTO_TEST_CASE(TestSolenoidBFieldInterfaceConsistency) { + SolenoidBField field({100, 1000, 20, 5}); + testInterfaceConsistency(field); +} + +BOOST_AUTO_TEST_CASE(TestInterpolatedBFieldMapInterfaceConsistency) { + // define dummy mapper and field cell, we don't need them to do anything + struct DummyFieldCell { + Vector3D getField(const Vector3D&) const { return {0, 0, 0}; } + bool isInside(const Vector3D&) const { return true; } + }; + + struct DummyMapper : DummyFieldCell { + using FieldCell = DummyFieldCell; + + DummyFieldCell getFieldCell(const Vector3D&) const { + return DummyFieldCell(); + } + std::vector<size_t> getNBins() const { return {42}; } + std::vector<double> getMin() const { return {5}; } + std::vector<double> getMax() const { return {15}; } + }; + + DummyMapper m; + InterpolatedBFieldMap<DummyMapper>::Config config(std::move(m)); + config.scale = 1.; + + // create BField service + InterpolatedBFieldMap<DummyMapper> b(std::move(config)); + + testInterfaceConsistency(b); +} + +BOOST_AUTO_TEST_CASE(TestSharedBFieldInterfaceConsistency) { + SharedBField<ConstantBField> field( + std::make_shared<ConstantBField>(Vector3D(1, 1, 1))); + testInterfaceConsistency(field); +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/MagneticField/SolenoidBFieldTests.cpp b/Tests/Core/MagneticField/SolenoidBFieldTests.cpp index f0d74867d5eb31a162e67545baf62d198dc98947..c82dd0a540eef8eb5a03fdfb31bba524b4a325d0 100644 --- a/Tests/Core/MagneticField/SolenoidBFieldTests.cpp +++ b/Tests/Core/MagneticField/SolenoidBFieldTests.cpp @@ -24,101 +24,97 @@ #include "Acts/MagneticField/MagneticFieldContext.hpp" namespace bdata = boost::unit_test::data; -namespace tt = boost::test_tools; +namespace tt = boost::test_tools; namespace Acts { namespace Test { - BOOST_AUTO_TEST_CASE(TestSolenoidBField) - { - - // Create a test context - MagneticFieldContext mfContext = MagneticFieldContext(); - - SolenoidBField::Config cfg; - cfg.length = 5.8 * Acts::units::_m; - cfg.radius = (2.56 + 2.46) * 0.5 * 0.5 * Acts::units::_m; - cfg.nCoils = 1154; - cfg.bMagCenter = 2. * Acts::units::_T; - SolenoidBField bField(cfg); - - SolenoidBField::Cache cache(mfContext); - CHECK_CLOSE_ABS(bField.getField({0, 0, 0}, cache), - Vector3D(0, 0, 2.0 * Acts::units::_T), - 1e-6 * Acts::units::_T); - - // std::ofstream outf("solenoid.csv"); - // outf << "x;y;z;B_x;B_y;B_z" << std::endl; - - double tol = 1e-6; - double tol_B = 1e-6 * Acts::units::_T; - size_t steps = 20; - for (size_t i = 0; i < steps; i++) { - double r = 1.5 * cfg.radius / steps * i; - BOOST_TEST_CONTEXT("r=" << r) - { - Vector3D B1 = bField.getField({r, 0, 0}, cache); - Vector3D B2 = bField.getField({-r, 0, 0}, cache); - CHECK_SMALL(B1.x(), tol); - CHECK_SMALL(B1.y(), tol); - BOOST_CHECK_GT(std::abs(B1.z()), tol_B); // greater than zero - // check symmetry: at z=0 it should be exactly symmetric - CHECK_CLOSE_ABS(B1, B2, tol_B); - - // at this point in r, go along the length - for (size_t j = 0; j <= steps; j++) { - // double z = cfg.L/steps * j - (cfg.L/2.); - double z = (1.5 * cfg.length / 2.) / steps * j; - BOOST_TEST_CONTEXT("z=" << z) - { - Vector3D B_zp_rp = bField.getField({r, 0, z}, cache); - Vector3D B_zn_rp = bField.getField({r, 0, -z}, cache); - Vector3D B_zp_rn = bField.getField({-r, 0, z}, cache); - Vector3D B_zn_rn = bField.getField({-r, 0, -z}, cache); - - // outf << r << ";0;" << z << ";" << B_zp_rp.x() << ";" << - // B_zp_rp.y() << ";" << B_zp_rp.z() << std::endl; - // if(j>0) { - // outf << r << ";0;" << -z << ";" << B_zn_rp.x() << ";" << - // B_zn_rp.y() << ";" << B_zn_rp.z() << std::endl; - //} - // if(i>0) { - // outf << -r << ";0;" << z << ";" << B_zp_rn.x() << ";" << - // B_zp_rn.y() << ";" << B_zp_rn.z() << std::endl; - //} - // if(i>0 && j>0) { - // outf << -r << ";0;" << -z << ";" << B_zn_rn.x() << ";" << - // B_zn_rn.y() << ";" << B_zn_rn.z() << std::endl; - //} - - // non-zero z - BOOST_CHECK_GT(std::abs(B_zp_rp.z()), tol_B); - BOOST_CHECK_GT(std::abs(B_zn_rp.z()), tol_B); - BOOST_CHECK_GT(std::abs(B_zn_rn.z()), tol_B); - BOOST_CHECK_GT(std::abs(B_zp_rn.z()), tol_B); - if (i > 0) { - // z components should be the same for +- r - CHECK_CLOSE_ABS(B_zp_rp.z(), B_zp_rn.z(), tol_B); - CHECK_CLOSE_ABS(B_zn_rp.z(), B_zn_rn.z(), tol_B); - // x components should be exactly opposite - CHECK_CLOSE_ABS(B_zp_rp.x(), -B_zp_rn.x(), tol_B); - CHECK_CLOSE_ABS(B_zn_rp.x(), -B_zn_rn.x(), tol_B); - } - if (j > 0) { - // z components should be the same for +- z - CHECK_CLOSE_ABS(B_zp_rp.z(), B_zn_rp.z(), tol_B); - CHECK_CLOSE_ABS(B_zp_rn.z(), B_zn_rn.z(), tol_B); - // x components should be exactly opposite - CHECK_CLOSE_ABS(B_zp_rp.x(), -B_zn_rp.x(), tol_B); - CHECK_CLOSE_ABS(B_zp_rn.x(), -B_zn_rn.x(), tol_B); - } +BOOST_AUTO_TEST_CASE(TestSolenoidBField) { + // Create a test context + MagneticFieldContext mfContext = MagneticFieldContext(); + + SolenoidBField::Config cfg; + cfg.length = 5.8 * Acts::units::_m; + cfg.radius = (2.56 + 2.46) * 0.5 * 0.5 * Acts::units::_m; + cfg.nCoils = 1154; + cfg.bMagCenter = 2. * Acts::units::_T; + SolenoidBField bField(cfg); + + SolenoidBField::Cache cache(mfContext); + CHECK_CLOSE_ABS(bField.getField({0, 0, 0}, cache), + Vector3D(0, 0, 2.0 * Acts::units::_T), + 1e-6 * Acts::units::_T); + + // std::ofstream outf("solenoid.csv"); + // outf << "x;y;z;B_x;B_y;B_z" << std::endl; + + double tol = 1e-6; + double tol_B = 1e-6 * Acts::units::_T; + size_t steps = 20; + for (size_t i = 0; i < steps; i++) { + double r = 1.5 * cfg.radius / steps * i; + BOOST_TEST_CONTEXT("r=" << r) { + Vector3D B1 = bField.getField({r, 0, 0}, cache); + Vector3D B2 = bField.getField({-r, 0, 0}, cache); + CHECK_SMALL(B1.x(), tol); + CHECK_SMALL(B1.y(), tol); + BOOST_CHECK_GT(std::abs(B1.z()), tol_B); // greater than zero + // check symmetry: at z=0 it should be exactly symmetric + CHECK_CLOSE_ABS(B1, B2, tol_B); + + // at this point in r, go along the length + for (size_t j = 0; j <= steps; j++) { + // double z = cfg.L/steps * j - (cfg.L/2.); + double z = (1.5 * cfg.length / 2.) / steps * j; + BOOST_TEST_CONTEXT("z=" << z) { + Vector3D B_zp_rp = bField.getField({r, 0, z}, cache); + Vector3D B_zn_rp = bField.getField({r, 0, -z}, cache); + Vector3D B_zp_rn = bField.getField({-r, 0, z}, cache); + Vector3D B_zn_rn = bField.getField({-r, 0, -z}, cache); + + // outf << r << ";0;" << z << ";" << B_zp_rp.x() << ";" << + // B_zp_rp.y() << ";" << B_zp_rp.z() << std::endl; + // if(j>0) { + // outf << r << ";0;" << -z << ";" << B_zn_rp.x() << ";" << + // B_zn_rp.y() << ";" << B_zn_rp.z() << std::endl; + //} + // if(i>0) { + // outf << -r << ";0;" << z << ";" << B_zp_rn.x() << ";" << + // B_zp_rn.y() << ";" << B_zp_rn.z() << std::endl; + //} + // if(i>0 && j>0) { + // outf << -r << ";0;" << -z << ";" << B_zn_rn.x() << ";" << + // B_zn_rn.y() << ";" << B_zn_rn.z() << std::endl; + //} + + // non-zero z + BOOST_CHECK_GT(std::abs(B_zp_rp.z()), tol_B); + BOOST_CHECK_GT(std::abs(B_zn_rp.z()), tol_B); + BOOST_CHECK_GT(std::abs(B_zn_rn.z()), tol_B); + BOOST_CHECK_GT(std::abs(B_zp_rn.z()), tol_B); + if (i > 0) { + // z components should be the same for +- r + CHECK_CLOSE_ABS(B_zp_rp.z(), B_zp_rn.z(), tol_B); + CHECK_CLOSE_ABS(B_zn_rp.z(), B_zn_rn.z(), tol_B); + // x components should be exactly opposite + CHECK_CLOSE_ABS(B_zp_rp.x(), -B_zp_rn.x(), tol_B); + CHECK_CLOSE_ABS(B_zn_rp.x(), -B_zn_rn.x(), tol_B); + } + if (j > 0) { + // z components should be the same for +- z + CHECK_CLOSE_ABS(B_zp_rp.z(), B_zn_rp.z(), tol_B); + CHECK_CLOSE_ABS(B_zp_rn.z(), B_zn_rn.z(), tol_B); + // x components should be exactly opposite + CHECK_CLOSE_ABS(B_zp_rp.x(), -B_zn_rp.x(), tol_B); + CHECK_CLOSE_ABS(B_zp_rn.x(), -B_zn_rn.x(), tol_B); } } } } - // outf.close(); } + // outf.close(); +} } // namespace Test diff --git a/Tests/Core/MagneticField/SolenoidFieldBenchmark.cpp b/Tests/Core/MagneticField/SolenoidFieldBenchmark.cpp index f6da48ecf4698f694f05b783c675feedac90807f..1efb25d4cebebb90d8edab0e5c7ddd7124ebe78f 100644 --- a/Tests/Core/MagneticField/SolenoidFieldBenchmark.cpp +++ b/Tests/Core/MagneticField/SolenoidFieldBenchmark.cpp @@ -16,21 +16,18 @@ #include <random> #include <string> -int -main(int argc, char* argv[]) -{ - +int main(int argc, char* argv[]) { size_t n = 1e6; if (argc == 2) { n = std::stoi(argv[1]); } - const double L = 5.8 * Acts::units::_m; - const double R = (2.56 + 2.46) * 0.5 * 0.5 * Acts::units::_m; - const size_t nCoils = 1154; + const double L = 5.8 * Acts::units::_m; + const double R = (2.56 + 2.46) * 0.5 * 0.5 * Acts::units::_m; + const size_t nCoils = 1154; const double bMagCenter = 2. * Acts::units::_T; - const size_t nBinsR = 150; - const size_t nBinsZ = 200; + const size_t nBinsR = 150; + const size_t nBinsZ = 200; double rMin = -0.1; double rMax = R * 2.; @@ -41,14 +38,14 @@ main(int argc, char* argv[]) Acts::SolenoidBField bSolenoidField({R, L, nCoils, bMagCenter}); std::cout << "building map" << std::endl; - auto mapper = Acts::solenoidFieldMapper( - {rMin, rMax}, {zMin, zMax}, {nBinsR, nBinsZ}, bSolenoidField); + auto mapper = Acts::solenoidFieldMapper({rMin, rMax}, {zMin, zMax}, + {nBinsR, nBinsZ}, bSolenoidField); using BField_t = Acts::InterpolatedBFieldMap<decltype(mapper)>; BField_t::Config cfg(std::move(mapper)); - auto bFieldMap = BField_t(std::move(cfg)); + auto bFieldMap = BField_t(std::move(cfg)); - std::mt19937 rng; + std::mt19937 rng; std::uniform_real_distribution<> zDist(1.5 * (-L / 2.), 1.5 * L / 2.); std::uniform_real_distribution<> rDist(0, R * 1.5); std::uniform_real_distribution<> phiDist(-M_PI, M_PI); @@ -56,9 +53,9 @@ main(int argc, char* argv[]) std::cout << "number of points: " << n << std::endl; std::cout << "start" << std::endl; using clock = std::chrono::steady_clock; - auto start = clock::now(); + auto start = clock::now(); - double z, r, phi; + double z, r, phi; Acts::Vector3D pos; Acts::Vector3D B; for (size_t i = 0; i < n; i++) { @@ -66,18 +63,18 @@ main(int argc, char* argv[]) std::cout << i << std::endl; } - z = zDist(rng); - r = rDist(rng); + z = zDist(rng); + r = rDist(rng); phi = phiDist(rng); pos = {r * std::cos(phi), r * std::sin(phi), z}; B = bSolenoidField.getField(pos); } - auto end = clock::now(); - double ms_solenoid - = std::chrono::duration_cast<std::chrono::duration<double>>(end - start) - .count(); + auto end = clock::now(); + double ms_solenoid = + std::chrono::duration_cast<std::chrono::duration<double>>(end - start) + .count(); start = clock::now(); for (size_t i = 0; i < n; i++) { @@ -85,8 +82,8 @@ main(int argc, char* argv[]) std::cout << i << std::endl; } - z = zDist(rng); - r = rDist(rng); + z = zDist(rng); + r = rDist(rng); phi = phiDist(rng); pos = {r * std::cos(phi), r * std::sin(phi), z}; @@ -94,9 +91,9 @@ main(int argc, char* argv[]) } end = clock::now(); - auto ms_map - = std::chrono::duration_cast<std::chrono::duration<double>>(end - start) - .count(); + auto ms_map = + std::chrono::duration_cast<std::chrono::duration<double>>(end - start) + .count(); std::cout << "solenoid: " << (ms_solenoid * 1000.) << "ms, per lookup: " << (ms_solenoid / n * 1000.) << "ms" diff --git a/Tests/Core/Material/AccumulatedMaterialPropertiesTests.cpp b/Tests/Core/Material/AccumulatedMaterialPropertiesTests.cpp index 229b3ac239c0f94227fcdff4aebc5e1d076a4725..c839a63bac0de99b5576a0e2ad23470c45a13bcc 100644 --- a/Tests/Core/Material/AccumulatedMaterialPropertiesTests.cpp +++ b/Tests/Core/Material/AccumulatedMaterialPropertiesTests.cpp @@ -21,178 +21,172 @@ namespace Acts { namespace Test { - /// Test the constructors - BOOST_AUTO_TEST_CASE(AccumulatedMaterialProperties_construction_test) - { - // Default constructor - AccumulatedMaterialProperties a; - - // Default copy constructor - AccumulatedMaterialProperties b(a); - - // Default assignment - AccumulatedMaterialProperties c = a; - - /// Check the move construction - AccumulatedMaterialProperties bMoved(std::move(b)); - - /// Check the move assignment - AccumulatedMaterialProperties cMovedAssigned = std::move(c); - - /// All of the material should be invalid (the accessible ones) - auto averageA = a.totalAverage(); - BOOST_CHECK_EQUAL(bool(averageA.first), false); - BOOST_CHECK_EQUAL(averageA.second, 0); - - /// All of the material should be invalid (the accessible ones) - auto averageB = bMoved.totalAverage(); - BOOST_CHECK_EQUAL(bool(averageB.first), false); - BOOST_CHECK_EQUAL(averageB.second, 0); - - /// All of the material should be invalid (the accessible ones) - auto averageC = cMovedAssigned.totalAverage(); - BOOST_CHECK_EQUAL(bool(averageC.first), false); - BOOST_CHECK_EQUAL(averageC.second, 0); - } - - /// Test the event averaging behavior - BOOST_AUTO_TEST_CASE(AccumulatedMaterialProperties_trackaverage_test) - { - // These are our material properties - MaterialProperties a(1., 2., 6., 3., 5., 1.); - MaterialProperties b(2., 4., 12., 6., 10., 2.); - MaterialProperties c(4., 8., 16., 8., 20., 3.); - - // Collect per event - AccumulatedMaterialProperties abc; - abc.accumulate(a); - abc.accumulate(b); - abc.accumulate(c); - abc.trackAverage(); - - // Now get back the total average - without unit thickness - auto averageAbc = abc.totalAverage(); - - // Both should have one event - BOOST_CHECK_EQUAL(averageAbc.second, 1); - auto mpAbc = averageAbc.first; - - // Thickness must be one for mapping - // Thickness in X0 is additive - CHECK_CLOSE_REL(mpAbc.thickness(), 1., 0.0001); - // A/Z should be 0.5 roughly for both - CHECK_CLOSE_REL(mpAbc.averageZ() / mpAbc.averageA(), 0.5, 0.0001); - // Thickness in X0 is additive - CHECK_CLOSE_REL(mpAbc.thicknessInX0(), - a.thicknessInX0() + b.thicknessInX0() + c.thicknessInX0(), - 0.0001); - // Consistency check : X0 - CHECK_CLOSE_REL( - mpAbc.thickness() / mpAbc.averageX0(), mpAbc.thicknessInX0(), 0.0001); - // Consistency check : L0 - CHECK_CLOSE_REL(mpAbc.thicknessInL0(), - a.thicknessInL0() + b.thicknessInL0() + c.thicknessInL0(), - 0.0001); - // The density scales with the thickness then - double rhoTmapped = mpAbc.averageRho() * mpAbc.thickness(); - double rhoTadded - = (a.thickness() * a.averageRho() + b.thickness() * b.averageRho() - + c.thickness() * c.averageRho()); - CHECK_CLOSE_REL(rhoTmapped, rhoTadded, 0.0001); - } - - /// Test the total averaging behavior - BOOST_AUTO_TEST_CASE(AccumulatedMaterialProperties_totalaverage_test) - { - - MaterialProperties a(1., 2., 6., 3., 5., 1.); - MaterialProperties a3(1., 2., 6., 3., 5., 3.); - - MaterialProperties v(1.); - - // Test is the average of a and a is a - AccumulatedMaterialProperties aa; - aa.accumulate(a); - aa.trackAverage(); - aa.accumulate(a); - aa.trackAverage(); - auto averageAA = aa.totalAverage(); - - BOOST_CHECK_EQUAL(a, averageAA.first); - BOOST_CHECK_EQUAL(2, averageAA.second); - - // Test: - // that the average of a and a vacuum - // step of same length is half a - MaterialProperties halfA = a; - halfA *= 0.5; - halfA.scaleToUnitThickness(); - - AccumulatedMaterialProperties av; - av.accumulate(a); - av.trackAverage(); - av.accumulate(v); - av.trackAverage(); - auto averageAV = av.totalAverage(); - auto matAV = averageAV.first; - - BOOST_CHECK_EQUAL(halfA.thicknessInX0(), matAV.thicknessInX0()); - BOOST_CHECK_EQUAL(halfA.thicknessInL0(), matAV.thicknessInL0()); - CHECK_CLOSE_REL(halfA.averageRho() * halfA.thickness(), - matAV.averageRho() * matAV.thickness(), - 0.0001); - BOOST_CHECK_EQUAL(2, averageAV.second); - - // Test: - // average of a + 3*a -> 2*a - MaterialProperties doubleA = a; - doubleA *= 2.; - - AccumulatedMaterialProperties aa3; - aa3.accumulate(a); - aa3.trackAverage(); - aa3.accumulate(a3); - aa3.trackAverage(); - auto averageAA3 = aa3.totalAverage(); - auto matAA3 = averageAA3.first; - - BOOST_CHECK_EQUAL(doubleA.thicknessInX0(), matAA3.thicknessInX0()); - BOOST_CHECK_EQUAL(doubleA.thicknessInL0(), matAA3.thicknessInL0()); - CHECK_CLOSE_REL(doubleA.averageRho() * doubleA.thickness(), - matAA3.averageRho() * matAA3.thickness(), - 0.0001); - BOOST_CHECK_EQUAL(2, averageAA3.second); - - /// Test: - /// average a + 3a + v - - AccumulatedMaterialProperties aa3v; - aa3v.accumulate(a); - aa3v.trackAverage(); - aa3v.accumulate(a3); - aa3v.trackAverage(); - aa3v.accumulate(v); - aa3v.trackAverage(); - auto averageAA3V = aa3v.totalAverage(); - auto matAA3V = averageAA3V.first; - - CHECK_CLOSE_REL(4. / 3., matAA3V.thicknessInX0(), 0.00001); - BOOST_CHECK_EQUAL(3, averageAA3V.second); - - /// Test: - /// average 4a + v - AccumulatedMaterialProperties a4v; - a4v.accumulate(a); - a4v.accumulate(a3); - a4v.trackAverage(); - a4v.accumulate(v); - a4v.trackAverage(); - auto averageA4V = a4v.totalAverage(); - auto matA4V = averageA4V.first; - - CHECK_CLOSE_REL(doubleA.thicknessInX0(), matA4V.thicknessInX0(), 0.00001); - BOOST_CHECK_EQUAL(2, averageA4V.second); - } +/// Test the constructors +BOOST_AUTO_TEST_CASE(AccumulatedMaterialProperties_construction_test) { + // Default constructor + AccumulatedMaterialProperties a; + + // Default copy constructor + AccumulatedMaterialProperties b(a); + + // Default assignment + AccumulatedMaterialProperties c = a; + + /// Check the move construction + AccumulatedMaterialProperties bMoved(std::move(b)); + + /// Check the move assignment + AccumulatedMaterialProperties cMovedAssigned = std::move(c); + + /// All of the material should be invalid (the accessible ones) + auto averageA = a.totalAverage(); + BOOST_CHECK_EQUAL(bool(averageA.first), false); + BOOST_CHECK_EQUAL(averageA.second, 0); + + /// All of the material should be invalid (the accessible ones) + auto averageB = bMoved.totalAverage(); + BOOST_CHECK_EQUAL(bool(averageB.first), false); + BOOST_CHECK_EQUAL(averageB.second, 0); + + /// All of the material should be invalid (the accessible ones) + auto averageC = cMovedAssigned.totalAverage(); + BOOST_CHECK_EQUAL(bool(averageC.first), false); + BOOST_CHECK_EQUAL(averageC.second, 0); +} + +/// Test the event averaging behavior +BOOST_AUTO_TEST_CASE(AccumulatedMaterialProperties_trackaverage_test) { + // These are our material properties + MaterialProperties a(1., 2., 6., 3., 5., 1.); + MaterialProperties b(2., 4., 12., 6., 10., 2.); + MaterialProperties c(4., 8., 16., 8., 20., 3.); + + // Collect per event + AccumulatedMaterialProperties abc; + abc.accumulate(a); + abc.accumulate(b); + abc.accumulate(c); + abc.trackAverage(); + + // Now get back the total average - without unit thickness + auto averageAbc = abc.totalAverage(); + + // Both should have one event + BOOST_CHECK_EQUAL(averageAbc.second, 1); + auto mpAbc = averageAbc.first; + + // Thickness must be one for mapping + // Thickness in X0 is additive + CHECK_CLOSE_REL(mpAbc.thickness(), 1., 0.0001); + // A/Z should be 0.5 roughly for both + CHECK_CLOSE_REL(mpAbc.averageZ() / mpAbc.averageA(), 0.5, 0.0001); + // Thickness in X0 is additive + CHECK_CLOSE_REL(mpAbc.thicknessInX0(), + a.thicknessInX0() + b.thicknessInX0() + c.thicknessInX0(), + 0.0001); + // Consistency check : X0 + CHECK_CLOSE_REL(mpAbc.thickness() / mpAbc.averageX0(), mpAbc.thicknessInX0(), + 0.0001); + // Consistency check : L0 + CHECK_CLOSE_REL(mpAbc.thicknessInL0(), + a.thicknessInL0() + b.thicknessInL0() + c.thicknessInL0(), + 0.0001); + // The density scales with the thickness then + double rhoTmapped = mpAbc.averageRho() * mpAbc.thickness(); + double rhoTadded = + (a.thickness() * a.averageRho() + b.thickness() * b.averageRho() + + c.thickness() * c.averageRho()); + CHECK_CLOSE_REL(rhoTmapped, rhoTadded, 0.0001); +} + +/// Test the total averaging behavior +BOOST_AUTO_TEST_CASE(AccumulatedMaterialProperties_totalaverage_test) { + MaterialProperties a(1., 2., 6., 3., 5., 1.); + MaterialProperties a3(1., 2., 6., 3., 5., 3.); + + MaterialProperties v(1.); + + // Test is the average of a and a is a + AccumulatedMaterialProperties aa; + aa.accumulate(a); + aa.trackAverage(); + aa.accumulate(a); + aa.trackAverage(); + auto averageAA = aa.totalAverage(); + + BOOST_CHECK_EQUAL(a, averageAA.first); + BOOST_CHECK_EQUAL(2, averageAA.second); + + // Test: + // that the average of a and a vacuum + // step of same length is half a + MaterialProperties halfA = a; + halfA *= 0.5; + halfA.scaleToUnitThickness(); + + AccumulatedMaterialProperties av; + av.accumulate(a); + av.trackAverage(); + av.accumulate(v); + av.trackAverage(); + auto averageAV = av.totalAverage(); + auto matAV = averageAV.first; + + BOOST_CHECK_EQUAL(halfA.thicknessInX0(), matAV.thicknessInX0()); + BOOST_CHECK_EQUAL(halfA.thicknessInL0(), matAV.thicknessInL0()); + CHECK_CLOSE_REL(halfA.averageRho() * halfA.thickness(), + matAV.averageRho() * matAV.thickness(), 0.0001); + BOOST_CHECK_EQUAL(2, averageAV.second); + + // Test: + // average of a + 3*a -> 2*a + MaterialProperties doubleA = a; + doubleA *= 2.; + + AccumulatedMaterialProperties aa3; + aa3.accumulate(a); + aa3.trackAverage(); + aa3.accumulate(a3); + aa3.trackAverage(); + auto averageAA3 = aa3.totalAverage(); + auto matAA3 = averageAA3.first; + + BOOST_CHECK_EQUAL(doubleA.thicknessInX0(), matAA3.thicknessInX0()); + BOOST_CHECK_EQUAL(doubleA.thicknessInL0(), matAA3.thicknessInL0()); + CHECK_CLOSE_REL(doubleA.averageRho() * doubleA.thickness(), + matAA3.averageRho() * matAA3.thickness(), 0.0001); + BOOST_CHECK_EQUAL(2, averageAA3.second); + + /// Test: + /// average a + 3a + v + + AccumulatedMaterialProperties aa3v; + aa3v.accumulate(a); + aa3v.trackAverage(); + aa3v.accumulate(a3); + aa3v.trackAverage(); + aa3v.accumulate(v); + aa3v.trackAverage(); + auto averageAA3V = aa3v.totalAverage(); + auto matAA3V = averageAA3V.first; + + CHECK_CLOSE_REL(4. / 3., matAA3V.thicknessInX0(), 0.00001); + BOOST_CHECK_EQUAL(3, averageAA3V.second); + + /// Test: + /// average 4a + v + AccumulatedMaterialProperties a4v; + a4v.accumulate(a); + a4v.accumulate(a3); + a4v.trackAverage(); + a4v.accumulate(v); + a4v.trackAverage(); + auto averageA4V = a4v.totalAverage(); + auto matA4V = averageA4V.first; + + CHECK_CLOSE_REL(doubleA.thicknessInX0(), matA4V.thicknessInX0(), 0.00001); + BOOST_CHECK_EQUAL(2, averageA4V.second); +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/Material/AccumulatedSurfaceMaterialTests.cpp b/Tests/Core/Material/AccumulatedSurfaceMaterialTests.cpp index 576fbc1b8d72a690ac65626f3d8a87b05f7ecc4c..e74f35c2e04239149a11c7e2d437de85a52c4b35 100644 --- a/Tests/Core/Material/AccumulatedSurfaceMaterialTests.cpp +++ b/Tests/Core/Material/AccumulatedSurfaceMaterialTests.cpp @@ -17,113 +17,107 @@ namespace Acts { namespace Test { - /// Test the constructors - BOOST_AUTO_TEST_CASE(AccumulatedSurfaceMaterial_construction_test) - { - // Test: - // HomogeneousSurfaceMaterial accumulation - AccumulatedSurfaceMaterial material0D{}; - auto accMat0D = material0D.accumulatedMaterial(); - BOOST_CHECK_EQUAL(accMat0D.size(), 1); - BOOST_CHECK_EQUAL(accMat0D[0].size(), 1); - BOOST_CHECK_EQUAL(material0D.splitFactor(), 0.); - - // Test: - // BinnesSurfaceMatieral accumulation - 1D - BinUtility binUtility1D(10, -5., 5., open, binX); - AccumulatedSurfaceMaterial material1D{binUtility1D}; - auto accMat1D = material1D.accumulatedMaterial(); - BOOST_CHECK_EQUAL(accMat1D.size(), 1); - BOOST_CHECK_EQUAL(accMat1D[0].size(), 10); - - // Test: - // BinnesSurfaceMatieral accumulation - 2D - BinUtility binUtility2D(10, -5., 5., open, binX); - binUtility2D += BinUtility(20, -10., 10., open, binY); - AccumulatedSurfaceMaterial material2D{binUtility2D}; - auto accMat2D = material2D.accumulatedMaterial(); - BOOST_CHECK_EQUAL(accMat2D.size(), 20); - for (size_t ib = 0; ib < accMat2D.size(); ++ib) { - BOOST_CHECK_EQUAL(accMat2D[ib].size(), 10); - } - } - - /// Test the filling and conversion - BOOST_AUTO_TEST_CASE(AccumulatedSurfaceMaterial_fill_convert_0D) - { - - MaterialProperties one(1., 1., 1., 1., 1., 1.); - MaterialProperties two(1., 1., 1., 1., 1., 2.); - - AccumulatedSurfaceMaterial material0D{}; - // assign 2 one steps - material0D.accumulate(Vector2D{0., 0.}, one); - material0D.accumulate(Vector2D{0., 0.}, one); - material0D.trackAverage(); - // assign 1 double step - material0D.accumulate(Vector3D(0., 0., 0.), two); - material0D.trackAverage(); - // get the single matrix - auto accMat0D = material0D.accumulatedMaterial(); - auto accMatProp0D = accMat0D[0][0]; - auto matProp0D = accMatProp0D.totalAverage(); - - BOOST_CHECK_EQUAL(matProp0D.second, 2); - BOOST_CHECK_EQUAL(matProp0D.first.thicknessInX0(), two.thicknessInX0()); - } - - /// Test the filling and conversion - BOOST_AUTO_TEST_CASE(AccumulatedSurfaceMaterial_fill_convert_1D) - { - - MaterialProperties one(1., 1., 1., 1., 1., 1.); - MaterialProperties two(1., 1., 1., 1., 1., 2.); - MaterialProperties three(1., 1., 1., 1., 1., 3.); - MaterialProperties four(1., 1., 1., 1., 1., 4.); - - // BinnesSurfaceMatieral accumulation - 2D - BinUtility binUtility2D(2, -1., 1., open, binX); - binUtility2D += BinUtility(2, -1., 1., open, binY); - AccumulatedSurfaceMaterial material2D{binUtility2D}; - - // assign in the different bins - // event 0 - material2D.accumulate(Vector2D{-0.5, -0.5}, one); - material2D.accumulate(Vector2D{0.5, -0.5}, two); - material2D.accumulate(Vector2D{-0.5, 0.5}, three); - material2D.accumulate(Vector2D{0.5, 0.5}, four); - material2D.trackAverage(); - // event 1 - material2D.accumulate(Vector2D{0.5, -0.5}, two); - material2D.accumulate(Vector2D{-0.5, 0.5}, three); - material2D.accumulate(Vector2D{0.5, 0.5}, four); - material2D.trackAverage(); - // event 2 - material2D.accumulate(Vector2D{-0.5, 0.5}, three); - material2D.accumulate(Vector2D{0.5, 0.5}, four); - material2D.trackAverage(); - // event 2 - material2D.accumulate(Vector2D{0.5, 0.5}, four); - material2D.trackAverage(); - // get the single matrix - auto accMat2D = material2D.accumulatedMaterial(); - // the accumulated properties - auto accMatProp00 = accMat2D[0][0].totalAverage(); - auto accMatProp01 = accMat2D[0][1].totalAverage(); - auto accMatProp10 = accMat2D[1][0].totalAverage(); - auto accMatProp11 = accMat2D[1][1].totalAverage(); - - BOOST_CHECK_EQUAL(accMatProp00.second, 1); - BOOST_CHECK_EQUAL(accMatProp01.second, 2); - BOOST_CHECK_EQUAL(accMatProp10.second, 3); - BOOST_CHECK_EQUAL(accMatProp11.second, 4); - - BOOST_CHECK_EQUAL(accMatProp00.first.thicknessInX0(), one.thicknessInX0()); - BOOST_CHECK_EQUAL(accMatProp01.first.thicknessInX0(), two.thicknessInX0()); - BOOST_CHECK_EQUAL(accMatProp10.first.thicknessInX0(), - three.thicknessInX0()); - BOOST_CHECK_EQUAL(accMatProp11.first.thicknessInX0(), four.thicknessInX0()); +/// Test the constructors +BOOST_AUTO_TEST_CASE(AccumulatedSurfaceMaterial_construction_test) { + // Test: + // HomogeneousSurfaceMaterial accumulation + AccumulatedSurfaceMaterial material0D{}; + auto accMat0D = material0D.accumulatedMaterial(); + BOOST_CHECK_EQUAL(accMat0D.size(), 1); + BOOST_CHECK_EQUAL(accMat0D[0].size(), 1); + BOOST_CHECK_EQUAL(material0D.splitFactor(), 0.); + + // Test: + // BinnesSurfaceMatieral accumulation - 1D + BinUtility binUtility1D(10, -5., 5., open, binX); + AccumulatedSurfaceMaterial material1D{binUtility1D}; + auto accMat1D = material1D.accumulatedMaterial(); + BOOST_CHECK_EQUAL(accMat1D.size(), 1); + BOOST_CHECK_EQUAL(accMat1D[0].size(), 10); + + // Test: + // BinnesSurfaceMatieral accumulation - 2D + BinUtility binUtility2D(10, -5., 5., open, binX); + binUtility2D += BinUtility(20, -10., 10., open, binY); + AccumulatedSurfaceMaterial material2D{binUtility2D}; + auto accMat2D = material2D.accumulatedMaterial(); + BOOST_CHECK_EQUAL(accMat2D.size(), 20); + for (size_t ib = 0; ib < accMat2D.size(); ++ib) { + BOOST_CHECK_EQUAL(accMat2D[ib].size(), 10); } +} + +/// Test the filling and conversion +BOOST_AUTO_TEST_CASE(AccumulatedSurfaceMaterial_fill_convert_0D) { + MaterialProperties one(1., 1., 1., 1., 1., 1.); + MaterialProperties two(1., 1., 1., 1., 1., 2.); + + AccumulatedSurfaceMaterial material0D{}; + // assign 2 one steps + material0D.accumulate(Vector2D{0., 0.}, one); + material0D.accumulate(Vector2D{0., 0.}, one); + material0D.trackAverage(); + // assign 1 double step + material0D.accumulate(Vector3D(0., 0., 0.), two); + material0D.trackAverage(); + // get the single matrix + auto accMat0D = material0D.accumulatedMaterial(); + auto accMatProp0D = accMat0D[0][0]; + auto matProp0D = accMatProp0D.totalAverage(); + + BOOST_CHECK_EQUAL(matProp0D.second, 2); + BOOST_CHECK_EQUAL(matProp0D.first.thicknessInX0(), two.thicknessInX0()); +} + +/// Test the filling and conversion +BOOST_AUTO_TEST_CASE(AccumulatedSurfaceMaterial_fill_convert_1D) { + MaterialProperties one(1., 1., 1., 1., 1., 1.); + MaterialProperties two(1., 1., 1., 1., 1., 2.); + MaterialProperties three(1., 1., 1., 1., 1., 3.); + MaterialProperties four(1., 1., 1., 1., 1., 4.); + + // BinnesSurfaceMatieral accumulation - 2D + BinUtility binUtility2D(2, -1., 1., open, binX); + binUtility2D += BinUtility(2, -1., 1., open, binY); + AccumulatedSurfaceMaterial material2D{binUtility2D}; + + // assign in the different bins + // event 0 + material2D.accumulate(Vector2D{-0.5, -0.5}, one); + material2D.accumulate(Vector2D{0.5, -0.5}, two); + material2D.accumulate(Vector2D{-0.5, 0.5}, three); + material2D.accumulate(Vector2D{0.5, 0.5}, four); + material2D.trackAverage(); + // event 1 + material2D.accumulate(Vector2D{0.5, -0.5}, two); + material2D.accumulate(Vector2D{-0.5, 0.5}, three); + material2D.accumulate(Vector2D{0.5, 0.5}, four); + material2D.trackAverage(); + // event 2 + material2D.accumulate(Vector2D{-0.5, 0.5}, three); + material2D.accumulate(Vector2D{0.5, 0.5}, four); + material2D.trackAverage(); + // event 2 + material2D.accumulate(Vector2D{0.5, 0.5}, four); + material2D.trackAverage(); + // get the single matrix + auto accMat2D = material2D.accumulatedMaterial(); + // the accumulated properties + auto accMatProp00 = accMat2D[0][0].totalAverage(); + auto accMatProp01 = accMat2D[0][1].totalAverage(); + auto accMatProp10 = accMat2D[1][0].totalAverage(); + auto accMatProp11 = accMat2D[1][1].totalAverage(); + + BOOST_CHECK_EQUAL(accMatProp00.second, 1); + BOOST_CHECK_EQUAL(accMatProp01.second, 2); + BOOST_CHECK_EQUAL(accMatProp10.second, 3); + BOOST_CHECK_EQUAL(accMatProp11.second, 4); + + BOOST_CHECK_EQUAL(accMatProp00.first.thicknessInX0(), one.thicknessInX0()); + BOOST_CHECK_EQUAL(accMatProp01.first.thicknessInX0(), two.thicknessInX0()); + BOOST_CHECK_EQUAL(accMatProp10.first.thicknessInX0(), three.thicknessInX0()); + BOOST_CHECK_EQUAL(accMatProp11.first.thicknessInX0(), four.thicknessInX0()); +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/Material/AccumulatedVolumeMaterialTests.cpp b/Tests/Core/Material/AccumulatedVolumeMaterialTests.cpp index cd8bd5b001e8a07be246c1270864dd6e1fc12c70..bf87560852a9f235a1d13e4993988da5fb0b3f12 100644 --- a/Tests/Core/Material/AccumulatedVolumeMaterialTests.cpp +++ b/Tests/Core/Material/AccumulatedVolumeMaterialTests.cpp @@ -18,58 +18,57 @@ namespace Acts { namespace Test { - BOOST_AUTO_TEST_CASE(AccumulatedMaterialMaterial_test) - { - AccumulatedVolumeMaterial avm; +BOOST_AUTO_TEST_CASE(AccumulatedMaterialMaterial_test) { + AccumulatedVolumeMaterial avm; - // Try averaging without content - Material result = avm.average(); - BOOST_CHECK_EQUAL(result, Material()); + // Try averaging without content + Material result = avm.average(); + BOOST_CHECK_EQUAL(result, Material()); - // Test that the mean of a single material is the material itself - Material mat1(1., 2., 3., 4., 5.); - avm.accumulate(mat1); - result = avm.average(); - CHECK_CLOSE_REL(result.X0(), mat1.X0(), 1e-4); - CHECK_CLOSE_REL(result.L0(), mat1.L0(), 1e-4); - CHECK_CLOSE_REL(result.A(), mat1.A(), 1e-4); - CHECK_CLOSE_REL(result.Z(), mat1.Z(), 1e-4); - CHECK_CLOSE_REL(result.rho(), mat1.rho(), 1e-4); + // Test that the mean of a single material is the material itself + Material mat1(1., 2., 3., 4., 5.); + avm.accumulate(mat1); + result = avm.average(); + CHECK_CLOSE_REL(result.X0(), mat1.X0(), 1e-4); + CHECK_CLOSE_REL(result.L0(), mat1.L0(), 1e-4); + CHECK_CLOSE_REL(result.A(), mat1.A(), 1e-4); + CHECK_CLOSE_REL(result.Z(), mat1.Z(), 1e-4); + CHECK_CLOSE_REL(result.rho(), mat1.rho(), 1e-4); - // Test that the mean is actually calculated - Material mat2(6., 7., 8., 9., 10.); - avm.accumulate(mat2); - result = avm.average(); - CHECK_CLOSE_REL(result.X0(), 0.5 * (mat1.X0() + mat2.X0()), 1e-4); - CHECK_CLOSE_REL(result.L0(), 0.5 * (mat1.L0() + mat2.L0()), 1e-4); - CHECK_CLOSE_REL(result.A(), 0.5 * (mat1.A() + mat2.A()), 1e-4); - CHECK_CLOSE_REL(result.Z(), 0.5 * (mat1.Z() + mat2.Z()), 1e-4); - CHECK_CLOSE_REL(result.rho(), 0.5 * (mat1.rho() + mat2.rho()), 1e-4); + // Test that the mean is actually calculated + Material mat2(6., 7., 8., 9., 10.); + avm.accumulate(mat2); + result = avm.average(); + CHECK_CLOSE_REL(result.X0(), 0.5 * (mat1.X0() + mat2.X0()), 1e-4); + CHECK_CLOSE_REL(result.L0(), 0.5 * (mat1.L0() + mat2.L0()), 1e-4); + CHECK_CLOSE_REL(result.A(), 0.5 * (mat1.A() + mat2.A()), 1e-4); + CHECK_CLOSE_REL(result.Z(), 0.5 * (mat1.Z() + mat2.Z()), 1e-4); + CHECK_CLOSE_REL(result.rho(), 0.5 * (mat1.rho() + mat2.rho()), 1e-4); - // Test that the mean of vacuums is a vacuum - AccumulatedVolumeMaterial avm2; - avm2.accumulate(Material()); - avm2.accumulate(Material()); - result = avm2.average(); - BOOST_CHECK_EQUAL(result, Material()); + // Test that the mean of vacuums is a vacuum + AccumulatedVolumeMaterial avm2; + avm2.accumulate(Material()); + avm2.accumulate(Material()); + result = avm2.average(); + BOOST_CHECK_EQUAL(result, Material()); - // Add vacuum to the material and test it - avm.accumulate(Material()); - result = avm.average(); - CHECK_CLOSE_REL(result.X0(), 0.25 * (mat1.X0() + mat2.X0()) * 3, 1e-4); - CHECK_CLOSE_REL(result.L0(), 0.25 * (mat1.L0() + mat2.L0()) * 3, 1e-4); - CHECK_CLOSE_REL(result.A(), (mat1.A() + mat2.A()) / 3, 1e-4); - CHECK_CLOSE_REL(result.Z(), (mat1.Z() + mat2.Z()) / 3, 1e-4); - CHECK_CLOSE_REL(result.rho(), (mat1.rho() + mat2.rho()) / 3, 1e-4); + // Add vacuum to the material and test it + avm.accumulate(Material()); + result = avm.average(); + CHECK_CLOSE_REL(result.X0(), 0.25 * (mat1.X0() + mat2.X0()) * 3, 1e-4); + CHECK_CLOSE_REL(result.L0(), 0.25 * (mat1.L0() + mat2.L0()) * 3, 1e-4); + CHECK_CLOSE_REL(result.A(), (mat1.A() + mat2.A()) / 3, 1e-4); + CHECK_CLOSE_REL(result.Z(), (mat1.Z() + mat2.Z()) / 3, 1e-4); + CHECK_CLOSE_REL(result.rho(), (mat1.rho() + mat2.rho()) / 3, 1e-4); - // Add material to the vacuum and test it - avm2.accumulate(mat1); - result = avm2.average(); - CHECK_CLOSE_REL(result.X0(), mat1.X0() * 3, 1e-4); - CHECK_CLOSE_REL(result.L0(), mat1.L0() * 3, 1e-4); - CHECK_CLOSE_REL(result.A(), mat1.A() / 3, 1e-4); - CHECK_CLOSE_REL(result.Z(), mat1.Z() / 3, 1e-4); - CHECK_CLOSE_REL(result.rho(), mat1.rho() / 3, 1e-4); - } + // Add material to the vacuum and test it + avm2.accumulate(mat1); + result = avm2.average(); + CHECK_CLOSE_REL(result.X0(), mat1.X0() * 3, 1e-4); + CHECK_CLOSE_REL(result.L0(), mat1.L0() * 3, 1e-4); + CHECK_CLOSE_REL(result.A(), mat1.A() / 3, 1e-4); + CHECK_CLOSE_REL(result.Z(), mat1.Z() / 3, 1e-4); + CHECK_CLOSE_REL(result.rho(), mat1.rho() / 3, 1e-4); +} } // namespace Test } // namespace Acts \ No newline at end of file diff --git a/Tests/Core/Material/BinnedSurfaceMaterialTests.cpp b/Tests/Core/Material/BinnedSurfaceMaterialTests.cpp index 864eca112e70a2729d9712c06b947f030e412e41..02c8da834b0734803c02ca2d04bb35cba01c202d 100644 --- a/Tests/Core/Material/BinnedSurfaceMaterialTests.cpp +++ b/Tests/Core/Material/BinnedSurfaceMaterialTests.cpp @@ -20,45 +20,43 @@ namespace Acts { namespace Test { - /// Test the constructors - BOOST_AUTO_TEST_CASE(BinnedSurfaceMaterial_construction_test) - { - - BinUtility xyBinning(2, -1., 1., open, binX); - xyBinning += BinUtility(3, -3., 3., open, binY); - - // Constructor a few material properties - MaterialProperties a00(1., 2., 3., 4., 5., 6.); - MaterialProperties a01(2., 3., 4., 5., 6., 7.); - MaterialProperties a02(3., 4., 5., 6., 7., 8.); - MaterialProperties a10(4., 5., 6., 7., 8., 9.); - MaterialProperties a11(5., 6., 7., 8., 9., 10.); - MaterialProperties a12(6., 7., 8., 9., 10., 11.); - - // Prepare the matrix - std::vector<MaterialProperties> l0 = {std::move(a00), std::move(a10)}; - std::vector<MaterialProperties> l1 = {std::move(a01), std::move(a11)}; - std::vector<MaterialProperties> l2 = {std::move(a02), std::move(a12)}; - - // Build the matrix - std::vector<std::vector<MaterialProperties>> m - = {std::move(l0), std::move(l1), std::move(l2)}; - - // Create the material - BinnedSurfaceMaterial bsm(xyBinning, std::move(m)); - - // Copy the material - BinnedSurfaceMaterial bsmCopy(bsm); - - // Assignment operation - BinnedSurfaceMaterial bsmAssigned = bsm; - - // Move constructor - BinnedSurfaceMaterial bsmMoved(std::move(bsmCopy)); - - // Move assigned - BinnedSurfaceMaterial bsmMoveAssigned(std::move(bsmAssigned)); - } +/// Test the constructors +BOOST_AUTO_TEST_CASE(BinnedSurfaceMaterial_construction_test) { + BinUtility xyBinning(2, -1., 1., open, binX); + xyBinning += BinUtility(3, -3., 3., open, binY); + + // Constructor a few material properties + MaterialProperties a00(1., 2., 3., 4., 5., 6.); + MaterialProperties a01(2., 3., 4., 5., 6., 7.); + MaterialProperties a02(3., 4., 5., 6., 7., 8.); + MaterialProperties a10(4., 5., 6., 7., 8., 9.); + MaterialProperties a11(5., 6., 7., 8., 9., 10.); + MaterialProperties a12(6., 7., 8., 9., 10., 11.); + + // Prepare the matrix + std::vector<MaterialProperties> l0 = {std::move(a00), std::move(a10)}; + std::vector<MaterialProperties> l1 = {std::move(a01), std::move(a11)}; + std::vector<MaterialProperties> l2 = {std::move(a02), std::move(a12)}; + + // Build the matrix + std::vector<std::vector<MaterialProperties>> m = { + std::move(l0), std::move(l1), std::move(l2)}; + + // Create the material + BinnedSurfaceMaterial bsm(xyBinning, std::move(m)); + + // Copy the material + BinnedSurfaceMaterial bsmCopy(bsm); + + // Assignment operation + BinnedSurfaceMaterial bsmAssigned = bsm; + + // Move constructor + BinnedSurfaceMaterial bsmMoved(std::move(bsmCopy)); + + // Move assigned + BinnedSurfaceMaterial bsmMoveAssigned(std::move(bsmAssigned)); +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/Material/HomogeneousSurfaceMaterialTests.cpp b/Tests/Core/Material/HomogeneousSurfaceMaterialTests.cpp index 86183e9d9700e8645f8c14ca0432e0e4182acd90..96797273b166e1e9ea3c61d9cb8bab3e13377fa1 100644 --- a/Tests/Core/Material/HomogeneousSurfaceMaterialTests.cpp +++ b/Tests/Core/Material/HomogeneousSurfaceMaterialTests.cpp @@ -23,165 +23,157 @@ namespace Acts { namespace Test { - /// Test the constructors - BOOST_AUTO_TEST_CASE(HomogeneousSurfaceMaterial_construction_test) - { - // construct the material properties from arguments - MaterialProperties mp(1., 2., 3., 4., 5., 0.1); - - // Constructor from arguments - HomogeneousSurfaceMaterial hsm(mp, 1.); - // Copy constructor - HomogeneousSurfaceMaterial hsmCopy(hsm); - // Test equality of the copy - BOOST_CHECK_EQUAL(hsm, hsmCopy); - // Copy move constructor - HomogeneousSurfaceMaterial hsmCopyMoved(std::move(hsmCopy)); - // Test equality of the copy - BOOST_CHECK_EQUAL(hsm, hsmCopyMoved); - // Assignment constructor - HomogeneousSurfaceMaterial hsmAssigned = hsm; - // Test equality of the asignment - BOOST_CHECK_EQUAL(hsm, hsmAssigned); - // Assignment move constructor - HomogeneousSurfaceMaterial hsmAssignedMoved(std::move(hsmAssigned)); - // Test equality of the copy - BOOST_CHECK_EQUAL(hsm, hsmAssignedMoved); - } - - // Test the Scaling - BOOST_AUTO_TEST_CASE(HomogeneousSurfaceMaterial_scaling_test) - { - - // Construct the material properties from arguments - MaterialProperties mat(1., 2., 3., 4., 5., 0.1); - MaterialProperties matHalf = mat; - matHalf *= 0.5; - - HomogeneousSurfaceMaterial hsm(mat, 1.); - hsm *= 0.5; - - auto matBin = hsm.materialProperties(0, 0); - - BOOST_CHECK_EQUAL(matBin, matHalf); - BOOST_CHECK_NE(matBin, mat); - } - - // Test the Access - BOOST_AUTO_TEST_CASE(HomogeneousSurfaceMaterial_access_test) - { - // construct the material properties from arguments - MaterialProperties mat(1., 2., 3., 4., 5., 0.1); - MaterialProperties matHalf = mat; - matHalf *= 0.5; - - MaterialProperties vacuum = MaterialProperties(); - - // Constructor from arguments - HomogeneousSurfaceMaterial hsmfwd(mat, 1.); - HomogeneousSurfaceMaterial hsmhalf(mat, 0.5); - HomogeneousSurfaceMaterial hsmbwd(mat, 0.); - - auto mat2d = hsmfwd.materialProperties(Vector2D{0., 0.}); - auto mat3d = hsmfwd.materialProperties(Vector3D{0., 0., 0.}); - auto matbin = hsmfwd.materialProperties(0, 0); - - // Test equality of the copy - BOOST_CHECK_EQUAL(mat, mat2d); - BOOST_CHECK_EQUAL(mat, mat3d); - BOOST_CHECK_EQUAL(mat, matbin); - - NavigationDirection fDir = forward; - NavigationDirection bDir = backward; - - MaterialUpdateStage pre = preUpdate; - MaterialUpdateStage full = fullUpdate; - MaterialUpdateStage post = postUpdate; - - // (a) Forward factor material test - BOOST_CHECK_EQUAL(hsmfwd.factor(fDir, full), 1.); - BOOST_CHECK_EQUAL(hsmfwd.factor(fDir, pre), 0.); - BOOST_CHECK_EQUAL(hsmfwd.factor(fDir, post), 1.); - - BOOST_CHECK_EQUAL(hsmfwd.factor(bDir, full), 1.); - BOOST_CHECK_EQUAL(hsmfwd.factor(bDir, pre), 1.); - BOOST_CHECK_EQUAL(hsmfwd.factor(bDir, post), 0.); - - auto matFwdFull - = hsmfwd.materialProperties(Vector3D{0., 0., 0.}, fDir, full); - auto matBwdFull - = hsmfwd.materialProperties(Vector3D{0., 0., 0.}, bDir, full); - - auto matFwdPost - = hsmfwd.materialProperties(Vector3D{0., 0., 0.}, fDir, post); - auto matBwdPost - = hsmfwd.materialProperties(Vector3D{0., 0., 0.}, bDir, post); - - auto matFwdPre = hsmfwd.materialProperties(Vector3D{0., 0., 0.}, fDir, pre); - auto matBwdPre = hsmfwd.materialProperties(Vector3D{0., 0., 0.}, bDir, pre); - - BOOST_CHECK_EQUAL(mat, matFwdFull); - BOOST_CHECK_EQUAL(mat, matBwdFull); - - BOOST_CHECK_EQUAL(mat, matFwdPost); - BOOST_CHECK_EQUAL(vacuum, matBwdPost); - - BOOST_CHECK_EQUAL(vacuum, matFwdPre); - BOOST_CHECK_EQUAL(mat, matBwdPre); - - // (b) Split factor material test - BOOST_CHECK_EQUAL(hsmhalf.factor(fDir, full), 1.); - CHECK_CLOSE_REL(hsmhalf.factor(fDir, pre), 0.5, 1e-6); - CHECK_CLOSE_REL(hsmhalf.factor(fDir, post), 0.5, 1e-6); - - BOOST_CHECK_EQUAL(hsmhalf.factor(bDir, full), 1.); - CHECK_CLOSE_REL(hsmhalf.factor(bDir, pre), 0.5, 1e-6); - CHECK_CLOSE_REL(hsmhalf.factor(bDir, post), 0.5, 1e-6); +/// Test the constructors +BOOST_AUTO_TEST_CASE(HomogeneousSurfaceMaterial_construction_test) { + // construct the material properties from arguments + MaterialProperties mp(1., 2., 3., 4., 5., 0.1); + + // Constructor from arguments + HomogeneousSurfaceMaterial hsm(mp, 1.); + // Copy constructor + HomogeneousSurfaceMaterial hsmCopy(hsm); + // Test equality of the copy + BOOST_CHECK_EQUAL(hsm, hsmCopy); + // Copy move constructor + HomogeneousSurfaceMaterial hsmCopyMoved(std::move(hsmCopy)); + // Test equality of the copy + BOOST_CHECK_EQUAL(hsm, hsmCopyMoved); + // Assignment constructor + HomogeneousSurfaceMaterial hsmAssigned = hsm; + // Test equality of the asignment + BOOST_CHECK_EQUAL(hsm, hsmAssigned); + // Assignment move constructor + HomogeneousSurfaceMaterial hsmAssignedMoved(std::move(hsmAssigned)); + // Test equality of the copy + BOOST_CHECK_EQUAL(hsm, hsmAssignedMoved); +} - matFwdFull = hsmhalf.materialProperties(Vector3D{0., 0., 0.}, fDir, full); - matBwdFull = hsmhalf.materialProperties(Vector3D{0., 0., 0.}, bDir, full); +// Test the Scaling +BOOST_AUTO_TEST_CASE(HomogeneousSurfaceMaterial_scaling_test) { + // Construct the material properties from arguments + MaterialProperties mat(1., 2., 3., 4., 5., 0.1); + MaterialProperties matHalf = mat; + matHalf *= 0.5; - matFwdPost = hsmhalf.materialProperties(Vector3D{0., 0., 0.}, fDir, post); - matBwdPost = hsmhalf.materialProperties(Vector3D{0., 0., 0.}, bDir, post); + HomogeneousSurfaceMaterial hsm(mat, 1.); + hsm *= 0.5; - matFwdPre = hsmhalf.materialProperties(Vector3D{0., 0., 0.}, fDir, pre); - matBwdPre = hsmhalf.materialProperties(Vector3D{0., 0., 0.}, bDir, pre); + auto matBin = hsm.materialProperties(0, 0); - BOOST_CHECK_EQUAL(mat, matFwdFull); - BOOST_CHECK_EQUAL(mat, matBwdFull); + BOOST_CHECK_EQUAL(matBin, matHalf); + BOOST_CHECK_NE(matBin, mat); +} - BOOST_CHECK_EQUAL(matHalf, matFwdPost); - BOOST_CHECK_EQUAL(matHalf, matBwdPost); +// Test the Access +BOOST_AUTO_TEST_CASE(HomogeneousSurfaceMaterial_access_test) { + // construct the material properties from arguments + MaterialProperties mat(1., 2., 3., 4., 5., 0.1); + MaterialProperties matHalf = mat; + matHalf *= 0.5; - BOOST_CHECK_EQUAL(matHalf, matFwdPre); - BOOST_CHECK_EQUAL(matHalf, matBwdPre); + MaterialProperties vacuum = MaterialProperties(); - // c) Forward factor material test - BOOST_CHECK_EQUAL(hsmbwd.factor(fDir, full), 1.); - BOOST_CHECK_EQUAL(hsmbwd.factor(fDir, pre), 1.); - BOOST_CHECK_EQUAL(hsmbwd.factor(fDir, post), 0.); + // Constructor from arguments + HomogeneousSurfaceMaterial hsmfwd(mat, 1.); + HomogeneousSurfaceMaterial hsmhalf(mat, 0.5); + HomogeneousSurfaceMaterial hsmbwd(mat, 0.); - BOOST_CHECK_EQUAL(hsmbwd.factor(bDir, full), 1.); - BOOST_CHECK_EQUAL(hsmbwd.factor(bDir, pre), 0.); - BOOST_CHECK_EQUAL(hsmbwd.factor(bDir, post), 1.); + auto mat2d = hsmfwd.materialProperties(Vector2D{0., 0.}); + auto mat3d = hsmfwd.materialProperties(Vector3D{0., 0., 0.}); + auto matbin = hsmfwd.materialProperties(0, 0); - matFwdFull = hsmbwd.materialProperties(Vector3D{0., 0., 0.}, fDir, full); - matBwdFull = hsmbwd.materialProperties(Vector3D{0., 0., 0.}, bDir, full); + // Test equality of the copy + BOOST_CHECK_EQUAL(mat, mat2d); + BOOST_CHECK_EQUAL(mat, mat3d); + BOOST_CHECK_EQUAL(mat, matbin); - matFwdPost = hsmbwd.materialProperties(Vector3D{0., 0., 0.}, fDir, post); - matBwdPost = hsmbwd.materialProperties(Vector3D{0., 0., 0.}, bDir, post); + NavigationDirection fDir = forward; + NavigationDirection bDir = backward; - matFwdPre = hsmbwd.materialProperties(Vector3D{0., 0., 0.}, fDir, pre); - matBwdPre = hsmbwd.materialProperties(Vector3D{0., 0., 0.}, bDir, pre); + MaterialUpdateStage pre = preUpdate; + MaterialUpdateStage full = fullUpdate; + MaterialUpdateStage post = postUpdate; - BOOST_CHECK_EQUAL(mat, matFwdFull); - BOOST_CHECK_EQUAL(mat, matBwdFull); + // (a) Forward factor material test + BOOST_CHECK_EQUAL(hsmfwd.factor(fDir, full), 1.); + BOOST_CHECK_EQUAL(hsmfwd.factor(fDir, pre), 0.); + BOOST_CHECK_EQUAL(hsmfwd.factor(fDir, post), 1.); - BOOST_CHECK_EQUAL(vacuum, matFwdPost); - BOOST_CHECK_EQUAL(mat, matBwdPost); + BOOST_CHECK_EQUAL(hsmfwd.factor(bDir, full), 1.); + BOOST_CHECK_EQUAL(hsmfwd.factor(bDir, pre), 1.); + BOOST_CHECK_EQUAL(hsmfwd.factor(bDir, post), 0.); - BOOST_CHECK_EQUAL(mat, matFwdPre); - BOOST_CHECK_EQUAL(vacuum, matBwdPre); - } -} + auto matFwdFull = hsmfwd.materialProperties(Vector3D{0., 0., 0.}, fDir, full); + auto matBwdFull = hsmfwd.materialProperties(Vector3D{0., 0., 0.}, bDir, full); + + auto matFwdPost = hsmfwd.materialProperties(Vector3D{0., 0., 0.}, fDir, post); + auto matBwdPost = hsmfwd.materialProperties(Vector3D{0., 0., 0.}, bDir, post); + + auto matFwdPre = hsmfwd.materialProperties(Vector3D{0., 0., 0.}, fDir, pre); + auto matBwdPre = hsmfwd.materialProperties(Vector3D{0., 0., 0.}, bDir, pre); + + BOOST_CHECK_EQUAL(mat, matFwdFull); + BOOST_CHECK_EQUAL(mat, matBwdFull); + + BOOST_CHECK_EQUAL(mat, matFwdPost); + BOOST_CHECK_EQUAL(vacuum, matBwdPost); + + BOOST_CHECK_EQUAL(vacuum, matFwdPre); + BOOST_CHECK_EQUAL(mat, matBwdPre); + + // (b) Split factor material test + BOOST_CHECK_EQUAL(hsmhalf.factor(fDir, full), 1.); + CHECK_CLOSE_REL(hsmhalf.factor(fDir, pre), 0.5, 1e-6); + CHECK_CLOSE_REL(hsmhalf.factor(fDir, post), 0.5, 1e-6); + + BOOST_CHECK_EQUAL(hsmhalf.factor(bDir, full), 1.); + CHECK_CLOSE_REL(hsmhalf.factor(bDir, pre), 0.5, 1e-6); + CHECK_CLOSE_REL(hsmhalf.factor(bDir, post), 0.5, 1e-6); + + matFwdFull = hsmhalf.materialProperties(Vector3D{0., 0., 0.}, fDir, full); + matBwdFull = hsmhalf.materialProperties(Vector3D{0., 0., 0.}, bDir, full); + + matFwdPost = hsmhalf.materialProperties(Vector3D{0., 0., 0.}, fDir, post); + matBwdPost = hsmhalf.materialProperties(Vector3D{0., 0., 0.}, bDir, post); + + matFwdPre = hsmhalf.materialProperties(Vector3D{0., 0., 0.}, fDir, pre); + matBwdPre = hsmhalf.materialProperties(Vector3D{0., 0., 0.}, bDir, pre); + + BOOST_CHECK_EQUAL(mat, matFwdFull); + BOOST_CHECK_EQUAL(mat, matBwdFull); + + BOOST_CHECK_EQUAL(matHalf, matFwdPost); + BOOST_CHECK_EQUAL(matHalf, matBwdPost); + + BOOST_CHECK_EQUAL(matHalf, matFwdPre); + BOOST_CHECK_EQUAL(matHalf, matBwdPre); + + // c) Forward factor material test + BOOST_CHECK_EQUAL(hsmbwd.factor(fDir, full), 1.); + BOOST_CHECK_EQUAL(hsmbwd.factor(fDir, pre), 1.); + BOOST_CHECK_EQUAL(hsmbwd.factor(fDir, post), 0.); + + BOOST_CHECK_EQUAL(hsmbwd.factor(bDir, full), 1.); + BOOST_CHECK_EQUAL(hsmbwd.factor(bDir, pre), 0.); + BOOST_CHECK_EQUAL(hsmbwd.factor(bDir, post), 1.); + + matFwdFull = hsmbwd.materialProperties(Vector3D{0., 0., 0.}, fDir, full); + matBwdFull = hsmbwd.materialProperties(Vector3D{0., 0., 0.}, bDir, full); + + matFwdPost = hsmbwd.materialProperties(Vector3D{0., 0., 0.}, fDir, post); + matBwdPost = hsmbwd.materialProperties(Vector3D{0., 0., 0.}, bDir, post); + + matFwdPre = hsmbwd.materialProperties(Vector3D{0., 0., 0.}, fDir, pre); + matBwdPre = hsmbwd.materialProperties(Vector3D{0., 0., 0.}, bDir, pre); + + BOOST_CHECK_EQUAL(mat, matFwdFull); + BOOST_CHECK_EQUAL(mat, matBwdFull); + + BOOST_CHECK_EQUAL(vacuum, matFwdPost); + BOOST_CHECK_EQUAL(mat, matBwdPost); + + BOOST_CHECK_EQUAL(mat, matFwdPre); + BOOST_CHECK_EQUAL(vacuum, matBwdPre); } +} // namespace Test +} // namespace Acts diff --git a/Tests/Core/Material/InterpolatedMaterialMapTests.cpp b/Tests/Core/Material/InterpolatedMaterialMapTests.cpp index 809828afcab285b7bcc5ad209a39fa43ba26d394..e073118dc65cb122a0d9aa7bf9395762cf65860a 100644 --- a/Tests/Core/Material/InterpolatedMaterialMapTests.cpp +++ b/Tests/Core/Material/InterpolatedMaterialMapTests.cpp @@ -24,157 +24,150 @@ namespace Acts { namespace Test { - constexpr unsigned int dim = 2; - using grid_t = detail:: - Grid<ActsVectorF<5>, detail::EquidistantAxis, detail::EquidistantAxis>; - - ActsVectorD<dim> - trafoGlobalToLocal(const Vector3D& global) - { - return {global.x(), global.y()}; +constexpr unsigned int dim = 2; +using grid_t = detail::Grid<ActsVectorF<5>, detail::EquidistantAxis, + detail::EquidistantAxis>; + +ActsVectorD<dim> trafoGlobalToLocal(const Vector3D& global) { + return {global.x(), global.y()}; +} + +BOOST_AUTO_TEST_CASE(InterpolatedMaterialMap_MaterialCell_test) { + // Build a material cell + std::array<double, dim> lowerLeft{{0., 0.}}; + std::array<double, dim> upperRight{{1., 1.}}; + ActsVectorF<5> mat; + mat << 1, 2, 3, 4, 5; + std::array<ActsVectorF<5>, 4> matArray = {mat, mat, mat, mat}; + + MaterialMapper<grid_t>::MaterialCell materialCell( + trafoGlobalToLocal, lowerLeft, upperRight, matArray); + + // Test InterpolatedMaterialMap::MaterialCell<DIM>::isInside method + BOOST_CHECK_EQUAL(materialCell.isInside(Vector3D(0.5, 0.5, 0.5)), true); + BOOST_CHECK_EQUAL(materialCell.isInside(Vector3D(-1., 0., 0.)), false); + BOOST_CHECK_EQUAL(materialCell.isInside(Vector3D(0., -1., 0.)), false); + BOOST_CHECK_EQUAL(materialCell.isInside(Vector3D(0., 0., -1.)), true); + BOOST_CHECK_EQUAL(materialCell.isInside(Vector3D(2., 0., 0.)), false); + BOOST_CHECK_EQUAL(materialCell.isInside(Vector3D(0., 2., 0.)), false); + BOOST_CHECK_EQUAL(materialCell.isInside(Vector3D(0., 0., 2.)), true); + + // Test the getter + CHECK_CLOSE_REL(materialCell.getMaterial({0.5, 0.5, 0.5}), Material(mat), + 1e-4); +} + +BOOST_AUTO_TEST_CASE(InterpolatedMaterialMap_MaterialMapper_test) { + // Create the axes for the grid + detail::EquidistantAxis axisX(0, 3, 3); + detail::EquidistantAxis axisY(0, 3, 3); + + // The material mapping grid + auto grid = grid_t(std::make_tuple(std::move(axisX), std::move(axisY))); + ActsVectorF<5> mat; + mat << 1, 2, 3, 4, 5; + + for (size_t i = 0; i < grid.size(); i++) { + grid.at(i) = mat; } - - BOOST_AUTO_TEST_CASE(InterpolatedMaterialMap_MaterialCell_test) - { - // Build a material cell - std::array<double, dim> lowerLeft{{0., 0.}}; - std::array<double, dim> upperRight{{1., 1.}}; - ActsVectorF<5> mat; - mat << 1, 2, 3, 4, 5; - std::array<ActsVectorF<5>, 4> matArray = {mat, mat, mat, mat}; - - MaterialMapper<grid_t>::MaterialCell materialCell( - trafoGlobalToLocal, lowerLeft, upperRight, matArray); - - // Test InterpolatedMaterialMap::MaterialCell<DIM>::isInside method - BOOST_CHECK_EQUAL(materialCell.isInside(Vector3D(0.5, 0.5, 0.5)), true); - BOOST_CHECK_EQUAL(materialCell.isInside(Vector3D(-1., 0., 0.)), false); - BOOST_CHECK_EQUAL(materialCell.isInside(Vector3D(0., -1., 0.)), false); - BOOST_CHECK_EQUAL(materialCell.isInside(Vector3D(0., 0., -1.)), true); - BOOST_CHECK_EQUAL(materialCell.isInside(Vector3D(2., 0., 0.)), false); - BOOST_CHECK_EQUAL(materialCell.isInside(Vector3D(0., 2., 0.)), false); - BOOST_CHECK_EQUAL(materialCell.isInside(Vector3D(0., 0., 2.)), true); - - // Test the getter - CHECK_CLOSE_REL( - materialCell.getMaterial({0.5, 0.5, 0.5}), Material(mat), 1e-4); + MaterialMapper<grid_t> matMap(trafoGlobalToLocal, grid); + + // Test Material getter + CHECK_CLOSE_REL(matMap.getMaterial({0.5, 0.5, 0.5}), Material(mat), 1e-4); + + // Test the MaterialCell getter + MaterialMapper<grid_t>::MaterialCell matCell = + matMap.getMaterialCell({0.5, 0.5, 0.5}); + CHECK_CLOSE_REL(matCell.getMaterial({0.5, 0.5, 0.5}), Material(mat), 1e-4); + + // Test the number of bins getter + std::vector<size_t> nBins = matMap.getNBins(); + BOOST_CHECK_EQUAL(nBins[0], 3); + BOOST_CHECK_EQUAL(nBins[1], 3); + + // Test the lower limits + std::vector<double> limits = matMap.getMin(); + CHECK_CLOSE_ABS(limits[0], 0., 1e-4); + CHECK_CLOSE_ABS(limits[1], 0., 1e-4); + + // Test the upper limits + limits = matMap.getMax(); + CHECK_CLOSE_REL(limits[0], 3., 1e-4); + CHECK_CLOSE_REL(limits[1], 3., 1e-4); + + // Test the inside check + BOOST_CHECK_EQUAL(matMap.isInside(Vector3D(1., 1., 1.)), true); + BOOST_CHECK_EQUAL(matMap.isInside(Vector3D(-1., 0., 0.)), false); + BOOST_CHECK_EQUAL(matMap.isInside(Vector3D(0., -1., 0.)), false); + BOOST_CHECK_EQUAL(matMap.isInside(Vector3D(0., 0., -1.)), true); + BOOST_CHECK_EQUAL(matMap.isInside(Vector3D(4., 0., 0.)), false); + BOOST_CHECK_EQUAL(matMap.isInside(Vector3D(0., 4., 0.)), false); + BOOST_CHECK_EQUAL(matMap.isInside(Vector3D(0., 0., 4.)), true); + + // Test the grid getter + auto matMapGrid = matMap.getGrid(); + for (unsigned int i = 0; i < dim; i++) { + BOOST_CHECK_EQUAL(grid.numLocalBins()[i], matMapGrid.numLocalBins()[i]); + BOOST_CHECK_EQUAL(grid.minPosition()[i], matMapGrid.minPosition()[i]); + BOOST_CHECK_EQUAL(grid.maxPosition()[i], matMapGrid.maxPosition()[i]); } - - BOOST_AUTO_TEST_CASE(InterpolatedMaterialMap_MaterialMapper_test) - { - // Create the axes for the grid - detail::EquidistantAxis axisX(0, 3, 3); - detail::EquidistantAxis axisY(0, 3, 3); - - // The material mapping grid - auto grid = grid_t(std::make_tuple(std::move(axisX), std::move(axisY))); - ActsVectorF<5> mat; - mat << 1, 2, 3, 4, 5; - - for (size_t i = 0; i < grid.size(); i++) { - grid.at(i) = mat; - } - MaterialMapper<grid_t> matMap(trafoGlobalToLocal, grid); - - // Test Material getter - CHECK_CLOSE_REL(matMap.getMaterial({0.5, 0.5, 0.5}), Material(mat), 1e-4); - - // Test the MaterialCell getter - MaterialMapper<grid_t>::MaterialCell matCell - = matMap.getMaterialCell({0.5, 0.5, 0.5}); - CHECK_CLOSE_REL(matCell.getMaterial({0.5, 0.5, 0.5}), Material(mat), 1e-4); - - // Test the number of bins getter - std::vector<size_t> nBins = matMap.getNBins(); - BOOST_CHECK_EQUAL(nBins[0], 3); - BOOST_CHECK_EQUAL(nBins[1], 3); - - // Test the lower limits - std::vector<double> limits = matMap.getMin(); - CHECK_CLOSE_ABS(limits[0], 0., 1e-4); - CHECK_CLOSE_ABS(limits[1], 0., 1e-4); - - // Test the upper limits - limits = matMap.getMax(); - CHECK_CLOSE_REL(limits[0], 3., 1e-4); - CHECK_CLOSE_REL(limits[1], 3., 1e-4); - - // Test the inside check - BOOST_CHECK_EQUAL(matMap.isInside(Vector3D(1., 1., 1.)), true); - BOOST_CHECK_EQUAL(matMap.isInside(Vector3D(-1., 0., 0.)), false); - BOOST_CHECK_EQUAL(matMap.isInside(Vector3D(0., -1., 0.)), false); - BOOST_CHECK_EQUAL(matMap.isInside(Vector3D(0., 0., -1.)), true); - BOOST_CHECK_EQUAL(matMap.isInside(Vector3D(4., 0., 0.)), false); - BOOST_CHECK_EQUAL(matMap.isInside(Vector3D(0., 4., 0.)), false); - BOOST_CHECK_EQUAL(matMap.isInside(Vector3D(0., 0., 4.)), true); - - // Test the grid getter - auto matMapGrid = matMap.getGrid(); - for (unsigned int i = 0; i < dim; i++) { - BOOST_CHECK_EQUAL(grid.numLocalBins()[i], matMapGrid.numLocalBins()[i]); - BOOST_CHECK_EQUAL(grid.minPosition()[i], matMapGrid.minPosition()[i]); - BOOST_CHECK_EQUAL(grid.maxPosition()[i], matMapGrid.maxPosition()[i]); - } - for (size_t i = 0; i < grid.size(); i++) { - CHECK_CLOSE_REL(grid.at(i), matMapGrid.at(i), 1e-4); - } + for (size_t i = 0; i < grid.size(); i++) { + CHECK_CLOSE_REL(grid.at(i), matMapGrid.at(i), 1e-4); } +} + +BOOST_AUTO_TEST_CASE(InterpolatedMaterialMap_test) { + // Create the axes for the grid + detail::EquidistantAxis axisX(0, 3, 3); + detail::EquidistantAxis axisY(0, 3, 3); - BOOST_AUTO_TEST_CASE(InterpolatedMaterialMap_test) - { - // Create the axes for the grid - detail::EquidistantAxis axisX(0, 3, 3); - detail::EquidistantAxis axisY(0, 3, 3); - - // The material mapping grid - auto grid = grid_t(std::make_tuple(std::move(axisX), std::move(axisY))); - ActsVectorF<5> mat; - mat << 1, 2, 3, 4, 5; - - for (size_t i = 0; i < grid.size(); i++) { - grid.at(i) = mat; - } - MaterialMapper<grid_t> matMap(trafoGlobalToLocal, grid); - InterpolatedMaterialMap ipolMatMap(matMap); - - // Test the material getter - CHECK_CLOSE_REL( - ipolMatMap.getMaterial({0.5, 0.5, 0.5}), Material(mat), 1e-4); - - // Test the material getter with a cache - // Build a material cell - std::array<double, dim> lowerLeft{{0., 0.}}; - std::array<double, dim> upperRight{{1., 1.}}; - std::array<ActsVectorF<5>, 4> matArray = {mat, mat, mat, mat}; - - MaterialMapper<grid_t>::MaterialCell materialCell( - trafoGlobalToLocal, lowerLeft, upperRight, matArray); - InterpolatedMaterialMap<MaterialMapper<grid_t>>::Cache cache; - cache.matCell = materialCell; - cache.initialized = true; - CHECK_CLOSE_REL(ipolMatMap.getMaterial(Vector3D(0.5, 0.5, 0.5), cache), - Material(mat), - 1e-4); - - // Test the material map getter - auto mapper = ipolMatMap.getMapper(); - BOOST_CHECK_EQUAL(mapper.getMaterial({0.5, 0.5, 0.5}), - matMap.getMaterial({0.5, 0.5, 0.5})); - for (unsigned int i = 0; i < dim; i++) { - BOOST_CHECK_EQUAL(mapper.getNBins()[i], matMap.getNBins()[i]); - BOOST_CHECK_EQUAL(mapper.getMin()[i], matMap.getMin()[i]); - BOOST_CHECK_EQUAL(mapper.getMax()[i], matMap.getMax()[i]); - } - - // Test the inside check - BOOST_CHECK_EQUAL(ipolMatMap.isInside(Vector3D(1., 1., 1.)), true); - BOOST_CHECK_EQUAL(ipolMatMap.isInside(Vector3D(-1., 0., 0.)), false); - BOOST_CHECK_EQUAL(ipolMatMap.isInside(Vector3D(0., -1., 0.)), false); - BOOST_CHECK_EQUAL(ipolMatMap.isInside(Vector3D(0., 0., -1.)), true); - BOOST_CHECK_EQUAL(ipolMatMap.isInside(Vector3D(4., 0., 0.)), false); - BOOST_CHECK_EQUAL(ipolMatMap.isInside(Vector3D(0., 4., 0.)), false); - BOOST_CHECK_EQUAL(ipolMatMap.isInside(Vector3D(0., 0., 4.)), true); + // The material mapping grid + auto grid = grid_t(std::make_tuple(std::move(axisX), std::move(axisY))); + ActsVectorF<5> mat; + mat << 1, 2, 3, 4, 5; + + for (size_t i = 0; i < grid.size(); i++) { + grid.at(i) = mat; + } + MaterialMapper<grid_t> matMap(trafoGlobalToLocal, grid); + InterpolatedMaterialMap ipolMatMap(matMap); + + // Test the material getter + CHECK_CLOSE_REL(ipolMatMap.getMaterial({0.5, 0.5, 0.5}), Material(mat), 1e-4); + + // Test the material getter with a cache + // Build a material cell + std::array<double, dim> lowerLeft{{0., 0.}}; + std::array<double, dim> upperRight{{1., 1.}}; + std::array<ActsVectorF<5>, 4> matArray = {mat, mat, mat, mat}; + + MaterialMapper<grid_t>::MaterialCell materialCell( + trafoGlobalToLocal, lowerLeft, upperRight, matArray); + InterpolatedMaterialMap<MaterialMapper<grid_t>>::Cache cache; + cache.matCell = materialCell; + cache.initialized = true; + CHECK_CLOSE_REL(ipolMatMap.getMaterial(Vector3D(0.5, 0.5, 0.5), cache), + Material(mat), 1e-4); + + // Test the material map getter + auto mapper = ipolMatMap.getMapper(); + BOOST_CHECK_EQUAL(mapper.getMaterial({0.5, 0.5, 0.5}), + matMap.getMaterial({0.5, 0.5, 0.5})); + for (unsigned int i = 0; i < dim; i++) { + BOOST_CHECK_EQUAL(mapper.getNBins()[i], matMap.getNBins()[i]); + BOOST_CHECK_EQUAL(mapper.getMin()[i], matMap.getMin()[i]); + BOOST_CHECK_EQUAL(mapper.getMax()[i], matMap.getMax()[i]); } + + // Test the inside check + BOOST_CHECK_EQUAL(ipolMatMap.isInside(Vector3D(1., 1., 1.)), true); + BOOST_CHECK_EQUAL(ipolMatMap.isInside(Vector3D(-1., 0., 0.)), false); + BOOST_CHECK_EQUAL(ipolMatMap.isInside(Vector3D(0., -1., 0.)), false); + BOOST_CHECK_EQUAL(ipolMatMap.isInside(Vector3D(0., 0., -1.)), true); + BOOST_CHECK_EQUAL(ipolMatMap.isInside(Vector3D(4., 0., 0.)), false); + BOOST_CHECK_EQUAL(ipolMatMap.isInside(Vector3D(0., 4., 0.)), false); + BOOST_CHECK_EQUAL(ipolMatMap.isInside(Vector3D(0., 0., 4.)), true); +} } // namespace Test } // namespace Acts \ No newline at end of file diff --git a/Tests/Core/Material/MaterialCompositionTests.cpp b/Tests/Core/Material/MaterialCompositionTests.cpp index 1d2c3f3674ee374893c46cf22d678073e981426e..a8cc8b859a06fa7395b2d0ce1854a410c40ffb75 100644 --- a/Tests/Core/Material/MaterialCompositionTests.cpp +++ b/Tests/Core/Material/MaterialCompositionTests.cpp @@ -22,143 +22,138 @@ namespace Acts { namespace Test { - // the maximum tolerance is half the accuracy - float elMaxTolerance = 0.5 / float(UCHAR_MAX); - - namespace au = Acts::units; - - BOOST_AUTO_TEST_CASE(ElementFraction_construction_test) - { - // carbon parameters, atomic charge is Z - unsigned char carbonZ = 12; - // a fraction between 0 and 255 - unsigned char carbonFractionCH = 46; - float carbonFractionFloat = float(46. / UCHAR_MAX); - - // test the carbon fraction - std::array<unsigned char, 2> data = {{carbonZ, carbonFractionCH}}; - ElementFraction carbonEFC(data); - ElementFraction carbonEFF((unsigned int)carbonZ, carbonFractionFloat); - - // check if you get the element and the fraction back - BOOST_CHECK_EQUAL(12ul, carbonEFC.element()); - CHECK_CLOSE_REL(carbonFractionFloat, carbonEFC.fraction(), elMaxTolerance); - BOOST_CHECK_EQUAL(12ul, carbonEFF.element()); - CHECK_CLOSE_REL(carbonFractionFloat, carbonEFF.fraction(), elMaxTolerance); - } +// the maximum tolerance is half the accuracy +float elMaxTolerance = 0.5 / float(UCHAR_MAX); + +namespace au = Acts::units; + +BOOST_AUTO_TEST_CASE(ElementFraction_construction_test) { + // carbon parameters, atomic charge is Z + unsigned char carbonZ = 12; + // a fraction between 0 and 255 + unsigned char carbonFractionCH = 46; + float carbonFractionFloat = float(46. / UCHAR_MAX); + + // test the carbon fraction + std::array<unsigned char, 2> data = {{carbonZ, carbonFractionCH}}; + ElementFraction carbonEFC(data); + ElementFraction carbonEFF((unsigned int)carbonZ, carbonFractionFloat); + + // check if you get the element and the fraction back + BOOST_CHECK_EQUAL(12ul, carbonEFC.element()); + CHECK_CLOSE_REL(carbonFractionFloat, carbonEFC.fraction(), elMaxTolerance); + BOOST_CHECK_EQUAL(12ul, carbonEFF.element()); + CHECK_CLOSE_REL(carbonFractionFloat, carbonEFF.fraction(), elMaxTolerance); +} - BOOST_AUTO_TEST_CASE(ElementFraction_movable_test) - { - // carbon parameters, atomic charge is Z - unsigned char carbonZ = 12; - // a fraction between 0 and 255 - float carbonFraction = float(46. / UCHAR_MAX); +BOOST_AUTO_TEST_CASE(ElementFraction_movable_test) { + // carbon parameters, atomic charge is Z + unsigned char carbonZ = 12; + // a fraction between 0 and 255 + float carbonFraction = float(46. / UCHAR_MAX); - // test the carbon fraction - ElementFraction carbon((unsigned int)carbonZ, carbonFraction); - ElementFraction carbonMoved(std::move(carbon)); + // test the carbon fraction + ElementFraction carbon((unsigned int)carbonZ, carbonFraction); + ElementFraction carbonMoved(std::move(carbon)); - BOOST_CHECK_EQUAL(12ul, carbonMoved.element()); - CHECK_CLOSE_REL(carbonFraction, carbonMoved.fraction(), elMaxTolerance); + BOOST_CHECK_EQUAL(12ul, carbonMoved.element()); + CHECK_CLOSE_REL(carbonFraction, carbonMoved.fraction(), elMaxTolerance); - ElementFraction carbonMovedAssigned = std::move(carbonMoved); - BOOST_CHECK_EQUAL(12ul, carbonMovedAssigned.element()); - CHECK_CLOSE_REL( - carbonFraction, carbonMovedAssigned.fraction(), elMaxTolerance); - } + ElementFraction carbonMovedAssigned = std::move(carbonMoved); + BOOST_CHECK_EQUAL(12ul, carbonMovedAssigned.element()); + CHECK_CLOSE_REL(carbonFraction, carbonMovedAssigned.fraction(), + elMaxTolerance); +} - BOOST_AUTO_TEST_CASE(MaterialComposition_construction_test) - { - // Carbon fraction - unsigned int carbonZ = 12; - float carbonFraction = 0.45; - ElementFraction carbon(carbonZ, carbonFraction); - - // Silicon fraction - unsigned int siliconZ = 14; - float siliconFracton = 0.1; - ElementFraction silicon(siliconZ, siliconFracton); - - // Titanium fraction - unsigned int titantiumZ = 22; - float titaniumFraction = 0.25; - ElementFraction titanium(titantiumZ, titaniumFraction); - - // Copper fraction - unsigned int copperZ = 29; - float copperFraction = 0.2; - ElementFraction copper(copperZ, copperFraction); - - std::vector<ElementFraction> elements = {silicon, carbon, titanium, copper}; - std::vector<ElementFraction> shuffled = {carbon, silicon, titanium, copper}; - - /// create the material composition - MaterialComposition elementsC(elements); - MaterialComposition shuffledC(shuffled); - // check if the sorting worked - BOOST_CHECK_EQUAL(elementsC.size(), shuffledC.size()); - BOOST_CHECK_EQUAL(elementsC.elements()[0].data()[0], - shuffledC.elements()[0].data()[0]); - BOOST_CHECK_EQUAL(elementsC.elements()[1].data()[0], - shuffledC.elements()[1].data()[0]); - BOOST_CHECK_EQUAL(elementsC.elements()[2].data()[0], - shuffledC.elements()[2].data()[0]); - BOOST_CHECK_EQUAL(elementsC.elements()[3].data()[0], - shuffledC.elements()[3].data()[0]); - BOOST_CHECK_EQUAL(elementsC.elements()[0].data()[1], - shuffledC.elements()[0].data()[1]); - BOOST_CHECK_EQUAL(elementsC.elements()[1].data()[1], - shuffledC.elements()[1].data()[1]); - BOOST_CHECK_EQUAL(elementsC.elements()[2].data()[1], - shuffledC.elements()[2].data()[1]); - BOOST_CHECK_EQUAL(elementsC.elements()[3].data()[1], - shuffledC.elements()[3].data()[1]); - /// or shortly - BOOST_CHECK_EQUAL(elementsC, shuffledC); - - float totalFraction = 0.; - for (auto& eFraction : elementsC.elements()) { - totalFraction += eFraction.fraction(); - } - // to better fit we need to implement some proper weight scaling - BOOST_CHECK_LT(std::abs(1. - totalFraction), - elementsC.elements().size() * elMaxTolerance); +BOOST_AUTO_TEST_CASE(MaterialComposition_construction_test) { + // Carbon fraction + unsigned int carbonZ = 12; + float carbonFraction = 0.45; + ElementFraction carbon(carbonZ, carbonFraction); + + // Silicon fraction + unsigned int siliconZ = 14; + float siliconFracton = 0.1; + ElementFraction silicon(siliconZ, siliconFracton); + + // Titanium fraction + unsigned int titantiumZ = 22; + float titaniumFraction = 0.25; + ElementFraction titanium(titantiumZ, titaniumFraction); + + // Copper fraction + unsigned int copperZ = 29; + float copperFraction = 0.2; + ElementFraction copper(copperZ, copperFraction); + + std::vector<ElementFraction> elements = {silicon, carbon, titanium, copper}; + std::vector<ElementFraction> shuffled = {carbon, silicon, titanium, copper}; + + /// create the material composition + MaterialComposition elementsC(elements); + MaterialComposition shuffledC(shuffled); + // check if the sorting worked + BOOST_CHECK_EQUAL(elementsC.size(), shuffledC.size()); + BOOST_CHECK_EQUAL(elementsC.elements()[0].data()[0], + shuffledC.elements()[0].data()[0]); + BOOST_CHECK_EQUAL(elementsC.elements()[1].data()[0], + shuffledC.elements()[1].data()[0]); + BOOST_CHECK_EQUAL(elementsC.elements()[2].data()[0], + shuffledC.elements()[2].data()[0]); + BOOST_CHECK_EQUAL(elementsC.elements()[3].data()[0], + shuffledC.elements()[3].data()[0]); + BOOST_CHECK_EQUAL(elementsC.elements()[0].data()[1], + shuffledC.elements()[0].data()[1]); + BOOST_CHECK_EQUAL(elementsC.elements()[1].data()[1], + shuffledC.elements()[1].data()[1]); + BOOST_CHECK_EQUAL(elementsC.elements()[2].data()[1], + shuffledC.elements()[2].data()[1]); + BOOST_CHECK_EQUAL(elementsC.elements()[3].data()[1], + shuffledC.elements()[3].data()[1]); + /// or shortly + BOOST_CHECK_EQUAL(elementsC, shuffledC); + + float totalFraction = 0.; + for (auto& eFraction : elementsC.elements()) { + totalFraction += eFraction.fraction(); } + // to better fit we need to implement some proper weight scaling + BOOST_CHECK_LT(std::abs(1. - totalFraction), + elementsC.elements().size() * elMaxTolerance); +} - BOOST_AUTO_TEST_CASE(MaterialComposition_movable_test) - { - // Carbon fraction - unsigned int carbonZ = 12; - float carbonFraction = 0.45; - ElementFraction carbon(carbonZ, carbonFraction); +BOOST_AUTO_TEST_CASE(MaterialComposition_movable_test) { + // Carbon fraction + unsigned int carbonZ = 12; + float carbonFraction = 0.45; + ElementFraction carbon(carbonZ, carbonFraction); - // Silicon fraction - unsigned int siliconZ = 14; - float siliconFracton = 0.1; - ElementFraction silicon(siliconZ, siliconFracton); + // Silicon fraction + unsigned int siliconZ = 14; + float siliconFracton = 0.1; + ElementFraction silicon(siliconZ, siliconFracton); - // Titanium fraction - unsigned int titantiumZ = 22; - float titaniumFraction = 0.25; - ElementFraction titanium(titantiumZ, titaniumFraction); + // Titanium fraction + unsigned int titantiumZ = 22; + float titaniumFraction = 0.25; + ElementFraction titanium(titantiumZ, titaniumFraction); - // Copper fraction - unsigned int copperZ = 29; - float copperFraction = 0.2; - ElementFraction copper(copperZ, copperFraction); + // Copper fraction + unsigned int copperZ = 29; + float copperFraction = 0.2; + ElementFraction copper(copperZ, copperFraction); - std::vector<ElementFraction> elements = {silicon, carbon, titanium, copper}; + std::vector<ElementFraction> elements = {silicon, carbon, titanium, copper}; - /// create the material composition - elements are copied here - MaterialComposition mComposition(elements); + /// create the material composition - elements are copied here + MaterialComposition mComposition(elements); - /// Move copy construction - object is moved here - MaterialComposition mCompositionMoved(std::move(mComposition)); - BOOST_CHECK_EQUAL(mCompositionMoved.size(), elements.size()); + /// Move copy construction - object is moved here + MaterialComposition mCompositionMoved(std::move(mComposition)); + BOOST_CHECK_EQUAL(mCompositionMoved.size(), elements.size()); - MaterialComposition mCompositionMovedAssigned - = std::move(mCompositionMoved); - BOOST_CHECK_EQUAL(mCompositionMovedAssigned.size(), elements.size()); - } -} + MaterialComposition mCompositionMovedAssigned = std::move(mCompositionMoved); + BOOST_CHECK_EQUAL(mCompositionMovedAssigned.size(), elements.size()); } +} // namespace Test +} // namespace Acts diff --git a/Tests/Core/Material/MaterialPropertiesTests.cpp b/Tests/Core/Material/MaterialPropertiesTests.cpp index ec905dda8d4679e28d95d0360aeaffd56e7f31f1..df9d0e4270d101592d13b76f32adf847afa8aeeb 100644 --- a/Tests/Core/Material/MaterialPropertiesTests.cpp +++ b/Tests/Core/Material/MaterialPropertiesTests.cpp @@ -22,112 +22,107 @@ namespace Acts { namespace Test { - /// Test the constructors - BOOST_AUTO_TEST_CASE(MaterialProperties_construction_test) - { - // constructor only from arguments - MaterialProperties a(1., 2., 3., 4., 5., 6.); - /// constructor with material - MaterialProperties b(Material(1., 2., 3., 4., 5.), 6.); - - // The thickness should be 6 - CHECK_CLOSE_REL(a.thickness(), 6., 0.0001); - CHECK_CLOSE_REL(a.thicknessInX0(), 6., 0.0001); - CHECK_CLOSE_REL(a.thicknessInL0(), 3., 0.0001); - BOOST_CHECK_EQUAL(a.averageA(), 3.); - BOOST_CHECK_EQUAL(a.averageZ(), 4.); - BOOST_CHECK_EQUAL(a.averageRho(), 5.); - CHECK_CLOSE_REL(a.zOverAtimesRho(), 6.666666666, 0.0001); - - /// Check if they are equal - BOOST_CHECK_EQUAL(a, b); - - /// Check the move construction - MaterialProperties bMoved(std::move(b)); - /// Check if they are equal - BOOST_CHECK_EQUAL(a, bMoved); - - /// Check the move assignment - MaterialProperties bMovedAssigned = std::move(bMoved); - /// Check if they are equal - BOOST_CHECK_EQUAL(a, bMovedAssigned); - } - - /// Test the constructors - BOOST_AUTO_TEST_CASE(MaterialProperties_compound_test) - { - MaterialProperties a(1., 2., 3., 4., 5., 1.); - MaterialProperties b(2., 4., 6., 8., 10., 2.); - MaterialProperties c(4., 8., 12., 16., 20., 3.); - - std::vector<MaterialProperties> compound = {{a, b, c}}; - - /// Thickness is scaled to unit here - MaterialProperties abc(compound, true); - - // Unit legnth thickness - CHECK_CLOSE_REL(abc.thickness(), 1., 0.0001); - - // Thickness in X0 is additive - CHECK_CLOSE_REL(abc.thicknessInX0(), - a.thicknessInX0() + b.thicknessInX0() + c.thicknessInX0(), - 0.0001); - - CHECK_CLOSE_REL( - abc.thickness() / abc.averageX0(), abc.thicknessInX0(), 0.0001); - - CHECK_CLOSE_REL(abc.thicknessInL0(), - a.thicknessInL0() + b.thicknessInL0() + c.thicknessInL0(), - 0.0001); - - // Thinkness is NOT unit scaled here - MaterialProperties abcNS(compound, false); - - // The density scales with the thickness then - CHECK_CLOSE_REL(abcNS.averageRho(), - (a.thickness() * a.averageRho() - + b.thickness() * b.averageRho() - + c.thickness() * c.averageRho()) - / (a.thickness() + b.thickness() + c.thickness()), - 0.0001); - - // The material properties are not the same - BOOST_CHECK_NE(abc, abcNS); - // Because thickness is not the same - BOOST_CHECK_NE(abc.thickness(), abcNS.thickness()); - // And the densities are differnt - BOOST_CHECK_NE(abc.averageRho(), abcNS.averageRho()); - // Though the amount should be the same - CHECK_CLOSE_REL(abc.thicknessInX0(), abcNS.thicknessInX0(), 0.0001); - CHECK_CLOSE_REL(abc.thicknessInL0(), abcNS.thicknessInL0(), 0.0001); - CHECK_CLOSE_REL(abc.averageA(), abcNS.averageA(), 0.0001); - CHECK_CLOSE_REL(abc.averageZ(), abcNS.averageZ(), 0.0001); - CHECK_CLOSE_REL(abc.averageRho() * abc.thickness(), - abcNS.averageRho() * abcNS.thickness(), - 0.0001); - } - - // Test the Scaling - BOOST_AUTO_TEST_CASE(MaterialProperties_scale_test) - { - // construct the material properties from arguments - MaterialProperties mat(1., 2., 3., 4., 5., 0.1); - MaterialProperties halfMat(1., 2., 3., 4., 5., 0.05); - MaterialProperties halfScaled = mat; - halfScaled *= 0.5; - - BOOST_CHECK_NE(mat, halfMat); - BOOST_CHECK_EQUAL(halfMat, halfScaled); - - // this means half the scattering - CHECK_CLOSE_REL(mat.thicknessInX0(), 2. * halfMat.thicknessInX0(), 0.0001); - CHECK_CLOSE_REL(mat.thicknessInL0(), 2. * halfMat.thicknessInL0(), 0.0001); - - // and half the energy loss, given - CHECK_CLOSE_REL(mat.thickness() * mat.averageRho(), - 2. * halfMat.thickness() * halfMat.averageRho(), - 0.0001); - } +/// Test the constructors +BOOST_AUTO_TEST_CASE(MaterialProperties_construction_test) { + // constructor only from arguments + MaterialProperties a(1., 2., 3., 4., 5., 6.); + /// constructor with material + MaterialProperties b(Material(1., 2., 3., 4., 5.), 6.); + + // The thickness should be 6 + CHECK_CLOSE_REL(a.thickness(), 6., 0.0001); + CHECK_CLOSE_REL(a.thicknessInX0(), 6., 0.0001); + CHECK_CLOSE_REL(a.thicknessInL0(), 3., 0.0001); + BOOST_CHECK_EQUAL(a.averageA(), 3.); + BOOST_CHECK_EQUAL(a.averageZ(), 4.); + BOOST_CHECK_EQUAL(a.averageRho(), 5.); + CHECK_CLOSE_REL(a.zOverAtimesRho(), 6.666666666, 0.0001); + + /// Check if they are equal + BOOST_CHECK_EQUAL(a, b); + + /// Check the move construction + MaterialProperties bMoved(std::move(b)); + /// Check if they are equal + BOOST_CHECK_EQUAL(a, bMoved); + + /// Check the move assignment + MaterialProperties bMovedAssigned = std::move(bMoved); + /// Check if they are equal + BOOST_CHECK_EQUAL(a, bMovedAssigned); +} + +/// Test the constructors +BOOST_AUTO_TEST_CASE(MaterialProperties_compound_test) { + MaterialProperties a(1., 2., 3., 4., 5., 1.); + MaterialProperties b(2., 4., 6., 8., 10., 2.); + MaterialProperties c(4., 8., 12., 16., 20., 3.); + + std::vector<MaterialProperties> compound = {{a, b, c}}; + + /// Thickness is scaled to unit here + MaterialProperties abc(compound, true); + + // Unit legnth thickness + CHECK_CLOSE_REL(abc.thickness(), 1., 0.0001); + + // Thickness in X0 is additive + CHECK_CLOSE_REL(abc.thicknessInX0(), + a.thicknessInX0() + b.thicknessInX0() + c.thicknessInX0(), + 0.0001); + + CHECK_CLOSE_REL(abc.thickness() / abc.averageX0(), abc.thicknessInX0(), + 0.0001); + + CHECK_CLOSE_REL(abc.thicknessInL0(), + a.thicknessInL0() + b.thicknessInL0() + c.thicknessInL0(), + 0.0001); + + // Thinkness is NOT unit scaled here + MaterialProperties abcNS(compound, false); + + // The density scales with the thickness then + CHECK_CLOSE_REL( + abcNS.averageRho(), + (a.thickness() * a.averageRho() + b.thickness() * b.averageRho() + + c.thickness() * c.averageRho()) / + (a.thickness() + b.thickness() + c.thickness()), + 0.0001); + + // The material properties are not the same + BOOST_CHECK_NE(abc, abcNS); + // Because thickness is not the same + BOOST_CHECK_NE(abc.thickness(), abcNS.thickness()); + // And the densities are differnt + BOOST_CHECK_NE(abc.averageRho(), abcNS.averageRho()); + // Though the amount should be the same + CHECK_CLOSE_REL(abc.thicknessInX0(), abcNS.thicknessInX0(), 0.0001); + CHECK_CLOSE_REL(abc.thicknessInL0(), abcNS.thicknessInL0(), 0.0001); + CHECK_CLOSE_REL(abc.averageA(), abcNS.averageA(), 0.0001); + CHECK_CLOSE_REL(abc.averageZ(), abcNS.averageZ(), 0.0001); + CHECK_CLOSE_REL(abc.averageRho() * abc.thickness(), + abcNS.averageRho() * abcNS.thickness(), 0.0001); +} + +// Test the Scaling +BOOST_AUTO_TEST_CASE(MaterialProperties_scale_test) { + // construct the material properties from arguments + MaterialProperties mat(1., 2., 3., 4., 5., 0.1); + MaterialProperties halfMat(1., 2., 3., 4., 5., 0.05); + MaterialProperties halfScaled = mat; + halfScaled *= 0.5; + + BOOST_CHECK_NE(mat, halfMat); + BOOST_CHECK_EQUAL(halfMat, halfScaled); + + // this means half the scattering + CHECK_CLOSE_REL(mat.thicknessInX0(), 2. * halfMat.thicknessInX0(), 0.0001); + CHECK_CLOSE_REL(mat.thicknessInL0(), 2. * halfMat.thicknessInL0(), 0.0001); + + // and half the energy loss, given + CHECK_CLOSE_REL(mat.thickness() * mat.averageRho(), + 2. * halfMat.thickness() * halfMat.averageRho(), 0.0001); +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/Material/MaterialTests.cpp b/Tests/Core/Material/MaterialTests.cpp index 262799eb15603da19a51f3ab19a30bf3b36d9df2..f75052ef57912bb23e3fb0b9aefeef5eaac0eca3 100644 --- a/Tests/Core/Material/MaterialTests.cpp +++ b/Tests/Core/Material/MaterialTests.cpp @@ -22,61 +22,57 @@ namespace Acts { namespace Test { - // the maximum tolerance is half the accuracy - float elMaxTolerance = 0.5 / float(UCHAR_MAX); - - namespace au = Acts::units; - - // first test correct boolean behavior - BOOST_AUTO_TEST_CASE(Material_boolean_test) - { - Material vacuum; - BOOST_CHECK_EQUAL(bool(vacuum), false); - - Material something(1., 2., 3., 4., 5); - BOOST_CHECK_EQUAL(bool(something), true); - } - - // now test thge construction and units - BOOST_AUTO_TEST_CASE(Material_construction_and_units) - { - - // density at room temperature - float X0 = 9.370 * au::_cm; - float L0 = 46.52 * au::_cm; - float A = 28.0855; - float Z = 14.; - float rho = 2.329 * au::_g / (au::_cm * au::_cm * au::_cm); - - Material silicon(X0, L0, A, Z, rho); - CHECK_CLOSE_REL(silicon.X0(), 93.70 * au::_mm, 0.001); - CHECK_CLOSE_REL(silicon.L0(), 465.2 * au::_mm, 0.001); - CHECK_CLOSE_REL(silicon.Z(), 14., 0.001); - CHECK_CLOSE_REL(silicon.A(), 28.0855, 0.001); - CHECK_CLOSE_REL(silicon.rho(), - 0.002329 * au::_g / (au::_mm * au::_mm * au::_mm), - 0.001); - CHECK_CLOSE_REL(silicon.zOverAtimesRho(), 14. / 28.0855 * 0.002329, 0.0001); - - ActsVectorF<5> siliconValues; - siliconValues << X0, L0, A, Z, rho; - Material siliconFromValues(siliconValues); - BOOST_CHECK_EQUAL(silicon, siliconFromValues); - - Material copiedSilicon(silicon); - BOOST_CHECK_EQUAL(silicon, copiedSilicon); - - Material moveCopiedSilicon(std::move(copiedSilicon)); - BOOST_CHECK_EQUAL(silicon, moveCopiedSilicon); - - Material assignedSilicon = silicon; - BOOST_CHECK_EQUAL(silicon, assignedSilicon); - - Material moveAssignedSilicon = std::move(assignedSilicon); - BOOST_CHECK_EQUAL(silicon, moveAssignedSilicon); - - ActsVectorF<5> decomposedSilicon = silicon.classificationNumbers(); - CHECK_CLOSE_REL(decomposedSilicon, siliconValues, 1e-4); - } +// the maximum tolerance is half the accuracy +float elMaxTolerance = 0.5 / float(UCHAR_MAX); + +namespace au = Acts::units; + +// first test correct boolean behavior +BOOST_AUTO_TEST_CASE(Material_boolean_test) { + Material vacuum; + BOOST_CHECK_EQUAL(bool(vacuum), false); + + Material something(1., 2., 3., 4., 5); + BOOST_CHECK_EQUAL(bool(something), true); +} + +// now test thge construction and units +BOOST_AUTO_TEST_CASE(Material_construction_and_units) { + // density at room temperature + float X0 = 9.370 * au::_cm; + float L0 = 46.52 * au::_cm; + float A = 28.0855; + float Z = 14.; + float rho = 2.329 * au::_g / (au::_cm * au::_cm * au::_cm); + + Material silicon(X0, L0, A, Z, rho); + CHECK_CLOSE_REL(silicon.X0(), 93.70 * au::_mm, 0.001); + CHECK_CLOSE_REL(silicon.L0(), 465.2 * au::_mm, 0.001); + CHECK_CLOSE_REL(silicon.Z(), 14., 0.001); + CHECK_CLOSE_REL(silicon.A(), 28.0855, 0.001); + CHECK_CLOSE_REL(silicon.rho(), + 0.002329 * au::_g / (au::_mm * au::_mm * au::_mm), 0.001); + CHECK_CLOSE_REL(silicon.zOverAtimesRho(), 14. / 28.0855 * 0.002329, 0.0001); + + ActsVectorF<5> siliconValues; + siliconValues << X0, L0, A, Z, rho; + Material siliconFromValues(siliconValues); + BOOST_CHECK_EQUAL(silicon, siliconFromValues); + + Material copiedSilicon(silicon); + BOOST_CHECK_EQUAL(silicon, copiedSilicon); + + Material moveCopiedSilicon(std::move(copiedSilicon)); + BOOST_CHECK_EQUAL(silicon, moveCopiedSilicon); + + Material assignedSilicon = silicon; + BOOST_CHECK_EQUAL(silicon, assignedSilicon); + + Material moveAssignedSilicon = std::move(assignedSilicon); + BOOST_CHECK_EQUAL(silicon, moveAssignedSilicon); + + ActsVectorF<5> decomposedSilicon = silicon.classificationNumbers(); + CHECK_CLOSE_REL(decomposedSilicon, siliconValues, 1e-4); +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/Material/ProtoSurfaceMaterialTests.cpp b/Tests/Core/Material/ProtoSurfaceMaterialTests.cpp index 6a76fcbc40879c62d37e4a50677870806e5a2de9..bce35f81aab1a18ae6fc83c620385e9113c161d9 100644 --- a/Tests/Core/Material/ProtoSurfaceMaterialTests.cpp +++ b/Tests/Core/Material/ProtoSurfaceMaterialTests.cpp @@ -17,19 +17,18 @@ namespace Acts { namespace Test { - /// Test the constructors - BOOST_AUTO_TEST_CASE(ProtoSurfaceMaterial_construction_test) - { - BinUtility smpBU(10, -10., 10., open, binX); - smpBU += BinUtility(10, -10., 10., open, binY); +/// Test the constructors +BOOST_AUTO_TEST_CASE(ProtoSurfaceMaterial_construction_test) { + BinUtility smpBU(10, -10., 10., open, binX); + smpBU += BinUtility(10, -10., 10., open, binY); - // Constructor from arguments - ProtoSurfaceMaterial smp(smpBU); - // Copy constructor - ProtoSurfaceMaterial smpCopy(smp); - // Copy move constructor - ProtoSurfaceMaterial smpCopyMoved(std::move(smpCopy)); - } + // Constructor from arguments + ProtoSurfaceMaterial smp(smpBU); + // Copy constructor + ProtoSurfaceMaterial smpCopy(smp); + // Copy move constructor + ProtoSurfaceMaterial smpCopyMoved(std::move(smpCopy)); +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/Material/SurfaceMaterialMapperTests.cpp b/Tests/Core/Material/SurfaceMaterialMapperTests.cpp index c617d10e9bb579429e8ab325b3c09f3d8935583f..88ac6424b4b2e3588b701983a43dfd13aa8e29ed 100644 --- a/Tests/Core/Material/SurfaceMaterialMapperTests.cpp +++ b/Tests/Core/Material/SurfaceMaterialMapperTests.cpp @@ -28,16 +28,13 @@ namespace Acts { /// @brief create a small tracking geometry to map some dummy material on -std::shared_ptr<const TrackingGeometry> -trackingGeometry() -{ - +std::shared_ptr<const TrackingGeometry> trackingGeometry() { BinUtility zbinned(8, -40, 40, open, binZ); - auto matProxy = std::make_shared<const ProtoSurfaceMaterial>(zbinned); + auto matProxy = std::make_shared<const ProtoSurfaceMaterial>(zbinned); Logging::Level surfaceLLevel = Logging::INFO; - Logging::Level layerLLevel = Logging::INFO; - Logging::Level volumeLLevel = Logging::INFO; + Logging::Level layerLLevel = Logging::INFO; + Logging::Level volumeLLevel = Logging::INFO; // configure surface array creator auto surfaceArrayCreator = std::make_shared<const SurfaceArrayCreator>( @@ -45,7 +42,7 @@ trackingGeometry() // configure the layer creator that uses the surface array creator LayerCreator::Config lcConfig; lcConfig.surfaceArrayCreator = surfaceArrayCreator; - auto layerCreator = std::make_shared<const LayerCreator>( + auto layerCreator = std::make_shared<const LayerCreator>( lcConfig, getDefaultLogger("LayerCreator", layerLLevel)); // configure the layer array creator LayerArrayCreator::Config lacConfig; @@ -58,38 +55,38 @@ trackingGeometry() tvacConfig, getDefaultLogger("TrackingVolumeArrayCreator", volumeLLevel)); // configure the cylinder volume helper CylinderVolumeHelper::Config cvhConfig; - cvhConfig.layerArrayCreator = layerArrayCreator; + cvhConfig.layerArrayCreator = layerArrayCreator; cvhConfig.trackingVolumeArrayCreator = tVolumeArrayCreator; auto cylinderVolumeHelper = std::make_shared<const CylinderVolumeHelper>( cvhConfig, getDefaultLogger("CylinderVolumeHelper", volumeLLevel)); PassiveLayerBuilder::Config layerBuilderConfig; - layerBuilderConfig.layerIdentification = "CentralBarrel"; - layerBuilderConfig.centralLayerRadii = {10., 20., 30.}; + layerBuilderConfig.layerIdentification = "CentralBarrel"; + layerBuilderConfig.centralLayerRadii = {10., 20., 30.}; layerBuilderConfig.centralLayerHalflengthZ = {40., 40., 40.}; - layerBuilderConfig.centralLayerThickness = {1., 1., 1.}; - layerBuilderConfig.centralLayerMaterial = {matProxy, matProxy, matProxy}; + layerBuilderConfig.centralLayerThickness = {1., 1., 1.}; + layerBuilderConfig.centralLayerMaterial = {matProxy, matProxy, matProxy}; auto layerBuilder = std::make_shared<const PassiveLayerBuilder>( layerBuilderConfig, getDefaultLogger("CentralBarrelBuilder", layerLLevel)); // create the volume for the beam pipe CylinderVolumeBuilder::Config cvbConfig; cvbConfig.trackingVolumeHelper = cylinderVolumeHelper; - cvbConfig.volumeName = "BeamPipe"; - cvbConfig.layerBuilder = layerBuilder; - cvbConfig.layerEnvelopeR = {1. * units::_mm, 1. * units::_mm}; - cvbConfig.buildToRadiusZero = true; - cvbConfig.volumeSignature = 0; + cvbConfig.volumeName = "BeamPipe"; + cvbConfig.layerBuilder = layerBuilder; + cvbConfig.layerEnvelopeR = {1. * units::_mm, 1. * units::_mm}; + cvbConfig.buildToRadiusZero = true; + cvbConfig.volumeSignature = 0; auto centralVolumeBuilder = std::make_shared<const CylinderVolumeBuilder>( cvbConfig, getDefaultLogger("CentralVolumeBuilder", volumeLLevel)); // create the bounds and the volume - auto centralVolumeBounds - = std::make_shared<const CylinderVolumeBounds>(0., 40., 110.); + auto centralVolumeBounds = + std::make_shared<const CylinderVolumeBounds>(0., 40., 110.); GeometryContext gCtx; - auto centralVolume = centralVolumeBuilder->trackingVolume( - gCtx, nullptr, centralVolumeBounds); + auto centralVolume = + centralVolumeBuilder->trackingVolume(gCtx, nullptr, centralVolumeBounds); return std::make_shared<const TrackingGeometry>(centralVolume); } @@ -98,30 +95,28 @@ std::shared_ptr<const TrackingGeometry> tGeometry = trackingGeometry(); namespace Test { - /// Test the filling and conversion - BOOST_AUTO_TEST_CASE(SurfaceMaterialMapper_tests) - { - - /// We need a Navigator, Stepper to build a Propagator - Navigator navigator(tGeometry); - StraightLineStepper stepper; - SurfaceMaterialMapper::StraightLinePropagator propagator( - std::move(stepper), std::move(navigator)); +/// Test the filling and conversion +BOOST_AUTO_TEST_CASE(SurfaceMaterialMapper_tests) { + /// We need a Navigator, Stepper to build a Propagator + Navigator navigator(tGeometry); + StraightLineStepper stepper; + SurfaceMaterialMapper::StraightLinePropagator propagator( + std::move(stepper), std::move(navigator)); - /// The config object - SurfaceMaterialMapper::Config smmConfig; - SurfaceMaterialMapper smMapper(smmConfig, std::move(propagator)); + /// The config object + SurfaceMaterialMapper::Config smmConfig; + SurfaceMaterialMapper smMapper(smmConfig, std::move(propagator)); - /// Create some contexts - GeometryContext gCtx; - MagneticFieldContext mfCtx; + /// Create some contexts + GeometryContext gCtx; + MagneticFieldContext mfCtx; - /// Now create the mapper state - auto mState = smMapper.createState(gCtx, mfCtx, *tGeometry); + /// Now create the mapper state + auto mState = smMapper.createState(gCtx, mfCtx, *tGeometry); - /// Test if this is not null - BOOST_CHECK_EQUAL(mState.accumulatedMaterial.size(), 3); - } + /// Test if this is not null + BOOST_CHECK_EQUAL(mState.accumulatedMaterial.size(), 3); +} } // namespace Test diff --git a/Tests/Core/Material/VolumeMaterialMapperTests.cpp b/Tests/Core/Material/VolumeMaterialMapperTests.cpp index 1b0ffd883e51554273359d09c32e9504ecc34be7..f5c333b26610cb944ffa608c7d83c97b7f6a5c85 100644 --- a/Tests/Core/Material/VolumeMaterialMapperTests.cpp +++ b/Tests/Core/Material/VolumeMaterialMapperTests.cpp @@ -43,311 +43,294 @@ using namespace detail; namespace Test { - using RecordedMaterial - = std::vector<std::pair<Acts::Material, Acts::Vector3D>>; - using EAxis = Acts::detail::EquidistantAxis; - using Grid2D - = Acts::detail::Grid<Acts::AccumulatedVolumeMaterial, EAxis, EAxis>; - using Grid3D = Acts::detail:: - Grid<Acts::AccumulatedVolumeMaterial, EAxis, EAxis, EAxis>; - using MaterialGrid2D = Acts::detail::Grid<Acts::ActsVectorF<5>, EAxis, EAxis>; - using MaterialGrid3D - = Acts::detail::Grid<Acts::ActsVectorF<5>, EAxis, EAxis, EAxis>; - - /// @brief This function assigns material to the 2D bin number that represents - /// the local index of the first axis to the material point. - /// - /// @param [in] matPos Position of the material - /// @param [in] grid Grid that is used for the look-up - /// - /// @return Local grid point with the closest distance to @p matPos along the - /// first axis - Grid2D::index_t - mapToBin2D(const Vector3D& matPos, const Grid2D& grid) - { - double dist = std::numeric_limits<double>::max(); - size_t index = 0; - // Loop through all elements in the first axis - for (size_t i = 0; i < grid.numLocalBins()[0]; i++) { - // Search the closest distance - elements are ordered - if (std::abs(grid.upperRightBinEdge({{i, 0}})[0] - matPos.x()) < dist) { - // Store distance and index - dist = std::abs(grid.upperRightBinEdge({{i, 0}})[0] - matPos.x()); - index = i; - } else { // Break if distance becomes larger - break; - } +using RecordedMaterial = std::vector<std::pair<Acts::Material, Acts::Vector3D>>; +using EAxis = Acts::detail::EquidistantAxis; +using Grid2D = + Acts::detail::Grid<Acts::AccumulatedVolumeMaterial, EAxis, EAxis>; +using Grid3D = + Acts::detail::Grid<Acts::AccumulatedVolumeMaterial, EAxis, EAxis, EAxis>; +using MaterialGrid2D = Acts::detail::Grid<Acts::ActsVectorF<5>, EAxis, EAxis>; +using MaterialGrid3D = + Acts::detail::Grid<Acts::ActsVectorF<5>, EAxis, EAxis, EAxis>; + +/// @brief This function assigns material to the 2D bin number that represents +/// the local index of the first axis to the material point. +/// +/// @param [in] matPos Position of the material +/// @param [in] grid Grid that is used for the look-up +/// +/// @return Local grid point with the closest distance to @p matPos along the +/// first axis +Grid2D::index_t mapToBin2D(const Vector3D& matPos, const Grid2D& grid) { + double dist = std::numeric_limits<double>::max(); + size_t index = 0; + // Loop through all elements in the first axis + for (size_t i = 0; i < grid.numLocalBins()[0]; i++) { + // Search the closest distance - elements are ordered + if (std::abs(grid.upperRightBinEdge({{i, 0}})[0] - matPos.x()) < dist) { + // Store distance and index + dist = std::abs(grid.upperRightBinEdge({{i, 0}})[0] - matPos.x()); + index = i; + } else { // Break if distance becomes larger + break; } - return {{index, 0}}; } - - /// @brief This function assigns material to the 3D bin number that represents - /// the local index of the first axis to the material point. - /// - /// @param [in] matPos Position of the material - /// @param [in] grid Grid that is used for the look-up - /// - /// @return Local grid point with the closest distance to @p matPos along the - /// first axis - Grid3D::index_t - mapToBin3D(const Vector3D& matPos, const Grid3D& grid) - { - double dist = std::numeric_limits<double>::max(); - size_t index = 0; - // Loop through all elements in the first axis - for (size_t i = 0; i < grid.numLocalBins()[0]; i++) { - // Search the closest distance - elements are ordered - if (std::abs(grid.upperRightBinEdge({{i, 0, 0}})[0] - matPos.x()) - < dist) { - // Store distance and index - dist = std::abs(grid.upperRightBinEdge({{i, 0, 0}})[0] - matPos.x()); - index = i; - } else { // Break if distance becomes larger - break; - } + return {{index, 0}}; +} + +/// @brief This function assigns material to the 3D bin number that represents +/// the local index of the first axis to the material point. +/// +/// @param [in] matPos Position of the material +/// @param [in] grid Grid that is used for the look-up +/// +/// @return Local grid point with the closest distance to @p matPos along the +/// first axis +Grid3D::index_t mapToBin3D(const Vector3D& matPos, const Grid3D& grid) { + double dist = std::numeric_limits<double>::max(); + size_t index = 0; + // Loop through all elements in the first axis + for (size_t i = 0; i < grid.numLocalBins()[0]; i++) { + // Search the closest distance - elements are ordered + if (std::abs(grid.upperRightBinEdge({{i, 0, 0}})[0] - matPos.x()) < dist) { + // Store distance and index + dist = std::abs(grid.upperRightBinEdge({{i, 0, 0}})[0] - matPos.x()); + index = i; + } else { // Break if distance becomes larger + break; } - return {{index, 0, 0}}; } - - /// @brief Rough searcher for closest point - /// - /// @param [in] matPos Position of the material - /// @param [in] grid Grid that is used for the look-up - /// - /// @return Local grid point with the closest distance to @p matPos - Grid3D::index_t - mapMaterial3D(const Vector3D& matPos, const Grid3D& grid) - { - double dist = std::numeric_limits<double>::max(); - size_t indexX = 0, indexY = 0, indexZ = 0; - // Loop through all elements - for (size_t i = 0; i < grid.numLocalBins()[0]; i++) { - for (size_t j = 0; j < grid.numLocalBins()[1]; j++) { - for (size_t k = 0; k < grid.numLocalBins()[2]; k++) { - // Search the closest distance - elements are ordered - double dX = grid.upperRightBinEdge({{i, j, k}})[0] - matPos.x(); - double dY = grid.upperRightBinEdge({{i, j, k}})[1] - matPos.y(); - double dZ = grid.upperRightBinEdge({{i, j, k}})[2] - matPos.z(); - - if (std::sqrt(dX * dX + dY * dY + dZ * dZ) < dist) { - // Store distance and index - dist = std::sqrt(dX * dX + dY * dY + dZ * dZ); - indexX = i; - indexY = j; - indexZ = k; - } else { // Break if distance becomes larger - break; - } + return {{index, 0, 0}}; +} + +/// @brief Rough searcher for closest point +/// +/// @param [in] matPos Position of the material +/// @param [in] grid Grid that is used for the look-up +/// +/// @return Local grid point with the closest distance to @p matPos +Grid3D::index_t mapMaterial3D(const Vector3D& matPos, const Grid3D& grid) { + double dist = std::numeric_limits<double>::max(); + size_t indexX = 0, indexY = 0, indexZ = 0; + // Loop through all elements + for (size_t i = 0; i < grid.numLocalBins()[0]; i++) { + for (size_t j = 0; j < grid.numLocalBins()[1]; j++) { + for (size_t k = 0; k < grid.numLocalBins()[2]; k++) { + // Search the closest distance - elements are ordered + double dX = grid.upperRightBinEdge({{i, j, k}})[0] - matPos.x(); + double dY = grid.upperRightBinEdge({{i, j, k}})[1] - matPos.y(); + double dZ = grid.upperRightBinEdge({{i, j, k}})[2] - matPos.z(); + + if (std::sqrt(dX * dX + dY * dY + dZ * dZ) < dist) { + // Store distance and index + dist = std::sqrt(dX * dX + dY * dY + dZ * dZ); + indexX = i; + indexY = j; + indexZ = k; + } else { // Break if distance becomes larger + break; } } } - return {{indexX, indexY, indexZ}}; } - - /// @brief Collector of material and position along propagation - struct MaterialCollector - { - struct this_result - { - std::vector<Material> matTrue; - std::vector<Vector3D> position; - }; - using result_type = this_result; - - template <typename propagator_state_t, typename stepper_t> - void - operator()(propagator_state_t& state, - const stepper_t& stepper, - result_type& result) const - { - if (state.navigation.currentVolume != nullptr) { - - auto position = stepper.position(state.stepping); - result.matTrue.push_back( - (state.navigation.currentVolume->volumeMaterial() != nullptr) - ? state.navigation.currentVolume->volumeMaterial()->material( - position) - : Material()); - - result.position.push_back(position); - } - } + return {{indexX, indexY, indexZ}}; +} + +/// @brief Collector of material and position along propagation +struct MaterialCollector { + struct this_result { + std::vector<Material> matTrue; + std::vector<Vector3D> position; }; - - /// @brief Various test cases of the VolumeMaterialMapper functions - BOOST_AUTO_TEST_CASE(VolumeMaterialMapper_tests) - { - - // Define some axes and grid points - std::array<double, 3> axis1 = {0., 1., 2.}; - std::array<double, 3> axis2 = {2., 4., 3.}; - std::array<double, 3> axis3 = {5., 6., 3.}; - - // Make some materials - std::vector<std::pair<Material, Vector3D>> matRecord; - Material mat1(1., 2., 3., 4., 5.); - Material mat2(6., 7., 8., 9., 10.); - - Material vacuum; - ActsVectorF<5> matMix; - matMix << 3.5, 4.5, 5.5, 6.5, 7.5; - - // - // Test the production chain in 2D - // - matRecord.clear(); - matRecord.push_back(std::make_pair(mat1, Vector3D(0., 0., 0.))); - matRecord.push_back(std::make_pair(mat2, Vector3D(0.4, 0., 0.))); - matRecord.push_back(std::make_pair(mat2, Vector3D(0.6, 0., 0.))); - - MaterialGrid2D mgrid2d - = createMaterialGrid(axis1, axis2, matRecord, mapToBin2D); - - // Test sizes - BOOST_CHECK_EQUAL(mgrid2d.size(), (axis1[2] + 2) * (axis2[2] + 2)); - for (size_t index = 0; index < mgrid2d.size(); index++) { - // Check the contained data - if (index == 0) { - BOOST_CHECK_EQUAL(mgrid2d.at(index), matMix); - continue; - } - if (index == 5) { - BOOST_CHECK_EQUAL(mgrid2d.at(index), mat2.classificationNumbers()); - continue; - } - BOOST_CHECK_EQUAL(mgrid2d.at(index), vacuum.classificationNumbers()); + using result_type = this_result; + + template <typename propagator_state_t, typename stepper_t> + void operator()(propagator_state_t& state, const stepper_t& stepper, + result_type& result) const { + if (state.navigation.currentVolume != nullptr) { + auto position = stepper.position(state.stepping); + result.matTrue.push_back( + (state.navigation.currentVolume->volumeMaterial() != nullptr) + ? state.navigation.currentVolume->volumeMaterial()->material( + position) + : Material()); + + result.position.push_back(position); } - - // - // Test the production chain in 3D - // - MaterialGrid3D mgrid3d - = createMaterialGrid(axis1, axis2, axis3, matRecord, mapToBin3D); - - // Test sizes - BOOST_CHECK_EQUAL(mgrid3d.size(), - (axis1[2] + 2) * (axis2[2] + 2) * (axis3[2] + 2)); - for (size_t index = 0; index < mgrid3d.size(); index++) { - // Check the contained data - if (index == 0) { - BOOST_CHECK_EQUAL(mgrid3d.at(index), matMix); - continue; - } - if (index == 25) { - BOOST_CHECK_EQUAL(mgrid3d.at(index), mat2.classificationNumbers()); - continue; - } - BOOST_CHECK_EQUAL(mgrid3d.at(index), vacuum.classificationNumbers()); + } +}; + +/// @brief Various test cases of the VolumeMaterialMapper functions +BOOST_AUTO_TEST_CASE(VolumeMaterialMapper_tests) { + // Define some axes and grid points + std::array<double, 3> axis1 = {0., 1., 2.}; + std::array<double, 3> axis2 = {2., 4., 3.}; + std::array<double, 3> axis3 = {5., 6., 3.}; + + // Make some materials + std::vector<std::pair<Material, Vector3D>> matRecord; + Material mat1(1., 2., 3., 4., 5.); + Material mat2(6., 7., 8., 9., 10.); + + Material vacuum; + ActsVectorF<5> matMix; + matMix << 3.5, 4.5, 5.5, 6.5, 7.5; + + // + // Test the production chain in 2D + // + matRecord.clear(); + matRecord.push_back(std::make_pair(mat1, Vector3D(0., 0., 0.))); + matRecord.push_back(std::make_pair(mat2, Vector3D(0.4, 0., 0.))); + matRecord.push_back(std::make_pair(mat2, Vector3D(0.6, 0., 0.))); + + MaterialGrid2D mgrid2d = + createMaterialGrid(axis1, axis2, matRecord, mapToBin2D); + + // Test sizes + BOOST_CHECK_EQUAL(mgrid2d.size(), (axis1[2] + 2) * (axis2[2] + 2)); + for (size_t index = 0; index < mgrid2d.size(); index++) { + // Check the contained data + if (index == 0) { + BOOST_CHECK_EQUAL(mgrid2d.at(index), matMix); + continue; + } + if (index == 5) { + BOOST_CHECK_EQUAL(mgrid2d.at(index), mat2.classificationNumbers()); + continue; } + BOOST_CHECK_EQUAL(mgrid2d.at(index), vacuum.classificationNumbers()); } - /// @brief Test case for comparison between the mapped material and the - /// associated material by propagation - BOOST_AUTO_TEST_CASE(VolumeMaterialMapper_comparison_tests) - { - // Build a vacuum volume - CuboidVolumeBuilder::VolumeConfig vCfg1; - vCfg1.position = Vector3D(0.5 * units::_m, 0., 0.); - vCfg1.length = Vector3D(1. * units::_m, 1. * units::_m, 1. * units::_m); - vCfg1.name = "Vacuum volume"; - vCfg1.volumeMaterial = std::make_shared<const HomogeneousVolumeMaterial>( - Material(352.8, 407., 9.012, 4., 1.848e-3)); - - // Build a material volume - CuboidVolumeBuilder::VolumeConfig vCfg2; - vCfg2.position = Vector3D(1.5 * units::_m, 0., 0.); - vCfg2.length = Vector3D(1. * units::_m, 1. * units::_m, 1. * units::_m); - vCfg2.name = "First material volume"; - vCfg2.volumeMaterial = std::make_shared<const HomogeneousVolumeMaterial>( - Material(95.7, 465.2, 28.03, 14., 2.32e-3)); - - // Build another material volume with different material - CuboidVolumeBuilder::VolumeConfig vCfg3; - vCfg3.position = Vector3D(2.5 * units::_m, 0., 0.); - vCfg3.length = Vector3D(1. * units::_m, 1. * units::_m, 1. * units::_m); - vCfg3.name = "Second material volume"; - vCfg3.volumeMaterial = std::make_shared<const HomogeneousVolumeMaterial>( - Material(352.8, 407., 9.012, 4., 1.848e-3)); - - // Configure world - CuboidVolumeBuilder::Config cfg; - cfg.position = Vector3D(1.5 * units::_m, 0., 0.); - cfg.length = Vector3D(3. * units::_m, 1. * units::_m, 1. * units::_m); - cfg.volumeCfg = {vCfg1, vCfg2, vCfg3}; - - GeometryContext gc; - - // Build a detector - CuboidVolumeBuilder cvb(cfg); - TrackingGeometryBuilder::Config tgbCfg; - tgbCfg.trackingVolumeBuilders.push_back( - [=](const auto& context, const auto& inner, const auto&) { - return cvb.trackingVolume(context, inner, nullptr); - }); - TrackingGeometryBuilder tgb(tgbCfg); - std::unique_ptr<const TrackingGeometry> detector = tgb.trackingGeometry(gc); - - // Set up the grid axes - std::array<double, 3> xAxis{0. * units::_m, 3. * units::_m, 7}; - std::array<double, 3> yAxis{-0.5 * units::_m, 0.5 * units::_m, 7}; - std::array<double, 3> zAxis{-0.5 * units::_m, 0.5 * units::_m, 7}; - - // Set up a random engine for sampling material - std::random_device rd; - std::mt19937 gen(42); - std::uniform_real_distribution<> disX(0., 3. * units::_m); - std::uniform_real_distribution<> disYZ(-0.5 * units::_m, 0.5 * units::_m); - - // Sample the Material in the detector - RecordedMaterial matRecord; - for (unsigned int i = 0; i < 1e4; i++) { - Vector3D pos(disX(gen), disYZ(gen), disYZ(gen)); - Material tv = (detector->lowestTrackingVolume(gc, pos)->volumeMaterial() - != nullptr) - ? (detector->lowestTrackingVolume(gc, pos)->volumeMaterial()) - ->material(pos) - : Material(); - matRecord.push_back(std::make_pair(tv, pos)); + // + // Test the production chain in 3D + // + MaterialGrid3D mgrid3d = + createMaterialGrid(axis1, axis2, axis3, matRecord, mapToBin3D); + + // Test sizes + BOOST_CHECK_EQUAL(mgrid3d.size(), + (axis1[2] + 2) * (axis2[2] + 2) * (axis3[2] + 2)); + for (size_t index = 0; index < mgrid3d.size(); index++) { + // Check the contained data + if (index == 0) { + BOOST_CHECK_EQUAL(mgrid3d.at(index), matMix); + continue; } - - // Build the material grid - MaterialGrid3D grid - = createMaterialGrid(xAxis, yAxis, zAxis, matRecord, mapMaterial3D); - - // Construct a simple propagation through the detector - StraightLineStepper sls; - Navigator nav(std::move(detector)); - Propagator<StraightLineStepper, Navigator> prop(sls, nav); - - // Set some start parameters - Vector3D pos(0., 0., 0.); - Vector3D mom(1. * units::_GeV, 0., 0.); - SingleCurvilinearTrackParameters<NeutralPolicy> sctp(nullptr, pos, mom); - - MagneticFieldContext mc; - - // Launch propagation and gather result - PropagatorOptions<ActionList<MaterialCollector>, - AbortList<detail::EndOfWorldReached>> - po(gc, mc); - po.maxStepSize = 1. * units::_mm; - po.maxSteps = 1e6; - const auto& result = prop.propagate(sctp, po).value(); - const MaterialCollector::this_result& stepResult - = result.get<typename MaterialCollector::result_type>(); - - // Collect the material as given by the grid and test it - std::vector<Material> matGrid; - double gridX0 = 0., gridL0 = 0., trueX0 = 0., trueL0 = 0.; - for (unsigned int i = 0; i < stepResult.position.size(); i++) { - matGrid.push_back(grid.atPosition(stepResult.position[i])); - gridX0 += matGrid[i].X0(); - gridL0 += matGrid[i].L0(); - trueX0 += stepResult.matTrue[i].X0(); - trueL0 += stepResult.matTrue[i].L0(); + if (index == 25) { + BOOST_CHECK_EQUAL(mgrid3d.at(index), mat2.classificationNumbers()); + continue; } - CHECK_CLOSE_REL(gridX0, trueX0, 1e-1); - CHECK_CLOSE_REL(gridL0, trueL0, 1e-1); + BOOST_CHECK_EQUAL(mgrid3d.at(index), vacuum.classificationNumbers()); + } +} + +/// @brief Test case for comparison between the mapped material and the +/// associated material by propagation +BOOST_AUTO_TEST_CASE(VolumeMaterialMapper_comparison_tests) { + // Build a vacuum volume + CuboidVolumeBuilder::VolumeConfig vCfg1; + vCfg1.position = Vector3D(0.5 * units::_m, 0., 0.); + vCfg1.length = Vector3D(1. * units::_m, 1. * units::_m, 1. * units::_m); + vCfg1.name = "Vacuum volume"; + vCfg1.volumeMaterial = std::make_shared<const HomogeneousVolumeMaterial>( + Material(352.8, 407., 9.012, 4., 1.848e-3)); + + // Build a material volume + CuboidVolumeBuilder::VolumeConfig vCfg2; + vCfg2.position = Vector3D(1.5 * units::_m, 0., 0.); + vCfg2.length = Vector3D(1. * units::_m, 1. * units::_m, 1. * units::_m); + vCfg2.name = "First material volume"; + vCfg2.volumeMaterial = std::make_shared<const HomogeneousVolumeMaterial>( + Material(95.7, 465.2, 28.03, 14., 2.32e-3)); + + // Build another material volume with different material + CuboidVolumeBuilder::VolumeConfig vCfg3; + vCfg3.position = Vector3D(2.5 * units::_m, 0., 0.); + vCfg3.length = Vector3D(1. * units::_m, 1. * units::_m, 1. * units::_m); + vCfg3.name = "Second material volume"; + vCfg3.volumeMaterial = std::make_shared<const HomogeneousVolumeMaterial>( + Material(352.8, 407., 9.012, 4., 1.848e-3)); + + // Configure world + CuboidVolumeBuilder::Config cfg; + cfg.position = Vector3D(1.5 * units::_m, 0., 0.); + cfg.length = Vector3D(3. * units::_m, 1. * units::_m, 1. * units::_m); + cfg.volumeCfg = {vCfg1, vCfg2, vCfg3}; + + GeometryContext gc; + + // Build a detector + CuboidVolumeBuilder cvb(cfg); + TrackingGeometryBuilder::Config tgbCfg; + tgbCfg.trackingVolumeBuilders.push_back( + [=](const auto& context, const auto& inner, const auto&) { + return cvb.trackingVolume(context, inner, nullptr); + }); + TrackingGeometryBuilder tgb(tgbCfg); + std::unique_ptr<const TrackingGeometry> detector = tgb.trackingGeometry(gc); + + // Set up the grid axes + std::array<double, 3> xAxis{0. * units::_m, 3. * units::_m, 7}; + std::array<double, 3> yAxis{-0.5 * units::_m, 0.5 * units::_m, 7}; + std::array<double, 3> zAxis{-0.5 * units::_m, 0.5 * units::_m, 7}; + + // Set up a random engine for sampling material + std::random_device rd; + std::mt19937 gen(42); + std::uniform_real_distribution<> disX(0., 3. * units::_m); + std::uniform_real_distribution<> disYZ(-0.5 * units::_m, 0.5 * units::_m); + + // Sample the Material in the detector + RecordedMaterial matRecord; + for (unsigned int i = 0; i < 1e4; i++) { + Vector3D pos(disX(gen), disYZ(gen), disYZ(gen)); + Material tv = + (detector->lowestTrackingVolume(gc, pos)->volumeMaterial() != nullptr) + ? (detector->lowestTrackingVolume(gc, pos)->volumeMaterial()) + ->material(pos) + : Material(); + matRecord.push_back(std::make_pair(tv, pos)); + } + + // Build the material grid + MaterialGrid3D grid = + createMaterialGrid(xAxis, yAxis, zAxis, matRecord, mapMaterial3D); + + // Construct a simple propagation through the detector + StraightLineStepper sls; + Navigator nav(std::move(detector)); + Propagator<StraightLineStepper, Navigator> prop(sls, nav); + + // Set some start parameters + Vector3D pos(0., 0., 0.); + Vector3D mom(1. * units::_GeV, 0., 0.); + SingleCurvilinearTrackParameters<NeutralPolicy> sctp(nullptr, pos, mom); + + MagneticFieldContext mc; + + // Launch propagation and gather result + PropagatorOptions<ActionList<MaterialCollector>, + AbortList<detail::EndOfWorldReached>> + po(gc, mc); + po.maxStepSize = 1. * units::_mm; + po.maxSteps = 1e6; + const auto& result = prop.propagate(sctp, po).value(); + const MaterialCollector::this_result& stepResult = + result.get<typename MaterialCollector::result_type>(); + + // Collect the material as given by the grid and test it + std::vector<Material> matGrid; + double gridX0 = 0., gridL0 = 0., trueX0 = 0., trueL0 = 0.; + for (unsigned int i = 0; i < stepResult.position.size(); i++) { + matGrid.push_back(grid.atPosition(stepResult.position[i])); + gridX0 += matGrid[i].X0(); + gridL0 += matGrid[i].L0(); + trueX0 += stepResult.matTrue[i].X0(); + trueL0 += stepResult.matTrue[i].L0(); } + CHECK_CLOSE_REL(gridX0, trueX0, 1e-1); + CHECK_CLOSE_REL(gridL0, trueL0, 1e-1); +} } // namespace Test } // namespace Acts \ No newline at end of file diff --git a/Tests/Core/Propagator/AbortListTests.cpp b/Tests/Core/Propagator/AbortListTests.cpp index f145ceac93347072eb9f4c25bc6e73c88f78e46a..773c01860a2d44ef4d7a7b2e452fdec3f6ccc706 100644 --- a/Tests/Core/Propagator/AbortListTests.cpp +++ b/Tests/Core/Propagator/AbortListTests.cpp @@ -27,7 +27,7 @@ #include "Acts/Utilities/detail/Extendable.hpp" namespace bdata = boost::unit_test::data; -namespace tt = boost::test_tools; +namespace tt = boost::test_tools; namespace Acts { @@ -35,125 +35,114 @@ class Surface; namespace Test { - // The path limit abort - using PathLimit = detail::PathLimitReached; +// The path limit abort +using PathLimit = detail::PathLimitReached; - // The end of world abort - using EndOfWorld = detail::EndOfWorldReached; +// The end of world abort +using EndOfWorld = detail::EndOfWorldReached; - // the constrained step class - using cstep = detail::ConstrainedStep; +// the constrained step class +using cstep = detail::ConstrainedStep; - /// This is a simple cache struct to mimic the - /// Navigator state - struct NavigatorState - { - /// Navigation cache: the start surface - const Surface* startSurface = nullptr; +/// This is a simple cache struct to mimic the +/// Navigator state +struct NavigatorState { + /// Navigation cache: the start surface + const Surface* startSurface = nullptr; - /// Navigation cache: the current surface - const Surface* currentSurface = nullptr; + /// Navigation cache: the current surface + const Surface* currentSurface = nullptr; - /// Navigation cache: the target surface - const Surface* targetSurface = nullptr; + /// Navigation cache: the target surface + const Surface* targetSurface = nullptr; - /// The boolean is reached - bool targetReached = false; - }; + /// The boolean is reached + bool targetReached = false; +}; - /// This is a simple cache struct to mimic the - /// Propagator state - struct PropagatorState - { - - // This is a simple cache struct to mimic the - // Stepper cache in the propagation - struct StepperState - { - // accummulated path length cache - double pathAccumulated = 0.; - - // adaptive sep size of the runge-kutta integration - cstep stepSize = std::numeric_limits<double>::max(); - }; - - /// emulate the options template - struct Options - { - - /// The path limit - double pathLimit = std::numeric_limits<double>::max(); - - /// The target tolerance - double targetTolerance = 1. * units::_um; - - /// Debug output - /// the string where debug messages are stored (optionally) - bool debug = false; - std::string debugString = ""; - /// buffer & formatting for consistent output - size_t debugPfxWidth = 30; - size_t debugMsgWidth = 50; - }; - - /// Give some options - Options options; - - /// The stepper state - StepperState stepping; - - /// The navigator state - NavigatorState navigation; - }; +/// This is a simple cache struct to mimic the +/// Propagator state +struct PropagatorState { + // This is a simple cache struct to mimic the + // Stepper cache in the propagation + struct StepperState { + // accummulated path length cache + double pathAccumulated = 0.; - /// This is a struct to mimic the stepper - struct Stepper - { + // adaptive sep size of the runge-kutta integration + cstep stepSize = std::numeric_limits<double>::max(); }; - /// This is a simple result struct to mimic the - /// propagator result - struct Result - { + /// emulate the options template + struct Options { + /// The path limit + double pathLimit = std::numeric_limits<double>::max(); + + /// The target tolerance + double targetTolerance = 1. * units::_um; + + /// Debug output + /// the string where debug messages are stored (optionally) + bool debug = false; + std::string debugString = ""; + /// buffer & formatting for consistent output + size_t debugPfxWidth = 30; + size_t debugMsgWidth = 50; }; - // This tests the implementation of the AbortList - // and the standard aborters - BOOST_AUTO_TEST_CASE(AbortListTest_PathLimit) - { - PropagatorState state; - state.options.pathLimit = 1. * units::_m; - Stepper stepper; - Result result; - - AbortList<PathLimit> abortList; - - // It should not abort yet - BOOST_CHECK(!abortList(result, state, stepper)); - // The step size should be adapted to 1 meter now - BOOST_CHECK_EQUAL(state.stepping.stepSize, 1. * units::_m); - // Let's do a step of 90 cm now - state.stepping.pathAccumulated = 90. * units::_cm; - // Still no abort yet - BOOST_CHECK(!abortList(result, state, stepper)); - // 10 cm are left - // The step size should be adapted to 10 cm now - BOOST_CHECK_EQUAL(state.stepping.stepSize, 10. * units::_cm); - - // Approach the target - while (!abortList(result, state, stepper)) { - state.stepping.pathAccumulated += 0.5 * state.stepping.stepSize; - } - - // now we need to be smaller than the tolerance - BOOST_CHECK_LT(state.stepping.stepSize, 1. * units::_um); - - // Check if you can expand the AbortList - EndOfWorld eow; - AbortList<PathLimit, EndOfWorld> pathWorld = abortList.append(eow); - auto& path = pathWorld.get<PathLimit>(); - BOOST_CHECK(path(result, state, stepper)); + /// Give some options + Options options; + + /// The stepper state + StepperState stepping; + + /// The navigator state + NavigatorState navigation; +}; + +/// This is a struct to mimic the stepper +struct Stepper {}; + +/// This is a simple result struct to mimic the +/// propagator result +struct Result {}; + +// This tests the implementation of the AbortList +// and the standard aborters +BOOST_AUTO_TEST_CASE(AbortListTest_PathLimit) { + PropagatorState state; + state.options.pathLimit = 1. * units::_m; + Stepper stepper; + Result result; + + AbortList<PathLimit> abortList; + + // It should not abort yet + BOOST_CHECK(!abortList(result, state, stepper)); + // The step size should be adapted to 1 meter now + BOOST_CHECK_EQUAL(state.stepping.stepSize, 1. * units::_m); + // Let's do a step of 90 cm now + state.stepping.pathAccumulated = 90. * units::_cm; + // Still no abort yet + BOOST_CHECK(!abortList(result, state, stepper)); + // 10 cm are left + // The step size should be adapted to 10 cm now + BOOST_CHECK_EQUAL(state.stepping.stepSize, 10. * units::_cm); + + // Approach the target + while (!abortList(result, state, stepper)) { + state.stepping.pathAccumulated += 0.5 * state.stepping.stepSize; } + // now we need to be smaller than the tolerance + BOOST_CHECK_LT(state.stepping.stepSize, 1. * units::_um); + + // Check if you can expand the AbortList + EndOfWorld eow; + AbortList<PathLimit, EndOfWorld> pathWorld = abortList.append(eow); + auto& path = pathWorld.get<PathLimit>(); + BOOST_CHECK(path(result, state, stepper)); +} + } // namespace Test } // namespace Acts diff --git a/Tests/Core/Propagator/ActionListTests.cpp b/Tests/Core/Propagator/ActionListTests.cpp index 05148ee9b727c4538c30e799d87374f1ac213651..eb9ecd53544bab2509f7254a232bfcdfb8803ff0 100644 --- a/Tests/Core/Propagator/ActionListTests.cpp +++ b/Tests/Core/Propagator/ActionListTests.cpp @@ -31,180 +31,153 @@ #include "Acts/Utilities/detail/Extendable.hpp" namespace bdata = boost::unit_test::data; -namespace tt = boost::test_tools; +namespace tt = boost::test_tools; namespace Acts { namespace Test { - // the constrained step class - using cstep = detail::ConstrainedStep; - - /// This is a simple cache struct to mimic the - /// Propagator cache - struct PropagatorState - { - - // This is a simple cache struct to mimic the - // Stepper cache in the propagation - struct StepperState - { - // accummulated path length cache - double pathAccumulated = 0.; - - // adaptive sep size of the runge-kutta integration - cstep stepSize = std::numeric_limits<double>::max(); - }; - - /// emulate the options template - struct Options - { - /// Debug output - /// the string where debug messages are stored (optionally) - bool debug = false; - std::string debugString = ""; - /// buffer & formatting for consistent output - size_t debugPfxWidth = 30; - size_t debugMsgWidth = 50; - }; - - /// Navigation cache: the start surface - const Surface* startSurface = nullptr; - - /// Navigation cache: the current surface - const Surface* currentSurface = nullptr; - - /// Navigation cache: the target surface - const Surface* targetSurface = nullptr; - bool targetReached = false; - - /// Give some options - Options options; - - /// The Stepper cache - StepperState stepping; - }; +// the constrained step class +using cstep = detail::ConstrainedStep; + +/// This is a simple cache struct to mimic the +/// Propagator cache +struct PropagatorState { + // This is a simple cache struct to mimic the + // Stepper cache in the propagation + struct StepperState { + // accummulated path length cache + double pathAccumulated = 0.; - /// This is a simple struct to mimic the stepper - struct Stepper - { + // adaptive sep size of the runge-kutta integration + cstep stepSize = std::numeric_limits<double>::max(); }; - /// A distance observer struct as an actor - struct DistanceObserver - { - double path_to_go = 100. * units::_mm; - - struct this_result - { - double distance = std::numeric_limits<double>::max(); - }; - - using result_type = this_result; - - DistanceObserver(double ptg = 0.) : path_to_go(ptg) {} - - template <typename propagator_state_t, typename stepper_t> - void - operator()(propagator_state_t& state, - const stepper_t& /*unused*/, - result_type& result) const - { - result.distance = path_to_go - state.stepping.pathAccumulated; - } - - template <typename propagator_state_t, typename stepper_t> - void - operator()(propagator_state_t& /*unused*/, - const stepper_t& /*unused*/) const - { - } + /// emulate the options template + struct Options { + /// Debug output + /// the string where debug messages are stored (optionally) + bool debug = false; + std::string debugString = ""; + /// buffer & formatting for consistent output + size_t debugPfxWidth = 30; + size_t debugMsgWidth = 50; }; - /// A call counter struct as an actor - struct CallCounter - { - - struct this_result - { - size_t calls = 0; - }; - - using result_type = this_result; - - CallCounter() = default; - - template <typename propagator_state_t, typename stepper_t> - void - operator()(propagator_state_t& /*unused*/, - const stepper_t& /*unused*/, - result_type& r) const - { - ++r.calls; - } - - template <typename propagator_state_t, typename stepper_t> - void - operator()(propagator_state_t& /*unused*/, - const stepper_t& /*unused*/) const - { - } + /// Navigation cache: the start surface + const Surface* startSurface = nullptr; + + /// Navigation cache: the current surface + const Surface* currentSurface = nullptr; + + /// Navigation cache: the target surface + const Surface* targetSurface = nullptr; + bool targetReached = false; + + /// Give some options + Options options; + + /// The Stepper cache + StepperState stepping; +}; + +/// This is a simple struct to mimic the stepper +struct Stepper {}; + +/// A distance observer struct as an actor +struct DistanceObserver { + double path_to_go = 100. * units::_mm; + + struct this_result { + double distance = std::numeric_limits<double>::max(); }; - // This tests the implementation of the ActionList - // and the standard aborters - BOOST_AUTO_TEST_CASE(ActionListTest_Distance) - { - // construct the (prop/step) cache and result - PropagatorState state; - Stepper stepper; - - // Type of track parameters produced at the end of the propagation - using distance_result = typename DistanceObserver::result_type; - detail::Extendable<distance_result> result; - - ActionList<DistanceObserver> action_list; - action_list.get<DistanceObserver>().path_to_go = 100. * units::_mm; - - // observe and check - action_list(state, stepper, result); - BOOST_CHECK_EQUAL(result.get<distance_result>().distance, - 100. * units::_mm); - - // now move the cache and check again - state.stepping.pathAccumulated = 50. * units::_mm; - action_list(state, stepper, result); - BOOST_CHECK_EQUAL(result.get<distance_result>().distance, 50. * units::_mm); + using result_type = this_result; + + DistanceObserver(double ptg = 0.) : path_to_go(ptg) {} + + template <typename propagator_state_t, typename stepper_t> + void operator()(propagator_state_t& state, const stepper_t& /*unused*/, + result_type& result) const { + result.distance = path_to_go - state.stepping.pathAccumulated; } - // This tests the implementation of the ActionList - // and the standard aborters - BOOST_AUTO_TEST_CASE(ActionListTest_TwoActions) - { - // construct the (prop/step) cache and result - PropagatorState state; - Stepper stepper; - - // Type of track parameters produced at the end of the propagation - using distance_result = typename DistanceObserver::result_type; - using caller_result = typename CallCounter::result_type; - ActionList<DistanceObserver, CallCounter> action_list; - action_list.get<DistanceObserver>().path_to_go = 100. * units::_mm; - - detail::Extendable<distance_result, caller_result> result; - - //// observe and check - action_list(state, stepper, result); - BOOST_CHECK_EQUAL(result.get<distance_result>().distance, - 100. * units::_mm); - BOOST_CHECK_EQUAL(result.get<caller_result>().calls, 1); - - // now move the cache and check again - state.stepping.pathAccumulated = 50. * units::_mm; - action_list(state, stepper, result); - BOOST_CHECK_EQUAL(result.get<distance_result>().distance, 50. * units::_mm); - BOOST_CHECK_EQUAL(result.get<caller_result>().calls, 2); + template <typename propagator_state_t, typename stepper_t> + void operator()(propagator_state_t& /*unused*/, + const stepper_t& /*unused*/) const {} +}; + +/// A call counter struct as an actor +struct CallCounter { + struct this_result { + size_t calls = 0; + }; + + using result_type = this_result; + + CallCounter() = default; + + template <typename propagator_state_t, typename stepper_t> + void operator()(propagator_state_t& /*unused*/, const stepper_t& /*unused*/, + result_type& r) const { + ++r.calls; } + template <typename propagator_state_t, typename stepper_t> + void operator()(propagator_state_t& /*unused*/, + const stepper_t& /*unused*/) const {} +}; + +// This tests the implementation of the ActionList +// and the standard aborters +BOOST_AUTO_TEST_CASE(ActionListTest_Distance) { + // construct the (prop/step) cache and result + PropagatorState state; + Stepper stepper; + + // Type of track parameters produced at the end of the propagation + using distance_result = typename DistanceObserver::result_type; + detail::Extendable<distance_result> result; + + ActionList<DistanceObserver> action_list; + action_list.get<DistanceObserver>().path_to_go = 100. * units::_mm; + + // observe and check + action_list(state, stepper, result); + BOOST_CHECK_EQUAL(result.get<distance_result>().distance, 100. * units::_mm); + + // now move the cache and check again + state.stepping.pathAccumulated = 50. * units::_mm; + action_list(state, stepper, result); + BOOST_CHECK_EQUAL(result.get<distance_result>().distance, 50. * units::_mm); +} + +// This tests the implementation of the ActionList +// and the standard aborters +BOOST_AUTO_TEST_CASE(ActionListTest_TwoActions) { + // construct the (prop/step) cache and result + PropagatorState state; + Stepper stepper; + + // Type of track parameters produced at the end of the propagation + using distance_result = typename DistanceObserver::result_type; + using caller_result = typename CallCounter::result_type; + ActionList<DistanceObserver, CallCounter> action_list; + action_list.get<DistanceObserver>().path_to_go = 100. * units::_mm; + + detail::Extendable<distance_result, caller_result> result; + + //// observe and check + action_list(state, stepper, result); + BOOST_CHECK_EQUAL(result.get<distance_result>().distance, 100. * units::_mm); + BOOST_CHECK_EQUAL(result.get<caller_result>().calls, 1); + + // now move the cache and check again + state.stepping.pathAccumulated = 50. * units::_mm; + action_list(state, stepper, result); + BOOST_CHECK_EQUAL(result.get<distance_result>().distance, 50. * units::_mm); + BOOST_CHECK_EQUAL(result.get<caller_result>().calls, 2); +} + } // namespace Test } // namespace Acts diff --git a/Tests/Core/Propagator/AtlasStepperBenchmark.cpp b/Tests/Core/Propagator/AtlasStepperBenchmark.cpp index 9f04d8b41c58b58b7cd1ae1c0ef199f8e9db0740..1e43b51e4a54ffab703d2adfa5f02056fb20dcb8 100644 --- a/Tests/Core/Propagator/AtlasStepperBenchmark.cpp +++ b/Tests/Core/Propagator/AtlasStepperBenchmark.cpp @@ -20,18 +20,16 @@ namespace po = boost::program_options; using namespace Acts; -int -main(int argc, char* argv[]) -{ - unsigned int toys = 1; - double pT = 1; - double Bz = 1; - double maxPath = 1; - unsigned int lvl = Acts::Logging::INFO; - bool withCov = true; +int main(int argc, char* argv[]) { + unsigned int toys = 1; + double pT = 1; + double Bz = 1; + double maxPath = 1; + unsigned int lvl = Acts::Logging::INFO; + bool withCov = true; // Create a test context - GeometryContext tgContext = GeometryContext(); + GeometryContext tgContext = GeometryContext(); MagneticFieldContext mfContext = MagneticFieldContext(); try { @@ -64,22 +62,21 @@ main(int argc, char* argv[]) // print information about profiling setup ACTS_INFO("propagating " << toys << " tracks with pT = " << pT << "GeV in a " - << Bz - << "T B-field"); + << Bz << "T B-field"); - using BField_type = ConstantBField; - using Stepper_type = AtlasStepper<BField_type>; + using BField_type = ConstantBField; + using Stepper_type = AtlasStepper<BField_type>; using Propagator_type = Propagator<Stepper_type>; - BField_type bField(0, 0, Bz * units::_T); - Stepper_type atlas_stepper(std::move(bField)); + BField_type bField(0, 0, Bz * units::_T); + Stepper_type atlas_stepper(std::move(bField)); Propagator_type propagator(std::move(atlas_stepper)); PropagatorOptions<> options(tgContext, mfContext); options.pathLimit = maxPath * units::_m; - Vector3D pos(0, 0, 0); - Vector3D mom(pT * units::_GeV, 0, 0); + Vector3D pos(0, 0, 0); + Vector3D mom(pT * units::_GeV, 0, 0); ActsSymMatrixD<5> cov; cov << 10 * units::_mm, 0, 0, 0, 0, 0, 10 * units::_mm, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1. / (10 * units::_GeV); @@ -94,12 +91,9 @@ main(int argc, char* argv[]) for (unsigned int i = 0; i < toys; ++i) { auto r = propagator.propagate(pars, options).value(); ACTS_DEBUG("reached position (" << r.endParameters->position().x() << ", " - << r.endParameters->position().y() - << ", " + << r.endParameters->position().y() << ", " << r.endParameters->position().z() - << ") in " - << r.steps - << " steps"); + << ") in " << r.steps << " steps"); totalPathLength += r.pathLength; } diff --git a/Tests/Core/Propagator/AuctioneerTests.cpp b/Tests/Core/Propagator/AuctioneerTests.cpp index d396abf1561b3c617d6027f1cd6c7ed3b14438cb..8ff550b2e141f13562bade16d6df13a54637f86a 100644 --- a/Tests/Core/Propagator/AuctioneerTests.cpp +++ b/Tests/Core/Propagator/AuctioneerTests.cpp @@ -19,43 +19,40 @@ namespace Acts { namespace Test { - BOOST_AUTO_TEST_CASE(AuctioneerTest_VoidAuctioneer) - { - // Build arbitrary vector - std::array<int, 4> vecArb = {0, 2, -5, 4}; - std::array<bool, 4> vecRes = {false, true, false, true}; - // Let it run through auction - detail::VoidAuctioneer va; - std::array<bool, 4> resultVa = va(vecArb); - // Test that vector did not change - BOOST_CHECK_EQUAL_COLLECTIONS( - vecRes.begin(), vecRes.end(), resultVa.begin(), resultVa.end()); - } +BOOST_AUTO_TEST_CASE(AuctioneerTest_VoidAuctioneer) { + // Build arbitrary vector + std::array<int, 4> vecArb = {0, 2, -5, 4}; + std::array<bool, 4> vecRes = {false, true, false, true}; + // Let it run through auction + detail::VoidAuctioneer va; + std::array<bool, 4> resultVa = va(vecArb); + // Test that vector did not change + BOOST_CHECK_EQUAL_COLLECTIONS(vecRes.begin(), vecRes.end(), resultVa.begin(), + resultVa.end()); +} - BOOST_AUTO_TEST_CASE(AuctioneerTest_FirstValidAuctioneer) - { - // Build arbitrary vector - std::array<int, 4> vecArb = {0, 1, -2, 4}; - // Let it run through auction - detail::FirstValidAuctioneer fva; - std::array<bool, 4> resultFva = fva(vecArb); - std::array<bool, 4> expected = {false, true, false, false}; - // Test that vector did not change - BOOST_CHECK_EQUAL_COLLECTIONS( - expected.begin(), expected.end(), resultFva.begin(), resultFva.end()); - } +BOOST_AUTO_TEST_CASE(AuctioneerTest_FirstValidAuctioneer) { + // Build arbitrary vector + std::array<int, 4> vecArb = {0, 1, -2, 4}; + // Let it run through auction + detail::FirstValidAuctioneer fva; + std::array<bool, 4> resultFva = fva(vecArb); + std::array<bool, 4> expected = {false, true, false, false}; + // Test that vector did not change + BOOST_CHECK_EQUAL_COLLECTIONS(expected.begin(), expected.end(), + resultFva.begin(), resultFva.end()); +} - BOOST_AUTO_TEST_CASE(AuctioneerTest_HighestValidAuctioneer) - { - // Build arbitrary vector - std::array<int, 4> vecArb = {0, 1, -2, 4}; - // Let it run through auction - detail::HighestValidAuctioneer fva; - std::array<bool, 4> resultFva = fva(vecArb); - std::array<bool, 4> expected = {false, false, false, true}; - // Test that vector did not change - BOOST_CHECK_EQUAL_COLLECTIONS( - expected.begin(), expected.end(), resultFva.begin(), resultFva.end()); - } +BOOST_AUTO_TEST_CASE(AuctioneerTest_HighestValidAuctioneer) { + // Build arbitrary vector + std::array<int, 4> vecArb = {0, 1, -2, 4}; + // Let it run through auction + detail::HighestValidAuctioneer fva; + std::array<bool, 4> resultFva = fva(vecArb); + std::array<bool, 4> expected = {false, false, false, true}; + // Test that vector did not change + BOOST_CHECK_EQUAL_COLLECTIONS(expected.begin(), expected.end(), + resultFva.begin(), resultFva.end()); +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/Propagator/ConstrainedStepTests.cpp b/Tests/Core/Propagator/ConstrainedStepTests.cpp index fbd3a9bccbd1d9b342f32ec31bb01db76b195bde..06396c6152a9dfa340870b0fb66eca5cc328fbcd 100644 --- a/Tests/Core/Propagator/ConstrainedStepTests.cpp +++ b/Tests/Core/Propagator/ConstrainedStepTests.cpp @@ -22,92 +22,90 @@ #include "Acts/Propagator/detail/ConstrainedStep.hpp" namespace bdata = boost::unit_test::data; -namespace tt = boost::test_tools; +namespace tt = boost::test_tools; namespace Acts { namespace Test { - // This tests the implementation of the AbortList - // and the standard aborters - BOOST_AUTO_TEST_CASE(ConstrainedStepTest) - { - - using cstep = detail::ConstrainedStep; - - // forward stepping test - cstep stepSize_p = 0.25; - - // All of the types should be 0.25 now - BOOST_CHECK_EQUAL(stepSize_p.values[cstep::accuracy], 0.25); - BOOST_CHECK_EQUAL(stepSize_p.values[cstep::actor], 0.25); - BOOST_CHECK_EQUAL(stepSize_p.values[cstep::aborter], 0.25); - BOOST_CHECK_EQUAL(stepSize_p.values[cstep::user], 0.25); - - // Check the cast operation to double - BOOST_CHECK_EQUAL(stepSize_p, 0.25); - - // now we update the accuracy - stepSize_p.update(0.1, cstep::accuracy); - BOOST_CHECK_EQUAL(stepSize_p, 0.1); - - // now we update the actor to smaller - stepSize_p.update(0.05, cstep::actor); - BOOST_CHECK_EQUAL(stepSize_p, 0.05); - // we increase the actor, but do not release the step size - stepSize_p.update(0.15, cstep::actor, false); - BOOST_CHECK_EQUAL(stepSize_p, 0.05); - // we increase the actor, but now DO release the step size - // it falls back to the accuracy - stepSize_p.update(0.15, cstep::actor, true); - BOOST_CHECK_EQUAL(stepSize_p, 0.1); - - // now set two and update them - stepSize_p.update(0.05, cstep::user); - stepSize_p.update(0.03, cstep::accuracy); - BOOST_CHECK_EQUAL(stepSize_p, 0.03); - - // now we release the accuracy - to the highest available value - stepSize_p.release(cstep::accuracy); - BOOST_CHECK_EQUAL(stepSize_p.values[cstep::accuracy], 0.25); - BOOST_CHECK_EQUAL(stepSize_p, 0.05); - - // backward stepping test - cstep stepSize_n = -0.25; - - // All of the types should be 0.25 now - BOOST_CHECK_EQUAL(stepSize_n.values[cstep::accuracy], -0.25); - BOOST_CHECK_EQUAL(stepSize_n.values[cstep::actor], -0.25); - BOOST_CHECK_EQUAL(stepSize_n.values[cstep::aborter], -0.25); - BOOST_CHECK_EQUAL(stepSize_n.values[cstep::user], -0.25); - - // Check the cast operation to double - BOOST_CHECK_EQUAL(stepSize_n, -0.25); - - // now we update the accuracy - stepSize_n.update(-0.1, cstep::accuracy); - BOOST_CHECK_EQUAL(stepSize_n, -0.1); - - // now we update the actor to smaller - stepSize_n.update(-0.05, cstep::actor); - BOOST_CHECK_EQUAL(stepSize_n, -0.05); - // we increase the actor and accuracy is smaller again, without reset - stepSize_n.update(-0.15, cstep::actor, false); - BOOST_CHECK_EQUAL(stepSize_n, -0.05); - // we increase the actor and accuracy is smaller again, with reset - stepSize_n.update(-0.15, cstep::actor, true); - BOOST_CHECK_EQUAL(stepSize_n, -0.1); - - // now set two and update them - stepSize_n.update(-0.05, cstep::user); - stepSize_n.update(-0.03, cstep::accuracy); - BOOST_CHECK_EQUAL(stepSize_n, -0.03); - - // now we release the accuracy - to the highest available value - stepSize_n.release(cstep::accuracy); - BOOST_CHECK_EQUAL(stepSize_n.values[cstep::accuracy], -0.25); - BOOST_CHECK_EQUAL(stepSize_n, -0.05); - } +// This tests the implementation of the AbortList +// and the standard aborters +BOOST_AUTO_TEST_CASE(ConstrainedStepTest) { + using cstep = detail::ConstrainedStep; + + // forward stepping test + cstep stepSize_p = 0.25; + + // All of the types should be 0.25 now + BOOST_CHECK_EQUAL(stepSize_p.values[cstep::accuracy], 0.25); + BOOST_CHECK_EQUAL(stepSize_p.values[cstep::actor], 0.25); + BOOST_CHECK_EQUAL(stepSize_p.values[cstep::aborter], 0.25); + BOOST_CHECK_EQUAL(stepSize_p.values[cstep::user], 0.25); + + // Check the cast operation to double + BOOST_CHECK_EQUAL(stepSize_p, 0.25); + + // now we update the accuracy + stepSize_p.update(0.1, cstep::accuracy); + BOOST_CHECK_EQUAL(stepSize_p, 0.1); + + // now we update the actor to smaller + stepSize_p.update(0.05, cstep::actor); + BOOST_CHECK_EQUAL(stepSize_p, 0.05); + // we increase the actor, but do not release the step size + stepSize_p.update(0.15, cstep::actor, false); + BOOST_CHECK_EQUAL(stepSize_p, 0.05); + // we increase the actor, but now DO release the step size + // it falls back to the accuracy + stepSize_p.update(0.15, cstep::actor, true); + BOOST_CHECK_EQUAL(stepSize_p, 0.1); + + // now set two and update them + stepSize_p.update(0.05, cstep::user); + stepSize_p.update(0.03, cstep::accuracy); + BOOST_CHECK_EQUAL(stepSize_p, 0.03); + + // now we release the accuracy - to the highest available value + stepSize_p.release(cstep::accuracy); + BOOST_CHECK_EQUAL(stepSize_p.values[cstep::accuracy], 0.25); + BOOST_CHECK_EQUAL(stepSize_p, 0.05); + + // backward stepping test + cstep stepSize_n = -0.25; + + // All of the types should be 0.25 now + BOOST_CHECK_EQUAL(stepSize_n.values[cstep::accuracy], -0.25); + BOOST_CHECK_EQUAL(stepSize_n.values[cstep::actor], -0.25); + BOOST_CHECK_EQUAL(stepSize_n.values[cstep::aborter], -0.25); + BOOST_CHECK_EQUAL(stepSize_n.values[cstep::user], -0.25); + + // Check the cast operation to double + BOOST_CHECK_EQUAL(stepSize_n, -0.25); + + // now we update the accuracy + stepSize_n.update(-0.1, cstep::accuracy); + BOOST_CHECK_EQUAL(stepSize_n, -0.1); + + // now we update the actor to smaller + stepSize_n.update(-0.05, cstep::actor); + BOOST_CHECK_EQUAL(stepSize_n, -0.05); + // we increase the actor and accuracy is smaller again, without reset + stepSize_n.update(-0.15, cstep::actor, false); + BOOST_CHECK_EQUAL(stepSize_n, -0.05); + // we increase the actor and accuracy is smaller again, with reset + stepSize_n.update(-0.15, cstep::actor, true); + BOOST_CHECK_EQUAL(stepSize_n, -0.1); + + // now set two and update them + stepSize_n.update(-0.05, cstep::user); + stepSize_n.update(-0.03, cstep::accuracy); + BOOST_CHECK_EQUAL(stepSize_n, -0.03); + + // now we release the accuracy - to the highest available value + stepSize_n.release(cstep::accuracy); + BOOST_CHECK_EQUAL(stepSize_n.values[cstep::accuracy], -0.25); + BOOST_CHECK_EQUAL(stepSize_n, -0.05); +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/Propagator/EigenStepperBenchmark.cpp b/Tests/Core/Propagator/EigenStepperBenchmark.cpp index a321361005812e375e82c6adc142e9249de87b41..de9f8b32fb8376c0e36286f5f7db595939030876 100644 --- a/Tests/Core/Propagator/EigenStepperBenchmark.cpp +++ b/Tests/Core/Propagator/EigenStepperBenchmark.cpp @@ -20,18 +20,16 @@ namespace po = boost::program_options; using namespace Acts; -int -main(int argc, char* argv[]) -{ - unsigned int toys = 1; - double pT = 1; - double Bz = 1; - double maxPath = 1; - unsigned int lvl = Acts::Logging::INFO; - bool withCov = true; +int main(int argc, char* argv[]) { + unsigned int toys = 1; + double pT = 1; + double Bz = 1; + double maxPath = 1; + unsigned int lvl = Acts::Logging::INFO; + bool withCov = true; // Create a test context - GeometryContext tgContext = GeometryContext(); + GeometryContext tgContext = GeometryContext(); MagneticFieldContext mfContext = MagneticFieldContext(); try { @@ -64,22 +62,21 @@ main(int argc, char* argv[]) // print information about profiling setup ACTS_INFO("propagating " << toys << " tracks with pT = " << pT << "GeV in a " - << Bz - << "T B-field"); + << Bz << "T B-field"); - using BField_type = ConstantBField; - using Stepper_type = EigenStepper<BField_type>; + using BField_type = ConstantBField; + using Stepper_type = EigenStepper<BField_type>; using Propagator_type = Propagator<Stepper_type>; - BField_type bField(0, 0, Bz * units::_T); - Stepper_type atlas_stepper(std::move(bField)); + BField_type bField(0, 0, Bz * units::_T); + Stepper_type atlas_stepper(std::move(bField)); Propagator_type propagator(std::move(atlas_stepper)); PropagatorOptions<> options(tgContext, mfContext); options.pathLimit = maxPath * units::_m; - Vector3D pos(0, 0, 0); - Vector3D mom(pT * units::_GeV, 0, 0); + Vector3D pos(0, 0, 0); + Vector3D mom(pT * units::_GeV, 0, 0); ActsSymMatrixD<5> cov; cov << 10 * units::_mm, 0, 0, 0, 0, 0, 10 * units::_mm, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1. / (10 * units::_GeV); @@ -94,12 +91,9 @@ main(int argc, char* argv[]) for (unsigned int i = 0; i < toys; ++i) { auto r = propagator.propagate(pars, options).value(); ACTS_DEBUG("reached position (" << r.endParameters->position().x() << ", " - << r.endParameters->position().y() - << ", " + << r.endParameters->position().y() << ", " << r.endParameters->position().z() - << ") in " - << r.steps - << " steps"); + << ") in " << r.steps << " steps"); totalPathLength += r.pathLength; } diff --git a/Tests/Core/Propagator/ExtrapolatorTests.cpp b/Tests/Core/Propagator/ExtrapolatorTests.cpp index a1bce9fd13ce591298a002aba6bcfa0919b32777..d4b506971ff2586b7df640f9f09d4da2687b6ff8 100644 --- a/Tests/Core/Propagator/ExtrapolatorTests.cpp +++ b/Tests/Core/Propagator/ExtrapolatorTests.cpp @@ -33,322 +33,291 @@ #include "Acts/MagneticField/MagneticFieldContext.hpp" namespace bdata = boost::unit_test::data; -namespace tt = boost::test_tools; +namespace tt = boost::test_tools; namespace Acts { namespace Test { - // Create a test context - GeometryContext tgContext = GeometryContext(); - MagneticFieldContext mfContext = MagneticFieldContext(); +// Create a test context +GeometryContext tgContext = GeometryContext(); +MagneticFieldContext mfContext = MagneticFieldContext(); - // Global definitions - // The path limit abort - using path_limit = detail::PathLimitReached; +// Global definitions +// The path limit abort +using path_limit = detail::PathLimitReached; - std::vector<std::unique_ptr<const Surface>> stepState; +std::vector<std::unique_ptr<const Surface>> stepState; - CylindricalTrackingGeometry cGeometry(tgContext); - auto tGeometry = cGeometry(); +CylindricalTrackingGeometry cGeometry(tgContext); +auto tGeometry = cGeometry(); - // Get the navigator and provide the TrackingGeometry - Navigator navigator(tGeometry); +// Get the navigator and provide the TrackingGeometry +Navigator navigator(tGeometry); - using BFieldType = ConstantBField; - using EigenStepperType = EigenStepper<BFieldType>; - using EigenPropagatorType = Propagator<EigenStepperType, Navigator>; +using BFieldType = ConstantBField; +using EigenStepperType = EigenStepper<BFieldType>; +using EigenPropagatorType = Propagator<EigenStepperType, Navigator>; - const double Bz = 2. * units::_T; - BFieldType bField(0, 0, Bz); - EigenStepperType estepper(bField); - EigenPropagatorType epropagator(std::move(estepper), std::move(navigator)); +const double Bz = 2. * units::_T; +BFieldType bField(0, 0, Bz); +EigenStepperType estepper(bField); +EigenPropagatorType epropagator(std::move(estepper), std::move(navigator)); - const int ntests = 100; - bool debugMode = false; +const int ntests = 100; +bool debugMode = false; - // A plane selector for the SurfaceCollector - struct PlaneSelector - { - /// Call operator - /// @param sf The input surface to be checked - bool - operator()(const Surface& sf) const - { - return (sf.type() == Surface::Plane); - } - }; - - // This test case checks that no segmentation fault appears - // - simple extrapolation test - BOOST_DATA_TEST_CASE( - test_extrapolation_, - bdata::random((bdata::seed = 0, - bdata::distribution - = std::uniform_real_distribution<>(0.4 * units::_GeV, - 10. * units::_GeV))) - ^ bdata::random((bdata::seed = 1, - bdata::distribution - = std::uniform_real_distribution<>(-M_PI, M_PI))) - ^ bdata::random((bdata::seed = 2, - bdata::distribution - = std::uniform_real_distribution<>(1.0, M_PI - 1.0))) - ^ bdata::random((bdata::seed = 3, - bdata::distribution - = std::uniform_int_distribution<>(0, 1))) - ^ bdata::xrange(ntests), - pT, - phi, - theta, - charge, - index) - { - - double dcharge = -1 + 2 * charge; - (void)index; - - // define start parameters - double x = 0; - double y = 0; - double z = 0; - double px = pT * cos(phi); - double py = pT * sin(phi); - double pz = pT / tan(theta); - double q = dcharge; - Vector3D pos(x, y, z); - Vector3D mom(px, py, pz); - /// a covariance matrix to transport - ActsSymMatrixD<5> cov; - // take some major correlations (off-diagonals) - cov << 10 * units::_mm, 0, 0.123, 0, 0.5, 0, 10 * units::_mm, 0, 0.162, 0, - 0.123, 0, 0.1, 0, 0, 0, 0.162, 0, 0.1, 0, 0.5, 0, 0, 0, - 1. / (10 * units::_GeV); - auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); - CurvilinearParameters start(std::move(covPtr), pos, mom, q); - - PropagatorOptions<> options(tgContext, mfContext); - options.maxStepSize = 10. * units::_cm; - options.pathLimit = 25 * units::_cm; - - BOOST_CHECK(epropagator.propagate(start, options).value().endParameters - != nullptr); +// A plane selector for the SurfaceCollector +struct PlaneSelector { + /// Call operator + /// @param sf The input surface to be checked + bool operator()(const Surface& sf) const { + return (sf.type() == Surface::Plane); } - - // This test case checks that no segmentation fault appears - // - this tests the collection of surfaces - BOOST_DATA_TEST_CASE( - test_surface_collection_, - bdata::random((bdata::seed = 10, - bdata::distribution - = std::uniform_real_distribution<>(0.4 * units::_GeV, - 10. * units::_GeV))) - ^ bdata::random((bdata::seed = 11, - bdata::distribution - = std::uniform_real_distribution<>(-M_PI, M_PI))) - ^ bdata::random((bdata::seed = 12, - bdata::distribution - = std::uniform_real_distribution<>(1.0, M_PI - 1.0))) - ^ bdata::random((bdata::seed = 13, - bdata::distribution - = std::uniform_int_distribution<>(0, 1))) - ^ bdata::xrange(ntests), - pT, - phi, - theta, - charge, - index) - { - - double dcharge = -1 + 2 * charge; - (void)index; - - // define start parameters - double x = 0; - double y = 0; - double z = 0; - double px = pT * cos(phi); - double py = pT * sin(phi); - double pz = pT / tan(theta); - double q = dcharge; - Vector3D pos(x, y, z); - Vector3D mom(px, py, pz); - /// a covariance matrix to transport - ActsSymMatrixD<5> cov; - // take some major correlations (off-diagonals) - cov << 10 * units::_mm, 0, 0.123, 0, 0.5, 0, 10 * units::_mm, 0, 0.162, 0, - 0.123, 0, 0.1, 0, 0, 0, 0.162, 0, 0.1, 0, 0.5, 0, 0, 0, - 1. / (10 * units::_GeV); - auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); - CurvilinearParameters start(std::move(covPtr), pos, mom, q); - - // A PlaneSelector for the SurfaceCollector - using PlaneCollector = SurfaceCollector<PlaneSelector>; - - PropagatorOptions<ActionList<PlaneCollector>> options(tgContext, mfContext); - - options.maxStepSize = 10. * units::_cm; - options.pathLimit = 25 * units::_cm; - options.debug = debugMode; - - const auto& result = epropagator.propagate(start, options).value(); - auto collector_result = result.get<PlaneCollector::result_type>(); - - // step through the surfaces and go step by step - PropagatorOptions<> optionsEmpty(tgContext, mfContext); - - optionsEmpty.maxStepSize = 25. * units::_cm; - optionsEmpty.debug = true; - // Try propagation from start to each surface - for (const auto& colsf : collector_result.collected) { - const auto& csurface = colsf.surface; - // Avoid going to the same surface - // @todo: decide on strategy and write unit test for this - if (csurface == &start.referenceSurface()) { - continue; - } - // Extrapolate & check - const auto& cresult - = epropagator.propagate(start, *csurface, optionsEmpty) - .value() - .endParameters; - BOOST_CHECK(cresult != nullptr); +}; + +// This test case checks that no segmentation fault appears +// - simple extrapolation test +BOOST_DATA_TEST_CASE( + test_extrapolation_, + bdata::random((bdata::seed = 0, + bdata::distribution = std::uniform_real_distribution<>( + 0.4 * units::_GeV, 10. * units::_GeV))) ^ + bdata::random((bdata::seed = 1, + bdata::distribution = + std::uniform_real_distribution<>(-M_PI, M_PI))) ^ + bdata::random((bdata::seed = 2, + bdata::distribution = + std::uniform_real_distribution<>(1.0, M_PI - 1.0))) ^ + bdata::random( + (bdata::seed = 3, + bdata::distribution = std::uniform_int_distribution<>(0, 1))) ^ + bdata::xrange(ntests), + pT, phi, theta, charge, index) { + double dcharge = -1 + 2 * charge; + (void)index; + + // define start parameters + double x = 0; + double y = 0; + double z = 0; + double px = pT * cos(phi); + double py = pT * sin(phi); + double pz = pT / tan(theta); + double q = dcharge; + Vector3D pos(x, y, z); + Vector3D mom(px, py, pz); + /// a covariance matrix to transport + ActsSymMatrixD<5> cov; + // take some major correlations (off-diagonals) + cov << 10 * units::_mm, 0, 0.123, 0, 0.5, 0, 10 * units::_mm, 0, 0.162, 0, + 0.123, 0, 0.1, 0, 0, 0, 0.162, 0, 0.1, 0, 0.5, 0, 0, 0, + 1. / (10 * units::_GeV); + auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); + CurvilinearParameters start(std::move(covPtr), pos, mom, q); + + PropagatorOptions<> options(tgContext, mfContext); + options.maxStepSize = 10. * units::_cm; + options.pathLimit = 25 * units::_cm; + + BOOST_CHECK(epropagator.propagate(start, options).value().endParameters != + nullptr); +} + +// This test case checks that no segmentation fault appears +// - this tests the collection of surfaces +BOOST_DATA_TEST_CASE( + test_surface_collection_, + bdata::random((bdata::seed = 10, + bdata::distribution = std::uniform_real_distribution<>( + 0.4 * units::_GeV, 10. * units::_GeV))) ^ + bdata::random((bdata::seed = 11, + bdata::distribution = + std::uniform_real_distribution<>(-M_PI, M_PI))) ^ + bdata::random((bdata::seed = 12, + bdata::distribution = + std::uniform_real_distribution<>(1.0, M_PI - 1.0))) ^ + bdata::random( + (bdata::seed = 13, + bdata::distribution = std::uniform_int_distribution<>(0, 1))) ^ + bdata::xrange(ntests), + pT, phi, theta, charge, index) { + double dcharge = -1 + 2 * charge; + (void)index; + + // define start parameters + double x = 0; + double y = 0; + double z = 0; + double px = pT * cos(phi); + double py = pT * sin(phi); + double pz = pT / tan(theta); + double q = dcharge; + Vector3D pos(x, y, z); + Vector3D mom(px, py, pz); + /// a covariance matrix to transport + ActsSymMatrixD<5> cov; + // take some major correlations (off-diagonals) + cov << 10 * units::_mm, 0, 0.123, 0, 0.5, 0, 10 * units::_mm, 0, 0.162, 0, + 0.123, 0, 0.1, 0, 0, 0, 0.162, 0, 0.1, 0, 0.5, 0, 0, 0, + 1. / (10 * units::_GeV); + auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); + CurvilinearParameters start(std::move(covPtr), pos, mom, q); + + // A PlaneSelector for the SurfaceCollector + using PlaneCollector = SurfaceCollector<PlaneSelector>; + + PropagatorOptions<ActionList<PlaneCollector>> options(tgContext, mfContext); + + options.maxStepSize = 10. * units::_cm; + options.pathLimit = 25 * units::_cm; + options.debug = debugMode; + + const auto& result = epropagator.propagate(start, options).value(); + auto collector_result = result.get<PlaneCollector::result_type>(); + + // step through the surfaces and go step by step + PropagatorOptions<> optionsEmpty(tgContext, mfContext); + + optionsEmpty.maxStepSize = 25. * units::_cm; + optionsEmpty.debug = true; + // Try propagation from start to each surface + for (const auto& colsf : collector_result.collected) { + const auto& csurface = colsf.surface; + // Avoid going to the same surface + // @todo: decide on strategy and write unit test for this + if (csurface == &start.referenceSurface()) { + continue; } + // Extrapolate & check + const auto& cresult = epropagator.propagate(start, *csurface, optionsEmpty) + .value() + .endParameters; + BOOST_CHECK(cresult != nullptr); } - - // This test case checks that no segmentation fault appears - // - this tests the collection of surfaces - BOOST_DATA_TEST_CASE( - test_material_interactor_, - bdata::random((bdata::seed = 20, - bdata::distribution - = std::uniform_real_distribution<>(0.4 * units::_GeV, - 10. * units::_GeV))) - ^ bdata::random((bdata::seed = 21, - bdata::distribution - = std::uniform_real_distribution<>(-M_PI, M_PI))) - ^ bdata::random((bdata::seed = 22, - bdata::distribution - = std::uniform_real_distribution<>(1.0, M_PI - 1.0))) - ^ bdata::random((bdata::seed = 23, - bdata::distribution - = std::uniform_int_distribution<>(0, 1))) - ^ bdata::xrange(ntests), - pT, - phi, - theta, - charge, - index) - { - - double dcharge = -1 + 2 * charge; - (void)index; - - // define start parameters - double x = 0; - double y = 0; - double z = 0; - double px = pT * cos(phi); - double py = pT * sin(phi); - double pz = pT / tan(theta); - double q = dcharge; - Vector3D pos(x, y, z); - Vector3D mom(px, py, pz); - /// a covariance matrix to transport - ActsSymMatrixD<5> cov; - // take some major correlations (off-diagonals) - cov << 10 * units::_mm, 0, 0.123, 0, 0.5, 0, 10 * units::_mm, 0, 0.162, 0, - 0.123, 0, 0.1, 0, 0, 0, 0.162, 0, 0.1, 0, 0.5, 0, 0, 0, - 1. / (10 * units::_GeV); - auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); - CurvilinearParameters start(std::move(covPtr), pos, mom, q); - - using DebugOutput = detail::DebugOutputActor; - - PropagatorOptions<ActionList<MaterialInteractor, DebugOutput>> options( - tgContext, mfContext); - options.debug = debugMode; - options.maxStepSize = 25. * units::_cm; - options.pathLimit = 25 * units::_cm; - - const auto& result = epropagator.propagate(start, options).value(); - if (result.endParameters) { - // test that you actually lost some energy - BOOST_CHECK_LT(result.endParameters->momentum().norm(), - start.momentum().norm()); - } - - if (debugMode) { - const auto& output = result.get<DebugOutput::result_type>(); - std::cout << ">>> Extrapolation output " << std::endl; - std::cout << output.debugString << std::endl; - } +} + +// This test case checks that no segmentation fault appears +// - this tests the collection of surfaces +BOOST_DATA_TEST_CASE( + test_material_interactor_, + bdata::random((bdata::seed = 20, + bdata::distribution = std::uniform_real_distribution<>( + 0.4 * units::_GeV, 10. * units::_GeV))) ^ + bdata::random((bdata::seed = 21, + bdata::distribution = + std::uniform_real_distribution<>(-M_PI, M_PI))) ^ + bdata::random((bdata::seed = 22, + bdata::distribution = + std::uniform_real_distribution<>(1.0, M_PI - 1.0))) ^ + bdata::random( + (bdata::seed = 23, + bdata::distribution = std::uniform_int_distribution<>(0, 1))) ^ + bdata::xrange(ntests), + pT, phi, theta, charge, index) { + double dcharge = -1 + 2 * charge; + (void)index; + + // define start parameters + double x = 0; + double y = 0; + double z = 0; + double px = pT * cos(phi); + double py = pT * sin(phi); + double pz = pT / tan(theta); + double q = dcharge; + Vector3D pos(x, y, z); + Vector3D mom(px, py, pz); + /// a covariance matrix to transport + ActsSymMatrixD<5> cov; + // take some major correlations (off-diagonals) + cov << 10 * units::_mm, 0, 0.123, 0, 0.5, 0, 10 * units::_mm, 0, 0.162, 0, + 0.123, 0, 0.1, 0, 0, 0, 0.162, 0, 0.1, 0, 0.5, 0, 0, 0, + 1. / (10 * units::_GeV); + auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); + CurvilinearParameters start(std::move(covPtr), pos, mom, q); + + using DebugOutput = detail::DebugOutputActor; + + PropagatorOptions<ActionList<MaterialInteractor, DebugOutput>> options( + tgContext, mfContext); + options.debug = debugMode; + options.maxStepSize = 25. * units::_cm; + options.pathLimit = 25 * units::_cm; + + const auto& result = epropagator.propagate(start, options).value(); + if (result.endParameters) { + // test that you actually lost some energy + BOOST_CHECK_LT(result.endParameters->momentum().norm(), + start.momentum().norm()); } - // This test case checks that no segmentation fault appears - // - this tests the loop protection - BOOST_DATA_TEST_CASE( - loop_protection_test, - bdata::random((bdata::seed = 20, - bdata::distribution - = std::uniform_real_distribution<>(0.1 * units::_GeV, - 0.5 * units::_GeV))) - ^ bdata::random((bdata::seed = 21, - bdata::distribution - = std::uniform_real_distribution<>(-M_PI, M_PI))) - ^ bdata::random((bdata::seed = 22, - bdata::distribution - = std::uniform_real_distribution<>(1.0, M_PI - 1.0))) - ^ bdata::random((bdata::seed = 23, - bdata::distribution - = std::uniform_int_distribution<>(0, 1))) - ^ bdata::xrange(ntests), - pT, - phi, - theta, - charge, - index) - { - double dcharge = -1 + 2 * charge; - (void)index; - - // define start parameters - double x = 0; - double y = 0; - double z = 0; - double px = pT * cos(phi); - double py = pT * sin(phi); - double pz = pT / tan(theta); - double q = dcharge; - Vector3D pos(x, y, z); - Vector3D mom(px, py, pz); - /// a covariance matrix to transport - ActsSymMatrixD<5> cov; - // take some major correlations (off-diagonals) - cov << 10 * units::_mm, 0, 0.123, 0, 0.5, 0, 10 * units::_mm, 0, 0.162, 0, - 0.123, 0, 0.1, 0, 0, 0, 0.162, 0, 0.1, 0, 0.5, 0, 0, 0, - 1. / (10 * units::_GeV); - auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); - CurvilinearParameters start(std::move(covPtr), pos, mom, q); - - // Action list and abort list - using DebugOutput = detail::DebugOutputActor; - - PropagatorOptions<ActionList<MaterialInteractor, DebugOutput>> options( - tgContext, mfContext); - options.maxStepSize = 25. * units::_cm; - options.pathLimit = 1500. * units::_mm; - - const auto& status = epropagator.propagate(start, options).value(); - // this test assumes state.options.loopFraction = 0.5 - // maximum momentum allowed - double pmax = units::SI2Nat<units::MOMENTUM>( - options.pathLimit * bField.getField(pos).norm() / M_PI); - if (mom.norm() < pmax) { - BOOST_CHECK_LT(status.pathLength, options.pathLimit); - } else { - CHECK_CLOSE_REL(status.pathLength, options.pathLimit, 1e-3); - } + if (debugMode) { + const auto& output = result.get<DebugOutput::result_type>(); + std::cout << ">>> Extrapolation output " << std::endl; + std::cout << output.debugString << std::endl; + } +} + +// This test case checks that no segmentation fault appears +// - this tests the loop protection +BOOST_DATA_TEST_CASE( + loop_protection_test, + bdata::random((bdata::seed = 20, + bdata::distribution = std::uniform_real_distribution<>( + 0.1 * units::_GeV, 0.5 * units::_GeV))) ^ + bdata::random((bdata::seed = 21, + bdata::distribution = + std::uniform_real_distribution<>(-M_PI, M_PI))) ^ + bdata::random((bdata::seed = 22, + bdata::distribution = + std::uniform_real_distribution<>(1.0, M_PI - 1.0))) ^ + bdata::random( + (bdata::seed = 23, + bdata::distribution = std::uniform_int_distribution<>(0, 1))) ^ + bdata::xrange(ntests), + pT, phi, theta, charge, index) { + double dcharge = -1 + 2 * charge; + (void)index; + + // define start parameters + double x = 0; + double y = 0; + double z = 0; + double px = pT * cos(phi); + double py = pT * sin(phi); + double pz = pT / tan(theta); + double q = dcharge; + Vector3D pos(x, y, z); + Vector3D mom(px, py, pz); + /// a covariance matrix to transport + ActsSymMatrixD<5> cov; + // take some major correlations (off-diagonals) + cov << 10 * units::_mm, 0, 0.123, 0, 0.5, 0, 10 * units::_mm, 0, 0.162, 0, + 0.123, 0, 0.1, 0, 0, 0, 0.162, 0, 0.1, 0, 0.5, 0, 0, 0, + 1. / (10 * units::_GeV); + auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); + CurvilinearParameters start(std::move(covPtr), pos, mom, q); + + // Action list and abort list + using DebugOutput = detail::DebugOutputActor; + + PropagatorOptions<ActionList<MaterialInteractor, DebugOutput>> options( + tgContext, mfContext); + options.maxStepSize = 25. * units::_cm; + options.pathLimit = 1500. * units::_mm; + + const auto& status = epropagator.propagate(start, options).value(); + // this test assumes state.options.loopFraction = 0.5 + // maximum momentum allowed + double pmax = units::SI2Nat<units::MOMENTUM>( + options.pathLimit * bField.getField(pos).norm() / M_PI); + if (mom.norm() < pmax) { + BOOST_CHECK_LT(status.pathLength, options.pathLimit); + } else { + CHECK_CLOSE_REL(status.pathLength, options.pathLimit, 1e-3); } +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/Propagator/IntersectionCorrectorTests.cpp b/Tests/Core/Propagator/IntersectionCorrectorTests.cpp index 8f6570ead60a66c4bb8163b3603a39053af9b15f..4d8766eaf58f23a6721ace45882a5d79f2e05c35 100644 --- a/Tests/Core/Propagator/IntersectionCorrectorTests.cpp +++ b/Tests/Core/Propagator/IntersectionCorrectorTests.cpp @@ -25,67 +25,65 @@ #include "Acts/Utilities/Helpers.hpp" namespace bdata = boost::unit_test::data; -namespace tt = boost::test_tools; +namespace tt = boost::test_tools; namespace Acts { namespace Test { - // This tests the implementation of the Step corrector - BOOST_AUTO_TEST_CASE(RelativePathCorrectorTests) - { - - // Create a test context - GeometryContext tgContext = GeometryContext(); - - // construct the surface - Vector3D pcenter(-4., 4., 0.); - Vector3D pnormal = Vector3D(-1., 4., 0.).normalized(); - auto plane = Surface::makeShared<PlaneSurface>(pcenter, pnormal); - - // The current position - origin - Vector3D position(0., 0., 0.); - Vector3D originalDirection = Vector3D(4., 7., 0.).normalized(); - Vector3D direction = originalDirection; - - // The two tracks - // (n) - Vector3D p0n(-7., 7., 0.); - Vector3D d0n = Vector3D(8., 4., 0.).normalized(); - double pathn = 10.5; - // (p) - Vector3D p0p(-1.5, -12., 0.); - Vector3D d0p = Vector3D(-2., 9., 0.).normalized(); - double pathp = 13.; - - auto intersect - = [&tgContext, &position, &direction, &plane]() -> Intersection { - auto pi = plane->intersectionEstimate( - tgContext, position, direction, forward, false); - std::cout << "Interseciton it at " << toString(pi.position) << std::endl; - return pi; - }; - - // original intersection - auto ointersect = intersect(); - - // Step corrector for the (n) track - detail::RelativePathCorrector corrFncn(p0n, d0n, pathn); - // -> correct & intersect - corrFncn(position, direction, ointersect.pathLength); - auto nintersect = intersect(); - - // re-assign the original direction - direction = originalDirection; - - // Step corrector for the (p) track - detail::RelativePathCorrector corrFncp(p0p, d0p, pathp); - // -> correct & intersect - corrFncp(position, direction, ointersect.pathLength); - auto pintersect = intersect(); - - BOOST_CHECK_LT(nintersect.pathLength, pintersect.pathLength); - } +// This tests the implementation of the Step corrector +BOOST_AUTO_TEST_CASE(RelativePathCorrectorTests) { + // Create a test context + GeometryContext tgContext = GeometryContext(); + + // construct the surface + Vector3D pcenter(-4., 4., 0.); + Vector3D pnormal = Vector3D(-1., 4., 0.).normalized(); + auto plane = Surface::makeShared<PlaneSurface>(pcenter, pnormal); + + // The current position - origin + Vector3D position(0., 0., 0.); + Vector3D originalDirection = Vector3D(4., 7., 0.).normalized(); + Vector3D direction = originalDirection; + + // The two tracks + // (n) + Vector3D p0n(-7., 7., 0.); + Vector3D d0n = Vector3D(8., 4., 0.).normalized(); + double pathn = 10.5; + // (p) + Vector3D p0p(-1.5, -12., 0.); + Vector3D d0p = Vector3D(-2., 9., 0.).normalized(); + double pathp = 13.; + + auto intersect = [&tgContext, &position, &direction, + &plane]() -> Intersection { + auto pi = plane->intersectionEstimate(tgContext, position, direction, + forward, false); + std::cout << "Interseciton it at " << toString(pi.position) << std::endl; + return pi; + }; + + // original intersection + auto ointersect = intersect(); + + // Step corrector for the (n) track + detail::RelativePathCorrector corrFncn(p0n, d0n, pathn); + // -> correct & intersect + corrFncn(position, direction, ointersect.pathLength); + auto nintersect = intersect(); + + // re-assign the original direction + direction = originalDirection; + + // Step corrector for the (p) track + detail::RelativePathCorrector corrFncp(p0p, d0p, pathp); + // -> correct & intersect + corrFncp(position, direction, ointersect.pathLength); + auto pintersect = intersect(); + + BOOST_CHECK_LT(nintersect.pathLength, pintersect.pathLength); +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/Propagator/JacobianTests.cpp b/Tests/Core/Propagator/JacobianTests.cpp index c099e3dd38a80c9974dba4985f1438d07b750c42..a7654c2871aa4306a32c7507c4d9f38955490ce8 100644 --- a/Tests/Core/Propagator/JacobianTests.cpp +++ b/Tests/Core/Propagator/JacobianTests.cpp @@ -28,260 +28,243 @@ #include "Acts/MagneticField/MagneticFieldContext.hpp" namespace bdata = boost::unit_test::data; -namespace tt = boost::test_tools; +namespace tt = boost::test_tools; namespace Acts { namespace Test { - using BFieldType = ConstantBField; - using EigenStepperType = EigenStepper<BFieldType>; - using AtlasStepperType = AtlasStepper<BFieldType>; - - // Create a test context - GeometryContext tgContext = GeometryContext(); - MagneticFieldContext mfContext = MagneticFieldContext(); - - /// Helper method to create a transform for a plane - /// to mimic detector situations, the plane is roughly - /// perpendicular to the track - /// - /// @param nnomal The nominal normal direction - /// @param angleT Rotation around the norminal normal - /// @param angleU Roation around the original U axis - std::shared_ptr<Transform3D> - createCylindricTransform(const Vector3D& nposition, - double angleX, - double angleY) - { - Transform3D ctransform; - ctransform.setIdentity(); - ctransform.pretranslate(nposition); - ctransform.prerotate(AngleAxis3D(angleX, Vector3D::UnitX())); - ctransform.prerotate(AngleAxis3D(angleY, Vector3D::UnitY())); - return std::make_shared<Transform3D>(ctransform); - } - - /// Helper method to create a transform for a plane - /// to mimic detector situations, the plane is roughly - /// perpendicular to the track - /// - /// @param nnomal The nominal normal direction - /// @param angleT Rotation around the norminal normal - /// @param angleU Roation around the original U axis - std::shared_ptr<Transform3D> - createPlanarTransform(const Vector3D& nposition, - const Vector3D& nnormal, - double angleT, - double angleU) - { - // the rotation of the destination surface - Vector3D T = nnormal.normalized(); - Vector3D U = std::abs(T.dot(Vector3D::UnitZ())) < 0.99 - ? Vector3D::UnitZ().cross(T).normalized() - : Vector3D::UnitX().cross(T).normalized(); - Vector3D V = T.cross(U); - // that's the plane curvilinear Rotation - RotationMatrix3D curvilinearRotation; - curvilinearRotation.col(0) = U; - curvilinearRotation.col(1) = V; - curvilinearRotation.col(2) = T; - // curvilinear surfaces are boundless - Transform3D ctransform{curvilinearRotation}; - ctransform.pretranslate(nposition); - ctransform.prerotate(AngleAxis3D(angleT, T)); - ctransform.prerotate(AngleAxis3D(angleU, U)); - // - return std::make_shared<Transform3D>(ctransform); - } - - /// Helper method : convert into Acts matrix - /// It takes the double array from AtlasStepper - /// and transforms it into an ActsMatrixD - /// - /// @param P is the pointer to the array - /// - /// Translation is (for lookup) - /// /dL0 /dL1 /dPhi /dThe /dCM - /// X ->P[0] dX / P[ 7] P[14] P[21] P[28] P[35] - /// Y ->P[1] dY / P[ 8] P[15] P[22] P[29] P[36] - /// Z ->P[2] dZ / P[ 9] P[16] P[23] P[30] P[37] - /// Ax ->P[3] dAx/ P[10] P[17] P[24] P[31] P[38] - /// Ay ->P[4] dAy/ P[11] P[18] P[25] P[32] P[39] - /// Az ->P[5] dAz/ P[12] P[19] P[26] P[33] P[40] - /// CM ->P[6] dCM/ P[13] P[20] P[27] P[34] P[41] - - ActsMatrixD<7, 5> - convertToMatrix(const double* P) - { - // initialize to zero - ActsMatrixD<7, 5> jMatrix = ActsMatrixD<7, 5>::Zero(); - for (size_t j = 0; j < 5; ++j) { - for (size_t i = 0; i < 7; ++i) { - size_t ijc = 7 + j * 7 + i; - jMatrix(i, j) = P[ijc]; - } +using BFieldType = ConstantBField; +using EigenStepperType = EigenStepper<BFieldType>; +using AtlasStepperType = AtlasStepper<BFieldType>; + +// Create a test context +GeometryContext tgContext = GeometryContext(); +MagneticFieldContext mfContext = MagneticFieldContext(); + +/// Helper method to create a transform for a plane +/// to mimic detector situations, the plane is roughly +/// perpendicular to the track +/// +/// @param nnomal The nominal normal direction +/// @param angleT Rotation around the norminal normal +/// @param angleU Roation around the original U axis +std::shared_ptr<Transform3D> createCylindricTransform(const Vector3D& nposition, + double angleX, + double angleY) { + Transform3D ctransform; + ctransform.setIdentity(); + ctransform.pretranslate(nposition); + ctransform.prerotate(AngleAxis3D(angleX, Vector3D::UnitX())); + ctransform.prerotate(AngleAxis3D(angleY, Vector3D::UnitY())); + return std::make_shared<Transform3D>(ctransform); +} + +/// Helper method to create a transform for a plane +/// to mimic detector situations, the plane is roughly +/// perpendicular to the track +/// +/// @param nnomal The nominal normal direction +/// @param angleT Rotation around the norminal normal +/// @param angleU Roation around the original U axis +std::shared_ptr<Transform3D> createPlanarTransform(const Vector3D& nposition, + const Vector3D& nnormal, + double angleT, + double angleU) { + // the rotation of the destination surface + Vector3D T = nnormal.normalized(); + Vector3D U = std::abs(T.dot(Vector3D::UnitZ())) < 0.99 + ? Vector3D::UnitZ().cross(T).normalized() + : Vector3D::UnitX().cross(T).normalized(); + Vector3D V = T.cross(U); + // that's the plane curvilinear Rotation + RotationMatrix3D curvilinearRotation; + curvilinearRotation.col(0) = U; + curvilinearRotation.col(1) = V; + curvilinearRotation.col(2) = T; + // curvilinear surfaces are boundless + Transform3D ctransform{curvilinearRotation}; + ctransform.pretranslate(nposition); + ctransform.prerotate(AngleAxis3D(angleT, T)); + ctransform.prerotate(AngleAxis3D(angleU, U)); + // + return std::make_shared<Transform3D>(ctransform); +} + +/// Helper method : convert into Acts matrix +/// It takes the double array from AtlasStepper +/// and transforms it into an ActsMatrixD +/// +/// @param P is the pointer to the array +/// +/// Translation is (for lookup) +/// /dL0 /dL1 /dPhi /dThe /dCM +/// X ->P[0] dX / P[ 7] P[14] P[21] P[28] P[35] +/// Y ->P[1] dY / P[ 8] P[15] P[22] P[29] P[36] +/// Z ->P[2] dZ / P[ 9] P[16] P[23] P[30] P[37] +/// Ax ->P[3] dAx/ P[10] P[17] P[24] P[31] P[38] +/// Ay ->P[4] dAy/ P[11] P[18] P[25] P[32] P[39] +/// Az ->P[5] dAz/ P[12] P[19] P[26] P[33] P[40] +/// CM ->P[6] dCM/ P[13] P[20] P[27] P[34] P[41] + +ActsMatrixD<7, 5> convertToMatrix(const double* P) { + // initialize to zero + ActsMatrixD<7, 5> jMatrix = ActsMatrixD<7, 5>::Zero(); + for (size_t j = 0; j < 5; ++j) { + for (size_t i = 0; i < 7; ++i) { + size_t ijc = 7 + j * 7 + i; + jMatrix(i, j) = P[ijc]; } - return jMatrix; - } - - /// Helper method : tests the jacobian to Global - /// for a templated Parameters object - /// - /// @tparam Parameters the parameter type - /// @param pars the parameter object - template <typename Parameters> - void - testJacobianToGlobal(const Parameters& pars) - { - // Jacobian creation for Propagator/Steppers - // a) ATLAS stepper - AtlasStepperType::State astepState(tgContext, mfContext, pars); - // b) Eigen stepper - EigenStepperType::State estepState(tgContext, mfContext, pars); - - // create the matrices - auto asMatrix = convertToMatrix(astepState.pVector); - - // cross comparison checks - CHECK_CLOSE_OR_SMALL(asMatrix, estepState.jacToGlobal, 1e-6, 1e-9); - } - - /// This tests the jacobian of local curvilinear -> global - BOOST_AUTO_TEST_CASE(JacobianCurvilinearToGlobalTest) - { - ActsSymMatrixD<NGlobalPars> cov; - cov << 10 * units::_mm, 0, 0, 0, 0, 0, 10 * units::_mm, 0, 0, 0, 0, 0, 0.1, - 0, 0, 0, 0, 0, 0.1, 0, 0, 0, 0, 0, 1. / (10 * units::_GeV); - auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); - - // Let's create a surface somewhere in space - Vector3D pos(341., 412., 93.); - Vector3D mom(1.2, 8.3, 0.45); - const double q = 1; - - // Create curvilinear parameters - CurvilinearParameters curvilinear(std::move(covPtr), pos, mom, q); - - // run the test - testJacobianToGlobal(curvilinear); } + return jMatrix; +} + +/// Helper method : tests the jacobian to Global +/// for a templated Parameters object +/// +/// @tparam Parameters the parameter type +/// @param pars the parameter object +template <typename Parameters> +void testJacobianToGlobal(const Parameters& pars) { + // Jacobian creation for Propagator/Steppers + // a) ATLAS stepper + AtlasStepperType::State astepState(tgContext, mfContext, pars); + // b) Eigen stepper + EigenStepperType::State estepState(tgContext, mfContext, pars); + + // create the matrices + auto asMatrix = convertToMatrix(astepState.pVector); + + // cross comparison checks + CHECK_CLOSE_OR_SMALL(asMatrix, estepState.jacToGlobal, 1e-6, 1e-9); +} + +/// This tests the jacobian of local curvilinear -> global +BOOST_AUTO_TEST_CASE(JacobianCurvilinearToGlobalTest) { + ActsSymMatrixD<NGlobalPars> cov; + cov << 10 * units::_mm, 0, 0, 0, 0, 0, 10 * units::_mm, 0, 0, 0, 0, 0, 0.1, 0, + 0, 0, 0, 0, 0.1, 0, 0, 0, 0, 0, 1. / (10 * units::_GeV); + auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); + + // Let's create a surface somewhere in space + Vector3D pos(341., 412., 93.); + Vector3D mom(1.2, 8.3, 0.45); + const double q = 1; + + // Create curvilinear parameters + CurvilinearParameters curvilinear(std::move(covPtr), pos, mom, q); + + // run the test + testJacobianToGlobal(curvilinear); +} + +/// This tests the jacobian of local cylinder -> global +BOOST_AUTO_TEST_CASE(JacobianCylinderToGlobalTest) { + // the cylinder transform and surface + auto cTransform = createCylindricTransform({10., -5., 0.}, 0.004, 0.03); + auto cSurface = Surface::makeShared<CylinderSurface>(cTransform, 200., 1000.); + + ActsSymMatrixD<NGlobalPars> cov; + cov << 10 * units::_mm, 0, 0, 0, 0, 0, 10 * units::_mm, 0, 0, 0, 0, 0, 0.1, 0, + 0, 0, 0, 0, 0.1, 0, 0, 0, 0, 0, 1. / (10 * units::_GeV); + auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); + + ActsVectorD<NGlobalPars> pars; + pars << 182.34, -82., 0.134, 0.85, 1. / (100 * units::_GeV); + + BoundParameters atCylinder(tgContext, std::move(covPtr), std::move(pars), + cSurface); + + // run the test + testJacobianToGlobal(atCylinder); +} + +/// This tests the jacobian of local disc -> global +BOOST_AUTO_TEST_CASE(JacobianDiscToGlobalTest) { + // the disc transform and surface + auto dTransform = createPlanarTransform( + {10., -5., 0.}, Vector3D(0.23, 0.07, 1.).normalized(), 0.004, 0.03); + auto dSurface = Surface::makeShared<DiscSurface>(dTransform, 200., 1000.); + + ActsSymMatrixD<NGlobalPars> cov; + cov << 10 * units::_mm, 0, 0, 0, 0, 0, 10 * units::_mm, 0, 0, 0, 0, 0, 0.1, 0, + 0, 0, 0, 0, 0.1, 0, 0, 0, 0, 0, 1. / (10 * units::_GeV); + auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); + + ActsVectorD<NGlobalPars> pars; + pars << 192.34, 1.823, 0.734, 0.235, 1. / (100 * units::_GeV); + + BoundParameters atDisc(tgContext, std::move(covPtr), std::move(pars), + dSurface); + + // run the test + testJacobianToGlobal(atDisc); +} + +/// This tests the jacobian of local plane -> global +BOOST_AUTO_TEST_CASE(JacobianPlaneToGlobalTest) { + // Let's create a surface somewhere in space + Vector3D sPosition(3421., 112., 893.); + Vector3D sNormal = Vector3D(1.2, -0.3, 0.05).normalized(); + + // Create a surface & parameters with covariance on the surface + auto pSurface = Surface::makeShared<PlaneSurface>(sPosition, sNormal); + + ActsSymMatrixD<NGlobalPars> cov; + cov << 10 * units::_mm, 0, 0, 0, 0, 0, 10 * units::_mm, 0, 0, 0, 0, 0, 0.1, 0, + 0, 0, 0, 0, 0.1, 0, 0, 0, 0, 0, 1. / (10 * units::_GeV); + auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); + + ActsVectorD<NGlobalPars> pars; + pars << 12.34, -8722., 2.134, 0.85, 1. / (100 * units::_GeV); + + BoundParameters atPlane(tgContext, std::move(covPtr), std::move(pars), + pSurface); + + // run the test + testJacobianToGlobal(atPlane); +} + +/// This tests the jacobian of local perigee -> global +BOOST_AUTO_TEST_CASE(JacobianPerigeeToGlobalTest) { + // Create a surface & parameters with covariance on the surface + auto pSurface = Surface::makeShared<PerigeeSurface>(Vector3D({0., 0., 0.})); + + ActsSymMatrixD<NGlobalPars> cov; + cov << 10 * units::_mm, 0, 0, 0, 0, 0, 10 * units::_mm, 0, 0, 0, 0, 0, 0.1, 0, + 0, 0, 0, 0, 0.1, 0, 0, 0, 0, 0, 1. / (10 * units::_GeV); + auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); + + ActsVectorD<NGlobalPars> pars; + pars << -3.34, -822., -0.734, 0.85, 1. / (100 * units::_GeV); + + BoundParameters perigee(tgContext, std::move(covPtr), std::move(pars), + pSurface); + + // run the test + testJacobianToGlobal(perigee); +} + +/// This tests the jacobian of local straw -> global +BOOST_AUTO_TEST_CASE(JacobianStrawToGlobalTest) { + // Create a surface & parameters with covariance on the surface + auto sTransform = createCylindricTransform({1019., -52., 382.}, 0.4, -0.3); + auto sSurface = Surface::makeShared<StrawSurface>(sTransform, 10., 1000.); - /// This tests the jacobian of local cylinder -> global - BOOST_AUTO_TEST_CASE(JacobianCylinderToGlobalTest) - { - // the cylinder transform and surface - auto cTransform = createCylindricTransform({10., -5., 0.}, 0.004, 0.03); - auto cSurface - = Surface::makeShared<CylinderSurface>(cTransform, 200., 1000.); - - ActsSymMatrixD<NGlobalPars> cov; - cov << 10 * units::_mm, 0, 0, 0, 0, 0, 10 * units::_mm, 0, 0, 0, 0, 0, 0.1, - 0, 0, 0, 0, 0, 0.1, 0, 0, 0, 0, 0, 1. / (10 * units::_GeV); - auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); - - ActsVectorD<NGlobalPars> pars; - pars << 182.34, -82., 0.134, 0.85, 1. / (100 * units::_GeV); - - BoundParameters atCylinder( - tgContext, std::move(covPtr), std::move(pars), cSurface); - - // run the test - testJacobianToGlobal(atCylinder); - } - - /// This tests the jacobian of local disc -> global - BOOST_AUTO_TEST_CASE(JacobianDiscToGlobalTest) - { - - // the disc transform and surface - auto dTransform = createPlanarTransform( - {10., -5., 0.}, Vector3D(0.23, 0.07, 1.).normalized(), 0.004, 0.03); - auto dSurface = Surface::makeShared<DiscSurface>(dTransform, 200., 1000.); - - ActsSymMatrixD<NGlobalPars> cov; - cov << 10 * units::_mm, 0, 0, 0, 0, 0, 10 * units::_mm, 0, 0, 0, 0, 0, 0.1, - 0, 0, 0, 0, 0, 0.1, 0, 0, 0, 0, 0, 1. / (10 * units::_GeV); - auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); - - ActsVectorD<NGlobalPars> pars; - pars << 192.34, 1.823, 0.734, 0.235, 1. / (100 * units::_GeV); - - BoundParameters atDisc( - tgContext, std::move(covPtr), std::move(pars), dSurface); - - // run the test - testJacobianToGlobal(atDisc); - } - - /// This tests the jacobian of local plane -> global - BOOST_AUTO_TEST_CASE(JacobianPlaneToGlobalTest) - { - // Let's create a surface somewhere in space - Vector3D sPosition(3421., 112., 893.); - Vector3D sNormal = Vector3D(1.2, -0.3, 0.05).normalized(); - - // Create a surface & parameters with covariance on the surface - auto pSurface = Surface::makeShared<PlaneSurface>(sPosition, sNormal); - - ActsSymMatrixD<NGlobalPars> cov; - cov << 10 * units::_mm, 0, 0, 0, 0, 0, 10 * units::_mm, 0, 0, 0, 0, 0, 0.1, - 0, 0, 0, 0, 0, 0.1, 0, 0, 0, 0, 0, 1. / (10 * units::_GeV); - auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); - - ActsVectorD<NGlobalPars> pars; - pars << 12.34, -8722., 2.134, 0.85, 1. / (100 * units::_GeV); - - BoundParameters atPlane( - tgContext, std::move(covPtr), std::move(pars), pSurface); - - // run the test - testJacobianToGlobal(atPlane); - } - - /// This tests the jacobian of local perigee -> global - BOOST_AUTO_TEST_CASE(JacobianPerigeeToGlobalTest) - { - - // Create a surface & parameters with covariance on the surface - auto pSurface = Surface::makeShared<PerigeeSurface>(Vector3D({0., 0., 0.})); - - ActsSymMatrixD<NGlobalPars> cov; - cov << 10 * units::_mm, 0, 0, 0, 0, 0, 10 * units::_mm, 0, 0, 0, 0, 0, 0.1, - 0, 0, 0, 0, 0, 0.1, 0, 0, 0, 0, 0, 1. / (10 * units::_GeV); - auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); - - ActsVectorD<NGlobalPars> pars; - pars << -3.34, -822., -0.734, 0.85, 1. / (100 * units::_GeV); - - BoundParameters perigee( - tgContext, std::move(covPtr), std::move(pars), pSurface); - - // run the test - testJacobianToGlobal(perigee); - } - - /// This tests the jacobian of local straw -> global - BOOST_AUTO_TEST_CASE(JacobianStrawToGlobalTest) - { - // Create a surface & parameters with covariance on the surface - auto sTransform = createCylindricTransform({1019., -52., 382.}, 0.4, -0.3); - auto sSurface = Surface::makeShared<StrawSurface>(sTransform, 10., 1000.); - - ActsSymMatrixD<NGlobalPars> cov; - cov << 10 * units::_mm, 0, 0, 0, 0, 0, 10 * units::_mm, 0, 0, 0, 0, 0, 0.1, - 0, 0, 0, 0, 0, 0.1, 0, 0, 0, 0, 0, 1. / (10 * units::_GeV); - auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); - - ActsVectorD<NGlobalPars> pars; - pars << -8.34, 812., 0.734, 0.25, 1. / (100 * units::_GeV); - - BoundParameters atStraw( - tgContext, std::move(covPtr), std::move(pars), sSurface); - - // run the test - testJacobianToGlobal(atStraw); - } + ActsSymMatrixD<NGlobalPars> cov; + cov << 10 * units::_mm, 0, 0, 0, 0, 0, 10 * units::_mm, 0, 0, 0, 0, 0, 0.1, 0, + 0, 0, 0, 0, 0.1, 0, 0, 0, 0, 0, 1. / (10 * units::_GeV); + auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); + + ActsVectorD<NGlobalPars> pars; + pars << -8.34, 812., 0.734, 0.25, 1. / (100 * units::_GeV); + + BoundParameters atStraw(tgContext, std::move(covPtr), std::move(pars), + sSurface); + + // run the test + testJacobianToGlobal(atStraw); +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/Propagator/KalmanExtrapolatorTests.cpp b/Tests/Core/Propagator/KalmanExtrapolatorTests.cpp index 0ebe809f571a1a852359bd0ab5ae412380d34544..a331c144642cbf1db715999c79d4891cb4f2f81e 100644 --- a/Tests/Core/Propagator/KalmanExtrapolatorTests.cpp +++ b/Tests/Core/Propagator/KalmanExtrapolatorTests.cpp @@ -33,163 +33,153 @@ namespace Acts { namespace Test { - using Jacobian = ActsMatrixD<5, 5>; +using Jacobian = ActsMatrixD<5, 5>; + +// Create a test context +GeometryContext tgContext = GeometryContext(); +MagneticFieldContext mfContext = MagneticFieldContext(); +/// +/// @brief the bound state propagation +/// +struct StepWiseActor { + /// The result is the piece-wise jacobian + struct this_result { + std::vector<Jacobian> jacobians = {}; + std::vector<double> paths = {}; + + Jacobian fullJacobian = Jacobian::Identity(); + double fullPath = 0.; + + bool finalized = false; + }; + /// Broadcast the result type + using result_type = this_result; - // Create a test context - GeometryContext tgContext = GeometryContext(); - MagneticFieldContext mfContext = MagneticFieldContext(); + /// @brief Kalman sequence operation /// - /// @brief the bound state propagation + /// @tparam propagator_state_t is the type of Propagagor state + /// @tparam stepper_t Type of the stepper used for the propagation /// - struct StepWiseActor - { - - /// The result is the piece-wise jacobian - struct this_result - { - - std::vector<Jacobian> jacobians = {}; - std::vector<double> paths = {}; - - Jacobian fullJacobian = Jacobian::Identity(); - double fullPath = 0.; - - bool finalized = false; - }; - /// Broadcast the result type - using result_type = this_result; - - /// @brief Kalman sequence operation - /// - /// @tparam propagator_state_t is the type of Propagagor state - /// @tparam stepper_t Type of the stepper used for the propagation - /// - /// @param state is the mutable propagator state object - /// @param stepper The stepper in use - /// @param result is the mutable result state object - template <typename propagator_state_t, typename stepper_t> - void - operator()(propagator_state_t& state, - const stepper_t& stepper, - result_type& result) const - { - // Listen to the surface and create bound state where necessary - auto surface = state.navigation.currentSurface; - if (surface and surface->associatedDetectorElement()) { - // Create a bound state and log the jacobian - auto boundState = stepper.boundState(state.stepping, *surface, true); - result.jacobians.push_back(std::move(std::get<Jacobian>(boundState))); - result.paths.push_back(std::get<double>(boundState)); - } - // Also store the jacobian and full path - if ((state.navigation.navigationBreak or state.navigation.targetReached) - and not result.finalized) { - // Set the last stepping parameter - result.paths.push_back(state.stepping.pathAccumulated); - // Set the full parameters - result.fullJacobian = state.stepping.jacobian; - result.fullPath = state.stepping.pathAccumulated; - // Remember that you finalized this - result.finalized = true; - } + /// @param state is the mutable propagator state object + /// @param stepper The stepper in use + /// @param result is the mutable result state object + template <typename propagator_state_t, typename stepper_t> + void operator()(propagator_state_t& state, const stepper_t& stepper, + result_type& result) const { + // Listen to the surface and create bound state where necessary + auto surface = state.navigation.currentSurface; + if (surface and surface->associatedDetectorElement()) { + // Create a bound state and log the jacobian + auto boundState = stepper.boundState(state.stepping, *surface, true); + result.jacobians.push_back(std::move(std::get<Jacobian>(boundState))); + result.paths.push_back(std::get<double>(boundState)); } - - /// @brief Kalman sequence operation - void operation - /// - /// @tparam propagator_state_t is the type of Propagagor state - /// @tparam stepper_t Type of the stepper - /// - /// @param state is the mutable propagator state object - /// @param stepper Stepper used by the propagation - template <typename propagator_state_t, typename stepper_t> - void - operator()(propagator_state_t& /*state*/, const stepper_t& /*unused*/) const - { + // Also store the jacobian and full path + if ((state.navigation.navigationBreak or state.navigation.targetReached) and + not result.finalized) { + // Set the last stepping parameter + result.paths.push_back(state.stepping.pathAccumulated); + // Set the full parameters + result.fullJacobian = state.stepping.jacobian; + result.fullPath = state.stepping.pathAccumulated; + // Remember that you finalized this + result.finalized = true; } - }; + } + /// @brief Kalman sequence operation - void operation /// - /// @brief Unit test for Kalman fitter propagation + /// @tparam propagator_state_t is the type of Propagagor state + /// @tparam stepper_t Type of the stepper /// - BOOST_AUTO_TEST_CASE(kalman_extrapolator) - { - // Build detector, take the cubic detector - CubicTrackingGeometry cGeometry(tgContext); - auto detector = cGeometry(); - - // The Navigator through the detector geometry - Navigator navigator(detector); - navigator.resolvePassive = false; - navigator.resolveMaterial = true; - navigator.resolveSensitive = true; - - // Configure propagation with deactivated B-field - ConstantBField bField(Vector3D(0., 0., 0.)); - using Stepper = EigenStepper<ConstantBField>; - Stepper stepper(bField); - using Propagator = Propagator<Stepper, Navigator>; - Propagator propagator(stepper, navigator); - - // Set initial parameters for the particle track - ActsSymMatrixD<5> cov; - cov << 10 * units::_mm, 0, 0.123, 0, 0.5, 0, 10 * units::_mm, 0, 0.162, 0, - 0.123, 0, 0.1, 0, 0, 0, 0.162, 0, 0.1, 0, 0.5, 0, 0, 0, - 1. / (10 * units::_GeV); - auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); - - // The start position and start parameters - Vector3D pos(-3. * units::_m, 0., 0.), mom(1. * units::_GeV, 0., 0); - SingleCurvilinearTrackParameters<ChargedPolicy> start( - std::move(covPtr), pos, mom, 1.); - - // Create the ActionList and AbortList - using StepWiseResult = StepWiseActor::result_type; - using StepWiseActors = ActionList<StepWiseActor>; - using Aborters = AbortList<detail::EndOfWorldReached>; - - // Create some options - using StepWiseOptions = PropagatorOptions<StepWiseActors, Aborters>; - StepWiseOptions swOptions(tgContext, mfContext); - - using PlainActors = ActionList<>; - using PlainOptions = PropagatorOptions<PlainActors, Aborters>; - PlainOptions pOptions(tgContext, mfContext); - - // Run the standard propagation - const auto& pResult = propagator.propagate(start, pOptions).value(); - // Let's get the end parameters and jacobian matrix - const auto& pJacobian = *(pResult.transportJacobian); - - // Run the stepwise propagation - const auto& swResult = propagator.propagate(start, swOptions).value(); - auto swJacobianTest = swResult.template get<StepWiseResult>(); - - // (1) Path length test - double accPath = 0.; - auto swPaths = swJacobianTest.paths; - // Sum up the step-wise paths, they are total though - for (auto cpath = swPaths.rbegin(); cpath != swPaths.rend(); ++cpath) { - if (cpath != swPaths.rend() - 1) { - accPath += (*cpath) - (*(cpath + 1)); - continue; - } - accPath += (*cpath) - 0.; + /// @param state is the mutable propagator state object + /// @param stepper Stepper used by the propagation + template <typename propagator_state_t, typename stepper_t> + void operator()(propagator_state_t& /*state*/, + const stepper_t& /*unused*/) const {} +}; + +/// +/// @brief Unit test for Kalman fitter propagation +/// +BOOST_AUTO_TEST_CASE(kalman_extrapolator) { + // Build detector, take the cubic detector + CubicTrackingGeometry cGeometry(tgContext); + auto detector = cGeometry(); + + // The Navigator through the detector geometry + Navigator navigator(detector); + navigator.resolvePassive = false; + navigator.resolveMaterial = true; + navigator.resolveSensitive = true; + + // Configure propagation with deactivated B-field + ConstantBField bField(Vector3D(0., 0., 0.)); + using Stepper = EigenStepper<ConstantBField>; + Stepper stepper(bField); + using Propagator = Propagator<Stepper, Navigator>; + Propagator propagator(stepper, navigator); + + // Set initial parameters for the particle track + ActsSymMatrixD<5> cov; + cov << 10 * units::_mm, 0, 0.123, 0, 0.5, 0, 10 * units::_mm, 0, 0.162, 0, + 0.123, 0, 0.1, 0, 0, 0, 0.162, 0, 0.1, 0, 0.5, 0, 0, 0, + 1. / (10 * units::_GeV); + auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); + + // The start position and start parameters + Vector3D pos(-3. * units::_m, 0., 0.), mom(1. * units::_GeV, 0., 0); + SingleCurvilinearTrackParameters<ChargedPolicy> start(std::move(covPtr), pos, + mom, 1.); + + // Create the ActionList and AbortList + using StepWiseResult = StepWiseActor::result_type; + using StepWiseActors = ActionList<StepWiseActor>; + using Aborters = AbortList<detail::EndOfWorldReached>; + + // Create some options + using StepWiseOptions = PropagatorOptions<StepWiseActors, Aborters>; + StepWiseOptions swOptions(tgContext, mfContext); + + using PlainActors = ActionList<>; + using PlainOptions = PropagatorOptions<PlainActors, Aborters>; + PlainOptions pOptions(tgContext, mfContext); + + // Run the standard propagation + const auto& pResult = propagator.propagate(start, pOptions).value(); + // Let's get the end parameters and jacobian matrix + const auto& pJacobian = *(pResult.transportJacobian); + + // Run the stepwise propagation + const auto& swResult = propagator.propagate(start, swOptions).value(); + auto swJacobianTest = swResult.template get<StepWiseResult>(); + + // (1) Path length test + double accPath = 0.; + auto swPaths = swJacobianTest.paths; + // Sum up the step-wise paths, they are total though + for (auto cpath = swPaths.rbegin(); cpath != swPaths.rend(); ++cpath) { + if (cpath != swPaths.rend() - 1) { + accPath += (*cpath) - (*(cpath + 1)); + continue; } - CHECK_CLOSE_REL(swJacobianTest.fullPath, accPath, 1e-6); - - // (2) Jacobian test - Jacobian accJacobian = Jacobian::Identity(); - // The stepwise jacobians - auto swJacobians = swJacobianTest.jacobians; - // The last-step jacobian, needed for the full jacobian transport - const auto& swlJacobian = *(swResult.transportJacobian); - - // Build up the step-wise jacobians - for (auto& j : swJacobians) { - accJacobian = j * accJacobian; - } - accJacobian = swlJacobian * accJacobian; - CHECK_CLOSE_OR_SMALL(pJacobian, accJacobian, 1e-6, 1e-9); + accPath += (*cpath) - 0.; } + CHECK_CLOSE_REL(swJacobianTest.fullPath, accPath, 1e-6); + + // (2) Jacobian test + Jacobian accJacobian = Jacobian::Identity(); + // The stepwise jacobians + auto swJacobians = swJacobianTest.jacobians; + // The last-step jacobian, needed for the full jacobian transport + const auto& swlJacobian = *(swResult.transportJacobian); + + // Build up the step-wise jacobians + for (auto& j : swJacobians) { + accJacobian = j * accJacobian; + } + accJacobian = swlJacobian * accJacobian; + CHECK_CLOSE_OR_SMALL(pJacobian, accJacobian, 1e-6, 1e-9); } -} +} // namespace Test +} // namespace Acts diff --git a/Tests/Core/Propagator/LoopProtectionTests.cpp b/Tests/Core/Propagator/LoopProtectionTests.cpp index 740dedb3a5e0f71a28e91a597355ca9fd048f032..939b11543e3515bd147b81904b1889e62e6479f1 100644 --- a/Tests/Core/Propagator/LoopProtectionTests.cpp +++ b/Tests/Core/Propagator/LoopProtectionTests.cpp @@ -27,7 +27,7 @@ #include "Acts/Utilities/Units.hpp" namespace bdata = boost::unit_test::data; -namespace tt = boost::test_tools; +namespace tt = boost::test_tools; namespace Acts { @@ -35,192 +35,162 @@ using namespace detail; namespace Test { - // Create a test context - GeometryContext tgContext = GeometryContext(); - MagneticFieldContext mfContext = MagneticFieldContext(); - - /// @brief mockup of stepping state - struct SteppingState - { - - /// Parameters - Vector3D pos = Vector3D(0., 0., 0.); - Vector3D dir = Vector3D(0., 0., 1); - double p = 100. * units::_MeV; - }; - - /// @brief mockup of stepping state - struct Stepper - { - - Vector3D field = Vector3D(0., 0., 2. * units::_T); - - /// Get the field for the stepping, it checks first if the access is still - /// within the Cell, and updates the cell if necessary. - /// - /// @param [in,out] state is the propagation state associated with the track - /// the magnetic field cell is used (and potentially - /// updated) - /// @param [in] pos is the field position - Vector3D - getField(SteppingState& /*unused*/, const Vector3D& /*unused*/) const - { - // get the field from the cell - return field; - } - - /// Access method - position - Vector3D - position(const SteppingState& state) const - { - return state.pos; - } - - /// Access method - direction - Vector3D - direction(const SteppingState& state) const - { - return state.dir; - } - - /// Access method - momentum - double - momentum(const SteppingState& state) const - { - return state.p; - } - }; - - /// @brief mockup of navigation state - struct NavigationState - { - bool navigationBreak = false; - }; - - /// @brief mockup of the Propagator Options - struct Options - { - - /// Absolute maximum path length - double pathLimit = std::numeric_limits<double>::max(); - bool loopProtection = true; - double loopFraction = 0.5; - - /// Contains: target aborters - AbortList<PathLimitReached> abortList; - }; - - /// @brief mockup of propagtor state - struct PropagatorState - { - /// Contains: stepping state - SteppingState stepping; - /// Contains: navigation state - NavigationState navigation; - /// Contains: options - Options options; - }; - - // This test case checks that no segmentation fault appears - // - this tests the collection of surfaces - BOOST_DATA_TEST_CASE( - loop_aborter_test, - bdata::random((bdata::seed = 21, - bdata::distribution - = std::uniform_real_distribution<>(-M_PI, M_PI))) - ^ bdata::random((bdata::seed = 22, - bdata::distribution - = std::uniform_real_distribution<>(-M_PI, M_PI))) - ^ bdata::xrange(1), - phi, - deltaPhi, - index) - { - (void)index; - (void)deltaPhi; - - PropagatorState pState; - pState.stepping.dir = Vector3D(cos(phi), sin(phi), 0.); - pState.stepping.p = 100. * units::_MeV; - - Stepper pStepper; - - auto initialLimit - = pState.options.abortList.get<PathLimitReached>().internalLimit; - - LoopProtection<PathLimitReached> lProtection; - lProtection(pState, pStepper); - - auto updatedLimit - = pState.options.abortList.get<PathLimitReached>().internalLimit; - BOOST_CHECK_LT(updatedLimit, initialLimit); +// Create a test context +GeometryContext tgContext = GeometryContext(); +MagneticFieldContext mfContext = MagneticFieldContext(); + +/// @brief mockup of stepping state +struct SteppingState { + /// Parameters + Vector3D pos = Vector3D(0., 0., 0.); + Vector3D dir = Vector3D(0., 0., 1); + double p = 100. * units::_MeV; +}; + +/// @brief mockup of stepping state +struct Stepper { + Vector3D field = Vector3D(0., 0., 2. * units::_T); + + /// Get the field for the stepping, it checks first if the access is still + /// within the Cell, and updates the cell if necessary. + /// + /// @param [in,out] state is the propagation state associated with the track + /// the magnetic field cell is used (and potentially + /// updated) + /// @param [in] pos is the field position + Vector3D getField(SteppingState& /*unused*/, + const Vector3D& /*unused*/) const { + // get the field from the cell + return field; } - using BField = ConstantBField; - using EigenStepper = EigenStepper<BField>; - using EigenPropagator = Propagator<EigenStepper>; - - const int ntests = 100; - const int skip = 0; - - // This test case checks that the propagator with loop LoopProtection - // stops where expected - BOOST_DATA_TEST_CASE( - propagator_loop_protection_test, - bdata::random((bdata::seed = 20, - bdata::distribution - = std::uniform_real_distribution<>(0.5 * units::_GeV, - 10. * units::_GeV))) - ^ bdata::random((bdata::seed = 21, - bdata::distribution - = std::uniform_real_distribution<>(-M_PI, M_PI))) - ^ bdata::random((bdata::seed = 22, - bdata::distribution - = std::uniform_real_distribution<>(1.0, M_PI - 1.0))) - ^ bdata::random((bdata::seed = 23, - bdata::distribution - = std::uniform_int_distribution<>(0, 1))) - ^ bdata::xrange(ntests), - pT, - phi, - theta, - charge, - index) - { - if (index < skip) { - return; - } - - double dcharge = -1 + 2 * charge; - - const double Bz = 2. * units::_T; - BField bField(0, 0, Bz); - - EigenStepper estepper(bField); - - EigenPropagator epropagator(std::move(estepper)); - - // define start parameters - double x = 0; - double y = 0; - double z = 0; - double px = pT * cos(phi); - double py = pT * sin(phi); - double pz = pT / tan(theta); - double q = dcharge; - Vector3D pos(x, y, z); - Vector3D mom(px, py, pz); - CurvilinearParameters start(nullptr, pos, mom, q); - - PropagatorOptions<> options(tgContext, mfContext); - options.maxSteps = 1e6; - const auto& result = epropagator.propagate(start, options).value(); - - // this test assumes state.options.loopFraction = 0.5 - CHECK_CLOSE_REL(px, -result.endParameters->momentum().x(), 1e-2); - CHECK_CLOSE_REL(py, -result.endParameters->momentum().y(), 1e-2); - CHECK_CLOSE_REL(pz, result.endParameters->momentum().z(), 1e-2); + /// Access method - position + Vector3D position(const SteppingState& state) const { return state.pos; } + + /// Access method - direction + Vector3D direction(const SteppingState& state) const { return state.dir; } + + /// Access method - momentum + double momentum(const SteppingState& state) const { return state.p; } +}; + +/// @brief mockup of navigation state +struct NavigationState { + bool navigationBreak = false; +}; + +/// @brief mockup of the Propagator Options +struct Options { + /// Absolute maximum path length + double pathLimit = std::numeric_limits<double>::max(); + bool loopProtection = true; + double loopFraction = 0.5; + + /// Contains: target aborters + AbortList<PathLimitReached> abortList; +}; + +/// @brief mockup of propagtor state +struct PropagatorState { + /// Contains: stepping state + SteppingState stepping; + /// Contains: navigation state + NavigationState navigation; + /// Contains: options + Options options; +}; + +// This test case checks that no segmentation fault appears +// - this tests the collection of surfaces +BOOST_DATA_TEST_CASE( + loop_aborter_test, + bdata::random( + (bdata::seed = 21, + bdata::distribution = std::uniform_real_distribution<>(-M_PI, M_PI))) ^ + bdata::random((bdata::seed = 22, + bdata::distribution = + std::uniform_real_distribution<>(-M_PI, M_PI))) ^ + bdata::xrange(1), + phi, deltaPhi, index) { + (void)index; + (void)deltaPhi; + + PropagatorState pState; + pState.stepping.dir = Vector3D(cos(phi), sin(phi), 0.); + pState.stepping.p = 100. * units::_MeV; + + Stepper pStepper; + + auto initialLimit = + pState.options.abortList.get<PathLimitReached>().internalLimit; + + LoopProtection<PathLimitReached> lProtection; + lProtection(pState, pStepper); + + auto updatedLimit = + pState.options.abortList.get<PathLimitReached>().internalLimit; + BOOST_CHECK_LT(updatedLimit, initialLimit); +} + +using BField = ConstantBField; +using EigenStepper = EigenStepper<BField>; +using EigenPropagator = Propagator<EigenStepper>; + +const int ntests = 100; +const int skip = 0; + +// This test case checks that the propagator with loop LoopProtection +// stops where expected +BOOST_DATA_TEST_CASE( + propagator_loop_protection_test, + bdata::random((bdata::seed = 20, + bdata::distribution = std::uniform_real_distribution<>( + 0.5 * units::_GeV, 10. * units::_GeV))) ^ + bdata::random((bdata::seed = 21, + bdata::distribution = + std::uniform_real_distribution<>(-M_PI, M_PI))) ^ + bdata::random((bdata::seed = 22, + bdata::distribution = + std::uniform_real_distribution<>(1.0, M_PI - 1.0))) ^ + bdata::random( + (bdata::seed = 23, + bdata::distribution = std::uniform_int_distribution<>(0, 1))) ^ + bdata::xrange(ntests), + pT, phi, theta, charge, index) { + if (index < skip) { + return; } + double dcharge = -1 + 2 * charge; + + const double Bz = 2. * units::_T; + BField bField(0, 0, Bz); + + EigenStepper estepper(bField); + + EigenPropagator epropagator(std::move(estepper)); + + // define start parameters + double x = 0; + double y = 0; + double z = 0; + double px = pT * cos(phi); + double py = pT * sin(phi); + double pz = pT / tan(theta); + double q = dcharge; + Vector3D pos(x, y, z); + Vector3D mom(px, py, pz); + CurvilinearParameters start(nullptr, pos, mom, q); + + PropagatorOptions<> options(tgContext, mfContext); + options.maxSteps = 1e6; + const auto& result = epropagator.propagate(start, options).value(); + + // this test assumes state.options.loopFraction = 0.5 + CHECK_CLOSE_REL(px, -result.endParameters->momentum().x(), 1e-2); + CHECK_CLOSE_REL(py, -result.endParameters->momentum().y(), 1e-2); + CHECK_CLOSE_REL(pz, result.endParameters->momentum().z(), 1e-2); +} + } // namespace Test } // namespace Acts diff --git a/Tests/Core/Propagator/MaterialCollectionTests.cpp b/Tests/Core/Propagator/MaterialCollectionTests.cpp index 847e31df6ee8af7c589f9ca207e78f4c2d742e3f..812891aeda2f8805df5694e3f98d8f32bcabf3c3 100644 --- a/Tests/Core/Propagator/MaterialCollectionTests.cpp +++ b/Tests/Core/Propagator/MaterialCollectionTests.cpp @@ -37,415 +37,397 @@ #include "Acts/MagneticField/MagneticFieldContext.hpp" namespace bdata = boost::unit_test::data; -namespace tt = boost::test_tools; +namespace tt = boost::test_tools; namespace Acts { namespace Test { - // Create a test context - GeometryContext tgContext = GeometryContext(); - MagneticFieldContext mfContext = MagneticFieldContext(); - - // Global definitions - // The path limit abort - using path_limit = detail::PathLimitReached; - - CylindricalTrackingGeometry cGeometry(tgContext); - auto tGeometry = cGeometry(); - - // create a navigator for this tracking geometry - Navigator navigatorES(tGeometry); - Navigator navigatorSL(tGeometry); - - using BField = ConstantBField; - using StepCorrector = detail::RelativePathCorrector; - using EigenStepper = EigenStepper<BField, StepCorrector>; - using EigenPropagator = Propagator<EigenStepper, Navigator>; - using StraightLinePropagator = Propagator<StraightLineStepper, Navigator>; - - const double Bz = 2. * units::_T; - BField bField(0, 0, Bz); - EigenStepper estepper(bField); - EigenPropagator epropagator(std::move(estepper), std::move(navigatorES)); - - StraightLineStepper slstepper; - StraightLinePropagator slpropagator(std::move(slstepper), - std::move(navigatorSL)); - const int ntests = 500; - const int skip = 0; - bool debugModeFwd = false; - bool debugModeBwd = false; - bool debugModeFwdStep = false; - bool debugModeBwdStep = false; - - /// the actual test nethod that runs the test - /// can be used with several propagator types - /// @tparam propagator_t is the actual propagator type - /// - /// @param prop is the propagator instance - /// @param pT the transverse momentum - /// @param phi the azimuthal angle of the track at creation - /// @param theta the polar angle of the track at creation - /// @param charge is the charge of the particle - /// @param index is the run index from the test - template <typename propagator_t> - void - runTest(const propagator_t& prop, - double pT, - double phi, - double theta, - int charge, - int index) - { - double dcharge = -1 + 2 * charge; - - if (index < skip) { - return; - } - - // define start parameters - double x = 0; - double y = 0; - double z = 0; - double px = pT * cos(phi); - double py = pT * sin(phi); - double pz = pT / tan(theta); - double q = dcharge; - Vector3D pos(x, y, z); - Vector3D mom(px, py, pz); - CurvilinearParameters start(nullptr, pos, mom, q); - - using DebugOutput = detail::DebugOutputActor; - - // Action list and abort list - using ActionListType = ActionList<MaterialInteractor, DebugOutput>; - using AbortListType = AbortList<>; - - using Options = PropagatorOptions<ActionListType, AbortListType>; - Options fwdOptions(tgContext, mfContext); - - fwdOptions.maxStepSize = 25. * units::_cm; - fwdOptions.pathLimit = 25 * units::_cm; - fwdOptions.debug = debugModeFwd; - - // get the material collector and configure it - auto& fwdMaterialInteractor - = fwdOptions.actionList.template get<MaterialInteractor>(); - fwdMaterialInteractor.recordInteractions = true; - fwdMaterialInteractor.energyLoss = false; - fwdMaterialInteractor.multipleScattering = false; - - if (debugModeFwd) { - std::cout << ">>> Forward Propagation : start." << std::endl; - } - // forward material test - const auto& fwdResult = prop.propagate(start, fwdOptions).value(); - auto& fwdMaterial - = fwdResult.template get<MaterialInteractor::result_type>(); - - double fwdStepMaterialInX0 = 0.; - double fwdStepMaterialInL0 = 0.; - // check that the collected material is not zero - BOOST_CHECK_NE(fwdMaterial.materialInX0, 0.); - BOOST_CHECK_NE(fwdMaterial.materialInL0, 0.); - // check that the sum of all steps is the total material - for (auto& mInteraction : fwdMaterial.materialInteractions) { - fwdStepMaterialInX0 += mInteraction.materialProperties.thicknessInX0(); - fwdStepMaterialInL0 += mInteraction.materialProperties.thicknessInL0(); - } - CHECK_CLOSE_REL(fwdMaterial.materialInX0, fwdStepMaterialInX0, 1e-3); - CHECK_CLOSE_REL(fwdMaterial.materialInL0, fwdStepMaterialInL0, 1e-3); - - // get the forward output to the screen - if (debugModeFwd) { - const auto& fwdOutput - = fwdResult.template get<DebugOutput::result_type>(); - std::cout << ">>> Forward Propagation & Navigation output " << std::endl; - std::cout << fwdOutput.debugString << std::endl; - // check if the surfaces are free - std::cout << ">>> Material steps found on ..." << std::endl; - for (auto& fwdStepsC : fwdMaterial.materialInteractions) { - std::cout << "--> Surface with " - << fwdStepsC.surface->geoID().toString() << std::endl; - } - } - - // backward material test - Options bwdOptions(tgContext, mfContext); - bwdOptions.maxStepSize = -25 * units::_cm; - bwdOptions.pathLimit = -25 * units::_cm; - bwdOptions.direction = backward; - bwdOptions.debug = debugModeBwd; - - // get the material collector and configure it - auto& bwdMaterialInteractor - = bwdOptions.actionList.template get<MaterialInteractor>(); - bwdMaterialInteractor.recordInteractions = true; - bwdMaterialInteractor.energyLoss = false; - bwdMaterialInteractor.multipleScattering = false; - - const auto& startSurface = start.referenceSurface(); - - if (debugModeBwd) { - std::cout << ">>> Backward Propagation : start." << std::endl; - } - const auto& bwdResult = prop.propagate(*fwdResult.endParameters.get(), - startSurface, - bwdOptions) - .value(); +// Create a test context +GeometryContext tgContext = GeometryContext(); +MagneticFieldContext mfContext = MagneticFieldContext(); + +// Global definitions +// The path limit abort +using path_limit = detail::PathLimitReached; + +CylindricalTrackingGeometry cGeometry(tgContext); +auto tGeometry = cGeometry(); + +// create a navigator for this tracking geometry +Navigator navigatorES(tGeometry); +Navigator navigatorSL(tGeometry); + +using BField = ConstantBField; +using StepCorrector = detail::RelativePathCorrector; +using EigenStepper = EigenStepper<BField, StepCorrector>; +using EigenPropagator = Propagator<EigenStepper, Navigator>; +using StraightLinePropagator = Propagator<StraightLineStepper, Navigator>; + +const double Bz = 2. * units::_T; +BField bField(0, 0, Bz); +EigenStepper estepper(bField); +EigenPropagator epropagator(std::move(estepper), std::move(navigatorES)); + +StraightLineStepper slstepper; +StraightLinePropagator slpropagator(std::move(slstepper), + std::move(navigatorSL)); +const int ntests = 500; +const int skip = 0; +bool debugModeFwd = false; +bool debugModeBwd = false; +bool debugModeFwdStep = false; +bool debugModeBwdStep = false; + +/// the actual test nethod that runs the test +/// can be used with several propagator types +/// @tparam propagator_t is the actual propagator type +/// +/// @param prop is the propagator instance +/// @param pT the transverse momentum +/// @param phi the azimuthal angle of the track at creation +/// @param theta the polar angle of the track at creation +/// @param charge is the charge of the particle +/// @param index is the run index from the test +template <typename propagator_t> +void runTest(const propagator_t& prop, double pT, double phi, double theta, + int charge, int index) { + double dcharge = -1 + 2 * charge; + + if (index < skip) { + return; + } - if (debugModeBwd) { - std::cout << ">>> Backward Propagation : end." << std::endl; + // define start parameters + double x = 0; + double y = 0; + double z = 0; + double px = pT * cos(phi); + double py = pT * sin(phi); + double pz = pT / tan(theta); + double q = dcharge; + Vector3D pos(x, y, z); + Vector3D mom(px, py, pz); + CurvilinearParameters start(nullptr, pos, mom, q); + + using DebugOutput = detail::DebugOutputActor; + + // Action list and abort list + using ActionListType = ActionList<MaterialInteractor, DebugOutput>; + using AbortListType = AbortList<>; + + using Options = PropagatorOptions<ActionListType, AbortListType>; + Options fwdOptions(tgContext, mfContext); + + fwdOptions.maxStepSize = 25. * units::_cm; + fwdOptions.pathLimit = 25 * units::_cm; + fwdOptions.debug = debugModeFwd; + + // get the material collector and configure it + auto& fwdMaterialInteractor = + fwdOptions.actionList.template get<MaterialInteractor>(); + fwdMaterialInteractor.recordInteractions = true; + fwdMaterialInteractor.energyLoss = false; + fwdMaterialInteractor.multipleScattering = false; + + if (debugModeFwd) { + std::cout << ">>> Forward Propagation : start." << std::endl; + } + // forward material test + const auto& fwdResult = prop.propagate(start, fwdOptions).value(); + auto& fwdMaterial = fwdResult.template get<MaterialInteractor::result_type>(); + + double fwdStepMaterialInX0 = 0.; + double fwdStepMaterialInL0 = 0.; + // check that the collected material is not zero + BOOST_CHECK_NE(fwdMaterial.materialInX0, 0.); + BOOST_CHECK_NE(fwdMaterial.materialInL0, 0.); + // check that the sum of all steps is the total material + for (auto& mInteraction : fwdMaterial.materialInteractions) { + fwdStepMaterialInX0 += mInteraction.materialProperties.thicknessInX0(); + fwdStepMaterialInL0 += mInteraction.materialProperties.thicknessInL0(); + } + CHECK_CLOSE_REL(fwdMaterial.materialInX0, fwdStepMaterialInX0, 1e-3); + CHECK_CLOSE_REL(fwdMaterial.materialInL0, fwdStepMaterialInL0, 1e-3); + + // get the forward output to the screen + if (debugModeFwd) { + const auto& fwdOutput = fwdResult.template get<DebugOutput::result_type>(); + std::cout << ">>> Forward Propagation & Navigation output " << std::endl; + std::cout << fwdOutput.debugString << std::endl; + // check if the surfaces are free + std::cout << ">>> Material steps found on ..." << std::endl; + for (auto& fwdStepsC : fwdMaterial.materialInteractions) { + std::cout << "--> Surface with " << fwdStepsC.surface->geoID().toString() + << std::endl; } + } - auto& bwdMaterial - = bwdResult.template get<typename MaterialInteractor::result_type>(); - - double bwdStepMaterialInX0 = 0.; - double bwdStepMaterialInL0 = 0.; + // backward material test + Options bwdOptions(tgContext, mfContext); + bwdOptions.maxStepSize = -25 * units::_cm; + bwdOptions.pathLimit = -25 * units::_cm; + bwdOptions.direction = backward; + bwdOptions.debug = debugModeBwd; - // check that the collected material is not zero - BOOST_CHECK_NE(bwdMaterial.materialInX0, 0.); - BOOST_CHECK_NE(bwdMaterial.materialInL0, 0.); - // check that the sum of all steps is the total material - for (auto& mInteraction : bwdMaterial.materialInteractions) { - bwdStepMaterialInX0 += mInteraction.materialProperties.thicknessInX0(); - bwdStepMaterialInL0 += mInteraction.materialProperties.thicknessInL0(); - } + // get the material collector and configure it + auto& bwdMaterialInteractor = + bwdOptions.actionList.template get<MaterialInteractor>(); + bwdMaterialInteractor.recordInteractions = true; + bwdMaterialInteractor.energyLoss = false; + bwdMaterialInteractor.multipleScattering = false; - CHECK_CLOSE_REL(bwdMaterial.materialInX0, bwdStepMaterialInX0, 1e-3); - CHECK_CLOSE_REL(bwdMaterial.materialInL0, bwdStepMaterialInL0, 1e-3); + const auto& startSurface = start.referenceSurface(); - // get the backward output to the screen - if (debugModeBwd) { - const auto& bwd_output - = bwdResult.template get<DebugOutput::result_type>(); - std::cout << ">>> Backward Propagation & Navigation output " << std::endl; - std::cout << bwd_output.debugString << std::endl; - // check if the surfaces are free - std::cout << ">>> Material steps found on ..." << std::endl; - for (auto& bwdStepsC : bwdMaterial.materialInteractions) { - std::cout << "--> Surface with " - << bwdStepsC.surface->geoID().toString() << std::endl; - } - } - - // forward-backward compatibility test - BOOST_CHECK_EQUAL(bwdMaterial.materialInteractions.size(), - fwdMaterial.materialInteractions.size()); + if (debugModeBwd) { + std::cout << ">>> Backward Propagation : start." << std::endl; + } + const auto& bwdResult = + prop.propagate(*fwdResult.endParameters.get(), startSurface, bwdOptions) + .value(); - CHECK_CLOSE_REL(bwdMaterial.materialInX0, fwdMaterial.materialInX0, 1e-3); - CHECK_CLOSE_REL(bwdMaterial.materialInL0, bwdMaterial.materialInL0, 1e-3); + if (debugModeBwd) { + std::cout << ">>> Backward Propagation : end." << std::endl; + } - // stepping from one surface to the next - // now go from surface to surface and check - Options fwdStepOptions(tgContext, mfContext); - fwdStepOptions.maxStepSize = 25. * units::_cm; - fwdStepOptions.pathLimit = 25 * units::_cm; - fwdStepOptions.debug = debugModeFwdStep; + auto& bwdMaterial = + bwdResult.template get<typename MaterialInteractor::result_type>(); - // get the material collector and configure it - auto& fwdStepMaterialInteractor - = fwdStepOptions.actionList.template get<MaterialInteractor>(); - fwdStepMaterialInteractor.recordInteractions = true; - fwdStepMaterialInteractor.energyLoss = false; - fwdStepMaterialInteractor.multipleScattering = false; + double bwdStepMaterialInX0 = 0.; + double bwdStepMaterialInL0 = 0.; - double fwdStepStepMaterialInX0 = 0.; - double fwdStepStepMaterialInL0 = 0.; + // check that the collected material is not zero + BOOST_CHECK_NE(bwdMaterial.materialInX0, 0.); + BOOST_CHECK_NE(bwdMaterial.materialInL0, 0.); + // check that the sum of all steps is the total material + for (auto& mInteraction : bwdMaterial.materialInteractions) { + bwdStepMaterialInX0 += mInteraction.materialProperties.thicknessInX0(); + bwdStepMaterialInL0 += mInteraction.materialProperties.thicknessInL0(); + } - if (debugModeFwdStep) { - // check if the surfaces are free - std::cout << ">>> Forward steps to be processed sequentially ..." + CHECK_CLOSE_REL(bwdMaterial.materialInX0, bwdStepMaterialInX0, 1e-3); + CHECK_CLOSE_REL(bwdMaterial.materialInL0, bwdStepMaterialInL0, 1e-3); + + // get the backward output to the screen + if (debugModeBwd) { + const auto& bwd_output = bwdResult.template get<DebugOutput::result_type>(); + std::cout << ">>> Backward Propagation & Navigation output " << std::endl; + std::cout << bwd_output.debugString << std::endl; + // check if the surfaces are free + std::cout << ">>> Material steps found on ..." << std::endl; + for (auto& bwdStepsC : bwdMaterial.materialInteractions) { + std::cout << "--> Surface with " << bwdStepsC.surface->geoID().toString() << std::endl; - for (auto& fwdStepsC : fwdMaterial.materialInteractions) { - std::cout << "--> Surface with " - << fwdStepsC.surface->geoID().toString() << std::endl; - } } + } - // move forward step by step through the surfaces - const TrackParameters* sParameters = &start; - std::vector<const TrackParameters*> stepParameters; - for (auto& fwdSteps : fwdMaterial.materialInteractions) { - if (debugModeFwdStep) { - std::cout << ">>> Forward step : " - << sParameters->referenceSurface().geoID().toString() - << " --> " << fwdSteps.surface->geoID().toString() - << std::endl; - } - - // make a forward step - const auto& fwdStep - = prop.propagate(*sParameters, (*fwdSteps.surface), fwdStepOptions) - .value(); - // get the backward output to the screen - if (debugModeFwdStep) { - const auto& fwdStepOutput - = fwdStep.template get<DebugOutput::result_type>(); - std::cout << fwdStepOutput.debugString << std::endl; - } - - auto& fwdStepMaterial - = fwdStep.template get<typename MaterialInteractor::result_type>(); - fwdStepStepMaterialInX0 += fwdStepMaterial.materialInX0; - fwdStepStepMaterialInL0 += fwdStepMaterial.materialInL0; - - if (fwdStep.endParameters != nullptr) { - sParameters = fwdStep.endParameters->clone(); - // make sure the parameters do not run out of scope - stepParameters.push_back(sParameters); - } + // forward-backward compatibility test + BOOST_CHECK_EQUAL(bwdMaterial.materialInteractions.size(), + fwdMaterial.materialInteractions.size()); + + CHECK_CLOSE_REL(bwdMaterial.materialInX0, fwdMaterial.materialInX0, 1e-3); + CHECK_CLOSE_REL(bwdMaterial.materialInL0, bwdMaterial.materialInL0, 1e-3); + + // stepping from one surface to the next + // now go from surface to surface and check + Options fwdStepOptions(tgContext, mfContext); + fwdStepOptions.maxStepSize = 25. * units::_cm; + fwdStepOptions.pathLimit = 25 * units::_cm; + fwdStepOptions.debug = debugModeFwdStep; + + // get the material collector and configure it + auto& fwdStepMaterialInteractor = + fwdStepOptions.actionList.template get<MaterialInteractor>(); + fwdStepMaterialInteractor.recordInteractions = true; + fwdStepMaterialInteractor.energyLoss = false; + fwdStepMaterialInteractor.multipleScattering = false; + + double fwdStepStepMaterialInX0 = 0.; + double fwdStepStepMaterialInL0 = 0.; + + if (debugModeFwdStep) { + // check if the surfaces are free + std::cout << ">>> Forward steps to be processed sequentially ..." + << std::endl; + for (auto& fwdStepsC : fwdMaterial.materialInteractions) { + std::cout << "--> Surface with " << fwdStepsC.surface->geoID().toString() + << std::endl; } - // final destination surface - const Surface& dSurface = fwdResult.endParameters->referenceSurface(); + } + // move forward step by step through the surfaces + const TrackParameters* sParameters = &start; + std::vector<const TrackParameters*> stepParameters; + for (auto& fwdSteps : fwdMaterial.materialInteractions) { if (debugModeFwdStep) { std::cout << ">>> Forward step : " << sParameters->referenceSurface().geoID().toString() << " --> " - << dSurface.geoID().toString() << std::endl; + << fwdSteps.surface->geoID().toString() << std::endl; } - const auto& fwdStepFinal - = prop.propagate(*sParameters, dSurface, fwdStepOptions).value(); - - auto& fwdStepMaterial - = fwdStepFinal.template get<typename MaterialInteractor::result_type>(); - fwdStepStepMaterialInX0 += fwdStepMaterial.materialInX0; - fwdStepStepMaterialInL0 += fwdStepMaterial.materialInL0; - - // forward-forward step compatibility test - CHECK_CLOSE_REL(fwdStepStepMaterialInX0, fwdStepMaterialInX0, 1e-3); - CHECK_CLOSE_REL(fwdStepStepMaterialInL0, fwdStepMaterialInL0, 1e-3); - + // make a forward step + const auto& fwdStep = + prop.propagate(*sParameters, (*fwdSteps.surface), fwdStepOptions) + .value(); // get the backward output to the screen if (debugModeFwdStep) { - const auto& fwdStepOutput - = fwdStepFinal.template get<DebugOutput::result_type>(); - std::cout << ">>> Forward final step propgation & navigation output " - << std::endl; + const auto& fwdStepOutput = + fwdStep.template get<DebugOutput::result_type>(); std::cout << fwdStepOutput.debugString << std::endl; } - // stepping from one surface to the next : backwards - // now go from surface to surface and check - Options bwdStepOptions(tgContext, mfContext); + auto& fwdStepMaterial = + fwdStep.template get<typename MaterialInteractor::result_type>(); + fwdStepStepMaterialInX0 += fwdStepMaterial.materialInX0; + fwdStepStepMaterialInL0 += fwdStepMaterial.materialInL0; - bwdStepOptions.maxStepSize = -25 * units::_cm; - bwdStepOptions.pathLimit = -25 * units::_cm; - bwdStepOptions.direction = backward; - bwdStepOptions.debug = debugModeBwdStep; + if (fwdStep.endParameters != nullptr) { + sParameters = fwdStep.endParameters->clone(); + // make sure the parameters do not run out of scope + stepParameters.push_back(sParameters); + } + } + // final destination surface + const Surface& dSurface = fwdResult.endParameters->referenceSurface(); - // get the material collector and configure it - auto& bwdStepMaterialInteractor - = bwdStepOptions.actionList.template get<MaterialInteractor>(); - bwdStepMaterialInteractor.recordInteractions = true; - bwdStepMaterialInteractor.multipleScattering = false; - bwdStepMaterialInteractor.energyLoss = false; + if (debugModeFwdStep) { + std::cout << ">>> Forward step : " + << sParameters->referenceSurface().geoID().toString() << " --> " + << dSurface.geoID().toString() << std::endl; + } - double bwdStepStepMaterialInX0 = 0.; - double bwdStepStepMaterialInL0 = 0.; + const auto& fwdStepFinal = + prop.propagate(*sParameters, dSurface, fwdStepOptions).value(); + + auto& fwdStepMaterial = + fwdStepFinal.template get<typename MaterialInteractor::result_type>(); + fwdStepStepMaterialInX0 += fwdStepMaterial.materialInX0; + fwdStepStepMaterialInL0 += fwdStepMaterial.materialInL0; + + // forward-forward step compatibility test + CHECK_CLOSE_REL(fwdStepStepMaterialInX0, fwdStepMaterialInX0, 1e-3); + CHECK_CLOSE_REL(fwdStepStepMaterialInL0, fwdStepMaterialInL0, 1e-3); + + // get the backward output to the screen + if (debugModeFwdStep) { + const auto& fwdStepOutput = + fwdStepFinal.template get<DebugOutput::result_type>(); + std::cout << ">>> Forward final step propgation & navigation output " + << std::endl; + std::cout << fwdStepOutput.debugString << std::endl; + } - if (debugModeBwdStep) { - // check if the surfaces are free - std::cout << ">>> Backward steps to be processed sequentially ..." + // stepping from one surface to the next : backwards + // now go from surface to surface and check + Options bwdStepOptions(tgContext, mfContext); + + bwdStepOptions.maxStepSize = -25 * units::_cm; + bwdStepOptions.pathLimit = -25 * units::_cm; + bwdStepOptions.direction = backward; + bwdStepOptions.debug = debugModeBwdStep; + + // get the material collector and configure it + auto& bwdStepMaterialInteractor = + bwdStepOptions.actionList.template get<MaterialInteractor>(); + bwdStepMaterialInteractor.recordInteractions = true; + bwdStepMaterialInteractor.multipleScattering = false; + bwdStepMaterialInteractor.energyLoss = false; + + double bwdStepStepMaterialInX0 = 0.; + double bwdStepStepMaterialInL0 = 0.; + + if (debugModeBwdStep) { + // check if the surfaces are free + std::cout << ">>> Backward steps to be processed sequentially ..." + << std::endl; + for (auto& bwdStepsC : bwdMaterial.materialInteractions) { + std::cout << "--> Surface with " << bwdStepsC.surface->geoID().toString() << std::endl; - for (auto& bwdStepsC : bwdMaterial.materialInteractions) { - std::cout << "--> Surface with " - << bwdStepsC.surface->geoID().toString() << std::endl; - } - } - - // move forward step by step through the surfaces - sParameters = fwdResult.endParameters.get(); - for (auto& bwdSteps : bwdMaterial.materialInteractions) { - if (debugModeBwdStep) { - std::cout << ">>> Backward step : " - << sParameters->referenceSurface().geoID().toString() - << " --> " << bwdSteps.surface->geoID().toString() - << std::endl; - } - // make a forward step - const auto& bwdStep - = prop.propagate(*sParameters, (*bwdSteps.surface), bwdStepOptions) - .value(); - // get the backward output to the screen - if (debugModeBwdStep) { - const auto& bwdStepOutput - = bwdStep.template get<DebugOutput::result_type>(); - std::cout << bwdStepOutput.debugString << std::endl; - } - - auto& bwdStepMaterial - = bwdStep.template get<typename MaterialInteractor::result_type>(); - bwdStepStepMaterialInX0 += bwdStepMaterial.materialInX0; - bwdStepStepMaterialInL0 += bwdStepMaterial.materialInL0; - - if (bwdStep.endParameters != nullptr) { - sParameters = bwdStep.endParameters->clone(); - // make sure the parameters do not run out of scope - stepParameters.push_back(sParameters); - } } - // final destination surface - const Surface& dbSurface = start.referenceSurface(); + } + // move forward step by step through the surfaces + sParameters = fwdResult.endParameters.get(); + for (auto& bwdSteps : bwdMaterial.materialInteractions) { if (debugModeBwdStep) { std::cout << ">>> Backward step : " << sParameters->referenceSurface().geoID().toString() << " --> " - << dSurface.geoID().toString() << std::endl; + << bwdSteps.surface->geoID().toString() << std::endl; + } + // make a forward step + const auto& bwdStep = + prop.propagate(*sParameters, (*bwdSteps.surface), bwdStepOptions) + .value(); + // get the backward output to the screen + if (debugModeBwdStep) { + const auto& bwdStepOutput = + bwdStep.template get<DebugOutput::result_type>(); + std::cout << bwdStepOutput.debugString << std::endl; } - const auto& bwdStepFinal - = prop.propagate(*sParameters, dbSurface, bwdStepOptions).value(); - - auto& bwdStepMaterial - = bwdStepFinal.template get<typename MaterialInteractor::result_type>(); + auto& bwdStepMaterial = + bwdStep.template get<typename MaterialInteractor::result_type>(); bwdStepStepMaterialInX0 += bwdStepMaterial.materialInX0; bwdStepStepMaterialInL0 += bwdStepMaterial.materialInL0; - // forward-forward step compatibility test - CHECK_CLOSE_REL(bwdStepStepMaterialInX0, bwdStepMaterialInX0, 1e-3); - CHECK_CLOSE_REL(bwdStepStepMaterialInL0, bwdStepMaterialInL0, 1e-3); - - // get the backward output to the screen - if (debugModeBwdStep) { - const auto& bwdStepOutput - = bwdStepFinal.template get<DebugOutput::result_type>(); - std::cout << ">>> Backward final step propgation & navigation output " - << std::endl; - std::cout << bwdStepOutput.debugString << std::endl; + if (bwdStep.endParameters != nullptr) { + sParameters = bwdStep.endParameters->clone(); + // make sure the parameters do not run out of scope + stepParameters.push_back(sParameters); } } + // final destination surface + const Surface& dbSurface = start.referenceSurface(); + + if (debugModeBwdStep) { + std::cout << ">>> Backward step : " + << sParameters->referenceSurface().geoID().toString() << " --> " + << dSurface.geoID().toString() << std::endl; + } - // This test case checks that no segmentation fault appears - // - this tests the collection of surfaces - BOOST_DATA_TEST_CASE( - test_material_collector, - bdata::random((bdata::seed = 20, - bdata::distribution - = std::uniform_real_distribution<>(0.5 * units::_GeV, - 10. * units::_GeV))) - ^ bdata::random((bdata::seed = 21, - bdata::distribution - = std::uniform_real_distribution<>(-M_PI, M_PI))) - ^ bdata::random((bdata::seed = 22, - bdata::distribution - = std::uniform_real_distribution<>(1.0, M_PI - 1.0))) - ^ bdata::random((bdata::seed = 23, - bdata::distribution - = std::uniform_int_distribution<>(0, 1))) - ^ bdata::xrange(ntests), - pT, - phi, - theta, - charge, - index) - { - runTest(epropagator, pT, phi, theta, charge, index); - runTest(slpropagator, pT, phi, theta, charge, index); + const auto& bwdStepFinal = + prop.propagate(*sParameters, dbSurface, bwdStepOptions).value(); + + auto& bwdStepMaterial = + bwdStepFinal.template get<typename MaterialInteractor::result_type>(); + bwdStepStepMaterialInX0 += bwdStepMaterial.materialInX0; + bwdStepStepMaterialInL0 += bwdStepMaterial.materialInL0; + + // forward-forward step compatibility test + CHECK_CLOSE_REL(bwdStepStepMaterialInX0, bwdStepMaterialInX0, 1e-3); + CHECK_CLOSE_REL(bwdStepStepMaterialInL0, bwdStepMaterialInL0, 1e-3); + + // get the backward output to the screen + if (debugModeBwdStep) { + const auto& bwdStepOutput = + bwdStepFinal.template get<DebugOutput::result_type>(); + std::cout << ">>> Backward final step propgation & navigation output " + << std::endl; + std::cout << bwdStepOutput.debugString << std::endl; } +} + +// This test case checks that no segmentation fault appears +// - this tests the collection of surfaces +BOOST_DATA_TEST_CASE( + test_material_collector, + bdata::random((bdata::seed = 20, + bdata::distribution = std::uniform_real_distribution<>( + 0.5 * units::_GeV, 10. * units::_GeV))) ^ + bdata::random((bdata::seed = 21, + bdata::distribution = + std::uniform_real_distribution<>(-M_PI, M_PI))) ^ + bdata::random((bdata::seed = 22, + bdata::distribution = + std::uniform_real_distribution<>(1.0, M_PI - 1.0))) ^ + bdata::random( + (bdata::seed = 23, + bdata::distribution = std::uniform_int_distribution<>(0, 1))) ^ + bdata::xrange(ntests), + pT, phi, theta, charge, index) { + runTest(epropagator, pT, phi, theta, charge, index); + runTest(slpropagator, pT, phi, theta, charge, index); +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/Propagator/NavigatorTests.cpp b/Tests/Core/Propagator/NavigatorTests.cpp index 8dbddcfef87c2b2202e47a91254dbc9c5f1dea0f..9c24f51d8be8c8a72d6cb523de3f0de4ec51e238 100644 --- a/Tests/Core/Propagator/NavigatorTests.cpp +++ b/Tests/Core/Propagator/NavigatorTests.cpp @@ -30,7 +30,7 @@ #include "Acts/Geometry/GeometryContext.hpp" namespace bdata = boost::unit_test::data; -namespace tt = boost::test_tools; +namespace tt = boost::test_tools; namespace Acts { @@ -38,466 +38,411 @@ using VectorHelpers::perp; namespace Test { - // Create a test context - GeometryContext tgContext = GeometryContext(); - - /// This is a simple cache struct to mimic the - /// Propagator cache - struct PropagatorState - { - /// This is a simple cache struct to mimic a Stepper - struct Stepper - { - // comply with concept - using Jacobian = ActsMatrixD<5, 5>; - using Covariance = ActsSymMatrixD<5>; - using BoundState = std::tuple<BoundParameters, Jacobian, double>; - using CurvilinearState - = std::tuple<CurvilinearParameters, Jacobian, double>; - using Corrector = VoidIntersectionCorrector; - - template <typename, typename> - using return_parameter_type = void; - - /// This is a simple cache struct to mimic the - /// Stepper cache in the propagation - struct State - { - /// Position - Vector3D pos = Vector3D(0., 0., 0.); - - /// Direction - Vector3D dir = Vector3D(1., 0., 0.); - - /// Momentum - double p; - - /// Charge - double q; - - /// the navigation direction - NavigationDirection navDir = forward; - - // accummulated path length cache - double pathAccumulated = 0.; - - // adaptive sep size of the runge-kutta integration - Cstep stepSize = Cstep(100 * units::_cm); - }; - - /// Global particle position accessor - Vector3D - position(const State& state) const - { - return state.pos; - } - - /// Momentum direction accessor - Vector3D - direction(const State& state) const - { - return state.dir; - } - - /// Momentum accessor - double - momentum(const State& state) const - { - return state.p; - } - - /// Charge access - double - charge(const State& state) const - { - return state.q; - } - - /// Return a corrector - VoidIntersectionCorrector - corrector(State& /*unused*/) const - { - return VoidIntersectionCorrector(); - } - - bool - surfaceReached(const State& state, const Surface* surface) const - { - return surface->isOnSurface( - tgContext, position(state), direction(state), true); - } - - BoundState - boundState(State& state, - const Surface& surface, - bool reinitialize = true) const - { - // suppress unused warning - (void)reinitialize; - BoundParameters parameters(tgContext, - nullptr, - state.pos, - state.p * state.dir, - state.q, - surface.getSharedPtr()); - BoundState bState{ - std::move(parameters), Jacobian::Identity(), state.pathAccumulated}; - return bState; - } - - CurvilinearState - curvilinearState(State& state, bool reinitialize = true) const - { - (void)reinitialize; - CurvilinearParameters parameters( - nullptr, state.pos, state.p * state.dir, state.q); - // Create the bound state - CurvilinearState curvState{ - std::move(parameters), Jacobian::Identity(), state.pathAccumulated}; - return curvState; - } - - void - update(State& /*state*/, const BoundParameters& /*pars*/) const - { - } - - void - update(State& /*state*/, - const Vector3D& /*uposition*/, - const Vector3D& /*udirection*/, - double /*up*/) const - { - } - - void - covarianceTransport(State& /*state*/, bool /*reinitialize = false*/) const - { - } - - void - covarianceTransport(State& /*unused*/, - const Surface& /*surface*/, - bool /*reinitialize = false*/) const - { - } - - Vector3D - getField(State& /*state*/, const Vector3D& /*pos*/) const - { - // get the field from the cell - return Vector3D(0., 0., 0.); - } - }; +// Create a test context +GeometryContext tgContext = GeometryContext(); + +/// This is a simple cache struct to mimic the +/// Propagator cache +struct PropagatorState { + /// This is a simple cache struct to mimic a Stepper + struct Stepper { + // comply with concept + using Jacobian = ActsMatrixD<5, 5>; + using Covariance = ActsSymMatrixD<5>; + using BoundState = std::tuple<BoundParameters, Jacobian, double>; + using CurvilinearState = + std::tuple<CurvilinearParameters, Jacobian, double>; + using Corrector = VoidIntersectionCorrector; + + template <typename, typename> + using return_parameter_type = void; + + /// This is a simple cache struct to mimic the + /// Stepper cache in the propagation + struct State { + /// Position + Vector3D pos = Vector3D(0., 0., 0.); + + /// Direction + Vector3D dir = Vector3D(1., 0., 0.); + + /// Momentum + double p; - static_assert(StepperConcept<Stepper>, - "Dummy stepper does not fulfill concept"); - - /// emulate the options template - struct Options - { - /// Debug output - /// the string where debug messages are stored (optionally) - bool debug = false; - std::string debugString = ""; - /// buffer & formatting for consistent output - size_t debugPfxWidth = 30; - size_t debugMsgWidth = 50; + /// Charge + double q; + + /// the navigation direction + NavigationDirection navDir = forward; + + // accummulated path length cache + double pathAccumulated = 0.; + + // adaptive sep size of the runge-kutta integration + Cstep stepSize = Cstep(100 * units::_cm); }; - /// Navigation cache: the start surface - const Surface* startSurface = nullptr; + /// Global particle position accessor + Vector3D position(const State& state) const { return state.pos; } - /// Navigation cache: the current surface - const Surface* currentSurface = nullptr; + /// Momentum direction accessor + Vector3D direction(const State& state) const { return state.dir; } - /// Navigation cache: the target surface - const Surface* targetSurface = nullptr; - bool targetReached = false; + /// Momentum accessor + double momentum(const State& state) const { return state.p; } - /// Give some options - Options options; + /// Charge access + double charge(const State& state) const { return state.q; } - /// The Stepper state - internal statew of the Stepper - Stepper::State stepping; + /// Return a corrector + VoidIntersectionCorrector corrector(State& /*unused*/) const { + return VoidIntersectionCorrector(); + } - /// Navigation state - internal state of the Navigator - Navigator::State navigation; + bool surfaceReached(const State& state, const Surface* surface) const { + return surface->isOnSurface(tgContext, position(state), direction(state), + true); + } - // The context cache for this propagation - GeometryContext geoContext = GeometryContext(); + BoundState boundState(State& state, const Surface& surface, + bool reinitialize = true) const { + // suppress unused warning + (void)reinitialize; + BoundParameters parameters(tgContext, nullptr, state.pos, + state.p * state.dir, state.q, + surface.getSharedPtr()); + BoundState bState{std::move(parameters), Jacobian::Identity(), + state.pathAccumulated}; + return bState; + } + + CurvilinearState curvilinearState(State& state, + bool reinitialize = true) const { + (void)reinitialize; + CurvilinearParameters parameters(nullptr, state.pos, state.p * state.dir, + state.q); + // Create the bound state + CurvilinearState curvState{std::move(parameters), Jacobian::Identity(), + state.pathAccumulated}; + return curvState; + } + + void update(State& /*state*/, const BoundParameters& /*pars*/) const {} + + void update(State& /*state*/, const Vector3D& /*uposition*/, + const Vector3D& /*udirection*/, double /*up*/) const {} + + void covarianceTransport(State& /*state*/, + bool /*reinitialize = false*/) const {} + + void covarianceTransport(State& /*unused*/, const Surface& /*surface*/, + bool /*reinitialize = false*/) const {} + + Vector3D getField(State& /*state*/, const Vector3D& /*pos*/) const { + // get the field from the cell + return Vector3D(0., 0., 0.); + } }; - template <typename stepper_state_t> - void - step(stepper_state_t& sstate) - { - // update the cache position - sstate.pos = sstate.pos + sstate.stepSize * sstate.dir; - // create navigation parameters - return; - } + static_assert(StepperConcept<Stepper>, + "Dummy stepper does not fulfill concept"); + + /// emulate the options template + struct Options { + /// Debug output + /// the string where debug messages are stored (optionally) + bool debug = false; + std::string debugString = ""; + /// buffer & formatting for consistent output + size_t debugPfxWidth = 30; + size_t debugMsgWidth = 50; + }; - // the surface cache & the creation of the geometry + /// Navigation cache: the start surface + const Surface* startSurface = nullptr; - CylindricalTrackingGeometry cGeometry(tgContext); - auto tGeometry = cGeometry(); + /// Navigation cache: the current surface + const Surface* currentSurface = nullptr; - // the debug boolean - bool debug = true; + /// Navigation cache: the target surface + const Surface* targetSurface = nullptr; + bool targetReached = false; - BOOST_AUTO_TEST_CASE(Navigator_methods) - { + /// Give some options + Options options; - // create a navigator - Navigator navigator; - navigator.trackingGeometry = tGeometry; - navigator.resolveSensitive = true; - navigator.resolveMaterial = true; - navigator.resolvePassive = false; + /// The Stepper state - internal statew of the Stepper + Stepper::State stepping; - // position and direction vector - Vector3D position(0., 0., 0); - Vector3D momentum(1., 1., 0); + /// Navigation state - internal state of the Navigator + Navigator::State navigation; - // the propagator cache - PropagatorState state; - state.options.debug = debug; + // The context cache for this propagation + GeometryContext geoContext = GeometryContext(); +}; - // the stepper cache - state.stepping.pos = position; - state.stepping.dir = momentum.normalized(); +template <typename stepper_state_t> +void step(stepper_state_t& sstate) { + // update the cache position + sstate.pos = sstate.pos + sstate.stepSize * sstate.dir; + // create navigation parameters + return; +} - // foward navigation ---------------------------------------------- - if (debug) { - std::cout << "<<<<<<<<<<<<<<<<<<<<< FORWARD NAVIGATION >>>>>>>>>>>>>>>>>>" - << std::endl; - } +// the surface cache & the creation of the geometry - // Stepper - PropagatorState::Stepper stepper; +CylindricalTrackingGeometry cGeometry(tgContext); +auto tGeometry = cGeometry(); - // (1) Initialization navigation from start point - // - this will call resolveLayers() as well - // - and thus should call a return to the stepper - navigator.status(state, stepper); - // Check that the currentVolume is set - BOOST_CHECK_NE(state.navigation.currentVolume, nullptr); - // Check that the currentVolume is the startVolume - BOOST_CHECK_EQUAL(state.navigation.currentVolume, - state.navigation.startVolume); - // Check that the currentSurface is reset to: - BOOST_CHECK_EQUAL(state.navigation.currentSurface, nullptr); - // No layer has been found - BOOST_CHECK_EQUAL(state.navigation.navLayers.size(), 0); - // ACTORS-ABORTERS-TARGET - navigator.target(state, stepper); - // A layer has been found - BOOST_CHECK_EQUAL(state.navigation.navLayers.size(), 1); - // The iterator should points to the begin - BOOST_CHECK(state.navigation.navLayerIter - == state.navigation.navLayers.begin()); - // Cache the beam pipe radius - double beamPipeRadius - = perp(state.navigation.navLayerIter->intersection.position); - // step size has been updated - CHECK_CLOSE_ABS( - state.stepping.stepSize, beamPipeRadius, s_onSurfaceTolerance); - if (debug) { - std::cout << "<<< Test 1a >>> initialize at " - << toString(state.stepping.pos) << std::endl; - std::cout << state.options.debugString << std::endl; - // Clear the debug string for the next test - state.options.debugString = ""; - } +// the debug boolean +bool debug = true; - // Do the step towards the beam pipe - step(state.stepping); +BOOST_AUTO_TEST_CASE(Navigator_methods) { + // create a navigator + Navigator navigator; + navigator.trackingGeometry = tGeometry; + navigator.resolveSensitive = true; + navigator.resolveMaterial = true; + navigator.resolvePassive = false; - // (2) re-entering navigator: - // STATUS - navigator.status(state, stepper); - // Check that the currentVolume is the still startVolume - BOOST_CHECK_EQUAL(state.navigation.currentVolume, - state.navigation.startVolume); - // The layer number has not changed - BOOST_CHECK_EQUAL(state.navigation.navLayers.size(), 1); - // The iterator still points to the begin - BOOST_CHECK( - (state.navigation.navLayerIter == state.navigation.navLayers.begin())); - // ACTORS-ABORTERS-TARGET - navigator.target(state, stepper); + // position and direction vector + Vector3D position(0., 0., 0); + Vector3D momentum(1., 1., 0); - if (debug) { - std::cout << "<<< Test 1b >>> step to the BeamPipe at " - << toString(state.stepping.pos) << std::endl; - std::cout << state.options.debugString << std::endl; - state.options.debugString = ""; - } + // the propagator cache + PropagatorState state; + state.options.debug = debug; - // Do the step towards the boundary - step(state.stepping); + // the stepper cache + state.stepping.pos = position; + state.stepping.dir = momentum.normalized(); - // (3) re-entering navigator: - // STATUS - navigator.status(state, stepper); - // ACTORS-ABORTERS-TARGET - navigator.target(state, stepper); + // foward navigation ---------------------------------------------- + if (debug) { + std::cout << "<<<<<<<<<<<<<<<<<<<<< FORWARD NAVIGATION >>>>>>>>>>>>>>>>>>" + << std::endl; + } - if (debug) { - std::cout << "<<< Test 1c >>> step to the Boundary at " - << toString(state.stepping.pos) << std::endl; - std::cout << state.options.debugString << std::endl; - state.options.debugString = ""; - } + // Stepper + PropagatorState::Stepper stepper; + + // (1) Initialization navigation from start point + // - this will call resolveLayers() as well + // - and thus should call a return to the stepper + navigator.status(state, stepper); + // Check that the currentVolume is set + BOOST_CHECK_NE(state.navigation.currentVolume, nullptr); + // Check that the currentVolume is the startVolume + BOOST_CHECK_EQUAL(state.navigation.currentVolume, + state.navigation.startVolume); + // Check that the currentSurface is reset to: + BOOST_CHECK_EQUAL(state.navigation.currentSurface, nullptr); + // No layer has been found + BOOST_CHECK_EQUAL(state.navigation.navLayers.size(), 0); + // ACTORS-ABORTERS-TARGET + navigator.target(state, stepper); + // A layer has been found + BOOST_CHECK_EQUAL(state.navigation.navLayers.size(), 1); + // The iterator should points to the begin + BOOST_CHECK(state.navigation.navLayerIter == + state.navigation.navLayers.begin()); + // Cache the beam pipe radius + double beamPipeRadius = + perp(state.navigation.navLayerIter->intersection.position); + // step size has been updated + CHECK_CLOSE_ABS(state.stepping.stepSize, beamPipeRadius, + s_onSurfaceTolerance); + if (debug) { + std::cout << "<<< Test 1a >>> initialize at " + << toString(state.stepping.pos) << std::endl; + std::cout << state.options.debugString << std::endl; + // Clear the debug string for the next test + state.options.debugString = ""; + } - // positive return: do the step - step(state.stepping); - // (4) re-entering navigator: - // STATUS - navigator.status(state, stepper); - // ACTORS-ABORTERS-TARGET - navigator.target(state, stepper); + // Do the step towards the beam pipe + step(state.stepping); + + // (2) re-entering navigator: + // STATUS + navigator.status(state, stepper); + // Check that the currentVolume is the still startVolume + BOOST_CHECK_EQUAL(state.navigation.currentVolume, + state.navigation.startVolume); + // The layer number has not changed + BOOST_CHECK_EQUAL(state.navigation.navLayers.size(), 1); + // The iterator still points to the begin + BOOST_CHECK( + (state.navigation.navLayerIter == state.navigation.navLayers.begin())); + // ACTORS-ABORTERS-TARGET + navigator.target(state, stepper); + + if (debug) { + std::cout << "<<< Test 1b >>> step to the BeamPipe at " + << toString(state.stepping.pos) << std::endl; + std::cout << state.options.debugString << std::endl; + state.options.debugString = ""; + } - if (debug) { - std::cout << "<<< Test 1d >>> step to 1st layer at " - << toString(state.stepping.pos) << std::endl; - std::cout << state.options.debugString << std::endl; - state.options.debugString = ""; - } + // Do the step towards the boundary + step(state.stepping); - // Step through the surfaces on first layer - for (size_t isf = 0; isf < 5; ++isf) { - - step(state.stepping); - // (5-9) re-entering navigator: - // STATUS - navigator.status(state, stepper); - // ACTORS-ABORTERS-TARGET - navigator.target(state, stepper); - - if (debug) { - std::cout << "<<< Test 1e-1i >>> step within 1st layer at " - << toString(state.stepping.pos) << std::endl; - std::cout << state.options.debugString << std::endl; - state.options.debugString = ""; - } - } + // (3) re-entering navigator: + // STATUS + navigator.status(state, stepper); + // ACTORS-ABORTERS-TARGET + navigator.target(state, stepper); - // positive return: do the step + if (debug) { + std::cout << "<<< Test 1c >>> step to the Boundary at " + << toString(state.stepping.pos) << std::endl; + std::cout << state.options.debugString << std::endl; + state.options.debugString = ""; + } + + // positive return: do the step + step(state.stepping); + // (4) re-entering navigator: + // STATUS + navigator.status(state, stepper); + // ACTORS-ABORTERS-TARGET + navigator.target(state, stepper); + + if (debug) { + std::cout << "<<< Test 1d >>> step to 1st layer at " + << toString(state.stepping.pos) << std::endl; + std::cout << state.options.debugString << std::endl; + state.options.debugString = ""; + } + + // Step through the surfaces on first layer + for (size_t isf = 0; isf < 5; ++isf) { step(state.stepping); - // (10) re-entering navigator: + // (5-9) re-entering navigator: // STATUS navigator.status(state, stepper); // ACTORS-ABORTERS-TARGET navigator.target(state, stepper); if (debug) { - std::cout << "<<< Test 1j >>> step to 2nd layer at " + std::cout << "<<< Test 1e-1i >>> step within 1st layer at " << toString(state.stepping.pos) << std::endl; std::cout << state.options.debugString << std::endl; state.options.debugString = ""; } + } - // Step through the surfaces on second layer - for (size_t isf = 0; isf < 5; ++isf) { - - step(state.stepping); - // (11-15) re-entering navigator: - // STATUS - navigator.status(state, stepper); - // ACTORS-ABORTERS-TARGET - navigator.target(state, stepper); - - if (debug) { - std::cout << "<<< Test 1k-1o >>> step within 2nd layer at " - << toString(state.stepping.pos) << std::endl; - std::cout << state.options.debugString << std::endl; - state.options.debugString = ""; - } - } + // positive return: do the step + step(state.stepping); + // (10) re-entering navigator: + // STATUS + navigator.status(state, stepper); + // ACTORS-ABORTERS-TARGET + navigator.target(state, stepper); + + if (debug) { + std::cout << "<<< Test 1j >>> step to 2nd layer at " + << toString(state.stepping.pos) << std::endl; + std::cout << state.options.debugString << std::endl; + state.options.debugString = ""; + } - // positive return: do the step + // Step through the surfaces on second layer + for (size_t isf = 0; isf < 5; ++isf) { step(state.stepping); - // (16) re-entering navigator: + // (11-15) re-entering navigator: // STATUS navigator.status(state, stepper); // ACTORS-ABORTERS-TARGET navigator.target(state, stepper); if (debug) { - std::cout << "<<< Test 1p >>> step to 3rd layer at " + std::cout << "<<< Test 1k-1o >>> step within 2nd layer at " << toString(state.stepping.pos) << std::endl; std::cout << state.options.debugString << std::endl; state.options.debugString = ""; } + } - // Step through the surfaces on third layer - for (size_t isf = 0; isf < 3; ++isf) { - - step(state.stepping); - // (17-19) re-entering navigator: - // STATUS - navigator.status(state, stepper); - // ACTORS-ABORTERS-TARGET - navigator.target(state, stepper); - - if (debug) { - std::cout << "<<< Test 1q-1s >>> step within 3rd layer at " - << toString(state.stepping.pos) << std::endl; - std::cout << state.options.debugString << std::endl; - state.options.debugString = ""; - } - } + // positive return: do the step + step(state.stepping); + // (16) re-entering navigator: + // STATUS + navigator.status(state, stepper); + // ACTORS-ABORTERS-TARGET + navigator.target(state, stepper); + + if (debug) { + std::cout << "<<< Test 1p >>> step to 3rd layer at " + << toString(state.stepping.pos) << std::endl; + std::cout << state.options.debugString << std::endl; + state.options.debugString = ""; + } - // positive return: do the step + // Step through the surfaces on third layer + for (size_t isf = 0; isf < 3; ++isf) { step(state.stepping); - // (20) re-entering navigator: + // (17-19) re-entering navigator: // STATUS navigator.status(state, stepper); // ACTORS-ABORTERS-TARGET navigator.target(state, stepper); if (debug) { - std::cout << "<<< Test 1t >>> step to 4th layer at " + std::cout << "<<< Test 1q-1s >>> step within 3rd layer at " << toString(state.stepping.pos) << std::endl; std::cout << state.options.debugString << std::endl; state.options.debugString = ""; } + } - // Step through the surfaces on second layer - for (size_t isf = 0; isf < 3; ++isf) { - - step(state.stepping); - // (21-23) re-entering navigator: - // STATUS - navigator.status(state, stepper); - // ACTORS-ABORTERS-TARGET - navigator.target(state, stepper); - - if (debug) { - std::cout << "<<< Test 1t-1v >>> step within 4th layer at " - << toString(state.stepping.pos) << std::endl; - std::cout << state.options.debugString << std::endl; - state.options.debugString = ""; - } - } + // positive return: do the step + step(state.stepping); + // (20) re-entering navigator: + // STATUS + navigator.status(state, stepper); + // ACTORS-ABORTERS-TARGET + navigator.target(state, stepper); + + if (debug) { + std::cout << "<<< Test 1t >>> step to 4th layer at " + << toString(state.stepping.pos) << std::endl; + std::cout << state.options.debugString << std::endl; + state.options.debugString = ""; + } - // positive return: do the step + // Step through the surfaces on second layer + for (size_t isf = 0; isf < 3; ++isf) { step(state.stepping); - // (24) re-entering navigator: + // (21-23) re-entering navigator: // STATUS navigator.status(state, stepper); // ACTORS-ABORTERS-TARGET navigator.target(state, stepper); if (debug) { - std::cout << "<<< Test 1w >>> step to boundary at " + std::cout << "<<< Test 1t-1v >>> step within 4th layer at " << toString(state.stepping.pos) << std::endl; std::cout << state.options.debugString << std::endl; state.options.debugString = ""; } } + // positive return: do the step + step(state.stepping); + // (24) re-entering navigator: + // STATUS + navigator.status(state, stepper); + // ACTORS-ABORTERS-TARGET + navigator.target(state, stepper); + + if (debug) { + std::cout << "<<< Test 1w >>> step to boundary at " + << toString(state.stepping.pos) << std::endl; + std::cout << state.options.debugString << std::endl; + state.options.debugString = ""; + } +} + } // namespace Test } // namespace Acts diff --git a/Tests/Core/Propagator/PropagatorTests.cpp b/Tests/Core/Propagator/PropagatorTests.cpp index 6005a5d88a51c0f83b27f3a4b4460cc5c451eaa2..755ce9c0f84845755f5012a9cc91357df988bde0 100644 --- a/Tests/Core/Propagator/PropagatorTests.cpp +++ b/Tests/Core/Propagator/PropagatorTests.cpp @@ -29,7 +29,7 @@ #include "Acts/MagneticField/MagneticFieldContext.hpp" namespace bdata = boost::unit_test::data; -namespace tt = boost::test_tools; +namespace tt = boost::test_tools; using Acts::VectorHelpers::perp; @@ -37,349 +37,302 @@ namespace Acts { namespace Test { - // Create a test context - GeometryContext tgContext = GeometryContext(); - MagneticFieldContext mfContext = MagneticFieldContext(); +// Create a test context +GeometryContext tgContext = GeometryContext(); +MagneticFieldContext mfContext = MagneticFieldContext(); - using cstep = detail::ConstrainedStep; +using cstep = detail::ConstrainedStep; - /// An observer that measures the perpendicular distance - struct PerpendicularMeasure - { - - /// Simple result struct to be returned - struct this_result - { - double distance = std::numeric_limits<double>::max(); - }; +/// An observer that measures the perpendicular distance +struct PerpendicularMeasure { + /// Simple result struct to be returned + struct this_result { + double distance = std::numeric_limits<double>::max(); + }; - using result_type = this_result; + using result_type = this_result; - PerpendicularMeasure() = default; + PerpendicularMeasure() = default; - template <typename propagator_state_t, typename stepper_t> - void - operator()(propagator_state_t& state, - const stepper_t& stepper, - result_type& result) const - { - result.distance = perp(stepper.position(state.stepping)); - } + template <typename propagator_state_t, typename stepper_t> + void operator()(propagator_state_t& state, const stepper_t& stepper, + result_type& result) const { + result.distance = perp(stepper.position(state.stepping)); + } - template <typename propagator_state_t, typename stepper_t> - void - operator()(propagator_state_t& /*unused*/, - const stepper_t& /*unused*/) const - { - } + template <typename propagator_state_t, typename stepper_t> + void operator()(propagator_state_t& /*unused*/, + const stepper_t& /*unused*/) const {} +}; + +/// An observer that measures the perpendicular distance +template <typename Surface> +struct SurfaceObserver { + // the surface to be intersected + const Surface* surface = nullptr; + // the tolerance for intersection + double tolerance = 1.e-5; + + /// Simple result struct to be returned + struct this_result { + size_t surfaces_passed = 0; + double surface_passed_r = std::numeric_limits<double>::max(); }; - /// An observer that measures the perpendicular distance - template <typename Surface> - struct SurfaceObserver - { - - // the surface to be intersected - const Surface* surface = nullptr; - // the tolerance for intersection - double tolerance = 1.e-5; - - /// Simple result struct to be returned - struct this_result - { - size_t surfaces_passed = 0; - double surface_passed_r = std::numeric_limits<double>::max(); - }; - - using result_type = this_result; - - SurfaceObserver() = default; - - template <typename propagator_state_t, typename stepper_t> - void - operator()(propagator_state_t& state, - const stepper_t& stepper, - result_type& result) const - { - if (surface && !result.surfaces_passed) { - // calculate the distance to the surface - const double distance - = surface - ->intersectionEstimate(state.geoContext, - stepper.position(state.stepping), - stepper.direction(state.stepping), - forward, - true) - .pathLength; - // Adjust the step size so that we cannot cross the target surface - state.stepping.stepSize.update(distance, cstep::actor); - // return true if you fall below tolerance - if (std::abs(distance) <= tolerance) { - ++result.surfaces_passed; - result.surface_passed_r = perp(stepper.position(state.stepping)); - // release the step size, will be re-adjusted - state.stepping.stepSize.release(cstep::actor); - } + using result_type = this_result; + + SurfaceObserver() = default; + + template <typename propagator_state_t, typename stepper_t> + void operator()(propagator_state_t& state, const stepper_t& stepper, + result_type& result) const { + if (surface && !result.surfaces_passed) { + // calculate the distance to the surface + const double distance = + surface + ->intersectionEstimate( + state.geoContext, stepper.position(state.stepping), + stepper.direction(state.stepping), forward, true) + .pathLength; + // Adjust the step size so that we cannot cross the target surface + state.stepping.stepSize.update(distance, cstep::actor); + // return true if you fall below tolerance + if (std::abs(distance) <= tolerance) { + ++result.surfaces_passed; + result.surface_passed_r = perp(stepper.position(state.stepping)); + // release the step size, will be re-adjusted + state.stepping.stepSize.release(cstep::actor); } } - - template <typename propagator_state_t, typename stepper_t> - void - operator()(propagator_state_t& /*unused*/, - const stepper_t& /*unused*/) const - { - } - }; - - // Global definitions - // The path limit abort - using path_limit = detail::PathLimitReached; - - using BFieldType = ConstantBField; - using EigenStepperType = EigenStepper<BFieldType>; - using EigenPropagatorType = Propagator<EigenStepperType>; - - const double Bz = 2. * units::_T; - BFieldType bField(0, 0, Bz); - EigenStepperType estepper(bField); - EigenPropagatorType epropagator(std::move(estepper)); - - auto mSurface - = Surface::makeShared<CylinderSurface>(nullptr, 10., 1000. * units::_mm); - auto cSurface - = Surface::makeShared<CylinderSurface>(nullptr, 150., 1000. * units::_mm); - - const int ntests = 5; - - // This tests the Options - BOOST_AUTO_TEST_CASE(PropagatorOptions_) - { - - using null_optionsType = PropagatorOptions<>; - null_optionsType null_options(tgContext, mfContext); - // todo write null options test - - using ActionListType = ActionList<PerpendicularMeasure>; - using AbortConditionsType = AbortList<>; - - using optionsType = PropagatorOptions<ActionListType, AbortConditionsType>; - - optionsType options(tgContext, mfContext); } - BOOST_DATA_TEST_CASE( - cylinder_passage_observer_, - bdata::random((bdata::seed = 0, - bdata::distribution - = std::uniform_real_distribution<>(0.4 * units::_GeV, - 10. * units::_GeV))) - ^ bdata::random((bdata::seed = 1, - bdata::distribution - = std::uniform_real_distribution<>(-M_PI, M_PI))) - ^ bdata::random((bdata::seed = 2, - bdata::distribution - = std::uniform_real_distribution<>(1.0, M_PI - 1.0))) - ^ bdata::random((bdata::seed = 3, - bdata::distribution - = std::uniform_int_distribution<>(0, 1))) - ^ bdata::xrange(ntests), - pT, - phi, - theta, - charge, - index) - { - double dcharge = -1 + 2 * charge; - (void)index; - - using CylinderObserver = SurfaceObserver<CylinderSurface>; - using ActionListType = ActionList<CylinderObserver>; - using AbortConditionsType = AbortList<>; - - // setup propagation options - PropagatorOptions<ActionListType, AbortConditionsType> options(tgContext, - mfContext); - - options.pathLimit = 20 * units::_m; - options.maxStepSize = 1 * units::_cm; - - // set the surface to be passed by - options.actionList.get<CylinderObserver>().surface = mSurface.get(); - - using so_result = typename CylinderObserver::result_type; - - // define start parameters - double x = 0; - double y = 0; - double z = 0; - double px = pT * cos(phi); - double py = pT * sin(phi); - double pz = pT / tan(theta); - double q = dcharge; - Vector3D pos(x, y, z); - Vector3D mom(px, py, pz); - CurvilinearParameters start(nullptr, pos, mom, q); - // propagate to the cylinder surface - const auto& result - = epropagator.propagate(start, *cSurface, options).value(); - auto& sor = result.get<so_result>(); - - BOOST_CHECK_EQUAL(sor.surfaces_passed, 1); - CHECK_CLOSE_ABS(sor.surface_passed_r, 10., 1e-5); - } - - BOOST_DATA_TEST_CASE( - curvilinear_additive_, - bdata::random((bdata::seed = 0, - bdata::distribution - = std::uniform_real_distribution<>(0.4 * units::_GeV, - 10. * units::_GeV))) - ^ bdata::random((bdata::seed = 1, - bdata::distribution - = std::uniform_real_distribution<>(-M_PI, M_PI))) - ^ bdata::random((bdata::seed = 2, - bdata::distribution - = std::uniform_real_distribution<>(1.0, M_PI - 1.0))) - ^ bdata::random((bdata::seed = 3, - bdata::distribution - = std::uniform_int_distribution<>(0, 1))) - ^ bdata::xrange(ntests), - pT, - phi, - theta, - charge, - index) - { - double dcharge = -1 + 2 * charge; - (void)index; - - // setup propagation options - the tow step options - PropagatorOptions<> options_2s(tgContext, mfContext); - options_2s.pathLimit = 50 * units::_cm; - options_2s.maxStepSize = 1 * units::_cm; - - // define start parameters - double x = 0; - double y = 0; - double z = 0; - double px = pT * cos(phi); - double py = pT * sin(phi); - double pz = pT / tan(theta); - double q = dcharge; - Vector3D pos(x, y, z); - Vector3D mom(px, py, pz); - /// a covariance matrix to transport - ActsSymMatrixD<5> cov; - // take some major correlations (off-diagonals) - cov << 10 * units::_mm, 0, 0.123, 0, 0.5, 0, 10 * units::_mm, 0, 0.162, 0, - 0.123, 0, 0.1, 0, 0, 0, 0.162, 0, 0.1, 0, 0.5, 0, 0, 0, - 1. / (10 * units::_GeV); - auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); - CurvilinearParameters start(std::move(covPtr), pos, mom, q); - // propagate to a path length of 100 with two steps of 50 - const auto& mid_parameters - = epropagator.propagate(start, options_2s).value().endParameters; - const auto& end_parameters_2s - = epropagator.propagate(*mid_parameters, options_2s) - .value() - .endParameters; - - // setup propagation options - the one step options - PropagatorOptions<> options_1s(tgContext, mfContext); - options_1s.pathLimit = 100 * units::_cm; - options_1s.maxStepSize = 1 * units::_cm; - // propagate to a path length of 100 in one step - const auto& end_parameters_1s - = epropagator.propagate(start, options_1s).value().endParameters; - - // test that the propagation is additive - CHECK_CLOSE_REL( - end_parameters_1s->position(), end_parameters_2s->position(), 0.001); - - const auto& cov_1s = *(end_parameters_1s->covariance()); - const auto& cov_2s = *(end_parameters_2s->covariance()); - - CHECK_CLOSE_COVARIANCE(cov_1s, cov_2s, 0.001); - } - - BOOST_DATA_TEST_CASE( - cylinder_additive_, - bdata::random((bdata::seed = 0, - bdata::distribution - = std::uniform_real_distribution<>(0.4 * units::_GeV, - 10. * units::_GeV))) - ^ bdata::random((bdata::seed = 1, - bdata::distribution - = std::uniform_real_distribution<>(-M_PI, M_PI))) - ^ bdata::random((bdata::seed = 2, - bdata::distribution - = std::uniform_real_distribution<>(1.0, M_PI - 1.0))) - ^ bdata::random((bdata::seed = 3, - bdata::distribution - = std::uniform_int_distribution<>(0, 1))) - ^ bdata::xrange(ntests), - pT, - phi, - theta, - charge, - index) - { - double dcharge = -1 + 2 * charge; - (void)index; - - // setup propagation options - 2 setp options - PropagatorOptions<> options_2s(tgContext, mfContext); - options_2s.pathLimit = 10 * units::_m; - options_2s.maxStepSize = 1 * units::_cm; - - // define start parameters - double x = 0; - double y = 0; - double z = 0; - double px = pT * cos(phi); - double py = pT * sin(phi); - double pz = pT / tan(theta); - double q = dcharge; - Vector3D pos(x, y, z); - Vector3D mom(px, py, pz); - /// a covariance matrix to transport - ActsSymMatrixD<5> cov; - // take some major correlations (off-diagonals) - cov << 10 * units::_mm, 0, 0.123, 0, 0.5, 0, 10 * units::_mm, 0, 0.162, 0, - 0.123, 0, 0.1, 0, 0, 0, 0.162, 0, 0.1, 0, 0.5, 0, 0, 0, - 1. / (10 * units::_GeV); - auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); - CurvilinearParameters start(std::move(covPtr), pos, mom, q); - // propagate to a final surface with one stop in between - const auto& mid_parameters - = epropagator.propagate(start, *mSurface, options_2s) - .value() - .endParameters; - - const auto& end_parameters_2s - = epropagator.propagate(*mid_parameters, *cSurface, options_2s) - .value() - .endParameters; - - // setup propagation options - one step options - PropagatorOptions<> options_1s(tgContext, mfContext); - options_1s.pathLimit = 10 * units::_m; - options_1s.maxStepSize = 1 * units::_cm; - // propagate to a final surface in one stop - const auto& end_parameters_1s - = epropagator.propagate(start, *cSurface, options_1s) - .value() - .endParameters; - - // test that the propagation is additive - CHECK_CLOSE_REL( - end_parameters_1s->position(), end_parameters_2s->position(), 0.001); - - const auto& cov_1s = *(end_parameters_1s->covariance()); - const auto& cov_2s = *(end_parameters_2s->covariance()); - - CHECK_CLOSE_COVARIANCE(cov_1s, cov_2s, 0.001); - } + template <typename propagator_state_t, typename stepper_t> + void operator()(propagator_state_t& /*unused*/, + const stepper_t& /*unused*/) const {} +}; + +// Global definitions +// The path limit abort +using path_limit = detail::PathLimitReached; + +using BFieldType = ConstantBField; +using EigenStepperType = EigenStepper<BFieldType>; +using EigenPropagatorType = Propagator<EigenStepperType>; + +const double Bz = 2. * units::_T; +BFieldType bField(0, 0, Bz); +EigenStepperType estepper(bField); +EigenPropagatorType epropagator(std::move(estepper)); + +auto mSurface = + Surface::makeShared<CylinderSurface>(nullptr, 10., 1000. * units::_mm); +auto cSurface = + Surface::makeShared<CylinderSurface>(nullptr, 150., 1000. * units::_mm); + +const int ntests = 5; + +// This tests the Options +BOOST_AUTO_TEST_CASE(PropagatorOptions_) { + using null_optionsType = PropagatorOptions<>; + null_optionsType null_options(tgContext, mfContext); + // todo write null options test + + using ActionListType = ActionList<PerpendicularMeasure>; + using AbortConditionsType = AbortList<>; + + using optionsType = PropagatorOptions<ActionListType, AbortConditionsType>; + + optionsType options(tgContext, mfContext); +} + +BOOST_DATA_TEST_CASE( + cylinder_passage_observer_, + bdata::random((bdata::seed = 0, + bdata::distribution = std::uniform_real_distribution<>( + 0.4 * units::_GeV, 10. * units::_GeV))) ^ + bdata::random((bdata::seed = 1, + bdata::distribution = + std::uniform_real_distribution<>(-M_PI, M_PI))) ^ + bdata::random((bdata::seed = 2, + bdata::distribution = + std::uniform_real_distribution<>(1.0, M_PI - 1.0))) ^ + bdata::random( + (bdata::seed = 3, + bdata::distribution = std::uniform_int_distribution<>(0, 1))) ^ + bdata::xrange(ntests), + pT, phi, theta, charge, index) { + double dcharge = -1 + 2 * charge; + (void)index; + + using CylinderObserver = SurfaceObserver<CylinderSurface>; + using ActionListType = ActionList<CylinderObserver>; + using AbortConditionsType = AbortList<>; + + // setup propagation options + PropagatorOptions<ActionListType, AbortConditionsType> options(tgContext, + mfContext); + + options.pathLimit = 20 * units::_m; + options.maxStepSize = 1 * units::_cm; + + // set the surface to be passed by + options.actionList.get<CylinderObserver>().surface = mSurface.get(); + + using so_result = typename CylinderObserver::result_type; + + // define start parameters + double x = 0; + double y = 0; + double z = 0; + double px = pT * cos(phi); + double py = pT * sin(phi); + double pz = pT / tan(theta); + double q = dcharge; + Vector3D pos(x, y, z); + Vector3D mom(px, py, pz); + CurvilinearParameters start(nullptr, pos, mom, q); + // propagate to the cylinder surface + const auto& result = epropagator.propagate(start, *cSurface, options).value(); + auto& sor = result.get<so_result>(); + + BOOST_CHECK_EQUAL(sor.surfaces_passed, 1); + CHECK_CLOSE_ABS(sor.surface_passed_r, 10., 1e-5); +} + +BOOST_DATA_TEST_CASE( + curvilinear_additive_, + bdata::random((bdata::seed = 0, + bdata::distribution = std::uniform_real_distribution<>( + 0.4 * units::_GeV, 10. * units::_GeV))) ^ + bdata::random((bdata::seed = 1, + bdata::distribution = + std::uniform_real_distribution<>(-M_PI, M_PI))) ^ + bdata::random((bdata::seed = 2, + bdata::distribution = + std::uniform_real_distribution<>(1.0, M_PI - 1.0))) ^ + bdata::random( + (bdata::seed = 3, + bdata::distribution = std::uniform_int_distribution<>(0, 1))) ^ + bdata::xrange(ntests), + pT, phi, theta, charge, index) { + double dcharge = -1 + 2 * charge; + (void)index; + + // setup propagation options - the tow step options + PropagatorOptions<> options_2s(tgContext, mfContext); + options_2s.pathLimit = 50 * units::_cm; + options_2s.maxStepSize = 1 * units::_cm; + + // define start parameters + double x = 0; + double y = 0; + double z = 0; + double px = pT * cos(phi); + double py = pT * sin(phi); + double pz = pT / tan(theta); + double q = dcharge; + Vector3D pos(x, y, z); + Vector3D mom(px, py, pz); + /// a covariance matrix to transport + ActsSymMatrixD<5> cov; + // take some major correlations (off-diagonals) + cov << 10 * units::_mm, 0, 0.123, 0, 0.5, 0, 10 * units::_mm, 0, 0.162, 0, + 0.123, 0, 0.1, 0, 0, 0, 0.162, 0, 0.1, 0, 0.5, 0, 0, 0, + 1. / (10 * units::_GeV); + auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); + CurvilinearParameters start(std::move(covPtr), pos, mom, q); + // propagate to a path length of 100 with two steps of 50 + const auto& mid_parameters = + epropagator.propagate(start, options_2s).value().endParameters; + const auto& end_parameters_2s = + epropagator.propagate(*mid_parameters, options_2s).value().endParameters; + + // setup propagation options - the one step options + PropagatorOptions<> options_1s(tgContext, mfContext); + options_1s.pathLimit = 100 * units::_cm; + options_1s.maxStepSize = 1 * units::_cm; + // propagate to a path length of 100 in one step + const auto& end_parameters_1s = + epropagator.propagate(start, options_1s).value().endParameters; + + // test that the propagation is additive + CHECK_CLOSE_REL(end_parameters_1s->position(), end_parameters_2s->position(), + 0.001); + + const auto& cov_1s = *(end_parameters_1s->covariance()); + const auto& cov_2s = *(end_parameters_2s->covariance()); + + CHECK_CLOSE_COVARIANCE(cov_1s, cov_2s, 0.001); +} + +BOOST_DATA_TEST_CASE( + cylinder_additive_, + bdata::random((bdata::seed = 0, + bdata::distribution = std::uniform_real_distribution<>( + 0.4 * units::_GeV, 10. * units::_GeV))) ^ + bdata::random((bdata::seed = 1, + bdata::distribution = + std::uniform_real_distribution<>(-M_PI, M_PI))) ^ + bdata::random((bdata::seed = 2, + bdata::distribution = + std::uniform_real_distribution<>(1.0, M_PI - 1.0))) ^ + bdata::random( + (bdata::seed = 3, + bdata::distribution = std::uniform_int_distribution<>(0, 1))) ^ + bdata::xrange(ntests), + pT, phi, theta, charge, index) { + double dcharge = -1 + 2 * charge; + (void)index; + + // setup propagation options - 2 setp options + PropagatorOptions<> options_2s(tgContext, mfContext); + options_2s.pathLimit = 10 * units::_m; + options_2s.maxStepSize = 1 * units::_cm; + + // define start parameters + double x = 0; + double y = 0; + double z = 0; + double px = pT * cos(phi); + double py = pT * sin(phi); + double pz = pT / tan(theta); + double q = dcharge; + Vector3D pos(x, y, z); + Vector3D mom(px, py, pz); + /// a covariance matrix to transport + ActsSymMatrixD<5> cov; + // take some major correlations (off-diagonals) + cov << 10 * units::_mm, 0, 0.123, 0, 0.5, 0, 10 * units::_mm, 0, 0.162, 0, + 0.123, 0, 0.1, 0, 0, 0, 0.162, 0, 0.1, 0, 0.5, 0, 0, 0, + 1. / (10 * units::_GeV); + auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); + CurvilinearParameters start(std::move(covPtr), pos, mom, q); + // propagate to a final surface with one stop in between + const auto& mid_parameters = + epropagator.propagate(start, *mSurface, options_2s).value().endParameters; + + const auto& end_parameters_2s = + epropagator.propagate(*mid_parameters, *cSurface, options_2s) + .value() + .endParameters; + + // setup propagation options - one step options + PropagatorOptions<> options_1s(tgContext, mfContext); + options_1s.pathLimit = 10 * units::_m; + options_1s.maxStepSize = 1 * units::_cm; + // propagate to a final surface in one stop + const auto& end_parameters_1s = + epropagator.propagate(start, *cSurface, options_1s).value().endParameters; + + // test that the propagation is additive + CHECK_CLOSE_REL(end_parameters_1s->position(), end_parameters_2s->position(), + 0.001); + + const auto& cov_1s = *(end_parameters_1s->covariance()); + const auto& cov_2s = *(end_parameters_2s->covariance()); + + CHECK_CLOSE_COVARIANCE(cov_1s, cov_2s, 0.001); +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/Propagator/StepperTests.cpp b/Tests/Core/Propagator/StepperTests.cpp index f589bdb3dac280f278d8be260862a1e81b17217a..982bbcba0d07f2c89f48c11fa6cb716b413e39c1 100644 --- a/Tests/Core/Propagator/StepperTests.cpp +++ b/Tests/Core/Propagator/StepperTests.cpp @@ -37,606 +37,576 @@ namespace tt = boost::test_tools; namespace Acts { namespace Test { - using cstep = detail::ConstrainedStep; +using cstep = detail::ConstrainedStep; - // Create a test context - GeometryContext tgContext = GeometryContext(); - MagneticFieldContext mfContext = MagneticFieldContext(); +// Create a test context +GeometryContext tgContext = GeometryContext(); +MagneticFieldContext mfContext = MagneticFieldContext(); - /// @brief Aborter for the case that a particle leaves the detector or reaches - /// a custom made threshold. +/// @brief Aborter for the case that a particle leaves the detector or reaches +/// a custom made threshold. +/// +struct EndOfWorld { + /// Maximum value in x-direction of the detector + double maxX = 1. * units::_m; + + /// @brief Constructor + EndOfWorld() = default; + + /// @brief Main call operator for the abort operation /// - struct EndOfWorld - { - /// Maximum value in x-direction of the detector - double maxX = 1. * units::_m; - - /// @brief Constructor - EndOfWorld() = default; - - /// @brief Main call operator for the abort operation - /// - /// @tparam propagator_state_t State of the propagator - /// @tparam stepper_t Type of the stepper - /// @param [in] state State of the propagation - /// @param [in] stepper Stepper of the propagation - /// @return Boolean statement if the particle is still in the detector - template <typename propagator_state_t, typename stepper_t> - bool - operator()(propagator_state_t& state, const stepper_t& stepper) const - { - const double tolerance = state.options.targetTolerance; - if (maxX - std::abs(stepper.position(state.stepping).x()) <= tolerance - || std::abs(stepper.position(state.stepping).y()) >= 0.5 * units::_m - || std::abs(stepper.position(state.stepping).z()) >= 0.5 * units::_m) - return true; - return false; - } - }; + /// @tparam propagator_state_t State of the propagator + /// @tparam stepper_t Type of the stepper + /// @param [in] state State of the propagation + /// @param [in] stepper Stepper of the propagation + /// @return Boolean statement if the particle is still in the detector + template <typename propagator_state_t, typename stepper_t> + bool operator()(propagator_state_t& state, const stepper_t& stepper) const { + const double tolerance = state.options.targetTolerance; + if (maxX - std::abs(stepper.position(state.stepping).x()) <= tolerance || + std::abs(stepper.position(state.stepping).y()) >= 0.5 * units::_m || + std::abs(stepper.position(state.stepping).z()) >= 0.5 * units::_m) + return true; + return false; + } +}; +/// +/// @brief Data collector while propagation +/// +struct StepCollector { /// - /// @brief Data collector while propagation + /// @brief Data container for result analysis /// - struct StepCollector - { - - /// - /// @brief Data container for result analysis - /// - struct this_result - { - // Position of the propagator after each step - std::vector<Vector3D> position; - // Momentum of the propagator after each step - std::vector<Vector3D> momentum; - }; - - using result_type = this_result; - - /// @brief Main call operator for the action list. It stores the data for - /// analysis afterwards - /// - /// @tparam propagator_state_t Type of the propagator state - /// @tparam stepper_t Type of the stepper - /// @param [in] state State of the propagator - /// @param [in] stepper Stepper of the propagation - /// @param [out] result Struct which is filled with the data - template <typename propagator_state_t, typename stepper_t> - void - operator()(propagator_state_t& state, - const stepper_t& stepper, - result_type& result) const - { - result.position.push_back(stepper.position(state.stepping)); - result.momentum.push_back(stepper.momentum(state.stepping) - * stepper.direction(state.stepping)); - } + struct this_result { + // Position of the propagator after each step + std::vector<Vector3D> position; + // Momentum of the propagator after each step + std::vector<Vector3D> momentum; }; - /// @brief This function tests the EigenStepper with the DefaultExtension and - /// the DenseEnvironmentExtension. The focus of this tests lies in the - /// choosing of the right extension for the individual use case. This is - /// performed with three different detectors: - /// a) Pure vaccuum -> DefaultExtension needs to act - /// b) Pure Be -> DenseEnvironmentExtension needs to act - /// c) Vacuum - Be - Vacuum -> Both should act and switch during the - /// propagation - - // Test case a). The DenseEnvironmentExtension should state that it is not - // valid in this case. - BOOST_AUTO_TEST_CASE(step_extension_vacuum_test) - { - CuboidVolumeBuilder cvb; - CuboidVolumeBuilder::VolumeConfig vConf; - vConf.position = {0.5 * units::_m, 0., 0.}; - vConf.length = {1. * units::_m, 1. * units::_m, 1. * units::_m}; - CuboidVolumeBuilder::Config conf; - conf.volumeCfg.push_back(vConf); - conf.position = {0.5 * units::_m, 0., 0.}; - conf.length = {1. * units::_m, 1. * units::_m, 1. * units::_m}; - - // Build detector - cvb.setConfig(conf); - TrackingGeometryBuilder::Config tgbCfg; - tgbCfg.trackingVolumeBuilders.push_back( - [=](const auto& context, const auto& inner, const auto& vb) { - return cvb.trackingVolume(context, inner, vb); - }); - TrackingGeometryBuilder tgb(tgbCfg); - std::shared_ptr<const TrackingGeometry> vacuum - = tgb.trackingGeometry(tgContext); - - // Build navigator - Navigator naviVac(vacuum); - naviVac.resolvePassive = true; - naviVac.resolveMaterial = true; - naviVac.resolveSensitive = true; - - // Set initial parameters for the particle track - ActsSymMatrixD<5> cov = ActsSymMatrixD<5>::Identity(); - auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); - Vector3D startParams(0., 0., 0.), startMom(1. * units::_GeV, 0., 0.); - SingleCurvilinearTrackParameters<ChargedPolicy> sbtp( - std::move(covPtr), startParams, startMom, 1.); - - // Create action list for surface collection - ActionList<StepCollector> aList; - AbortList<EndOfWorld> abortList; - - // Set options for propagator - DenseStepperPropagatorOptions<ActionList<StepCollector>, - AbortList<EndOfWorld>> - propOpts(tgContext, mfContext); - propOpts.actionList = aList; - propOpts.abortList = abortList; - propOpts.maxSteps = 100; - propOpts.maxStepSize = 0.5 * units::_m; - - // Build stepper and propagator - ConstantBField bField(Vector3D(0., 0., 0.)); - EigenStepper<ConstantBField, - VoidIntersectionCorrector, - StepperExtensionList<DefaultExtension, - DenseEnvironmentExtension>, - detail::HighestValidAuctioneer> - es(bField); - Propagator<EigenStepper<ConstantBField, - VoidIntersectionCorrector, - StepperExtensionList<DefaultExtension, - DenseEnvironmentExtension>, - detail::HighestValidAuctioneer>, - Navigator> - prop(es, naviVac); - - // Launch and collect results - const auto& result = prop.propagate(sbtp, propOpts).value(); - const StepCollector::this_result& stepResult - = result.get<typename StepCollector::result_type>(); - - // Check that the propagation happend without interactions - for (const auto& pos : stepResult.position) { - CHECK_SMALL(pos.y(), 1. * units::_um); - CHECK_SMALL(pos.z(), 1. * units::_um); - if (pos == stepResult.position.back()) - CHECK_CLOSE_ABS(pos.x(), 1. * units::_m, 1. * units::_um); - } - for (const auto& mom : stepResult.momentum) { - CHECK_CLOSE_ABS(mom, startMom, 1. * units::_keV); - } + using result_type = this_result; - // Rebuild and check the choice of extension - ActionList<StepCollector> aListDef; - - // Set options for propagator - PropagatorOptions<ActionList<StepCollector>, AbortList<EndOfWorld>> - propOptsDef(tgContext, mfContext); - propOptsDef.actionList = aListDef; - propOptsDef.abortList = abortList; - propOptsDef.maxSteps = 100; - propOptsDef.maxStepSize = 0.5 * units::_m; - - EigenStepper<ConstantBField, - VoidIntersectionCorrector, - StepperExtensionList<DefaultExtension>> - esDef(bField); - Propagator<EigenStepper<ConstantBField, - VoidIntersectionCorrector, - StepperExtensionList<DefaultExtension>>, - Navigator> - propDef(esDef, naviVac); - - // Launch and collect results - const auto& resultDef = propDef.propagate(sbtp, propOptsDef).value(); - const StepCollector::this_result& stepResultDef - = resultDef.get<typename StepCollector::result_type>(); - - // Check that the right extension was chosen - // If chosen correctly, the number of elements should be identical - BOOST_TEST(stepResult.position.size() == stepResultDef.position.size()); - for (unsigned int i = 0; i < stepResult.position.size(); i++) { - CHECK_CLOSE_ABS( - stepResult.position[i], stepResultDef.position[i], 1. * units::_um); - } - BOOST_TEST(stepResult.momentum.size() == stepResultDef.momentum.size()); - for (unsigned int i = 0; i < stepResult.momentum.size(); i++) { - CHECK_CLOSE_ABS( - stepResult.momentum[i], stepResultDef.momentum[i], 1. * units::_keV); - } + /// @brief Main call operator for the action list. It stores the data for + /// analysis afterwards + /// + /// @tparam propagator_state_t Type of the propagator state + /// @tparam stepper_t Type of the stepper + /// @param [in] state State of the propagator + /// @param [in] stepper Stepper of the propagation + /// @param [out] result Struct which is filled with the data + template <typename propagator_state_t, typename stepper_t> + void operator()(propagator_state_t& state, const stepper_t& stepper, + result_type& result) const { + result.position.push_back(stepper.position(state.stepping)); + result.momentum.push_back(stepper.momentum(state.stepping) * + stepper.direction(state.stepping)); + } +}; + +/// @brief This function tests the EigenStepper with the DefaultExtension and +/// the DenseEnvironmentExtension. The focus of this tests lies in the +/// choosing of the right extension for the individual use case. This is +/// performed with three different detectors: +/// a) Pure vaccuum -> DefaultExtension needs to act +/// b) Pure Be -> DenseEnvironmentExtension needs to act +/// c) Vacuum - Be - Vacuum -> Both should act and switch during the +/// propagation + +// Test case a). The DenseEnvironmentExtension should state that it is not +// valid in this case. +BOOST_AUTO_TEST_CASE(step_extension_vacuum_test) { + CuboidVolumeBuilder cvb; + CuboidVolumeBuilder::VolumeConfig vConf; + vConf.position = {0.5 * units::_m, 0., 0.}; + vConf.length = {1. * units::_m, 1. * units::_m, 1. * units::_m}; + CuboidVolumeBuilder::Config conf; + conf.volumeCfg.push_back(vConf); + conf.position = {0.5 * units::_m, 0., 0.}; + conf.length = {1. * units::_m, 1. * units::_m, 1. * units::_m}; + + // Build detector + cvb.setConfig(conf); + TrackingGeometryBuilder::Config tgbCfg; + tgbCfg.trackingVolumeBuilders.push_back( + [=](const auto& context, const auto& inner, const auto& vb) { + return cvb.trackingVolume(context, inner, vb); + }); + TrackingGeometryBuilder tgb(tgbCfg); + std::shared_ptr<const TrackingGeometry> vacuum = + tgb.trackingGeometry(tgContext); + + // Build navigator + Navigator naviVac(vacuum); + naviVac.resolvePassive = true; + naviVac.resolveMaterial = true; + naviVac.resolveSensitive = true; + + // Set initial parameters for the particle track + ActsSymMatrixD<5> cov = ActsSymMatrixD<5>::Identity(); + auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); + Vector3D startParams(0., 0., 0.), startMom(1. * units::_GeV, 0., 0.); + SingleCurvilinearTrackParameters<ChargedPolicy> sbtp( + std::move(covPtr), startParams, startMom, 1.); + + // Create action list for surface collection + ActionList<StepCollector> aList; + AbortList<EndOfWorld> abortList; + + // Set options for propagator + DenseStepperPropagatorOptions<ActionList<StepCollector>, + AbortList<EndOfWorld>> + propOpts(tgContext, mfContext); + propOpts.actionList = aList; + propOpts.abortList = abortList; + propOpts.maxSteps = 100; + propOpts.maxStepSize = 0.5 * units::_m; + + // Build stepper and propagator + ConstantBField bField(Vector3D(0., 0., 0.)); + EigenStepper< + ConstantBField, VoidIntersectionCorrector, + StepperExtensionList<DefaultExtension, DenseEnvironmentExtension>, + detail::HighestValidAuctioneer> + es(bField); + Propagator<EigenStepper<ConstantBField, VoidIntersectionCorrector, + StepperExtensionList<DefaultExtension, + DenseEnvironmentExtension>, + detail::HighestValidAuctioneer>, + Navigator> + prop(es, naviVac); + + // Launch and collect results + const auto& result = prop.propagate(sbtp, propOpts).value(); + const StepCollector::this_result& stepResult = + result.get<typename StepCollector::result_type>(); + + // Check that the propagation happend without interactions + for (const auto& pos : stepResult.position) { + CHECK_SMALL(pos.y(), 1. * units::_um); + CHECK_SMALL(pos.z(), 1. * units::_um); + if (pos == stepResult.position.back()) + CHECK_CLOSE_ABS(pos.x(), 1. * units::_m, 1. * units::_um); + } + for (const auto& mom : stepResult.momentum) { + CHECK_CLOSE_ABS(mom, startMom, 1. * units::_keV); } - // Test case b). The DefaultExtension should state that it is invalid here. - BOOST_AUTO_TEST_CASE(step_extension_material_test) - { - CuboidVolumeBuilder cvb; - CuboidVolumeBuilder::VolumeConfig vConf; - vConf.position = {0.5 * units::_m, 0., 0.}; - vConf.length = {1. * units::_m, 1. * units::_m, 1. * units::_m}; - vConf.volumeMaterial = std::make_shared<const HomogeneousVolumeMaterial>( - Material(352.8, 394.133, 9.012, 4., 1.848e-3)); - CuboidVolumeBuilder::Config conf; - conf.volumeCfg.push_back(vConf); - conf.position = {0.5 * units::_m, 0., 0.}; - conf.length = {1. * units::_m, 1. * units::_m, 1. * units::_m}; - - // Build detector - cvb.setConfig(conf); - TrackingGeometryBuilder::Config tgbCfg; - tgbCfg.trackingVolumeBuilders.push_back( - [=](const auto& context, const auto& inner, const auto& vb) { - return cvb.trackingVolume(context, inner, vb); - }); - TrackingGeometryBuilder tgb(tgbCfg); - std::shared_ptr<const TrackingGeometry> material - = tgb.trackingGeometry(tgContext); - - // Build navigator - Navigator naviMat(material); - naviMat.resolvePassive = true; - naviMat.resolveMaterial = true; - naviMat.resolveSensitive = true; - - // Set initial parameters for the particle track - ActsSymMatrixD<5> cov = ActsSymMatrixD<5>::Identity(); - auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); - Vector3D startParams(0., 0., 0.), startMom(5. * units::_GeV, 0., 0.); - SingleCurvilinearTrackParameters<ChargedPolicy> sbtp( - std::move(covPtr), startParams, startMom, 1.); - - // Create action list for surface collection - ActionList<StepCollector> aList; - AbortList<EndOfWorld> abortList; - - // Set options for propagator - DenseStepperPropagatorOptions<ActionList<StepCollector>, - AbortList<EndOfWorld>> - propOpts(tgContext, mfContext); - propOpts.actionList = aList; - propOpts.abortList = abortList; - propOpts.maxSteps = 100; - propOpts.maxStepSize = 0.5 * units::_m; - propOpts.debug = true; - - // Build stepper and propagator - ConstantBField bField(Vector3D(0., 0., 0.)); - EigenStepper<ConstantBField, - VoidIntersectionCorrector, - StepperExtensionList<DefaultExtension, - DenseEnvironmentExtension>, - detail::HighestValidAuctioneer> - es(bField); - Propagator<EigenStepper<ConstantBField, - VoidIntersectionCorrector, - StepperExtensionList<DefaultExtension, - DenseEnvironmentExtension>, - detail::HighestValidAuctioneer>, - Navigator> - prop(es, naviMat); - - // Launch and collect results - const auto& result = prop.propagate(sbtp, propOpts).value(); - const StepCollector::this_result& stepResult - = result.get<typename StepCollector::result_type>(); - - // Check that there occured interaction - for (const auto& pos : stepResult.position) { - CHECK_SMALL(pos.y(), 1. * units::_um); - CHECK_SMALL(pos.z(), 1. * units::_um); - if (pos == stepResult.position.front()) { - CHECK_SMALL(pos.x(), 1. * units::_um); - } else { - BOOST_CHECK_GT(std::abs(pos.x()), 1. * units::_um); - } - } - for (const auto& mom : stepResult.momentum) { - CHECK_SMALL(mom.y(), 1. * units::_keV); - CHECK_SMALL(mom.z(), 1. * units::_keV); - if (mom == stepResult.momentum.front()) { - CHECK_CLOSE_ABS(mom.x(), 5. * units::_GeV, 1. * units::_keV); - } else { - BOOST_CHECK_LT(mom.x(), 5. * units::_GeV); - } - } - // Rebuild and check the choice of extension - // Set options for propagator - DenseStepperPropagatorOptions<ActionList<StepCollector>, - AbortList<EndOfWorld>> - propOptsDense(tgContext, mfContext); - propOptsDense.actionList = aList; - propOptsDense.abortList = abortList; - propOptsDense.maxSteps = 100; - propOptsDense.maxStepSize = 0.5 * units::_m; - propOptsDense.debug = true; - - // Build stepper and propagator - EigenStepper<ConstantBField, - VoidIntersectionCorrector, - StepperExtensionList<DenseEnvironmentExtension>> - esDense(bField); - Propagator<EigenStepper<ConstantBField, - VoidIntersectionCorrector, - StepperExtensionList<DenseEnvironmentExtension>>, - Navigator> - propDense(esDense, naviMat); - - // Launch and collect results - const auto& resultDense = propDense.propagate(sbtp, propOptsDense).value(); - const StepCollector::this_result& stepResultDense - = resultDense.get<typename StepCollector::result_type>(); - - // Check that the right extension was chosen - // If chosen correctly, the number of elements should be identical - BOOST_TEST(stepResult.position.size() == stepResultDense.position.size()); - for (unsigned int i = 0; i < stepResult.position.size(); i++) { - CHECK_CLOSE_ABS( - stepResult.position[i], stepResultDense.position[i], 1. * units::_um); + // Rebuild and check the choice of extension + ActionList<StepCollector> aListDef; + + // Set options for propagator + PropagatorOptions<ActionList<StepCollector>, AbortList<EndOfWorld>> + propOptsDef(tgContext, mfContext); + propOptsDef.actionList = aListDef; + propOptsDef.abortList = abortList; + propOptsDef.maxSteps = 100; + propOptsDef.maxStepSize = 0.5 * units::_m; + + EigenStepper<ConstantBField, VoidIntersectionCorrector, + StepperExtensionList<DefaultExtension>> + esDef(bField); + Propagator<EigenStepper<ConstantBField, VoidIntersectionCorrector, + StepperExtensionList<DefaultExtension>>, + Navigator> + propDef(esDef, naviVac); + + // Launch and collect results + const auto& resultDef = propDef.propagate(sbtp, propOptsDef).value(); + const StepCollector::this_result& stepResultDef = + resultDef.get<typename StepCollector::result_type>(); + + // Check that the right extension was chosen + // If chosen correctly, the number of elements should be identical + BOOST_TEST(stepResult.position.size() == stepResultDef.position.size()); + for (unsigned int i = 0; i < stepResult.position.size(); i++) { + CHECK_CLOSE_ABS(stepResult.position[i], stepResultDef.position[i], + 1. * units::_um); + } + BOOST_TEST(stepResult.momentum.size() == stepResultDef.momentum.size()); + for (unsigned int i = 0; i < stepResult.momentum.size(); i++) { + CHECK_CLOSE_ABS(stepResult.momentum[i], stepResultDef.momentum[i], + 1. * units::_keV); + } +} +// Test case b). The DefaultExtension should state that it is invalid here. +BOOST_AUTO_TEST_CASE(step_extension_material_test) { + CuboidVolumeBuilder cvb; + CuboidVolumeBuilder::VolumeConfig vConf; + vConf.position = {0.5 * units::_m, 0., 0.}; + vConf.length = {1. * units::_m, 1. * units::_m, 1. * units::_m}; + vConf.volumeMaterial = std::make_shared<const HomogeneousVolumeMaterial>( + Material(352.8, 394.133, 9.012, 4., 1.848e-3)); + CuboidVolumeBuilder::Config conf; + conf.volumeCfg.push_back(vConf); + conf.position = {0.5 * units::_m, 0., 0.}; + conf.length = {1. * units::_m, 1. * units::_m, 1. * units::_m}; + + // Build detector + cvb.setConfig(conf); + TrackingGeometryBuilder::Config tgbCfg; + tgbCfg.trackingVolumeBuilders.push_back( + [=](const auto& context, const auto& inner, const auto& vb) { + return cvb.trackingVolume(context, inner, vb); + }); + TrackingGeometryBuilder tgb(tgbCfg); + std::shared_ptr<const TrackingGeometry> material = + tgb.trackingGeometry(tgContext); + + // Build navigator + Navigator naviMat(material); + naviMat.resolvePassive = true; + naviMat.resolveMaterial = true; + naviMat.resolveSensitive = true; + + // Set initial parameters for the particle track + ActsSymMatrixD<5> cov = ActsSymMatrixD<5>::Identity(); + auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); + Vector3D startParams(0., 0., 0.), startMom(5. * units::_GeV, 0., 0.); + SingleCurvilinearTrackParameters<ChargedPolicy> sbtp( + std::move(covPtr), startParams, startMom, 1.); + + // Create action list for surface collection + ActionList<StepCollector> aList; + AbortList<EndOfWorld> abortList; + + // Set options for propagator + DenseStepperPropagatorOptions<ActionList<StepCollector>, + AbortList<EndOfWorld>> + propOpts(tgContext, mfContext); + propOpts.actionList = aList; + propOpts.abortList = abortList; + propOpts.maxSteps = 100; + propOpts.maxStepSize = 0.5 * units::_m; + propOpts.debug = true; + + // Build stepper and propagator + ConstantBField bField(Vector3D(0., 0., 0.)); + EigenStepper< + ConstantBField, VoidIntersectionCorrector, + StepperExtensionList<DefaultExtension, DenseEnvironmentExtension>, + detail::HighestValidAuctioneer> + es(bField); + Propagator<EigenStepper<ConstantBField, VoidIntersectionCorrector, + StepperExtensionList<DefaultExtension, + DenseEnvironmentExtension>, + detail::HighestValidAuctioneer>, + Navigator> + prop(es, naviMat); + + // Launch and collect results + const auto& result = prop.propagate(sbtp, propOpts).value(); + const StepCollector::this_result& stepResult = + result.get<typename StepCollector::result_type>(); + + // Check that there occured interaction + for (const auto& pos : stepResult.position) { + CHECK_SMALL(pos.y(), 1. * units::_um); + CHECK_SMALL(pos.z(), 1. * units::_um); + if (pos == stepResult.position.front()) { + CHECK_SMALL(pos.x(), 1. * units::_um); + } else { + BOOST_CHECK_GT(std::abs(pos.x()), 1. * units::_um); } - BOOST_TEST(stepResult.momentum.size() == stepResultDense.momentum.size()); - for (unsigned int i = 0; i < stepResult.momentum.size(); i++) { - CHECK_CLOSE_ABS(stepResult.momentum[i], - stepResultDense.momentum[i], - 1. * units::_keV); + } + for (const auto& mom : stepResult.momentum) { + CHECK_SMALL(mom.y(), 1. * units::_keV); + CHECK_SMALL(mom.z(), 1. * units::_keV); + if (mom == stepResult.momentum.front()) { + CHECK_CLOSE_ABS(mom.x(), 5. * units::_GeV, 1. * units::_keV); + } else { + BOOST_CHECK_LT(mom.x(), 5. * units::_GeV); } + } + + // Rebuild and check the choice of extension + // Set options for propagator + DenseStepperPropagatorOptions<ActionList<StepCollector>, + AbortList<EndOfWorld>> + propOptsDense(tgContext, mfContext); + propOptsDense.actionList = aList; + propOptsDense.abortList = abortList; + propOptsDense.maxSteps = 100; + propOptsDense.maxStepSize = 0.5 * units::_m; + propOptsDense.debug = true; + + // Build stepper and propagator + EigenStepper<ConstantBField, VoidIntersectionCorrector, + StepperExtensionList<DenseEnvironmentExtension>> + esDense(bField); + Propagator<EigenStepper<ConstantBField, VoidIntersectionCorrector, + StepperExtensionList<DenseEnvironmentExtension>>, + Navigator> + propDense(esDense, naviMat); + + // Launch and collect results + const auto& resultDense = propDense.propagate(sbtp, propOptsDense).value(); + const StepCollector::this_result& stepResultDense = + resultDense.get<typename StepCollector::result_type>(); + + // Check that the right extension was chosen + // If chosen correctly, the number of elements should be identical + BOOST_TEST(stepResult.position.size() == stepResultDense.position.size()); + for (unsigned int i = 0; i < stepResult.position.size(); i++) { + CHECK_CLOSE_ABS(stepResult.position[i], stepResultDense.position[i], + 1. * units::_um); + } + BOOST_TEST(stepResult.momentum.size() == stepResultDense.momentum.size()); + for (unsigned int i = 0; i < stepResult.momentum.size(); i++) { + CHECK_CLOSE_ABS(stepResult.momentum[i], stepResultDense.momentum[i], + 1. * units::_keV); + } - //////////////////////////////////////////////////////////////////// - - // Re-launch the configuration with magnetic field - bField.setField(0., 1. * units::_T, 0.); - EigenStepper<ConstantBField, - VoidIntersectionCorrector, - StepperExtensionList<DefaultExtension, - DenseEnvironmentExtension>, - detail::HighestValidAuctioneer> - esB(bField); - Propagator<EigenStepper<ConstantBField, - VoidIntersectionCorrector, - StepperExtensionList<DefaultExtension, - DenseEnvironmentExtension>, - detail::HighestValidAuctioneer>, - Navigator> - propB(esB, naviMat); - - const auto& resultB = propB.propagate(sbtp, propOptsDense).value(); - const StepCollector::this_result& stepResultB - = resultB.get<typename StepCollector::result_type>(); - - // Check that there occured interaction - for (const auto& pos : stepResultB.position) { - if (pos == stepResultB.position.front()) { - CHECK_SMALL(pos, 1. * units::_um); - } else { - BOOST_CHECK_GT(std::abs(pos.x()), 1. * units::_um); - CHECK_SMALL(pos.y(), 1. * units::_um); - BOOST_CHECK_GT(std::abs(pos.z()), 1. * units::_um); - } + //////////////////////////////////////////////////////////////////// + + // Re-launch the configuration with magnetic field + bField.setField(0., 1. * units::_T, 0.); + EigenStepper< + ConstantBField, VoidIntersectionCorrector, + StepperExtensionList<DefaultExtension, DenseEnvironmentExtension>, + detail::HighestValidAuctioneer> + esB(bField); + Propagator<EigenStepper<ConstantBField, VoidIntersectionCorrector, + StepperExtensionList<DefaultExtension, + DenseEnvironmentExtension>, + detail::HighestValidAuctioneer>, + Navigator> + propB(esB, naviMat); + + const auto& resultB = propB.propagate(sbtp, propOptsDense).value(); + const StepCollector::this_result& stepResultB = + resultB.get<typename StepCollector::result_type>(); + + // Check that there occured interaction + for (const auto& pos : stepResultB.position) { + if (pos == stepResultB.position.front()) { + CHECK_SMALL(pos, 1. * units::_um); + } else { + BOOST_CHECK_GT(std::abs(pos.x()), 1. * units::_um); + CHECK_SMALL(pos.y(), 1. * units::_um); + BOOST_CHECK_GT(std::abs(pos.z()), 1. * units::_um); } - for (const auto& mom : stepResultB.momentum) { - if (mom == stepResultB.momentum.front()) { - CHECK_CLOSE_ABS(mom, startMom, 1. * units::_keV); - } else { - BOOST_CHECK_NE(mom.x(), 5. * units::_GeV); - CHECK_SMALL(mom.y(), 1. * units::_keV); - BOOST_CHECK_NE(mom.z(), 0.); - } + } + for (const auto& mom : stepResultB.momentum) { + if (mom == stepResultB.momentum.front()) { + CHECK_CLOSE_ABS(mom, startMom, 1. * units::_keV); + } else { + BOOST_CHECK_NE(mom.x(), 5. * units::_GeV); + CHECK_SMALL(mom.y(), 1. * units::_keV); + BOOST_CHECK_NE(mom.z(), 0.); } } - // Test case c). Both should be involved in their part of the detector - BOOST_AUTO_TEST_CASE(step_extension_vacmatvac_test) - { - CuboidVolumeBuilder cvb; - CuboidVolumeBuilder::VolumeConfig vConfVac1; - vConfVac1.position = {0.5 * units::_m, 0., 0.}; - vConfVac1.length = {1. * units::_m, 1. * units::_m, 1. * units::_m}; - vConfVac1.name = "First vacuum volume"; - CuboidVolumeBuilder::VolumeConfig vConfMat; - vConfMat.position = {1.5 * units::_m, 0., 0.}; - vConfMat.length = {1. * units::_m, 1. * units::_m, 1. * units::_m}; - vConfMat.volumeMaterial = std::make_shared<const HomogeneousVolumeMaterial>( - Material(352.8, 394.133, 9.012, 4., 1.848e-3)); - vConfMat.name = "Material volume"; - CuboidVolumeBuilder::VolumeConfig vConfVac2; - vConfVac2.position = {2.5 * units::_m, 0., 0.}; - vConfVac2.length = {1. * units::_m, 1. * units::_m, 1. * units::_m}; - vConfVac2.name = "Second vacuum volume"; - CuboidVolumeBuilder::Config conf; - conf.volumeCfg = {vConfVac1, vConfMat, vConfVac2}; - conf.position = {1.5 * units::_m, 0., 0.}; - conf.length = {3. * units::_m, 1. * units::_m, 1. * units::_m}; - - // Build detector - cvb.setConfig(conf); - TrackingGeometryBuilder::Config tgbCfg; - tgbCfg.trackingVolumeBuilders.push_back( - [=](const auto& context, const auto& inner, const auto& vb) { - return cvb.trackingVolume(context, inner, vb); - }); - TrackingGeometryBuilder tgb(tgbCfg); - std::shared_ptr<const TrackingGeometry> det - = tgb.trackingGeometry(tgContext); - - // Build navigator - Navigator naviDet(det); - naviDet.resolvePassive = true; - naviDet.resolveMaterial = true; - naviDet.resolveSensitive = true; - - // Set initial parameters for the particle track - ActsSymMatrixD<5> cov = ActsSymMatrixD<5>::Identity(); - auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); - Vector3D startParams(0., 0., 0.), startMom(5. * units::_GeV, 0., 0.); - SingleCurvilinearTrackParameters<ChargedPolicy> sbtp( - std::move(covPtr), startParams, startMom, 1.); - - // Create action list for surface collection - ActionList<StepCollector> aList; - AbortList<EndOfWorld> abortList; - abortList.get<EndOfWorld>().maxX = 3. * units::_m; - - // Set options for propagator - DenseStepperPropagatorOptions<ActionList<StepCollector>, - AbortList<EndOfWorld>> - propOpts(tgContext, mfContext); - propOpts.actionList = aList; - propOpts.abortList = abortList; - propOpts.maxSteps = 100; - propOpts.maxStepSize = 0.5 * units::_m; - - // Build stepper and propagator - ConstantBField bField(Vector3D(0., 1. * units::_T, 0.)); - EigenStepper<ConstantBField, - VoidIntersectionCorrector, - StepperExtensionList<DefaultExtension, - DenseEnvironmentExtension>, - detail::HighestValidAuctioneer> - es(bField); - Propagator<EigenStepper<ConstantBField, - VoidIntersectionCorrector, - StepperExtensionList<DefaultExtension, - DenseEnvironmentExtension>, - detail::HighestValidAuctioneer>, - Navigator> - prop(es, naviDet); - - // Launch and collect results - const auto& result = prop.propagate(sbtp, propOpts).value(); - const StepCollector::this_result& stepResult - = result.get<typename StepCollector::result_type>(); - - // Manually set the extensions for each step and propagate through each - // volume by propagation to the boundaries - // Collect boundaries - std::vector<Surface const*> surs; - std::vector<std::shared_ptr<const BoundarySurfaceT<TrackingVolume>>> - boundaries - = det->lowestTrackingVolume(tgContext, {0.5 * units::_m, 0., 0.}) +} +// Test case c). Both should be involved in their part of the detector +BOOST_AUTO_TEST_CASE(step_extension_vacmatvac_test) { + CuboidVolumeBuilder cvb; + CuboidVolumeBuilder::VolumeConfig vConfVac1; + vConfVac1.position = {0.5 * units::_m, 0., 0.}; + vConfVac1.length = {1. * units::_m, 1. * units::_m, 1. * units::_m}; + vConfVac1.name = "First vacuum volume"; + CuboidVolumeBuilder::VolumeConfig vConfMat; + vConfMat.position = {1.5 * units::_m, 0., 0.}; + vConfMat.length = {1. * units::_m, 1. * units::_m, 1. * units::_m}; + vConfMat.volumeMaterial = std::make_shared<const HomogeneousVolumeMaterial>( + Material(352.8, 394.133, 9.012, 4., 1.848e-3)); + vConfMat.name = "Material volume"; + CuboidVolumeBuilder::VolumeConfig vConfVac2; + vConfVac2.position = {2.5 * units::_m, 0., 0.}; + vConfVac2.length = {1. * units::_m, 1. * units::_m, 1. * units::_m}; + vConfVac2.name = "Second vacuum volume"; + CuboidVolumeBuilder::Config conf; + conf.volumeCfg = {vConfVac1, vConfMat, vConfVac2}; + conf.position = {1.5 * units::_m, 0., 0.}; + conf.length = {3. * units::_m, 1. * units::_m, 1. * units::_m}; + + // Build detector + cvb.setConfig(conf); + TrackingGeometryBuilder::Config tgbCfg; + tgbCfg.trackingVolumeBuilders.push_back( + [=](const auto& context, const auto& inner, const auto& vb) { + return cvb.trackingVolume(context, inner, vb); + }); + TrackingGeometryBuilder tgb(tgbCfg); + std::shared_ptr<const TrackingGeometry> det = tgb.trackingGeometry(tgContext); + + // Build navigator + Navigator naviDet(det); + naviDet.resolvePassive = true; + naviDet.resolveMaterial = true; + naviDet.resolveSensitive = true; + + // Set initial parameters for the particle track + ActsSymMatrixD<5> cov = ActsSymMatrixD<5>::Identity(); + auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); + Vector3D startParams(0., 0., 0.), startMom(5. * units::_GeV, 0., 0.); + SingleCurvilinearTrackParameters<ChargedPolicy> sbtp( + std::move(covPtr), startParams, startMom, 1.); + + // Create action list for surface collection + ActionList<StepCollector> aList; + AbortList<EndOfWorld> abortList; + abortList.get<EndOfWorld>().maxX = 3. * units::_m; + + // Set options for propagator + DenseStepperPropagatorOptions<ActionList<StepCollector>, + AbortList<EndOfWorld>> + propOpts(tgContext, mfContext); + propOpts.actionList = aList; + propOpts.abortList = abortList; + propOpts.maxSteps = 100; + propOpts.maxStepSize = 0.5 * units::_m; + + // Build stepper and propagator + ConstantBField bField(Vector3D(0., 1. * units::_T, 0.)); + EigenStepper< + ConstantBField, VoidIntersectionCorrector, + StepperExtensionList<DefaultExtension, DenseEnvironmentExtension>, + detail::HighestValidAuctioneer> + es(bField); + Propagator<EigenStepper<ConstantBField, VoidIntersectionCorrector, + StepperExtensionList<DefaultExtension, + DenseEnvironmentExtension>, + detail::HighestValidAuctioneer>, + Navigator> + prop(es, naviDet); + + // Launch and collect results + const auto& result = prop.propagate(sbtp, propOpts).value(); + const StepCollector::this_result& stepResult = + result.get<typename StepCollector::result_type>(); + + // Manually set the extensions for each step and propagate through each + // volume by propagation to the boundaries + // Collect boundaries + std::vector<Surface const*> surs; + std::vector<std::shared_ptr<const BoundarySurfaceT<TrackingVolume>>> + boundaries = + det->lowestTrackingVolume(tgContext, {0.5 * units::_m, 0., 0.}) ->boundarySurfaces(); - for (auto& b : boundaries) { - if (b->surfaceRepresentation().center(tgContext).x() == 1. * units::_m) { - surs.push_back(&(b->surfaceRepresentation())); - break; - } + for (auto& b : boundaries) { + if (b->surfaceRepresentation().center(tgContext).x() == 1. * units::_m) { + surs.push_back(&(b->surfaceRepresentation())); + break; } - boundaries = det->lowestTrackingVolume(tgContext, {1.5 * units::_m, 0., 0.}) - ->boundarySurfaces(); - for (auto& b : boundaries) { - if (b->surfaceRepresentation().center(tgContext).x() == 2. * units::_m) { - surs.push_back(&(b->surfaceRepresentation())); - break; - } + } + boundaries = det->lowestTrackingVolume(tgContext, {1.5 * units::_m, 0., 0.}) + ->boundarySurfaces(); + for (auto& b : boundaries) { + if (b->surfaceRepresentation().center(tgContext).x() == 2. * units::_m) { + surs.push_back(&(b->surfaceRepresentation())); + break; } - boundaries = det->lowestTrackingVolume(tgContext, {2.5 * units::_m, 0., 0.}) - ->boundarySurfaces(); - for (auto& b : boundaries) { - if (b->surfaceRepresentation().center(tgContext).x() == 3. * units::_m) { - surs.push_back(&(b->surfaceRepresentation())); - break; - } + } + boundaries = det->lowestTrackingVolume(tgContext, {2.5 * units::_m, 0., 0.}) + ->boundarySurfaces(); + for (auto& b : boundaries) { + if (b->surfaceRepresentation().center(tgContext).x() == 3. * units::_m) { + surs.push_back(&(b->surfaceRepresentation())); + break; } + } - // Build launcher through vacuum - // Set options for propagator - ActionList<StepCollector> aListDef; - - PropagatorOptions<ActionList<StepCollector>, AbortList<EndOfWorld>> - propOptsDef(tgContext, mfContext); - abortList.get<EndOfWorld>().maxX = 1. * units::_m; - propOptsDef.actionList = aListDef; - propOptsDef.abortList = abortList; - propOptsDef.maxSteps = 100; - propOptsDef.maxStepSize = 0.5 * units::_m; - - // Build stepper and propagator - EigenStepper<ConstantBField, - VoidIntersectionCorrector, - StepperExtensionList<DefaultExtension>> - esDef(bField); - Propagator<EigenStepper<ConstantBField, - VoidIntersectionCorrector, - StepperExtensionList<DefaultExtension>>, - Navigator> - propDef(esDef, naviDet); - - // Launch and collect results - const auto& resultDef - = propDef.propagate(sbtp, *(surs[0]), propOptsDef).value(); - const StepCollector::this_result& stepResultDef - = resultDef.get<typename StepCollector::result_type>(); - - // Check the exit situation of the first volume - std::pair<Vector3D, Vector3D> endParams, endParamsControl; - for (unsigned int i = 0; i < stepResultDef.position.size(); i++) { - if (1. * units::_m - stepResultDef.position[i].x() < 1e-4) { - endParams = std::make_pair(stepResultDef.position[i], - stepResultDef.momentum[i]); - break; - } + // Build launcher through vacuum + // Set options for propagator + ActionList<StepCollector> aListDef; + + PropagatorOptions<ActionList<StepCollector>, AbortList<EndOfWorld>> + propOptsDef(tgContext, mfContext); + abortList.get<EndOfWorld>().maxX = 1. * units::_m; + propOptsDef.actionList = aListDef; + propOptsDef.abortList = abortList; + propOptsDef.maxSteps = 100; + propOptsDef.maxStepSize = 0.5 * units::_m; + + // Build stepper and propagator + EigenStepper<ConstantBField, VoidIntersectionCorrector, + StepperExtensionList<DefaultExtension>> + esDef(bField); + Propagator<EigenStepper<ConstantBField, VoidIntersectionCorrector, + StepperExtensionList<DefaultExtension>>, + Navigator> + propDef(esDef, naviDet); + + // Launch and collect results + const auto& resultDef = + propDef.propagate(sbtp, *(surs[0]), propOptsDef).value(); + const StepCollector::this_result& stepResultDef = + resultDef.get<typename StepCollector::result_type>(); + + // Check the exit situation of the first volume + std::pair<Vector3D, Vector3D> endParams, endParamsControl; + for (unsigned int i = 0; i < stepResultDef.position.size(); i++) { + if (1. * units::_m - stepResultDef.position[i].x() < 1e-4) { + endParams = + std::make_pair(stepResultDef.position[i], stepResultDef.momentum[i]); + break; } - for (unsigned int i = 0; i < stepResult.position.size(); i++) { - if (1. * units::_m - stepResult.position[i].x() < 1e-4) { - endParamsControl - = std::make_pair(stepResult.position[i], stepResult.momentum[i]); - break; - } + } + for (unsigned int i = 0; i < stepResult.position.size(); i++) { + if (1. * units::_m - stepResult.position[i].x() < 1e-4) { + endParamsControl = + std::make_pair(stepResult.position[i], stepResult.momentum[i]); + break; } + } - CHECK_CLOSE_ABS(endParams.first, endParamsControl.first, 1. * units::_um); - CHECK_CLOSE_ABS(endParams.second, endParamsControl.second, 1. * units::_um); - - // Build launcher through material - // Set initial parameters for the particle track by using the result of the - // first volume - covPtr = std::make_unique<const ActsSymMatrixD<5>>( - ActsSymMatrixD<5>::Identity()); - startParams = endParams.first; - startMom = endParams.second; - SingleCurvilinearTrackParameters<ChargedPolicy> sbtpPiecewise( - std::move(covPtr), startParams, startMom, 1.); - - // Set options for propagator - DenseStepperPropagatorOptions<ActionList<StepCollector>, - AbortList<EndOfWorld>> - propOptsDense(tgContext, mfContext); - abortList.get<EndOfWorld>().maxX = 2. * units::_m; - propOptsDense.actionList = aList; - propOptsDense.abortList = abortList; - propOptsDense.maxSteps = 100; - propOptsDense.maxStepSize = 0.5 * units::_m; - propOptsDense.tolerance = 1e-8; - - // Build stepper and propagator - EigenStepper<ConstantBField, - VoidIntersectionCorrector, - StepperExtensionList<DenseEnvironmentExtension>> - esDense(bField); - Propagator<EigenStepper<ConstantBField, - VoidIntersectionCorrector, - StepperExtensionList<DenseEnvironmentExtension>>, - Navigator> - propDense(esDense, naviDet); - - // Launch and collect results - const auto& resultDense - = propDense.propagate(sbtpPiecewise, *(surs[1]), propOptsDense).value(); - const StepCollector::this_result& stepResultDense - = resultDense.get<typename StepCollector::result_type>(); - - // Check the exit situation of the second volume - for (unsigned int i = 0; i < stepResultDense.position.size(); i++) { - if (2. * units::_m - stepResultDense.position[i].x() < 1e-4) { - endParams = std::make_pair(stepResultDense.position[i], - stepResultDense.momentum[i]); - break; - } + CHECK_CLOSE_ABS(endParams.first, endParamsControl.first, 1. * units::_um); + CHECK_CLOSE_ABS(endParams.second, endParamsControl.second, 1. * units::_um); + + // Build launcher through material + // Set initial parameters for the particle track by using the result of the + // first volume + covPtr = + std::make_unique<const ActsSymMatrixD<5>>(ActsSymMatrixD<5>::Identity()); + startParams = endParams.first; + startMom = endParams.second; + SingleCurvilinearTrackParameters<ChargedPolicy> sbtpPiecewise( + std::move(covPtr), startParams, startMom, 1.); + + // Set options for propagator + DenseStepperPropagatorOptions<ActionList<StepCollector>, + AbortList<EndOfWorld>> + propOptsDense(tgContext, mfContext); + abortList.get<EndOfWorld>().maxX = 2. * units::_m; + propOptsDense.actionList = aList; + propOptsDense.abortList = abortList; + propOptsDense.maxSteps = 100; + propOptsDense.maxStepSize = 0.5 * units::_m; + propOptsDense.tolerance = 1e-8; + + // Build stepper and propagator + EigenStepper<ConstantBField, VoidIntersectionCorrector, + StepperExtensionList<DenseEnvironmentExtension>> + esDense(bField); + Propagator<EigenStepper<ConstantBField, VoidIntersectionCorrector, + StepperExtensionList<DenseEnvironmentExtension>>, + Navigator> + propDense(esDense, naviDet); + + // Launch and collect results + const auto& resultDense = + propDense.propagate(sbtpPiecewise, *(surs[1]), propOptsDense).value(); + const StepCollector::this_result& stepResultDense = + resultDense.get<typename StepCollector::result_type>(); + + // Check the exit situation of the second volume + for (unsigned int i = 0; i < stepResultDense.position.size(); i++) { + if (2. * units::_m - stepResultDense.position[i].x() < 1e-4) { + endParams = std::make_pair(stepResultDense.position[i], + stepResultDense.momentum[i]); + break; } - for (unsigned int i = 0; i < stepResult.position.size(); i++) { - if (2. * units::_m - stepResult.position[i].x() < 1e-4) { - endParamsControl - = std::make_pair(stepResult.position[i], stepResult.momentum[i]); - break; - } + } + for (unsigned int i = 0; i < stepResult.position.size(); i++) { + if (2. * units::_m - stepResult.position[i].x() < 1e-4) { + endParamsControl = + std::make_pair(stepResult.position[i], stepResult.momentum[i]); + break; } - - CHECK_CLOSE_ABS(endParams.first, endParamsControl.first, 1. * units::_um); - CHECK_CLOSE_ABS(endParams.second, endParamsControl.second, 1. * units::_um); } + + CHECK_CLOSE_ABS(endParams.first, endParamsControl.first, 1. * units::_um); + CHECK_CLOSE_ABS(endParams.second, endParamsControl.second, 1. * units::_um); +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/Seeding/ATLASBottomBinFinder.hpp b/Tests/Core/Seeding/ATLASBottomBinFinder.hpp index d55d1880d2cc40bf45ec048cedf77bc6e19ebc45..587fd83330e650daf85808dab57e8ee5e239e84b 100644 --- a/Tests/Core/Seeding/ATLASBottomBinFinder.hpp +++ b/Tests/Core/Seeding/ATLASBottomBinFinder.hpp @@ -21,9 +21,8 @@ namespace Acts { /// satisfying the IBinFinder interface. Assumes the grid has 11 bins filled by /// the same logic as ATLAS bins. template <typename SpacePoint> -class ATLASBottomBinFinder : public IBinFinder<SpacePoint> -{ -public: +class ATLASBottomBinFinder : public IBinFinder<SpacePoint> { + public: /// destructor ~ATLASBottomBinFinder() = default; @@ -32,10 +31,8 @@ public: /// @param phiBin phi index of bin with middle space points /// @param zBin z index of bin with middle space points /// @param binnedSP phi-z grid containing all bins - std::set<size_t> - findBins(size_t phiBin, - size_t zBin, - const SpacePointGrid<SpacePoint>* binnedSP); + std::set<size_t> findBins(size_t phiBin, size_t zBin, + const SpacePointGrid<SpacePoint>* binnedSP); }; -} +} // namespace Acts #include "ATLASBottomBinFinder.ipp" diff --git a/Tests/Core/Seeding/ATLASBottomBinFinder.ipp b/Tests/Core/Seeding/ATLASBottomBinFinder.ipp index d005d6a714c146c10b1f6ebae4a2530a60f0c179..a2a5481dae02a97b2d54793b8fb2746844a47b51 100644 --- a/Tests/Core/Seeding/ATLASBottomBinFinder.ipp +++ b/Tests/Core/Seeding/ATLASBottomBinFinder.ipp @@ -9,15 +9,11 @@ // DEBUG: THIS REQUIRES THE BINS TO BE SET TO phi:41 z:11 template <typename SpacePoint> -std::set<size_t> -Acts::ATLASBottomBinFinder<SpacePoint>::findBins( - size_t phiBin, - size_t zBin, - const Acts::SpacePointGrid<SpacePoint>* binnedSP) -{ - - std::set<size_t> neighbourBins - = binnedSP->neighborHoodIndices({phiBin, zBin}, 1); +std::set<size_t> Acts::ATLASBottomBinFinder<SpacePoint>::findBins( + size_t phiBin, size_t zBin, + const Acts::SpacePointGrid<SpacePoint>* binnedSP) { + std::set<size_t> neighbourBins = + binnedSP->neighborHoodIndices({phiBin, zBin}, 1); if (zBin == 6) { neighbourBins.erase(binnedSP->getGlobalBinIndex({phiBin, zBin + 1})); neighbourBins.erase(binnedSP->getGlobalBinIndex({phiBin - 1, zBin + 1})); diff --git a/Tests/Core/Seeding/ATLASCuts.hpp b/Tests/Core/Seeding/ATLASCuts.hpp index 29769deb4dbf6b004ef93b5e6f8f714835934910..78283d9d1c6eced36a947b7f27176cf08ae78b56 100644 --- a/Tests/Core/Seeding/ATLASCuts.hpp +++ b/Tests/Core/Seeding/ATLASCuts.hpp @@ -11,29 +11,25 @@ namespace Acts { template <typename SpacePoint> -class ATLASCuts : public IExperimentCuts<SpacePoint> -{ -public: +class ATLASCuts : public IExperimentCuts<SpacePoint> { + public: /// Returns seed weight bonus/malus depending on detector considerations. /// @param bottom bottom space point of the current seed /// @param middle middle space point of the current seed /// @param top top space point of the current seed /// @return seed weight to be added to the seed's weight - float - seedWeight(const InternalSpacePoint<SpacePoint>& bottom, - const InternalSpacePoint<SpacePoint>& middle, - const InternalSpacePoint<SpacePoint>& top) const; + float seedWeight(const InternalSpacePoint<SpacePoint>& bottom, + const InternalSpacePoint<SpacePoint>& middle, + const InternalSpacePoint<SpacePoint>& top) const; /// @param weight the current seed weight /// @param bottom bottom space point of the current seed /// @param middle middle space point of the current seed /// @param top top space point of the current seed /// @return true if the seed should be kept, false if the seed should be /// discarded - bool - singleSeedCut(float weight, - const InternalSpacePoint<SpacePoint>& bottom, - const InternalSpacePoint<SpacePoint>&, - const InternalSpacePoint<SpacePoint>&) const; + bool singleSeedCut(float weight, const InternalSpacePoint<SpacePoint>& bottom, + const InternalSpacePoint<SpacePoint>&, + const InternalSpacePoint<SpacePoint>&) const; /// @param seeds contains pairs of weight and seed created for one middle /// space @@ -41,18 +37,16 @@ public: /// @return vector of seeds that pass the cut std::vector<std::pair<float, std::unique_ptr<const InternalSeed<SpacePoint>>>> cutPerMiddleSP( - std::vector<std::pair<float, - std::unique_ptr<const InternalSeed<SpacePoint>>>> + std::vector< + std::pair<float, std::unique_ptr<const InternalSeed<SpacePoint>>>> seeds) const; }; template <typename SpacePoint> -float -ATLASCuts<SpacePoint>::seedWeight( +float ATLASCuts<SpacePoint>::seedWeight( const InternalSpacePoint<SpacePoint>& bottom, const InternalSpacePoint<SpacePoint>&, - const InternalSpacePoint<SpacePoint>& top) const -{ + const InternalSpacePoint<SpacePoint>& top) const { float weight = 0; if (bottom.radius() > 150) { weight = 400; @@ -64,23 +58,19 @@ ATLASCuts<SpacePoint>::seedWeight( } template <typename SpacePoint> -bool -ATLASCuts<SpacePoint>::singleSeedCut( - float weight, - const InternalSpacePoint<SpacePoint>& b, +bool ATLASCuts<SpacePoint>::singleSeedCut( + float weight, const InternalSpacePoint<SpacePoint>& b, const InternalSpacePoint<SpacePoint>&, - const InternalSpacePoint<SpacePoint>&) const -{ + const InternalSpacePoint<SpacePoint>&) const { return !(b.radius() > 150. && weight < 380.); } template <typename SpacePoint> std::vector<std::pair<float, std::unique_ptr<const InternalSeed<SpacePoint>>>> ATLASCuts<SpacePoint>::cutPerMiddleSP( - std::vector<std::pair<float, - std::unique_ptr<const InternalSeed<SpacePoint>>>> - seeds) const -{ + std::vector< + std::pair<float, std::unique_ptr<const InternalSeed<SpacePoint>>>> + seeds) const { std::vector<std::pair<float, std::unique_ptr<const InternalSeed<SpacePoint>>>> newSeedsVector; if (seeds.size() > 1) { @@ -96,4 +86,4 @@ ATLASCuts<SpacePoint>::cutPerMiddleSP( } return std::move(seeds); } -} +} // namespace Acts diff --git a/Tests/Core/Seeding/ATLASTopBinFinder.hpp b/Tests/Core/Seeding/ATLASTopBinFinder.hpp index 7a18d71aec3720859290f7794b6e2cd89f5bf1a0..e77c737f754b2592b67a3bd791e59e811677f65c 100644 --- a/Tests/Core/Seeding/ATLASTopBinFinder.hpp +++ b/Tests/Core/Seeding/ATLASTopBinFinder.hpp @@ -21,9 +21,8 @@ namespace Acts { /// satisfying the IBinFinder interface. Assumes the grid has 11 bins filled by /// the same logic as ATLAS bins. template <typename SpacePoint> -class ATLASTopBinFinder : public IBinFinder<SpacePoint> -{ -public: +class ATLASTopBinFinder : public IBinFinder<SpacePoint> { + public: /// Virtual destructor ~ATLASTopBinFinder() = default; @@ -32,11 +31,9 @@ public: /// @param phiBin phi index of bin with middle space points /// @param zBin z index of bin with middle space points /// @param binnedSP phi-z grid containing all bins - std::set<size_t> - findBins(size_t phiBin, - size_t zBin, - const SpacePointGrid<SpacePoint>* binnedSP); + std::set<size_t> findBins(size_t phiBin, size_t zBin, + const SpacePointGrid<SpacePoint>* binnedSP); }; -} +} // namespace Acts #include "ATLASTopBinFinder.ipp" diff --git a/Tests/Core/Seeding/ATLASTopBinFinder.ipp b/Tests/Core/Seeding/ATLASTopBinFinder.ipp index ff5a2dfda9fde9bee61c146d62961a9839daaef6..9a1c89ebd313fd806f1b263d5ab7d4cdeaf8ace3 100644 --- a/Tests/Core/Seeding/ATLASTopBinFinder.ipp +++ b/Tests/Core/Seeding/ATLASTopBinFinder.ipp @@ -8,15 +8,11 @@ // DEBUG: THIS REQUIRES THE BINS TO BE SET TO phi:41 z:11 template <typename SpacePoint> -std::set<size_t> -Acts::ATLASTopBinFinder<SpacePoint>::findBins( - size_t phiBin, - size_t zBin, - const Acts::SpacePointGrid<SpacePoint>* binnedSP) -{ - - std::set<size_t> neighbourBins - = binnedSP->neighborHoodIndices({phiBin, zBin}, 1); +std::set<size_t> Acts::ATLASTopBinFinder<SpacePoint>::findBins( + size_t phiBin, size_t zBin, + const Acts::SpacePointGrid<SpacePoint>* binnedSP) { + std::set<size_t> neighbourBins = + binnedSP->neighborHoodIndices({phiBin, zBin}, 1); if (zBin == 6) { return neighbourBins; } diff --git a/Tests/Core/Seeding/SeedfinderTest.cpp b/Tests/Core/Seeding/SeedfinderTest.cpp index 50d0532b791f524f675e56288f9f19172c1362fe..1c0af88dd8960144025bb9e1696c94c36d3e0129 100644 --- a/Tests/Core/Seeding/SeedfinderTest.cpp +++ b/Tests/Core/Seeding/SeedfinderTest.cpp @@ -23,12 +23,9 @@ #include <sstream> #include <utility> -std::vector<const SpacePoint*> -readFile(std::string filename) -{ - - std::string line; - int layer; +std::vector<const SpacePoint*> readFile(std::string filename) { + std::string line; + int layer; std::vector<const SpacePoint*> readSP; std::ifstream spFile(filename); @@ -36,16 +33,17 @@ readFile(std::string filename) while (!spFile.eof()) { std::getline(spFile, line); std::stringstream ss(line); - std::string linetype; + std::string linetype; ss >> linetype; float x, y, z, r, covr, covz; if (linetype == "lxyz") { ss >> layer >> x >> y >> z >> covr >> covz; - r = std::sqrt(x * x + y * y); - float f22 = covr; - float wid = covz; - float cov = wid * wid * .08333; - if (cov < f22) cov = f22; + r = std::sqrt(x * x + y * y); + float f22 = covr; + float wid = covz; + float cov = wid * wid * .08333; + if (cov < f22) + cov = f22; if (std::abs(z) > 450.) { covz = 9. * cov; covr = .06; @@ -64,37 +62,35 @@ readFile(std::string filename) return readSP; } -int -main() -{ +int main() { std::vector<const SpacePoint*> spVec = readFile("sp.txt"); std::cout << "size of read SP: " << spVec.size() << std::endl; Acts::SeedfinderConfig<SpacePoint> config; // silicon detector max - config.rMax = 160.; - config.deltaRMin = 5.; - config.deltaRMax = 160.; + config.rMax = 160.; + config.deltaRMin = 5.; + config.deltaRMax = 160.; config.collisionRegionMin = -250.; config.collisionRegionMax = 250.; - config.zMin = -2800.; - config.zMax = 2800.; - config.maxSeedsPerSpM = 5; + config.zMin = -2800.; + config.zMax = 2800.; + config.maxSeedsPerSpM = 5; // 2.7 eta - config.cotThetaMax = 7.40627; + config.cotThetaMax = 7.40627; config.sigmaScattering = 1.00000; - config.minPt = 500.; + config.minPt = 500.; config.bFieldInZ = 0.00199724; - config.beamPos = {-.5, -.5}; + config.beamPos = {-.5, -.5}; config.impactMax = 10.; auto bottomBinFinder = std::make_shared<Acts::BinFinder<SpacePoint>>( Acts::BinFinder<SpacePoint>()); auto topBinFinder = std::make_shared<Acts::BinFinder<SpacePoint>>( Acts::BinFinder<SpacePoint>()); - Acts::SeedFilterConfig sfconf; + Acts::SeedFilterConfig sfconf; Acts::ATLASCuts<SpacePoint> atlasCuts = Acts::ATLASCuts<SpacePoint>(); config.seedFilter = std::make_unique<Acts::SeedFilter<SpacePoint>>( Acts::SeedFilter<SpacePoint>(sfconf, &atlasCuts)); @@ -109,11 +105,10 @@ main() spVec.begin(), spVec.end(), ct, bottomBinFinder, topBinFinder); auto start = std::chrono::system_clock::now(); for (Acts::SeedfinderStateIterator<SpacePoint> it = state.begin(); - !(it == state.end()); - ++it) { + !(it == state.end()); ++it) { a.createSeedsForRegion(it, state); } - auto end = std::chrono::system_clock::now(); + auto end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end - start; std::cout << "time to create seeds: " << elapsed_seconds.count() << std::endl; std::cout << "Number of regions: " << state.outputVec.size() << std::endl; @@ -125,7 +120,7 @@ main() for (auto& regionVec : state.outputVec) { for (size_t i = 0; i < regionVec.size(); i++) { const Acts::Seed<SpacePoint>* seed = regionVec[i].get(); - const SpacePoint* sp = seed->sp()[0]; + const SpacePoint* sp = seed->sp()[0]; std::cout << " (" << sp->x() << ", " << sp->y() << ", " << sp->z() << ") "; sp = seed->sp()[1]; diff --git a/Tests/Core/Seeding/SpacePoint.hpp b/Tests/Core/Seeding/SpacePoint.hpp index 377c9c1085b8413c080e829ea9144af9c0483a18..25d7ed12a3be2fbac1b85bbe8018f5a1577ea789 100644 --- a/Tests/Core/Seeding/SpacePoint.hpp +++ b/Tests/Core/Seeding/SpacePoint.hpp @@ -7,33 +7,16 @@ // file, You can obtain one at http://mozilla.org/MPL/2.0/. #pragma once -struct SpacePoint -{ +struct SpacePoint { float m_x; float m_y; float m_z; float m_r; - int surface; + int surface; float covr; float covz; - float - x() const - { - return m_x; - } - float - y() const - { - return m_y; - } - float - z() const - { - return m_z; - } - float - r() const - { - return m_r; - } + float x() const { return m_x; } + float y() const { return m_y; } + float z() const { return m_z; } + float r() const { return m_r; } }; diff --git a/Tests/Core/Seeding/TestCovarianceTool.hpp b/Tests/Core/Seeding/TestCovarianceTool.hpp index f300fbf67a8ffe29917e1561a1a997a111c9e2d9..dfc07a1b9805048f50463d0ad1ccfeb2f842349c 100644 --- a/Tests/Core/Seeding/TestCovarianceTool.hpp +++ b/Tests/Core/Seeding/TestCovarianceTool.hpp @@ -9,9 +9,8 @@ #pragma once namespace Acts { -class CovarianceTool -{ -public: +class CovarianceTool { + public: /// Virtual destructor ~CovarianceTool() = default; @@ -26,22 +25,16 @@ public: /// @param sigma is multiplied with the combined alignment and covariance /// errors template <typename SpacePoint> - Acts::Vector2D - getCovariances(const SpacePoint* sp, - float zAlign = 0, - float rAlign = 0, - float sigma = 1); + Acts::Vector2D getCovariances(const SpacePoint* sp, float zAlign = 0, + float rAlign = 0, float sigma = 1); }; template <typename SpacePoint> -inline Acts::Vector2D -CovarianceTool::getCovariances(const SpacePoint* sp, - float zAlign, - float rAlign, - float sigma) -{ +inline Acts::Vector2D CovarianceTool::getCovariances(const SpacePoint* sp, + float zAlign, float rAlign, + float sigma) { Acts::Vector2D cov; cov[0] = ((*sp).covr + rAlign * rAlign) * sigma; cov[1] = ((*sp).covz + zAlign * zAlign) * sigma; return cov; } -} +} // namespace Acts diff --git a/Tests/Core/Surfaces/BoundaryCheckBenchmark.cpp b/Tests/Core/Surfaces/BoundaryCheckBenchmark.cpp index 2c31445b3cfb8668b90fa45a4841044e30556f75..f2b45c84f92e39bb731d8f091688abcb90590f3f 100644 --- a/Tests/Core/Surfaces/BoundaryCheckBenchmark.cpp +++ b/Tests/Core/Surfaces/BoundaryCheckBenchmark.cpp @@ -21,16 +21,14 @@ using namespace Acts; constexpr int NTESTS = 2 << 15; // trapezoidal area -static const Vector2D POLY[] - = {{0.4, 0.25}, {0.6, 0.25}, {0.8, 0.75}, {0.2, 0.75}}; +static const Vector2D POLY[] = { + {0.4, 0.25}, {0.6, 0.25}, {0.8, 0.75}, {0.2, 0.75}}; -std::vector<Vector2D> -make_random_points() -{ - std::mt19937 rng(42); +std::vector<Vector2D> make_random_points() { + std::mt19937 rng(42); std::uniform_real_distribution<double> axis(0, 1); - auto rnd_axis = std::bind(axis, rng); + auto rnd_axis = std::bind(axis, rng); auto rnd_point = [&]() { return Vector2D(rnd_axis(), rnd_axis()); }; std::vector<Vector2D> points(NTESTS); @@ -61,28 +59,23 @@ make_random_points() // return check.TestKDOPKDOP(limits, limitsErr); //} -inline bool -isInside(const Vector2D& point, const BoundaryCheck& check) -{ +inline bool isInside(const Vector2D& point, const BoundaryCheck& check) { return check.isInside(point, POLY); } -struct StopWatch -{ - using Clock = std::chrono::high_resolution_clock; +struct StopWatch { + using Clock = std::chrono::high_resolution_clock; using TimePoint = Clock::time_point; TimePoint start; StopWatch() : start(Clock::now()) {} - void - finish(size_t n_trials, const char* name) - { + void finish(size_t n_trials, const char* name) { auto stop = Clock::now(); std::chrono::duration<double, std::micro> total = stop - start; - std::chrono::duration<double, std::micro> perTrial - = (stop - start) / n_trials; + std::chrono::duration<double, std::micro> perTrial = + (stop - start) / n_trials; std::cout << name << ":\n"; std::cout << " trials: " << n_trials << '\n'; @@ -91,17 +84,15 @@ struct StopWatch } }; -int -main(int /*argc*/, char** /*argv[]*/) -{ +int main(int /*argc*/, char** /*argv[]*/) { using std::cout; // absolute check w/o tolerance { - auto points = make_random_points(); + auto points = make_random_points(); BoundaryCheck check(true); - int n_inside = 0; - StopWatch watch; + int n_inside = 0; + StopWatch watch; for (const auto& point : points) { n_inside += (isInside(point, check) ? 1 : 0); } @@ -109,12 +100,12 @@ main(int /*argc*/, char** /*argv[]*/) } // check w/ covariance { - auto points = make_random_points(); + auto points = make_random_points(); ActsSymMatrixD<2> cov; cov << 0.2, 0.02, 0.15, 0.02; BoundaryCheck check(cov, 3.0); // 3-sigma cut - int n_inside = 0; - StopWatch watch; + int n_inside = 0; + StopWatch watch; for (const auto& point : points) { n_inside += (isInside(point, check) ? 1 : 0); } diff --git a/Tests/Core/Surfaces/BoundaryCheckTests.cpp b/Tests/Core/Surfaces/BoundaryCheckTests.cpp index 72eac113d03fff87dce8fed6d8ce04d96e5fe0c8..d5fad428e95eb3a271ca7712fecd7c9246c38c04 100644 --- a/Tests/Core/Surfaces/BoundaryCheckTests.cpp +++ b/Tests/Core/Surfaces/BoundaryCheckTests.cpp @@ -21,121 +21,113 @@ namespace Acts { namespace Test { - BOOST_AUTO_TEST_SUITE(Surfaces) - // See: https://en.wikipedia.org/wiki/Bounding_volume - // - // Aligned box w/ simple check - BOOST_AUTO_TEST_CASE(BoundaryCheckBoxSimple) - { - BoundaryCheck check(true); - Vector2D ll(-1, -1); - Vector2D ur(1, 1); - BOOST_CHECK(check.isInside({0, 0}, ll, ur)); - BOOST_CHECK(!check.isInside({2, 2}, ll, ur)); - BOOST_CHECK(!check.isInside({0, 2}, ll, ur)); - BOOST_CHECK(!check.isInside({2, 0}, ll, ur)); - } - // Aligned box w/ tolerance check along first axis - BOOST_AUTO_TEST_CASE(BoundaryCheckBoxToleranceLoc0) - { - BoundaryCheck check(true, false, 1.5, 0.0); - Vector2D ll(-1, -1); - Vector2D ur(1, 1); - BOOST_CHECK(check.isInside({0, 0}, ll, ur)); - BOOST_CHECK(check.isInside({2, 2}, ll, ur)); - BOOST_CHECK(!check.isInside({4, 4}, ll, ur)); - BOOST_CHECK(check.isInside({0, 2}, ll, ur)); - BOOST_CHECK(check.isInside({2, 0}, ll, ur)); - } - - BOOST_AUTO_TEST_CASE(BoundaryCheckBoxDistance) - { +BOOST_AUTO_TEST_SUITE(Surfaces) +// See: https://en.wikipedia.org/wiki/Bounding_volume +// +// Aligned box w/ simple check +BOOST_AUTO_TEST_CASE(BoundaryCheckBoxSimple) { + BoundaryCheck check(true); + Vector2D ll(-1, -1); + Vector2D ur(1, 1); + BOOST_CHECK(check.isInside({0, 0}, ll, ur)); + BOOST_CHECK(!check.isInside({2, 2}, ll, ur)); + BOOST_CHECK(!check.isInside({0, 2}, ll, ur)); + BOOST_CHECK(!check.isInside({2, 0}, ll, ur)); +} +// Aligned box w/ tolerance check along first axis +BOOST_AUTO_TEST_CASE(BoundaryCheckBoxToleranceLoc0) { + BoundaryCheck check(true, false, 1.5, 0.0); + Vector2D ll(-1, -1); + Vector2D ur(1, 1); + BOOST_CHECK(check.isInside({0, 0}, ll, ur)); + BOOST_CHECK(check.isInside({2, 2}, ll, ur)); + BOOST_CHECK(!check.isInside({4, 4}, ll, ur)); + BOOST_CHECK(check.isInside({0, 2}, ll, ur)); + BOOST_CHECK(check.isInside({2, 0}, ll, ur)); +} +BOOST_AUTO_TEST_CASE(BoundaryCheckBoxDistance) { #include "BoundaryCheckTestsRefs.hpp" - BoundaryCheck bcheck(true); - - for (size_t i = 0; i < rectTestPoints.size(); i++) { - const Vector2D& testPoint = rectTestPoints.at(i); - double refDistance = rectDistances.at(i); - Vector2D ll(rectDimensions.xmin, rectDimensions.ymin); - Vector2D ur(rectDimensions.xmax, rectDimensions.ymax); - double distance = bcheck.distance(testPoint, ll, ur); - CHECK_CLOSE_REL(refDistance, distance, 1e-6); - } + BoundaryCheck bcheck(true); - for (size_t i = 0; i < rectShiftedTestPoints.size(); i++) { - const Vector2D& testPoint = rectShiftedTestPoints.at(i); - double refDistance = rectShiftedDistances.at(i); - Vector2D ll(rectShiftedDimensions.xmin, rectShiftedDimensions.ymin); - Vector2D ur(rectShiftedDimensions.xmax, rectShiftedDimensions.ymax); - double distance = bcheck.distance(testPoint, ll, ur); - CHECK_CLOSE_REL(refDistance, distance, 1e-6); - } + for (size_t i = 0; i < rectTestPoints.size(); i++) { + const Vector2D& testPoint = rectTestPoints.at(i); + double refDistance = rectDistances.at(i); + Vector2D ll(rectDimensions.xmin, rectDimensions.ymin); + Vector2D ur(rectDimensions.xmax, rectDimensions.ymax); + double distance = bcheck.distance(testPoint, ll, ur); + CHECK_CLOSE_REL(refDistance, distance, 1e-6); } - // Aligned box w/ covariance check - BOOST_AUTO_TEST_CASE(BoundaryCheckBoxCovariance) - { - ActsSymMatrixD<2> cov; - cov << 1, 0.5, 0.5, 2; - BoundaryCheck check(cov, 3.0); - Vector2D ll(-1, -1); - Vector2D ur(1, 1); - BOOST_CHECK(check.isInside({0, 0}, ll, ur)); - BOOST_CHECK(check.isInside({2, 2}, ll, ur)); - BOOST_CHECK(!check.isInside({4, 4}, ll, ur)); - BOOST_CHECK(check.isInside({0, 3}, ll, ur)); - BOOST_CHECK(check.isInside({3, 0}, ll, ur)); + for (size_t i = 0; i < rectShiftedTestPoints.size(); i++) { + const Vector2D& testPoint = rectShiftedTestPoints.at(i); + double refDistance = rectShiftedDistances.at(i); + Vector2D ll(rectShiftedDimensions.xmin, rectShiftedDimensions.ymin); + Vector2D ur(rectShiftedDimensions.xmax, rectShiftedDimensions.ymax); + double distance = bcheck.distance(testPoint, ll, ur); + CHECK_CLOSE_REL(refDistance, distance, 1e-6); } +} - BOOST_AUTO_TEST_CASE(BoundaryCheckPolyDistance) - { -// we check a box again, but this time described as a poly +// Aligned box w/ covariance check +BOOST_AUTO_TEST_CASE(BoundaryCheckBoxCovariance) { + ActsSymMatrixD<2> cov; + cov << 1, 0.5, 0.5, 2; + BoundaryCheck check(cov, 3.0); + Vector2D ll(-1, -1); + Vector2D ur(1, 1); + BOOST_CHECK(check.isInside({0, 0}, ll, ur)); + BOOST_CHECK(check.isInside({2, 2}, ll, ur)); + BOOST_CHECK(!check.isInside({4, 4}, ll, ur)); + BOOST_CHECK(check.isInside({0, 3}, ll, ur)); + BOOST_CHECK(check.isInside({3, 0}, ll, ur)); +} -#include "BoundaryCheckTestsRefs.hpp" +BOOST_AUTO_TEST_CASE(BoundaryCheckPolyDistance) { + // we check a box again, but this time described as a poly - BoundaryCheck bcheck(true); +#include "BoundaryCheckTestsRefs.hpp" - for (size_t i = 0; i < rectTestPoints.size(); i++) { - const Vector2D& testPoint = rectTestPoints.at(i); - double refDistance = rectDistances.at(i); - double distance = bcheck.distance(testPoint, rectVertices); - CHECK_CLOSE_REL(refDistance, distance, 1e-6); - } + BoundaryCheck bcheck(true); - for (size_t i = 0; i < rectShiftedTestPoints.size(); i++) { - const Vector2D& testPoint = rectShiftedTestPoints.at(i); - double refDistance = rectShiftedDistances.at(i); - double distance = bcheck.distance(testPoint, rectShiftedVertices); - CHECK_CLOSE_REL(refDistance, distance, 1e-6); - } + for (size_t i = 0; i < rectTestPoints.size(); i++) { + const Vector2D& testPoint = rectTestPoints.at(i); + double refDistance = rectDistances.at(i); + double distance = bcheck.distance(testPoint, rectVertices); + CHECK_CLOSE_REL(refDistance, distance, 1e-6); } - // Triangle w/ simple check - BOOST_AUTO_TEST_CASE(BoundaryCheckTriangleSimple) - { - Vector2D vertices[] = {{-2, 0}, {2, 0}, {0, 2}}; - BoundaryCheck check(true); - BOOST_CHECK(check.isInside({0, 0}, vertices)); - BOOST_CHECK(check.isInside({0, 1}, vertices)); - BOOST_CHECK(!check.isInside({2, 2}, vertices)); - BOOST_CHECK(!check.isInside({0, -1}, vertices)); + for (size_t i = 0; i < rectShiftedTestPoints.size(); i++) { + const Vector2D& testPoint = rectShiftedTestPoints.at(i); + double refDistance = rectShiftedDistances.at(i); + double distance = bcheck.distance(testPoint, rectShiftedVertices); + CHECK_CLOSE_REL(refDistance, distance, 1e-6); } - // Triangle w/ covariance check - BOOST_AUTO_TEST_CASE(BoundaryCheckTriangleCovariance) - { - Vector2D vertices[] = {{-2, 0}, {2, 0}, {0, 2}}; - ActsSymMatrixD<2> cov; - cov << 0.5, 0, 0, 0.5; - BoundaryCheck check(cov, 4.1); - BOOST_CHECK(check.isInside({0, 0}, vertices)); - BOOST_CHECK(check.isInside({0, 1}, vertices)); - BOOST_CHECK(check.isInside({0, 2}, vertices)); - BOOST_CHECK(check.isInside({0, 3}, vertices)); - BOOST_CHECK(check.isInside({0, 4}, vertices)); - BOOST_CHECK(!check.isInside({0, 5}, vertices)); - } - BOOST_AUTO_TEST_SUITE_END() +} + +// Triangle w/ simple check +BOOST_AUTO_TEST_CASE(BoundaryCheckTriangleSimple) { + Vector2D vertices[] = {{-2, 0}, {2, 0}, {0, 2}}; + BoundaryCheck check(true); + BOOST_CHECK(check.isInside({0, 0}, vertices)); + BOOST_CHECK(check.isInside({0, 1}, vertices)); + BOOST_CHECK(!check.isInside({2, 2}, vertices)); + BOOST_CHECK(!check.isInside({0, -1}, vertices)); +} +// Triangle w/ covariance check +BOOST_AUTO_TEST_CASE(BoundaryCheckTriangleCovariance) { + Vector2D vertices[] = {{-2, 0}, {2, 0}, {0, 2}}; + ActsSymMatrixD<2> cov; + cov << 0.5, 0, 0, 0.5; + BoundaryCheck check(cov, 4.1); + BOOST_CHECK(check.isInside({0, 0}, vertices)); + BOOST_CHECK(check.isInside({0, 1}, vertices)); + BOOST_CHECK(check.isInside({0, 2}, vertices)); + BOOST_CHECK(check.isInside({0, 3}, vertices)); + BOOST_CHECK(check.isInside({0, 4}, vertices)); + BOOST_CHECK(!check.isInside({0, 5}, vertices)); +} +BOOST_AUTO_TEST_SUITE_END() } // namespace Test } // namespace Acts diff --git a/Tests/Core/Surfaces/ConeBoundsTests.cpp b/Tests/Core/Surfaces/ConeBoundsTests.cpp index 605ba9291bb7c4664e70005c1fed4e1b7778c617..0a76875f00adbdfcb3c882396def451acf9c46e9 100644 --- a/Tests/Core/Surfaces/ConeBoundsTests.cpp +++ b/Tests/Core/Surfaces/ConeBoundsTests.cpp @@ -33,100 +33,95 @@ namespace Acts { namespace Test { - BOOST_AUTO_TEST_SUITE(Surfaces) - /// Unit test for creating compliant/non-compliant ConeBounds object - BOOST_AUTO_TEST_CASE(ConeBoundsConstruction) - { - // test default construction - // ConeBounds defaultConstructedConeBounds; // deleted - double alpha(M_PI / 8.0), zMin(3.), zMax(6.), halfPhi(M_PI / 4.0), - averagePhi(0.); - const bool symmetric(false); - BOOST_TEST_CHECKPOINT("Four parameter constructor (last two at default)"); - ConeBounds defaultConeBounds(alpha, symmetric); - BOOST_CHECK_EQUAL(defaultConeBounds.type(), SurfaceBounds::Cone); - BOOST_TEST_CHECKPOINT("Four parameter constructor"); - ConeBounds fourParameterConstructed(alpha, symmetric, halfPhi, averagePhi); - BOOST_CHECK_EQUAL(fourParameterConstructed.type(), SurfaceBounds::Cone); - BOOST_TEST_CHECKPOINT("Five parameter constructor (last two at default)"); - ConeBounds defaulted5ParamConeBounds(alpha, zMin, zMax); - BOOST_CHECK_EQUAL(defaulted5ParamConeBounds.type(), SurfaceBounds::Cone); - BOOST_TEST_CHECKPOINT("Five parameter constructor)"); - ConeBounds fiveParamConstructedConeBounds( - alpha, zMin, zMax, halfPhi, averagePhi); - BOOST_CHECK_EQUAL(fiveParamConstructedConeBounds.type(), - SurfaceBounds::Cone); - BOOST_TEST_CHECKPOINT("Copy constructor"); - ConeBounds copyConstructedConeBounds(fiveParamConstructedConeBounds); - BOOST_CHECK_EQUAL(copyConstructedConeBounds, - fiveParamConstructedConeBounds); - auto pClonedConeBounds = fiveParamConstructedConeBounds.clone(); - BOOST_CHECK_EQUAL(*pClonedConeBounds, fiveParamConstructedConeBounds); - delete pClonedConeBounds; - } - /// Unit tests for properties of ConeBounds object - BOOST_AUTO_TEST_CASE(ConeBoundsProperties) - { - double alpha(M_PI / 8.0), zMin(3.), zMax(6.), halfPhi(M_PI / 4.0), - averagePhi(0.); - // const bool symmetric(false); - const Vector2D origin(0, 0); - const Vector2D somewhere(4., 4.); - ConeBounds coneBoundsObject(alpha, zMin, zMax, halfPhi, averagePhi); - // - /// test for type (redundant) - BOOST_CHECK_EQUAL(coneBoundsObject.type(), SurfaceBounds::Cone); - // - /// test for inside - BOOST_CHECK(!coneBoundsObject.inside(origin)); - // - /// test for distanceToBoundary - // std::cout << coneBoundsObject.distanceToBoundary(origin) << std::endl; - // - /// test for r - CHECK_CLOSE_REL(coneBoundsObject.r(zMin), zMin * std::tan(alpha), 1e-6); - // - /// test for tanAlpha - CHECK_CLOSE_REL(coneBoundsObject.tanAlpha(), std::tan(alpha), 1e-6); - // - /// test for sinAlpha - CHECK_CLOSE_REL(coneBoundsObject.sinAlpha(), std::sin(alpha), 1e-6); - // - /// test for cosAlpha - CHECK_CLOSE_REL(coneBoundsObject.cosAlpha(), std::cos(alpha), 1e-6); - // - /// test for alpha - CHECK_CLOSE_REL(coneBoundsObject.alpha(), alpha, 1e-6); - // - /// test for minZ - CHECK_CLOSE_REL(coneBoundsObject.minZ(), zMin, 1e-6); - // - /// test for maxZ - CHECK_CLOSE_REL(coneBoundsObject.maxZ(), zMax, 1e-6); - // - /// test for averagePhi - CHECK_CLOSE_REL(coneBoundsObject.halfPhiSector(), halfPhi, 1e-6); - // - /// test for dump - boost::test_tools::output_test_stream dumpOuput; - coneBoundsObject.toStream(dumpOuput); - BOOST_CHECK(dumpOuput.is_equal( - "Acts::ConeBounds: (tanAlpha, minZ, maxZ, averagePhi, halfPhiSector) = " - "(0.4142136, 3.0000000, 6.0000000, 0.0000000, 0.7853982)")); - } - /// Unit test for testing ConeBounds assignment - BOOST_AUTO_TEST_CASE(ConeBoundsAssignment) - { - double alpha(M_PI / 8.0), zMin(3.), zMax(6.), halfPhi(M_PI / 4.0), - averagePhi(0.); - // const bool symmetric(false); - ConeBounds originalConeBounds(alpha, zMin, zMax, halfPhi, averagePhi); - ConeBounds assignedConeBounds(0.1, 2.3, 4.5, 1.2, 2.1); - assignedConeBounds = originalConeBounds; - BOOST_CHECK_EQUAL(assignedConeBounds, originalConeBounds); - } +BOOST_AUTO_TEST_SUITE(Surfaces) +/// Unit test for creating compliant/non-compliant ConeBounds object +BOOST_AUTO_TEST_CASE(ConeBoundsConstruction) { + // test default construction + // ConeBounds defaultConstructedConeBounds; // deleted + double alpha(M_PI / 8.0), zMin(3.), zMax(6.), halfPhi(M_PI / 4.0), + averagePhi(0.); + const bool symmetric(false); + BOOST_TEST_CHECKPOINT("Four parameter constructor (last two at default)"); + ConeBounds defaultConeBounds(alpha, symmetric); + BOOST_CHECK_EQUAL(defaultConeBounds.type(), SurfaceBounds::Cone); + BOOST_TEST_CHECKPOINT("Four parameter constructor"); + ConeBounds fourParameterConstructed(alpha, symmetric, halfPhi, averagePhi); + BOOST_CHECK_EQUAL(fourParameterConstructed.type(), SurfaceBounds::Cone); + BOOST_TEST_CHECKPOINT("Five parameter constructor (last two at default)"); + ConeBounds defaulted5ParamConeBounds(alpha, zMin, zMax); + BOOST_CHECK_EQUAL(defaulted5ParamConeBounds.type(), SurfaceBounds::Cone); + BOOST_TEST_CHECKPOINT("Five parameter constructor)"); + ConeBounds fiveParamConstructedConeBounds(alpha, zMin, zMax, halfPhi, + averagePhi); + BOOST_CHECK_EQUAL(fiveParamConstructedConeBounds.type(), SurfaceBounds::Cone); + BOOST_TEST_CHECKPOINT("Copy constructor"); + ConeBounds copyConstructedConeBounds(fiveParamConstructedConeBounds); + BOOST_CHECK_EQUAL(copyConstructedConeBounds, fiveParamConstructedConeBounds); + auto pClonedConeBounds = fiveParamConstructedConeBounds.clone(); + BOOST_CHECK_EQUAL(*pClonedConeBounds, fiveParamConstructedConeBounds); + delete pClonedConeBounds; +} +/// Unit tests for properties of ConeBounds object +BOOST_AUTO_TEST_CASE(ConeBoundsProperties) { + double alpha(M_PI / 8.0), zMin(3.), zMax(6.), halfPhi(M_PI / 4.0), + averagePhi(0.); + // const bool symmetric(false); + const Vector2D origin(0, 0); + const Vector2D somewhere(4., 4.); + ConeBounds coneBoundsObject(alpha, zMin, zMax, halfPhi, averagePhi); + // + /// test for type (redundant) + BOOST_CHECK_EQUAL(coneBoundsObject.type(), SurfaceBounds::Cone); + // + /// test for inside + BOOST_CHECK(!coneBoundsObject.inside(origin)); + // + /// test for distanceToBoundary + // std::cout << coneBoundsObject.distanceToBoundary(origin) << std::endl; + // + /// test for r + CHECK_CLOSE_REL(coneBoundsObject.r(zMin), zMin * std::tan(alpha), 1e-6); + // + /// test for tanAlpha + CHECK_CLOSE_REL(coneBoundsObject.tanAlpha(), std::tan(alpha), 1e-6); + // + /// test for sinAlpha + CHECK_CLOSE_REL(coneBoundsObject.sinAlpha(), std::sin(alpha), 1e-6); + // + /// test for cosAlpha + CHECK_CLOSE_REL(coneBoundsObject.cosAlpha(), std::cos(alpha), 1e-6); + // + /// test for alpha + CHECK_CLOSE_REL(coneBoundsObject.alpha(), alpha, 1e-6); + // + /// test for minZ + CHECK_CLOSE_REL(coneBoundsObject.minZ(), zMin, 1e-6); + // + /// test for maxZ + CHECK_CLOSE_REL(coneBoundsObject.maxZ(), zMax, 1e-6); + // + /// test for averagePhi + CHECK_CLOSE_REL(coneBoundsObject.halfPhiSector(), halfPhi, 1e-6); + // + /// test for dump + boost::test_tools::output_test_stream dumpOuput; + coneBoundsObject.toStream(dumpOuput); + BOOST_CHECK(dumpOuput.is_equal( + "Acts::ConeBounds: (tanAlpha, minZ, maxZ, averagePhi, halfPhiSector) = " + "(0.4142136, 3.0000000, 6.0000000, 0.0000000, 0.7853982)")); +} +/// Unit test for testing ConeBounds assignment +BOOST_AUTO_TEST_CASE(ConeBoundsAssignment) { + double alpha(M_PI / 8.0), zMin(3.), zMax(6.), halfPhi(M_PI / 4.0), + averagePhi(0.); + // const bool symmetric(false); + ConeBounds originalConeBounds(alpha, zMin, zMax, halfPhi, averagePhi); + ConeBounds assignedConeBounds(0.1, 2.3, 4.5, 1.2, 2.1); + assignedConeBounds = originalConeBounds; + BOOST_CHECK_EQUAL(assignedConeBounds, originalConeBounds); +} - BOOST_AUTO_TEST_SUITE_END() +BOOST_AUTO_TEST_SUITE_END() } // namespace Test diff --git a/Tests/Core/Surfaces/ConeSurfaceTests.cpp b/Tests/Core/Surfaces/ConeSurfaceTests.cpp index 2ee4e5d04aab2d1e86a735c6b57d29c80216429f..885b9c02f5cf5017b6365e30dff5a4c8be52ac23 100644 --- a/Tests/Core/Surfaces/ConeSurfaceTests.cpp +++ b/Tests/Core/Surfaces/ConeSurfaceTests.cpp @@ -29,213 +29,201 @@ namespace Acts { namespace Test { - // Create a test context - GeometryContext tgContext = GeometryContext(); - - BOOST_AUTO_TEST_SUITE(ConeSurfaces) - /// Unit test for creating compliant/non-compliant ConeSurface object - BOOST_AUTO_TEST_CASE(ConeSurfaceConstruction) - { - // ConeSurface default constructor is deleted - // - /// Constructor with transform pointer, null or valid, alpha and symmetry - /// indicator - double alpha{M_PI / 8.}, halfPhiSector{M_PI / 16.}, zMin{1.0}, zMax{10.}; - bool symmetric(false); - Translation3D translation{0., 1., 2.}; - auto pTransform = std::make_shared<const Transform3D>(translation); - auto pNullTransform = std::make_shared<const Transform3D>(); - BOOST_CHECK_EQUAL( - Surface::makeShared<ConeSurface>(pNullTransform, alpha, symmetric) - ->type(), - Surface::Cone); - BOOST_CHECK_EQUAL( - Surface::makeShared<ConeSurface>(pTransform, alpha, symmetric)->type(), - Surface::Cone); - // - /// Constructor with transform pointer, alpha,z min and max, halfPhiSector - BOOST_CHECK_EQUAL(Surface::makeShared<ConeSurface>( - pTransform, alpha, zMin, zMax, halfPhiSector) - ->type(), - Surface::Cone); - // - - /// Constructor with transform and ConeBounds pointer - // ConeBounds (double alpha, double zmin, double zmax, double halfphi=M_PI, - // double avphi=0.) - auto pConeBounds = std::make_shared<const ConeBounds>( - alpha, zMin, zMax, halfPhiSector, 0.); - BOOST_CHECK_EQUAL( - Surface::makeShared<ConeSurface>(pTransform, pConeBounds)->type(), - Surface::Cone); - // - // - /// Copy constructor - auto coneSurfaceObject - = Surface::makeShared<ConeSurface>(pTransform, alpha, symmetric); - auto copiedConeSurface - = Surface::makeShared<ConeSurface>(*coneSurfaceObject); - BOOST_CHECK_EQUAL(copiedConeSurface->type(), Surface::Cone); - BOOST_CHECK(*copiedConeSurface == *coneSurfaceObject); - // - /// Copied and transformed - auto copiedTransformedConeSurface = Surface::makeShared<ConeSurface>( - tgContext, *coneSurfaceObject, *pTransform); - BOOST_CHECK_EQUAL(copiedTransformedConeSurface->type(), Surface::Cone); - - /// Construct with nullptr bounds - BOOST_CHECK_THROW(auto nullBounds - = Surface::makeShared<ConeSurface>(nullptr, nullptr), - AssertionFailureException); - } - // - /// Unit test for testing ConeSurface properties - BOOST_AUTO_TEST_CASE(ConeSurfaceProperties) - { - /// Test clone method - double alpha{M_PI / 8.} /*,halfPhiSector{M_PI/16.}, zMin{1.0}, zMax{10.}*/; - bool symmetric(false); - Translation3D translation{0., 1., 2.}; - auto pTransform = std::make_shared<const Transform3D>(translation); - // auto pNullTransform = std::make_shared<const Transform3D>(); - auto coneSurfaceObject - = Surface::makeShared<ConeSurface>(pTransform, alpha, symmetric); - // - auto pClonedConeSurface - = coneSurfaceObject->clone(tgContext, Transform3D::Identity()); - BOOST_CHECK_EQUAL(pClonedConeSurface->type(), Surface::Cone); - // - /// Test type (redundant) - BOOST_CHECK_EQUAL(coneSurfaceObject->type(), Surface::Cone); - // - /// Test binningPosition - Vector3D binningPosition{0., 1., 2.}; - CHECK_CLOSE_ABS( - coneSurfaceObject->binningPosition(tgContext, BinningValue::binPhi), - binningPosition, - 1e-6); - // - /// Test referenceFrame - Vector3D globalPosition{2.0, 2.0, 2.0}; - Vector3D momentum{1.e6, 1.e6, 1.e6}; - double rootHalf = std::sqrt(0.5); - RotationMatrix3D expectedFrame; - expectedFrame << -rootHalf, 0., rootHalf, rootHalf, 0., rootHalf, 0., 1., - 0.; - CHECK_CLOSE_OR_SMALL( - coneSurfaceObject->referenceFrame(tgContext, globalPosition, momentum), - expectedFrame, - 1e-6, - 1e-9); - // - /// Test normal, given 3D position - Vector3D origin{0., 0., 0.}; - Vector3D normal3D = {0., -1., 0.}; - CHECK_CLOSE_ABS( - coneSurfaceObject->normal(tgContext, origin), normal3D, 1e-6); - // - /// Test normal given 2D rphi position - Vector2D positionPiBy2(1.0, M_PI / 2.); - Vector3D normalAtPiBy2{0.0312768, 0.92335, -0.382683}; - - CHECK_CLOSE_OR_SMALL(coneSurfaceObject->normal(tgContext, positionPiBy2), - normalAtPiBy2, - 1e-2, - 1e-9); - // - /// Test rotational symmetry axis - Vector3D symmetryAxis{0., 0., 1.}; - CHECK_CLOSE_ABS( - coneSurfaceObject->rotSymmetryAxis(tgContext), symmetryAxis, 1e-6); - // - /// Test bounds - BOOST_CHECK_EQUAL(coneSurfaceObject->bounds().type(), SurfaceBounds::Cone); - // - /// Test localToGlobal - Vector2D localPosition{1.0, M_PI / 2.0}; - coneSurfaceObject->localToGlobal( - tgContext, localPosition, momentum, globalPosition); - // std::cout<<globalPosition<<std::endl; - Vector3D expectedPosition{0.0220268, 1.65027, 3.5708}; - - CHECK_CLOSE_REL(globalPosition, expectedPosition, 1e-2); - // - /// Testing globalToLocal - coneSurfaceObject->globalToLocal( - tgContext, globalPosition, momentum, localPosition); - // std::cout<<localPosition<<std::endl; - Vector2D expectedLocalPosition{1.0, M_PI / 2.0}; - - CHECK_CLOSE_REL(localPosition, expectedLocalPosition, 1e-6); - // - /// Test isOnSurface - Vector3D offSurface{100, 1, 2}; - BOOST_CHECK(coneSurfaceObject->isOnSurface( - tgContext, globalPosition, momentum, true)); - BOOST_CHECK( - !coneSurfaceObject->isOnSurface(tgContext, offSurface, momentum, true)); - // - /// intersectionEstimate - Vector3D direction{-1., 0, 0}; - auto intersect = coneSurfaceObject->intersectionEstimate( - tgContext, offSurface, direction, forward, false); - Intersection expectedIntersect{Vector3D{0, 1, 2}, 100., true, 0}; - BOOST_CHECK(intersect.valid); - CHECK_CLOSE_ABS(intersect.position, expectedIntersect.position, 1e-6); - CHECK_CLOSE_ABS(intersect.pathLength, expectedIntersect.pathLength, 1e-6); - CHECK_CLOSE_ABS(intersect.distance, expectedIntersect.distance, 1e-6); - // - /// Test pathCorrection - CHECK_CLOSE_REL( - coneSurfaceObject->pathCorrection(tgContext, offSurface, momentum), - 0.40218866453252877, - 0.01); - // - /// Test name - BOOST_CHECK_EQUAL(coneSurfaceObject->name(), - std::string("Acts::ConeSurface")); - // - /// Test dump - // TODO 2017-04-12 msmk: check how to correctly check output - // boost::test_tools::output_test_stream dumpOuput; - // coneSurfaceObject.toStream(dumpOuput); - // BOOST_CHECK(dumpOuput.is_equal( - // "Acts::ConeSurface\n" - // " Center position (x, y, z) = (0.0000, 1.0000, 2.0000)\n" - // " Rotation: colX = (1.000000, 0.000000, 0.000000)\n" - // " colY = (0.000000, 1.000000, 0.000000)\n" - // " colZ = (0.000000, 0.000000, 1.000000)\n" - // " Bounds : Acts::ConeBounds: (tanAlpha, minZ, maxZ, averagePhi, - // halfPhiSector) = (0.4142136, 0.0000000, inf, 0.0000000, - // 3.1415927)")); - } - - BOOST_AUTO_TEST_CASE(EqualityOperators) - { - double alpha{M_PI / 8.} /*, halfPhiSector{M_PI/16.}, zMin{1.0}, zMax{10.}*/; - bool symmetric(false); - Translation3D translation{0., 1., 2.}; - auto pTransform = std::make_shared<const Transform3D>(translation); - auto coneSurfaceObject - = Surface::makeShared<ConeSurface>(pTransform, alpha, symmetric); - // - auto coneSurfaceObject2 - = Surface::makeShared<ConeSurface>(pTransform, alpha, symmetric); - // - /// Test equality operator - BOOST_CHECK(*coneSurfaceObject == *coneSurfaceObject2); - // - BOOST_TEST_CHECKPOINT( - "Create and then assign a ConeSurface object to the existing one"); - /// Test assignment - auto assignedConeSurface - = Surface::makeShared<ConeSurface>(nullptr, 0.1, true); - *assignedConeSurface = *coneSurfaceObject; - /// Test equality of assigned to original - BOOST_CHECK(*assignedConeSurface == *coneSurfaceObject); - } - - BOOST_AUTO_TEST_SUITE_END() +// Create a test context +GeometryContext tgContext = GeometryContext(); + +BOOST_AUTO_TEST_SUITE(ConeSurfaces) +/// Unit test for creating compliant/non-compliant ConeSurface object +BOOST_AUTO_TEST_CASE(ConeSurfaceConstruction) { + // ConeSurface default constructor is deleted + // + /// Constructor with transform pointer, null or valid, alpha and symmetry + /// indicator + double alpha{M_PI / 8.}, halfPhiSector{M_PI / 16.}, zMin{1.0}, zMax{10.}; + bool symmetric(false); + Translation3D translation{0., 1., 2.}; + auto pTransform = std::make_shared<const Transform3D>(translation); + auto pNullTransform = std::make_shared<const Transform3D>(); + BOOST_CHECK_EQUAL( + Surface::makeShared<ConeSurface>(pNullTransform, alpha, symmetric) + ->type(), + Surface::Cone); + BOOST_CHECK_EQUAL( + Surface::makeShared<ConeSurface>(pTransform, alpha, symmetric)->type(), + Surface::Cone); + // + /// Constructor with transform pointer, alpha,z min and max, halfPhiSector + BOOST_CHECK_EQUAL(Surface::makeShared<ConeSurface>(pTransform, alpha, zMin, + zMax, halfPhiSector) + ->type(), + Surface::Cone); + // + + /// Constructor with transform and ConeBounds pointer + // ConeBounds (double alpha, double zmin, double zmax, double halfphi=M_PI, + // double avphi=0.) + auto pConeBounds = + std::make_shared<const ConeBounds>(alpha, zMin, zMax, halfPhiSector, 0.); + BOOST_CHECK_EQUAL( + Surface::makeShared<ConeSurface>(pTransform, pConeBounds)->type(), + Surface::Cone); + // + // + /// Copy constructor + auto coneSurfaceObject = + Surface::makeShared<ConeSurface>(pTransform, alpha, symmetric); + auto copiedConeSurface = Surface::makeShared<ConeSurface>(*coneSurfaceObject); + BOOST_CHECK_EQUAL(copiedConeSurface->type(), Surface::Cone); + BOOST_CHECK(*copiedConeSurface == *coneSurfaceObject); + // + /// Copied and transformed + auto copiedTransformedConeSurface = Surface::makeShared<ConeSurface>( + tgContext, *coneSurfaceObject, *pTransform); + BOOST_CHECK_EQUAL(copiedTransformedConeSurface->type(), Surface::Cone); + + /// Construct with nullptr bounds + BOOST_CHECK_THROW( + auto nullBounds = Surface::makeShared<ConeSurface>(nullptr, nullptr), + AssertionFailureException); +} +// +/// Unit test for testing ConeSurface properties +BOOST_AUTO_TEST_CASE(ConeSurfaceProperties) { + /// Test clone method + double alpha{M_PI / 8.} /*,halfPhiSector{M_PI/16.}, zMin{1.0}, zMax{10.}*/; + bool symmetric(false); + Translation3D translation{0., 1., 2.}; + auto pTransform = std::make_shared<const Transform3D>(translation); + // auto pNullTransform = std::make_shared<const Transform3D>(); + auto coneSurfaceObject = + Surface::makeShared<ConeSurface>(pTransform, alpha, symmetric); + // + auto pClonedConeSurface = + coneSurfaceObject->clone(tgContext, Transform3D::Identity()); + BOOST_CHECK_EQUAL(pClonedConeSurface->type(), Surface::Cone); + // + /// Test type (redundant) + BOOST_CHECK_EQUAL(coneSurfaceObject->type(), Surface::Cone); + // + /// Test binningPosition + Vector3D binningPosition{0., 1., 2.}; + CHECK_CLOSE_ABS( + coneSurfaceObject->binningPosition(tgContext, BinningValue::binPhi), + binningPosition, 1e-6); + // + /// Test referenceFrame + Vector3D globalPosition{2.0, 2.0, 2.0}; + Vector3D momentum{1.e6, 1.e6, 1.e6}; + double rootHalf = std::sqrt(0.5); + RotationMatrix3D expectedFrame; + expectedFrame << -rootHalf, 0., rootHalf, rootHalf, 0., rootHalf, 0., 1., 0.; + CHECK_CLOSE_OR_SMALL( + coneSurfaceObject->referenceFrame(tgContext, globalPosition, momentum), + expectedFrame, 1e-6, 1e-9); + // + /// Test normal, given 3D position + Vector3D origin{0., 0., 0.}; + Vector3D normal3D = {0., -1., 0.}; + CHECK_CLOSE_ABS(coneSurfaceObject->normal(tgContext, origin), normal3D, 1e-6); + // + /// Test normal given 2D rphi position + Vector2D positionPiBy2(1.0, M_PI / 2.); + Vector3D normalAtPiBy2{0.0312768, 0.92335, -0.382683}; + + CHECK_CLOSE_OR_SMALL(coneSurfaceObject->normal(tgContext, positionPiBy2), + normalAtPiBy2, 1e-2, 1e-9); + // + /// Test rotational symmetry axis + Vector3D symmetryAxis{0., 0., 1.}; + CHECK_CLOSE_ABS(coneSurfaceObject->rotSymmetryAxis(tgContext), symmetryAxis, + 1e-6); + // + /// Test bounds + BOOST_CHECK_EQUAL(coneSurfaceObject->bounds().type(), SurfaceBounds::Cone); + // + /// Test localToGlobal + Vector2D localPosition{1.0, M_PI / 2.0}; + coneSurfaceObject->localToGlobal(tgContext, localPosition, momentum, + globalPosition); + // std::cout<<globalPosition<<std::endl; + Vector3D expectedPosition{0.0220268, 1.65027, 3.5708}; + + CHECK_CLOSE_REL(globalPosition, expectedPosition, 1e-2); + // + /// Testing globalToLocal + coneSurfaceObject->globalToLocal(tgContext, globalPosition, momentum, + localPosition); + // std::cout<<localPosition<<std::endl; + Vector2D expectedLocalPosition{1.0, M_PI / 2.0}; + + CHECK_CLOSE_REL(localPosition, expectedLocalPosition, 1e-6); + // + /// Test isOnSurface + Vector3D offSurface{100, 1, 2}; + BOOST_CHECK(coneSurfaceObject->isOnSurface(tgContext, globalPosition, + momentum, true)); + BOOST_CHECK( + !coneSurfaceObject->isOnSurface(tgContext, offSurface, momentum, true)); + // + /// intersectionEstimate + Vector3D direction{-1., 0, 0}; + auto intersect = coneSurfaceObject->intersectionEstimate( + tgContext, offSurface, direction, forward, false); + Intersection expectedIntersect{Vector3D{0, 1, 2}, 100., true, 0}; + BOOST_CHECK(intersect.valid); + CHECK_CLOSE_ABS(intersect.position, expectedIntersect.position, 1e-6); + CHECK_CLOSE_ABS(intersect.pathLength, expectedIntersect.pathLength, 1e-6); + CHECK_CLOSE_ABS(intersect.distance, expectedIntersect.distance, 1e-6); + // + /// Test pathCorrection + CHECK_CLOSE_REL( + coneSurfaceObject->pathCorrection(tgContext, offSurface, momentum), + 0.40218866453252877, 0.01); + // + /// Test name + BOOST_CHECK_EQUAL(coneSurfaceObject->name(), + std::string("Acts::ConeSurface")); + // + /// Test dump + // TODO 2017-04-12 msmk: check how to correctly check output + // boost::test_tools::output_test_stream dumpOuput; + // coneSurfaceObject.toStream(dumpOuput); + // BOOST_CHECK(dumpOuput.is_equal( + // "Acts::ConeSurface\n" + // " Center position (x, y, z) = (0.0000, 1.0000, 2.0000)\n" + // " Rotation: colX = (1.000000, 0.000000, 0.000000)\n" + // " colY = (0.000000, 1.000000, 0.000000)\n" + // " colZ = (0.000000, 0.000000, 1.000000)\n" + // " Bounds : Acts::ConeBounds: (tanAlpha, minZ, maxZ, averagePhi, + // halfPhiSector) = (0.4142136, 0.0000000, inf, 0.0000000, + // 3.1415927)")); +} + +BOOST_AUTO_TEST_CASE(EqualityOperators) { + double alpha{M_PI / 8.} /*, halfPhiSector{M_PI/16.}, zMin{1.0}, zMax{10.}*/; + bool symmetric(false); + Translation3D translation{0., 1., 2.}; + auto pTransform = std::make_shared<const Transform3D>(translation); + auto coneSurfaceObject = + Surface::makeShared<ConeSurface>(pTransform, alpha, symmetric); + // + auto coneSurfaceObject2 = + Surface::makeShared<ConeSurface>(pTransform, alpha, symmetric); + // + /// Test equality operator + BOOST_CHECK(*coneSurfaceObject == *coneSurfaceObject2); + // + BOOST_TEST_CHECKPOINT( + "Create and then assign a ConeSurface object to the existing one"); + /// Test assignment + auto assignedConeSurface = + Surface::makeShared<ConeSurface>(nullptr, 0.1, true); + *assignedConeSurface = *coneSurfaceObject; + /// Test equality of assigned to original + BOOST_CHECK(*assignedConeSurface == *coneSurfaceObject); +} + +BOOST_AUTO_TEST_SUITE_END() } // namespace Test diff --git a/Tests/Core/Surfaces/ConvexPolygonBoundsTest.cpp b/Tests/Core/Surfaces/ConvexPolygonBoundsTest.cpp index 1c256e4c32b96c27a4a35bb339a9dcc136c39a87..8cefb69144810a82e36e99672c01dd8c27580ba2 100644 --- a/Tests/Core/Surfaces/ConvexPolygonBoundsTest.cpp +++ b/Tests/Core/Surfaces/ConvexPolygonBoundsTest.cpp @@ -25,122 +25,112 @@ using poly = Acts::ConvexPolygonBounds<N>; namespace Acts { namespace Test { - BOOST_AUTO_TEST_SUITE(Surfaces) +BOOST_AUTO_TEST_SUITE(Surfaces) - BOOST_AUTO_TEST_CASE(convexity_test) +BOOST_AUTO_TEST_CASE(convexity_test) { + std::vector<vec2> vertices; + vertices = {{0, 0}, {1, 0}, {0.2, 0.2}, {0, 1}}; + { BOOST_CHECK_THROW(poly<4> quad(vertices), AssertionFailureException); } + + vertices = {{0, 0}, {1, 0}, {0.8, 0.8}, {0, 1}}; + { + // wrong number of vertices + BOOST_CHECK_THROW(poly<3> trip{vertices}, AssertionFailureException); + } { - std::vector<vec2> vertices; - vertices = {{0, 0}, {1, 0}, {0.2, 0.2}, {0, 1}}; - { - BOOST_CHECK_THROW(poly<4> quad(vertices), AssertionFailureException); - } - - vertices = {{0, 0}, {1, 0}, {0.8, 0.8}, {0, 1}}; - { - // wrong number of vertices - BOOST_CHECK_THROW(poly<3> trip{vertices}, AssertionFailureException); - } - { - poly<4> quad = {vertices}; - BOOST_CHECK(quad.convex()); - } - - // this one is self intersecting - vertices = {{0, 0}, {1, 0}, {0.5, 1}, {0.9, 1.2}}; - { - BOOST_CHECK_THROW(poly<4> quad{vertices}, AssertionFailureException); - } - - // this one is not - vertices = {{0, 0}, {1, 0}, {0.9, 1.2}, {0.5, 1}}; - { - poly<4> quad = {vertices}; - BOOST_CHECK(quad.convex()); - } - - vertices = {{0, 0}, {1, 0}, {0.8, 0.5}, {1, 1}, {0, 1}}; - { - BOOST_CHECK_THROW(poly<5> pent(vertices), AssertionFailureException); - } - - vertices = {{0, 0}, {1, 0}, {1.1, 0.5}, {1, 1}, {0, 1}}; - { - poly<5> pent{vertices}; - BOOST_CHECK(pent.convex()); - } + poly<4> quad = {vertices}; + BOOST_CHECK(quad.convex()); } - BOOST_AUTO_TEST_CASE(construction_test) + // this one is self intersecting + vertices = {{0, 0}, {1, 0}, {0.5, 1}, {0.9, 1.2}}; + { BOOST_CHECK_THROW(poly<4> quad{vertices}, AssertionFailureException); } + + // this one is not + vertices = {{0, 0}, {1, 0}, {0.9, 1.2}, {0.5, 1}}; { + poly<4> quad = {vertices}; + BOOST_CHECK(quad.convex()); + } - std::vector<vec2> vertices; + vertices = {{0, 0}, {1, 0}, {0.8, 0.5}, {1, 1}, {0, 1}}; + { BOOST_CHECK_THROW(poly<5> pent(vertices), AssertionFailureException); } - // triangle - vertices = {{0, 0}, {1, 0}, {0.5, 1}}; - poly<3> triangle(vertices); + vertices = {{0, 0}, {1, 0}, {1.1, 0.5}, {1, 1}, {0, 1}}; + { + poly<5> pent{vertices}; + BOOST_CHECK(pent.convex()); + } +} - RectangleBounds bb = triangle.boundingBox(); - BOOST_CHECK_EQUAL(bb.min(), Vector2D(0, 0)); - BOOST_CHECK_EQUAL(bb.max(), Vector2D(1., 1)); +BOOST_AUTO_TEST_CASE(construction_test) { + std::vector<vec2> vertices; - BoundaryCheck bc(true); + // triangle + vertices = {{0, 0}, {1, 0}, {0.5, 1}}; + poly<3> triangle(vertices); - BOOST_CHECK(triangle.inside({0.2, 0.2}, bc)); - BOOST_CHECK(!triangle.inside({0.4, 0.9}, bc)); - BOOST_CHECK(!triangle.inside({0.8, 0.8}, bc)); - BOOST_CHECK(!triangle.inside({0.3, -0.2}, bc)); + RectangleBounds bb = triangle.boundingBox(); + BOOST_CHECK_EQUAL(bb.min(), Vector2D(0, 0)); + BOOST_CHECK_EQUAL(bb.max(), Vector2D(1., 1)); - CHECK_CLOSE_ABS(triangle.distanceToBoundary({0.2, 0.2}), -0.0894427, 1e-6); - CHECK_CLOSE_ABS(triangle.distanceToBoundary({0.4, 0.9}), 0.0447213, 1e-6); - CHECK_CLOSE_ABS(triangle.distanceToBoundary({0.8, 0.8}), 0.1788854, 1e-6); - CHECK_CLOSE_ABS(triangle.distanceToBoundary({0.3, -0.2}), 0.2, 1e-6); + BoundaryCheck bc(true); - // rectangular poly - vertices = {{0, 0}, {1, 0}, {0.9, 1.2}, {0.5, 1}}; - poly<4> quad(vertices); + BOOST_CHECK(triangle.inside({0.2, 0.2}, bc)); + BOOST_CHECK(!triangle.inside({0.4, 0.9}, bc)); + BOOST_CHECK(!triangle.inside({0.8, 0.8}, bc)); + BOOST_CHECK(!triangle.inside({0.3, -0.2}, bc)); - bb = quad.boundingBox(); - BOOST_CHECK_EQUAL(bb.min(), Vector2D(0, 0)); - BOOST_CHECK_EQUAL(bb.max(), Vector2D(1, 1.2)); + CHECK_CLOSE_ABS(triangle.distanceToBoundary({0.2, 0.2}), -0.0894427, 1e-6); + CHECK_CLOSE_ABS(triangle.distanceToBoundary({0.4, 0.9}), 0.0447213, 1e-6); + CHECK_CLOSE_ABS(triangle.distanceToBoundary({0.8, 0.8}), 0.1788854, 1e-6); + CHECK_CLOSE_ABS(triangle.distanceToBoundary({0.3, -0.2}), 0.2, 1e-6); - BOOST_CHECK(quad.inside({0.2, 0.2}, bc)); - BOOST_CHECK(!quad.inside({0.4, 0.9}, bc)); - BOOST_CHECK(quad.inside({0.8, 0.8}, bc)); - BOOST_CHECK(!quad.inside({0.3, -0.2}, bc)); + // rectangular poly + vertices = {{0, 0}, {1, 0}, {0.9, 1.2}, {0.5, 1}}; + poly<4> quad(vertices); - CHECK_CLOSE_ABS(quad.distanceToBoundary({0.2, 0.2}), -0.089442, 1e-6); - CHECK_CLOSE_ABS(quad.distanceToBoundary({0.4, 0.9}), 0.044721, 1e-6); - CHECK_CLOSE_ABS(quad.distanceToBoundary({0.8, 0.8}), -0.132872, 1e-6); - CHECK_CLOSE_ABS(quad.distanceToBoundary({0.3, -0.2}), 0.2, 1e-6); - } + bb = quad.boundingBox(); + BOOST_CHECK_EQUAL(bb.min(), Vector2D(0, 0)); + BOOST_CHECK_EQUAL(bb.max(), Vector2D(1, 1.2)); - BOOST_AUTO_TEST_CASE(construction_test_dynamic) - { - using poly = ConvexPolygonBounds<PolygonDynamic>; + BOOST_CHECK(quad.inside({0.2, 0.2}, bc)); + BOOST_CHECK(!quad.inside({0.4, 0.9}, bc)); + BOOST_CHECK(quad.inside({0.8, 0.8}, bc)); + BOOST_CHECK(!quad.inside({0.3, -0.2}, bc)); - std::vector<vec2> vertices; + CHECK_CLOSE_ABS(quad.distanceToBoundary({0.2, 0.2}), -0.089442, 1e-6); + CHECK_CLOSE_ABS(quad.distanceToBoundary({0.4, 0.9}), 0.044721, 1e-6); + CHECK_CLOSE_ABS(quad.distanceToBoundary({0.8, 0.8}), -0.132872, 1e-6); + CHECK_CLOSE_ABS(quad.distanceToBoundary({0.3, -0.2}), 0.2, 1e-6); +} - // triangle - vertices = {{0, 0}, {1, 0}, {0.5, 1}}; - poly triangle(vertices); +BOOST_AUTO_TEST_CASE(construction_test_dynamic) { + using poly = ConvexPolygonBounds<PolygonDynamic>; - RectangleBounds bb = triangle.boundingBox(); - BOOST_CHECK_EQUAL(bb.min(), Vector2D(0, 0)); - BOOST_CHECK_EQUAL(bb.max(), Vector2D(1., 1)); + std::vector<vec2> vertices; - BoundaryCheck bc(true); + // triangle + vertices = {{0, 0}, {1, 0}, {0.5, 1}}; + poly triangle(vertices); - BOOST_CHECK(triangle.inside({0.2, 0.2}, bc)); - BOOST_CHECK(!triangle.inside({0.4, 0.9}, bc)); - BOOST_CHECK(!triangle.inside({0.8, 0.8}, bc)); - BOOST_CHECK(!triangle.inside({0.3, -0.2}, bc)); + RectangleBounds bb = triangle.boundingBox(); + BOOST_CHECK_EQUAL(bb.min(), Vector2D(0, 0)); + BOOST_CHECK_EQUAL(bb.max(), Vector2D(1., 1)); - CHECK_CLOSE_ABS(triangle.distanceToBoundary({0.2, 0.2}), -0.0894427, 1e-6); - CHECK_CLOSE_ABS(triangle.distanceToBoundary({0.4, 0.9}), 0.0447213, 1e-6); - CHECK_CLOSE_ABS(triangle.distanceToBoundary({0.8, 0.8}), 0.1788854, 1e-6); - CHECK_CLOSE_ABS(triangle.distanceToBoundary({0.3, -0.2}), 0.2, 1e-6); - } + BoundaryCheck bc(true); - BOOST_AUTO_TEST_SUITE_END() -} + BOOST_CHECK(triangle.inside({0.2, 0.2}, bc)); + BOOST_CHECK(!triangle.inside({0.4, 0.9}, bc)); + BOOST_CHECK(!triangle.inside({0.8, 0.8}, bc)); + BOOST_CHECK(!triangle.inside({0.3, -0.2}, bc)); + + CHECK_CLOSE_ABS(triangle.distanceToBoundary({0.2, 0.2}), -0.0894427, 1e-6); + CHECK_CLOSE_ABS(triangle.distanceToBoundary({0.4, 0.9}), 0.0447213, 1e-6); + CHECK_CLOSE_ABS(triangle.distanceToBoundary({0.8, 0.8}), 0.1788854, 1e-6); + CHECK_CLOSE_ABS(triangle.distanceToBoundary({0.3, -0.2}), 0.2, 1e-6); } + +BOOST_AUTO_TEST_SUITE_END() +} // namespace Test +} // namespace Acts diff --git a/Tests/Core/Surfaces/CylinderBoundsTests.cpp b/Tests/Core/Surfaces/CylinderBoundsTests.cpp index 331d3ec1d92921a397483db500c716a081734698..3903eeb2c0fb6d6d6dbd38e5f9d80b9686d3542b 100644 --- a/Tests/Core/Surfaces/CylinderBoundsTests.cpp +++ b/Tests/Core/Surfaces/CylinderBoundsTests.cpp @@ -23,118 +23,109 @@ namespace Acts { namespace Test { - BOOST_AUTO_TEST_SUITE(Surfaces) - /// Unit test for creating compliant/non-compliant CylinderBounds object - BOOST_AUTO_TEST_CASE(CylinderBoundsConstruction) - { - /// test default construction - // CylinderBounds defaultConstructedCylinderBounds; // deleted - double radius(0.5), halfz(10.), halfphi(M_PI / 2.0), averagePhi(M_PI / 2.0); - BOOST_CHECK_EQUAL(CylinderBounds(radius, halfz).type(), - SurfaceBounds::Cylinder); - BOOST_CHECK_EQUAL(CylinderBounds(radius, halfphi, halfz).type(), - SurfaceBounds::Cylinder); - BOOST_CHECK_EQUAL(CylinderBounds(radius, averagePhi, halfphi, halfz).type(), - SurfaceBounds::Cylinder); - // - /// test copy construction; - CylinderBounds cylinderBounds(radius, halfz); - CylinderBounds copyConstructedCylinderBounds(cylinderBounds); - BOOST_CHECK_EQUAL(copyConstructedCylinderBounds.type(), - SurfaceBounds::Cylinder); - } - - /// Unit tests for CylinderBounds properties - BOOST_AUTO_TEST_CASE_EXPECTED_FAILURES(CylinderBoundsProperties, 4) - BOOST_AUTO_TEST_CASE(CylinderBoundsProperties) - { - // CylinderBounds object of radius 0.5 and halfz 20 - double nominalRadius{0.5}; - double nominalHalfLength{20.}; - double averagePhi(0.0); - double halfphi(M_PI / 4.0); - CylinderBounds cylinderBoundsObject(nominalRadius, nominalHalfLength); - CylinderBounds cylinderBoundsSegment( - nominalRadius, averagePhi, halfphi, nominalHalfLength); - /// test for clone - auto pCylinderBoundsClone = cylinderBoundsObject.clone(); - BOOST_CHECK_NE(pCylinderBoundsClone, nullptr); - delete pCylinderBoundsClone; - - /// test for type() - BOOST_CHECK_EQUAL(cylinderBoundsObject.type(), SurfaceBounds::Cylinder); - - /// test for inside(), 2D coords are r or phi ,z? : needs clarification - const Vector2D origin{0., 0.}; - const Vector2D atPiBy2{M_PI / 2., 0.0}; - const Vector2D atPi{M_PI, 0.0}; - const Vector2D beyondEnd{0, 30.0}; - const Vector2D unitZ{0.0, 1.0}; - const Vector2D unitPhi{1.0, 0.0}; - const BoundaryCheck trueBoundaryCheckWithTolerance(true, true, 0.1, 0.1); - BOOST_CHECK( - cylinderBoundsObject.inside(atPiBy2, trueBoundaryCheckWithTolerance)); - BOOST_CHECK( - !cylinderBoundsSegment.inside(unitPhi, trueBoundaryCheckWithTolerance)); - BOOST_CHECK( - cylinderBoundsObject.inside(origin, trueBoundaryCheckWithTolerance)); - - /// test for inside3D() with Vector3D argument - const Vector3D origin3D{0., 0., 0.}; - BOOST_CHECK(!cylinderBoundsObject.inside3D(origin3D, - trueBoundaryCheckWithTolerance)); - - /// test for distanceToBoundary - CHECK_CLOSE_REL(cylinderBoundsObject.distanceToBoundary(origin), - 0.5, - 1e-6); // fail - CHECK_CLOSE_REL(cylinderBoundsObject.distanceToBoundary(beyondEnd), - 10.0, - 1e-6); // pass - double sinPiBy8 = std::sin(M_PI / 8.); - CHECK_CLOSE_REL(cylinderBoundsSegment.distanceToBoundary(atPi), - sinPiBy8, - 1e-6); // pass - CHECK_CLOSE_REL(cylinderBoundsSegment.distanceToBoundary(origin), - 0.5, - 1e-6); // fail - - /// test for r() - CHECK_CLOSE_REL(cylinderBoundsObject.r(), nominalRadius, 1e-6); - - /// test for averagePhi - CHECK_CLOSE_REL(cylinderBoundsObject.averagePhi(), averagePhi, 1e-6); - - /// test for halfPhiSector - CHECK_CLOSE_REL(cylinderBoundsSegment.halfPhiSector(), - halfphi, - 1e-6); // fail - - /// test for halflengthZ (NOTE: Naming violation) - CHECK_CLOSE_REL( - cylinderBoundsObject.halflengthZ(), nominalHalfLength, 1e-6); - - /// test for dump - boost::test_tools::output_test_stream dumpOuput; - cylinderBoundsObject.toStream(dumpOuput); - BOOST_CHECK( - dumpOuput.is_equal("Acts::CylinderBounds: (radius, averagePhi, " - "halfPhiSector, halflengthInZ) = (0.5000000, " - "0.0000000, 3.1415927, 20.0000000)")); - } - /// Unit test for testing CylinderBounds assignment - BOOST_AUTO_TEST_CASE(CylinderBoundsAssignment) - { - double nominalRadius{0.5}; - double nominalHalfLength{20.}; - CylinderBounds cylinderBoundsObject(nominalRadius, nominalHalfLength); - CylinderBounds assignedCylinderBounds(10.5, 6.6); - assignedCylinderBounds = cylinderBoundsObject; - BOOST_CHECK_EQUAL(assignedCylinderBounds.r(), cylinderBoundsObject.r()); - BOOST_CHECK_EQUAL(assignedCylinderBounds, cylinderBoundsObject); - } - - BOOST_AUTO_TEST_SUITE_END() +BOOST_AUTO_TEST_SUITE(Surfaces) +/// Unit test for creating compliant/non-compliant CylinderBounds object +BOOST_AUTO_TEST_CASE(CylinderBoundsConstruction) { + /// test default construction + // CylinderBounds defaultConstructedCylinderBounds; // deleted + double radius(0.5), halfz(10.), halfphi(M_PI / 2.0), averagePhi(M_PI / 2.0); + BOOST_CHECK_EQUAL(CylinderBounds(radius, halfz).type(), + SurfaceBounds::Cylinder); + BOOST_CHECK_EQUAL(CylinderBounds(radius, halfphi, halfz).type(), + SurfaceBounds::Cylinder); + BOOST_CHECK_EQUAL(CylinderBounds(radius, averagePhi, halfphi, halfz).type(), + SurfaceBounds::Cylinder); + // + /// test copy construction; + CylinderBounds cylinderBounds(radius, halfz); + CylinderBounds copyConstructedCylinderBounds(cylinderBounds); + BOOST_CHECK_EQUAL(copyConstructedCylinderBounds.type(), + SurfaceBounds::Cylinder); +} + +/// Unit tests for CylinderBounds properties +BOOST_AUTO_TEST_CASE_EXPECTED_FAILURES(CylinderBoundsProperties, 4) +BOOST_AUTO_TEST_CASE(CylinderBoundsProperties) { + // CylinderBounds object of radius 0.5 and halfz 20 + double nominalRadius{0.5}; + double nominalHalfLength{20.}; + double averagePhi(0.0); + double halfphi(M_PI / 4.0); + CylinderBounds cylinderBoundsObject(nominalRadius, nominalHalfLength); + CylinderBounds cylinderBoundsSegment(nominalRadius, averagePhi, halfphi, + nominalHalfLength); + /// test for clone + auto pCylinderBoundsClone = cylinderBoundsObject.clone(); + BOOST_CHECK_NE(pCylinderBoundsClone, nullptr); + delete pCylinderBoundsClone; + + /// test for type() + BOOST_CHECK_EQUAL(cylinderBoundsObject.type(), SurfaceBounds::Cylinder); + + /// test for inside(), 2D coords are r or phi ,z? : needs clarification + const Vector2D origin{0., 0.}; + const Vector2D atPiBy2{M_PI / 2., 0.0}; + const Vector2D atPi{M_PI, 0.0}; + const Vector2D beyondEnd{0, 30.0}; + const Vector2D unitZ{0.0, 1.0}; + const Vector2D unitPhi{1.0, 0.0}; + const BoundaryCheck trueBoundaryCheckWithTolerance(true, true, 0.1, 0.1); + BOOST_CHECK( + cylinderBoundsObject.inside(atPiBy2, trueBoundaryCheckWithTolerance)); + BOOST_CHECK( + !cylinderBoundsSegment.inside(unitPhi, trueBoundaryCheckWithTolerance)); + BOOST_CHECK( + cylinderBoundsObject.inside(origin, trueBoundaryCheckWithTolerance)); + + /// test for inside3D() with Vector3D argument + const Vector3D origin3D{0., 0., 0.}; + BOOST_CHECK( + !cylinderBoundsObject.inside3D(origin3D, trueBoundaryCheckWithTolerance)); + + /// test for distanceToBoundary + CHECK_CLOSE_REL(cylinderBoundsObject.distanceToBoundary(origin), 0.5, + 1e-6); // fail + CHECK_CLOSE_REL(cylinderBoundsObject.distanceToBoundary(beyondEnd), 10.0, + 1e-6); // pass + double sinPiBy8 = std::sin(M_PI / 8.); + CHECK_CLOSE_REL(cylinderBoundsSegment.distanceToBoundary(atPi), sinPiBy8, + 1e-6); // pass + CHECK_CLOSE_REL(cylinderBoundsSegment.distanceToBoundary(origin), 0.5, + 1e-6); // fail + + /// test for r() + CHECK_CLOSE_REL(cylinderBoundsObject.r(), nominalRadius, 1e-6); + + /// test for averagePhi + CHECK_CLOSE_REL(cylinderBoundsObject.averagePhi(), averagePhi, 1e-6); + + /// test for halfPhiSector + CHECK_CLOSE_REL(cylinderBoundsSegment.halfPhiSector(), halfphi, + 1e-6); // fail + + /// test for halflengthZ (NOTE: Naming violation) + CHECK_CLOSE_REL(cylinderBoundsObject.halflengthZ(), nominalHalfLength, 1e-6); + + /// test for dump + boost::test_tools::output_test_stream dumpOuput; + cylinderBoundsObject.toStream(dumpOuput); + BOOST_CHECK( + dumpOuput.is_equal("Acts::CylinderBounds: (radius, averagePhi, " + "halfPhiSector, halflengthInZ) = (0.5000000, " + "0.0000000, 3.1415927, 20.0000000)")); +} +/// Unit test for testing CylinderBounds assignment +BOOST_AUTO_TEST_CASE(CylinderBoundsAssignment) { + double nominalRadius{0.5}; + double nominalHalfLength{20.}; + CylinderBounds cylinderBoundsObject(nominalRadius, nominalHalfLength); + CylinderBounds assignedCylinderBounds(10.5, 6.6); + assignedCylinderBounds = cylinderBoundsObject; + BOOST_CHECK_EQUAL(assignedCylinderBounds.r(), cylinderBoundsObject.r()); + BOOST_CHECK_EQUAL(assignedCylinderBounds, cylinderBoundsObject); +} + +BOOST_AUTO_TEST_SUITE_END() } // namespace Test diff --git a/Tests/Core/Surfaces/CylinderSurfaceTests.cpp b/Tests/Core/Surfaces/CylinderSurfaceTests.cpp index e32daa3340e4f16844f168b922a16c06a58f0a99..de28ad012e1414f98189501e527f2eeea2bc404d 100644 --- a/Tests/Core/Surfaces/CylinderSurfaceTests.cpp +++ b/Tests/Core/Surfaces/CylinderSurfaceTests.cpp @@ -30,223 +30,207 @@ namespace Acts { namespace Test { - // Create a test context - GeometryContext testContext = GeometryContext(); - - BOOST_AUTO_TEST_SUITE(CylinderSurfaces) - /// Unit test for creating compliant/non-compliant CylinderSurface object - BOOST_AUTO_TEST_CASE(CylinderSurfaceConstruction) - { - // CylinderSurface default constructor is deleted - // - /// Constructor with transform pointer, null or valid, radius and halfZ - double radius(1.0), halfZ(10.), halfPhiSector(M_PI / 8.); - Translation3D translation{0., 1., 2.}; - auto pTransform = std::make_shared<const Transform3D>(translation); - auto pNullTransform = std::make_shared<const Transform3D>(); - BOOST_CHECK_EQUAL( - Surface::makeShared<CylinderSurface>(pNullTransform, radius, halfZ) - ->type(), - Surface::Cylinder); - BOOST_CHECK_EQUAL( - Surface::makeShared<CylinderSurface>(pTransform, radius, halfZ)->type(), - Surface::Cylinder); - // - /// Constructor with transform pointer, radius, halfZ and halfPhiSector - BOOST_CHECK_EQUAL(Surface::makeShared<CylinderSurface>( - pTransform, radius, halfPhiSector, halfZ) - ->type(), - Surface::Cylinder); - - /// Constructor with transform and CylinderBounds pointer - auto pCylinderBounds - = std::make_shared<const CylinderBounds>(radius, halfZ); - BOOST_CHECK_EQUAL( - Surface::makeShared<CylinderSurface>(pTransform, pCylinderBounds) - ->type(), - Surface::Cylinder); - // - // - /// Copy constructor - auto cylinderSurfaceObject - = Surface::makeShared<CylinderSurface>(pTransform, radius, halfZ); - auto copiedCylinderSurface - = Surface::makeShared<CylinderSurface>(*cylinderSurfaceObject); - BOOST_CHECK_EQUAL(copiedCylinderSurface->type(), Surface::Cylinder); - BOOST_CHECK(*copiedCylinderSurface == *cylinderSurfaceObject); - // - /// Copied and transformed - auto copiedTransformedCylinderSurface - = Surface::makeShared<CylinderSurface>( - testContext, *cylinderSurfaceObject, *pTransform); - BOOST_CHECK_EQUAL(copiedTransformedCylinderSurface->type(), - Surface::Cylinder); - - /// Construct with nullptr bounds - BOOST_CHECK_THROW(auto nullBounds - = Surface::makeShared<CylinderSurface>(nullptr, nullptr), - AssertionFailureException); - } - // - /// Unit test for testing CylinderSurface properties - BOOST_AUTO_TEST_CASE(CylinderSurfaceProperties) - { - /// Test clone method - double radius(1.0), halfZ(10.); - Translation3D translation{0., 1., 2.}; - auto pTransform = std::make_shared<const Transform3D>(translation); - // auto pNullTransform = std::make_shared<const Transform3D>(); - auto cylinderSurfaceObject - = Surface::makeShared<CylinderSurface>(pTransform, radius, halfZ); - // - auto pClonedCylinderSurface - = cylinderSurfaceObject->clone(testContext, Transform3D::Identity()); - BOOST_CHECK_EQUAL(pClonedCylinderSurface->type(), Surface::Cylinder); - // - /// Test type (redundant) - BOOST_CHECK_EQUAL(cylinderSurfaceObject->type(), Surface::Cylinder); - // - /// Test binningPosition - Vector3D binningPosition{0., 1., 2.}; - CHECK_CLOSE_ABS(cylinderSurfaceObject->binningPosition( - testContext, BinningValue::binPhi), - binningPosition, - 1e-9); - // - /// Test referenceFrame - double rootHalf = std::sqrt(0.5); - Vector3D globalPosition{rootHalf, 1. - rootHalf, 0.}; - Vector3D globalPositionZ{rootHalf, 1. - rootHalf, 2.0}; - Vector3D momentum{15., 15., 15.}; - Vector3D momentum2{6.6, -3., 2.}; - RotationMatrix3D expectedFrame; - expectedFrame << rootHalf, 0., rootHalf, rootHalf, 0., -rootHalf, 0., 1., - 0.; - // check without shift - CHECK_CLOSE_OR_SMALL(cylinderSurfaceObject->referenceFrame( - testContext, globalPosition, momentum), - expectedFrame, - 1e-6, - 1e-9); - // check with shift and different momentum - CHECK_CLOSE_OR_SMALL(cylinderSurfaceObject->referenceFrame( - testContext, globalPositionZ, momentum2), - expectedFrame, - 1e-6, - 1e-9); - // - /// Test normal, given 3D position - Vector3D origin{0., 0., 0.}; - Vector3D normal3D = {0., -1., 0.}; - CHECK_CLOSE_ABS( - cylinderSurfaceObject->normal(testContext, origin), normal3D, 1e-9); - - Vector3D pos45deg = {rootHalf, 1 + rootHalf, 0.}; - Vector3D pos45degZ = {rootHalf, 1 + rootHalf, 4.}; - Vector3D normal45deg = {rootHalf, rootHalf, 0.}; - // test the normal vector - CHECK_CLOSE_ABS(cylinderSurfaceObject->normal(testContext, pos45deg), - normal45deg, - 1e-6 * rootHalf); - // thest that the normal vector is independent of z coordinate - CHECK_CLOSE_ABS(cylinderSurfaceObject->normal(testContext, pos45degZ), - normal45deg, - 1e-6 * rootHalf); - // - /// Test normal given 2D rphi position - Vector2D positionPiBy2(1.0, 0.); - Vector3D normalAtPiBy2{std::cos(1.), std::sin(1.), 0.}; - CHECK_CLOSE_ABS(cylinderSurfaceObject->normal(testContext, positionPiBy2), - normalAtPiBy2, - 1e-9); - - // - /// Test rotational symmetry axis - Vector3D symmetryAxis{0., 0., 1.}; - CHECK_CLOSE_ABS(cylinderSurfaceObject->rotSymmetryAxis(testContext), - symmetryAxis, - 1e-9); - // - /// Test bounds - BOOST_CHECK_EQUAL(cylinderSurfaceObject->bounds().type(), - SurfaceBounds::Cylinder); - // - /// Test localToGlobal - Vector2D localPosition{0., 0.}; - cylinderSurfaceObject->localToGlobal( - testContext, localPosition, momentum, globalPosition); - Vector3D expectedPosition{1, 1, 2}; - BOOST_CHECK_EQUAL(globalPosition, expectedPosition); - // - /// Testing globalToLocal - cylinderSurfaceObject->globalToLocal( - testContext, globalPosition, momentum, localPosition); - Vector2D expectedLocalPosition{0., 0.}; - BOOST_CHECK_EQUAL(localPosition, expectedLocalPosition); - // - /// Test isOnSurface - Vector3D offSurface{100, 1, 2}; - BOOST_CHECK(cylinderSurfaceObject->isOnSurface( - testContext, globalPosition, momentum, true)); - BOOST_CHECK(!cylinderSurfaceObject->isOnSurface( - testContext, offSurface, momentum, true)); - // - /// intersectionEstimate - Vector3D direction{-1., 0, 0}; - auto intersect = cylinderSurfaceObject->intersectionEstimate( - testContext, offSurface, direction); - Intersection expectedIntersect{Vector3D{1, 1, 2}, 99., true, 0}; - BOOST_CHECK(intersect.valid); - CHECK_CLOSE_ABS(intersect.position, expectedIntersect.position, 1e-9); - CHECK_CLOSE_ABS(intersect.pathLength, expectedIntersect.pathLength, 1e-9); - CHECK_CLOSE_ABS(intersect.distance, expectedIntersect.distance, 1e-9); - // - /// Test pathCorrection - CHECK_CLOSE_REL(cylinderSurfaceObject->pathCorrection( - testContext, offSurface, momentum), - std::sqrt(3.), - 0.01); - // - /// Test name - BOOST_CHECK_EQUAL(cylinderSurfaceObject->name(), - std::string("Acts::CylinderSurface")); - // - /// Test dump - boost::test_tools::output_test_stream dumpOuput; - cylinderSurfaceObject->toStream(testContext, dumpOuput); - BOOST_CHECK(dumpOuput.is_equal("Acts::CylinderSurface\n\ +// Create a test context +GeometryContext testContext = GeometryContext(); + +BOOST_AUTO_TEST_SUITE(CylinderSurfaces) +/// Unit test for creating compliant/non-compliant CylinderSurface object +BOOST_AUTO_TEST_CASE(CylinderSurfaceConstruction) { + // CylinderSurface default constructor is deleted + // + /// Constructor with transform pointer, null or valid, radius and halfZ + double radius(1.0), halfZ(10.), halfPhiSector(M_PI / 8.); + Translation3D translation{0., 1., 2.}; + auto pTransform = std::make_shared<const Transform3D>(translation); + auto pNullTransform = std::make_shared<const Transform3D>(); + BOOST_CHECK_EQUAL( + Surface::makeShared<CylinderSurface>(pNullTransform, radius, halfZ) + ->type(), + Surface::Cylinder); + BOOST_CHECK_EQUAL( + Surface::makeShared<CylinderSurface>(pTransform, radius, halfZ)->type(), + Surface::Cylinder); + // + /// Constructor with transform pointer, radius, halfZ and halfPhiSector + BOOST_CHECK_EQUAL(Surface::makeShared<CylinderSurface>(pTransform, radius, + halfPhiSector, halfZ) + ->type(), + Surface::Cylinder); + + /// Constructor with transform and CylinderBounds pointer + auto pCylinderBounds = std::make_shared<const CylinderBounds>(radius, halfZ); + BOOST_CHECK_EQUAL( + Surface::makeShared<CylinderSurface>(pTransform, pCylinderBounds)->type(), + Surface::Cylinder); + // + // + /// Copy constructor + auto cylinderSurfaceObject = + Surface::makeShared<CylinderSurface>(pTransform, radius, halfZ); + auto copiedCylinderSurface = + Surface::makeShared<CylinderSurface>(*cylinderSurfaceObject); + BOOST_CHECK_EQUAL(copiedCylinderSurface->type(), Surface::Cylinder); + BOOST_CHECK(*copiedCylinderSurface == *cylinderSurfaceObject); + // + /// Copied and transformed + auto copiedTransformedCylinderSurface = Surface::makeShared<CylinderSurface>( + testContext, *cylinderSurfaceObject, *pTransform); + BOOST_CHECK_EQUAL(copiedTransformedCylinderSurface->type(), + Surface::Cylinder); + + /// Construct with nullptr bounds + BOOST_CHECK_THROW( + auto nullBounds = Surface::makeShared<CylinderSurface>(nullptr, nullptr), + AssertionFailureException); +} +// +/// Unit test for testing CylinderSurface properties +BOOST_AUTO_TEST_CASE(CylinderSurfaceProperties) { + /// Test clone method + double radius(1.0), halfZ(10.); + Translation3D translation{0., 1., 2.}; + auto pTransform = std::make_shared<const Transform3D>(translation); + // auto pNullTransform = std::make_shared<const Transform3D>(); + auto cylinderSurfaceObject = + Surface::makeShared<CylinderSurface>(pTransform, radius, halfZ); + // + auto pClonedCylinderSurface = + cylinderSurfaceObject->clone(testContext, Transform3D::Identity()); + BOOST_CHECK_EQUAL(pClonedCylinderSurface->type(), Surface::Cylinder); + // + /// Test type (redundant) + BOOST_CHECK_EQUAL(cylinderSurfaceObject->type(), Surface::Cylinder); + // + /// Test binningPosition + Vector3D binningPosition{0., 1., 2.}; + CHECK_CLOSE_ABS( + cylinderSurfaceObject->binningPosition(testContext, BinningValue::binPhi), + binningPosition, 1e-9); + // + /// Test referenceFrame + double rootHalf = std::sqrt(0.5); + Vector3D globalPosition{rootHalf, 1. - rootHalf, 0.}; + Vector3D globalPositionZ{rootHalf, 1. - rootHalf, 2.0}; + Vector3D momentum{15., 15., 15.}; + Vector3D momentum2{6.6, -3., 2.}; + RotationMatrix3D expectedFrame; + expectedFrame << rootHalf, 0., rootHalf, rootHalf, 0., -rootHalf, 0., 1., 0.; + // check without shift + CHECK_CLOSE_OR_SMALL(cylinderSurfaceObject->referenceFrame( + testContext, globalPosition, momentum), + expectedFrame, 1e-6, 1e-9); + // check with shift and different momentum + CHECK_CLOSE_OR_SMALL(cylinderSurfaceObject->referenceFrame( + testContext, globalPositionZ, momentum2), + expectedFrame, 1e-6, 1e-9); + // + /// Test normal, given 3D position + Vector3D origin{0., 0., 0.}; + Vector3D normal3D = {0., -1., 0.}; + CHECK_CLOSE_ABS(cylinderSurfaceObject->normal(testContext, origin), normal3D, + 1e-9); + + Vector3D pos45deg = {rootHalf, 1 + rootHalf, 0.}; + Vector3D pos45degZ = {rootHalf, 1 + rootHalf, 4.}; + Vector3D normal45deg = {rootHalf, rootHalf, 0.}; + // test the normal vector + CHECK_CLOSE_ABS(cylinderSurfaceObject->normal(testContext, pos45deg), + normal45deg, 1e-6 * rootHalf); + // thest that the normal vector is independent of z coordinate + CHECK_CLOSE_ABS(cylinderSurfaceObject->normal(testContext, pos45degZ), + normal45deg, 1e-6 * rootHalf); + // + /// Test normal given 2D rphi position + Vector2D positionPiBy2(1.0, 0.); + Vector3D normalAtPiBy2{std::cos(1.), std::sin(1.), 0.}; + CHECK_CLOSE_ABS(cylinderSurfaceObject->normal(testContext, positionPiBy2), + normalAtPiBy2, 1e-9); + + // + /// Test rotational symmetry axis + Vector3D symmetryAxis{0., 0., 1.}; + CHECK_CLOSE_ABS(cylinderSurfaceObject->rotSymmetryAxis(testContext), + symmetryAxis, 1e-9); + // + /// Test bounds + BOOST_CHECK_EQUAL(cylinderSurfaceObject->bounds().type(), + SurfaceBounds::Cylinder); + // + /// Test localToGlobal + Vector2D localPosition{0., 0.}; + cylinderSurfaceObject->localToGlobal(testContext, localPosition, momentum, + globalPosition); + Vector3D expectedPosition{1, 1, 2}; + BOOST_CHECK_EQUAL(globalPosition, expectedPosition); + // + /// Testing globalToLocal + cylinderSurfaceObject->globalToLocal(testContext, globalPosition, momentum, + localPosition); + Vector2D expectedLocalPosition{0., 0.}; + BOOST_CHECK_EQUAL(localPosition, expectedLocalPosition); + // + /// Test isOnSurface + Vector3D offSurface{100, 1, 2}; + BOOST_CHECK(cylinderSurfaceObject->isOnSurface(testContext, globalPosition, + momentum, true)); + BOOST_CHECK(!cylinderSurfaceObject->isOnSurface(testContext, offSurface, + momentum, true)); + // + /// intersectionEstimate + Vector3D direction{-1., 0, 0}; + auto intersect = cylinderSurfaceObject->intersectionEstimate( + testContext, offSurface, direction); + Intersection expectedIntersect{Vector3D{1, 1, 2}, 99., true, 0}; + BOOST_CHECK(intersect.valid); + CHECK_CLOSE_ABS(intersect.position, expectedIntersect.position, 1e-9); + CHECK_CLOSE_ABS(intersect.pathLength, expectedIntersect.pathLength, 1e-9); + CHECK_CLOSE_ABS(intersect.distance, expectedIntersect.distance, 1e-9); + // + /// Test pathCorrection + CHECK_CLOSE_REL( + cylinderSurfaceObject->pathCorrection(testContext, offSurface, momentum), + std::sqrt(3.), 0.01); + // + /// Test name + BOOST_CHECK_EQUAL(cylinderSurfaceObject->name(), + std::string("Acts::CylinderSurface")); + // + /// Test dump + boost::test_tools::output_test_stream dumpOuput; + cylinderSurfaceObject->toStream(testContext, dumpOuput); + BOOST_CHECK( + dumpOuput.is_equal("Acts::CylinderSurface\n\ Center position (x, y, z) = (0.0000, 1.0000, 2.0000)\n\ Rotation: colX = (1.000000, 0.000000, 0.000000)\n\ colY = (0.000000, 1.000000, 0.000000)\n\ colZ = (0.000000, 0.000000, 1.000000)\n\ Bounds : Acts::CylinderBounds: (radius, averagePhi, halfPhiSector, halflengthInZ) = (1.0000000, 0.0000000, 3.1415927, 10.0000000)")); - } - - BOOST_AUTO_TEST_CASE(EqualityOperators) - { - double radius(1.0), halfZ(10.); - Translation3D translation{0., 1., 2.}; - auto pTransform = std::make_shared<const Transform3D>(translation); - auto cylinderSurfaceObject - = Surface::makeShared<CylinderSurface>(pTransform, radius, halfZ); - // - auto cylinderSurfaceObject2 - = Surface::makeShared<CylinderSurface>(pTransform, radius, halfZ); - // - /// Test equality operator - BOOST_CHECK(*cylinderSurfaceObject == *cylinderSurfaceObject2); - // - BOOST_TEST_CHECKPOINT( - "Create and then assign a CylinderSurface object to the existing one"); - /// Test assignment - auto assignedCylinderSurface - = Surface::makeShared<CylinderSurface>(nullptr, 6.6, 5.4); - *assignedCylinderSurface = *cylinderSurfaceObject; - /// Test equality of assigned to original - BOOST_CHECK(*assignedCylinderSurface == *cylinderSurfaceObject); - } - - BOOST_AUTO_TEST_SUITE_END() +} + +BOOST_AUTO_TEST_CASE(EqualityOperators) { + double radius(1.0), halfZ(10.); + Translation3D translation{0., 1., 2.}; + auto pTransform = std::make_shared<const Transform3D>(translation); + auto cylinderSurfaceObject = + Surface::makeShared<CylinderSurface>(pTransform, radius, halfZ); + // + auto cylinderSurfaceObject2 = + Surface::makeShared<CylinderSurface>(pTransform, radius, halfZ); + // + /// Test equality operator + BOOST_CHECK(*cylinderSurfaceObject == *cylinderSurfaceObject2); + // + BOOST_TEST_CHECKPOINT( + "Create and then assign a CylinderSurface object to the existing one"); + /// Test assignment + auto assignedCylinderSurface = + Surface::makeShared<CylinderSurface>(nullptr, 6.6, 5.4); + *assignedCylinderSurface = *cylinderSurfaceObject; + /// Test equality of assigned to original + BOOST_CHECK(*assignedCylinderSurface == *cylinderSurfaceObject); +} + +BOOST_AUTO_TEST_SUITE_END() } // namespace Test diff --git a/Tests/Core/Surfaces/DiamondBoundsTests.cpp b/Tests/Core/Surfaces/DiamondBoundsTests.cpp index 51149efa8cfbe7ac3e99f47e09403dca4cccaac0..64fd4437489b93a425f681692af5800c14ada904 100644 --- a/Tests/Core/Surfaces/DiamondBoundsTests.cpp +++ b/Tests/Core/Surfaces/DiamondBoundsTests.cpp @@ -24,132 +24,122 @@ namespace Acts { namespace Test { - BOOST_AUTO_TEST_SUITE(Surfaces) - /// Unit test for creating compliant/non-compliant DiamondBounds object - BOOST_AUTO_TEST_CASE(DiamondBoundsConstruction) - { - double minHalfX(10.), midHalfX(20.), maxHalfX(15.), halfY1(5.), halfY2(7.); - // test default construction - // DiamondBounds defaultConstructedDiamondBounds; //deleted - // - /// Test construction with dimensions - // DiamondBounds d(minHalfX, midHalfX, maxHalfX, halfY1, halfY2); - BOOST_CHECK_EQUAL( - DiamondBounds(minHalfX, midHalfX, maxHalfX, halfY1, halfY2).type(), - SurfaceBounds::Diamond); - // - /// Copy constructor - DiamondBounds original(minHalfX, midHalfX, maxHalfX, halfY1, halfY2); - DiamondBounds copied(original); - BOOST_CHECK_EQUAL(copied.type(), SurfaceBounds::Diamond); +BOOST_AUTO_TEST_SUITE(Surfaces) +/// Unit test for creating compliant/non-compliant DiamondBounds object +BOOST_AUTO_TEST_CASE(DiamondBoundsConstruction) { + double minHalfX(10.), midHalfX(20.), maxHalfX(15.), halfY1(5.), halfY2(7.); + // test default construction + // DiamondBounds defaultConstructedDiamondBounds; //deleted + // + /// Test construction with dimensions + // DiamondBounds d(minHalfX, midHalfX, maxHalfX, halfY1, halfY2); + BOOST_CHECK_EQUAL( + DiamondBounds(minHalfX, midHalfX, maxHalfX, halfY1, halfY2).type(), + SurfaceBounds::Diamond); + // + /// Copy constructor + DiamondBounds original(minHalfX, midHalfX, maxHalfX, halfY1, halfY2); + DiamondBounds copied(original); + BOOST_CHECK_EQUAL(copied.type(), SurfaceBounds::Diamond); - // invalid inputs - BOOST_CHECK_THROW( - DiamondBounds db(midHalfX, minHalfX, maxHalfX, halfY1, halfY2), - AssertionFailureException); - BOOST_CHECK_THROW( - DiamondBounds db(minHalfX, maxHalfX, midHalfX, halfY1, halfY2), - AssertionFailureException); - } - /// Unit tests for DiamondBounds properties - BOOST_AUTO_TEST_CASE(DiamondBoundsProperties) - { - double minHalfX(10.), midHalfX(50.), maxHalfX(30.), halfY1(10.), - halfY2(20.); - /// Test clone - DiamondBounds diamondBoundsObject( - minHalfX, midHalfX, maxHalfX, halfY1, halfY2); - auto pClonedDiamondBoundsObject = diamondBoundsObject.clone(); - BOOST_CHECK_NE(pClonedDiamondBoundsObject, nullptr); - delete pClonedDiamondBoundsObject; - // - /// Test type() (redundant; already used in constructor confirmation) - BOOST_CHECK_EQUAL(diamondBoundsObject.type(), SurfaceBounds::Diamond); - // //redundant test - // - /// Test minHalflengthX() NOTE: Naming violation - BOOST_CHECK_EQUAL(diamondBoundsObject.minHalflengthX(), minHalfX); - // - /// Test medHalflengthX() NOTE: Naming violation - BOOST_CHECK_EQUAL(diamondBoundsObject.medHalflengthX(), midHalfX); - // - /// Test maxHalflengthX() NOTE: Naming violation - BOOST_CHECK_EQUAL(diamondBoundsObject.maxHalflengthX(), maxHalfX); - // - /// Test halflengthY1() NOTE: Naming violation - BOOST_CHECK_EQUAL(diamondBoundsObject.halflengthY1(), halfY1); - // - /// Test halflengthY2() NOTE: Naming violation - BOOST_CHECK_EQUAL(diamondBoundsObject.halflengthY2(), halfY2); - // - /// Test boundingBox - BOOST_CHECK_EQUAL(diamondBoundsObject.boundingBox(), - RectangleBounds(50., 20.)); - // - // clone already tested - // - /// Test distanceToBoundary - Vector2D origin(0., 0.); - Vector2D outsideBy10(0., 30.); - Vector2D inRectangle(15., 0.); - CHECK_CLOSE_REL(diamondBoundsObject.distanceToBoundary(origin), - -10., - 1e-6); // makes sense - CHECK_CLOSE_REL(diamondBoundsObject.distanceToBoundary(outsideBy10), - 10., - 1e-6); // ok - // - /// Test dump - // Acts::DiamondBounds: (minHlengthX, medHlengthX, maxHlengthX, hlengthY1, - // hlengthY2 ) = (30.0000000, 10.0000000, 50.0000000, 10.0000000, - // 20.0000000) - diamondBoundsObject.toStream(std::cout); - boost::test_tools::output_test_stream dumpOuput; - diamondBoundsObject.toStream(dumpOuput); - BOOST_CHECK( - dumpOuput.is_equal("Acts::DiamondBounds: (minHlengthX, medHlengthX, " - "maxHlengthX, hlengthY1, hlengthY2 ) = (10.0000000, " - "50.0000000, 30.0000000, 10.0000000, 20.0000000)")); - // - /// Test inside - BOOST_CHECK(diamondBoundsObject.inside(origin, BoundaryCheck(true))); - // dont understand why this is so: - BOOST_CHECK(!diamondBoundsObject.inside(outsideBy10, BoundaryCheck(true))); - // - /// Test vertices (does this need to be implemented in this class?? - // auto v=diamondBoundsObject.vertices(); - std::vector<Vector2D> referenceVertices{{minHalfX, -halfY1}, - {midHalfX, 0.}, - {maxHalfX, halfY2}, - {-maxHalfX, halfY2}, - {-midHalfX, 0.}, - {-minHalfX, -halfY1}}; - const auto& actualVertices = diamondBoundsObject.vertices(); - BOOST_CHECK_EQUAL_COLLECTIONS(actualVertices.cbegin(), - actualVertices.cend(), - referenceVertices.cbegin(), - referenceVertices.cend()); - } - /// Unit test for testing DiamondBounds assignment - BOOST_AUTO_TEST_CASE(DiamondBoundsAssignment) - { - double minHalfX(10.), midHalfX(20.), maxHalfX(15.), halfY1(5.), halfY2(7.); - DiamondBounds diamondBoundsObject( - minHalfX, midHalfX, maxHalfX, halfY1, halfY2); - DiamondBounds similarlyConstructeDiamondBoundsObject( - minHalfX, midHalfX, maxHalfX, halfY1, halfY2); - /// Test operator == - BOOST_CHECK_EQUAL(diamondBoundsObject, - similarlyConstructeDiamondBoundsObject); - // - /// Test assignment - DiamondBounds assignedDiamondBoundsObject(0, 0, 0, 0, 0); // invalid - // object, in some sense - assignedDiamondBoundsObject = diamondBoundsObject; - BOOST_CHECK_EQUAL(assignedDiamondBoundsObject, diamondBoundsObject); - } + // invalid inputs + BOOST_CHECK_THROW( + DiamondBounds db(midHalfX, minHalfX, maxHalfX, halfY1, halfY2), + AssertionFailureException); + BOOST_CHECK_THROW( + DiamondBounds db(minHalfX, maxHalfX, midHalfX, halfY1, halfY2), + AssertionFailureException); +} +/// Unit tests for DiamondBounds properties +BOOST_AUTO_TEST_CASE(DiamondBoundsProperties) { + double minHalfX(10.), midHalfX(50.), maxHalfX(30.), halfY1(10.), halfY2(20.); + /// Test clone + DiamondBounds diamondBoundsObject(minHalfX, midHalfX, maxHalfX, halfY1, + halfY2); + auto pClonedDiamondBoundsObject = diamondBoundsObject.clone(); + BOOST_CHECK_NE(pClonedDiamondBoundsObject, nullptr); + delete pClonedDiamondBoundsObject; + // + /// Test type() (redundant; already used in constructor confirmation) + BOOST_CHECK_EQUAL(diamondBoundsObject.type(), SurfaceBounds::Diamond); + // //redundant test + // + /// Test minHalflengthX() NOTE: Naming violation + BOOST_CHECK_EQUAL(diamondBoundsObject.minHalflengthX(), minHalfX); + // + /// Test medHalflengthX() NOTE: Naming violation + BOOST_CHECK_EQUAL(diamondBoundsObject.medHalflengthX(), midHalfX); + // + /// Test maxHalflengthX() NOTE: Naming violation + BOOST_CHECK_EQUAL(diamondBoundsObject.maxHalflengthX(), maxHalfX); + // + /// Test halflengthY1() NOTE: Naming violation + BOOST_CHECK_EQUAL(diamondBoundsObject.halflengthY1(), halfY1); + // + /// Test halflengthY2() NOTE: Naming violation + BOOST_CHECK_EQUAL(diamondBoundsObject.halflengthY2(), halfY2); + // + /// Test boundingBox + BOOST_CHECK_EQUAL(diamondBoundsObject.boundingBox(), + RectangleBounds(50., 20.)); + // + // clone already tested + // + /// Test distanceToBoundary + Vector2D origin(0., 0.); + Vector2D outsideBy10(0., 30.); + Vector2D inRectangle(15., 0.); + CHECK_CLOSE_REL(diamondBoundsObject.distanceToBoundary(origin), -10., + 1e-6); // makes sense + CHECK_CLOSE_REL(diamondBoundsObject.distanceToBoundary(outsideBy10), 10., + 1e-6); // ok + // + /// Test dump + // Acts::DiamondBounds: (minHlengthX, medHlengthX, maxHlengthX, hlengthY1, + // hlengthY2 ) = (30.0000000, 10.0000000, 50.0000000, 10.0000000, + // 20.0000000) + diamondBoundsObject.toStream(std::cout); + boost::test_tools::output_test_stream dumpOuput; + diamondBoundsObject.toStream(dumpOuput); + BOOST_CHECK( + dumpOuput.is_equal("Acts::DiamondBounds: (minHlengthX, medHlengthX, " + "maxHlengthX, hlengthY1, hlengthY2 ) = (10.0000000, " + "50.0000000, 30.0000000, 10.0000000, 20.0000000)")); + // + /// Test inside + BOOST_CHECK(diamondBoundsObject.inside(origin, BoundaryCheck(true))); + // dont understand why this is so: + BOOST_CHECK(!diamondBoundsObject.inside(outsideBy10, BoundaryCheck(true))); + // + /// Test vertices (does this need to be implemented in this class?? + // auto v=diamondBoundsObject.vertices(); + std::vector<Vector2D> referenceVertices{ + {minHalfX, -halfY1}, {midHalfX, 0.}, {maxHalfX, halfY2}, + {-maxHalfX, halfY2}, {-midHalfX, 0.}, {-minHalfX, -halfY1}}; + const auto& actualVertices = diamondBoundsObject.vertices(); + BOOST_CHECK_EQUAL_COLLECTIONS(actualVertices.cbegin(), actualVertices.cend(), + referenceVertices.cbegin(), + referenceVertices.cend()); +} +/// Unit test for testing DiamondBounds assignment +BOOST_AUTO_TEST_CASE(DiamondBoundsAssignment) { + double minHalfX(10.), midHalfX(20.), maxHalfX(15.), halfY1(5.), halfY2(7.); + DiamondBounds diamondBoundsObject(minHalfX, midHalfX, maxHalfX, halfY1, + halfY2); + DiamondBounds similarlyConstructeDiamondBoundsObject( + minHalfX, midHalfX, maxHalfX, halfY1, halfY2); + /// Test operator == + BOOST_CHECK_EQUAL(diamondBoundsObject, + similarlyConstructeDiamondBoundsObject); + // + /// Test assignment + DiamondBounds assignedDiamondBoundsObject(0, 0, 0, 0, 0); // invalid + // object, in some sense + assignedDiamondBoundsObject = diamondBoundsObject; + BOOST_CHECK_EQUAL(assignedDiamondBoundsObject, diamondBoundsObject); +} - BOOST_AUTO_TEST_SUITE_END() +BOOST_AUTO_TEST_SUITE_END() } // namespace Test diff --git a/Tests/Core/Surfaces/DiscSurfaceTests.cpp b/Tests/Core/Surfaces/DiscSurfaceTests.cpp index 4285a9176b0b0a48e87fe5ace487a73646d8bd96..f5c1d4d01c582a8ca53c85268cc7ecbbd1adfbe0 100644 --- a/Tests/Core/Surfaces/DiscSurfaceTests.cpp +++ b/Tests/Core/Surfaces/DiscSurfaceTests.cpp @@ -25,208 +25,194 @@ #include "Acts/Utilities/Definitions.hpp" namespace utf = boost::unit_test; -namespace tt = boost::test_tools; +namespace tt = boost::test_tools; namespace Acts { namespace Test { - // using boost::test_tools::output_test_stream; - // Create a test context - GeometryContext tgContext = GeometryContext(); +// using boost::test_tools::output_test_stream; +// Create a test context +GeometryContext tgContext = GeometryContext(); - BOOST_AUTO_TEST_SUITE(Surfaces) - /// Unit tests for creating DiscSurface object - BOOST_AUTO_TEST_CASE(DiscSurface_constructors_test) - { - // default constructor is deleted - // scaffolding... - double rMin(1.0), rMax(5.0), halfPhiSector(M_PI / 8.); - // - /// Test DiscSurface fully specified constructor but no transform - BOOST_CHECK_NO_THROW( - Surface::makeShared<DiscSurface>(nullptr, rMin, rMax, halfPhiSector)); - // - /// Test DiscSurface constructor with default halfPhiSector - BOOST_CHECK_NO_THROW(Surface::makeShared<DiscSurface>(nullptr, rMin, rMax)); - // - /// Test DiscSurface constructor with a transform specified - Translation3D translation{0., 1., 2.}; - auto pTransform = std::make_shared<const Transform3D>(translation); - BOOST_CHECK_NO_THROW(Surface::makeShared<DiscSurface>( - pTransform, rMin, rMax, halfPhiSector)); - // - /// Copy constructed DiscSurface - auto anotherDiscSurface = Surface::makeShared<DiscSurface>( - pTransform, rMin, rMax, halfPhiSector); - // N.B. Just using - // BOOST_CHECK_NO_THROW(Surface::makeShared<DiscSurface>(anotherDiscSurface)) - // tries to call - // the (deleted) default constructor. - auto copiedSurface = Surface::makeShared<DiscSurface>(*anotherDiscSurface); - BOOST_TEST_MESSAGE("Copy constructed DiscSurface ok"); - // - /// Copied and transformed DiscSurface - BOOST_CHECK_NO_THROW(Surface::makeShared<DiscSurface>( - tgContext, *anotherDiscSurface, *pTransform)); +BOOST_AUTO_TEST_SUITE(Surfaces) +/// Unit tests for creating DiscSurface object +BOOST_AUTO_TEST_CASE(DiscSurface_constructors_test) { + // default constructor is deleted + // scaffolding... + double rMin(1.0), rMax(5.0), halfPhiSector(M_PI / 8.); + // + /// Test DiscSurface fully specified constructor but no transform + BOOST_CHECK_NO_THROW( + Surface::makeShared<DiscSurface>(nullptr, rMin, rMax, halfPhiSector)); + // + /// Test DiscSurface constructor with default halfPhiSector + BOOST_CHECK_NO_THROW(Surface::makeShared<DiscSurface>(nullptr, rMin, rMax)); + // + /// Test DiscSurface constructor with a transform specified + Translation3D translation{0., 1., 2.}; + auto pTransform = std::make_shared<const Transform3D>(translation); + BOOST_CHECK_NO_THROW( + Surface::makeShared<DiscSurface>(pTransform, rMin, rMax, halfPhiSector)); + // + /// Copy constructed DiscSurface + auto anotherDiscSurface = + Surface::makeShared<DiscSurface>(pTransform, rMin, rMax, halfPhiSector); + // N.B. Just using + // BOOST_CHECK_NO_THROW(Surface::makeShared<DiscSurface>(anotherDiscSurface)) + // tries to call + // the (deleted) default constructor. + auto copiedSurface = Surface::makeShared<DiscSurface>(*anotherDiscSurface); + BOOST_TEST_MESSAGE("Copy constructed DiscSurface ok"); + // + /// Copied and transformed DiscSurface + BOOST_CHECK_NO_THROW(Surface::makeShared<DiscSurface>( + tgContext, *anotherDiscSurface, *pTransform)); - /// Construct with nullptr bounds - DetectorElementStub detElem; - BOOST_CHECK_THROW(auto nullBounds - = Surface::makeShared<DiscSurface>(nullptr, detElem), - AssertionFailureException); - } + /// Construct with nullptr bounds + DetectorElementStub detElem; + BOOST_CHECK_THROW( + auto nullBounds = Surface::makeShared<DiscSurface>(nullptr, detElem), + AssertionFailureException); +} - /// Unit tests of all named methods - BOOST_AUTO_TEST_CASE(DiscSurface_properties_test, *utf::expected_failures(2)) - { - Vector3D origin3D{0, 0, 0}; - std::shared_ptr<const Transform3D> pTransform; // nullptr - double rMin(1.0), rMax(5.0), halfPhiSector(M_PI / 8.); - auto discSurfaceObject = Surface::makeShared<DiscSurface>( - pTransform, rMin, rMax, halfPhiSector); - // - /// Test type - BOOST_CHECK_EQUAL(discSurfaceObject->type(), Surface::Disc); - // - /// Test normal, no local position specified - Vector3D zAxis{0, 0, 1}; - BOOST_CHECK_EQUAL(discSurfaceObject->normal(tgContext), zAxis); - // - /// Test normal, local position specified - Vector2D lpos(2.0, 0.05); - BOOST_CHECK_EQUAL(discSurfaceObject->normal(tgContext, lpos), zAxis); - // - /// Test binningPosition - // auto binningPosition= - // discSurfaceObject.binningPosition(BinningValue::binRPhi ); - // std::cout<<binningPosition<<std::endl; - BOOST_CHECK_EQUAL( - discSurfaceObject->binningPosition(tgContext, BinningValue::binRPhi), - origin3D); - // - /// Test bounds - BOOST_CHECK_EQUAL(discSurfaceObject->bounds().type(), SurfaceBounds::Disc); - // - Vector3D ignoredMomentum{0., 0., 0.}; - /// Test isOnSurface() - Vector3D point3DNotInSector{0.0, 1.2, 0}; - Vector3D point3DOnSurface{1.2, 0.0, 0}; - BOOST_CHECK(!discSurfaceObject->isOnSurface( - tgContext, point3DNotInSector, ignoredMomentum, true)); // passes - BOOST_CHECK(discSurfaceObject->isOnSurface( - tgContext, point3DOnSurface, ignoredMomentum, true)); // passes - // - /// Test localToGlobal - Vector3D returnedPosition{10.9, 8.7, 6.5}; - Vector3D expectedPosition{1.2, 0, 0}; - Vector2D rPhiOnDisc{1.2, 0.0}; - Vector2D rPhiNotInSector{1.2, M_PI}; // outside sector at Phi=0, +/- pi/8 - discSurfaceObject->localToGlobal( - tgContext, rPhiOnDisc, ignoredMomentum, returnedPosition); - CHECK_CLOSE_ABS(returnedPosition, expectedPosition, 1e-6); - // - discSurfaceObject->localToGlobal( - tgContext, rPhiNotInSector, ignoredMomentum, returnedPosition); - Vector3D expectedNonPosition{-1.2, 0, 0}; - CHECK_CLOSE_ABS(returnedPosition, expectedNonPosition, 1e-6); - // - /// Test globalToLocal - Vector2D returnedLocalPosition{33., 44.}; - Vector2D expectedLocalPosition{1.2, 0.0}; - BOOST_CHECK( - discSurfaceObject->globalToLocal(tgContext, - point3DOnSurface, - ignoredMomentum, - returnedLocalPosition)); // pass - CHECK_CLOSE_ABS(returnedLocalPosition, expectedLocalPosition, 1e-6); - // - BOOST_CHECK(!discSurfaceObject->globalToLocal( - tgContext, - point3DNotInSector, - ignoredMomentum, - returnedLocalPosition)); // test fails - // - Vector3D pointOutsideRadius{0.0, 100., 0}; - BOOST_CHECK( - !discSurfaceObject->globalToLocal(tgContext, - pointOutsideRadius, - ignoredMomentum, - returnedLocalPosition)); // fails - // - /// Test localPolarToCartesian - Vector2D rPhi1_1{std::sqrt(2.), M_PI / 4.}; - Vector2D cartesian1_1{1., 1.}; - CHECK_CLOSE_REL( - discSurfaceObject->localPolarToCartesian(rPhi1_1), cartesian1_1, 1e-6); - // - /// Test localCartesianToPolar - CHECK_CLOSE_REL( - discSurfaceObject->localCartesianToPolar(cartesian1_1), rPhi1_1, 1e-6); - // - /// Test localPolarToLocalCartesian - CHECK_CLOSE_REL(discSurfaceObject->localPolarToLocalCartesian(rPhi1_1), - cartesian1_1, - 1e-6); - // - /// Test localCartesianToGlobal - Vector3D cartesian3D1_1{1., 1., 0.}; - CHECK_CLOSE_ABS( - discSurfaceObject->localCartesianToGlobal(tgContext, cartesian1_1), - cartesian3D1_1, - 1e-6); - // - /// Test globalToLocalCartesian - CHECK_CLOSE_REL( - discSurfaceObject->globalToLocalCartesian(tgContext, cartesian3D1_1), - cartesian1_1, - 1e-6); - // - /// Test pathCorrection - double projected3DMomentum = std::sqrt(3.) * 1.e6; - Vector3D momentum{ - projected3DMomentum, projected3DMomentum, projected3DMomentum}; - Vector3D ignoredPosition{1.1, 2.2, 3.3}; - CHECK_CLOSE_REL( - discSurfaceObject->pathCorrection(tgContext, ignoredPosition, momentum), - std::sqrt(3), - 0.01); - // - /// intersectionEstimate - Vector3D globalPosition{1.2, 0.0, -10.}; - Vector3D direction{0., 0., 1.}; // must be normalised - Vector3D expected{1.2, 0.0, 0.0}; - // intersect is a struct of (Vector3D) position, pathLength, distance and - // (bool) valid - auto intersect = discSurfaceObject->intersectionEstimate( - tgContext, globalPosition, direction); - Intersection expectedIntersect{Vector3D{1.2, 0., 0.}, 10., true, 0.0}; - BOOST_CHECK(intersect.valid); - CHECK_CLOSE_ABS(intersect.position, expectedIntersect.position, 1e-9); - CHECK_CLOSE_ABS(intersect.pathLength, expectedIntersect.pathLength, 1e-9); - CHECK_CLOSE_ABS(intersect.distance, expectedIntersect.distance, 1e-9); - // - /// Test name - boost::test_tools::output_test_stream nameOuput; - nameOuput << discSurfaceObject->name(); - BOOST_CHECK(nameOuput.is_equal("Acts::DiscSurface")); - } - // - /// Unit test for testing DiscSurface assignment and equality - BOOST_AUTO_TEST_CASE(DiscSurface_assignment_test) - { - Vector3D origin3D{0, 0, 0}; - std::shared_ptr<const Transform3D> pTransform; // nullptr - double rMin(1.0), rMax(5.0), halfPhiSector(M_PI / 8.); - auto discSurfaceObject = Surface::makeShared<DiscSurface>( - pTransform, rMin, rMax, halfPhiSector); - auto assignedDisc - = Surface::makeShared<DiscSurface>(nullptr, 2.2, 4.4, 0.07); - // - BOOST_CHECK_NO_THROW(*assignedDisc = *discSurfaceObject); - BOOST_CHECK((*assignedDisc) == (*discSurfaceObject)); - } +/// Unit tests of all named methods +BOOST_AUTO_TEST_CASE(DiscSurface_properties_test, *utf::expected_failures(2)) { + Vector3D origin3D{0, 0, 0}; + std::shared_ptr<const Transform3D> pTransform; // nullptr + double rMin(1.0), rMax(5.0), halfPhiSector(M_PI / 8.); + auto discSurfaceObject = + Surface::makeShared<DiscSurface>(pTransform, rMin, rMax, halfPhiSector); + // + /// Test type + BOOST_CHECK_EQUAL(discSurfaceObject->type(), Surface::Disc); + // + /// Test normal, no local position specified + Vector3D zAxis{0, 0, 1}; + BOOST_CHECK_EQUAL(discSurfaceObject->normal(tgContext), zAxis); + // + /// Test normal, local position specified + Vector2D lpos(2.0, 0.05); + BOOST_CHECK_EQUAL(discSurfaceObject->normal(tgContext, lpos), zAxis); + // + /// Test binningPosition + // auto binningPosition= + // discSurfaceObject.binningPosition(BinningValue::binRPhi ); + // std::cout<<binningPosition<<std::endl; + BOOST_CHECK_EQUAL( + discSurfaceObject->binningPosition(tgContext, BinningValue::binRPhi), + origin3D); + // + /// Test bounds + BOOST_CHECK_EQUAL(discSurfaceObject->bounds().type(), SurfaceBounds::Disc); + // + Vector3D ignoredMomentum{0., 0., 0.}; + /// Test isOnSurface() + Vector3D point3DNotInSector{0.0, 1.2, 0}; + Vector3D point3DOnSurface{1.2, 0.0, 0}; + BOOST_CHECK(!discSurfaceObject->isOnSurface( + tgContext, point3DNotInSector, ignoredMomentum, true)); // passes + BOOST_CHECK(discSurfaceObject->isOnSurface(tgContext, point3DOnSurface, + ignoredMomentum, true)); // passes + // + /// Test localToGlobal + Vector3D returnedPosition{10.9, 8.7, 6.5}; + Vector3D expectedPosition{1.2, 0, 0}; + Vector2D rPhiOnDisc{1.2, 0.0}; + Vector2D rPhiNotInSector{1.2, M_PI}; // outside sector at Phi=0, +/- pi/8 + discSurfaceObject->localToGlobal(tgContext, rPhiOnDisc, ignoredMomentum, + returnedPosition); + CHECK_CLOSE_ABS(returnedPosition, expectedPosition, 1e-6); + // + discSurfaceObject->localToGlobal(tgContext, rPhiNotInSector, ignoredMomentum, + returnedPosition); + Vector3D expectedNonPosition{-1.2, 0, 0}; + CHECK_CLOSE_ABS(returnedPosition, expectedNonPosition, 1e-6); + // + /// Test globalToLocal + Vector2D returnedLocalPosition{33., 44.}; + Vector2D expectedLocalPosition{1.2, 0.0}; + BOOST_CHECK(discSurfaceObject->globalToLocal(tgContext, point3DOnSurface, + ignoredMomentum, + returnedLocalPosition)); // pass + CHECK_CLOSE_ABS(returnedLocalPosition, expectedLocalPosition, 1e-6); + // + BOOST_CHECK(!discSurfaceObject->globalToLocal( + tgContext, point3DNotInSector, ignoredMomentum, + returnedLocalPosition)); // test fails + // + Vector3D pointOutsideRadius{0.0, 100., 0}; + BOOST_CHECK(!discSurfaceObject->globalToLocal( + tgContext, pointOutsideRadius, ignoredMomentum, + returnedLocalPosition)); // fails + // + /// Test localPolarToCartesian + Vector2D rPhi1_1{std::sqrt(2.), M_PI / 4.}; + Vector2D cartesian1_1{1., 1.}; + CHECK_CLOSE_REL(discSurfaceObject->localPolarToCartesian(rPhi1_1), + cartesian1_1, 1e-6); + // + /// Test localCartesianToPolar + CHECK_CLOSE_REL(discSurfaceObject->localCartesianToPolar(cartesian1_1), + rPhi1_1, 1e-6); + // + /// Test localPolarToLocalCartesian + CHECK_CLOSE_REL(discSurfaceObject->localPolarToLocalCartesian(rPhi1_1), + cartesian1_1, 1e-6); + // + /// Test localCartesianToGlobal + Vector3D cartesian3D1_1{1., 1., 0.}; + CHECK_CLOSE_ABS( + discSurfaceObject->localCartesianToGlobal(tgContext, cartesian1_1), + cartesian3D1_1, 1e-6); + // + /// Test globalToLocalCartesian + CHECK_CLOSE_REL( + discSurfaceObject->globalToLocalCartesian(tgContext, cartesian3D1_1), + cartesian1_1, 1e-6); + // + /// Test pathCorrection + double projected3DMomentum = std::sqrt(3.) * 1.e6; + Vector3D momentum{projected3DMomentum, projected3DMomentum, + projected3DMomentum}; + Vector3D ignoredPosition{1.1, 2.2, 3.3}; + CHECK_CLOSE_REL( + discSurfaceObject->pathCorrection(tgContext, ignoredPosition, momentum), + std::sqrt(3), 0.01); + // + /// intersectionEstimate + Vector3D globalPosition{1.2, 0.0, -10.}; + Vector3D direction{0., 0., 1.}; // must be normalised + Vector3D expected{1.2, 0.0, 0.0}; + // intersect is a struct of (Vector3D) position, pathLength, distance and + // (bool) valid + auto intersect = discSurfaceObject->intersectionEstimate( + tgContext, globalPosition, direction); + Intersection expectedIntersect{Vector3D{1.2, 0., 0.}, 10., true, 0.0}; + BOOST_CHECK(intersect.valid); + CHECK_CLOSE_ABS(intersect.position, expectedIntersect.position, 1e-9); + CHECK_CLOSE_ABS(intersect.pathLength, expectedIntersect.pathLength, 1e-9); + CHECK_CLOSE_ABS(intersect.distance, expectedIntersect.distance, 1e-9); + // + /// Test name + boost::test_tools::output_test_stream nameOuput; + nameOuput << discSurfaceObject->name(); + BOOST_CHECK(nameOuput.is_equal("Acts::DiscSurface")); +} +// +/// Unit test for testing DiscSurface assignment and equality +BOOST_AUTO_TEST_CASE(DiscSurface_assignment_test) { + Vector3D origin3D{0, 0, 0}; + std::shared_ptr<const Transform3D> pTransform; // nullptr + double rMin(1.0), rMax(5.0), halfPhiSector(M_PI / 8.); + auto discSurfaceObject = + Surface::makeShared<DiscSurface>(pTransform, rMin, rMax, halfPhiSector); + auto assignedDisc = Surface::makeShared<DiscSurface>(nullptr, 2.2, 4.4, 0.07); + // + BOOST_CHECK_NO_THROW(*assignedDisc = *discSurfaceObject); + BOOST_CHECK((*assignedDisc) == (*discSurfaceObject)); +} - BOOST_AUTO_TEST_SUITE_END() +BOOST_AUTO_TEST_SUITE_END() } // namespace Test diff --git a/Tests/Core/Surfaces/DiscTrapezoidalBoundsTests.cpp b/Tests/Core/Surfaces/DiscTrapezoidalBoundsTests.cpp index f1b1105fd128e03f22ef1009a12ff00c027557ba..ef2df8a35b904bf046fa350f8a2fd39a891735c2 100644 --- a/Tests/Core/Surfaces/DiscTrapezoidalBoundsTests.cpp +++ b/Tests/Core/Surfaces/DiscTrapezoidalBoundsTests.cpp @@ -23,119 +23,112 @@ namespace Acts { namespace Test { - BOOST_AUTO_TEST_SUITE(Surfaces) - /// Unit tests for DiscTrapezoidalBounds constrcuctors - BOOST_AUTO_TEST_CASE(DiscTrapezoidalBoundsConstruction) - { - double minHalfX(1.0), maxHalfX(5.0), rMin(2.0), rMax(6.0), averagePhi(0.0), - stereo(0.1); - // test default construction - // DiscTrapezoidalBounds defaultConstructedDiscTrapezoidalBounds; should be - // deleted - // - /// Test construction with dimensions and default stereo - BOOST_CHECK_EQUAL( - DiscTrapezoidalBounds(minHalfX, maxHalfX, rMin, rMax, averagePhi) - .type(), - SurfaceBounds::DiscTrapezoidal); - // - /// Test construction with all dimensions - BOOST_CHECK_EQUAL(DiscTrapezoidalBounds( - minHalfX, maxHalfX, rMin, rMax, averagePhi, stereo) - .type(), - SurfaceBounds::DiscTrapezoidal); - // - /// Copy constructor - DiscTrapezoidalBounds original(minHalfX, maxHalfX, rMin, rMax, averagePhi); - DiscTrapezoidalBounds copied(original); - BOOST_CHECK_EQUAL(copied.type(), SurfaceBounds::DiscTrapezoidal); - } +BOOST_AUTO_TEST_SUITE(Surfaces) +/// Unit tests for DiscTrapezoidalBounds constrcuctors +BOOST_AUTO_TEST_CASE(DiscTrapezoidalBoundsConstruction) { + double minHalfX(1.0), maxHalfX(5.0), rMin(2.0), rMax(6.0), averagePhi(0.0), + stereo(0.1); + // test default construction + // DiscTrapezoidalBounds defaultConstructedDiscTrapezoidalBounds; should be + // deleted + // + /// Test construction with dimensions and default stereo + BOOST_CHECK_EQUAL( + DiscTrapezoidalBounds(minHalfX, maxHalfX, rMin, rMax, averagePhi).type(), + SurfaceBounds::DiscTrapezoidal); + // + /// Test construction with all dimensions + BOOST_CHECK_EQUAL( + DiscTrapezoidalBounds(minHalfX, maxHalfX, rMin, rMax, averagePhi, stereo) + .type(), + SurfaceBounds::DiscTrapezoidal); + // + /// Copy constructor + DiscTrapezoidalBounds original(minHalfX, maxHalfX, rMin, rMax, averagePhi); + DiscTrapezoidalBounds copied(original); + BOOST_CHECK_EQUAL(copied.type(), SurfaceBounds::DiscTrapezoidal); +} - /// Unit tests for DiscTrapezoidalBounds properties - BOOST_AUTO_TEST_CASE(DiscTrapezoidalBoundsProperties) - { - double minHalfX(1.0), maxHalfX(5.0), rMin(2.0), rMax(6.0), - averagePhi(0.0) /*, stereo(0.1)*/; - /// Test clone - DiscTrapezoidalBounds discTrapezoidalBoundsObject( - minHalfX, maxHalfX, rMin, rMax, averagePhi); - auto pClonedDiscTrapezoidalBounds = discTrapezoidalBoundsObject.clone(); - BOOST_CHECK_NE(pClonedDiscTrapezoidalBounds, nullptr); - delete pClonedDiscTrapezoidalBounds; - // - /// Test type() (redundant; already used in constructor confirmation) - BOOST_CHECK_EQUAL(discTrapezoidalBoundsObject.type(), - SurfaceBounds::DiscTrapezoidal); - // - /// Test distanceToBoundary - Vector2D origin(0., 0.); - Vector2D outside(30., 0.); - Vector2D inSurface(2., 0.0); - CHECK_CLOSE_REL( - discTrapezoidalBoundsObject.distanceToBoundary(origin), 2.0, 1e-6); - CHECK_CLOSE_REL( - discTrapezoidalBoundsObject.distanceToBoundary(outside), 24.0, 1e-6); - // - /// Test dump - boost::test_tools::output_test_stream dumpOuput; - discTrapezoidalBoundsObject.toStream(dumpOuput); - BOOST_CHECK(dumpOuput.is_equal( - "Acts::DiscTrapezoidalBounds: (innerRadius, outerRadius, hMinX, " - "hMaxX, hlengthY, hPhiSector, averagePhi, rCenter, stereo) = " - "(2.0000000, 6.0000000, 1.0000000, 5.0000000, 0.7922870, 0.9851108, " - "0.0000000, 2.5243378, 0.0000000)")); - // - /// Test inside - BOOST_CHECK( - discTrapezoidalBoundsObject.inside(inSurface, BoundaryCheck(true))); - BOOST_CHECK( - !discTrapezoidalBoundsObject.inside(outside, BoundaryCheck(true))); - // - /// Test rMin - CHECK_CLOSE_REL(discTrapezoidalBoundsObject.rMin(), rMin, 1e-6); - // - /// Test rMax - CHECK_CLOSE_REL(discTrapezoidalBoundsObject.rMax(), rMax, 1e-6); - // - /// Test averagePhi - CHECK_SMALL(discTrapezoidalBoundsObject.averagePhi(), 1e-9); - // - /// Test rCenter (redundant; not configurable) - CHECK_CLOSE_REL(discTrapezoidalBoundsObject.rCenter(), 2.524337798, 1e-6); - // - /// Test halfPhiSector (redundant; not configurable) - CHECK_SMALL(discTrapezoidalBoundsObject.stereo(), 1e-6); - // - /// Test minHalflengthX - CHECK_CLOSE_REL( - discTrapezoidalBoundsObject.minHalflengthX(), minHalfX, 1e-6); - // - /// Test maxHalflengthX - CHECK_CLOSE_REL( - discTrapezoidalBoundsObject.maxHalflengthX(), maxHalfX, 1e-6); - // - /// Test halflengthY - CHECK_CLOSE_REL( - discTrapezoidalBoundsObject.halflengthY(), 0.792286991, 1e-6); - } - /// Unit test for testing DiscTrapezoidalBounds assignment - BOOST_AUTO_TEST_CASE(DiscTrapezoidalBoundsAssignment) - { - double minHalfX(1.0), maxHalfX(5.0), rMin(2.0), rMax(6.0), averagePhi(0.0), - stereo(0.1); - DiscTrapezoidalBounds discTrapezoidalBoundsObject( - minHalfX, maxHalfX, rMin, rMax, averagePhi, stereo); - // operator == not implemented in this class - // - /// Test assignment - DiscTrapezoidalBounds assignedDiscTrapezoidalBoundsObject( - 2.1, 6.6, 3.4, 4.2, 33.); - assignedDiscTrapezoidalBoundsObject = discTrapezoidalBoundsObject; - BOOST_CHECK_EQUAL(assignedDiscTrapezoidalBoundsObject, - discTrapezoidalBoundsObject); - } +/// Unit tests for DiscTrapezoidalBounds properties +BOOST_AUTO_TEST_CASE(DiscTrapezoidalBoundsProperties) { + double minHalfX(1.0), maxHalfX(5.0), rMin(2.0), rMax(6.0), + averagePhi(0.0) /*, stereo(0.1)*/; + /// Test clone + DiscTrapezoidalBounds discTrapezoidalBoundsObject(minHalfX, maxHalfX, rMin, + rMax, averagePhi); + auto pClonedDiscTrapezoidalBounds = discTrapezoidalBoundsObject.clone(); + BOOST_CHECK_NE(pClonedDiscTrapezoidalBounds, nullptr); + delete pClonedDiscTrapezoidalBounds; + // + /// Test type() (redundant; already used in constructor confirmation) + BOOST_CHECK_EQUAL(discTrapezoidalBoundsObject.type(), + SurfaceBounds::DiscTrapezoidal); + // + /// Test distanceToBoundary + Vector2D origin(0., 0.); + Vector2D outside(30., 0.); + Vector2D inSurface(2., 0.0); + CHECK_CLOSE_REL(discTrapezoidalBoundsObject.distanceToBoundary(origin), 2.0, + 1e-6); + CHECK_CLOSE_REL(discTrapezoidalBoundsObject.distanceToBoundary(outside), 24.0, + 1e-6); + // + /// Test dump + boost::test_tools::output_test_stream dumpOuput; + discTrapezoidalBoundsObject.toStream(dumpOuput); + BOOST_CHECK(dumpOuput.is_equal( + "Acts::DiscTrapezoidalBounds: (innerRadius, outerRadius, hMinX, " + "hMaxX, hlengthY, hPhiSector, averagePhi, rCenter, stereo) = " + "(2.0000000, 6.0000000, 1.0000000, 5.0000000, 0.7922870, 0.9851108, " + "0.0000000, 2.5243378, 0.0000000)")); + // + /// Test inside + BOOST_CHECK( + discTrapezoidalBoundsObject.inside(inSurface, BoundaryCheck(true))); + BOOST_CHECK( + !discTrapezoidalBoundsObject.inside(outside, BoundaryCheck(true))); + // + /// Test rMin + CHECK_CLOSE_REL(discTrapezoidalBoundsObject.rMin(), rMin, 1e-6); + // + /// Test rMax + CHECK_CLOSE_REL(discTrapezoidalBoundsObject.rMax(), rMax, 1e-6); + // + /// Test averagePhi + CHECK_SMALL(discTrapezoidalBoundsObject.averagePhi(), 1e-9); + // + /// Test rCenter (redundant; not configurable) + CHECK_CLOSE_REL(discTrapezoidalBoundsObject.rCenter(), 2.524337798, 1e-6); + // + /// Test halfPhiSector (redundant; not configurable) + CHECK_SMALL(discTrapezoidalBoundsObject.stereo(), 1e-6); + // + /// Test minHalflengthX + CHECK_CLOSE_REL(discTrapezoidalBoundsObject.minHalflengthX(), minHalfX, 1e-6); + // + /// Test maxHalflengthX + CHECK_CLOSE_REL(discTrapezoidalBoundsObject.maxHalflengthX(), maxHalfX, 1e-6); + // + /// Test halflengthY + CHECK_CLOSE_REL(discTrapezoidalBoundsObject.halflengthY(), 0.792286991, 1e-6); +} +/// Unit test for testing DiscTrapezoidalBounds assignment +BOOST_AUTO_TEST_CASE(DiscTrapezoidalBoundsAssignment) { + double minHalfX(1.0), maxHalfX(5.0), rMin(2.0), rMax(6.0), averagePhi(0.0), + stereo(0.1); + DiscTrapezoidalBounds discTrapezoidalBoundsObject(minHalfX, maxHalfX, rMin, + rMax, averagePhi, stereo); + // operator == not implemented in this class + // + /// Test assignment + DiscTrapezoidalBounds assignedDiscTrapezoidalBoundsObject(2.1, 6.6, 3.4, 4.2, + 33.); + assignedDiscTrapezoidalBoundsObject = discTrapezoidalBoundsObject; + BOOST_CHECK_EQUAL(assignedDiscTrapezoidalBoundsObject, + discTrapezoidalBoundsObject); +} - BOOST_AUTO_TEST_SUITE_END() +BOOST_AUTO_TEST_SUITE_END() } // namespace Test diff --git a/Tests/Core/Surfaces/EllipseBoundsTests.cpp b/Tests/Core/Surfaces/EllipseBoundsTests.cpp index 3e27852514e9b2f8272ba8339837e580b9ba2864..cd766d0a7647240f27ccdbdfcc1e447fb4c4286e 100644 --- a/Tests/Core/Surfaces/EllipseBoundsTests.cpp +++ b/Tests/Core/Surfaces/EllipseBoundsTests.cpp @@ -23,122 +23,115 @@ namespace Acts { namespace Test { - BOOST_AUTO_TEST_SUITE(Surfaces) - /// Unit test for creating compliant/non-compliant EllipseBounds object - BOOST_AUTO_TEST_CASE(EllipseBoundsConstruction) - { - double minRad1(10.), minRad2(15.), maxRad1(15.), maxRad2(20.), - averagePhi(0.), phiSector(M_PI / 2.); - // test default construction - // EllipseBounds defaultConstructedEllipseBounds; //deleted - // - /// Test construction with dimensions - BOOST_CHECK_EQUAL( - EllipseBounds(minRad1, minRad2, maxRad1, maxRad2, averagePhi, phiSector) - .type(), - SurfaceBounds::Ellipse); - // - /// Copy constructor - EllipseBounds original( - minRad1, minRad2, maxRad1, maxRad2, averagePhi, phiSector); - EllipseBounds copied(original); - BOOST_CHECK_EQUAL(copied.type(), SurfaceBounds::Ellipse); - } +BOOST_AUTO_TEST_SUITE(Surfaces) +/// Unit test for creating compliant/non-compliant EllipseBounds object +BOOST_AUTO_TEST_CASE(EllipseBoundsConstruction) { + double minRad1(10.), minRad2(15.), maxRad1(15.), maxRad2(20.), averagePhi(0.), + phiSector(M_PI / 2.); + // test default construction + // EllipseBounds defaultConstructedEllipseBounds; //deleted + // + /// Test construction with dimensions + BOOST_CHECK_EQUAL( + EllipseBounds(minRad1, minRad2, maxRad1, maxRad2, averagePhi, phiSector) + .type(), + SurfaceBounds::Ellipse); + // + /// Copy constructor + EllipseBounds original(minRad1, minRad2, maxRad1, maxRad2, averagePhi, + phiSector); + EllipseBounds copied(original); + BOOST_CHECK_EQUAL(copied.type(), SurfaceBounds::Ellipse); +} - /// Unit tests for EllipseBounds properties - BOOST_AUTO_TEST_CASE_EXPECTED_FAILURES(CylinderBoundsProperties, 1) - BOOST_AUTO_TEST_CASE(EllipseBoundsProperties) - { - double minRad1(10.), minRad2(15.), maxRad1(15.), maxRad2(20.), - averagePhi(0.), phiSector(M_PI / 2.); - /// Test clone - EllipseBounds ellipseBoundsObject( - minRad1, minRad2, maxRad1, maxRad2, averagePhi, phiSector); - auto pClonedEllipseBoundsObject = ellipseBoundsObject.clone(); - BOOST_CHECK_NE(pClonedEllipseBoundsObject, nullptr); - delete pClonedEllipseBoundsObject; - // - /// Test type() (redundant; already used in constructor confirmation) - BOOST_CHECK_EQUAL(ellipseBoundsObject.type(), SurfaceBounds::Ellipse); - // - // clone already tested - // - /// Test distanceToBoundary - Vector2D origin(0., 0.); - Vector2D outsideBy10(0., 30.); - Vector2D inRectangle(17., 11.); - CHECK_CLOSE_REL(ellipseBoundsObject.distanceToBoundary(origin), - 10., - 1e-6); // makes sense - CHECK_CLOSE_REL(ellipseBoundsObject.distanceToBoundary(outsideBy10), - 10., - 1e-6); // fails, not clear why - // - /// Test rMinX - BOOST_CHECK_EQUAL(ellipseBoundsObject.rMinX(), minRad1); - // - /// Test rMinY - BOOST_CHECK_EQUAL(ellipseBoundsObject.rMinY(), minRad2); - // - /// Test rMaxX - BOOST_CHECK_EQUAL(ellipseBoundsObject.rMaxX(), maxRad1); - // - /// Test rMaxY - BOOST_CHECK_EQUAL(ellipseBoundsObject.rMaxY(), maxRad2); - // - /// Test averagePhi - BOOST_CHECK_EQUAL(ellipseBoundsObject.averagePhi(), averagePhi); - // - /// Test vertices - std::vector<Vector2D> expectedVertices{ - {15, 0}, {0, 20}, {-15, 0}, {0, -20}}; - const auto& actualVertices = ellipseBoundsObject.vertices(); - BOOST_CHECK_EQUAL_COLLECTIONS(actualVertices.cbegin(), - actualVertices.cend(), - expectedVertices.cbegin(), - expectedVertices.cend()); - // - /// Test boundingBox - BOOST_CHECK_EQUAL(ellipseBoundsObject.boundingBox(), - RectangleBounds(15., 20.)); - // - /// Test halfPhiSector - BOOST_CHECK_EQUAL(ellipseBoundsObject.halfPhiSector(), M_PI / 2.); - // - /// Test dump - boost::test_tools::output_test_stream dumpOuput; - ellipseBoundsObject.toStream(dumpOuput); - BOOST_CHECK(dumpOuput.is_equal( - "Acts::EllipseBounds: (innerRadiusX, innerRadiusY, outerRadiusX, " - "outerRadiusY, hPhiSector) = (10.0000000, 15.0000000, 15.0000000, " - "20.0000000, 0.0000000, 1.5707963)")); - // - /// Test inside - BOOST_CHECK(!ellipseBoundsObject.inside(inRectangle, BoundaryCheck(true))); - // dont understand why this is so: - BOOST_CHECK(!ellipseBoundsObject.inside(outsideBy10, BoundaryCheck(true))); - } - /// Unit test for testing EllipseBounds assignment - BOOST_AUTO_TEST_CASE(EllipseBoundsAssignment) - { - double minRad1(10.), minRad2(15.), maxRad1(15.), maxRad2(20.), - averagePhi(0.), phiSector(M_PI / 2.); - EllipseBounds ellipseBoundsObject( - minRad1, minRad2, maxRad1, maxRad2, averagePhi, phiSector); - EllipseBounds similarlyConstructeEllipseBoundsObject( - minRad1, minRad2, maxRad1, maxRad2, averagePhi, phiSector); - /// Test operator == - BOOST_CHECK_EQUAL(ellipseBoundsObject, - similarlyConstructeEllipseBoundsObject); - // - /// Test assignment - EllipseBounds assignedEllipseBoundsObject(11., 12., 17., 18., 1.); - // object, in some sense - assignedEllipseBoundsObject = ellipseBoundsObject; - BOOST_CHECK_EQUAL(assignedEllipseBoundsObject, ellipseBoundsObject); - } +/// Unit tests for EllipseBounds properties +BOOST_AUTO_TEST_CASE_EXPECTED_FAILURES(CylinderBoundsProperties, 1) +BOOST_AUTO_TEST_CASE(EllipseBoundsProperties) { + double minRad1(10.), minRad2(15.), maxRad1(15.), maxRad2(20.), averagePhi(0.), + phiSector(M_PI / 2.); + /// Test clone + EllipseBounds ellipseBoundsObject(minRad1, minRad2, maxRad1, maxRad2, + averagePhi, phiSector); + auto pClonedEllipseBoundsObject = ellipseBoundsObject.clone(); + BOOST_CHECK_NE(pClonedEllipseBoundsObject, nullptr); + delete pClonedEllipseBoundsObject; + // + /// Test type() (redundant; already used in constructor confirmation) + BOOST_CHECK_EQUAL(ellipseBoundsObject.type(), SurfaceBounds::Ellipse); + // + // clone already tested + // + /// Test distanceToBoundary + Vector2D origin(0., 0.); + Vector2D outsideBy10(0., 30.); + Vector2D inRectangle(17., 11.); + CHECK_CLOSE_REL(ellipseBoundsObject.distanceToBoundary(origin), 10., + 1e-6); // makes sense + CHECK_CLOSE_REL(ellipseBoundsObject.distanceToBoundary(outsideBy10), 10., + 1e-6); // fails, not clear why + // + /// Test rMinX + BOOST_CHECK_EQUAL(ellipseBoundsObject.rMinX(), minRad1); + // + /// Test rMinY + BOOST_CHECK_EQUAL(ellipseBoundsObject.rMinY(), minRad2); + // + /// Test rMaxX + BOOST_CHECK_EQUAL(ellipseBoundsObject.rMaxX(), maxRad1); + // + /// Test rMaxY + BOOST_CHECK_EQUAL(ellipseBoundsObject.rMaxY(), maxRad2); + // + /// Test averagePhi + BOOST_CHECK_EQUAL(ellipseBoundsObject.averagePhi(), averagePhi); + // + /// Test vertices + std::vector<Vector2D> expectedVertices{{15, 0}, {0, 20}, {-15, 0}, {0, -20}}; + const auto& actualVertices = ellipseBoundsObject.vertices(); + BOOST_CHECK_EQUAL_COLLECTIONS(actualVertices.cbegin(), actualVertices.cend(), + expectedVertices.cbegin(), + expectedVertices.cend()); + // + /// Test boundingBox + BOOST_CHECK_EQUAL(ellipseBoundsObject.boundingBox(), + RectangleBounds(15., 20.)); + // + /// Test halfPhiSector + BOOST_CHECK_EQUAL(ellipseBoundsObject.halfPhiSector(), M_PI / 2.); + // + /// Test dump + boost::test_tools::output_test_stream dumpOuput; + ellipseBoundsObject.toStream(dumpOuput); + BOOST_CHECK(dumpOuput.is_equal( + "Acts::EllipseBounds: (innerRadiusX, innerRadiusY, outerRadiusX, " + "outerRadiusY, hPhiSector) = (10.0000000, 15.0000000, 15.0000000, " + "20.0000000, 0.0000000, 1.5707963)")); + // + /// Test inside + BOOST_CHECK(!ellipseBoundsObject.inside(inRectangle, BoundaryCheck(true))); + // dont understand why this is so: + BOOST_CHECK(!ellipseBoundsObject.inside(outsideBy10, BoundaryCheck(true))); +} +/// Unit test for testing EllipseBounds assignment +BOOST_AUTO_TEST_CASE(EllipseBoundsAssignment) { + double minRad1(10.), minRad2(15.), maxRad1(15.), maxRad2(20.), averagePhi(0.), + phiSector(M_PI / 2.); + EllipseBounds ellipseBoundsObject(minRad1, minRad2, maxRad1, maxRad2, + averagePhi, phiSector); + EllipseBounds similarlyConstructeEllipseBoundsObject( + minRad1, minRad2, maxRad1, maxRad2, averagePhi, phiSector); + /// Test operator == + BOOST_CHECK_EQUAL(ellipseBoundsObject, + similarlyConstructeEllipseBoundsObject); + // + /// Test assignment + EllipseBounds assignedEllipseBoundsObject(11., 12., 17., 18., 1.); + // object, in some sense + assignedEllipseBoundsObject = ellipseBoundsObject; + BOOST_CHECK_EQUAL(assignedEllipseBoundsObject, ellipseBoundsObject); +} - BOOST_AUTO_TEST_SUITE_END() +BOOST_AUTO_TEST_SUITE_END() } // namespace Test diff --git a/Tests/Core/Surfaces/InfiniteBoundsTests.cpp b/Tests/Core/Surfaces/InfiniteBoundsTests.cpp index 0579da3248705b816740cc4af11cf5dfbe24a626..55ccefea97e604df426978d87966b56ccfd90ef3 100644 --- a/Tests/Core/Surfaces/InfiniteBoundsTests.cpp +++ b/Tests/Core/Surfaces/InfiniteBoundsTests.cpp @@ -25,46 +25,44 @@ namespace Acts { namespace Test { - BOOST_AUTO_TEST_SUITE(Surfaces) - /// Unit test for creating compliant/non-compliant InfiniteBounds object - BOOST_AUTO_TEST_CASE(InfiniteBoundsConstruction) - { - InfiniteBounds u; - BOOST_CHECK_EQUAL(u.type(), SurfaceBounds::Boundless); - // InfiniteBounds s(1); // would act as size_t cast to InfiniteBounds - // InfiniteBounds t(s); - InfiniteBounds v(u); // implicit - BOOST_CHECK_EQUAL(v.type(), SurfaceBounds::Boundless); - } - /// Unit tests for InfiniteBounds properties - BOOST_AUTO_TEST_CASE(InfiniteBoundsProperties) - { - InfiniteBounds infiniteBoundsObject; - /// test for type() - BOOST_CHECK_EQUAL(infiniteBoundsObject.type(), SurfaceBounds::Boundless); +BOOST_AUTO_TEST_SUITE(Surfaces) +/// Unit test for creating compliant/non-compliant InfiniteBounds object +BOOST_AUTO_TEST_CASE(InfiniteBoundsConstruction) { + InfiniteBounds u; + BOOST_CHECK_EQUAL(u.type(), SurfaceBounds::Boundless); + // InfiniteBounds s(1); // would act as size_t cast to InfiniteBounds + // InfiniteBounds t(s); + InfiniteBounds v(u); // implicit + BOOST_CHECK_EQUAL(v.type(), SurfaceBounds::Boundless); +} +/// Unit tests for InfiniteBounds properties +BOOST_AUTO_TEST_CASE(InfiniteBoundsProperties) { + InfiniteBounds infiniteBoundsObject; + /// test for type() + BOOST_CHECK_EQUAL(infiniteBoundsObject.type(), SurfaceBounds::Boundless); - /// test for inside() - const Vector2D anyVector{0., 1.}; - const BoundaryCheck anyBoundaryCheck(true); - BOOST_CHECK(infiniteBoundsObject.inside(anyVector, anyBoundaryCheck)); + /// test for inside() + const Vector2D anyVector{0., 1.}; + const BoundaryCheck anyBoundaryCheck(true); + BOOST_CHECK(infiniteBoundsObject.inside(anyVector, anyBoundaryCheck)); - /// test for distanceToBoundary - BOOST_TEST_MESSAGE("Perhaps the following should be inf?"); - BOOST_CHECK_EQUAL(infiniteBoundsObject.distanceToBoundary(anyVector), 0.); + /// test for distanceToBoundary + BOOST_TEST_MESSAGE("Perhaps the following should be inf?"); + BOOST_CHECK_EQUAL(infiniteBoundsObject.distanceToBoundary(anyVector), 0.); - /// test for clone - auto pInfiniteBoundsClone = infiniteBoundsObject.clone(); - BOOST_CHECK_NE(pInfiniteBoundsClone, nullptr); - delete pInfiniteBoundsClone; + /// test for clone + auto pInfiniteBoundsClone = infiniteBoundsObject.clone(); + BOOST_CHECK_NE(pInfiniteBoundsClone, nullptr); + delete pInfiniteBoundsClone; - /// test for dump - boost::test_tools::output_test_stream dumpOuput; - infiniteBoundsObject.toStream(dumpOuput); - BOOST_CHECK( - dumpOuput.is_equal("Acts::InfiniteBounds ... boundless surface\n")); - } + /// test for dump + boost::test_tools::output_test_stream dumpOuput; + infiniteBoundsObject.toStream(dumpOuput); + BOOST_CHECK( + dumpOuput.is_equal("Acts::InfiniteBounds ... boundless surface\n")); +} - BOOST_AUTO_TEST_SUITE_END() +BOOST_AUTO_TEST_SUITE_END() } // namespace Test diff --git a/Tests/Core/Surfaces/LineBoundsTests.cpp b/Tests/Core/Surfaces/LineBoundsTests.cpp index 29aa46554d19500bc223fa3121b4489d338cd4e9..1c52dc48f1778fd96048d796ac360222b11160db 100644 --- a/Tests/Core/Surfaces/LineBoundsTests.cpp +++ b/Tests/Core/Surfaces/LineBoundsTests.cpp @@ -21,81 +21,77 @@ namespace Acts { namespace Test { - BOOST_AUTO_TEST_SUITE(Surfaces) - /// Unit test for creating compliant/non-compliant LineBounds object - BOOST_AUTO_TEST_CASE(LineBoundsConstruction) - { - /// test default construction - LineBounds defaultConstructedLineBounds; // implicit - BOOST_CHECK_EQUAL(defaultConstructedLineBounds.type(), SurfaceBounds::Line); - /// test LineBounds(double, double) - double radius(0.5), halfz(10.); - BOOST_CHECK_EQUAL(LineBounds(radius, halfz).type(), SurfaceBounds::Line); - // - LineBounds s(1); // would act as size_t cast to LineBounds - /// test copy construction; - LineBounds copyConstructedLineBounds( - defaultConstructedLineBounds); // implicit - BOOST_CHECK_EQUAL(copyConstructedLineBounds.type(), SurfaceBounds::Line); - } +BOOST_AUTO_TEST_SUITE(Surfaces) +/// Unit test for creating compliant/non-compliant LineBounds object +BOOST_AUTO_TEST_CASE(LineBoundsConstruction) { + /// test default construction + LineBounds defaultConstructedLineBounds; // implicit + BOOST_CHECK_EQUAL(defaultConstructedLineBounds.type(), SurfaceBounds::Line); + /// test LineBounds(double, double) + double radius(0.5), halfz(10.); + BOOST_CHECK_EQUAL(LineBounds(radius, halfz).type(), SurfaceBounds::Line); + // + LineBounds s(1); // would act as size_t cast to LineBounds + /// test copy construction; + LineBounds copyConstructedLineBounds( + defaultConstructedLineBounds); // implicit + BOOST_CHECK_EQUAL(copyConstructedLineBounds.type(), SurfaceBounds::Line); +} - /// Unit tests for LineBounds properties - BOOST_AUTO_TEST_CASE_EXPECTED_FAILURES(LineBoundsProperties, 1) - BOOST_AUTO_TEST_CASE(LineBoundsProperties) - { - // LineBounds object of radius 0.5 and halfz 20 - double nominalRadius{0.5}; - double nominalHalfLength{20.}; - LineBounds lineBoundsObject(nominalRadius, nominalHalfLength); +/// Unit tests for LineBounds properties +BOOST_AUTO_TEST_CASE_EXPECTED_FAILURES(LineBoundsProperties, 1) +BOOST_AUTO_TEST_CASE(LineBoundsProperties) { + // LineBounds object of radius 0.5 and halfz 20 + double nominalRadius{0.5}; + double nominalHalfLength{20.}; + LineBounds lineBoundsObject(nominalRadius, nominalHalfLength); - /// test for clone - auto pLineBoundsClone = lineBoundsObject.clone(); - BOOST_CHECK_NE(pLineBoundsClone, nullptr); - delete pLineBoundsClone; + /// test for clone + auto pLineBoundsClone = lineBoundsObject.clone(); + BOOST_CHECK_NE(pLineBoundsClone, nullptr); + delete pLineBoundsClone; - /// test for type() - BOOST_CHECK_EQUAL(lineBoundsObject.type(), SurfaceBounds::Line); + /// test for type() + BOOST_CHECK_EQUAL(lineBoundsObject.type(), SurfaceBounds::Line); - /// test for inside() - const Vector2D origin{0., 0.}; - const Vector2D atRadius{0.5, 10.}; - const Vector2D beyondEnd{0.0, 30.0}; - const Vector2D unitZ{0.0, 1.0}; - const Vector2D unitR{1.0, 0.0}; - const BoundaryCheck trueBoundaryCheckWithTolerance(true, true, 0.1, 0.1); - BOOST_CHECK( - lineBoundsObject.inside(atRadius, trueBoundaryCheckWithTolerance)); + /// test for inside() + const Vector2D origin{0., 0.}; + const Vector2D atRadius{0.5, 10.}; + const Vector2D beyondEnd{0.0, 30.0}; + const Vector2D unitZ{0.0, 1.0}; + const Vector2D unitR{1.0, 0.0}; + const BoundaryCheck trueBoundaryCheckWithTolerance(true, true, 0.1, 0.1); + BOOST_CHECK( + lineBoundsObject.inside(atRadius, trueBoundaryCheckWithTolerance)); - /// test for distanceToBoundary - CHECK_CLOSE_REL(lineBoundsObject.distanceToBoundary(unitR), - 1., - 1e-6); // why? + /// test for distanceToBoundary + CHECK_CLOSE_REL(lineBoundsObject.distanceToBoundary(unitR), 1., + 1e-6); // why? - /// test for r() - BOOST_CHECK_EQUAL(lineBoundsObject.r(), nominalRadius); + /// test for r() + BOOST_CHECK_EQUAL(lineBoundsObject.r(), nominalRadius); - /// test for halflengthZ (NOTE: Naming violation) - BOOST_CHECK_EQUAL(lineBoundsObject.halflengthZ(), nominalHalfLength); + /// test for halflengthZ (NOTE: Naming violation) + BOOST_CHECK_EQUAL(lineBoundsObject.halflengthZ(), nominalHalfLength); - /// test for dump - boost::test_tools::output_test_stream dumpOuput; - lineBoundsObject.toStream(dumpOuput); - BOOST_CHECK(dumpOuput.is_equal( - "Acts::LineBounds: (radius, halflengthInZ) = (0.5000000, 20.0000000)")); - } - /// Unit test for testing LineBounds assignment - BOOST_AUTO_TEST_CASE(LineBoundsAssignment) - { - double nominalRadius{0.5}; - double nominalHalfLength{20.}; - LineBounds lineBoundsObject(nominalRadius, nominalHalfLength); - LineBounds assignedLineBounds; - assignedLineBounds = lineBoundsObject; - BOOST_CHECK_EQUAL(assignedLineBounds.r(), lineBoundsObject.r()); - BOOST_CHECK_EQUAL(assignedLineBounds.halflengthZ(), - lineBoundsObject.halflengthZ()); - } - BOOST_AUTO_TEST_SUITE_END() + /// test for dump + boost::test_tools::output_test_stream dumpOuput; + lineBoundsObject.toStream(dumpOuput); + BOOST_CHECK(dumpOuput.is_equal( + "Acts::LineBounds: (radius, halflengthInZ) = (0.5000000, 20.0000000)")); +} +/// Unit test for testing LineBounds assignment +BOOST_AUTO_TEST_CASE(LineBoundsAssignment) { + double nominalRadius{0.5}; + double nominalHalfLength{20.}; + LineBounds lineBoundsObject(nominalRadius, nominalHalfLength); + LineBounds assignedLineBounds; + assignedLineBounds = lineBoundsObject; + BOOST_CHECK_EQUAL(assignedLineBounds.r(), lineBoundsObject.r()); + BOOST_CHECK_EQUAL(assignedLineBounds.halflengthZ(), + lineBoundsObject.halflengthZ()); +} +BOOST_AUTO_TEST_SUITE_END() } // namespace Test diff --git a/Tests/Core/Surfaces/LineSurfaceTests.cpp b/Tests/Core/Surfaces/LineSurfaceTests.cpp index 7c5f6c604ed75c11016192a148fb928fd22d3ff0..8438513cac44285820154be3c0d4cdfc5c70e0ae 100644 --- a/Tests/Core/Surfaces/LineSurfaceTests.cpp +++ b/Tests/Core/Surfaces/LineSurfaceTests.cpp @@ -29,145 +29,141 @@ namespace Acts { namespace Test { - // Create a test context - GeometryContext tgContext = GeometryContext(); +// Create a test context +GeometryContext tgContext = GeometryContext(); - // using boost::test_tools::output_test_stream; +// using boost::test_tools::output_test_stream; - BOOST_AUTO_TEST_SUITE(Surfaces) - /// Unit test for creating compliant/non-compliant LineSurface object - BOOST_AUTO_TEST_CASE(LineSurface_Constructors_test) - { - // Default ctor is deleted - // LineSurfaceStub l; - // ctor with translation, radius, halfz - Translation3D translation{0., 1., 2.}; - Transform3D transform(translation); - auto pTransform = std::make_shared<const Transform3D>(translation); - const double radius{2.0}, halfz{20.}; - BOOST_CHECK(LineSurfaceStub(pTransform, radius, halfz).constructedOk()); - // ctor with nullptr for LineBounds - BOOST_CHECK(LineSurfaceStub(pTransform).constructedOk()); - // ctor with LineBounds - auto pLineBounds = std::make_shared<const LineBounds>(10.0); - BOOST_CHECK(LineSurfaceStub(pTransform, pLineBounds).constructedOk()); - // ctor with LineBounds, detector element, Identifier - MaterialProperties properties{1., 1., 1., 20., 10, 5.}; - auto pMaterial - = std::make_shared<const HomogeneousSurfaceMaterial>(properties); - DetectorElementStub detElement{pTransform, pLineBounds, 0.2, pMaterial}; - BOOST_CHECK(LineSurfaceStub(pLineBounds, detElement).constructedOk()); - LineSurfaceStub lineToCopy(pTransform, 2.0, 20.); - // Copy ctor - BOOST_CHECK(LineSurfaceStub(lineToCopy).constructedOk()); - // Copied and transformed ctor - BOOST_CHECK( - LineSurfaceStub(tgContext, lineToCopy, transform).constructedOk()); +BOOST_AUTO_TEST_SUITE(Surfaces) +/// Unit test for creating compliant/non-compliant LineSurface object +BOOST_AUTO_TEST_CASE(LineSurface_Constructors_test) { + // Default ctor is deleted + // LineSurfaceStub l; + // ctor with translation, radius, halfz + Translation3D translation{0., 1., 2.}; + Transform3D transform(translation); + auto pTransform = std::make_shared<const Transform3D>(translation); + const double radius{2.0}, halfz{20.}; + BOOST_CHECK(LineSurfaceStub(pTransform, radius, halfz).constructedOk()); + // ctor with nullptr for LineBounds + BOOST_CHECK(LineSurfaceStub(pTransform).constructedOk()); + // ctor with LineBounds + auto pLineBounds = std::make_shared<const LineBounds>(10.0); + BOOST_CHECK(LineSurfaceStub(pTransform, pLineBounds).constructedOk()); + // ctor with LineBounds, detector element, Identifier + MaterialProperties properties{1., 1., 1., 20., 10, 5.}; + auto pMaterial = + std::make_shared<const HomogeneousSurfaceMaterial>(properties); + DetectorElementStub detElement{pTransform, pLineBounds, 0.2, pMaterial}; + BOOST_CHECK(LineSurfaceStub(pLineBounds, detElement).constructedOk()); + LineSurfaceStub lineToCopy(pTransform, 2.0, 20.); + // Copy ctor + BOOST_CHECK(LineSurfaceStub(lineToCopy).constructedOk()); + // Copied and transformed ctor + BOOST_CHECK( + LineSurfaceStub(tgContext, lineToCopy, transform).constructedOk()); - /// Construct with nullptr bounds - DetectorElementStub detElem; - BOOST_CHECK_THROW(LineSurfaceStub nullBounds(nullptr, detElem), - AssertionFailureException); + /// Construct with nullptr bounds + DetectorElementStub detElem; + BOOST_CHECK_THROW(LineSurfaceStub nullBounds(nullptr, detElem), + AssertionFailureException); - BOOST_TEST_MESSAGE( - "All LineSurface constructors are callable without problem"); - } - /// Unit tests of all named methods - BOOST_AUTO_TEST_CASE(LineSurface_allNamedMethods_test) - { - // binningPosition() - Translation3D translation{0., 1., 2.}; - Transform3D transform(translation); - auto pTransform = std::make_shared<const Transform3D>(translation); - LineSurfaceStub line(pTransform, 2.0, 20.); - Vector3D referencePosition{0., 1., 2.}; - CHECK_CLOSE_ABS( - referencePosition, line.binningPosition(tgContext, binX), 1e-6); - // - // bounds() - auto pLineBounds = std::make_shared<const LineBounds>(10.0); - LineSurfaceStub boundedLine(pTransform, pLineBounds); - const LineBounds& bounds - = dynamic_cast<const LineBounds&>(boundedLine.bounds()); - BOOST_CHECK_EQUAL(bounds, LineBounds(10.0)); - // - // globalToLocal() - Vector3D gpos{0., 1., 0.}; - const Vector3D mom{20., 0., 0.}; // needs more realistic parameters - Vector2D localPosition; - BOOST_CHECK(line.globalToLocal(tgContext, gpos, mom, localPosition)); - const Vector2D expectedResult{0, -2}; - CHECK_CLOSE_ABS(expectedResult, localPosition, 1e-6); - // - // intersectionEstimate - const Vector3D direction{0., 1., 2.}; - NavigationDirection navDir = anyDirection; - BoundaryCheck bcheck(false); - auto intersection = line.intersectionEstimate( - tgContext, {0., 0., 0.}, direction.normalized(), navDir, bcheck); - BOOST_CHECK(intersection.valid); - Vector3D expectedIntersection(0, 1., 2.); - CHECK_CLOSE_ABS(intersection.position, - expectedIntersection, - 1e-6); // need more tests.. - // - // isOnSurface - const Vector3D insidePosition{0., 2.5, 0.}; - BOOST_CHECK(line.isOnSurface( - tgContext, insidePosition, mom, false)); // need better test here - const Vector3D outsidePosition{100., 100., 200.}; - BOOST_CHECK(!line.isOnSurface(tgContext, outsidePosition, mom, true)); - // - // localToGlobal - Vector3D returnedGlobalPosition{0., 0., 0.}; - // Vector2D localPosition{0., 0.}; - const Vector3D momentum{300., 200., 0.}; // find better values! - line.localToGlobal( - tgContext, localPosition, momentum, returnedGlobalPosition); - const Vector3D expectedGlobalPosition{0, 1, 0}; - CHECK_CLOSE_ABS(returnedGlobalPosition, expectedGlobalPosition, 1e-6); - // - // referenceFrame - Vector3D globalPosition{0., 0., 0.}; - auto returnedRotationMatrix - = line.referenceFrame(tgContext, globalPosition, momentum); - double v0 = std::cos(std::atan(2. / 3.)); - double v1 = std::sin(std::atan(2. / 3.)); - RotationMatrix3D expectedRotationMatrix; - expectedRotationMatrix << -v1, 0., v0, v0, 0., v1, 0., 1., -0.; - // std::cout<<returnedRotationMatrix<<std::endl; - // std::cout<<expectedRotationMatrix<<std::endl; - CHECK_CLOSE_OR_SMALL( - returnedRotationMatrix, expectedRotationMatrix, 1e-6, 1e-9); - // - // name() - boost::test_tools::output_test_stream output; - output << line.name(); - BOOST_CHECK(output.is_equal("Acts::LineSurface")); - // - // normal - Vector3D normalVector{0., 0., 1.}; // line direction is same as normal???? - CHECK_CLOSE_ABS(line.normal(tgContext), normalVector, 1e-6); - // - // pathCorrection - auto any3DVector = normalVector; - CHECK_CLOSE_REL( - line.pathCorrection(tgContext, any3DVector, any3DVector), 1., 1e-6); - } - /// Unit test for testing LineSurface assignment - BOOST_AUTO_TEST_CASE(LineSurface_assignment_test) - { - Translation3D translation{0., 1., 2.}; - Transform3D transform(translation); - auto pTransform = std::make_shared<const Transform3D>(translation); - LineSurfaceStub originalLine(pTransform, 2.0, 20.); - LineSurfaceStub assignedLine(pTransform, 1.0, 1.0); - BOOST_CHECK(assignedLine != originalLine); // operator != from base - assignedLine = originalLine; - BOOST_CHECK(assignedLine == originalLine); // operator == from base - } + BOOST_TEST_MESSAGE( + "All LineSurface constructors are callable without problem"); +} +/// Unit tests of all named methods +BOOST_AUTO_TEST_CASE(LineSurface_allNamedMethods_test) { + // binningPosition() + Translation3D translation{0., 1., 2.}; + Transform3D transform(translation); + auto pTransform = std::make_shared<const Transform3D>(translation); + LineSurfaceStub line(pTransform, 2.0, 20.); + Vector3D referencePosition{0., 1., 2.}; + CHECK_CLOSE_ABS(referencePosition, line.binningPosition(tgContext, binX), + 1e-6); + // + // bounds() + auto pLineBounds = std::make_shared<const LineBounds>(10.0); + LineSurfaceStub boundedLine(pTransform, pLineBounds); + const LineBounds& bounds = + dynamic_cast<const LineBounds&>(boundedLine.bounds()); + BOOST_CHECK_EQUAL(bounds, LineBounds(10.0)); + // + // globalToLocal() + Vector3D gpos{0., 1., 0.}; + const Vector3D mom{20., 0., 0.}; // needs more realistic parameters + Vector2D localPosition; + BOOST_CHECK(line.globalToLocal(tgContext, gpos, mom, localPosition)); + const Vector2D expectedResult{0, -2}; + CHECK_CLOSE_ABS(expectedResult, localPosition, 1e-6); + // + // intersectionEstimate + const Vector3D direction{0., 1., 2.}; + NavigationDirection navDir = anyDirection; + BoundaryCheck bcheck(false); + auto intersection = line.intersectionEstimate( + tgContext, {0., 0., 0.}, direction.normalized(), navDir, bcheck); + BOOST_CHECK(intersection.valid); + Vector3D expectedIntersection(0, 1., 2.); + CHECK_CLOSE_ABS(intersection.position, expectedIntersection, + 1e-6); // need more tests.. + // + // isOnSurface + const Vector3D insidePosition{0., 2.5, 0.}; + BOOST_CHECK(line.isOnSurface(tgContext, insidePosition, mom, + false)); // need better test here + const Vector3D outsidePosition{100., 100., 200.}; + BOOST_CHECK(!line.isOnSurface(tgContext, outsidePosition, mom, true)); + // + // localToGlobal + Vector3D returnedGlobalPosition{0., 0., 0.}; + // Vector2D localPosition{0., 0.}; + const Vector3D momentum{300., 200., 0.}; // find better values! + line.localToGlobal(tgContext, localPosition, momentum, + returnedGlobalPosition); + const Vector3D expectedGlobalPosition{0, 1, 0}; + CHECK_CLOSE_ABS(returnedGlobalPosition, expectedGlobalPosition, 1e-6); + // + // referenceFrame + Vector3D globalPosition{0., 0., 0.}; + auto returnedRotationMatrix = + line.referenceFrame(tgContext, globalPosition, momentum); + double v0 = std::cos(std::atan(2. / 3.)); + double v1 = std::sin(std::atan(2. / 3.)); + RotationMatrix3D expectedRotationMatrix; + expectedRotationMatrix << -v1, 0., v0, v0, 0., v1, 0., 1., -0.; + // std::cout<<returnedRotationMatrix<<std::endl; + // std::cout<<expectedRotationMatrix<<std::endl; + CHECK_CLOSE_OR_SMALL(returnedRotationMatrix, expectedRotationMatrix, 1e-6, + 1e-9); + // + // name() + boost::test_tools::output_test_stream output; + output << line.name(); + BOOST_CHECK(output.is_equal("Acts::LineSurface")); + // + // normal + Vector3D normalVector{0., 0., 1.}; // line direction is same as normal???? + CHECK_CLOSE_ABS(line.normal(tgContext), normalVector, 1e-6); + // + // pathCorrection + auto any3DVector = normalVector; + CHECK_CLOSE_REL(line.pathCorrection(tgContext, any3DVector, any3DVector), 1., + 1e-6); +} +/// Unit test for testing LineSurface assignment +BOOST_AUTO_TEST_CASE(LineSurface_assignment_test) { + Translation3D translation{0., 1., 2.}; + Transform3D transform(translation); + auto pTransform = std::make_shared<const Transform3D>(translation); + LineSurfaceStub originalLine(pTransform, 2.0, 20.); + LineSurfaceStub assignedLine(pTransform, 1.0, 1.0); + BOOST_CHECK(assignedLine != originalLine); // operator != from base + assignedLine = originalLine; + BOOST_CHECK(assignedLine == originalLine); // operator == from base +} - BOOST_AUTO_TEST_SUITE_END() +BOOST_AUTO_TEST_SUITE_END() } // namespace Test diff --git a/Tests/Core/Surfaces/PerigeeSurfaceTests.cpp b/Tests/Core/Surfaces/PerigeeSurfaceTests.cpp index ea35d7f0acba27cab39c5c60e45a3edcccc4db98..0a4e3fa664f64e2df1c025a3db582cfa03acf766 100644 --- a/Tests/Core/Surfaces/PerigeeSurfaceTests.cpp +++ b/Tests/Core/Surfaces/PerigeeSurfaceTests.cpp @@ -31,85 +31,81 @@ namespace Acts { namespace Test { - // Create a test context - GeometryContext tgContext = GeometryContext(); +// Create a test context +GeometryContext tgContext = GeometryContext(); - BOOST_AUTO_TEST_SUITE(PerigeeSurfaces) - /// Unit test for creating compliant/non-compliant PerigeeSurface object - BOOST_AUTO_TEST_CASE(PerigeeSurfaceConstruction) - { - // PerigeeSurface default constructor is deleted - // - /// Constructor with Vector3D - Vector3D unitXYZ{1., 1., 1.}; - auto perigeeSurfaceObject = Surface::makeShared<PerigeeSurface>(unitXYZ); - BOOST_CHECK_EQUAL(Surface::makeShared<PerigeeSurface>(unitXYZ)->type(), - Surface::Perigee); - // - /// Constructor with transform pointer, null or valid - Translation3D translation{0., 1., 2.}; - auto pTransform = std::make_shared<const Transform3D>(translation); - auto pNullTransform = std::make_shared<const Transform3D>(); - BOOST_CHECK_EQUAL( - Surface::makeShared<PerigeeSurface>(pNullTransform)->type(), - Surface::Perigee); - BOOST_CHECK_EQUAL(Surface::makeShared<PerigeeSurface>(pTransform)->type(), - Surface::Perigee); - // - /// Copy constructor - auto copiedPerigeeSurface - = Surface::makeShared<PerigeeSurface>(*perigeeSurfaceObject); - BOOST_CHECK_EQUAL(copiedPerigeeSurface->type(), Surface::Perigee); - BOOST_CHECK(*copiedPerigeeSurface == *perigeeSurfaceObject); - // - /// Copied and transformed - auto copiedTransformedPerigeeSurface = Surface::makeShared<PerigeeSurface>( - tgContext, *perigeeSurfaceObject, *pTransform); - BOOST_CHECK_EQUAL(copiedTransformedPerigeeSurface->type(), - Surface::Perigee); - } +BOOST_AUTO_TEST_SUITE(PerigeeSurfaces) +/// Unit test for creating compliant/non-compliant PerigeeSurface object +BOOST_AUTO_TEST_CASE(PerigeeSurfaceConstruction) { + // PerigeeSurface default constructor is deleted // - /// Unit test for testing PerigeeSurface properties - BOOST_AUTO_TEST_CASE(PerigeeSurfaceProperties) - { - /// Test clone method - Vector3D unitXYZ{1., 1., 1.}; - auto perigeeSurfaceObject = Surface::makeShared<PerigeeSurface>(unitXYZ); - auto pClonedPerigeeSurface - = perigeeSurfaceObject->clone(tgContext, Transform3D::Identity()); - BOOST_CHECK_EQUAL(pClonedPerigeeSurface->type(), Surface::Perigee); - // - /// Test type (redundant) - BOOST_CHECK_EQUAL(perigeeSurfaceObject->type(), Surface::Perigee); - // - /// Test name - BOOST_CHECK_EQUAL(perigeeSurfaceObject->name(), - std::string("Acts::PerigeeSurface")); - // - /// Test dump - boost::test_tools::output_test_stream dumpOuput; - perigeeSurfaceObject->toStream(tgContext, dumpOuput); - BOOST_CHECK(dumpOuput.is_equal("Acts::PerigeeSurface:\n\ + /// Constructor with Vector3D + Vector3D unitXYZ{1., 1., 1.}; + auto perigeeSurfaceObject = Surface::makeShared<PerigeeSurface>(unitXYZ); + BOOST_CHECK_EQUAL(Surface::makeShared<PerigeeSurface>(unitXYZ)->type(), + Surface::Perigee); + // + /// Constructor with transform pointer, null or valid + Translation3D translation{0., 1., 2.}; + auto pTransform = std::make_shared<const Transform3D>(translation); + auto pNullTransform = std::make_shared<const Transform3D>(); + BOOST_CHECK_EQUAL(Surface::makeShared<PerigeeSurface>(pNullTransform)->type(), + Surface::Perigee); + BOOST_CHECK_EQUAL(Surface::makeShared<PerigeeSurface>(pTransform)->type(), + Surface::Perigee); + // + /// Copy constructor + auto copiedPerigeeSurface = + Surface::makeShared<PerigeeSurface>(*perigeeSurfaceObject); + BOOST_CHECK_EQUAL(copiedPerigeeSurface->type(), Surface::Perigee); + BOOST_CHECK(*copiedPerigeeSurface == *perigeeSurfaceObject); + // + /// Copied and transformed + auto copiedTransformedPerigeeSurface = Surface::makeShared<PerigeeSurface>( + tgContext, *perigeeSurfaceObject, *pTransform); + BOOST_CHECK_EQUAL(copiedTransformedPerigeeSurface->type(), Surface::Perigee); +} +// +/// Unit test for testing PerigeeSurface properties +BOOST_AUTO_TEST_CASE(PerigeeSurfaceProperties) { + /// Test clone method + Vector3D unitXYZ{1., 1., 1.}; + auto perigeeSurfaceObject = Surface::makeShared<PerigeeSurface>(unitXYZ); + auto pClonedPerigeeSurface = + perigeeSurfaceObject->clone(tgContext, Transform3D::Identity()); + BOOST_CHECK_EQUAL(pClonedPerigeeSurface->type(), Surface::Perigee); + // + /// Test type (redundant) + BOOST_CHECK_EQUAL(perigeeSurfaceObject->type(), Surface::Perigee); + // + /// Test name + BOOST_CHECK_EQUAL(perigeeSurfaceObject->name(), + std::string("Acts::PerigeeSurface")); + // + /// Test dump + boost::test_tools::output_test_stream dumpOuput; + perigeeSurfaceObject->toStream(tgContext, dumpOuput); + BOOST_CHECK( + dumpOuput.is_equal("Acts::PerigeeSurface:\n\ Center position (x, y, z) = (1.0000000, 1.0000000, 1.0000000)")); - } +} - BOOST_AUTO_TEST_CASE(EqualityOperators) - { - Vector3D unitXYZ{1., 1., 1.}; - Vector3D invalidPosition{0.0, 0.0, 0.0}; - auto perigeeSurfaceObject = Surface::makeShared<PerigeeSurface>(unitXYZ); - auto perigeeSurfaceObject2 = Surface::makeShared<PerigeeSurface>(unitXYZ); - auto assignedPerigeeSurface - = Surface::makeShared<PerigeeSurface>(invalidPosition); - /// Test equality operator - BOOST_CHECK(*perigeeSurfaceObject == *perigeeSurfaceObject2); - /// Test assignment - *assignedPerigeeSurface = *perigeeSurfaceObject; - /// Test equality of assigned to original - BOOST_CHECK(*assignedPerigeeSurface == *perigeeSurfaceObject); - } +BOOST_AUTO_TEST_CASE(EqualityOperators) { + Vector3D unitXYZ{1., 1., 1.}; + Vector3D invalidPosition{0.0, 0.0, 0.0}; + auto perigeeSurfaceObject = Surface::makeShared<PerigeeSurface>(unitXYZ); + auto perigeeSurfaceObject2 = Surface::makeShared<PerigeeSurface>(unitXYZ); + auto assignedPerigeeSurface = + Surface::makeShared<PerigeeSurface>(invalidPosition); + /// Test equality operator + BOOST_CHECK(*perigeeSurfaceObject == *perigeeSurfaceObject2); + /// Test assignment + *assignedPerigeeSurface = *perigeeSurfaceObject; + /// Test equality of assigned to original + BOOST_CHECK(*assignedPerigeeSurface == *perigeeSurfaceObject); +} - BOOST_AUTO_TEST_SUITE_END() +BOOST_AUTO_TEST_SUITE_END() } // namespace Test diff --git a/Tests/Core/Surfaces/PlaneSurfaceTests.cpp b/Tests/Core/Surfaces/PlaneSurfaceTests.cpp index f9c2135c320c6a87bf73ba7e11535056940252a5..748bcf55318f18f3cd667f95e309825fab003874 100644 --- a/Tests/Core/Surfaces/PlaneSurfaceTests.cpp +++ b/Tests/Core/Surfaces/PlaneSurfaceTests.cpp @@ -31,194 +31,189 @@ namespace Acts { namespace Test { - // Create a test context - GeometryContext tgContext = GeometryContext(); - - BOOST_AUTO_TEST_SUITE(PlaneSurfaces) - /// Unit test for creating compliant/non-compliant PlaneSurface object - BOOST_AUTO_TEST_CASE(PlaneSurfaceConstruction) - { - // PlaneSurface default constructor is deleted - // bounds object, rectangle type - auto rBounds = std::make_shared<const RectangleBounds>(3., 4.); - /// Constructor with transform pointer, null or valid, alpha and symmetry - /// indicator - Translation3D translation{0., 1., 2.}; - auto pTransform = std::make_shared<const Transform3D>(translation); - auto pNullTransform = std::make_shared<const Transform3D>(); - // constructor with nullptr transform - BOOST_CHECK_EQUAL( - Surface::makeShared<PlaneSurface>(pNullTransform, rBounds)->type(), - Surface::Plane); - // constructor with transform - BOOST_CHECK_EQUAL( - Surface::makeShared<PlaneSurface>(pTransform, rBounds)->type(), - Surface::Plane); - /// Copy constructor - auto planeSurfaceObject - = Surface::makeShared<PlaneSurface>(pTransform, rBounds); - auto copiedPlaneSurface - = Surface::makeShared<PlaneSurface>(*planeSurfaceObject); - BOOST_CHECK_EQUAL(copiedPlaneSurface->type(), Surface::Plane); - BOOST_CHECK(*copiedPlaneSurface == *planeSurfaceObject); - // - /// Copied and transformed - auto copiedTransformedPlaneSurface = Surface::makeShared<PlaneSurface>( - tgContext, *planeSurfaceObject, *pTransform); - BOOST_CHECK_EQUAL(copiedTransformedPlaneSurface->type(), Surface::Plane); - - /// Construct with nullptr bounds - DetectorElementStub detElem; - BOOST_CHECK_THROW(auto nullBounds - = Surface::makeShared<PlaneSurface>(nullptr, detElem), - AssertionFailureException); - } +// Create a test context +GeometryContext tgContext = GeometryContext(); + +BOOST_AUTO_TEST_SUITE(PlaneSurfaces) +/// Unit test for creating compliant/non-compliant PlaneSurface object +BOOST_AUTO_TEST_CASE(PlaneSurfaceConstruction) { + // PlaneSurface default constructor is deleted + // bounds object, rectangle type + auto rBounds = std::make_shared<const RectangleBounds>(3., 4.); + /// Constructor with transform pointer, null or valid, alpha and symmetry + /// indicator + Translation3D translation{0., 1., 2.}; + auto pTransform = std::make_shared<const Transform3D>(translation); + auto pNullTransform = std::make_shared<const Transform3D>(); + // constructor with nullptr transform + BOOST_CHECK_EQUAL( + Surface::makeShared<PlaneSurface>(pNullTransform, rBounds)->type(), + Surface::Plane); + // constructor with transform + BOOST_CHECK_EQUAL( + Surface::makeShared<PlaneSurface>(pTransform, rBounds)->type(), + Surface::Plane); + /// Copy constructor + auto planeSurfaceObject = + Surface::makeShared<PlaneSurface>(pTransform, rBounds); + auto copiedPlaneSurface = + Surface::makeShared<PlaneSurface>(*planeSurfaceObject); + BOOST_CHECK_EQUAL(copiedPlaneSurface->type(), Surface::Plane); + BOOST_CHECK(*copiedPlaneSurface == *planeSurfaceObject); // - /// Unit test for testing PlaneSurface properties - BOOST_AUTO_TEST_CASE(PlaneSurfaceProperties) - { - // bounds object, rectangle type - auto rBounds = std::make_shared<const RectangleBounds>(3., 4.); - /// Test clone method - Translation3D translation{0., 1., 2.}; - auto pTransform = std::make_shared<const Transform3D>(translation); - // auto pNullTransform = std::make_shared<const Transform3D>(); - auto planeSurfaceObject - = Surface::makeShared<PlaneSurface>(pTransform, rBounds); - // - auto pClonedPlaneSurface - = planeSurfaceObject->clone(tgContext, Transform3D::Identity()); - BOOST_CHECK_EQUAL(pClonedPlaneSurface->type(), Surface::Plane); - // Test clone method with translation - auto pClonedShiftedPlaneSurface - = planeSurfaceObject->clone(tgContext, *pTransform.get()); - // Does it exist at all in a decent state? - BOOST_CHECK_EQUAL(pClonedShiftedPlaneSurface->type(), Surface::Plane); - // Is it in the right place? - Translation3D translation2{0., 2., 4.}; - auto pTransform2 = std::make_shared<const Transform3D>(translation2); - auto planeSurfaceObject2 - = Surface::makeShared<PlaneSurface>(pTransform2, rBounds); - // these two surfaces should be equivalent now (prematurely testing equality - // also) - BOOST_CHECK(*pClonedShiftedPlaneSurface == *planeSurfaceObject2); - // and, trivially, the shifted cloned surface should be different from the - // original - BOOST_CHECK(*pClonedShiftedPlaneSurface != *planeSurfaceObject); - // - /// Test type (redundant) - BOOST_CHECK_EQUAL(planeSurfaceObject->type(), Surface::Plane); - // - /// Test binningPosition - Vector3D binningPosition{0., 1., 2.}; - BOOST_CHECK_EQUAL( - planeSurfaceObject->binningPosition(tgContext, BinningValue::binX), - binningPosition); - // - /// Test referenceFrame - Vector3D globalPosition{2.0, 2.0, 0.0}; - Vector3D momentum{1.e6, 1.e6, 1.e6}; - RotationMatrix3D expectedFrame; - expectedFrame << 1., 0., 0., 0., 1., 0., 0., 0., 1.; - - CHECK_CLOSE_OR_SMALL( - planeSurfaceObject->referenceFrame(tgContext, globalPosition, momentum), - expectedFrame, - 1e-6, - 1e-9); - // - /// Test normal, given 3D position - Vector3D normal3D(0., 0., 1.); - BOOST_CHECK_EQUAL(planeSurfaceObject->normal(tgContext), normal3D); - // - /// Test bounds - BOOST_CHECK_EQUAL(planeSurfaceObject->bounds().type(), - SurfaceBounds::Rectangle); - - /// Test localToGlobal - Vector2D localPosition{1.5, 1.7}; - planeSurfaceObject->localToGlobal( - tgContext, localPosition, momentum, globalPosition); - // - // expected position is the translated one - Vector3D expectedPosition{ - 1.5 + translation.x(), 1.7 + translation.y(), translation.z()}; - - CHECK_CLOSE_REL(globalPosition, expectedPosition, 1e-2); - // - /// Testing globalToLocal - planeSurfaceObject->globalToLocal( - tgContext, globalPosition, momentum, localPosition); - Vector2D expectedLocalPosition{1.5, 1.7}; - - CHECK_CLOSE_REL(localPosition, expectedLocalPosition, 1e-2); - - /// Test isOnSurface - Vector3D offSurface{0, 1, -2.}; - BOOST_CHECK(planeSurfaceObject->isOnSurface( - tgContext, globalPosition, momentum, true)); - BOOST_CHECK(!planeSurfaceObject->isOnSurface( - tgContext, offSurface, momentum, true)); - // - /// intersectionEstimate - Vector3D direction{0., 0., 1.}; - auto intersect = planeSurfaceObject->intersectionEstimate( - tgContext, offSurface, direction, forward, true); - Intersection expectedIntersect{Vector3D{0, 1, 2}, 4., true, 0}; - BOOST_CHECK(intersect.valid); - BOOST_CHECK_EQUAL(intersect.position, expectedIntersect.position); - BOOST_CHECK_EQUAL(intersect.pathLength, expectedIntersect.pathLength); - BOOST_CHECK_EQUAL(intersect.distance, expectedIntersect.distance); - // - /// Test pathCorrection - // CHECK_CLOSE_REL(planeSurfaceObject->pathCorrection(offSurface, momentum), - // 0.40218866453252877, - // 0.01); - // - /// Test name - BOOST_CHECK_EQUAL(planeSurfaceObject->name(), - std::string("Acts::PlaneSurface")); - // - /// Test dump - // TODO 2017-04-12 msmk: check how to correctly check output - // boost::test_tools::output_test_stream dumpOuput; - // planeSurfaceObject.toStream(dumpOuput); - // BOOST_CHECK(dumpOuput.is_equal( - // "Acts::PlaneSurface\n" - // " Center position (x, y, z) = (0.0000, 1.0000, 2.0000)\n" - // " Rotation: colX = (1.000000, 0.000000, 0.000000)\n" - // " colY = (0.000000, 1.000000, 0.000000)\n" - // " colZ = (0.000000, 0.000000, 1.000000)\n" - // " Bounds : Acts::ConeBounds: (tanAlpha, minZ, maxZ, averagePhi, - // halfPhiSector) = (0.4142136, 0.0000000, inf, 0.0000000, - // 3.1415927)")); - } - - BOOST_AUTO_TEST_CASE(EqualityOperators) - { - // rectangle bounds - auto rBounds = std::make_shared<const RectangleBounds>(3., 4.); - Translation3D translation{0., 1., 2.}; - auto pTransform = std::make_shared<const Transform3D>(translation); - auto planeSurfaceObject - = Surface::makeShared<PlaneSurface>(pTransform, rBounds); - auto planeSurfaceObject2 - = Surface::makeShared<PlaneSurface>(pTransform, rBounds); - // - /// Test equality operator - BOOST_CHECK(*planeSurfaceObject == *planeSurfaceObject2); - // - BOOST_TEST_CHECKPOINT( - "Create and then assign a PlaneSurface object to the existing one"); - /// Test assignment - auto assignedPlaneSurface - = Surface::makeShared<PlaneSurface>(nullptr, nullptr); - *assignedPlaneSurface = *planeSurfaceObject; - /// Test equality of assigned to original - BOOST_CHECK(*assignedPlaneSurface == *planeSurfaceObject); - } - - BOOST_AUTO_TEST_SUITE_END() + /// Copied and transformed + auto copiedTransformedPlaneSurface = Surface::makeShared<PlaneSurface>( + tgContext, *planeSurfaceObject, *pTransform); + BOOST_CHECK_EQUAL(copiedTransformedPlaneSurface->type(), Surface::Plane); + + /// Construct with nullptr bounds + DetectorElementStub detElem; + BOOST_CHECK_THROW( + auto nullBounds = Surface::makeShared<PlaneSurface>(nullptr, detElem), + AssertionFailureException); +} +// +/// Unit test for testing PlaneSurface properties +BOOST_AUTO_TEST_CASE(PlaneSurfaceProperties) { + // bounds object, rectangle type + auto rBounds = std::make_shared<const RectangleBounds>(3., 4.); + /// Test clone method + Translation3D translation{0., 1., 2.}; + auto pTransform = std::make_shared<const Transform3D>(translation); + // auto pNullTransform = std::make_shared<const Transform3D>(); + auto planeSurfaceObject = + Surface::makeShared<PlaneSurface>(pTransform, rBounds); + // + auto pClonedPlaneSurface = + planeSurfaceObject->clone(tgContext, Transform3D::Identity()); + BOOST_CHECK_EQUAL(pClonedPlaneSurface->type(), Surface::Plane); + // Test clone method with translation + auto pClonedShiftedPlaneSurface = + planeSurfaceObject->clone(tgContext, *pTransform.get()); + // Does it exist at all in a decent state? + BOOST_CHECK_EQUAL(pClonedShiftedPlaneSurface->type(), Surface::Plane); + // Is it in the right place? + Translation3D translation2{0., 2., 4.}; + auto pTransform2 = std::make_shared<const Transform3D>(translation2); + auto planeSurfaceObject2 = + Surface::makeShared<PlaneSurface>(pTransform2, rBounds); + // these two surfaces should be equivalent now (prematurely testing equality + // also) + BOOST_CHECK(*pClonedShiftedPlaneSurface == *planeSurfaceObject2); + // and, trivially, the shifted cloned surface should be different from the + // original + BOOST_CHECK(*pClonedShiftedPlaneSurface != *planeSurfaceObject); + // + /// Test type (redundant) + BOOST_CHECK_EQUAL(planeSurfaceObject->type(), Surface::Plane); + // + /// Test binningPosition + Vector3D binningPosition{0., 1., 2.}; + BOOST_CHECK_EQUAL( + planeSurfaceObject->binningPosition(tgContext, BinningValue::binX), + binningPosition); + // + /// Test referenceFrame + Vector3D globalPosition{2.0, 2.0, 0.0}; + Vector3D momentum{1.e6, 1.e6, 1.e6}; + RotationMatrix3D expectedFrame; + expectedFrame << 1., 0., 0., 0., 1., 0., 0., 0., 1.; + + CHECK_CLOSE_OR_SMALL( + planeSurfaceObject->referenceFrame(tgContext, globalPosition, momentum), + expectedFrame, 1e-6, 1e-9); + // + /// Test normal, given 3D position + Vector3D normal3D(0., 0., 1.); + BOOST_CHECK_EQUAL(planeSurfaceObject->normal(tgContext), normal3D); + // + /// Test bounds + BOOST_CHECK_EQUAL(planeSurfaceObject->bounds().type(), + SurfaceBounds::Rectangle); + + /// Test localToGlobal + Vector2D localPosition{1.5, 1.7}; + planeSurfaceObject->localToGlobal(tgContext, localPosition, momentum, + globalPosition); + // + // expected position is the translated one + Vector3D expectedPosition{1.5 + translation.x(), 1.7 + translation.y(), + translation.z()}; + + CHECK_CLOSE_REL(globalPosition, expectedPosition, 1e-2); + // + /// Testing globalToLocal + planeSurfaceObject->globalToLocal(tgContext, globalPosition, momentum, + localPosition); + Vector2D expectedLocalPosition{1.5, 1.7}; + + CHECK_CLOSE_REL(localPosition, expectedLocalPosition, 1e-2); + + /// Test isOnSurface + Vector3D offSurface{0, 1, -2.}; + BOOST_CHECK(planeSurfaceObject->isOnSurface(tgContext, globalPosition, + momentum, true)); + BOOST_CHECK( + !planeSurfaceObject->isOnSurface(tgContext, offSurface, momentum, true)); + // + /// intersectionEstimate + Vector3D direction{0., 0., 1.}; + auto intersect = planeSurfaceObject->intersectionEstimate( + tgContext, offSurface, direction, forward, true); + Intersection expectedIntersect{Vector3D{0, 1, 2}, 4., true, 0}; + BOOST_CHECK(intersect.valid); + BOOST_CHECK_EQUAL(intersect.position, expectedIntersect.position); + BOOST_CHECK_EQUAL(intersect.pathLength, expectedIntersect.pathLength); + BOOST_CHECK_EQUAL(intersect.distance, expectedIntersect.distance); + // + /// Test pathCorrection + // CHECK_CLOSE_REL(planeSurfaceObject->pathCorrection(offSurface, momentum), + // 0.40218866453252877, + // 0.01); + // + /// Test name + BOOST_CHECK_EQUAL(planeSurfaceObject->name(), + std::string("Acts::PlaneSurface")); + // + /// Test dump + // TODO 2017-04-12 msmk: check how to correctly check output + // boost::test_tools::output_test_stream dumpOuput; + // planeSurfaceObject.toStream(dumpOuput); + // BOOST_CHECK(dumpOuput.is_equal( + // "Acts::PlaneSurface\n" + // " Center position (x, y, z) = (0.0000, 1.0000, 2.0000)\n" + // " Rotation: colX = (1.000000, 0.000000, 0.000000)\n" + // " colY = (0.000000, 1.000000, 0.000000)\n" + // " colZ = (0.000000, 0.000000, 1.000000)\n" + // " Bounds : Acts::ConeBounds: (tanAlpha, minZ, maxZ, averagePhi, + // halfPhiSector) = (0.4142136, 0.0000000, inf, 0.0000000, + // 3.1415927)")); +} + +BOOST_AUTO_TEST_CASE(EqualityOperators) { + // rectangle bounds + auto rBounds = std::make_shared<const RectangleBounds>(3., 4.); + Translation3D translation{0., 1., 2.}; + auto pTransform = std::make_shared<const Transform3D>(translation); + auto planeSurfaceObject = + Surface::makeShared<PlaneSurface>(pTransform, rBounds); + auto planeSurfaceObject2 = + Surface::makeShared<PlaneSurface>(pTransform, rBounds); + // + /// Test equality operator + BOOST_CHECK(*planeSurfaceObject == *planeSurfaceObject2); + // + BOOST_TEST_CHECKPOINT( + "Create and then assign a PlaneSurface object to the existing one"); + /// Test assignment + auto assignedPlaneSurface = + Surface::makeShared<PlaneSurface>(nullptr, nullptr); + *assignedPlaneSurface = *planeSurfaceObject; + /// Test equality of assigned to original + BOOST_CHECK(*assignedPlaneSurface == *planeSurfaceObject); +} + +BOOST_AUTO_TEST_SUITE_END() } // namespace Test diff --git a/Tests/Core/Surfaces/RadialBoundsTests.cpp b/Tests/Core/Surfaces/RadialBoundsTests.cpp index 136634012f3956b1c5af5bfd27948d15339d87bf..3c6ba06e550e6ff1c982aeb371e43c951cafb81e 100644 --- a/Tests/Core/Surfaces/RadialBoundsTests.cpp +++ b/Tests/Core/Surfaces/RadialBoundsTests.cpp @@ -23,89 +23,85 @@ namespace Acts { namespace Test { - BOOST_AUTO_TEST_SUITE(Surfaces) - /// Unit tests for RadialBounds constrcuctors - BOOST_AUTO_TEST_CASE(RadialBoundsConstruction) - { - double minRadius(1.0), maxRadius(5.0), halfPhiSector(M_PI / 8.0); - // test default construction - // RadialBounds defaultConstructedRadialBounds; should be deleted - // - /// Test construction with radii and default sector - BOOST_CHECK_EQUAL(RadialBounds(minRadius, maxRadius).type(), - SurfaceBounds::Disc); - // - /// Test construction with radii and sector half angle - BOOST_CHECK_EQUAL(RadialBounds(minRadius, maxRadius, halfPhiSector).type(), - SurfaceBounds::Disc); - // - /// Copy constructor - RadialBounds original(minRadius, maxRadius); - RadialBounds copied(original); - BOOST_CHECK_EQUAL(copied.type(), SurfaceBounds::Disc); - } +BOOST_AUTO_TEST_SUITE(Surfaces) +/// Unit tests for RadialBounds constrcuctors +BOOST_AUTO_TEST_CASE(RadialBoundsConstruction) { + double minRadius(1.0), maxRadius(5.0), halfPhiSector(M_PI / 8.0); + // test default construction + // RadialBounds defaultConstructedRadialBounds; should be deleted + // + /// Test construction with radii and default sector + BOOST_CHECK_EQUAL(RadialBounds(minRadius, maxRadius).type(), + SurfaceBounds::Disc); + // + /// Test construction with radii and sector half angle + BOOST_CHECK_EQUAL(RadialBounds(minRadius, maxRadius, halfPhiSector).type(), + SurfaceBounds::Disc); + // + /// Copy constructor + RadialBounds original(minRadius, maxRadius); + RadialBounds copied(original); + BOOST_CHECK_EQUAL(copied.type(), SurfaceBounds::Disc); +} - /// Unit tests for RadialBounds properties - BOOST_AUTO_TEST_CASE(RadialBoundsProperties) - { - double minRadius(1.0), maxRadius(5.0), halfPhiSector(M_PI / 8.0); - /// Test clone - RadialBounds radialBoundsObject(minRadius, maxRadius, halfPhiSector); - auto pClonedRadialBounds = radialBoundsObject.clone(); - BOOST_CHECK_NE(pClonedRadialBounds, nullptr); - delete pClonedRadialBounds; - // - /// Test type() (redundant; already used in constructor confirmation) - BOOST_CHECK_EQUAL(radialBoundsObject.type(), SurfaceBounds::Disc); - // - /// Test distanceToBoundary - Vector2D origin(0., 0.); - Vector2D outside(30., 0.); - Vector2D inSurface(2., 0.0); - CHECK_CLOSE_REL(radialBoundsObject.distanceToBoundary(origin), - 1., - 1e-6); // makes sense - CHECK_CLOSE_REL(radialBoundsObject.distanceToBoundary(outside), - 25., - 1e-6); // ok - // - /// Test dump - boost::test_tools::output_test_stream dumpOuput; - radialBoundsObject.toStream(dumpOuput); - BOOST_CHECK(dumpOuput.is_equal("Acts::RadialBounds: (innerRadius, " - "outerRadius, hPhiSector) = (1.0000000, " - "5.0000000, 0.0000000, 0.3926991)")); - // - /// Test inside - BOOST_CHECK(radialBoundsObject.inside(inSurface, BoundaryCheck(true))); - BOOST_CHECK(!radialBoundsObject.inside(outside, BoundaryCheck(true))); - // - /// Test rMin - BOOST_CHECK_EQUAL(radialBoundsObject.rMin(), minRadius); - // - /// Test rMax - BOOST_CHECK_EQUAL(radialBoundsObject.rMax(), maxRadius); - // - /// Test averagePhi (should be a redundant method, this is not configurable) - BOOST_CHECK_EQUAL(radialBoundsObject.averagePhi(), 0.0); - // - /// Test halfPhiSector - BOOST_CHECK_EQUAL(radialBoundsObject.halfPhiSector(), halfPhiSector); - } - /// Unit test for testing RadialBounds assignment - BOOST_AUTO_TEST_CASE(RadialBoundsAssignment) - { - double minRadius(1.0), maxRadius(5.0), halfPhiSector(M_PI / 8.0); - RadialBounds radialBoundsObject(minRadius, maxRadius, halfPhiSector); - // operator == not implemented in this class - // - /// Test assignment - RadialBounds assignedRadialBoundsObject(10.1, 123.); - assignedRadialBoundsObject = radialBoundsObject; - BOOST_CHECK_EQUAL(assignedRadialBoundsObject, radialBoundsObject); - } +/// Unit tests for RadialBounds properties +BOOST_AUTO_TEST_CASE(RadialBoundsProperties) { + double minRadius(1.0), maxRadius(5.0), halfPhiSector(M_PI / 8.0); + /// Test clone + RadialBounds radialBoundsObject(minRadius, maxRadius, halfPhiSector); + auto pClonedRadialBounds = radialBoundsObject.clone(); + BOOST_CHECK_NE(pClonedRadialBounds, nullptr); + delete pClonedRadialBounds; + // + /// Test type() (redundant; already used in constructor confirmation) + BOOST_CHECK_EQUAL(radialBoundsObject.type(), SurfaceBounds::Disc); + // + /// Test distanceToBoundary + Vector2D origin(0., 0.); + Vector2D outside(30., 0.); + Vector2D inSurface(2., 0.0); + CHECK_CLOSE_REL(radialBoundsObject.distanceToBoundary(origin), 1., + 1e-6); // makes sense + CHECK_CLOSE_REL(radialBoundsObject.distanceToBoundary(outside), 25., + 1e-6); // ok + // + /// Test dump + boost::test_tools::output_test_stream dumpOuput; + radialBoundsObject.toStream(dumpOuput); + BOOST_CHECK( + dumpOuput.is_equal("Acts::RadialBounds: (innerRadius, " + "outerRadius, hPhiSector) = (1.0000000, " + "5.0000000, 0.0000000, 0.3926991)")); + // + /// Test inside + BOOST_CHECK(radialBoundsObject.inside(inSurface, BoundaryCheck(true))); + BOOST_CHECK(!radialBoundsObject.inside(outside, BoundaryCheck(true))); + // + /// Test rMin + BOOST_CHECK_EQUAL(radialBoundsObject.rMin(), minRadius); + // + /// Test rMax + BOOST_CHECK_EQUAL(radialBoundsObject.rMax(), maxRadius); + // + /// Test averagePhi (should be a redundant method, this is not configurable) + BOOST_CHECK_EQUAL(radialBoundsObject.averagePhi(), 0.0); + // + /// Test halfPhiSector + BOOST_CHECK_EQUAL(radialBoundsObject.halfPhiSector(), halfPhiSector); +} +/// Unit test for testing RadialBounds assignment +BOOST_AUTO_TEST_CASE(RadialBoundsAssignment) { + double minRadius(1.0), maxRadius(5.0), halfPhiSector(M_PI / 8.0); + RadialBounds radialBoundsObject(minRadius, maxRadius, halfPhiSector); + // operator == not implemented in this class + // + /// Test assignment + RadialBounds assignedRadialBoundsObject(10.1, 123.); + assignedRadialBoundsObject = radialBoundsObject; + BOOST_CHECK_EQUAL(assignedRadialBoundsObject, radialBoundsObject); +} - BOOST_AUTO_TEST_SUITE_END() +BOOST_AUTO_TEST_SUITE_END() } // namespace Test diff --git a/Tests/Core/Surfaces/RectangleBoundsTests.cpp b/Tests/Core/Surfaces/RectangleBoundsTests.cpp index d0631a075e694b9e23e2882d77d5c0e486aed104..b6638789886dcbfab03f69bf7f6a7a8bd28368b0 100644 --- a/Tests/Core/Surfaces/RectangleBoundsTests.cpp +++ b/Tests/Core/Surfaces/RectangleBoundsTests.cpp @@ -22,121 +22,109 @@ #include "Acts/Tests/CommonHelpers/FloatComparisons.hpp" #include "Acts/Utilities/Definitions.hpp" -namespace utf = boost::unit_test; +namespace utf = boost::unit_test; const double inf = std::numeric_limits<double>::infinity(); const double NaN = std::numeric_limits<double>::quiet_NaN(); namespace Acts { namespace Test { - void - dumpVertices(const RectangleBounds& r) - { - const auto& v = r.vertices(); - for (const auto& i : v) { - std::cout << "(" << i[0] << ", " << i[1] << ")" << std::endl; - } - } - bool - approximatelyEqual(const Vector2D& a, const Vector2D& b) - { - const double dif0 = std::abs(a[0] - b[0]); - const double dif1 = std::abs(a[1] - b[1]); - const double tol = 1e-9; - return ((dif0 < tol) and (dif1 < tol)); - } - BOOST_AUTO_TEST_SUITE(Surfaces) - /// Unit test for creating compliant/non-compliant RectangleBounds object - BOOST_AUTO_TEST_CASE(RectangleBoundsConstruction) - { - const double halfX(10.), halfY(5.); - RectangleBounds twentyByTenRectangle(halfX, halfY); - BOOST_CHECK_EQUAL(twentyByTenRectangle.type(), - Acts::SurfaceBounds::Rectangle); - // - // nonsensical bounds are also permitted, but maybe should not be - const double zeroHalfX(0.), zeroHalfY(0.); - const double infHalfX(inf), infHalfY(inf); - const double nanHalfX(NaN), nanHalfY(NaN); - const double negHalfX(-10.), negHalfY(-5.); - // - // BOOST_TEST_MESSAGE("Initialise with zero dimensions"); - RectangleBounds zeroDimensionsRectangle(zeroHalfX, zeroHalfY); - BOOST_CHECK_EQUAL(zeroDimensionsRectangle.type(), - Acts::SurfaceBounds::Rectangle); - // - // BOOST_TEST_MESSAGE("Initialise with infinite dimensions"); - RectangleBounds infinite(infHalfX, infHalfY); - BOOST_CHECK_EQUAL(infinite.type(), Acts::SurfaceBounds::Rectangle); - // - // BOOST_TEST_MESSAGE("Initialise with NaN dimensions"); - RectangleBounds nanRectangle(nanHalfX, nanHalfY); - BOOST_CHECK_EQUAL(nanRectangle.type(), Acts::SurfaceBounds::Rectangle); - // - // BOOST_TEST_MESSAGE("Initialise with negative dimensions"); - RectangleBounds negativeDimensionedRectangle(negHalfX, negHalfY); - BOOST_CHECK_EQUAL(negativeDimensionedRectangle.type(), - Acts::SurfaceBounds::Rectangle); +void dumpVertices(const RectangleBounds& r) { + const auto& v = r.vertices(); + for (const auto& i : v) { + std::cout << "(" << i[0] << ", " << i[1] << ")" << std::endl; } +} +bool approximatelyEqual(const Vector2D& a, const Vector2D& b) { + const double dif0 = std::abs(a[0] - b[0]); + const double dif1 = std::abs(a[1] - b[1]); + const double tol = 1e-9; + return ((dif0 < tol) and (dif1 < tol)); +} +BOOST_AUTO_TEST_SUITE(Surfaces) +/// Unit test for creating compliant/non-compliant RectangleBounds object +BOOST_AUTO_TEST_CASE(RectangleBoundsConstruction) { + const double halfX(10.), halfY(5.); + RectangleBounds twentyByTenRectangle(halfX, halfY); + BOOST_CHECK_EQUAL(twentyByTenRectangle.type(), + Acts::SurfaceBounds::Rectangle); + // + // nonsensical bounds are also permitted, but maybe should not be + const double zeroHalfX(0.), zeroHalfY(0.); + const double infHalfX(inf), infHalfY(inf); + const double nanHalfX(NaN), nanHalfY(NaN); + const double negHalfX(-10.), negHalfY(-5.); + // + // BOOST_TEST_MESSAGE("Initialise with zero dimensions"); + RectangleBounds zeroDimensionsRectangle(zeroHalfX, zeroHalfY); + BOOST_CHECK_EQUAL(zeroDimensionsRectangle.type(), + Acts::SurfaceBounds::Rectangle); + // + // BOOST_TEST_MESSAGE("Initialise with infinite dimensions"); + RectangleBounds infinite(infHalfX, infHalfY); + BOOST_CHECK_EQUAL(infinite.type(), Acts::SurfaceBounds::Rectangle); + // + // BOOST_TEST_MESSAGE("Initialise with NaN dimensions"); + RectangleBounds nanRectangle(nanHalfX, nanHalfY); + BOOST_CHECK_EQUAL(nanRectangle.type(), Acts::SurfaceBounds::Rectangle); + // + // BOOST_TEST_MESSAGE("Initialise with negative dimensions"); + RectangleBounds negativeDimensionedRectangle(negHalfX, negHalfY); + BOOST_CHECK_EQUAL(negativeDimensionedRectangle.type(), + Acts::SurfaceBounds::Rectangle); +} - /// Unit test for testing RectangleBounds properties - BOOST_TEST_DECORATOR(*utf::tolerance(1e-10)) - BOOST_AUTO_TEST_CASE(RectangleBoundsProperties) - { - const double halfX(10.), halfY(5.); - RectangleBounds rect(halfX, halfY); - BOOST_CHECK_EQUAL(rect.halflengthX(), 10.); - BOOST_CHECK_EQUAL(rect.halflengthY(), 5.); +/// Unit test for testing RectangleBounds properties +BOOST_TEST_DECORATOR(*utf::tolerance(1e-10)) +BOOST_AUTO_TEST_CASE(RectangleBoundsProperties) { + const double halfX(10.), halfY(5.); + RectangleBounds rect(halfX, halfY); + BOOST_CHECK_EQUAL(rect.halflengthX(), 10.); + BOOST_CHECK_EQUAL(rect.halflengthY(), 5.); - CHECK_CLOSE_ABS(rect.min(), Vector2D(-halfX, -halfY), 1e-6); - CHECK_CLOSE_ABS(rect.max(), Vector2D(halfX, halfY), 1e-6); + CHECK_CLOSE_ABS(rect.min(), Vector2D(-halfX, -halfY), 1e-6); + CHECK_CLOSE_ABS(rect.max(), Vector2D(halfX, halfY), 1e-6); - const std::vector<Vector2D> coords - = {{10., -5.}, {10., 5.}, {-10., 5.}, {-10., -5.}}; - // equality, ensure ordering is ok - const auto& rectVertices = rect.vertices(); - BOOST_CHECK_EQUAL_COLLECTIONS(coords.cbegin(), - coords.cend(), - rectVertices.cbegin(), - rectVertices.cend()); - const Vector2D pointA{1.0, 1.0}, pointB{9.0, 1.0}, outside{10.1, 5.1}; - // distance is signed, from boundary to point. (doesn't seem right, given - // the name of the method) - CHECK_CLOSE_REL(rect.distanceToBoundary(pointA), -4.0, 1e-6); - CHECK_CLOSE_REL(rect.distanceToBoundary(pointB), -1.0, 1e-6); - BoundaryCheck bcheck(true, true); - BOOST_CHECK(rect.inside(pointA, bcheck)); - } - BOOST_AUTO_TEST_CASE(RectangleBoundsAssignment) - { - const double halfX(10.), halfY(2.); - RectangleBounds rectA(halfX, halfY); - RectangleBounds rectB(0.0, 0.0); - rectB = rectA; - const auto originalVertices = rectA.vertices(); - const auto assignedVertices = rectB.vertices(); - BOOST_CHECK_EQUAL_COLLECTIONS(originalVertices.cbegin(), - originalVertices.cend(), - assignedVertices.cbegin(), - assignedVertices.cend()); - } + const std::vector<Vector2D> coords = { + {10., -5.}, {10., 5.}, {-10., 5.}, {-10., -5.}}; + // equality, ensure ordering is ok + const auto& rectVertices = rect.vertices(); + BOOST_CHECK_EQUAL_COLLECTIONS(coords.cbegin(), coords.cend(), + rectVertices.cbegin(), rectVertices.cend()); + const Vector2D pointA{1.0, 1.0}, pointB{9.0, 1.0}, outside{10.1, 5.1}; + // distance is signed, from boundary to point. (doesn't seem right, given + // the name of the method) + CHECK_CLOSE_REL(rect.distanceToBoundary(pointA), -4.0, 1e-6); + CHECK_CLOSE_REL(rect.distanceToBoundary(pointB), -1.0, 1e-6); + BoundaryCheck bcheck(true, true); + BOOST_CHECK(rect.inside(pointA, bcheck)); +} +BOOST_AUTO_TEST_CASE(RectangleBoundsAssignment) { + const double halfX(10.), halfY(2.); + RectangleBounds rectA(halfX, halfY); + RectangleBounds rectB(0.0, 0.0); + rectB = rectA; + const auto originalVertices = rectA.vertices(); + const auto assignedVertices = rectB.vertices(); + BOOST_CHECK_EQUAL_COLLECTIONS( + originalVertices.cbegin(), originalVertices.cend(), + assignedVertices.cbegin(), assignedVertices.cend()); +} - BOOST_AUTO_TEST_CASE(RectangleBoundsClone) - { - const double halfX(10.), halfY(5.); - RectangleBounds rectA(halfX, halfY); - auto rectB = rectA.clone(); - BOOST_CHECK_NE(rectB, nullptr); - const auto& originalVertices = rectA.vertices(); - const auto& clonedVertices = rectB->vertices(); - BOOST_CHECK_EQUAL_COLLECTIONS(originalVertices.cbegin(), - originalVertices.cend(), - clonedVertices.cbegin(), - clonedVertices.cend()); - delete rectB; - } +BOOST_AUTO_TEST_CASE(RectangleBoundsClone) { + const double halfX(10.), halfY(5.); + RectangleBounds rectA(halfX, halfY); + auto rectB = rectA.clone(); + BOOST_CHECK_NE(rectB, nullptr); + const auto& originalVertices = rectA.vertices(); + const auto& clonedVertices = rectB->vertices(); + BOOST_CHECK_EQUAL_COLLECTIONS(originalVertices.cbegin(), + originalVertices.cend(), + clonedVertices.cbegin(), clonedVertices.cend()); + delete rectB; +} - BOOST_AUTO_TEST_SUITE_END() +BOOST_AUTO_TEST_SUITE_END() } // namespace Test } // namespace Acts diff --git a/Tests/Core/Surfaces/StrawSurfaceTests.cpp b/Tests/Core/Surfaces/StrawSurfaceTests.cpp index ab614c877472f52ab7b79a2ec41a87c21246ac1d..44c198852a1054849f7f3da12b5699fe91fd4d1e 100644 --- a/Tests/Core/Surfaces/StrawSurfaceTests.cpp +++ b/Tests/Core/Surfaces/StrawSurfaceTests.cpp @@ -33,114 +33,111 @@ namespace Acts { namespace Test { - // Create a test context - GeometryContext tgContext = GeometryContext(); +// Create a test context +GeometryContext tgContext = GeometryContext(); - BOOST_AUTO_TEST_SUITE(StrawSurfaces) - /// Unit test for creating compliant/non-compliant StrawSurface object - BOOST_AUTO_TEST_CASE(StrawSurfaceConstruction) - { - // StrawSurface default constructor is deleted - // - /// Constructor with transform pointer, null or valid, radius and halfZ - double radius(1.0), halfZ(10.); - Translation3D translation{0., 1., 2.}; - auto pTransform = std::make_shared<const Transform3D>(translation); - auto pNullTransform = std::make_shared<const Transform3D>(); - BOOST_CHECK_EQUAL( - Surface::makeShared<StrawSurface>(pNullTransform, radius, halfZ) - ->type(), - Surface::Straw); - BOOST_CHECK_EQUAL( - Surface::makeShared<StrawSurface>(pTransform, radius, halfZ)->type(), - Surface::Straw); - // - /// Constructor with transform and LineBounds pointer - auto pLineBounds = std::make_shared<const LineBounds>(radius, halfZ); - BOOST_CHECK_EQUAL( - Surface::makeShared<StrawSurface>(pTransform, pLineBounds)->type(), - Surface::Straw); - // - /// Constructor with LineBounds ptr, DetectorElement - std::shared_ptr<const Acts::PlanarBounds> p - = std::make_shared<const RectangleBounds>(1., 10.); - DetectorElementStub detElement{pTransform, p, 1.0, nullptr}; - BOOST_CHECK_EQUAL( - Surface::makeShared<StrawSurface>(pLineBounds, detElement)->type(), - Surface::Straw); - // - /// Copy constructor - auto strawSurfaceObject - = Surface::makeShared<StrawSurface>(pTransform, radius, halfZ); - auto copiedStrawSurface - = Surface::makeShared<StrawSurface>(*strawSurfaceObject); - BOOST_CHECK_EQUAL(copiedStrawSurface->type(), Surface::Straw); - BOOST_CHECK(*copiedStrawSurface == *strawSurfaceObject); - // - /// Copied and transformed - auto copiedTransformedStrawSurface = Surface::makeShared<StrawSurface>( - tgContext, *strawSurfaceObject, *pTransform); - BOOST_CHECK_EQUAL(copiedTransformedStrawSurface->type(), Surface::Straw); - } +BOOST_AUTO_TEST_SUITE(StrawSurfaces) +/// Unit test for creating compliant/non-compliant StrawSurface object +BOOST_AUTO_TEST_CASE(StrawSurfaceConstruction) { + // StrawSurface default constructor is deleted // - /// Unit test for testing StrawSurface properties - BOOST_AUTO_TEST_CASE(StrawSurfaceProperties) - { - /// Test clone method - double radius(1.0), halfZ(10.); - Translation3D translation{0., 1., 2.}; - auto pTransform = std::make_shared<const Transform3D>(translation); - // auto pNullTransform = std::make_shared<const Transform3D>(); - auto strawSurfaceObject - = Surface::makeShared<StrawSurface>(pTransform, radius, halfZ); - // - auto pClonedStrawSurface - = strawSurfaceObject->clone(tgContext, Transform3D::Identity()); - BOOST_CHECK_EQUAL(pClonedStrawSurface->type(), Surface::Straw); - // - /// Test type (redundant) - BOOST_CHECK_EQUAL(strawSurfaceObject->type(), Surface::Straw); - // - /// Test name - BOOST_CHECK_EQUAL(strawSurfaceObject->name(), - std::string("Acts::StrawSurface")); - // - /// Test dump - boost::test_tools::output_test_stream dumpOuput; - strawSurfaceObject->toStream(tgContext, dumpOuput); - BOOST_CHECK(dumpOuput.is_equal("Acts::StrawSurface\n\ + /// Constructor with transform pointer, null or valid, radius and halfZ + double radius(1.0), halfZ(10.); + Translation3D translation{0., 1., 2.}; + auto pTransform = std::make_shared<const Transform3D>(translation); + auto pNullTransform = std::make_shared<const Transform3D>(); + BOOST_CHECK_EQUAL( + Surface::makeShared<StrawSurface>(pNullTransform, radius, halfZ)->type(), + Surface::Straw); + BOOST_CHECK_EQUAL( + Surface::makeShared<StrawSurface>(pTransform, radius, halfZ)->type(), + Surface::Straw); + // + /// Constructor with transform and LineBounds pointer + auto pLineBounds = std::make_shared<const LineBounds>(radius, halfZ); + BOOST_CHECK_EQUAL( + Surface::makeShared<StrawSurface>(pTransform, pLineBounds)->type(), + Surface::Straw); + // + /// Constructor with LineBounds ptr, DetectorElement + std::shared_ptr<const Acts::PlanarBounds> p = + std::make_shared<const RectangleBounds>(1., 10.); + DetectorElementStub detElement{pTransform, p, 1.0, nullptr}; + BOOST_CHECK_EQUAL( + Surface::makeShared<StrawSurface>(pLineBounds, detElement)->type(), + Surface::Straw); + // + /// Copy constructor + auto strawSurfaceObject = + Surface::makeShared<StrawSurface>(pTransform, radius, halfZ); + auto copiedStrawSurface = + Surface::makeShared<StrawSurface>(*strawSurfaceObject); + BOOST_CHECK_EQUAL(copiedStrawSurface->type(), Surface::Straw); + BOOST_CHECK(*copiedStrawSurface == *strawSurfaceObject); + // + /// Copied and transformed + auto copiedTransformedStrawSurface = Surface::makeShared<StrawSurface>( + tgContext, *strawSurfaceObject, *pTransform); + BOOST_CHECK_EQUAL(copiedTransformedStrawSurface->type(), Surface::Straw); +} +// +/// Unit test for testing StrawSurface properties +BOOST_AUTO_TEST_CASE(StrawSurfaceProperties) { + /// Test clone method + double radius(1.0), halfZ(10.); + Translation3D translation{0., 1., 2.}; + auto pTransform = std::make_shared<const Transform3D>(translation); + // auto pNullTransform = std::make_shared<const Transform3D>(); + auto strawSurfaceObject = + Surface::makeShared<StrawSurface>(pTransform, radius, halfZ); + // + auto pClonedStrawSurface = + strawSurfaceObject->clone(tgContext, Transform3D::Identity()); + BOOST_CHECK_EQUAL(pClonedStrawSurface->type(), Surface::Straw); + // + /// Test type (redundant) + BOOST_CHECK_EQUAL(strawSurfaceObject->type(), Surface::Straw); + // + /// Test name + BOOST_CHECK_EQUAL(strawSurfaceObject->name(), + std::string("Acts::StrawSurface")); + // + /// Test dump + boost::test_tools::output_test_stream dumpOuput; + strawSurfaceObject->toStream(tgContext, dumpOuput); + BOOST_CHECK( + dumpOuput.is_equal("Acts::StrawSurface\n\ Center position (x, y, z) = (0.0000, 1.0000, 2.0000)\n\ Rotation: colX = (1.000000, 0.000000, 0.000000)\n\ colY = (0.000000, 1.000000, 0.000000)\n\ colZ = (0.000000, 0.000000, 1.000000)\n\ Bounds : Acts::LineBounds: (radius, halflengthInZ) = (1.0000000, 10.0000000)")); - } +} - BOOST_AUTO_TEST_CASE(EqualityOperators) - { - double radius(1.0), halfZ(10.); - Translation3D translation{0., 1., 2.}; - auto pTransform = std::make_shared<const Transform3D>(translation); - auto strawSurfaceObject - = Surface::makeShared<StrawSurface>(pTransform, radius, halfZ); - // - auto strawSurfaceObject2 - = Surface::makeShared<StrawSurface>(pTransform, radius, halfZ); - // - /// Test equality operator - BOOST_CHECK(*strawSurfaceObject == *strawSurfaceObject2); - // - BOOST_TEST_CHECKPOINT( - "Create and then assign a StrawSurface object to the existing one"); - /// Test assignment - auto assignedStrawSurface - = Surface::makeShared<StrawSurface>(nullptr, 6.6, 33.33); - *assignedStrawSurface = *strawSurfaceObject; - /// Test equality of assigned to original - BOOST_CHECK(*assignedStrawSurface == *strawSurfaceObject); - } +BOOST_AUTO_TEST_CASE(EqualityOperators) { + double radius(1.0), halfZ(10.); + Translation3D translation{0., 1., 2.}; + auto pTransform = std::make_shared<const Transform3D>(translation); + auto strawSurfaceObject = + Surface::makeShared<StrawSurface>(pTransform, radius, halfZ); + // + auto strawSurfaceObject2 = + Surface::makeShared<StrawSurface>(pTransform, radius, halfZ); + // + /// Test equality operator + BOOST_CHECK(*strawSurfaceObject == *strawSurfaceObject2); + // + BOOST_TEST_CHECKPOINT( + "Create and then assign a StrawSurface object to the existing one"); + /// Test assignment + auto assignedStrawSurface = + Surface::makeShared<StrawSurface>(nullptr, 6.6, 33.33); + *assignedStrawSurface = *strawSurfaceObject; + /// Test equality of assigned to original + BOOST_CHECK(*assignedStrawSurface == *strawSurfaceObject); +} - BOOST_AUTO_TEST_SUITE_END() +BOOST_AUTO_TEST_SUITE_END() } // namespace Test diff --git a/Tests/Core/Surfaces/SurfaceArrayTests.cpp b/Tests/Core/Surfaces/SurfaceArrayTests.cpp index 9e4951d30ea841b0e87566ef85225cb03070826f..b7b22b2804696cc6e13b4577e9b79e94f9e24f92 100644 --- a/Tests/Core/Surfaces/SurfaceArrayTests.cpp +++ b/Tests/Core/Surfaces/SurfaceArrayTests.cpp @@ -29,268 +29,236 @@ #include <fstream> -using Acts::VectorHelpers::phi; using Acts::VectorHelpers::perp; +using Acts::VectorHelpers::phi; namespace bdata = boost::unit_test::data; -namespace tt = boost::test_tools; +namespace tt = boost::test_tools; namespace Acts { namespace Test { - // Create a test context - GeometryContext tgContext = GeometryContext(); +// Create a test context +GeometryContext tgContext = GeometryContext(); - using SrfVec = std::vector<std::shared_ptr<const Surface>>; - struct SurfaceArrayFixture - { - std::vector<std::shared_ptr<const Surface>> m_surfaces; +using SrfVec = std::vector<std::shared_ptr<const Surface>>; +struct SurfaceArrayFixture { + std::vector<std::shared_ptr<const Surface>> m_surfaces; - SurfaceArrayFixture() { BOOST_TEST_MESSAGE("setup fixture"); } - ~SurfaceArrayFixture() { BOOST_TEST_MESSAGE("teardown fixture"); } + SurfaceArrayFixture() { BOOST_TEST_MESSAGE("setup fixture"); } + ~SurfaceArrayFixture() { BOOST_TEST_MESSAGE("teardown fixture"); } - SrfVec - fullPhiTestSurfacesEC(size_t n = 10, - double shift = 0, - double zbase = 0, - double r = 10) - { + SrfVec fullPhiTestSurfacesEC(size_t n = 10, double shift = 0, + double zbase = 0, double r = 10) { + SrfVec res; - SrfVec res; + double phiStep = 2 * M_PI / n; + for (size_t i = 0; i < n; ++i) { + double z = zbase + ((i % 2 == 0) ? 1 : -1) * 0.2; - double phiStep = 2 * M_PI / n; - for (size_t i = 0; i < n; ++i) { + Transform3D trans; + trans.setIdentity(); + trans.rotate(Eigen::AngleAxisd(i * phiStep + shift, Vector3D(0, 0, 1))); + trans.translate(Vector3D(r, 0, z)); - double z = zbase + ((i % 2 == 0) ? 1 : -1) * 0.2; + auto bounds = std::make_shared<const RectangleBounds>(2, 1); - Transform3D trans; - trans.setIdentity(); - trans.rotate(Eigen::AngleAxisd(i * phiStep + shift, Vector3D(0, 0, 1))); - trans.translate(Vector3D(r, 0, z)); + auto transptr = std::make_shared<const Transform3D>(trans); + std::shared_ptr<const Surface> srf = + Surface::makeShared<PlaneSurface>(transptr, bounds); - auto bounds = std::make_shared<const RectangleBounds>(2, 1); + res.push_back(srf); + m_surfaces.push_back( + std::move(srf)); // keep shared, will get destroyed at the end + } - auto transptr = std::make_shared<const Transform3D>(trans); - std::shared_ptr<const Surface> srf - = Surface::makeShared<PlaneSurface>(transptr, bounds); + return res; + } - res.push_back(srf); - m_surfaces.push_back( - std::move(srf)); // keep shared, will get destroyed at the end - } + SrfVec fullPhiTestSurfacesBRL(int n = 10, double shift = 0, double zbase = 0, + double incl = M_PI / 9., double w = 2, + double h = 1.5) { + SrfVec res; - return res; - } + double phiStep = 2 * M_PI / n; + for (int i = 0; i < n; ++i) { + double z = zbase; - SrfVec - fullPhiTestSurfacesBRL(int n = 10, - double shift = 0, - double zbase = 0, - double incl = M_PI / 9., - double w = 2, - double h = 1.5) - { + Transform3D trans; + trans.setIdentity(); + trans.rotate(Eigen::AngleAxisd(i * phiStep + shift, Vector3D(0, 0, 1))); + trans.translate(Vector3D(10, 0, z)); + trans.rotate(Eigen::AngleAxisd(incl, Vector3D(0, 0, 1))); + trans.rotate(Eigen::AngleAxisd(M_PI / 2., Vector3D(0, 1, 0))); - SrfVec res; + auto bounds = std::make_shared<const RectangleBounds>(w, h); - double phiStep = 2 * M_PI / n; - for (int i = 0; i < n; ++i) { + auto transptr = std::make_shared<const Transform3D>(trans); + std::shared_ptr<const Surface> srf = + Surface::makeShared<PlaneSurface>(transptr, bounds); - double z = zbase; + res.push_back(srf); + m_surfaces.push_back( + std::move(srf)); // keep shared, will get destroyed at the end + } - Transform3D trans; - trans.setIdentity(); - trans.rotate(Eigen::AngleAxisd(i * phiStep + shift, Vector3D(0, 0, 1))); - trans.translate(Vector3D(10, 0, z)); - trans.rotate(Eigen::AngleAxisd(incl, Vector3D(0, 0, 1))); - trans.rotate(Eigen::AngleAxisd(M_PI / 2., Vector3D(0, 1, 0))); + return res; + } - auto bounds = std::make_shared<const RectangleBounds>(w, h); + SrfVec straightLineSurfaces( + size_t n = 10., double step = 3, const Vector3D& origin = {0, 0, 1.5}, + const Transform3D& pretrans = Transform3D::Identity(), + const Vector3D& dir = {0, 0, 1}) { + SrfVec res; + for (size_t i = 0; i < n; ++i) { + Transform3D trans; + trans.setIdentity(); + trans.translate(origin + dir * step * i); + // trans.rotate(AngleAxis3D(M_PI/9., Vector3D(0, 0, 1))); + trans.rotate(AngleAxis3D(M_PI / 2., Vector3D(1, 0, 0))); + trans = trans * pretrans; + + auto bounds = std::make_shared<const RectangleBounds>(2, 1.5); + + auto transptr = std::make_shared<const Transform3D>(trans); + std::shared_ptr<const Surface> srf = + Surface::makeShared<PlaneSurface>(transptr, bounds); + + res.push_back(srf); + m_surfaces.push_back( + std::move(srf)); // keep shared, will get destroyed at the end + } - auto transptr = std::make_shared<const Transform3D>(trans); - std::shared_ptr<const Surface> srf - = Surface::makeShared<PlaneSurface>(transptr, bounds); + return res; + } - res.push_back(srf); - m_surfaces.push_back( - std::move(srf)); // keep shared, will get destroyed at the end - } + SrfVec makeBarrel(int nPhi, int nZ, double w, double h) { + double z0 = -(nZ - 1) * w; + SrfVec res; - return res; + for (int i = 0; i < nZ; i++) { + double z = i * w * 2 + z0; + // std::cout << "z=" << z << std::endl; + SrfVec ring = fullPhiTestSurfacesBRL(nPhi, 0, z, M_PI / 9., w, h); + res.insert(res.end(), ring.begin(), ring.end()); } - SrfVec - straightLineSurfaces(size_t n = 10., - double step = 3, - const Vector3D& origin = {0, 0, 1.5}, - const Transform3D& pretrans = Transform3D::Identity(), - const Vector3D& dir = {0, 0, 1}) - { - SrfVec res; - for (size_t i = 0; i < n; ++i) { - Transform3D trans; - trans.setIdentity(); - trans.translate(origin + dir * step * i); - // trans.rotate(AngleAxis3D(M_PI/9., Vector3D(0, 0, 1))); - trans.rotate(AngleAxis3D(M_PI / 2., Vector3D(1, 0, 0))); - trans = trans * pretrans; - - auto bounds = std::make_shared<const RectangleBounds>(2, 1.5); - - auto transptr = std::make_shared<const Transform3D>(trans); - std::shared_ptr<const Surface> srf - = Surface::makeShared<PlaneSurface>(transptr, bounds); - - res.push_back(srf); - m_surfaces.push_back( - std::move(srf)); // keep shared, will get destroyed at the end - } + return res; + } - return res; - } + void draw_surfaces(const SrfVec& surfaces, const std::string& fname) { + std::ofstream os; + os.open(fname); + + os << std::fixed << std::setprecision(4); + + size_t nVtx = 0; + for (const auto& srfx : surfaces) { + std::shared_ptr<const PlaneSurface> srf = + std::dynamic_pointer_cast<const PlaneSurface>(srfx); + const PlanarBounds* bounds = + dynamic_cast<const PlanarBounds*>(&srf->bounds()); - SrfVec - makeBarrel(int nPhi, int nZ, double w, double h) - { - double z0 = -(nZ - 1) * w; - SrfVec res; - - for (int i = 0; i < nZ; i++) { - double z = i * w * 2 + z0; - // std::cout << "z=" << z << std::endl; - SrfVec ring = fullPhiTestSurfacesBRL(nPhi, 0, z, M_PI / 9., w, h); - res.insert(res.end(), ring.begin(), ring.end()); + for (const auto& vtxloc : bounds->vertices()) { + Vector3D vtx = + srf->transform(tgContext) * Vector3D(vtxloc.x(), vtxloc.y(), 0); + os << "v " << vtx.x() << " " << vtx.y() << " " << vtx.z() << "\n"; } - return res; + // connect them + os << "f"; + for (size_t i = 1; i <= bounds->vertices().size(); ++i) { + os << " " << nVtx + i; + } + os << "\n"; + + nVtx += bounds->vertices().size(); } - void - draw_surfaces(const SrfVec& surfaces, const std::string& fname) - { + os.close(); + } +}; - std::ofstream os; - os.open(fname); +BOOST_AUTO_TEST_SUITE(Surfaces) - os << std::fixed << std::setprecision(4); +BOOST_FIXTURE_TEST_CASE(SurfaceArray_create, SurfaceArrayFixture) { + GeometryContext tgContext = GeometryContext(); - size_t nVtx = 0; - for (const auto& srfx : surfaces) { - std::shared_ptr<const PlaneSurface> srf - = std::dynamic_pointer_cast<const PlaneSurface>(srfx); - const PlanarBounds* bounds - = dynamic_cast<const PlanarBounds*>(&srf->bounds()); + SrfVec brl = makeBarrel(30, 7, 2, 1); + std::vector<const Surface*> brlRaw = unpack_shared_vector(brl); + draw_surfaces(brl, "SurfaceArray_create_BRL_1.obj"); - for (const auto& vtxloc : bounds->vertices()) { - Vector3D vtx - = srf->transform(tgContext) * Vector3D(vtxloc.x(), vtxloc.y(), 0); - os << "v " << vtx.x() << " " << vtx.y() << " " << vtx.z() << "\n"; - } + detail::Axis<detail::AxisType::Equidistant, detail::AxisBoundaryType::Closed> + phiAxis(-M_PI, M_PI, 30u); + detail::Axis<detail::AxisType::Equidistant, detail::AxisBoundaryType::Bound> + zAxis(-14, 14, 7u); - // connect them - os << "f"; - for (size_t i = 1; i <= bounds->vertices().size(); ++i) { - os << " " << nVtx + i; - } - os << "\n"; + double angleShift = 2 * M_PI / 30. / 2.; + auto transform = [angleShift](const Vector3D& pos) { + return Vector2D(phi(pos) + angleShift, pos.z()); + }; + double R = 10; + auto itransform = [angleShift, R](const Vector2D& loc) { + return Vector3D(R * std::cos(loc[0] - angleShift), + R * std::sin(loc[0] - angleShift), loc[1]); + }; - nVtx += bounds->vertices().size(); - } + auto sl = std::make_unique< + SurfaceArray::SurfaceGridLookup<decltype(phiAxis), decltype(zAxis)>>( + transform, itransform, + std::make_tuple(std::move(phiAxis), std::move(zAxis))); + sl->fill(tgContext, brlRaw); + SurfaceArray sa(std::move(sl), brl); - os.close(); - } - }; + // let's see if we can access all surfaces + sa.toStream(tgContext, std::cout); - BOOST_AUTO_TEST_SUITE(Surfaces) - - BOOST_FIXTURE_TEST_CASE(SurfaceArray_create, SurfaceArrayFixture) - { - - GeometryContext tgContext = GeometryContext(); - - SrfVec brl = makeBarrel(30, 7, 2, 1); - std::vector<const Surface*> brlRaw = unpack_shared_vector(brl); - draw_surfaces(brl, "SurfaceArray_create_BRL_1.obj"); - - detail::Axis<detail::AxisType::Equidistant, - detail::AxisBoundaryType::Closed> - phiAxis(-M_PI, M_PI, 30u); - detail::Axis<detail::AxisType::Equidistant, detail::AxisBoundaryType::Bound> - zAxis(-14, 14, 7u); - - double angleShift = 2 * M_PI / 30. / 2.; - auto transform = [angleShift](const Vector3D& pos) { - return Vector2D(phi(pos) + angleShift, pos.z()); - }; - double R = 10; - auto itransform = [angleShift, R](const Vector2D& loc) { - return Vector3D(R * std::cos(loc[0] - angleShift), - R * std::sin(loc[0] - angleShift), - loc[1]); - }; - - auto sl - = std::make_unique<SurfaceArray::SurfaceGridLookup<decltype(phiAxis), - decltype(zAxis)>>( - transform, - itransform, - std::make_tuple(std::move(phiAxis), std::move(zAxis))); - sl->fill(tgContext, brlRaw); - SurfaceArray sa(std::move(sl), brl); - - // let's see if we can access all surfaces - sa.toStream(tgContext, std::cout); - - for (const auto& srf : brl) { - Vector3D ctr = srf->binningPosition(tgContext, binR); - std::vector<const Surface*> binContent = sa.at(ctr); - - BOOST_CHECK_EQUAL(binContent.size(), 1); - BOOST_CHECK_EQUAL(srf.get(), binContent.at(0)); - } + for (const auto& srf : brl) { + Vector3D ctr = srf->binningPosition(tgContext, binR); + std::vector<const Surface*> binContent = sa.at(ctr); - std::vector<const Surface*> neighbors - = sa.neighbors(itransform(Vector2D(0, 0))); - BOOST_CHECK_EQUAL(neighbors.size(), 9); - - auto sl2 - = std::make_unique<SurfaceArray::SurfaceGridLookup<decltype(phiAxis), - decltype(zAxis)>>( - transform, - itransform, - std::make_tuple(std::move(phiAxis), std::move(zAxis))); - // do NOT fill, only completebinning - sl2->completeBinning(tgContext, brlRaw); - SurfaceArray sa2(std::move(sl2), brl); - sa.toStream(tgContext, std::cout); - for (const auto& srf : brl) { - Vector3D ctr = srf->binningPosition(tgContext, binR); - std::vector<const Surface*> binContent = sa2.at(ctr); - - BOOST_CHECK_EQUAL(binContent.size(), 1); - BOOST_CHECK_EQUAL(srf.get(), binContent.at(0)); - } + BOOST_CHECK_EQUAL(binContent.size(), 1); + BOOST_CHECK_EQUAL(srf.get(), binContent.at(0)); } - BOOST_AUTO_TEST_CASE(SurfaceArray_singleElement) - { - double w = 3, h = 4; - auto bounds = std::make_shared<const RectangleBounds>(w, h); - auto transptr - = std::make_shared<const Transform3D>(Transform3D::Identity()); - auto srf = Surface::makeShared<PlaneSurface>(transptr, bounds); + std::vector<const Surface*> neighbors = + sa.neighbors(itransform(Vector2D(0, 0))); + BOOST_CHECK_EQUAL(neighbors.size(), 9); + + auto sl2 = std::make_unique< + SurfaceArray::SurfaceGridLookup<decltype(phiAxis), decltype(zAxis)>>( + transform, itransform, + std::make_tuple(std::move(phiAxis), std::move(zAxis))); + // do NOT fill, only completebinning + sl2->completeBinning(tgContext, brlRaw); + SurfaceArray sa2(std::move(sl2), brl); + sa.toStream(tgContext, std::cout); + for (const auto& srf : brl) { + Vector3D ctr = srf->binningPosition(tgContext, binR); + std::vector<const Surface*> binContent = sa2.at(ctr); - SurfaceArray sa(srf); - - auto binContent = sa.at(Vector3D(42, 42, 42)); BOOST_CHECK_EQUAL(binContent.size(), 1); - BOOST_CHECK_EQUAL(binContent.at(0), srf.get()); - BOOST_CHECK_EQUAL(sa.surfaces().size(), 1); - BOOST_CHECK_EQUAL(sa.surfaces().at(0), srf.get()); + BOOST_CHECK_EQUAL(srf.get(), binContent.at(0)); } +} + +BOOST_AUTO_TEST_CASE(SurfaceArray_singleElement) { + double w = 3, h = 4; + auto bounds = std::make_shared<const RectangleBounds>(w, h); + auto transptr = std::make_shared<const Transform3D>(Transform3D::Identity()); + auto srf = Surface::makeShared<PlaneSurface>(transptr, bounds); + + SurfaceArray sa(srf); + + auto binContent = sa.at(Vector3D(42, 42, 42)); + BOOST_CHECK_EQUAL(binContent.size(), 1); + BOOST_CHECK_EQUAL(binContent.at(0), srf.get()); + BOOST_CHECK_EQUAL(sa.surfaces().size(), 1); + BOOST_CHECK_EQUAL(sa.surfaces().at(0), srf.get()); +} - BOOST_AUTO_TEST_SUITE_END() +BOOST_AUTO_TEST_SUITE_END() } // namespace Test } // namespace Acts diff --git a/Tests/Core/Surfaces/SurfaceBoundsTests.cpp b/Tests/Core/Surfaces/SurfaceBoundsTests.cpp index d293c810389b93866aa9f1c3a42abb28a197c977..e8abbfa0d2fcbbc4d541195ded27b99b21b3cf30 100644 --- a/Tests/Core/Surfaces/SurfaceBoundsTests.cpp +++ b/Tests/Core/Surfaces/SurfaceBoundsTests.cpp @@ -25,92 +25,68 @@ namespace Acts { /// Class to implement pure virtual method of SurfaceBounds for testing only -class SurfaceBoundsStub : public SurfaceBounds -{ -public: +class SurfaceBoundsStub : public SurfaceBounds { + public: /// Implement ctor and pure virtual methods of SurfaceBounds - explicit SurfaceBoundsStub(size_t nValues = 0) : m_values(nValues) - { + explicit SurfaceBoundsStub(size_t nValues = 0) : m_values(nValues) { for (size_t i = 0; i < nValues; ++i) { m_values[i] = i; } } - ~SurfaceBoundsStub() override { /*nop*/} - SurfaceBounds* - clone() const final - { - return nullptr; + ~SurfaceBoundsStub() override { /*nop*/ } - BoundsType - type() const final - { - return SurfaceBounds::Other; - } - std::vector<TDD_real_t> - valueStore() const override - { - return m_values; - } - bool - inside(const Vector2D& /*lpos*/, const BoundaryCheck& /*bcheck*/) const final - { + SurfaceBounds* clone() const final { return nullptr; } + BoundsType type() const final { return SurfaceBounds::Other; } + std::vector<TDD_real_t> valueStore() const override { return m_values; } + bool inside(const Vector2D& /*lpos*/, + const BoundaryCheck& /*bcheck*/) const final { return true; } - double - distanceToBoundary(const Vector2D& /*lpos*/) const final - { + double distanceToBoundary(const Vector2D& /*lpos*/) const final { return 10.; } - std::ostream& - toStream(std::ostream& sl) const final - { + std::ostream& toStream(std::ostream& sl) const final { sl << "SurfaceBoundsStub"; return sl; } -private: + private: std::vector<TDD_real_t> m_values; }; namespace Test { - BOOST_AUTO_TEST_SUITE(Surfaces) - /// Unit test for creating compliant/non-compliant SurfaceBounds object - BOOST_AUTO_TEST_CASE(SurfaceBoundsConstruction) - { - SurfaceBoundsStub u; - SurfaceBoundsStub s(1); // would act as size_t cast to SurfaceBounds - SurfaceBoundsStub t(s); - SurfaceBoundsStub v(u); - } - BOOST_AUTO_TEST_CASE(SurfaceBoundsProperties) - { - SurfaceBoundsStub surface(5); - std::vector<TDD_real_t> reference{0, 1, 2, 3, 4}; - const auto& valueStore = surface.valueStore(); - BOOST_CHECK_EQUAL_COLLECTIONS(reference.cbegin(), - reference.cend(), - valueStore.cbegin(), - valueStore.cend()); - } - /// Unit test for testing SurfaceBounds properties - BOOST_AUTO_TEST_CASE(SurfaceBoundsEquality) - { - SurfaceBoundsStub surface(1); - SurfaceBoundsStub copiedSurface(surface); - SurfaceBoundsStub differentSurface(2); - BOOST_CHECK_EQUAL(surface, copiedSurface); - BOOST_CHECK_NE(surface, differentSurface); - SurfaceBoundsStub assignedSurface; - assignedSurface = surface; - BOOST_CHECK_EQUAL(surface, assignedSurface); - const auto& surfaceValueStore = surface.valueStore(); - const auto& assignedValueStore = assignedSurface.valueStore(); - BOOST_CHECK_EQUAL_COLLECTIONS(surfaceValueStore.cbegin(), - surfaceValueStore.cend(), - assignedValueStore.cbegin(), - assignedValueStore.cend()); - } - BOOST_AUTO_TEST_SUITE_END() +BOOST_AUTO_TEST_SUITE(Surfaces) +/// Unit test for creating compliant/non-compliant SurfaceBounds object +BOOST_AUTO_TEST_CASE(SurfaceBoundsConstruction) { + SurfaceBoundsStub u; + SurfaceBoundsStub s(1); // would act as size_t cast to SurfaceBounds + SurfaceBoundsStub t(s); + SurfaceBoundsStub v(u); +} +BOOST_AUTO_TEST_CASE(SurfaceBoundsProperties) { + SurfaceBoundsStub surface(5); + std::vector<TDD_real_t> reference{0, 1, 2, 3, 4}; + const auto& valueStore = surface.valueStore(); + BOOST_CHECK_EQUAL_COLLECTIONS(reference.cbegin(), reference.cend(), + valueStore.cbegin(), valueStore.cend()); +} +/// Unit test for testing SurfaceBounds properties +BOOST_AUTO_TEST_CASE(SurfaceBoundsEquality) { + SurfaceBoundsStub surface(1); + SurfaceBoundsStub copiedSurface(surface); + SurfaceBoundsStub differentSurface(2); + BOOST_CHECK_EQUAL(surface, copiedSurface); + BOOST_CHECK_NE(surface, differentSurface); + SurfaceBoundsStub assignedSurface; + assignedSurface = surface; + BOOST_CHECK_EQUAL(surface, assignedSurface); + const auto& surfaceValueStore = surface.valueStore(); + const auto& assignedValueStore = assignedSurface.valueStore(); + BOOST_CHECK_EQUAL_COLLECTIONS( + surfaceValueStore.cbegin(), surfaceValueStore.cend(), + assignedValueStore.cbegin(), assignedValueStore.cend()); +} +BOOST_AUTO_TEST_SUITE_END() } // namespace Test diff --git a/Tests/Core/Surfaces/SurfaceStub.hpp b/Tests/Core/Surfaces/SurfaceStub.hpp index b002d0804a318be2d1d83da79c80af89aa9c3694..9349943b2032e07f1d7fec1450b79f50e3c7e704 100644 --- a/Tests/Core/Surfaces/SurfaceStub.hpp +++ b/Tests/Core/Surfaces/SurfaceStub.hpp @@ -14,143 +14,100 @@ namespace Acts { /// Surface derived class stub -class SurfaceStub : public Surface -{ -public: +class SurfaceStub : public Surface { + public: SurfaceStub(std::shared_ptr<const Transform3D> htrans = nullptr) - : GeometryObject(), Surface(htrans) - { - } - SurfaceStub(const GeometryContext& gctx, - const SurfaceStub& sf, - const Transform3D& transf) - : GeometryObject(), Surface(gctx, sf, transf) - { - } + : GeometryObject(), Surface(htrans) {} + SurfaceStub(const GeometryContext& gctx, const SurfaceStub& sf, + const Transform3D& transf) + : GeometryObject(), Surface(gctx, sf, transf) {} SurfaceStub(const DetectorElementBase& detelement) - : GeometryObject(), Surface(detelement) - { - } + : GeometryObject(), Surface(detelement) {} - ~SurfaceStub() override { /*nop */} + ~SurfaceStub() override { /*nop */ + } /// Implicit constructor - Surface* - clone(const GeometryContext& /*gctx*/, - const Transform3D& /*shift = nullptr*/) const - { + Surface* clone(const GeometryContext& /*gctx*/, + const Transform3D& /*shift = nullptr*/) const { return nullptr; } /// Return method for the Surface type to avoid dynamic casts - SurfaceType - type() const final - { - return Surface::Other; - } + SurfaceType type() const final { return Surface::Other; } /// Return method for the normal vector of the surface - const Vector3D - normal(const GeometryContext& gctx, const Vector2D& /*lpos*/) const final - { + const Vector3D normal(const GeometryContext& gctx, + const Vector2D& /*lpos*/) const final { return normal(gctx); } - const Vector3D - normal(const GeometryContext& gctx, const Vector3D&) const final - { + const Vector3D normal(const GeometryContext& gctx, + const Vector3D&) const final { return normal(gctx); } - const Vector3D - normal(const GeometryContext& /*gctx*/) const final - { + const Vector3D normal(const GeometryContext& /*gctx*/) const final { return Vector3D{0., 0., 0.}; } /// Return method for SurfaceBounds - const SurfaceBounds& - bounds() const final - { + const SurfaceBounds& bounds() const final { return s_noBounds; // need to improve this for meaningful test } /// Local to global transformation - void - localToGlobal(const GeometryContext& /*gctx*/, - const Vector2D& /*lpos*/, - const Vector3D& /*gmom*/, - Vector3D& /*gpos*/) const final - { + void localToGlobal(const GeometryContext& /*gctx*/, const Vector2D& /*lpos*/, + const Vector3D& /*gmom*/, Vector3D& /*gpos*/) const final { // nop } /// Global to local transformation - bool - globalToLocal(const GeometryContext& /*cxt*/, - const Vector3D& /*gpos*/, - const Vector3D& /*gmom*/, - Vector2D& lpos) const final - { + bool globalToLocal(const GeometryContext& /*cxt*/, const Vector3D& /*gpos*/, + const Vector3D& /*gmom*/, Vector2D& lpos) const final { lpos = Vector2D{20., 20.}; return true; } /// Calculation of the path correction for incident - double - pathCorrection(const GeometryContext& /*cxt*/, - const Vector3D& /*gpos*/, - const Vector3D& /*gmom*/) const final - { + double pathCorrection(const GeometryContext& /*cxt*/, + const Vector3D& /*gpos*/, + const Vector3D& /*gmom*/) const final { return 0.0; } /// Straight line intersection schema from parameters - Intersection - intersectionEstimate(const GeometryContext& /*cxt*/, - const Vector3D& /*gpos*/, - const Vector3D& /*gdir*/, - NavigationDirection /*navDir*/, - const BoundaryCheck& /*bcheck*/, - CorrFnc corrfnc = nullptr) const final - { + Intersection intersectionEstimate(const GeometryContext& /*cxt*/, + const Vector3D& /*gpos*/, + const Vector3D& /*gdir*/, + NavigationDirection /*navDir*/, + const BoundaryCheck& /*bcheck*/, + CorrFnc corrfnc = nullptr) const final { (void)corrfnc; const Intersection is{Vector3D{1, 1, 1}, 20., true}; return is; } /// Inherited from GeometryObject base - const Vector3D - binningPosition(const GeometryContext& /*txt*/, - BinningValue /*bValue*/) const final - { + const Vector3D binningPosition(const GeometryContext& /*txt*/, + BinningValue /*bValue*/) const final { const Vector3D v{0.0, 0.0, 0.0}; return v; } /// Return properly formatted class name - std::string - name() const final - { - return std::string("SurfaceStub"); - } + std::string name() const final { return std::string("SurfaceStub"); } /// Simply return true to check a method can be called on a constructed object - bool - constructedOk() const - { - return true; - } + bool constructedOk() const { return true; } -private: + private: /// the bounds of this surface std::shared_ptr<const PlanarBounds> m_bounds; - SurfaceStub* - clone_impl(const GeometryContext& /*gctx*/, - const Transform3D& /* shift */) const override - { + SurfaceStub* clone_impl(const GeometryContext& /*gctx*/, + const Transform3D& /* shift */) const override { return nullptr; } }; -} +} // namespace Acts diff --git a/Tests/Core/Surfaces/SurfaceTests.cpp b/Tests/Core/Surfaces/SurfaceTests.cpp index 09575f5ebb1aa157f8e877900dff88f4d72f635d..432e3962479f6be9f8ce4de188577d2813889e28 100644 --- a/Tests/Core/Surfaces/SurfaceTests.cpp +++ b/Tests/Core/Surfaces/SurfaceTests.cpp @@ -32,160 +32,147 @@ namespace utf = boost::unit_test; namespace Acts { /// Mock track object with minimal methods implemented for compilation -class MockTrack -{ -public: - MockTrack(const Vector3D& mom, const Vector3D& pos) : m_mom(mom), m_pos(pos) - { +class MockTrack { + public: + MockTrack(const Vector3D& mom, const Vector3D& pos) : m_mom(mom), m_pos(pos) { // nop } - Vector3D - momentum() const - { - return m_mom; - } + Vector3D momentum() const { return m_mom; } - Vector3D - position() const - { - return m_pos; - } + Vector3D position() const { return m_pos; } -private: + private: Vector3D m_mom; Vector3D m_pos; }; namespace Test { - // Create a test context - GeometryContext tgContext = GeometryContext(); - - BOOST_AUTO_TEST_SUITE(Surfaces) - - /// todo: make test fixture; separate out different cases - - /// Unit test for creating compliant/non-compliant Surface object - BOOST_AUTO_TEST_CASE(SurfaceConstruction) - { - // SurfaceStub s; - BOOST_CHECK_EQUAL(Surface::Other, SurfaceStub().type()); - SurfaceStub original; - BOOST_CHECK_EQUAL(Surface::Other, SurfaceStub(original).type()); - Translation3D translation{0., 1., 2.}; - Transform3D transform(translation); - BOOST_CHECK_EQUAL(Surface::Other, - SurfaceStub(tgContext, original, transform).type()); - // need some cruft to make the next one work - auto pTransform = std::make_shared<const Transform3D>(translation); - std::shared_ptr<const Acts::PlanarBounds> p - = std::make_shared<const RectangleBounds>(5., 10.); - DetectorElementStub detElement{pTransform, p, 0.2, nullptr}; - BOOST_CHECK_EQUAL(Surface::Other, SurfaceStub(detElement).type()); - } - - /// Unit test for testing Surface properties - BOOST_AUTO_TEST_CASE(SurfaceProperties, *utf::expected_failures(1)) - { - // build a test object , 'surface' - std::shared_ptr<const Acts::PlanarBounds> pPlanarBound - = std::make_shared<const RectangleBounds>(5., 10.); - Vector3D reference{0., 1., 2.}; - Translation3D translation{0., 1., 2.}; - auto pTransform = std::make_shared<const Transform3D>(translation); - auto pLayer = PlaneLayer::create(pTransform, pPlanarBound); - MaterialProperties properties{0.2, 0.2, 0.2, 20., 10, 5.}; - auto pMaterial - = std::make_shared<const HomogeneousSurfaceMaterial>(properties); - DetectorElementStub detElement{pTransform, pPlanarBound, 0.2, pMaterial}; - SurfaceStub surface(detElement); - // associatedDetectorElement - BOOST_CHECK_EQUAL(surface.associatedDetectorElement(), &detElement); - // test associatelayer, associatedLayer - surface.associateLayer(*pLayer); - BOOST_CHECK_EQUAL(surface.associatedLayer(), pLayer.get()); - // associated Material is not set to the surface - // it is set to the detector element surface though - BOOST_CHECK_NE(surface.surfaceMaterial(), pMaterial.get()); - // center() - CHECK_CLOSE_OR_SMALL(reference, surface.center(tgContext), 1e-6, 1e-9); - // insideBounds - Vector2D localPosition{0.1, 3.0}; - BOOST_CHECK(surface.insideBounds(localPosition)); - Vector2D outside{20., 20.}; - BOOST_CHECK(!surface.insideBounds( - outside)); // fails: m_bounds only in derived classes - // intersectionEstimate (should delegate to derived class method of same - // name) - Vector3D mom{100., 200., 300.}; - auto intersectionEstimate = surface.intersectionEstimate( - tgContext, reference, mom, forward, false); - const Intersection ref{Vector3D{1, 1, 1}, 20., true}; - BOOST_CHECK_EQUAL(ref.position, intersectionEstimate.position); - // isOnSurface - BOOST_CHECK(surface.isOnSurface(tgContext, reference, mom, false)); - BOOST_CHECK(surface.isOnSurface( - tgContext, reference, mom, true)); // need to improve bounds() - // referenceFrame() - RotationMatrix3D unitary; - unitary << 1, 0, 0, 0, 1, 0, 0, 0, 1; - auto referenceFrame = surface.referenceFrame( - tgContext, reference, mom); // need more complex case to test - BOOST_CHECK_EQUAL(referenceFrame, unitary); - // normal() - auto normal = surface.Surface::normal(tgContext, - reference); // needs more complex - // test - Vector3D zero{0., 0., 0.}; - BOOST_CHECK_EQUAL(zero, normal); - // pathCorrection is pure virtual - // surfaceMaterial() - MaterialProperties newProperties{0.5, 0.5, 0.5, 20., 10., 5.}; - auto pNewMaterial - = std::make_shared<const HomogeneousSurfaceMaterial>(newProperties); - surface.assignSurfaceMaterial(pNewMaterial); - BOOST_CHECK_EQUAL(surface.surfaceMaterial(), - pNewMaterial.get()); // passes ?? - // - CHECK_CLOSE_OR_SMALL(surface.transform(tgContext), *pTransform, 1e-6, 1e-9); - // type() is pure virtual - } - - BOOST_AUTO_TEST_CASE(EqualityOperators) - { - // build some test objects - std::shared_ptr<const Acts::PlanarBounds> pPlanarBound - = std::make_shared<const RectangleBounds>(5., 10.); - Vector3D reference{0., 1., 2.}; - Translation3D translation1{0., 1., 2.}; - Translation3D translation2{1., 1., 2.}; - auto pTransform1 = std::make_shared<const Transform3D>(translation1); - auto pTransform2 = std::make_shared<const Transform3D>(translation2); - auto pLayer = PlaneLayer::create(pTransform1, pPlanarBound); - MaterialProperties properties{1., 1., 1., 20., 10, 5.}; - auto pMaterial - = std::make_shared<const HomogeneousSurfaceMaterial>(properties); - DetectorElementStub detElement1{pTransform1, pPlanarBound, 0.2, pMaterial}; - DetectorElementStub detElement2{pTransform1, pPlanarBound, 0.3, pMaterial}; - DetectorElementStub detElement3{pTransform2, pPlanarBound, 0.3, pMaterial}; - // - SurfaceStub surface1(detElement1); - SurfaceStub surface2(detElement1); // 1 and 2 are the same - SurfaceStub surface3(detElement2); // 3 differs in thickness - SurfaceStub surface4(detElement3); // 4 has a different transform and id - // - BOOST_CHECK(surface1 == surface2); - // - // remove test for the moment, - // surfaces do not have a concept of thickness (only detector elements have) - // only thickness is different here - // - // BOOST_CHECK_NE(surface1, surface3); // will fail - // - BOOST_CHECK(surface1 != surface4); - } - BOOST_AUTO_TEST_SUITE_END() +// Create a test context +GeometryContext tgContext = GeometryContext(); + +BOOST_AUTO_TEST_SUITE(Surfaces) + +/// todo: make test fixture; separate out different cases + +/// Unit test for creating compliant/non-compliant Surface object +BOOST_AUTO_TEST_CASE(SurfaceConstruction) { + // SurfaceStub s; + BOOST_CHECK_EQUAL(Surface::Other, SurfaceStub().type()); + SurfaceStub original; + BOOST_CHECK_EQUAL(Surface::Other, SurfaceStub(original).type()); + Translation3D translation{0., 1., 2.}; + Transform3D transform(translation); + BOOST_CHECK_EQUAL(Surface::Other, + SurfaceStub(tgContext, original, transform).type()); + // need some cruft to make the next one work + auto pTransform = std::make_shared<const Transform3D>(translation); + std::shared_ptr<const Acts::PlanarBounds> p = + std::make_shared<const RectangleBounds>(5., 10.); + DetectorElementStub detElement{pTransform, p, 0.2, nullptr}; + BOOST_CHECK_EQUAL(Surface::Other, SurfaceStub(detElement).type()); +} + +/// Unit test for testing Surface properties +BOOST_AUTO_TEST_CASE(SurfaceProperties, *utf::expected_failures(1)) { + // build a test object , 'surface' + std::shared_ptr<const Acts::PlanarBounds> pPlanarBound = + std::make_shared<const RectangleBounds>(5., 10.); + Vector3D reference{0., 1., 2.}; + Translation3D translation{0., 1., 2.}; + auto pTransform = std::make_shared<const Transform3D>(translation); + auto pLayer = PlaneLayer::create(pTransform, pPlanarBound); + MaterialProperties properties{0.2, 0.2, 0.2, 20., 10, 5.}; + auto pMaterial = + std::make_shared<const HomogeneousSurfaceMaterial>(properties); + DetectorElementStub detElement{pTransform, pPlanarBound, 0.2, pMaterial}; + SurfaceStub surface(detElement); + // associatedDetectorElement + BOOST_CHECK_EQUAL(surface.associatedDetectorElement(), &detElement); + // test associatelayer, associatedLayer + surface.associateLayer(*pLayer); + BOOST_CHECK_EQUAL(surface.associatedLayer(), pLayer.get()); + // associated Material is not set to the surface + // it is set to the detector element surface though + BOOST_CHECK_NE(surface.surfaceMaterial(), pMaterial.get()); + // center() + CHECK_CLOSE_OR_SMALL(reference, surface.center(tgContext), 1e-6, 1e-9); + // insideBounds + Vector2D localPosition{0.1, 3.0}; + BOOST_CHECK(surface.insideBounds(localPosition)); + Vector2D outside{20., 20.}; + BOOST_CHECK(!surface.insideBounds( + outside)); // fails: m_bounds only in derived classes + // intersectionEstimate (should delegate to derived class method of same + // name) + Vector3D mom{100., 200., 300.}; + auto intersectionEstimate = + surface.intersectionEstimate(tgContext, reference, mom, forward, false); + const Intersection ref{Vector3D{1, 1, 1}, 20., true}; + BOOST_CHECK_EQUAL(ref.position, intersectionEstimate.position); + // isOnSurface + BOOST_CHECK(surface.isOnSurface(tgContext, reference, mom, false)); + BOOST_CHECK(surface.isOnSurface(tgContext, reference, mom, + true)); // need to improve bounds() + // referenceFrame() + RotationMatrix3D unitary; + unitary << 1, 0, 0, 0, 1, 0, 0, 0, 1; + auto referenceFrame = surface.referenceFrame( + tgContext, reference, mom); // need more complex case to test + BOOST_CHECK_EQUAL(referenceFrame, unitary); + // normal() + auto normal = surface.Surface::normal(tgContext, + reference); // needs more complex + // test + Vector3D zero{0., 0., 0.}; + BOOST_CHECK_EQUAL(zero, normal); + // pathCorrection is pure virtual + // surfaceMaterial() + MaterialProperties newProperties{0.5, 0.5, 0.5, 20., 10., 5.}; + auto pNewMaterial = + std::make_shared<const HomogeneousSurfaceMaterial>(newProperties); + surface.assignSurfaceMaterial(pNewMaterial); + BOOST_CHECK_EQUAL(surface.surfaceMaterial(), + pNewMaterial.get()); // passes ?? + // + CHECK_CLOSE_OR_SMALL(surface.transform(tgContext), *pTransform, 1e-6, 1e-9); + // type() is pure virtual +} + +BOOST_AUTO_TEST_CASE(EqualityOperators) { + // build some test objects + std::shared_ptr<const Acts::PlanarBounds> pPlanarBound = + std::make_shared<const RectangleBounds>(5., 10.); + Vector3D reference{0., 1., 2.}; + Translation3D translation1{0., 1., 2.}; + Translation3D translation2{1., 1., 2.}; + auto pTransform1 = std::make_shared<const Transform3D>(translation1); + auto pTransform2 = std::make_shared<const Transform3D>(translation2); + auto pLayer = PlaneLayer::create(pTransform1, pPlanarBound); + MaterialProperties properties{1., 1., 1., 20., 10, 5.}; + auto pMaterial = + std::make_shared<const HomogeneousSurfaceMaterial>(properties); + DetectorElementStub detElement1{pTransform1, pPlanarBound, 0.2, pMaterial}; + DetectorElementStub detElement2{pTransform1, pPlanarBound, 0.3, pMaterial}; + DetectorElementStub detElement3{pTransform2, pPlanarBound, 0.3, pMaterial}; + // + SurfaceStub surface1(detElement1); + SurfaceStub surface2(detElement1); // 1 and 2 are the same + SurfaceStub surface3(detElement2); // 3 differs in thickness + SurfaceStub surface4(detElement3); // 4 has a different transform and id + // + BOOST_CHECK(surface1 == surface2); + // + // remove test for the moment, + // surfaces do not have a concept of thickness (only detector elements have) + // only thickness is different here + // + // BOOST_CHECK_NE(surface1, surface3); // will fail + // + BOOST_CHECK(surface1 != surface4); +} +BOOST_AUTO_TEST_SUITE_END() } // namespace Test diff --git a/Tests/Core/Surfaces/TrapezoidBoundsTests.cpp b/Tests/Core/Surfaces/TrapezoidBoundsTests.cpp index 5b5d28cbb7eee7e87e21f86bcb38d354ca65a500..f01248cd0290809ca2b7383c181d4052d37156e3 100644 --- a/Tests/Core/Surfaces/TrapezoidBoundsTests.cpp +++ b/Tests/Core/Surfaces/TrapezoidBoundsTests.cpp @@ -25,102 +25,97 @@ namespace utf = boost::unit_test; namespace Acts { namespace Test { - BOOST_AUTO_TEST_SUITE(Surfaces) - /// Unit test for creating compliant/non-compliant TrapezoidBounds object - BOOST_AUTO_TEST_CASE(TrapezoidBoundsConstruction) - { - double minHalfX(1.), maxHalfX(6.), halfY(2.); - // - // default construction deleted - // TrapezoidBounds defaultConstructedTrapezoidBounds; - // - /// Test construction with defining half lengths - BOOST_CHECK_EQUAL(TrapezoidBounds(minHalfX, maxHalfX, halfY).type(), - SurfaceBounds::Trapezoid); - /// Copy constructor - TrapezoidBounds original(minHalfX, maxHalfX, halfY); - TrapezoidBounds copied(original); - BOOST_CHECK_EQUAL(copied.type(), SurfaceBounds::Trapezoid); - } +BOOST_AUTO_TEST_SUITE(Surfaces) +/// Unit test for creating compliant/non-compliant TrapezoidBounds object +BOOST_AUTO_TEST_CASE(TrapezoidBoundsConstruction) { + double minHalfX(1.), maxHalfX(6.), halfY(2.); + // + // default construction deleted + // TrapezoidBounds defaultConstructedTrapezoidBounds; + // + /// Test construction with defining half lengths + BOOST_CHECK_EQUAL(TrapezoidBounds(minHalfX, maxHalfX, halfY).type(), + SurfaceBounds::Trapezoid); + /// Copy constructor + TrapezoidBounds original(minHalfX, maxHalfX, halfY); + TrapezoidBounds copied(original); + BOOST_CHECK_EQUAL(copied.type(), SurfaceBounds::Trapezoid); +} - /// Unit tests for TrapezoidBounds properties - BOOST_AUTO_TEST_CASE(TrapezoidBoundsProperties, *utf::expected_failures(3)) - { - double minHalfX(1.), maxHalfX(6.), halfY(2.); - // - TrapezoidBounds trapezoidBoundsObject(minHalfX, maxHalfX, halfY); - /// Test clone - auto pClonedTrapezoidBounds = trapezoidBoundsObject.clone(); - BOOST_CHECK_NE(pClonedTrapezoidBounds, nullptr); - delete pClonedTrapezoidBounds; - // - /// Test type() (redundant; already used in constructor confirmation) - BOOST_CHECK_EQUAL(trapezoidBoundsObject.type(), SurfaceBounds::Trapezoid); - // - /// Test minHalflengthX - BOOST_CHECK_EQUAL(trapezoidBoundsObject.minHalflengthX(), minHalfX); - // - /// Test maxHalfLengthX - BOOST_CHECK_EQUAL(trapezoidBoundsObject.maxHalflengthX(), maxHalfX); - // - /// Test halflengthY - BOOST_CHECK_EQUAL(trapezoidBoundsObject.halflengthY(), halfY); - // - /// Test distanceToBoundary - Vector2D origin(0., 0.); - Vector2D outside(30., 0.); - Vector2D inRectangle(2., 0.5); - CHECK_CLOSE_REL(trapezoidBoundsObject.distanceToBoundary(origin), - -2., - 1e-6); // makes sense - CHECK_CLOSE_REL(trapezoidBoundsObject.distanceToBoundary(outside), - std::hypot(2., 24.), - 1e-6); // ok - // - /// Test vertices - std::vector<Vector2D> expectedVertices{ - {1., -2.}, {6., 2.}, {-6., 2.}, {-1., -2.}}; - const auto& actualVertices = trapezoidBoundsObject.vertices(); - BOOST_CHECK_EQUAL_COLLECTIONS(actualVertices.cbegin(), - actualVertices.cend(), - expectedVertices.cbegin(), - expectedVertices.cend()); - /** - for (auto i: trapezoidBoundsObject.vertices()){ - std::cout<<i[0]<<", "<<i[1]<<std::endl; - }**/ - // - /// Test boundingBox - BOOST_CHECK_EQUAL(trapezoidBoundsObject.boundingBox(), - RectangleBounds(6., 2.)); - // +/// Unit tests for TrapezoidBounds properties +BOOST_AUTO_TEST_CASE(TrapezoidBoundsProperties, *utf::expected_failures(3)) { + double minHalfX(1.), maxHalfX(6.), halfY(2.); + // + TrapezoidBounds trapezoidBoundsObject(minHalfX, maxHalfX, halfY); + /// Test clone + auto pClonedTrapezoidBounds = trapezoidBoundsObject.clone(); + BOOST_CHECK_NE(pClonedTrapezoidBounds, nullptr); + delete pClonedTrapezoidBounds; + // + /// Test type() (redundant; already used in constructor confirmation) + BOOST_CHECK_EQUAL(trapezoidBoundsObject.type(), SurfaceBounds::Trapezoid); + // + /// Test minHalflengthX + BOOST_CHECK_EQUAL(trapezoidBoundsObject.minHalflengthX(), minHalfX); + // + /// Test maxHalfLengthX + BOOST_CHECK_EQUAL(trapezoidBoundsObject.maxHalflengthX(), maxHalfX); + // + /// Test halflengthY + BOOST_CHECK_EQUAL(trapezoidBoundsObject.halflengthY(), halfY); + // + /// Test distanceToBoundary + Vector2D origin(0., 0.); + Vector2D outside(30., 0.); + Vector2D inRectangle(2., 0.5); + CHECK_CLOSE_REL(trapezoidBoundsObject.distanceToBoundary(origin), -2., + 1e-6); // makes sense + CHECK_CLOSE_REL(trapezoidBoundsObject.distanceToBoundary(outside), + std::hypot(2., 24.), + 1e-6); // ok + // + /// Test vertices + std::vector<Vector2D> expectedVertices{ + {1., -2.}, {6., 2.}, {-6., 2.}, {-1., -2.}}; + const auto& actualVertices = trapezoidBoundsObject.vertices(); + BOOST_CHECK_EQUAL_COLLECTIONS(actualVertices.cbegin(), actualVertices.cend(), + expectedVertices.cbegin(), + expectedVertices.cend()); + /** + for (auto i: trapezoidBoundsObject.vertices()){ + std::cout<<i[0]<<", "<<i[1]<<std::endl; + }**/ + // + /// Test boundingBox + BOOST_CHECK_EQUAL(trapezoidBoundsObject.boundingBox(), + RectangleBounds(6., 2.)); + // - // - /// Test dump - boost::test_tools::output_test_stream dumpOuput; - trapezoidBoundsObject.toStream(dumpOuput); - BOOST_CHECK( - dumpOuput.is_equal("Acts::TrapezoidBounds: (minHlengthX, maxHlengthX, " - "hlengthY) = (1.0000000, 6.0000000, 2.0000000)")); - // - /// Test inside - BOOST_CHECK(trapezoidBoundsObject.inside(inRectangle, BoundaryCheck(true))); - BOOST_CHECK(!trapezoidBoundsObject.inside(outside, BoundaryCheck(true))); - } - /// Unit test for testing TrapezoidBounds assignment - BOOST_AUTO_TEST_CASE(TrapezoidBoundsAssignment) - { - double minHalfX(1.), maxHalfX(6.), halfY(2.); - TrapezoidBounds trapezoidBoundsObject(minHalfX, maxHalfX, halfY); - // operator == not implemented in this class - // - /// Test assignment - TrapezoidBounds assignedTrapezoidBoundsObject(10., 20., 14.2); - assignedTrapezoidBoundsObject = trapezoidBoundsObject; - BOOST_CHECK_EQUAL(assignedTrapezoidBoundsObject, trapezoidBoundsObject); - } + // + /// Test dump + boost::test_tools::output_test_stream dumpOuput; + trapezoidBoundsObject.toStream(dumpOuput); + BOOST_CHECK( + dumpOuput.is_equal("Acts::TrapezoidBounds: (minHlengthX, maxHlengthX, " + "hlengthY) = (1.0000000, 6.0000000, 2.0000000)")); + // + /// Test inside + BOOST_CHECK(trapezoidBoundsObject.inside(inRectangle, BoundaryCheck(true))); + BOOST_CHECK(!trapezoidBoundsObject.inside(outside, BoundaryCheck(true))); +} +/// Unit test for testing TrapezoidBounds assignment +BOOST_AUTO_TEST_CASE(TrapezoidBoundsAssignment) { + double minHalfX(1.), maxHalfX(6.), halfY(2.); + TrapezoidBounds trapezoidBoundsObject(minHalfX, maxHalfX, halfY); + // operator == not implemented in this class + // + /// Test assignment + TrapezoidBounds assignedTrapezoidBoundsObject(10., 20., 14.2); + assignedTrapezoidBoundsObject = trapezoidBoundsObject; + BOOST_CHECK_EQUAL(assignedTrapezoidBoundsObject, trapezoidBoundsObject); +} - BOOST_AUTO_TEST_SUITE_END() +BOOST_AUTO_TEST_SUITE_END() } // namespace Test diff --git a/Tests/Core/Surfaces/TriangleBoundsTests.cpp b/Tests/Core/Surfaces/TriangleBoundsTests.cpp index abb32e7531f7dc6e8a6cff41a42ec6d0344d10ba..e5ea38c8337d13ddf742b6e5b10cf1483d807e81 100644 --- a/Tests/Core/Surfaces/TriangleBoundsTests.cpp +++ b/Tests/Core/Surfaces/TriangleBoundsTests.cpp @@ -25,102 +25,94 @@ namespace utf = boost::unit_test; namespace Acts { namespace Test { - BOOST_AUTO_TEST_SUITE(Surfaces) - /// Unit test for creating compliant/non-compliant TriangleBounds object - BOOST_AUTO_TEST_CASE(TriangleBoundsConstruction) - { - std::array<Vector2D, 3> vertices({{Vector2D(1., 1.), - Vector2D(4., 1.), - Vector2D(4., 5.)}}); // 3-4-5 triangle - // test default construction - // TriangleBounds defaultConstructedTriangleBounds; //deleted - // - /// Test construction with vertices - BOOST_CHECK_EQUAL(TriangleBounds(vertices).type(), SurfaceBounds::Triangle); - // - /// Copy constructor - TriangleBounds original(vertices); - TriangleBounds copied(original); - BOOST_CHECK_EQUAL(copied.type(), SurfaceBounds::Triangle); - } +BOOST_AUTO_TEST_SUITE(Surfaces) +/// Unit test for creating compliant/non-compliant TriangleBounds object +BOOST_AUTO_TEST_CASE(TriangleBoundsConstruction) { + std::array<Vector2D, 3> vertices({{Vector2D(1., 1.), Vector2D(4., 1.), + Vector2D(4., 5.)}}); // 3-4-5 triangle + // test default construction + // TriangleBounds defaultConstructedTriangleBounds; //deleted + // + /// Test construction with vertices + BOOST_CHECK_EQUAL(TriangleBounds(vertices).type(), SurfaceBounds::Triangle); + // + /// Copy constructor + TriangleBounds original(vertices); + TriangleBounds copied(original); + BOOST_CHECK_EQUAL(copied.type(), SurfaceBounds::Triangle); +} - /// Unit tests for TriangleBounds properties - BOOST_AUTO_TEST_CASE(TriangleBoundsProperties) - { - std::array<Vector2D, 3> vertices({{Vector2D(1., 1.), - Vector2D(4., 1.), - Vector2D(4., 5.)}}); // 3-4-5 triangle - /// Test clone - TriangleBounds triangleBoundsObject(vertices); - auto pClonedTriangleBounds = triangleBoundsObject.clone(); - BOOST_CHECK_NE(pClonedTriangleBounds, nullptr); - delete pClonedTriangleBounds; - // - /// Test type() (redundant; already used in constructor confirmation) - BOOST_CHECK_EQUAL(triangleBoundsObject.type(), SurfaceBounds::Triangle); - // - /// Test distanceToBoundary - Vector2D origin(0., 0.); - Vector2D outside(30., 1.); - Vector2D inTriangle(2., 1.5); - CHECK_CLOSE_REL(triangleBoundsObject.distanceToBoundary(origin), - std::sqrt(2.), - 1e-6); // makes sense - CHECK_CLOSE_REL(triangleBoundsObject.distanceToBoundary(outside), - 26., - 1e-6); // ok - // - /// Test vertices : fail; there are in fact 6 vertices (10.03.2017) - std::array<Vector2D, 3> expectedVertices = vertices; - BOOST_TEST_MESSAGE( - "Following two tests fail because the triangle has six vertices"); - BOOST_CHECK_EQUAL(triangleBoundsObject.vertices().size(), (size_t)3); - for (size_t i = 0; i < 3; i++) { - CHECK_CLOSE_REL( - triangleBoundsObject.vertices().at(i), expectedVertices.at(i), 1e-6); - } - /// Test boundingBox NOTE: Bounding box too big - BOOST_CHECK_EQUAL(triangleBoundsObject.boundingBox(), - RectangleBounds(4., 5.)); - // +/// Unit tests for TriangleBounds properties +BOOST_AUTO_TEST_CASE(TriangleBoundsProperties) { + std::array<Vector2D, 3> vertices({{Vector2D(1., 1.), Vector2D(4., 1.), + Vector2D(4., 5.)}}); // 3-4-5 triangle + /// Test clone + TriangleBounds triangleBoundsObject(vertices); + auto pClonedTriangleBounds = triangleBoundsObject.clone(); + BOOST_CHECK_NE(pClonedTriangleBounds, nullptr); + delete pClonedTriangleBounds; + // + /// Test type() (redundant; already used in constructor confirmation) + BOOST_CHECK_EQUAL(triangleBoundsObject.type(), SurfaceBounds::Triangle); + // + /// Test distanceToBoundary + Vector2D origin(0., 0.); + Vector2D outside(30., 1.); + Vector2D inTriangle(2., 1.5); + CHECK_CLOSE_REL(triangleBoundsObject.distanceToBoundary(origin), + std::sqrt(2.), + 1e-6); // makes sense + CHECK_CLOSE_REL(triangleBoundsObject.distanceToBoundary(outside), 26., + 1e-6); // ok + // + /// Test vertices : fail; there are in fact 6 vertices (10.03.2017) + std::array<Vector2D, 3> expectedVertices = vertices; + BOOST_TEST_MESSAGE( + "Following two tests fail because the triangle has six vertices"); + BOOST_CHECK_EQUAL(triangleBoundsObject.vertices().size(), (size_t)3); + for (size_t i = 0; i < 3; i++) { + CHECK_CLOSE_REL(triangleBoundsObject.vertices().at(i), + expectedVertices.at(i), 1e-6); + } + /// Test boundingBox NOTE: Bounding box too big + BOOST_CHECK_EQUAL(triangleBoundsObject.boundingBox(), + RectangleBounds(4., 5.)); + // - // - /// Test dump - boost::test_tools::output_test_stream dumpOuput; - triangleBoundsObject.toStream(dumpOuput); - BOOST_CHECK(dumpOuput.is_equal( - "Acts::TriangleBounds: generating vertices (X, Y)(1.0000000 , 1.0000000) \n\ + // + /// Test dump + boost::test_tools::output_test_stream dumpOuput; + triangleBoundsObject.toStream(dumpOuput); + BOOST_CHECK(dumpOuput.is_equal( + "Acts::TriangleBounds: generating vertices (X, Y)(1.0000000 , 1.0000000) \n\ (4.0000000 , 1.0000000) \n\ (4.0000000 , 5.0000000) ")); - // - /// Test inside - BOOST_CHECK(triangleBoundsObject.inside(inTriangle, BoundaryCheck(true))); - BOOST_CHECK(!triangleBoundsObject.inside(outside, BoundaryCheck(true))); - } - /// Unit test for testing TriangleBounds assignment - BOOST_AUTO_TEST_CASE(TriangleBoundsAssignment) - { - std::array<Vector2D, 3> vertices({{Vector2D(1., 1.), - Vector2D(4., 1.), - Vector2D(4., 5)}}); // 3-4-5 triangle - std::array<Vector2D, 3> invalid( - {{Vector2D(-1, -1), Vector2D(-1, -1), Vector2D(-1, -1)}}); - TriangleBounds triangleBoundsObject(vertices); - // operator == not implemented in this class - // - /// Test assignment - TriangleBounds assignedTriangleBoundsObject( - invalid); // invalid object, in some sense - assignedTriangleBoundsObject = triangleBoundsObject; - const auto& assignedVertices = assignedTriangleBoundsObject.vertices(); - const auto& originalVertices = triangleBoundsObject.vertices(); - BOOST_CHECK_EQUAL_COLLECTIONS(assignedVertices.cbegin(), - assignedVertices.cend(), - originalVertices.cbegin(), - originalVertices.cend()); - } + // + /// Test inside + BOOST_CHECK(triangleBoundsObject.inside(inTriangle, BoundaryCheck(true))); + BOOST_CHECK(!triangleBoundsObject.inside(outside, BoundaryCheck(true))); +} +/// Unit test for testing TriangleBounds assignment +BOOST_AUTO_TEST_CASE(TriangleBoundsAssignment) { + std::array<Vector2D, 3> vertices({{Vector2D(1., 1.), Vector2D(4., 1.), + Vector2D(4., 5)}}); // 3-4-5 triangle + std::array<Vector2D, 3> invalid( + {{Vector2D(-1, -1), Vector2D(-1, -1), Vector2D(-1, -1)}}); + TriangleBounds triangleBoundsObject(vertices); + // operator == not implemented in this class + // + /// Test assignment + TriangleBounds assignedTriangleBoundsObject( + invalid); // invalid object, in some sense + assignedTriangleBoundsObject = triangleBoundsObject; + const auto& assignedVertices = assignedTriangleBoundsObject.vertices(); + const auto& originalVertices = triangleBoundsObject.vertices(); + BOOST_CHECK_EQUAL_COLLECTIONS( + assignedVertices.cbegin(), assignedVertices.cend(), + originalVertices.cbegin(), originalVertices.cend()); +} - BOOST_AUTO_TEST_SUITE_END() +BOOST_AUTO_TEST_SUITE_END() } // namespace Test diff --git a/Tests/Core/Utilities/AxesTests.cpp b/Tests/Core/Utilities/AxesTests.cpp index df888957751c775b68717b2937506734ee6c9a10..0cbf1125a51d9a0189baa89ef025b37ca75c0a13 100644 --- a/Tests/Core/Utilities/AxesTests.cpp +++ b/Tests/Core/Utilities/AxesTests.cpp @@ -18,366 +18,358 @@ using namespace detail; namespace Test { - BOOST_AUTO_TEST_CASE(equidistant_axis) - { - EquidistantAxis a(0.0, 10.0, 10u); - - // general binning properties - BOOST_CHECK_EQUAL(a.getNBins(), 10u); - BOOST_CHECK_EQUAL(a.getMax(), 10.); - BOOST_CHECK_EQUAL(a.getMin(), 0.); - BOOST_CHECK_EQUAL(a.getBinWidth(), 1.); - - // bin index calculation - BOOST_CHECK_EQUAL(a.getBin(-0.3), 0u); - BOOST_CHECK_EQUAL(a.getBin(-0.), 1u); - BOOST_CHECK_EQUAL(a.getBin(0.), 1u); - BOOST_CHECK_EQUAL(a.getBin(0.7), 1u); - BOOST_CHECK_EQUAL(a.getBin(1), 2u); - BOOST_CHECK_EQUAL(a.getBin(1.2), 2u); - BOOST_CHECK_EQUAL(a.getBin(2.), 3u); - BOOST_CHECK_EQUAL(a.getBin(2.7), 3u); - BOOST_CHECK_EQUAL(a.getBin(3.), 4u); - BOOST_CHECK_EQUAL(a.getBin(3.6), 4u); - BOOST_CHECK_EQUAL(a.getBin(4.), 5u); - BOOST_CHECK_EQUAL(a.getBin(4.98), 5u); - BOOST_CHECK_EQUAL(a.getBin(5.), 6u); - BOOST_CHECK_EQUAL(a.getBin(5.12), 6u); - BOOST_CHECK_EQUAL(a.getBin(6.), 7u); - BOOST_CHECK_EQUAL(a.getBin(6.00001), 7u); - BOOST_CHECK_EQUAL(a.getBin(7.), 8u); - BOOST_CHECK_EQUAL(a.getBin(7.5), 8u); - BOOST_CHECK_EQUAL(a.getBin(8.), 9u); - BOOST_CHECK_EQUAL(a.getBin(8.1), 9u); - BOOST_CHECK_EQUAL(a.getBin(9.), 10u); - BOOST_CHECK_EQUAL(a.getBin(9.999), 10u); - BOOST_CHECK_EQUAL(a.getBin(10.), 11u); - BOOST_CHECK_EQUAL(a.getBin(100.3), 11u); - - // lower bin boundaries - BOOST_CHECK_EQUAL(a.getBinLowerBound(1), 0.); - BOOST_CHECK_EQUAL(a.getBinLowerBound(2), 1.); - BOOST_CHECK_EQUAL(a.getBinLowerBound(3), 2.); - BOOST_CHECK_EQUAL(a.getBinLowerBound(4), 3.); - BOOST_CHECK_EQUAL(a.getBinLowerBound(5), 4.); - BOOST_CHECK_EQUAL(a.getBinLowerBound(6), 5.); - BOOST_CHECK_EQUAL(a.getBinLowerBound(7), 6.); - BOOST_CHECK_EQUAL(a.getBinLowerBound(8), 7.); - BOOST_CHECK_EQUAL(a.getBinLowerBound(9), 8.); - BOOST_CHECK_EQUAL(a.getBinLowerBound(10), 9.); - - // upper bin boundaries - BOOST_CHECK_EQUAL(a.getBinUpperBound(1), 1.); - BOOST_CHECK_EQUAL(a.getBinUpperBound(2), 2.); - BOOST_CHECK_EQUAL(a.getBinUpperBound(3), 3.); - BOOST_CHECK_EQUAL(a.getBinUpperBound(4), 4.); - BOOST_CHECK_EQUAL(a.getBinUpperBound(5), 5.); - BOOST_CHECK_EQUAL(a.getBinUpperBound(6), 6.); - BOOST_CHECK_EQUAL(a.getBinUpperBound(7), 7.); - BOOST_CHECK_EQUAL(a.getBinUpperBound(8), 8.); - BOOST_CHECK_EQUAL(a.getBinUpperBound(9), 9.); - BOOST_CHECK_EQUAL(a.getBinUpperBound(10), 10.); - - // bin centers - BOOST_CHECK_EQUAL(a.getBinCenter(1), 0.5); - BOOST_CHECK_EQUAL(a.getBinCenter(2), 1.5); - BOOST_CHECK_EQUAL(a.getBinCenter(3), 2.5); - BOOST_CHECK_EQUAL(a.getBinCenter(4), 3.5); - BOOST_CHECK_EQUAL(a.getBinCenter(5), 4.5); - BOOST_CHECK_EQUAL(a.getBinCenter(6), 5.5); - BOOST_CHECK_EQUAL(a.getBinCenter(7), 6.5); - BOOST_CHECK_EQUAL(a.getBinCenter(8), 7.5); - BOOST_CHECK_EQUAL(a.getBinCenter(9), 8.5); - BOOST_CHECK_EQUAL(a.getBinCenter(10), 9.5); - - // inside check - BOOST_CHECK(not a.isInside(-0.2)); - BOOST_CHECK(a.isInside(0.)); - BOOST_CHECK(a.isInside(3.)); - BOOST_CHECK(not a.isInside(10.)); - BOOST_CHECK(not a.isInside(12.)); - } - - BOOST_AUTO_TEST_CASE(variable_axis) - { - VariableAxis a({0, 0.5, 3, 4.5, 6}); - - // general binning properties - BOOST_CHECK_EQUAL(a.getNBins(), 4u); - BOOST_CHECK_EQUAL(a.getMax(), 6.); - BOOST_CHECK_EQUAL(a.getMin(), 0.); - - // bin index calculation - BOOST_CHECK_EQUAL(a.getBin(-0.3), 0u); - BOOST_CHECK_EQUAL(a.getBin(-0.), 1u); - BOOST_CHECK_EQUAL(a.getBin(0.), 1u); - BOOST_CHECK_EQUAL(a.getBin(0.3), 1u); - BOOST_CHECK_EQUAL(a.getBin(0.5), 2u); - BOOST_CHECK_EQUAL(a.getBin(1.2), 2u); - BOOST_CHECK_EQUAL(a.getBin(2.7), 2u); - BOOST_CHECK_EQUAL(a.getBin(3.), 3u); - BOOST_CHECK_EQUAL(a.getBin(4.49999), 3u); - BOOST_CHECK_EQUAL(a.getBin(4.5), 4u); - BOOST_CHECK_EQUAL(a.getBin(5.12), 4u); - BOOST_CHECK_EQUAL(a.getBin(6.), 5u); - BOOST_CHECK_EQUAL(a.getBin(6.00001), 5u); - BOOST_CHECK_EQUAL(a.getBin(7.5), 5u); - - // lower bin boundaries - BOOST_CHECK_EQUAL(a.getBinLowerBound(1), 0.); - BOOST_CHECK_EQUAL(a.getBinLowerBound(2), 0.5); - BOOST_CHECK_EQUAL(a.getBinLowerBound(3), 3.); - BOOST_CHECK_EQUAL(a.getBinLowerBound(4), 4.5); - - // upper bin boundaries - BOOST_CHECK_EQUAL(a.getBinUpperBound(1), 0.5); - BOOST_CHECK_EQUAL(a.getBinUpperBound(2), 3.); - BOOST_CHECK_EQUAL(a.getBinUpperBound(3), 4.5); - BOOST_CHECK_EQUAL(a.getBinUpperBound(4), 6.); - - // bin centers - BOOST_CHECK_EQUAL(a.getBinCenter(1), 0.25); - BOOST_CHECK_EQUAL(a.getBinCenter(2), 1.75); - BOOST_CHECK_EQUAL(a.getBinCenter(3), 3.75); - BOOST_CHECK_EQUAL(a.getBinCenter(4), 5.25); - - // inside check - BOOST_CHECK(not a.isInside(-0.2)); - BOOST_CHECK(a.isInside(0.)); - BOOST_CHECK(a.isInside(3.)); - BOOST_CHECK(not a.isInside(6.)); - BOOST_CHECK(not a.isInside(12.)); - } - - BOOST_AUTO_TEST_CASE(open_axis) - { - Axis<AxisType::Equidistant, AxisBoundaryType::Bound> a(0, 10, 10); - - // normal inside - BOOST_CHECK_EQUAL(a.getBin(0.5), 1u); - BOOST_CHECK_EQUAL(a.getBin(9.5), 10u); - - // out of bounds, but is open - // -> should clamp - BOOST_CHECK_EQUAL(a.getBin(-0.5), 1u); - BOOST_CHECK_EQUAL(a.getBin(10.5), 10u); - - Axis<AxisType::Variable, AxisBoundaryType::Bound> b( - {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}); - - // normal inside - BOOST_CHECK_EQUAL(b.getBin(0.5), 1u); - BOOST_CHECK_EQUAL(b.getBin(9.5), 10u); - - // out of bounds, but is open - // -> should clamp - BOOST_CHECK_EQUAL(b.getBin(-0.5), 1u); - BOOST_CHECK_EQUAL(b.getBin(10.5), 10u); - } - - BOOST_AUTO_TEST_CASE(closed_axis) - { - Axis<AxisType::Equidistant, AxisBoundaryType::Closed> a(0, 10, 10); - - // normal inside - BOOST_CHECK_EQUAL(a.getBin(0.5), 1u); - BOOST_CHECK_EQUAL(a.getBin(9.5), 10u); - - // out of bounds, but is closed - // -> should wrap to opposite side bin - BOOST_CHECK_EQUAL(a.getBin(-0.5), 10u); - BOOST_CHECK_EQUAL(a.getBin(10.5), 1u); - - Axis<AxisType::Variable, AxisBoundaryType::Closed> b( - {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}); - - // normal inside - BOOST_CHECK_EQUAL(b.getBin(0.5), 1u); - BOOST_CHECK_EQUAL(b.getBin(9.5), 10u); - - // out of bounds, but is closed - // -> should wrap to opposite side bin - BOOST_CHECK_EQUAL(b.getBin(-0.5), 10u); - BOOST_CHECK_EQUAL(b.getBin(10.5), 1u); - } - - BOOST_AUTO_TEST_CASE(neighborhood) - { - using bins_t = std::vector<size_t>; - Axis<AxisType::Equidistant, AxisBoundaryType::Open> a1(0.0, 1.0, 10u); - - BOOST_CHECK(a1.neighborHoodIndices(0, 1).collect() == bins_t({0, 1})); - BOOST_CHECK(a1.neighborHoodIndices(1, 1).collect() == bins_t({0, 1, 2})); - BOOST_CHECK(a1.neighborHoodIndices(11, 1).collect() == bins_t({10, 11})); - BOOST_CHECK(a1.neighborHoodIndices(10, 1).collect() == bins_t({9, 10, 11})); - BOOST_CHECK(a1.neighborHoodIndices(5, 1).collect() == bins_t({4, 5, 6})); - BOOST_CHECK(a1.neighborHoodIndices(5, {1, 0}).collect() == bins_t({4, 5})); - BOOST_CHECK(a1.neighborHoodIndices(5, {0, 1}).collect() == bins_t({5, 6})); - - BOOST_CHECK(a1.neighborHoodIndices(0, 2).collect() == bins_t({0, 1, 2})); - BOOST_CHECK(a1.neighborHoodIndices(1, 2).collect() == bins_t({0, 1, 2, 3})); - BOOST_CHECK(a1.neighborHoodIndices(11, 2).collect() == bins_t({9, 10, 11})); - BOOST_CHECK(a1.neighborHoodIndices(10, 2).collect() - == bins_t({8, 9, 10, 11})); - BOOST_CHECK(a1.neighborHoodIndices(5, 2).collect() - == bins_t({3, 4, 5, 6, 7})); - - Axis<AxisType::Variable, AxisBoundaryType::Open> a2( - {0.0, 2.0, 4.0, 9.0, 10.0}); - BOOST_CHECK(a2.neighborHoodIndices(0, 1).collect() == bins_t({0, 1})); - BOOST_CHECK(a2.neighborHoodIndices(1, 1).collect() == bins_t({0, 1, 2})); - BOOST_CHECK(a2.neighborHoodIndices(5, 1).collect() == bins_t({4, 5})); - BOOST_CHECK(a2.neighborHoodIndices(4, 1).collect() == bins_t({3, 4, 5})); - BOOST_CHECK(a2.neighborHoodIndices(4, {1, 0}).collect() == bins_t({3, 4})); - BOOST_CHECK(a2.neighborHoodIndices(2, 1).collect() == bins_t({1, 2, 3})); - BOOST_CHECK(a2.neighborHoodIndices(2, {0, 1}).collect() == bins_t({2, 3})); - - BOOST_CHECK(a2.neighborHoodIndices(0, 2).collect() == bins_t({0, 1, 2})); - BOOST_CHECK(a2.neighborHoodIndices(1, 2).collect() == bins_t({0, 1, 2, 3})); - BOOST_CHECK(a2.neighborHoodIndices(5, 2).collect() == bins_t({3, 4, 5})); - BOOST_CHECK(a2.neighborHoodIndices(4, 2).collect() == bins_t({2, 3, 4, 5})); - BOOST_CHECK(a2.neighborHoodIndices(3, 2).collect() - == bins_t({1, 2, 3, 4, 5})); - - Axis<AxisType::Equidistant, AxisBoundaryType::Bound> a3(0.0, 1.0, 10u); - - BOOST_CHECK(a3.neighborHoodIndices(0, 1).collect() == bins_t({})); - BOOST_CHECK(a3.neighborHoodIndices(1, 1).collect() == bins_t({1, 2})); - BOOST_CHECK(a3.neighborHoodIndices(11, 1).collect() == bins_t({})); - BOOST_CHECK(a3.neighborHoodIndices(10, 1).collect() == bins_t({9, 10})); - BOOST_CHECK(a3.neighborHoodIndices(10, {0, 1}).collect() == bins_t({10})); - BOOST_CHECK(a3.neighborHoodIndices(5, 1).collect() == bins_t({4, 5, 6})); - BOOST_CHECK(a3.neighborHoodIndices(5, {1, 0}).collect() == bins_t({4, 5})); - BOOST_CHECK(a3.neighborHoodIndices(5, {0, 1}).collect() == bins_t({5, 6})); - - BOOST_CHECK(a3.neighborHoodIndices(0, 2).collect() == bins_t({})); - BOOST_CHECK(a3.neighborHoodIndices(1, 2).collect() == bins_t({1, 2, 3})); - BOOST_CHECK(a3.neighborHoodIndices(11, 2).collect() == bins_t({})); - BOOST_CHECK(a3.neighborHoodIndices(10, 2).collect() == bins_t({8, 9, 10})); - BOOST_CHECK(a3.neighborHoodIndices(5, 2).collect() - == bins_t({3, 4, 5, 6, 7})); - - Axis<AxisType::Equidistant, AxisBoundaryType::Closed> a4(0.0, 1.0, 10u); - - BOOST_CHECK(a4.neighborHoodIndices(0, 1).collect() == bins_t({})); - BOOST_CHECK(a4.neighborHoodIndices(1, 1).collect() == bins_t({10, 1, 2})); - BOOST_CHECK(a4.neighborHoodIndices(11, 1).collect() == bins_t({})); - BOOST_CHECK(a4.neighborHoodIndices(10, 1).collect() == bins_t({9, 10, 1})); - BOOST_CHECK(a4.neighborHoodIndices(10, {0, 1}).collect() - == bins_t({10, 1})); - BOOST_CHECK(a4.neighborHoodIndices(5, 1).collect() == bins_t({4, 5, 6})); - BOOST_CHECK(a4.neighborHoodIndices(5, {1, 0}).collect() == bins_t({4, 5})); - BOOST_CHECK(a4.neighborHoodIndices(5, {0, 1}).collect() == bins_t({5, 6})); - - BOOST_CHECK(a4.neighborHoodIndices(0, 2).collect() == bins_t({})); - BOOST_CHECK(a4.neighborHoodIndices(1, 2).collect() - == bins_t({9, 10, 1, 2, 3})); - BOOST_CHECK(a4.neighborHoodIndices(11, 2).collect() == bins_t({})); - BOOST_CHECK(a4.neighborHoodIndices(10, 2).collect() - == bins_t({8, 9, 10, 1, 2})); - BOOST_CHECK(a4.neighborHoodIndices(5, 2).collect() - == bins_t({3, 4, 5, 6, 7})); - - Axis<AxisType::Variable, AxisBoundaryType::Bound> a5( - {0.0, 2.0, 4.0, 9.0, 9.5, 10.0}); - BOOST_CHECK(a5.neighborHoodIndices(0, 1).collect() == bins_t({})); - BOOST_CHECK(a5.neighborHoodIndices(1, 1).collect() == bins_t({1, 2})); - BOOST_CHECK(a5.neighborHoodIndices(6, 1).collect() == bins_t({})); - BOOST_CHECK(a5.neighborHoodIndices(5, 1).collect() == bins_t({4, 5})); - BOOST_CHECK(a5.neighborHoodIndices(5, {0, 1}).collect() == bins_t({5})); - BOOST_CHECK(a5.neighborHoodIndices(2, 1).collect() == bins_t({1, 2, 3})); - BOOST_CHECK(a5.neighborHoodIndices(2, {1, 0}).collect() == bins_t({1, 2})); - BOOST_CHECK(a5.neighborHoodIndices(2, {0, 1}).collect() == bins_t({2, 3})); - - BOOST_CHECK(a5.neighborHoodIndices(0, 2).collect() == bins_t({})); - BOOST_CHECK(a5.neighborHoodIndices(1, 2).collect() == bins_t({1, 2, 3})); - BOOST_CHECK(a5.neighborHoodIndices(6, 2).collect() == bins_t({})); - BOOST_CHECK(a5.neighborHoodIndices(5, 2).collect() == bins_t({3, 4, 5})); - BOOST_CHECK(a5.neighborHoodIndices(3, 2).collect() - == bins_t({1, 2, 3, 4, 5})); - - Axis<AxisType::Variable, AxisBoundaryType::Closed> a6( - {0.0, 2.0, 4.0, 9.0, 9.5, 10.0}); - BOOST_CHECK(a6.neighborHoodIndices(0, 1).collect() == bins_t({})); - BOOST_CHECK(a6.neighborHoodIndices(1, 1).collect() == bins_t({5, 1, 2})); - BOOST_CHECK(a6.neighborHoodIndices(6, 1).collect() == bins_t({})); - BOOST_CHECK(a6.neighborHoodIndices(5, 1).collect() == bins_t({4, 5, 1})); - BOOST_CHECK(a6.neighborHoodIndices(5, {0, 1}).collect() == bins_t({5, 1})); - BOOST_CHECK(a6.neighborHoodIndices(2, 1).collect() == bins_t({1, 2, 3})); - BOOST_CHECK(a6.neighborHoodIndices(2, {1, 0}).collect() == bins_t({1, 2})); - BOOST_CHECK(a6.neighborHoodIndices(2, {0, 1}).collect() == bins_t({2, 3})); - - BOOST_CHECK(a6.neighborHoodIndices(0, 2).collect() == bins_t({})); - BOOST_CHECK(a6.neighborHoodIndices(1, 2).collect() - == bins_t({4, 5, 1, 2, 3})); - BOOST_CHECK(a6.neighborHoodIndices(6, 2).collect() == bins_t({})); - BOOST_CHECK(a6.neighborHoodIndices(5, 2).collect() - == bins_t({3, 4, 5, 1, 2})); - BOOST_CHECK(a6.neighborHoodIndices(3, 2).collect() - == bins_t({1, 2, 3, 4, 5})); - BOOST_CHECK(a6.neighborHoodIndices(3, {0, 2}).collect() - == bins_t({3, 4, 5})); - - BOOST_CHECK(a6.neighborHoodIndices(1, 3).collect() - == bins_t({3, 4, 5, 1, 2})); - BOOST_CHECK(a6.neighborHoodIndices(5, 3).collect() - == bins_t({2, 3, 4, 5, 1})); - } - - BOOST_AUTO_TEST_CASE(wrapBin) - { - Axis<AxisType::Equidistant, AxisBoundaryType::Open> a1(0.0, 1.0, 10u); - BOOST_CHECK_EQUAL(a1.wrapBin(0), 0); - BOOST_CHECK_EQUAL(a1.wrapBin(1), 1); - BOOST_CHECK_EQUAL(a1.wrapBin(-1), 0); - BOOST_CHECK_EQUAL(a1.wrapBin(10), 10); - BOOST_CHECK_EQUAL(a1.wrapBin(11), 11); - BOOST_CHECK_EQUAL(a1.wrapBin(12), 11); - - Axis<AxisType::Equidistant, AxisBoundaryType::Bound> a2(0.0, 1.0, 10u); - BOOST_CHECK_EQUAL(a2.wrapBin(0), 1); - BOOST_CHECK_EQUAL(a2.wrapBin(1), 1); - BOOST_CHECK_EQUAL(a2.wrapBin(-1), 1); - BOOST_CHECK_EQUAL(a2.wrapBin(10), 10); - BOOST_CHECK_EQUAL(a2.wrapBin(11), 10); - BOOST_CHECK_EQUAL(a2.wrapBin(12), 10); - - Axis<AxisType::Equidistant, AxisBoundaryType::Closed> a3(0.0, 1.0, 10u); - BOOST_CHECK_EQUAL(a3.wrapBin(0), 10); - BOOST_CHECK_EQUAL(a3.wrapBin(1), 1); - BOOST_CHECK_EQUAL(a3.wrapBin(-1), 9); - BOOST_CHECK_EQUAL(a3.wrapBin(10), 10); - BOOST_CHECK_EQUAL(a3.wrapBin(11), 1); - BOOST_CHECK_EQUAL(a3.wrapBin(12), 2); - - Axis<AxisType::Variable, AxisBoundaryType::Open> a4( - {0.0, 2.0, 4.0, 9.0, 10.0}); - BOOST_CHECK_EQUAL(a4.wrapBin(0), 0); - BOOST_CHECK_EQUAL(a4.wrapBin(1), 1); - BOOST_CHECK_EQUAL(a4.wrapBin(-1), 0); - BOOST_CHECK_EQUAL(a4.wrapBin(4), 4); - BOOST_CHECK_EQUAL(a4.wrapBin(5), 5); - BOOST_CHECK_EQUAL(a4.wrapBin(6), 5); - - Axis<AxisType::Variable, AxisBoundaryType::Bound> a5( - {0.0, 2.0, 4.0, 9.0, 9.5, 10.0}); - BOOST_CHECK_EQUAL(a5.wrapBin(0), 1); - BOOST_CHECK_EQUAL(a5.wrapBin(1), 1); - BOOST_CHECK_EQUAL(a5.wrapBin(-1), 1); - BOOST_CHECK_EQUAL(a5.wrapBin(4), 4); - BOOST_CHECK_EQUAL(a5.wrapBin(5), 5); - BOOST_CHECK_EQUAL(a5.wrapBin(6), 5); - - Axis<AxisType::Variable, AxisBoundaryType::Closed> a6( - {0.0, 2.0, 4.0, 9.0, 9.5, 10.0}); - BOOST_CHECK_EQUAL(a6.wrapBin(0), 5); - BOOST_CHECK_EQUAL(a6.wrapBin(1), 1); - BOOST_CHECK_EQUAL(a6.wrapBin(-1), 4); - BOOST_CHECK_EQUAL(a6.wrapBin(4), 4); - BOOST_CHECK_EQUAL(a6.wrapBin(5), 5); - BOOST_CHECK_EQUAL(a6.wrapBin(6), 1); - BOOST_CHECK_EQUAL(a6.wrapBin(7), 2); - } +BOOST_AUTO_TEST_CASE(equidistant_axis) { + EquidistantAxis a(0.0, 10.0, 10u); + + // general binning properties + BOOST_CHECK_EQUAL(a.getNBins(), 10u); + BOOST_CHECK_EQUAL(a.getMax(), 10.); + BOOST_CHECK_EQUAL(a.getMin(), 0.); + BOOST_CHECK_EQUAL(a.getBinWidth(), 1.); + + // bin index calculation + BOOST_CHECK_EQUAL(a.getBin(-0.3), 0u); + BOOST_CHECK_EQUAL(a.getBin(-0.), 1u); + BOOST_CHECK_EQUAL(a.getBin(0.), 1u); + BOOST_CHECK_EQUAL(a.getBin(0.7), 1u); + BOOST_CHECK_EQUAL(a.getBin(1), 2u); + BOOST_CHECK_EQUAL(a.getBin(1.2), 2u); + BOOST_CHECK_EQUAL(a.getBin(2.), 3u); + BOOST_CHECK_EQUAL(a.getBin(2.7), 3u); + BOOST_CHECK_EQUAL(a.getBin(3.), 4u); + BOOST_CHECK_EQUAL(a.getBin(3.6), 4u); + BOOST_CHECK_EQUAL(a.getBin(4.), 5u); + BOOST_CHECK_EQUAL(a.getBin(4.98), 5u); + BOOST_CHECK_EQUAL(a.getBin(5.), 6u); + BOOST_CHECK_EQUAL(a.getBin(5.12), 6u); + BOOST_CHECK_EQUAL(a.getBin(6.), 7u); + BOOST_CHECK_EQUAL(a.getBin(6.00001), 7u); + BOOST_CHECK_EQUAL(a.getBin(7.), 8u); + BOOST_CHECK_EQUAL(a.getBin(7.5), 8u); + BOOST_CHECK_EQUAL(a.getBin(8.), 9u); + BOOST_CHECK_EQUAL(a.getBin(8.1), 9u); + BOOST_CHECK_EQUAL(a.getBin(9.), 10u); + BOOST_CHECK_EQUAL(a.getBin(9.999), 10u); + BOOST_CHECK_EQUAL(a.getBin(10.), 11u); + BOOST_CHECK_EQUAL(a.getBin(100.3), 11u); + + // lower bin boundaries + BOOST_CHECK_EQUAL(a.getBinLowerBound(1), 0.); + BOOST_CHECK_EQUAL(a.getBinLowerBound(2), 1.); + BOOST_CHECK_EQUAL(a.getBinLowerBound(3), 2.); + BOOST_CHECK_EQUAL(a.getBinLowerBound(4), 3.); + BOOST_CHECK_EQUAL(a.getBinLowerBound(5), 4.); + BOOST_CHECK_EQUAL(a.getBinLowerBound(6), 5.); + BOOST_CHECK_EQUAL(a.getBinLowerBound(7), 6.); + BOOST_CHECK_EQUAL(a.getBinLowerBound(8), 7.); + BOOST_CHECK_EQUAL(a.getBinLowerBound(9), 8.); + BOOST_CHECK_EQUAL(a.getBinLowerBound(10), 9.); + + // upper bin boundaries + BOOST_CHECK_EQUAL(a.getBinUpperBound(1), 1.); + BOOST_CHECK_EQUAL(a.getBinUpperBound(2), 2.); + BOOST_CHECK_EQUAL(a.getBinUpperBound(3), 3.); + BOOST_CHECK_EQUAL(a.getBinUpperBound(4), 4.); + BOOST_CHECK_EQUAL(a.getBinUpperBound(5), 5.); + BOOST_CHECK_EQUAL(a.getBinUpperBound(6), 6.); + BOOST_CHECK_EQUAL(a.getBinUpperBound(7), 7.); + BOOST_CHECK_EQUAL(a.getBinUpperBound(8), 8.); + BOOST_CHECK_EQUAL(a.getBinUpperBound(9), 9.); + BOOST_CHECK_EQUAL(a.getBinUpperBound(10), 10.); + + // bin centers + BOOST_CHECK_EQUAL(a.getBinCenter(1), 0.5); + BOOST_CHECK_EQUAL(a.getBinCenter(2), 1.5); + BOOST_CHECK_EQUAL(a.getBinCenter(3), 2.5); + BOOST_CHECK_EQUAL(a.getBinCenter(4), 3.5); + BOOST_CHECK_EQUAL(a.getBinCenter(5), 4.5); + BOOST_CHECK_EQUAL(a.getBinCenter(6), 5.5); + BOOST_CHECK_EQUAL(a.getBinCenter(7), 6.5); + BOOST_CHECK_EQUAL(a.getBinCenter(8), 7.5); + BOOST_CHECK_EQUAL(a.getBinCenter(9), 8.5); + BOOST_CHECK_EQUAL(a.getBinCenter(10), 9.5); + + // inside check + BOOST_CHECK(not a.isInside(-0.2)); + BOOST_CHECK(a.isInside(0.)); + BOOST_CHECK(a.isInside(3.)); + BOOST_CHECK(not a.isInside(10.)); + BOOST_CHECK(not a.isInside(12.)); +} + +BOOST_AUTO_TEST_CASE(variable_axis) { + VariableAxis a({0, 0.5, 3, 4.5, 6}); + + // general binning properties + BOOST_CHECK_EQUAL(a.getNBins(), 4u); + BOOST_CHECK_EQUAL(a.getMax(), 6.); + BOOST_CHECK_EQUAL(a.getMin(), 0.); + + // bin index calculation + BOOST_CHECK_EQUAL(a.getBin(-0.3), 0u); + BOOST_CHECK_EQUAL(a.getBin(-0.), 1u); + BOOST_CHECK_EQUAL(a.getBin(0.), 1u); + BOOST_CHECK_EQUAL(a.getBin(0.3), 1u); + BOOST_CHECK_EQUAL(a.getBin(0.5), 2u); + BOOST_CHECK_EQUAL(a.getBin(1.2), 2u); + BOOST_CHECK_EQUAL(a.getBin(2.7), 2u); + BOOST_CHECK_EQUAL(a.getBin(3.), 3u); + BOOST_CHECK_EQUAL(a.getBin(4.49999), 3u); + BOOST_CHECK_EQUAL(a.getBin(4.5), 4u); + BOOST_CHECK_EQUAL(a.getBin(5.12), 4u); + BOOST_CHECK_EQUAL(a.getBin(6.), 5u); + BOOST_CHECK_EQUAL(a.getBin(6.00001), 5u); + BOOST_CHECK_EQUAL(a.getBin(7.5), 5u); + + // lower bin boundaries + BOOST_CHECK_EQUAL(a.getBinLowerBound(1), 0.); + BOOST_CHECK_EQUAL(a.getBinLowerBound(2), 0.5); + BOOST_CHECK_EQUAL(a.getBinLowerBound(3), 3.); + BOOST_CHECK_EQUAL(a.getBinLowerBound(4), 4.5); + + // upper bin boundaries + BOOST_CHECK_EQUAL(a.getBinUpperBound(1), 0.5); + BOOST_CHECK_EQUAL(a.getBinUpperBound(2), 3.); + BOOST_CHECK_EQUAL(a.getBinUpperBound(3), 4.5); + BOOST_CHECK_EQUAL(a.getBinUpperBound(4), 6.); + + // bin centers + BOOST_CHECK_EQUAL(a.getBinCenter(1), 0.25); + BOOST_CHECK_EQUAL(a.getBinCenter(2), 1.75); + BOOST_CHECK_EQUAL(a.getBinCenter(3), 3.75); + BOOST_CHECK_EQUAL(a.getBinCenter(4), 5.25); + + // inside check + BOOST_CHECK(not a.isInside(-0.2)); + BOOST_CHECK(a.isInside(0.)); + BOOST_CHECK(a.isInside(3.)); + BOOST_CHECK(not a.isInside(6.)); + BOOST_CHECK(not a.isInside(12.)); +} + +BOOST_AUTO_TEST_CASE(open_axis) { + Axis<AxisType::Equidistant, AxisBoundaryType::Bound> a(0, 10, 10); + + // normal inside + BOOST_CHECK_EQUAL(a.getBin(0.5), 1u); + BOOST_CHECK_EQUAL(a.getBin(9.5), 10u); + + // out of bounds, but is open + // -> should clamp + BOOST_CHECK_EQUAL(a.getBin(-0.5), 1u); + BOOST_CHECK_EQUAL(a.getBin(10.5), 10u); + + Axis<AxisType::Variable, AxisBoundaryType::Bound> b( + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}); + + // normal inside + BOOST_CHECK_EQUAL(b.getBin(0.5), 1u); + BOOST_CHECK_EQUAL(b.getBin(9.5), 10u); + + // out of bounds, but is open + // -> should clamp + BOOST_CHECK_EQUAL(b.getBin(-0.5), 1u); + BOOST_CHECK_EQUAL(b.getBin(10.5), 10u); +} + +BOOST_AUTO_TEST_CASE(closed_axis) { + Axis<AxisType::Equidistant, AxisBoundaryType::Closed> a(0, 10, 10); + + // normal inside + BOOST_CHECK_EQUAL(a.getBin(0.5), 1u); + BOOST_CHECK_EQUAL(a.getBin(9.5), 10u); + + // out of bounds, but is closed + // -> should wrap to opposite side bin + BOOST_CHECK_EQUAL(a.getBin(-0.5), 10u); + BOOST_CHECK_EQUAL(a.getBin(10.5), 1u); + + Axis<AxisType::Variable, AxisBoundaryType::Closed> b( + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}); + + // normal inside + BOOST_CHECK_EQUAL(b.getBin(0.5), 1u); + BOOST_CHECK_EQUAL(b.getBin(9.5), 10u); + + // out of bounds, but is closed + // -> should wrap to opposite side bin + BOOST_CHECK_EQUAL(b.getBin(-0.5), 10u); + BOOST_CHECK_EQUAL(b.getBin(10.5), 1u); +} + +BOOST_AUTO_TEST_CASE(neighborhood) { + using bins_t = std::vector<size_t>; + Axis<AxisType::Equidistant, AxisBoundaryType::Open> a1(0.0, 1.0, 10u); + + BOOST_CHECK(a1.neighborHoodIndices(0, 1).collect() == bins_t({0, 1})); + BOOST_CHECK(a1.neighborHoodIndices(1, 1).collect() == bins_t({0, 1, 2})); + BOOST_CHECK(a1.neighborHoodIndices(11, 1).collect() == bins_t({10, 11})); + BOOST_CHECK(a1.neighborHoodIndices(10, 1).collect() == bins_t({9, 10, 11})); + BOOST_CHECK(a1.neighborHoodIndices(5, 1).collect() == bins_t({4, 5, 6})); + BOOST_CHECK(a1.neighborHoodIndices(5, {1, 0}).collect() == bins_t({4, 5})); + BOOST_CHECK(a1.neighborHoodIndices(5, {0, 1}).collect() == bins_t({5, 6})); + + BOOST_CHECK(a1.neighborHoodIndices(0, 2).collect() == bins_t({0, 1, 2})); + BOOST_CHECK(a1.neighborHoodIndices(1, 2).collect() == bins_t({0, 1, 2, 3})); + BOOST_CHECK(a1.neighborHoodIndices(11, 2).collect() == bins_t({9, 10, 11})); + BOOST_CHECK(a1.neighborHoodIndices(10, 2).collect() == + bins_t({8, 9, 10, 11})); + BOOST_CHECK(a1.neighborHoodIndices(5, 2).collect() == + bins_t({3, 4, 5, 6, 7})); + + Axis<AxisType::Variable, AxisBoundaryType::Open> a2( + {0.0, 2.0, 4.0, 9.0, 10.0}); + BOOST_CHECK(a2.neighborHoodIndices(0, 1).collect() == bins_t({0, 1})); + BOOST_CHECK(a2.neighborHoodIndices(1, 1).collect() == bins_t({0, 1, 2})); + BOOST_CHECK(a2.neighborHoodIndices(5, 1).collect() == bins_t({4, 5})); + BOOST_CHECK(a2.neighborHoodIndices(4, 1).collect() == bins_t({3, 4, 5})); + BOOST_CHECK(a2.neighborHoodIndices(4, {1, 0}).collect() == bins_t({3, 4})); + BOOST_CHECK(a2.neighborHoodIndices(2, 1).collect() == bins_t({1, 2, 3})); + BOOST_CHECK(a2.neighborHoodIndices(2, {0, 1}).collect() == bins_t({2, 3})); + + BOOST_CHECK(a2.neighborHoodIndices(0, 2).collect() == bins_t({0, 1, 2})); + BOOST_CHECK(a2.neighborHoodIndices(1, 2).collect() == bins_t({0, 1, 2, 3})); + BOOST_CHECK(a2.neighborHoodIndices(5, 2).collect() == bins_t({3, 4, 5})); + BOOST_CHECK(a2.neighborHoodIndices(4, 2).collect() == bins_t({2, 3, 4, 5})); + BOOST_CHECK(a2.neighborHoodIndices(3, 2).collect() == + bins_t({1, 2, 3, 4, 5})); + + Axis<AxisType::Equidistant, AxisBoundaryType::Bound> a3(0.0, 1.0, 10u); + + BOOST_CHECK(a3.neighborHoodIndices(0, 1).collect() == bins_t({})); + BOOST_CHECK(a3.neighborHoodIndices(1, 1).collect() == bins_t({1, 2})); + BOOST_CHECK(a3.neighborHoodIndices(11, 1).collect() == bins_t({})); + BOOST_CHECK(a3.neighborHoodIndices(10, 1).collect() == bins_t({9, 10})); + BOOST_CHECK(a3.neighborHoodIndices(10, {0, 1}).collect() == bins_t({10})); + BOOST_CHECK(a3.neighborHoodIndices(5, 1).collect() == bins_t({4, 5, 6})); + BOOST_CHECK(a3.neighborHoodIndices(5, {1, 0}).collect() == bins_t({4, 5})); + BOOST_CHECK(a3.neighborHoodIndices(5, {0, 1}).collect() == bins_t({5, 6})); + + BOOST_CHECK(a3.neighborHoodIndices(0, 2).collect() == bins_t({})); + BOOST_CHECK(a3.neighborHoodIndices(1, 2).collect() == bins_t({1, 2, 3})); + BOOST_CHECK(a3.neighborHoodIndices(11, 2).collect() == bins_t({})); + BOOST_CHECK(a3.neighborHoodIndices(10, 2).collect() == bins_t({8, 9, 10})); + BOOST_CHECK(a3.neighborHoodIndices(5, 2).collect() == + bins_t({3, 4, 5, 6, 7})); + + Axis<AxisType::Equidistant, AxisBoundaryType::Closed> a4(0.0, 1.0, 10u); + + BOOST_CHECK(a4.neighborHoodIndices(0, 1).collect() == bins_t({})); + BOOST_CHECK(a4.neighborHoodIndices(1, 1).collect() == bins_t({10, 1, 2})); + BOOST_CHECK(a4.neighborHoodIndices(11, 1).collect() == bins_t({})); + BOOST_CHECK(a4.neighborHoodIndices(10, 1).collect() == bins_t({9, 10, 1})); + BOOST_CHECK(a4.neighborHoodIndices(10, {0, 1}).collect() == bins_t({10, 1})); + BOOST_CHECK(a4.neighborHoodIndices(5, 1).collect() == bins_t({4, 5, 6})); + BOOST_CHECK(a4.neighborHoodIndices(5, {1, 0}).collect() == bins_t({4, 5})); + BOOST_CHECK(a4.neighborHoodIndices(5, {0, 1}).collect() == bins_t({5, 6})); + + BOOST_CHECK(a4.neighborHoodIndices(0, 2).collect() == bins_t({})); + BOOST_CHECK(a4.neighborHoodIndices(1, 2).collect() == + bins_t({9, 10, 1, 2, 3})); + BOOST_CHECK(a4.neighborHoodIndices(11, 2).collect() == bins_t({})); + BOOST_CHECK(a4.neighborHoodIndices(10, 2).collect() == + bins_t({8, 9, 10, 1, 2})); + BOOST_CHECK(a4.neighborHoodIndices(5, 2).collect() == + bins_t({3, 4, 5, 6, 7})); + + Axis<AxisType::Variable, AxisBoundaryType::Bound> a5( + {0.0, 2.0, 4.0, 9.0, 9.5, 10.0}); + BOOST_CHECK(a5.neighborHoodIndices(0, 1).collect() == bins_t({})); + BOOST_CHECK(a5.neighborHoodIndices(1, 1).collect() == bins_t({1, 2})); + BOOST_CHECK(a5.neighborHoodIndices(6, 1).collect() == bins_t({})); + BOOST_CHECK(a5.neighborHoodIndices(5, 1).collect() == bins_t({4, 5})); + BOOST_CHECK(a5.neighborHoodIndices(5, {0, 1}).collect() == bins_t({5})); + BOOST_CHECK(a5.neighborHoodIndices(2, 1).collect() == bins_t({1, 2, 3})); + BOOST_CHECK(a5.neighborHoodIndices(2, {1, 0}).collect() == bins_t({1, 2})); + BOOST_CHECK(a5.neighborHoodIndices(2, {0, 1}).collect() == bins_t({2, 3})); + + BOOST_CHECK(a5.neighborHoodIndices(0, 2).collect() == bins_t({})); + BOOST_CHECK(a5.neighborHoodIndices(1, 2).collect() == bins_t({1, 2, 3})); + BOOST_CHECK(a5.neighborHoodIndices(6, 2).collect() == bins_t({})); + BOOST_CHECK(a5.neighborHoodIndices(5, 2).collect() == bins_t({3, 4, 5})); + BOOST_CHECK(a5.neighborHoodIndices(3, 2).collect() == + bins_t({1, 2, 3, 4, 5})); + + Axis<AxisType::Variable, AxisBoundaryType::Closed> a6( + {0.0, 2.0, 4.0, 9.0, 9.5, 10.0}); + BOOST_CHECK(a6.neighborHoodIndices(0, 1).collect() == bins_t({})); + BOOST_CHECK(a6.neighborHoodIndices(1, 1).collect() == bins_t({5, 1, 2})); + BOOST_CHECK(a6.neighborHoodIndices(6, 1).collect() == bins_t({})); + BOOST_CHECK(a6.neighborHoodIndices(5, 1).collect() == bins_t({4, 5, 1})); + BOOST_CHECK(a6.neighborHoodIndices(5, {0, 1}).collect() == bins_t({5, 1})); + BOOST_CHECK(a6.neighborHoodIndices(2, 1).collect() == bins_t({1, 2, 3})); + BOOST_CHECK(a6.neighborHoodIndices(2, {1, 0}).collect() == bins_t({1, 2})); + BOOST_CHECK(a6.neighborHoodIndices(2, {0, 1}).collect() == bins_t({2, 3})); + + BOOST_CHECK(a6.neighborHoodIndices(0, 2).collect() == bins_t({})); + BOOST_CHECK(a6.neighborHoodIndices(1, 2).collect() == + bins_t({4, 5, 1, 2, 3})); + BOOST_CHECK(a6.neighborHoodIndices(6, 2).collect() == bins_t({})); + BOOST_CHECK(a6.neighborHoodIndices(5, 2).collect() == + bins_t({3, 4, 5, 1, 2})); + BOOST_CHECK(a6.neighborHoodIndices(3, 2).collect() == + bins_t({1, 2, 3, 4, 5})); + BOOST_CHECK(a6.neighborHoodIndices(3, {0, 2}).collect() == bins_t({3, 4, 5})); + + BOOST_CHECK(a6.neighborHoodIndices(1, 3).collect() == + bins_t({3, 4, 5, 1, 2})); + BOOST_CHECK(a6.neighborHoodIndices(5, 3).collect() == + bins_t({2, 3, 4, 5, 1})); +} + +BOOST_AUTO_TEST_CASE(wrapBin) { + Axis<AxisType::Equidistant, AxisBoundaryType::Open> a1(0.0, 1.0, 10u); + BOOST_CHECK_EQUAL(a1.wrapBin(0), 0); + BOOST_CHECK_EQUAL(a1.wrapBin(1), 1); + BOOST_CHECK_EQUAL(a1.wrapBin(-1), 0); + BOOST_CHECK_EQUAL(a1.wrapBin(10), 10); + BOOST_CHECK_EQUAL(a1.wrapBin(11), 11); + BOOST_CHECK_EQUAL(a1.wrapBin(12), 11); + + Axis<AxisType::Equidistant, AxisBoundaryType::Bound> a2(0.0, 1.0, 10u); + BOOST_CHECK_EQUAL(a2.wrapBin(0), 1); + BOOST_CHECK_EQUAL(a2.wrapBin(1), 1); + BOOST_CHECK_EQUAL(a2.wrapBin(-1), 1); + BOOST_CHECK_EQUAL(a2.wrapBin(10), 10); + BOOST_CHECK_EQUAL(a2.wrapBin(11), 10); + BOOST_CHECK_EQUAL(a2.wrapBin(12), 10); + + Axis<AxisType::Equidistant, AxisBoundaryType::Closed> a3(0.0, 1.0, 10u); + BOOST_CHECK_EQUAL(a3.wrapBin(0), 10); + BOOST_CHECK_EQUAL(a3.wrapBin(1), 1); + BOOST_CHECK_EQUAL(a3.wrapBin(-1), 9); + BOOST_CHECK_EQUAL(a3.wrapBin(10), 10); + BOOST_CHECK_EQUAL(a3.wrapBin(11), 1); + BOOST_CHECK_EQUAL(a3.wrapBin(12), 2); + + Axis<AxisType::Variable, AxisBoundaryType::Open> a4( + {0.0, 2.0, 4.0, 9.0, 10.0}); + BOOST_CHECK_EQUAL(a4.wrapBin(0), 0); + BOOST_CHECK_EQUAL(a4.wrapBin(1), 1); + BOOST_CHECK_EQUAL(a4.wrapBin(-1), 0); + BOOST_CHECK_EQUAL(a4.wrapBin(4), 4); + BOOST_CHECK_EQUAL(a4.wrapBin(5), 5); + BOOST_CHECK_EQUAL(a4.wrapBin(6), 5); + + Axis<AxisType::Variable, AxisBoundaryType::Bound> a5( + {0.0, 2.0, 4.0, 9.0, 9.5, 10.0}); + BOOST_CHECK_EQUAL(a5.wrapBin(0), 1); + BOOST_CHECK_EQUAL(a5.wrapBin(1), 1); + BOOST_CHECK_EQUAL(a5.wrapBin(-1), 1); + BOOST_CHECK_EQUAL(a5.wrapBin(4), 4); + BOOST_CHECK_EQUAL(a5.wrapBin(5), 5); + BOOST_CHECK_EQUAL(a5.wrapBin(6), 5); + + Axis<AxisType::Variable, AxisBoundaryType::Closed> a6( + {0.0, 2.0, 4.0, 9.0, 9.5, 10.0}); + BOOST_CHECK_EQUAL(a6.wrapBin(0), 5); + BOOST_CHECK_EQUAL(a6.wrapBin(1), 1); + BOOST_CHECK_EQUAL(a6.wrapBin(-1), 4); + BOOST_CHECK_EQUAL(a6.wrapBin(4), 4); + BOOST_CHECK_EQUAL(a6.wrapBin(5), 5); + BOOST_CHECK_EQUAL(a6.wrapBin(6), 1); + BOOST_CHECK_EQUAL(a6.wrapBin(7), 2); +} } // namespace Test diff --git a/Tests/Core/Utilities/BFieldMapUtilsTests.cpp b/Tests/Core/Utilities/BFieldMapUtilsTests.cpp index 56737daa894e013288cdb1fc37dc59c96457d0e8..2cf707f3ad773e42433309a258fd3e1d5756a364 100644 --- a/Tests/Core/Utilities/BFieldMapUtilsTests.cpp +++ b/Tests/Core/Utilities/BFieldMapUtilsTests.cpp @@ -28,363 +28,332 @@ using namespace detail; namespace Test { - BOOST_AUTO_TEST_CASE(bfield_creation) - { - // create grid values - std::vector<double> rPos = {0., 1., 2.}; - std::vector<double> xPos = {0., 1., 2.}; - std::vector<double> yPos = {0., 1., 2.}; - std::vector<double> zPos = {0., 1., 2.}; - - // create b field in rz - std::vector<Acts::Vector2D> bField_rz; - for (int i = 0; i < 9; i++) { - bField_rz.push_back(Acts::Vector2D(i, i)); - } - - auto localToGlobalBin_rz - = [](std::array<size_t, 2> binsRZ, std::array<size_t, 2> nBinsRZ) { - return (binsRZ.at(1) * nBinsRZ.at(0) + binsRZ.at(0)); - }; - // create b field mapper in rz - auto mapper_rz = Acts::fieldMapperRZ( - localToGlobalBin_rz, rPos, zPos, bField_rz, 1, 1, false); - // check number of bins, minima & maxima - std::vector<size_t> nBins_rz = {rPos.size(), zPos.size()}; - std::vector<double> minima_rz = {0., 0.}; - std::vector<double> maxima_rz = {3., 3.}; - BOOST_CHECK(mapper_rz.getNBins() == nBins_rz); - // check minimum (should be first value because bin values are always - // assigned to the left boundary) - BOOST_CHECK(mapper_rz.getMin() == minima_rz); - // check maximum (should be last value + 1 step because bin values are - // always assigned to the left boundary) - BOOST_CHECK(mapper_rz.getMax() == maxima_rz); - - // create b field in xyz - std::vector<Acts::Vector3D> bField_xyz; - for (int i = 0; i < 27; i++) { - bField_xyz.push_back(Acts::Vector3D(i, i, i)); - } - - auto localToGlobalBin_xyz - = [](std::array<size_t, 3> binsXYZ, std::array<size_t, 3> nBinsXYZ) { - return (binsXYZ.at(0) * (nBinsXYZ.at(1) * nBinsXYZ.at(2)) - + binsXYZ.at(1) * nBinsXYZ.at(2) - + binsXYZ.at(2)); - }; - - // create b field mapper in xyz - auto mapper_xyz = Acts::fieldMapperXYZ( - localToGlobalBin_xyz, xPos, yPos, zPos, bField_xyz, 1, 1, false); - // check number of bins, minima & maxima - std::vector<size_t> nBins_xyz = {xPos.size(), yPos.size(), zPos.size()}; - std::vector<double> minima_xyz = {0., 0., 0.}; - std::vector<double> maxima_xyz = {3., 3., 3.}; - BOOST_CHECK(mapper_xyz.getNBins() == nBins_xyz); - // check minimum (should be first value because bin values are always - // assigned to the left boundary) - BOOST_CHECK(mapper_xyz.getMin() == minima_xyz); - // check maximum (should be last value + 1 step because bin values are - // always assigned to the left boundary) - BOOST_CHECK(mapper_xyz.getMax() == maxima_xyz); - - // check if filled value is expected value in rz - Acts::Vector3D pos0_rz(0., 0., 0.); - Acts::Vector3D pos1_rz(1., 0., 1.); - Acts::Vector3D pos2_rz(0., 2., 2.); - auto value0_rz = mapper_rz.getField(pos0_rz); - auto value1_rz = mapper_rz.getField(pos1_rz); - auto value2_rz = mapper_rz.getField(pos2_rz); - // calculate what the value should be at this point - auto b0_rz = bField_rz.at( - localToGlobalBin_rz({{0, 0}}, {{rPos.size(), zPos.size()}})); - auto b1_rz = bField_rz.at( - localToGlobalBin_rz({{1, 1}}, {{rPos.size(), zPos.size()}})); - auto b2_rz = bField_rz.at( - localToGlobalBin_rz({{2, 2}}, {{rPos.size(), zPos.size()}})); - Acts::Vector3D bField0_rz(b0_rz.x(), 0., b0_rz.y()); - Acts::Vector3D bField1_rz(b1_rz.x(), 0., b1_rz.y()); - Acts::Vector3D bField2_rz(0., b2_rz.x(), b2_rz.y()); - // check the value - // in rz case field is phi symmetric (check radius) - CHECK_CLOSE_ABS(perp(value0_rz), perp(bField0_rz), 1e-9); - CHECK_CLOSE_ABS(value0_rz.z(), bField0_rz.z(), 1e-9); - CHECK_CLOSE_ABS(perp(value1_rz), perp(bField1_rz), 1e-9); - CHECK_CLOSE_ABS(value1_rz.z(), bField1_rz.z(), 1e-9); - CHECK_CLOSE_ABS(perp(value2_rz), perp(bField2_rz), 1e-9); - CHECK_CLOSE_ABS(value2_rz.z(), bField2_rz.z(), 1e-9); - - // check if filled value is expected value in rz - Acts::Vector3D pos0_xyz(0., 0., 0.); - Acts::Vector3D pos1_xyz(1., 1., 1.); - Acts::Vector3D pos2_xyz(2., 2., 2.); - auto value0_xyz = mapper_xyz.getField(pos0_xyz); - auto value1_xyz = mapper_xyz.getField(pos1_xyz); - auto value2_xyz = mapper_xyz.getField(pos2_xyz); - // calculate what the value should be at this point - auto b0_xyz = bField_xyz.at(localToGlobalBin_xyz( - {{0, 0, 0}}, {{xPos.size(), yPos.size(), zPos.size()}})); - auto b1_xyz = bField_xyz.at(localToGlobalBin_xyz( - {{1, 1, 1}}, {{xPos.size(), yPos.size(), zPos.size()}})); - auto b2_xyz = bField_xyz.at(localToGlobalBin_xyz( - {{2, 2, 2}}, {{xPos.size(), yPos.size(), zPos.size()}})); - // check the value - BOOST_CHECK_EQUAL(value0_xyz, b0_xyz); - BOOST_CHECK_EQUAL(value1_xyz, b1_xyz); - BOOST_CHECK_EQUAL(value2_xyz, b2_xyz); - - // checkx-,y-,z-symmetry - need to check close (because of interpolation - // there can be small differences) - CHECK_CLOSE_ABS(value0_xyz, b0_xyz, 1e-9); - CHECK_CLOSE_ABS(value1_xyz, b1_xyz, 1e-9); - CHECK_CLOSE_ABS(value2_xyz, b2_xyz, 1e-9); +BOOST_AUTO_TEST_CASE(bfield_creation) { + // create grid values + std::vector<double> rPos = {0., 1., 2.}; + std::vector<double> xPos = {0., 1., 2.}; + std::vector<double> yPos = {0., 1., 2.}; + std::vector<double> zPos = {0., 1., 2.}; + + // create b field in rz + std::vector<Acts::Vector2D> bField_rz; + for (int i = 0; i < 9; i++) { + bField_rz.push_back(Acts::Vector2D(i, i)); } - BOOST_AUTO_TEST_CASE(bfield_symmetry) - { - // create grid values - std::vector<double> rPos = {0., 1., 2.}; - std::vector<double> xPos = {0., 1., 2.}; - std::vector<double> yPos = {0., 1., 2.}; - std::vector<double> zPos = {0., 1., 2.}; - // the bfield values in rz - std::vector<Acts::Vector2D> bField_rz; - for (int i = 0; i < 9; i++) { - bField_rz.push_back(Acts::Vector2D(i, i)); - } - // the field mapper in rz - auto mapper_rz = Acts::fieldMapperRZ( - [](std::array<size_t, 2> binsRZ, std::array<size_t, 2> nBinsRZ) { - return (binsRZ.at(1) * nBinsRZ.at(0) + binsRZ.at(0)); - }, - rPos, - zPos, - bField_rz, - 1, - 1, - true); - - // check number of bins, minima & maxima - std::vector<size_t> nBins_rz = {rPos.size(), 2 * zPos.size() - 1}; - std::vector<double> minima_rz = {0., -2.}; - std::vector<double> maxima_rz = {3., 3.}; - BOOST_CHECK(mapper_rz.getNBins() == nBins_rz); - auto vec = mapper_rz.getNBins(); - auto vec0 = mapper_rz.getMin(); - // check minimum (should be first value because bin values are always - // assigned to the left boundary) - BOOST_CHECK(mapper_rz.getMin() == minima_rz); - // check maximum (should be last value + 1 step because bin values are - // always assigned to the left boundary) - BOOST_CHECK(mapper_rz.getMax() == maxima_rz); - - // the bfield values in xyz - std::vector<Acts::Vector3D> bField_xyz; - for (int i = 0; i < 27; i++) { - bField_xyz.push_back(Acts::Vector3D(i, i, i)); - } - // the field mapper in xyz - auto mapper_xyz = Acts::fieldMapperXYZ( - [](std::array<size_t, 3> binsXYZ, std::array<size_t, 3> nBinsXYZ) { - return (binsXYZ.at(0) * (nBinsXYZ.at(1) * nBinsXYZ.at(2)) - + binsXYZ.at(1) * nBinsXYZ.at(2) - + binsXYZ.at(2)); - }, - xPos, - yPos, - zPos, - bField_xyz, - 1, - 1, - true); - - // check number of bins, minima & maxima - std::vector<size_t> nBins_xyz - = {2 * xPos.size() - 1, 2 * yPos.size() - 1, 2 * zPos.size() - 1}; - std::vector<double> minima_xyz = {-2., -2., -2.}; - std::vector<double> maxima_xyz = {3., 3., 3.}; - BOOST_CHECK(mapper_xyz.getNBins() == nBins_xyz); - // check minimum (should be first value because bin values are always - // assigned to the left boundary) - BOOST_CHECK(mapper_xyz.getMin() == minima_xyz); - // check maximum (should be last value + 1 step because bin values are - // always assigned to the left boundary) - BOOST_CHECK(mapper_xyz.getMax() == maxima_xyz); - - Acts::Vector3D pos0(1.2, 1.3, 1.4); - Acts::Vector3D pos1(1.2, 1.3, -1.4); - Acts::Vector3D pos2(-1.2, 1.3, 1.4); - Acts::Vector3D pos3(1.2, -1.3, 1.4); - Acts::Vector3D pos4(-1.2, -1.3, 1.4); - - auto value0_rz = mapper_rz.getField(pos0); - auto value1_rz = mapper_rz.getField(pos1); - auto value2_rz = mapper_rz.getField(pos2); - auto value3_rz = mapper_rz.getField(pos3); - auto value4_rz = mapper_rz.getField(pos4); - - auto value0_xyz = mapper_xyz.getField(pos0); - auto value1_xyz = mapper_xyz.getField(pos1); - auto value2_xyz = mapper_xyz.getField(pos2); - auto value3_xyz = mapper_xyz.getField(pos3); - auto value4_xyz = mapper_xyz.getField(pos4); - - // check z- and phi-symmetry - CHECK_CLOSE_REL(perp(value0_rz), perp(value1_rz), 1e-10); - CHECK_CLOSE_REL(value0_rz.z(), value1_rz.z(), 1e-10); - CHECK_CLOSE_REL(perp(value0_rz), perp(value2_rz), 1e-10); - CHECK_CLOSE_REL(value0_rz.z(), value2_rz.z(), 1e-10); - CHECK_CLOSE_REL(perp(value0_rz), perp(value3_rz), 1e-10); - CHECK_CLOSE_REL(value0_rz.z(), value3_rz.z(), 1e-10); - CHECK_CLOSE_REL(perp(value0_rz), perp(value4_rz), 1e-10); - CHECK_CLOSE_REL(value0_rz.z(), value4_rz.z(), 1e-10); - - // checkx-,y-,z-symmetry - need to check close (because of interpolation - // there can be small differences) - CHECK_CLOSE_REL(value0_xyz, value1_xyz, 1e-10); - CHECK_CLOSE_REL(value0_xyz, value2_xyz, 1e-10); - CHECK_CLOSE_REL(value0_xyz, value3_xyz, 1e-10); - CHECK_CLOSE_REL(value0_xyz, value4_xyz, 1e-10); + auto localToGlobalBin_rz = [](std::array<size_t, 2> binsRZ, + std::array<size_t, 2> nBinsRZ) { + return (binsRZ.at(1) * nBinsRZ.at(0) + binsRZ.at(0)); + }; + // create b field mapper in rz + auto mapper_rz = Acts::fieldMapperRZ(localToGlobalBin_rz, rPos, zPos, + bField_rz, 1, 1, false); + // check number of bins, minima & maxima + std::vector<size_t> nBins_rz = {rPos.size(), zPos.size()}; + std::vector<double> minima_rz = {0., 0.}; + std::vector<double> maxima_rz = {3., 3.}; + BOOST_CHECK(mapper_rz.getNBins() == nBins_rz); + // check minimum (should be first value because bin values are always + // assigned to the left boundary) + BOOST_CHECK(mapper_rz.getMin() == minima_rz); + // check maximum (should be last value + 1 step because bin values are + // always assigned to the left boundary) + BOOST_CHECK(mapper_rz.getMax() == maxima_rz); + + // create b field in xyz + std::vector<Acts::Vector3D> bField_xyz; + for (int i = 0; i < 27; i++) { + bField_xyz.push_back(Acts::Vector3D(i, i, i)); } - /// Unit test for testing the decomposeToSurfaces() function - BOOST_DATA_TEST_CASE( - bfield_symmetry_random, - bdata::random((bdata::seed = 0, - bdata::distribution - = std::uniform_real_distribution<>(-10., 10.))) - ^ bdata::random((bdata::seed = 0, - bdata::distribution - = std::uniform_real_distribution<>(-10., 10.))) - ^ bdata::random((bdata::seed = 0, - bdata::distribution - = std::uniform_real_distribution<>(-20., 20.))) - ^ bdata::xrange(10), - x, - y, - z, - index) - { - (void)index; - - std::vector<double> rPos; - std::vector<double> xPos; - std::vector<double> yPos; - std::vector<double> zPos; - double maxR = 20.; - double maxZ = 30.; - double maxBr = 10.; - double maxBz = 20.; - size_t nBins = 10; - double stepR = maxR / nBins; - double stepZ = maxZ / nBins; - double bStepR = maxBr / nBins; - double bStepZ = maxBz / nBins; - - for (size_t i = 0; i < nBins; i++) { - rPos.push_back(i * stepR); - xPos.push_back(i * stepR); - yPos.push_back(i * stepR); - zPos.push_back(i * stepZ); - } - // bfield in rz - std::vector<Acts::Vector2D> bField_rz; - for (size_t i = 0; i < nBins * nBins; i++) { - bField_rz.push_back(Acts::Vector2D(i * bStepR, i * bStepZ)); - } - // the mapper in rz - auto mapper_rz = Acts::fieldMapperRZ( - [](std::array<size_t, 2> binsRZ, std::array<size_t, 2> nBinsRZ) { - return (binsRZ.at(1) * nBinsRZ.at(0) + binsRZ.at(0)); - }, - rPos, - zPos, - bField_rz, - 1, - 1, - true); - - // check number of bins, minima & maxima - std::vector<size_t> nBins_rz = {rPos.size(), 2 * zPos.size() - 1}; - std::vector<double> minima_rz = {0., -((nBins - 1) * stepZ)}; - std::vector<double> maxima_rz = {nBins * stepR, nBins * stepZ}; - BOOST_CHECK(mapper_rz.getNBins() == nBins_rz); - // check minimum (should be first value because bin values are always - // assigned to the left boundary) - CHECK_CLOSE_ABS(mapper_rz.getMin(), minima_rz, 1e-10); - // check maximum (should be last value + 1 step because bin values are - // always assigned to the left boundary) - CHECK_CLOSE_ABS(mapper_rz.getMax(), maxima_rz, 1e-10); - - // bfield in xyz - std::vector<Acts::Vector3D> bField_xyz; - for (size_t i = 0; i < nBins * nBins * nBins; i++) { - bField_xyz.push_back(Acts::Vector3D(i * bStepR, i * bStepR, i * bStepZ)); - } - // the mapper in xyz - auto mapper_xyz = Acts::fieldMapperXYZ( - [](std::array<size_t, 3> binsXYZ, std::array<size_t, 3> nBinsXYZ) { - return (binsXYZ.at(0) * (nBinsXYZ.at(1) * nBinsXYZ.at(2)) - + binsXYZ.at(1) * nBinsXYZ.at(2) - + binsXYZ.at(2)); - }, - xPos, - yPos, - zPos, - bField_xyz, - 1, - 1, - true); - // check number of bins, minima & maxima - std::vector<size_t> nBins_xyz - = {2 * xPos.size() - 1, 2 * yPos.size() - 1, 2 * zPos.size() - 1}; - std::vector<double> minima_xyz = { - -((nBins - 1) * stepR), -((nBins - 1) * stepR), -((nBins - 1) * stepZ)}; - std::vector<double> maxima_xyz - = {nBins * stepR, nBins * stepR, nBins * stepZ}; - BOOST_CHECK(mapper_xyz.getNBins() == nBins_xyz); - // check minimum (should be first value because bin values are always - // assigned to the left boundary) - CHECK_CLOSE_REL(mapper_xyz.getMin(), minima_xyz, 1e-10); - // check maximum (should be last value + 1 step because bin values are - // always assigned to the left boundary) - CHECK_CLOSE_REL(mapper_xyz.getMax(), maxima_xyz, 1e-10); - - Acts::Vector3D pos0(x, y, z); - Acts::Vector3D pos1(x, y, -z); - Acts::Vector3D pos2(-x, y, z); - Acts::Vector3D pos3(x, -y, z); - Acts::Vector3D pos4(-x, -y, z); - - auto value0_rz = mapper_rz.getField(pos0); - auto value1_rz = mapper_rz.getField(pos1); - auto value2_rz = mapper_rz.getField(pos2); - auto value3_rz = mapper_rz.getField(pos3); - auto value4_rz = mapper_rz.getField(pos4); - - // check z- and phi-symmetry - CHECK_CLOSE_REL(perp(value0_rz), perp(value1_rz), 1e-10); - CHECK_CLOSE_REL(value0_rz.z(), value1_rz.z(), 1e-10); - CHECK_CLOSE_REL(perp(value0_rz), perp(value2_rz), 1e-10); - CHECK_CLOSE_REL(value0_rz.z(), value2_rz.z(), 1e-10); - CHECK_CLOSE_REL(perp(value0_rz), perp(value3_rz), 1e-10); - CHECK_CLOSE_REL(value0_rz.z(), value3_rz.z(), 1e-10); - CHECK_CLOSE_REL(perp(value0_rz), perp(value4_rz), 1e-10); - CHECK_CLOSE_REL(value0_rz.z(), value4_rz.z(), 1e-10); - - auto value0_xyz = mapper_xyz.getField(pos0); - auto value1_xyz = mapper_xyz.getField(pos1); - auto value2_xyz = mapper_xyz.getField(pos2); - auto value3_xyz = mapper_xyz.getField(pos3); - auto value4_xyz = mapper_xyz.getField(pos4); - - // checkx-,y-,z-symmetry - need to check close (because of interpolation - // there can be small differences) - CHECK_CLOSE_REL(value0_xyz, value1_xyz, 1e-10); - CHECK_CLOSE_REL(value0_xyz, value2_xyz, 1e-10); - CHECK_CLOSE_REL(value0_xyz, value3_xyz, 1e-10); - CHECK_CLOSE_REL(value0_xyz, value4_xyz, 1e-10); + auto localToGlobalBin_xyz = [](std::array<size_t, 3> binsXYZ, + std::array<size_t, 3> nBinsXYZ) { + return (binsXYZ.at(0) * (nBinsXYZ.at(1) * nBinsXYZ.at(2)) + + binsXYZ.at(1) * nBinsXYZ.at(2) + binsXYZ.at(2)); + }; + + // create b field mapper in xyz + auto mapper_xyz = Acts::fieldMapperXYZ(localToGlobalBin_xyz, xPos, yPos, zPos, + bField_xyz, 1, 1, false); + // check number of bins, minima & maxima + std::vector<size_t> nBins_xyz = {xPos.size(), yPos.size(), zPos.size()}; + std::vector<double> minima_xyz = {0., 0., 0.}; + std::vector<double> maxima_xyz = {3., 3., 3.}; + BOOST_CHECK(mapper_xyz.getNBins() == nBins_xyz); + // check minimum (should be first value because bin values are always + // assigned to the left boundary) + BOOST_CHECK(mapper_xyz.getMin() == minima_xyz); + // check maximum (should be last value + 1 step because bin values are + // always assigned to the left boundary) + BOOST_CHECK(mapper_xyz.getMax() == maxima_xyz); + + // check if filled value is expected value in rz + Acts::Vector3D pos0_rz(0., 0., 0.); + Acts::Vector3D pos1_rz(1., 0., 1.); + Acts::Vector3D pos2_rz(0., 2., 2.); + auto value0_rz = mapper_rz.getField(pos0_rz); + auto value1_rz = mapper_rz.getField(pos1_rz); + auto value2_rz = mapper_rz.getField(pos2_rz); + // calculate what the value should be at this point + auto b0_rz = + bField_rz.at(localToGlobalBin_rz({{0, 0}}, {{rPos.size(), zPos.size()}})); + auto b1_rz = + bField_rz.at(localToGlobalBin_rz({{1, 1}}, {{rPos.size(), zPos.size()}})); + auto b2_rz = + bField_rz.at(localToGlobalBin_rz({{2, 2}}, {{rPos.size(), zPos.size()}})); + Acts::Vector3D bField0_rz(b0_rz.x(), 0., b0_rz.y()); + Acts::Vector3D bField1_rz(b1_rz.x(), 0., b1_rz.y()); + Acts::Vector3D bField2_rz(0., b2_rz.x(), b2_rz.y()); + // check the value + // in rz case field is phi symmetric (check radius) + CHECK_CLOSE_ABS(perp(value0_rz), perp(bField0_rz), 1e-9); + CHECK_CLOSE_ABS(value0_rz.z(), bField0_rz.z(), 1e-9); + CHECK_CLOSE_ABS(perp(value1_rz), perp(bField1_rz), 1e-9); + CHECK_CLOSE_ABS(value1_rz.z(), bField1_rz.z(), 1e-9); + CHECK_CLOSE_ABS(perp(value2_rz), perp(bField2_rz), 1e-9); + CHECK_CLOSE_ABS(value2_rz.z(), bField2_rz.z(), 1e-9); + + // check if filled value is expected value in rz + Acts::Vector3D pos0_xyz(0., 0., 0.); + Acts::Vector3D pos1_xyz(1., 1., 1.); + Acts::Vector3D pos2_xyz(2., 2., 2.); + auto value0_xyz = mapper_xyz.getField(pos0_xyz); + auto value1_xyz = mapper_xyz.getField(pos1_xyz); + auto value2_xyz = mapper_xyz.getField(pos2_xyz); + // calculate what the value should be at this point + auto b0_xyz = bField_xyz.at(localToGlobalBin_xyz( + {{0, 0, 0}}, {{xPos.size(), yPos.size(), zPos.size()}})); + auto b1_xyz = bField_xyz.at(localToGlobalBin_xyz( + {{1, 1, 1}}, {{xPos.size(), yPos.size(), zPos.size()}})); + auto b2_xyz = bField_xyz.at(localToGlobalBin_xyz( + {{2, 2, 2}}, {{xPos.size(), yPos.size(), zPos.size()}})); + // check the value + BOOST_CHECK_EQUAL(value0_xyz, b0_xyz); + BOOST_CHECK_EQUAL(value1_xyz, b1_xyz); + BOOST_CHECK_EQUAL(value2_xyz, b2_xyz); + + // checkx-,y-,z-symmetry - need to check close (because of interpolation + // there can be small differences) + CHECK_CLOSE_ABS(value0_xyz, b0_xyz, 1e-9); + CHECK_CLOSE_ABS(value1_xyz, b1_xyz, 1e-9); + CHECK_CLOSE_ABS(value2_xyz, b2_xyz, 1e-9); +} + +BOOST_AUTO_TEST_CASE(bfield_symmetry) { + // create grid values + std::vector<double> rPos = {0., 1., 2.}; + std::vector<double> xPos = {0., 1., 2.}; + std::vector<double> yPos = {0., 1., 2.}; + std::vector<double> zPos = {0., 1., 2.}; + // the bfield values in rz + std::vector<Acts::Vector2D> bField_rz; + for (int i = 0; i < 9; i++) { + bField_rz.push_back(Acts::Vector2D(i, i)); } + // the field mapper in rz + auto mapper_rz = Acts::fieldMapperRZ( + [](std::array<size_t, 2> binsRZ, std::array<size_t, 2> nBinsRZ) { + return (binsRZ.at(1) * nBinsRZ.at(0) + binsRZ.at(0)); + }, + rPos, zPos, bField_rz, 1, 1, true); + + // check number of bins, minima & maxima + std::vector<size_t> nBins_rz = {rPos.size(), 2 * zPos.size() - 1}; + std::vector<double> minima_rz = {0., -2.}; + std::vector<double> maxima_rz = {3., 3.}; + BOOST_CHECK(mapper_rz.getNBins() == nBins_rz); + auto vec = mapper_rz.getNBins(); + auto vec0 = mapper_rz.getMin(); + // check minimum (should be first value because bin values are always + // assigned to the left boundary) + BOOST_CHECK(mapper_rz.getMin() == minima_rz); + // check maximum (should be last value + 1 step because bin values are + // always assigned to the left boundary) + BOOST_CHECK(mapper_rz.getMax() == maxima_rz); + + // the bfield values in xyz + std::vector<Acts::Vector3D> bField_xyz; + for (int i = 0; i < 27; i++) { + bField_xyz.push_back(Acts::Vector3D(i, i, i)); + } + // the field mapper in xyz + auto mapper_xyz = Acts::fieldMapperXYZ( + [](std::array<size_t, 3> binsXYZ, std::array<size_t, 3> nBinsXYZ) { + return (binsXYZ.at(0) * (nBinsXYZ.at(1) * nBinsXYZ.at(2)) + + binsXYZ.at(1) * nBinsXYZ.at(2) + binsXYZ.at(2)); + }, + xPos, yPos, zPos, bField_xyz, 1, 1, true); + + // check number of bins, minima & maxima + std::vector<size_t> nBins_xyz = {2 * xPos.size() - 1, 2 * yPos.size() - 1, + 2 * zPos.size() - 1}; + std::vector<double> minima_xyz = {-2., -2., -2.}; + std::vector<double> maxima_xyz = {3., 3., 3.}; + BOOST_CHECK(mapper_xyz.getNBins() == nBins_xyz); + // check minimum (should be first value because bin values are always + // assigned to the left boundary) + BOOST_CHECK(mapper_xyz.getMin() == minima_xyz); + // check maximum (should be last value + 1 step because bin values are + // always assigned to the left boundary) + BOOST_CHECK(mapper_xyz.getMax() == maxima_xyz); + + Acts::Vector3D pos0(1.2, 1.3, 1.4); + Acts::Vector3D pos1(1.2, 1.3, -1.4); + Acts::Vector3D pos2(-1.2, 1.3, 1.4); + Acts::Vector3D pos3(1.2, -1.3, 1.4); + Acts::Vector3D pos4(-1.2, -1.3, 1.4); + + auto value0_rz = mapper_rz.getField(pos0); + auto value1_rz = mapper_rz.getField(pos1); + auto value2_rz = mapper_rz.getField(pos2); + auto value3_rz = mapper_rz.getField(pos3); + auto value4_rz = mapper_rz.getField(pos4); + + auto value0_xyz = mapper_xyz.getField(pos0); + auto value1_xyz = mapper_xyz.getField(pos1); + auto value2_xyz = mapper_xyz.getField(pos2); + auto value3_xyz = mapper_xyz.getField(pos3); + auto value4_xyz = mapper_xyz.getField(pos4); + + // check z- and phi-symmetry + CHECK_CLOSE_REL(perp(value0_rz), perp(value1_rz), 1e-10); + CHECK_CLOSE_REL(value0_rz.z(), value1_rz.z(), 1e-10); + CHECK_CLOSE_REL(perp(value0_rz), perp(value2_rz), 1e-10); + CHECK_CLOSE_REL(value0_rz.z(), value2_rz.z(), 1e-10); + CHECK_CLOSE_REL(perp(value0_rz), perp(value3_rz), 1e-10); + CHECK_CLOSE_REL(value0_rz.z(), value3_rz.z(), 1e-10); + CHECK_CLOSE_REL(perp(value0_rz), perp(value4_rz), 1e-10); + CHECK_CLOSE_REL(value0_rz.z(), value4_rz.z(), 1e-10); + + // checkx-,y-,z-symmetry - need to check close (because of interpolation + // there can be small differences) + CHECK_CLOSE_REL(value0_xyz, value1_xyz, 1e-10); + CHECK_CLOSE_REL(value0_xyz, value2_xyz, 1e-10); + CHECK_CLOSE_REL(value0_xyz, value3_xyz, 1e-10); + CHECK_CLOSE_REL(value0_xyz, value4_xyz, 1e-10); } + +/// Unit test for testing the decomposeToSurfaces() function +BOOST_DATA_TEST_CASE( + bfield_symmetry_random, + bdata::random( + (bdata::seed = 0, + bdata::distribution = std::uniform_real_distribution<>(-10., 10.))) ^ + bdata::random((bdata::seed = 0, + bdata::distribution = + std::uniform_real_distribution<>(-10., 10.))) ^ + bdata::random((bdata::seed = 0, + bdata::distribution = + std::uniform_real_distribution<>(-20., 20.))) ^ + bdata::xrange(10), + x, y, z, index) { + (void)index; + + std::vector<double> rPos; + std::vector<double> xPos; + std::vector<double> yPos; + std::vector<double> zPos; + double maxR = 20.; + double maxZ = 30.; + double maxBr = 10.; + double maxBz = 20.; + size_t nBins = 10; + double stepR = maxR / nBins; + double stepZ = maxZ / nBins; + double bStepR = maxBr / nBins; + double bStepZ = maxBz / nBins; + + for (size_t i = 0; i < nBins; i++) { + rPos.push_back(i * stepR); + xPos.push_back(i * stepR); + yPos.push_back(i * stepR); + zPos.push_back(i * stepZ); + } + // bfield in rz + std::vector<Acts::Vector2D> bField_rz; + for (size_t i = 0; i < nBins * nBins; i++) { + bField_rz.push_back(Acts::Vector2D(i * bStepR, i * bStepZ)); + } + // the mapper in rz + auto mapper_rz = Acts::fieldMapperRZ( + [](std::array<size_t, 2> binsRZ, std::array<size_t, 2> nBinsRZ) { + return (binsRZ.at(1) * nBinsRZ.at(0) + binsRZ.at(0)); + }, + rPos, zPos, bField_rz, 1, 1, true); + + // check number of bins, minima & maxima + std::vector<size_t> nBins_rz = {rPos.size(), 2 * zPos.size() - 1}; + std::vector<double> minima_rz = {0., -((nBins - 1) * stepZ)}; + std::vector<double> maxima_rz = {nBins * stepR, nBins * stepZ}; + BOOST_CHECK(mapper_rz.getNBins() == nBins_rz); + // check minimum (should be first value because bin values are always + // assigned to the left boundary) + CHECK_CLOSE_ABS(mapper_rz.getMin(), minima_rz, 1e-10); + // check maximum (should be last value + 1 step because bin values are + // always assigned to the left boundary) + CHECK_CLOSE_ABS(mapper_rz.getMax(), maxima_rz, 1e-10); + + // bfield in xyz + std::vector<Acts::Vector3D> bField_xyz; + for (size_t i = 0; i < nBins * nBins * nBins; i++) { + bField_xyz.push_back(Acts::Vector3D(i * bStepR, i * bStepR, i * bStepZ)); + } + // the mapper in xyz + auto mapper_xyz = Acts::fieldMapperXYZ( + [](std::array<size_t, 3> binsXYZ, std::array<size_t, 3> nBinsXYZ) { + return (binsXYZ.at(0) * (nBinsXYZ.at(1) * nBinsXYZ.at(2)) + + binsXYZ.at(1) * nBinsXYZ.at(2) + binsXYZ.at(2)); + }, + xPos, yPos, zPos, bField_xyz, 1, 1, true); + // check number of bins, minima & maxima + std::vector<size_t> nBins_xyz = {2 * xPos.size() - 1, 2 * yPos.size() - 1, + 2 * zPos.size() - 1}; + std::vector<double> minima_xyz = { + -((nBins - 1) * stepR), -((nBins - 1) * stepR), -((nBins - 1) * stepZ)}; + std::vector<double> maxima_xyz = {nBins * stepR, nBins * stepR, + nBins * stepZ}; + BOOST_CHECK(mapper_xyz.getNBins() == nBins_xyz); + // check minimum (should be first value because bin values are always + // assigned to the left boundary) + CHECK_CLOSE_REL(mapper_xyz.getMin(), minima_xyz, 1e-10); + // check maximum (should be last value + 1 step because bin values are + // always assigned to the left boundary) + CHECK_CLOSE_REL(mapper_xyz.getMax(), maxima_xyz, 1e-10); + + Acts::Vector3D pos0(x, y, z); + Acts::Vector3D pos1(x, y, -z); + Acts::Vector3D pos2(-x, y, z); + Acts::Vector3D pos3(x, -y, z); + Acts::Vector3D pos4(-x, -y, z); + + auto value0_rz = mapper_rz.getField(pos0); + auto value1_rz = mapper_rz.getField(pos1); + auto value2_rz = mapper_rz.getField(pos2); + auto value3_rz = mapper_rz.getField(pos3); + auto value4_rz = mapper_rz.getField(pos4); + + // check z- and phi-symmetry + CHECK_CLOSE_REL(perp(value0_rz), perp(value1_rz), 1e-10); + CHECK_CLOSE_REL(value0_rz.z(), value1_rz.z(), 1e-10); + CHECK_CLOSE_REL(perp(value0_rz), perp(value2_rz), 1e-10); + CHECK_CLOSE_REL(value0_rz.z(), value2_rz.z(), 1e-10); + CHECK_CLOSE_REL(perp(value0_rz), perp(value3_rz), 1e-10); + CHECK_CLOSE_REL(value0_rz.z(), value3_rz.z(), 1e-10); + CHECK_CLOSE_REL(perp(value0_rz), perp(value4_rz), 1e-10); + CHECK_CLOSE_REL(value0_rz.z(), value4_rz.z(), 1e-10); + + auto value0_xyz = mapper_xyz.getField(pos0); + auto value1_xyz = mapper_xyz.getField(pos1); + auto value2_xyz = mapper_xyz.getField(pos2); + auto value3_xyz = mapper_xyz.getField(pos3); + auto value4_xyz = mapper_xyz.getField(pos4); + + // checkx-,y-,z-symmetry - need to check close (because of interpolation + // there can be small differences) + CHECK_CLOSE_REL(value0_xyz, value1_xyz, 1e-10); + CHECK_CLOSE_REL(value0_xyz, value2_xyz, 1e-10); + CHECK_CLOSE_REL(value0_xyz, value3_xyz, 1e-10); + CHECK_CLOSE_REL(value0_xyz, value4_xyz, 1e-10); } +} // namespace Test +} // namespace Acts diff --git a/Tests/Core/Utilities/BinUtilityTests.cpp b/Tests/Core/Utilities/BinUtilityTests.cpp index e3c4afd2f3c271c3b6d2b3f306aa718364977b40..0a85cab5b5e60c0e2823dc0ac3e8e28e0a1d2774 100644 --- a/Tests/Core/Utilities/BinUtilityTests.cpp +++ b/Tests/Core/Utilities/BinUtilityTests.cpp @@ -17,87 +17,78 @@ namespace Acts { namespace Test { - namespace tt = boost::test_tools; - - // OPEN - equidistant binning tests - BOOST_AUTO_TEST_CASE(BinUtility_equidistant_binning) - { - Vector3D xyzPosition(1.5, 2.5, 3.5); - Vector3D edgePosition(0.5, 0.5, 0.5); - - // | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | - BinUtility xUtil_eq(10, 0., 10., open, binX); - BinUtility yUtil_eq(10, 0., 10., open, binY); - BinUtility zUtil_eq(10, 0., 10., open, binZ); - BOOST_CHECK_EQUAL(xUtil_eq.bins(), (size_t)10); - // make it 2-dim - BinUtility xyUtil_eq(10, 0., 10., open, binX); - xyUtil_eq += yUtil_eq; - BOOST_CHECK_EQUAL(xyUtil_eq.bins(), 100); - // make it 3-dim - BinUtility xyzUtil_eq(xyUtil_eq); - xyzUtil_eq += zUtil_eq; - BOOST_CHECK_EQUAL(xyzUtil_eq.bins(), 1000); - // check the dimensions - BOOST_CHECK_EQUAL(xUtil_eq.dimensions(), 1); - BOOST_CHECK_EQUAL(xyUtil_eq.dimensions(), 2); - BOOST_CHECK_EQUAL(xyzUtil_eq.dimensions(), 3); - - // bin triples and clusters - auto xTriple = xUtil_eq.binTriple(xyzPosition); - auto xyTriple = xyUtil_eq.binTriple(xyzPosition); - auto xyzTriple = xyzUtil_eq.binTriple(xyzPosition); - - BOOST_CHECK_EQUAL(xTriple[0], 1); - BOOST_CHECK_EQUAL(xTriple[1], 0); - BOOST_CHECK_EQUAL(xTriple[2], 0); - - BOOST_CHECK_EQUAL(xyTriple[0], 1); - BOOST_CHECK_EQUAL(xyTriple[1], 2); - BOOST_CHECK_EQUAL(xyTriple[2], 0); - - BOOST_CHECK_EQUAL(xyzTriple[0], 1); - BOOST_CHECK_EQUAL(xyzTriple[1], 2); - BOOST_CHECK_EQUAL(xyzTriple[2], 3); - - // Full range - std::vector<size_t> xRangeCheck0 = {0, 1, 2}; - std::vector<size_t> xyRangeCheck1 = {1, 2, 3}; - std::vector<size_t> xyzRangeCheck2 = {2, 3, 4}; - - auto xNrange0 = xUtil_eq.neighbourRange(xyzPosition, 0); - BOOST_CHECK_EQUAL_COLLECTIONS(xNrange0.begin(), - xNrange0.end(), - xRangeCheck0.begin(), - xRangeCheck0.end()); - - auto xNrange1 = xUtil_eq.neighbourRange(xyzPosition, 1); - BOOST_CHECK_EQUAL(xNrange1.size(), 1); - BOOST_CHECK_EQUAL(xNrange1[0], 0); - - auto xNrange2 = xUtil_eq.neighbourRange(xyzPosition, 2); - BOOST_CHECK_EQUAL(xNrange2.size(), 1); - BOOST_CHECK_EQUAL(xNrange2[0], 0); - - auto xyNrange1 = xyUtil_eq.neighbourRange(xyzPosition, 1); - BOOST_CHECK_EQUAL_COLLECTIONS(xyNrange1.begin(), - xyNrange1.end(), - xyRangeCheck1.begin(), - xyRangeCheck1.end()); - - auto xyzNrange2 = xyzUtil_eq.neighbourRange(xyzPosition, 2); - BOOST_CHECK_EQUAL_COLLECTIONS(xyzNrange2.begin(), - xyzNrange2.end(), - xyzRangeCheck2.begin(), - xyzRangeCheck2.end()); - - // Partial range - std::vector<size_t> xEdgeCheck = {0, 1}; - auto xEdgeRange = xUtil_eq.neighbourRange(edgePosition, 0); - BOOST_CHECK_EQUAL_COLLECTIONS(xEdgeRange.begin(), - xEdgeRange.end(), - xEdgeCheck.begin(), - xEdgeCheck.end()); - } -} +namespace tt = boost::test_tools; + +// OPEN - equidistant binning tests +BOOST_AUTO_TEST_CASE(BinUtility_equidistant_binning) { + Vector3D xyzPosition(1.5, 2.5, 3.5); + Vector3D edgePosition(0.5, 0.5, 0.5); + + // | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | + BinUtility xUtil_eq(10, 0., 10., open, binX); + BinUtility yUtil_eq(10, 0., 10., open, binY); + BinUtility zUtil_eq(10, 0., 10., open, binZ); + BOOST_CHECK_EQUAL(xUtil_eq.bins(), (size_t)10); + // make it 2-dim + BinUtility xyUtil_eq(10, 0., 10., open, binX); + xyUtil_eq += yUtil_eq; + BOOST_CHECK_EQUAL(xyUtil_eq.bins(), 100); + // make it 3-dim + BinUtility xyzUtil_eq(xyUtil_eq); + xyzUtil_eq += zUtil_eq; + BOOST_CHECK_EQUAL(xyzUtil_eq.bins(), 1000); + // check the dimensions + BOOST_CHECK_EQUAL(xUtil_eq.dimensions(), 1); + BOOST_CHECK_EQUAL(xyUtil_eq.dimensions(), 2); + BOOST_CHECK_EQUAL(xyzUtil_eq.dimensions(), 3); + + // bin triples and clusters + auto xTriple = xUtil_eq.binTriple(xyzPosition); + auto xyTriple = xyUtil_eq.binTriple(xyzPosition); + auto xyzTriple = xyzUtil_eq.binTriple(xyzPosition); + + BOOST_CHECK_EQUAL(xTriple[0], 1); + BOOST_CHECK_EQUAL(xTriple[1], 0); + BOOST_CHECK_EQUAL(xTriple[2], 0); + + BOOST_CHECK_EQUAL(xyTriple[0], 1); + BOOST_CHECK_EQUAL(xyTriple[1], 2); + BOOST_CHECK_EQUAL(xyTriple[2], 0); + + BOOST_CHECK_EQUAL(xyzTriple[0], 1); + BOOST_CHECK_EQUAL(xyzTriple[1], 2); + BOOST_CHECK_EQUAL(xyzTriple[2], 3); + + // Full range + std::vector<size_t> xRangeCheck0 = {0, 1, 2}; + std::vector<size_t> xyRangeCheck1 = {1, 2, 3}; + std::vector<size_t> xyzRangeCheck2 = {2, 3, 4}; + + auto xNrange0 = xUtil_eq.neighbourRange(xyzPosition, 0); + BOOST_CHECK_EQUAL_COLLECTIONS(xNrange0.begin(), xNrange0.end(), + xRangeCheck0.begin(), xRangeCheck0.end()); + + auto xNrange1 = xUtil_eq.neighbourRange(xyzPosition, 1); + BOOST_CHECK_EQUAL(xNrange1.size(), 1); + BOOST_CHECK_EQUAL(xNrange1[0], 0); + + auto xNrange2 = xUtil_eq.neighbourRange(xyzPosition, 2); + BOOST_CHECK_EQUAL(xNrange2.size(), 1); + BOOST_CHECK_EQUAL(xNrange2[0], 0); + + auto xyNrange1 = xyUtil_eq.neighbourRange(xyzPosition, 1); + BOOST_CHECK_EQUAL_COLLECTIONS(xyNrange1.begin(), xyNrange1.end(), + xyRangeCheck1.begin(), xyRangeCheck1.end()); + + auto xyzNrange2 = xyzUtil_eq.neighbourRange(xyzPosition, 2); + BOOST_CHECK_EQUAL_COLLECTIONS(xyzNrange2.begin(), xyzNrange2.end(), + xyzRangeCheck2.begin(), xyzRangeCheck2.end()); + + // Partial range + std::vector<size_t> xEdgeCheck = {0, 1}; + auto xEdgeRange = xUtil_eq.neighbourRange(edgePosition, 0); + BOOST_CHECK_EQUAL_COLLECTIONS(xEdgeRange.begin(), xEdgeRange.end(), + xEdgeCheck.begin(), xEdgeCheck.end()); } +} // namespace Test +} // namespace Acts diff --git a/Tests/Core/Utilities/BinningDataTests.cpp b/Tests/Core/Utilities/BinningDataTests.cpp index 6bb9c875f65c1dc03a7af5b50279d407fb0c449e..644d17f024135317a7110ff8e5da4958d8993ef3 100644 --- a/Tests/Core/Utilities/BinningDataTests.cpp +++ b/Tests/Core/Utilities/BinningDataTests.cpp @@ -21,438 +21,427 @@ namespace Acts { namespace Test { - namespace tt = boost::test_tools; - - // the test positions in 3D - Vector3D xyzPosition(0.5, 1.5, 2.5); - Vector3D xyzPositionOutside(30., -30., 200.); - Vector3D phi0Position(0.5, 0., 2.5); - Vector3D phiPihPosition(0., 1.5, 2.5); - Vector3D eta0Position(0.5, 1.5, 0.); - // the test positions in 2D - Vector2D xyPosition(0.5, 1.5); - Vector2D rphizPosition(0.1, 2.5); - Vector2D rphiPosition(3.5, M_PI / 8.); - - // the binnings - equidistant - // x/y/zData - // bin boundaries +namespace tt = boost::test_tools; + +// the test positions in 3D +Vector3D xyzPosition(0.5, 1.5, 2.5); +Vector3D xyzPositionOutside(30., -30., 200.); +Vector3D phi0Position(0.5, 0., 2.5); +Vector3D phiPihPosition(0., 1.5, 2.5); +Vector3D eta0Position(0.5, 1.5, 0.); +// the test positions in 2D +Vector2D xyPosition(0.5, 1.5); +Vector2D rphizPosition(0.1, 2.5); +Vector2D rphiPosition(3.5, M_PI / 8.); + +// the binnings - equidistant +// x/y/zData +// bin boundaries +// | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | +BinningData xData_eq(open, binX, 10, 0., 10.); +BinningData yData_eq(open, binY, 10, 0., 10.); +BinningData zData_eq(open, binZ, 10, 0., 10.); +// r/phi/rphiData +// bin boundaries +// | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | +BinningData rData_eq(open, binR, 10, 0., 10.); +// bin boundaries +// > -M_PI | -3/5 M_PI | -1/5 M_PI | 1/5 M_PI | 3/5 M_PI | M_PI < +BinningData phiData_eq(closed, binPhi, 5, -M_PI, M_PI); +BinningData rPhiData_eq(closed, binRPhi, 5, -M_PI, M_PI); +// h/etaData +// bin boundaries +// | 0 | 2 | 4 | 6 | 8 | 10 | +BinningData hData_eq(open, binH, 5, 0., 10.); +// | -2.5 | -1.5 | -0.5 | 0.5 | 1.5 | 2.5 | +BinningData etaData_eq(open, binEta, 5, -2.5, 2.5); + +// the binnings - arbitrary +std::vector<float> values = {0., 1., 2., 3., 4., 10.}; +// bin boundaries +// | 0 | 1 | 2 | 3 | 4 | 10 | +BinningData xData_arb(open, binX, values); +BinningData yData_arb(open, binY, values); +// | -M_PI | -2 | -1 | 1 | 2 | M_PI | +std::vector<float> phiValues = {-M_PI, -2., -1., 1., 2., M_PI}; +BinningData phiData_arb(closed, binPhi, phiValues); + +// the binnings - arbitrary when switching to binary search - for boundary +// sizes >= 50 +size_t nBins_binary = 59; +double valueMin = 0.; +double phiMin = -M_PI; +double delta = 0.5; +double phiDelta = 0.1064; + +// the binning - substructure +std::vector<float> sstr = {0., 1., 1.5, 2., 3.}; +// multiplicative +auto xData_sstr_mult = std::make_unique<const BinningData>(open, binX, sstr); +// | 0 | 1 | 1.5 | 2 | 3 | 4 | 4.5 | 5 | 6 | 7 | 7.5 | 8 | 9 | +BinningData xData_mult(open, binX, 3, 0., 9., std::move(xData_sstr_mult)); +/// additive +// | 0 | 1 | 1.5 | 2 | 3 | 4 | 5 | +std::vector<float> main_sstr = {0., 3., 4., 5.}; +auto xData_sstr_add = std::make_unique<const BinningData>(open, binX, sstr); +BinningData xData_add(open, binX, main_sstr, std::move(xData_sstr_add)); + +// enum BinningValue { binX, binY, binZ, binR, binPhi, binRPhi, binH, binEta } +// +// test the different binning values +BOOST_AUTO_TEST_CASE(BinningData_BinningValue) { + // the binnings - arbitrary when switching to binary search - for boundary + // sizes >= 50 + std::vector<float> values_binary; + std::vector<float> phiValues_binary; + for (size_t i = 0; i <= nBins_binary; i++) { + values_binary.push_back(valueMin + i * delta); + phiValues_binary.push_back(phiMin + i * phiDelta); + } + // bin boundaries when switching to binary search - for boundary sizes >= 50 + BinningData xData_arb_binary(open, binX, values_binary); + BinningData phiData_arb_binary(closed, binPhi, phiValues_binary); + /// x/y/zData + /// check the global position requests // | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | - BinningData xData_eq(open, binX, 10, 0., 10.); - BinningData yData_eq(open, binY, 10, 0., 10.); - BinningData zData_eq(open, binZ, 10, 0., 10.); + BOOST_CHECK_EQUAL(xData_eq.bins(), size_t(10)); + // | 0 | 1 | 2 | 3 | 4 | 10 | + BOOST_CHECK_EQUAL(xData_arb.bins(), size_t(5)); + // | 0 | 1 | 1.5 | 2 | 3 | 4 | 4.5 | 5 | 6 | 7 | 7.5 | 8 | 9 | + BOOST_CHECK_EQUAL(xData_mult.bins(), size_t(12)); + // | 0 | 1 | 1.5 | 2 | 3 | 4 | 5 | + BOOST_CHECK_EQUAL(xData_add.bins(), size_t(6)); + BOOST_CHECK_EQUAL(xData_arb_binary.bins(), nBins_binary); + + /// check the global position requests + BOOST_CHECK_EQUAL(xData_eq.value(xyzPosition), 0.5); + BOOST_CHECK_EQUAL(yData_eq.value(xyzPosition), 1.5); + BOOST_CHECK_EQUAL(zData_eq.value(xyzPosition), 2.5); + BOOST_CHECK_EQUAL(xData_arb.value(xyzPosition), 0.5); + BOOST_CHECK_EQUAL(xData_mult.value(xyzPosition), 0.5); + BOOST_CHECK_EQUAL(xData_add.value(xyzPosition), 0.5); + BOOST_CHECK_EQUAL(xData_arb_binary.value(xyzPosition), 0.5); + + /// check the local position requests + BOOST_CHECK_EQUAL(xData_eq.value(xyPosition), 0.5); + BOOST_CHECK_EQUAL(yData_eq.value(xyPosition), 1.5); + BOOST_CHECK_EQUAL(zData_eq.value(rphizPosition), 2.5); + BOOST_CHECK_EQUAL(xData_arb.value(xyPosition), 0.5); + BOOST_CHECK_EQUAL(xData_mult.value(xyPosition), 0.5); + BOOST_CHECK_EQUAL(xData_add.value(xyPosition), 0.5); + BOOST_CHECK_EQUAL(xData_arb_binary.value(xyPosition), 0.5); + // r/phi/rphiData - // bin boundaries - // | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | - BinningData rData_eq(open, binR, 10, 0., 10.); - // bin boundaries - // > -M_PI | -3/5 M_PI | -1/5 M_PI | 1/5 M_PI | 3/5 M_PI | M_PI < - BinningData phiData_eq(closed, binPhi, 5, -M_PI, M_PI); - BinningData rPhiData_eq(closed, binRPhi, 5, -M_PI, M_PI); + CHECK_CLOSE_REL(rData_eq.value(xyzPosition), sqrt(0.5 * 0.5 + 1.5 * 1.5), + 1e-5); + BOOST_CHECK_EQUAL(rData_eq.value(rphiPosition), 3.5); + + CHECK_SMALL(phiData_eq.value(phi0Position), 1e-6 * M_PI); + CHECK_CLOSE_REL(phiData_eq.value(phiPihPosition), M_PI / 2, 1e-5); + + BOOST_CHECK_EQUAL(phiData_eq.bins(), size_t(5)); + BOOST_CHECK_EQUAL(phiData_arb.bins(), size_t(5)); + BOOST_CHECK_EQUAL(phiData_arb_binary.bins(), size_t(nBins_binary)); + // h/etaData - // bin boundaries - // | 0 | 2 | 4 | 6 | 8 | 10 | - BinningData hData_eq(open, binH, 5, 0., 10.); - // | -2.5 | -1.5 | -0.5 | 0.5 | 1.5 | 2.5 | - BinningData etaData_eq(open, binEta, 5, -2.5, 2.5); - - // the binnings - arbitrary - std::vector<float> values = {0., 1., 2., 3., 4., 10.}; - // bin boundaries - // | 0 | 1 | 2 | 3 | 4 | 10 | - BinningData xData_arb(open, binX, values); - BinningData yData_arb(open, binY, values); - // | -M_PI | -2 | -1 | 1 | 2 | M_PI | - std::vector<float> phiValues = {-M_PI, -2., -1., 1., 2., M_PI}; - BinningData phiData_arb(closed, binPhi, phiValues); + CHECK_SMALL(etaData_eq.value(eta0Position), 1e-5); +} +// test bin values +BOOST_AUTO_TEST_CASE(BinningData_bins) { // the binnings - arbitrary when switching to binary search - for boundary // sizes >= 50 - size_t nBins_binary = 59; - double valueMin = 0.; - double phiMin = -M_PI; - double delta = 0.5; - double phiDelta = 0.1064; - - // the binning - substructure - std::vector<float> sstr = {0., 1., 1.5, 2., 3.}; - // multiplicative - auto xData_sstr_mult = std::make_unique<const BinningData>(open, binX, sstr); - // | 0 | 1 | 1.5 | 2 | 3 | 4 | 4.5 | 5 | 6 | 7 | 7.5 | 8 | 9 | - BinningData xData_mult(open, binX, 3, 0., 9., std::move(xData_sstr_mult)); - /// additive - // | 0 | 1 | 1.5 | 2 | 3 | 4 | 5 | - std::vector<float> main_sstr = {0., 3., 4., 5.}; - auto xData_sstr_add = std::make_unique<const BinningData>(open, binX, sstr); - BinningData xData_add(open, binX, main_sstr, std::move(xData_sstr_add)); - - // enum BinningValue { binX, binY, binZ, binR, binPhi, binRPhi, binH, binEta } - // - // test the different binning values - BOOST_AUTO_TEST_CASE(BinningData_BinningValue) - { - // the binnings - arbitrary when switching to binary search - for boundary - // sizes >= 50 - std::vector<float> values_binary; - std::vector<float> phiValues_binary; - for (size_t i = 0; i <= nBins_binary; i++) { - values_binary.push_back(valueMin + i * delta); - phiValues_binary.push_back(phiMin + i * phiDelta); - } - // bin boundaries when switching to binary search - for boundary sizes >= 50 - BinningData xData_arb_binary(open, binX, values_binary); - BinningData phiData_arb_binary(closed, binPhi, phiValues_binary); - /// x/y/zData - /// check the global position requests - // | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | - BOOST_CHECK_EQUAL(xData_eq.bins(), size_t(10)); - // | 0 | 1 | 2 | 3 | 4 | 10 | - BOOST_CHECK_EQUAL(xData_arb.bins(), size_t(5)); - // | 0 | 1 | 1.5 | 2 | 3 | 4 | 4.5 | 5 | 6 | 7 | 7.5 | 8 | 9 | - BOOST_CHECK_EQUAL(xData_mult.bins(), size_t(12)); - // | 0 | 1 | 1.5 | 2 | 3 | 4 | 5 | - BOOST_CHECK_EQUAL(xData_add.bins(), size_t(6)); - BOOST_CHECK_EQUAL(xData_arb_binary.bins(), nBins_binary); - - /// check the global position requests - BOOST_CHECK_EQUAL(xData_eq.value(xyzPosition), 0.5); - BOOST_CHECK_EQUAL(yData_eq.value(xyzPosition), 1.5); - BOOST_CHECK_EQUAL(zData_eq.value(xyzPosition), 2.5); - BOOST_CHECK_EQUAL(xData_arb.value(xyzPosition), 0.5); - BOOST_CHECK_EQUAL(xData_mult.value(xyzPosition), 0.5); - BOOST_CHECK_EQUAL(xData_add.value(xyzPosition), 0.5); - BOOST_CHECK_EQUAL(xData_arb_binary.value(xyzPosition), 0.5); - - /// check the local position requests - BOOST_CHECK_EQUAL(xData_eq.value(xyPosition), 0.5); - BOOST_CHECK_EQUAL(yData_eq.value(xyPosition), 1.5); - BOOST_CHECK_EQUAL(zData_eq.value(rphizPosition), 2.5); - BOOST_CHECK_EQUAL(xData_arb.value(xyPosition), 0.5); - BOOST_CHECK_EQUAL(xData_mult.value(xyPosition), 0.5); - BOOST_CHECK_EQUAL(xData_add.value(xyPosition), 0.5); - BOOST_CHECK_EQUAL(xData_arb_binary.value(xyPosition), 0.5); - - // r/phi/rphiData - CHECK_CLOSE_REL( - rData_eq.value(xyzPosition), sqrt(0.5 * 0.5 + 1.5 * 1.5), 1e-5); - BOOST_CHECK_EQUAL(rData_eq.value(rphiPosition), 3.5); - - CHECK_SMALL(phiData_eq.value(phi0Position), 1e-6 * M_PI); - CHECK_CLOSE_REL(phiData_eq.value(phiPihPosition), M_PI / 2, 1e-5); - - BOOST_CHECK_EQUAL(phiData_eq.bins(), size_t(5)); - BOOST_CHECK_EQUAL(phiData_arb.bins(), size_t(5)); - BOOST_CHECK_EQUAL(phiData_arb_binary.bins(), size_t(nBins_binary)); - - // h/etaData - CHECK_SMALL(etaData_eq.value(eta0Position), 1e-5); + std::vector<float> values_binary; + std::vector<float> phiValues_binary; + for (size_t i = 0; i <= nBins_binary; i++) { + values_binary.push_back(valueMin + i * delta); + phiValues_binary.push_back(phiMin + i * phiDelta); } + // bin boundaries when switching to binary search - for boundary sizes >= 50 + BinningData xData_arb_binary(open, binX, values_binary); + BinningData phiData_arb_binary(closed, binPhi, phiValues_binary); + /// x/y/zData + /// check the global position requests + // | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | + BOOST_CHECK_EQUAL(xData_eq.searchGlobal(xyzPosition), size_t(0)); + BOOST_CHECK_EQUAL(yData_eq.searchGlobal(xyzPosition), size_t(1)); + BOOST_CHECK_EQUAL(zData_eq.searchGlobal(xyzPosition), size_t(2)); + // | 0 | 1 | 2 | 3 | 4 | 10 | + BOOST_CHECK_EQUAL(xData_arb.searchGlobal(xyzPosition), size_t(0)); + BOOST_CHECK_EQUAL(xData_arb.search(6.), size_t(4)); + BOOST_CHECK_EQUAL(xData_arb_binary.searchGlobal(xyzPosition), size_t(1)); + BOOST_CHECK_EQUAL(xData_arb_binary.search(50.), (nBins_binary - 1)); + // | 0 | 1 | 1.5 | 2 | 3 | 4 | 5 | + BOOST_CHECK_EQUAL(xData_add.searchGlobal(xyzPosition), size_t(0)); + BOOST_CHECK_EQUAL(xData_add.searchGlobal(xyzPosition), size_t(0)); + BOOST_CHECK_EQUAL(xData_add.search(0.2), size_t(0)); + BOOST_CHECK_EQUAL(xData_add.search(1.2), size_t(1)); + BOOST_CHECK_EQUAL(xData_add.search(1.7), size_t(2)); + BOOST_CHECK_EQUAL(xData_add.search(2.5), size_t(3)); + BOOST_CHECK_EQUAL(xData_add.search(3.5), size_t(4)); + BOOST_CHECK_EQUAL(xData_add.search(4.2), size_t(5)); + BOOST_CHECK_EQUAL(xData_add.search(7.), size_t(5)); + // | 0 | 1 | 1.5 | 2 | 3 | 4 | 4.5 | 5 | 6 | 7 | 7.5 | 8 | 9 | + BOOST_CHECK_EQUAL(xData_mult.searchGlobal(xyzPosition), size_t(0)); + BOOST_CHECK_EQUAL(xData_mult.search(0.2), size_t(0)); + BOOST_CHECK_EQUAL(xData_mult.search(1.2), size_t(1)); + BOOST_CHECK_EQUAL(xData_mult.search(1.7), size_t(2)); + BOOST_CHECK_EQUAL(xData_mult.search(2.5), size_t(3)); + BOOST_CHECK_EQUAL(xData_mult.search(3.5), size_t(4)); + BOOST_CHECK_EQUAL(xData_mult.search(4.2), size_t(5)); + BOOST_CHECK_EQUAL(xData_mult.search(4.7), size_t(6)); + BOOST_CHECK_EQUAL(xData_mult.search(5.7), size_t(7)); + BOOST_CHECK_EQUAL(xData_mult.search(6.5), size_t(8)); + BOOST_CHECK_EQUAL(xData_mult.search(7.2), size_t(9)); + BOOST_CHECK_EQUAL(xData_mult.search(7.7), size_t(10)); + BOOST_CHECK_EQUAL(xData_mult.search(8.1), size_t(11)); + + /// check the local position requests + BOOST_CHECK_EQUAL(xData_eq.searchLocal(xyPosition), size_t(0)); + BOOST_CHECK_EQUAL(yData_eq.searchLocal(xyPosition), size_t(1)); + BOOST_CHECK_EQUAL(zData_eq.searchLocal(rphizPosition), size_t(2)); + BOOST_CHECK_EQUAL(xData_arb.searchLocal(xyPosition), size_t(0)); + BOOST_CHECK_EQUAL(xData_arb_binary.searchLocal(xyPosition), size_t(1)); - // test bin values - BOOST_AUTO_TEST_CASE(BinningData_bins) - { - // the binnings - arbitrary when switching to binary search - for boundary - // sizes >= 50 - std::vector<float> values_binary; - std::vector<float> phiValues_binary; - for (size_t i = 0; i <= nBins_binary; i++) { - values_binary.push_back(valueMin + i * delta); - phiValues_binary.push_back(phiMin + i * phiDelta); - } - // bin boundaries when switching to binary search - for boundary sizes >= 50 - BinningData xData_arb_binary(open, binX, values_binary); - BinningData phiData_arb_binary(closed, binPhi, phiValues_binary); - /// x/y/zData - /// check the global position requests - // | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | - BOOST_CHECK_EQUAL(xData_eq.searchGlobal(xyzPosition), size_t(0)); - BOOST_CHECK_EQUAL(yData_eq.searchGlobal(xyzPosition), size_t(1)); - BOOST_CHECK_EQUAL(zData_eq.searchGlobal(xyzPosition), size_t(2)); - // | 0 | 1 | 2 | 3 | 4 | 10 | - BOOST_CHECK_EQUAL(xData_arb.searchGlobal(xyzPosition), size_t(0)); - BOOST_CHECK_EQUAL(xData_arb.search(6.), size_t(4)); - BOOST_CHECK_EQUAL(xData_arb_binary.searchGlobal(xyzPosition), size_t(1)); - BOOST_CHECK_EQUAL(xData_arb_binary.search(50.), (nBins_binary - 1)); - // | 0 | 1 | 1.5 | 2 | 3 | 4 | 5 | - BOOST_CHECK_EQUAL(xData_add.searchGlobal(xyzPosition), size_t(0)); - BOOST_CHECK_EQUAL(xData_add.searchGlobal(xyzPosition), size_t(0)); - BOOST_CHECK_EQUAL(xData_add.search(0.2), size_t(0)); - BOOST_CHECK_EQUAL(xData_add.search(1.2), size_t(1)); - BOOST_CHECK_EQUAL(xData_add.search(1.7), size_t(2)); - BOOST_CHECK_EQUAL(xData_add.search(2.5), size_t(3)); - BOOST_CHECK_EQUAL(xData_add.search(3.5), size_t(4)); - BOOST_CHECK_EQUAL(xData_add.search(4.2), size_t(5)); - BOOST_CHECK_EQUAL(xData_add.search(7.), size_t(5)); - // | 0 | 1 | 1.5 | 2 | 3 | 4 | 4.5 | 5 | 6 | 7 | 7.5 | 8 | 9 | - BOOST_CHECK_EQUAL(xData_mult.searchGlobal(xyzPosition), size_t(0)); - BOOST_CHECK_EQUAL(xData_mult.search(0.2), size_t(0)); - BOOST_CHECK_EQUAL(xData_mult.search(1.2), size_t(1)); - BOOST_CHECK_EQUAL(xData_mult.search(1.7), size_t(2)); - BOOST_CHECK_EQUAL(xData_mult.search(2.5), size_t(3)); - BOOST_CHECK_EQUAL(xData_mult.search(3.5), size_t(4)); - BOOST_CHECK_EQUAL(xData_mult.search(4.2), size_t(5)); - BOOST_CHECK_EQUAL(xData_mult.search(4.7), size_t(6)); - BOOST_CHECK_EQUAL(xData_mult.search(5.7), size_t(7)); - BOOST_CHECK_EQUAL(xData_mult.search(6.5), size_t(8)); - BOOST_CHECK_EQUAL(xData_mult.search(7.2), size_t(9)); - BOOST_CHECK_EQUAL(xData_mult.search(7.7), size_t(10)); - BOOST_CHECK_EQUAL(xData_mult.search(8.1), size_t(11)); - - /// check the local position requests - BOOST_CHECK_EQUAL(xData_eq.searchLocal(xyPosition), size_t(0)); - BOOST_CHECK_EQUAL(yData_eq.searchLocal(xyPosition), size_t(1)); - BOOST_CHECK_EQUAL(zData_eq.searchLocal(rphizPosition), size_t(2)); - BOOST_CHECK_EQUAL(xData_arb.searchLocal(xyPosition), size_t(0)); - BOOST_CHECK_EQUAL(xData_arb_binary.searchLocal(xyPosition), size_t(1)); - - // r/phi/rphiData - BOOST_CHECK_EQUAL(rData_eq.searchGlobal(xyzPosition), size_t(1)); - BOOST_CHECK_EQUAL(rData_eq.searchLocal(rphiPosition), size_t(3)); - BOOST_CHECK_EQUAL(phiData_eq.searchGlobal(phi0Position), size_t(2)); - BOOST_CHECK_EQUAL(phiData_eq.searchGlobal(phiPihPosition), size_t(3)); - BOOST_CHECK_EQUAL(phiData_arb_binary.search(M_PI), size_t(0)); - - // h/etaData - BOOST_CHECK_EQUAL(etaData_eq.searchGlobal(eta0Position), size_t(2)); - } + // r/phi/rphiData + BOOST_CHECK_EQUAL(rData_eq.searchGlobal(xyzPosition), size_t(1)); + BOOST_CHECK_EQUAL(rData_eq.searchLocal(rphiPosition), size_t(3)); + BOOST_CHECK_EQUAL(phiData_eq.searchGlobal(phi0Position), size_t(2)); + BOOST_CHECK_EQUAL(phiData_eq.searchGlobal(phiPihPosition), size_t(3)); + BOOST_CHECK_EQUAL(phiData_arb_binary.search(M_PI), size_t(0)); - // test inside/outside - BOOST_AUTO_TEST_CASE(BinningData_inside_outside) - { - // the binnings - arbitrary when switching to binary search - for boundary - // sizes >= 50 - std::vector<float> values_binary; - std::vector<float> phiValues_binary; - for (size_t i = 0; i <= nBins_binary; i++) { - values_binary.push_back(valueMin + i * delta); - phiValues_binary.push_back(phiMin + i * phiDelta); - } - // bin boundaries when switching to binary search - for boundary sizes >= 50 - BinningData xData_arb_binary(open, binX, values_binary); - BinningData phiData_arb_binary(closed, binPhi, phiValues_binary); - // check the global inside - BOOST_CHECK_EQUAL(xData_eq.inside(xyzPosition), true); - BOOST_CHECK_EQUAL(yData_eq.inside(xyzPosition), true); - BOOST_CHECK_EQUAL(zData_eq.inside(xyzPosition), true); - BOOST_CHECK_EQUAL(xData_arb.inside(xyzPosition), true); - BOOST_CHECK_EQUAL(xData_add.inside(xyzPosition), true); - BOOST_CHECK_EQUAL(xData_mult.inside(xyzPosition), true); - BOOST_CHECK_EQUAL(xData_arb_binary.inside(xyzPosition), true); - - // check the global outside - BOOST_CHECK_EQUAL(xData_eq.inside(xyzPositionOutside), false); - BOOST_CHECK_EQUAL(yData_eq.inside(xyzPositionOutside), false); - BOOST_CHECK_EQUAL(zData_eq.inside(xyzPositionOutside), false); - BOOST_CHECK_EQUAL(xData_arb.inside(xyzPositionOutside), false); - BOOST_CHECK_EQUAL(xData_add.inside(xyzPositionOutside), false); - BOOST_CHECK_EQUAL(xData_mult.inside(xyzPositionOutside), false); - BOOST_CHECK_EQUAL(xData_arb_binary.inside(xyzPositionOutside), false); - - // cthe local inside - BOOST_CHECK_EQUAL(xData_eq.inside(xyPosition), true); - BOOST_CHECK_EQUAL(yData_eq.inside(xyPosition), true); - BOOST_CHECK_EQUAL(zData_eq.inside(rphizPosition), true); - - // r/phi/rphiData inside - BOOST_CHECK_EQUAL(phiData_eq.inside(phi0Position), true); - BOOST_CHECK_EQUAL(phiData_eq.inside(phiPihPosition), true); - //// h/etaData - BOOST_CHECK_EQUAL(etaData_eq.inside(eta0Position), true); - } + // h/etaData + BOOST_CHECK_EQUAL(etaData_eq.searchGlobal(eta0Position), size_t(2)); +} - // test open/close - BOOST_AUTO_TEST_CASE(BinningData_open_close) - { - // the binnings - arbitrary when switching to binary search - for boundary - // sizes >= 50 - std::vector<float> values_binary; - std::vector<float> phiValues_binary; - for (size_t i = 0; i <= nBins_binary; i++) { - values_binary.push_back(valueMin + i * delta); - phiValues_binary.push_back(phiMin + i * phiDelta); - } - // bin boundaries when switching to binary search - for boundary sizes >= 50 - BinningData xData_arb_binary(open, binX, values_binary); - BinningData phiData_arb_binary(closed, binPhi, phiValues_binary); - // open values - BOOST_CHECK_EQUAL(xData_eq.searchGlobal(xyzPositionOutside), size_t(9)); - BOOST_CHECK_EQUAL(yData_eq.searchGlobal(xyzPositionOutside), size_t(0)); - BOOST_CHECK_EQUAL(zData_eq.searchGlobal(xyzPositionOutside), size_t(9)); - BOOST_CHECK_EQUAL(xData_arb.searchGlobal(xyzPositionOutside) + 1, - xData_arb.bins()); - BOOST_CHECK_EQUAL(xData_arb_binary.searchGlobal(xyzPositionOutside) + 1, - xData_arb_binary.bins()); - BOOST_CHECK_EQUAL(yData_arb.searchGlobal(xyzPositionOutside), size_t(0)); - - // increment an open bin - // - for equidistant - size_t bin = 9; - xData_eq.increment(bin); - BOOST_CHECK_EQUAL(bin, size_t(9)); - bin = 0; - xData_eq.decrement(bin); - BOOST_CHECK_EQUAL(bin, size_t(0)); - // - for arbitrary - bin = 5; - xData_arb.increment(bin); - BOOST_CHECK_EQUAL(bin, size_t(5)); - bin = 0; - xData_arb.decrement(bin); - BOOST_CHECK_EQUAL(bin, size_t(0)); - - bin = nBins_binary; - xData_arb_binary.increment(bin); - BOOST_CHECK_EQUAL(bin, nBins_binary); - bin = 0; - xData_arb_binary.decrement(bin); - BOOST_CHECK_EQUAL(bin, size_t(0)); - - // closed values - BOOST_CHECK_EQUAL(phiData_eq.search(-4.), size_t(4)); - BOOST_CHECK_EQUAL(phiData_eq.search(4.), size_t(0)); - BOOST_CHECK_EQUAL(phiData_arb.search(-4.), size_t(4)); - BOOST_CHECK_EQUAL(phiData_arb.search(4.), size_t(0)); - BOOST_CHECK_EQUAL(phiData_arb_binary.search(-4.), (nBins_binary - 1)); - BOOST_CHECK_EQUAL(phiData_arb_binary.search(4.), size_t(0)); - - bin = 4; - phiData_eq.increment(bin); - BOOST_CHECK_EQUAL(bin, size_t(0)); - bin = 0; - phiData_eq.decrement(bin); - BOOST_CHECK_EQUAL(bin, size_t(4)); - - bin = 4; - phiData_arb.increment(bin); - BOOST_CHECK_EQUAL(bin, size_t(0)); - bin = 0; - phiData_arb.decrement(bin); - BOOST_CHECK_EQUAL(bin, size_t(4)); - - bin = nBins_binary; - phiData_arb_binary.increment(bin); - BOOST_CHECK_EQUAL(bin, size_t(0)); - bin = 0; - phiData_arb_binary.decrement(bin); - BOOST_CHECK_EQUAL(bin, (nBins_binary - 1)); +// test inside/outside +BOOST_AUTO_TEST_CASE(BinningData_inside_outside) { + // the binnings - arbitrary when switching to binary search - for boundary + // sizes >= 50 + std::vector<float> values_binary; + std::vector<float> phiValues_binary; + for (size_t i = 0; i <= nBins_binary; i++) { + values_binary.push_back(valueMin + i * delta); + phiValues_binary.push_back(phiMin + i * phiDelta); } - - // test boundaries - BOOST_AUTO_TEST_CASE(BinningData_boundaries) - { - // open values - std::vector<float> boundaries - = {0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.}; - BOOST_CHECK_EQUAL_COLLECTIONS(xData_eq.boundaries().begin(), - xData_eq.boundaries().end(), - boundaries.begin(), - boundaries.end()); - - float phiStep = M_PI * 2. / 5.; - std::vector<float> phiBoundaries_eq = {-M_PI, - float(-M_PI + 1 * phiStep), - float(-M_PI + 2 * phiStep), - float(-M_PI + 3 * phiStep), - float(-M_PI + 4 * phiStep), - float(-M_PI + 5 * phiStep)}; - CHECK_CLOSE_REL(phiData_eq.boundaries(), phiBoundaries_eq, 1e-5); + // bin boundaries when switching to binary search - for boundary sizes >= 50 + BinningData xData_arb_binary(open, binX, values_binary); + BinningData phiData_arb_binary(closed, binPhi, phiValues_binary); + // check the global inside + BOOST_CHECK_EQUAL(xData_eq.inside(xyzPosition), true); + BOOST_CHECK_EQUAL(yData_eq.inside(xyzPosition), true); + BOOST_CHECK_EQUAL(zData_eq.inside(xyzPosition), true); + BOOST_CHECK_EQUAL(xData_arb.inside(xyzPosition), true); + BOOST_CHECK_EQUAL(xData_add.inside(xyzPosition), true); + BOOST_CHECK_EQUAL(xData_mult.inside(xyzPosition), true); + BOOST_CHECK_EQUAL(xData_arb_binary.inside(xyzPosition), true); + + // check the global outside + BOOST_CHECK_EQUAL(xData_eq.inside(xyzPositionOutside), false); + BOOST_CHECK_EQUAL(yData_eq.inside(xyzPositionOutside), false); + BOOST_CHECK_EQUAL(zData_eq.inside(xyzPositionOutside), false); + BOOST_CHECK_EQUAL(xData_arb.inside(xyzPositionOutside), false); + BOOST_CHECK_EQUAL(xData_add.inside(xyzPositionOutside), false); + BOOST_CHECK_EQUAL(xData_mult.inside(xyzPositionOutside), false); + BOOST_CHECK_EQUAL(xData_arb_binary.inside(xyzPositionOutside), false); + + // cthe local inside + BOOST_CHECK_EQUAL(xData_eq.inside(xyPosition), true); + BOOST_CHECK_EQUAL(yData_eq.inside(xyPosition), true); + BOOST_CHECK_EQUAL(zData_eq.inside(rphizPosition), true); + + // r/phi/rphiData inside + BOOST_CHECK_EQUAL(phiData_eq.inside(phi0Position), true); + BOOST_CHECK_EQUAL(phiData_eq.inside(phiPihPosition), true); + //// h/etaData + BOOST_CHECK_EQUAL(etaData_eq.inside(eta0Position), true); +} + +// test open/close +BOOST_AUTO_TEST_CASE(BinningData_open_close) { + // the binnings - arbitrary when switching to binary search - for boundary + // sizes >= 50 + std::vector<float> values_binary; + std::vector<float> phiValues_binary; + for (size_t i = 0; i <= nBins_binary; i++) { + values_binary.push_back(valueMin + i * delta); + phiValues_binary.push_back(phiMin + i * phiDelta); } - - // test bin center values - // test boundaries - BOOST_AUTO_TEST_CASE(BinningData_bincenter) - { - // the binnings - arbitrary when switching to binary search - for boundary - // sizes >= 50 - std::vector<float> values_binary; - std::vector<float> phiValues_binary; - for (size_t i = 0; i <= nBins_binary; i++) { - values_binary.push_back(valueMin + i * delta); - phiValues_binary.push_back(phiMin + i * phiDelta); - } - // bin boundaries when switching to binary search - for boundary sizes >= 50 - BinningData xData_arb_binary(open, binX, values_binary); - BinningData phiData_arb_binary(closed, binPhi, phiValues_binary); - /// check the global position requests - // | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | - BOOST_CHECK_EQUAL(xData_eq.center(3), 3.5); - // | 0 | 1 | 2 | 3 | 4 | 10 | - BOOST_CHECK_EQUAL(xData_arb.center(4), 7.); - // | 0 | 1 | 1.5 | 2 | 3 | 4 | 5 | - BOOST_CHECK_EQUAL(xData_add.center(0), 0.5); - BOOST_CHECK_EQUAL(xData_add.center(1), 1.25); - BOOST_CHECK_EQUAL(xData_add.center(4), 3.5); - // | 0 | 1 | 1.5 | 2 | 3 | 4 | 4.5 | 5 | 6 | 7 | 7.5 | 8 | 9 | - BOOST_CHECK_EQUAL(xData_mult.center(0), 0.5); - BOOST_CHECK_EQUAL(xData_mult.center(1), 1.25); - BOOST_CHECK_EQUAL(xData_mult.center(4), 3.5); - BOOST_CHECK_EQUAL(xData_mult.center(10), 7.75); - BOOST_CHECK_EQUAL(xData_mult.center(11), 8.5); - - BOOST_CHECK_EQUAL(xData_arb_binary.center(0), 0.5 * delta); - - // open values - std::vector<float> center - = {0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5}; - for (size_t ib = 0; ib < center.size(); ++ib) { - BOOST_CHECK_EQUAL(xData_eq.center(ib), center[ib]); - } - - // running into rounding errors here - float phiStep = M_PI * 2. / 5.; - std::vector<float> phiCenters_eq = {float(-M_PI + 0.5 * phiStep), - float(-M_PI + 1.5 * phiStep), - float(-M_PI + 2.5 * phiStep), - float(-M_PI + 3.5 * phiStep), - float(-M_PI + 4.5 * phiStep)}; - - for (size_t ib = 0; ib < phiCenters_eq.size(); ++ib) { - CHECK_CLOSE_ABS(phiData_eq.center(ib), phiCenters_eq[ib], 1e-3); - } + // bin boundaries when switching to binary search - for boundary sizes >= 50 + BinningData xData_arb_binary(open, binX, values_binary); + BinningData phiData_arb_binary(closed, binPhi, phiValues_binary); + // open values + BOOST_CHECK_EQUAL(xData_eq.searchGlobal(xyzPositionOutside), size_t(9)); + BOOST_CHECK_EQUAL(yData_eq.searchGlobal(xyzPositionOutside), size_t(0)); + BOOST_CHECK_EQUAL(zData_eq.searchGlobal(xyzPositionOutside), size_t(9)); + BOOST_CHECK_EQUAL(xData_arb.searchGlobal(xyzPositionOutside) + 1, + xData_arb.bins()); + BOOST_CHECK_EQUAL(xData_arb_binary.searchGlobal(xyzPositionOutside) + 1, + xData_arb_binary.bins()); + BOOST_CHECK_EQUAL(yData_arb.searchGlobal(xyzPositionOutside), size_t(0)); + + // increment an open bin + // - for equidistant + size_t bin = 9; + xData_eq.increment(bin); + BOOST_CHECK_EQUAL(bin, size_t(9)); + bin = 0; + xData_eq.decrement(bin); + BOOST_CHECK_EQUAL(bin, size_t(0)); + // - for arbitrary + bin = 5; + xData_arb.increment(bin); + BOOST_CHECK_EQUAL(bin, size_t(5)); + bin = 0; + xData_arb.decrement(bin); + BOOST_CHECK_EQUAL(bin, size_t(0)); + + bin = nBins_binary; + xData_arb_binary.increment(bin); + BOOST_CHECK_EQUAL(bin, nBins_binary); + bin = 0; + xData_arb_binary.decrement(bin); + BOOST_CHECK_EQUAL(bin, size_t(0)); + + // closed values + BOOST_CHECK_EQUAL(phiData_eq.search(-4.), size_t(4)); + BOOST_CHECK_EQUAL(phiData_eq.search(4.), size_t(0)); + BOOST_CHECK_EQUAL(phiData_arb.search(-4.), size_t(4)); + BOOST_CHECK_EQUAL(phiData_arb.search(4.), size_t(0)); + BOOST_CHECK_EQUAL(phiData_arb_binary.search(-4.), (nBins_binary - 1)); + BOOST_CHECK_EQUAL(phiData_arb_binary.search(4.), size_t(0)); + + bin = 4; + phiData_eq.increment(bin); + BOOST_CHECK_EQUAL(bin, size_t(0)); + bin = 0; + phiData_eq.decrement(bin); + BOOST_CHECK_EQUAL(bin, size_t(4)); + + bin = 4; + phiData_arb.increment(bin); + BOOST_CHECK_EQUAL(bin, size_t(0)); + bin = 0; + phiData_arb.decrement(bin); + BOOST_CHECK_EQUAL(bin, size_t(4)); + + bin = nBins_binary; + phiData_arb_binary.increment(bin); + BOOST_CHECK_EQUAL(bin, size_t(0)); + bin = 0; + phiData_arb_binary.decrement(bin); + BOOST_CHECK_EQUAL(bin, (nBins_binary - 1)); +} + +// test boundaries +BOOST_AUTO_TEST_CASE(BinningData_boundaries) { + // open values + std::vector<float> boundaries = {0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.}; + BOOST_CHECK_EQUAL_COLLECTIONS(xData_eq.boundaries().begin(), + xData_eq.boundaries().end(), boundaries.begin(), + boundaries.end()); + + float phiStep = M_PI * 2. / 5.; + std::vector<float> phiBoundaries_eq = {-M_PI, + float(-M_PI + 1 * phiStep), + float(-M_PI + 2 * phiStep), + float(-M_PI + 3 * phiStep), + float(-M_PI + 4 * phiStep), + float(-M_PI + 5 * phiStep)}; + CHECK_CLOSE_REL(phiData_eq.boundaries(), phiBoundaries_eq, 1e-5); +} + +// test bin center values +// test boundaries +BOOST_AUTO_TEST_CASE(BinningData_bincenter) { + // the binnings - arbitrary when switching to binary search - for boundary + // sizes >= 50 + std::vector<float> values_binary; + std::vector<float> phiValues_binary; + for (size_t i = 0; i <= nBins_binary; i++) { + values_binary.push_back(valueMin + i * delta); + phiValues_binary.push_back(phiMin + i * phiDelta); + } + // bin boundaries when switching to binary search - for boundary sizes >= 50 + BinningData xData_arb_binary(open, binX, values_binary); + BinningData phiData_arb_binary(closed, binPhi, phiValues_binary); + /// check the global position requests + // | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | + BOOST_CHECK_EQUAL(xData_eq.center(3), 3.5); + // | 0 | 1 | 2 | 3 | 4 | 10 | + BOOST_CHECK_EQUAL(xData_arb.center(4), 7.); + // | 0 | 1 | 1.5 | 2 | 3 | 4 | 5 | + BOOST_CHECK_EQUAL(xData_add.center(0), 0.5); + BOOST_CHECK_EQUAL(xData_add.center(1), 1.25); + BOOST_CHECK_EQUAL(xData_add.center(4), 3.5); + // | 0 | 1 | 1.5 | 2 | 3 | 4 | 4.5 | 5 | 6 | 7 | 7.5 | 8 | 9 | + BOOST_CHECK_EQUAL(xData_mult.center(0), 0.5); + BOOST_CHECK_EQUAL(xData_mult.center(1), 1.25); + BOOST_CHECK_EQUAL(xData_mult.center(4), 3.5); + BOOST_CHECK_EQUAL(xData_mult.center(10), 7.75); + BOOST_CHECK_EQUAL(xData_mult.center(11), 8.5); + + BOOST_CHECK_EQUAL(xData_arb_binary.center(0), 0.5 * delta); + + // open values + std::vector<float> center = {0.5, 1.5, 2.5, 3.5, 4.5, + 5.5, 6.5, 7.5, 8.5, 9.5}; + for (size_t ib = 0; ib < center.size(); ++ib) { + BOOST_CHECK_EQUAL(xData_eq.center(ib), center[ib]); } - // special test for phi binning - BOOST_AUTO_TEST_CASE(BinningData_phi_modules) - { - // n phi modules with phi boundary at -M_Pi/+M_PI are checked above - // one module expands over -M_Pi/+M_PI - float deltaPhi = 0.1; - BinningData phiData_mod( - closed, binPhi, 5, -M_PI + deltaPhi, M_PI + deltaPhi); - float phiStep = M_PI * 2. / 5.; - std::vector<float> phiBoundaries_mod - = {float(-M_PI + deltaPhi), - float(-M_PI + 1 * phiStep) + deltaPhi, - float(-M_PI + 2 * phiStep) + deltaPhi, - float(-M_PI + 3 * phiStep) + deltaPhi, - float(-M_PI + 4 * phiStep) + deltaPhi, - float(-M_PI + 5 * phiStep) + deltaPhi}; - // this is the boundary test - CHECK_CLOSE_REL(phiData_mod.boundaries(), phiBoundaries_mod, 1e-5); - - // now test the bin jump 0/maxbin - - float firstAngle = (-M_PI + 1.5 * deltaPhi); - Vector3D firstBin(cos(firstAngle), sin(firstAngle), 0.); - BOOST_CHECK_EQUAL(phiData_mod.search(firstAngle), size_t(0)); - BOOST_CHECK_EQUAL(phiData_mod.searchGlobal(firstBin), size_t(0)); - - float firstAngleNeg = (-M_PI + 0.5 * deltaPhi); - Vector3D lastBinNeg(cos(firstAngleNeg), sin(firstAngleNeg), 0.); - BOOST_CHECK_EQUAL(phiData_mod.search(firstAngleNeg), size_t(4)); - BOOST_CHECK_EQUAL(phiData_mod.searchGlobal(lastBinNeg), size_t(4)); - - float lastAnglePos = (M_PI + 0.5 * deltaPhi); - Vector3D lastBinPos(cos(lastAnglePos), sin(lastAnglePos), 0.); - BOOST_CHECK_EQUAL(phiData_mod.search(lastAnglePos), size_t(4)); - BOOST_CHECK_EQUAL(phiData_mod.searchGlobal(lastBinPos), size_t(4)); - - // now test the (remaining) phi scaling - float underscaledAngle = -M_PI - 0.5 * deltaPhi; - Vector3D underscaledPos(cos(underscaledAngle), sin(underscaledAngle), 0.); - BOOST_CHECK_EQUAL(phiData_mod.search(underscaledAngle), size_t(4)); - BOOST_CHECK_EQUAL(phiData_mod.searchGlobal(underscaledPos), size_t(4)); + // running into rounding errors here + float phiStep = M_PI * 2. / 5.; + std::vector<float> phiCenters_eq = { + float(-M_PI + 0.5 * phiStep), float(-M_PI + 1.5 * phiStep), + float(-M_PI + 2.5 * phiStep), float(-M_PI + 3.5 * phiStep), + float(-M_PI + 4.5 * phiStep)}; + + for (size_t ib = 0; ib < phiCenters_eq.size(); ++ib) { + CHECK_CLOSE_ABS(phiData_eq.center(ib), phiCenters_eq[ib], 1e-3); } +} + +// special test for phi binning +BOOST_AUTO_TEST_CASE(BinningData_phi_modules) { + // n phi modules with phi boundary at -M_Pi/+M_PI are checked above + // one module expands over -M_Pi/+M_PI + float deltaPhi = 0.1; + BinningData phiData_mod(closed, binPhi, 5, -M_PI + deltaPhi, M_PI + deltaPhi); + float phiStep = M_PI * 2. / 5.; + std::vector<float> phiBoundaries_mod = { + float(-M_PI + deltaPhi), + float(-M_PI + 1 * phiStep) + deltaPhi, + float(-M_PI + 2 * phiStep) + deltaPhi, + float(-M_PI + 3 * phiStep) + deltaPhi, + float(-M_PI + 4 * phiStep) + deltaPhi, + float(-M_PI + 5 * phiStep) + deltaPhi}; + // this is the boundary test + CHECK_CLOSE_REL(phiData_mod.boundaries(), phiBoundaries_mod, 1e-5); + + // now test the bin jump 0/maxbin + + float firstAngle = (-M_PI + 1.5 * deltaPhi); + Vector3D firstBin(cos(firstAngle), sin(firstAngle), 0.); + BOOST_CHECK_EQUAL(phiData_mod.search(firstAngle), size_t(0)); + BOOST_CHECK_EQUAL(phiData_mod.searchGlobal(firstBin), size_t(0)); + + float firstAngleNeg = (-M_PI + 0.5 * deltaPhi); + Vector3D lastBinNeg(cos(firstAngleNeg), sin(firstAngleNeg), 0.); + BOOST_CHECK_EQUAL(phiData_mod.search(firstAngleNeg), size_t(4)); + BOOST_CHECK_EQUAL(phiData_mod.searchGlobal(lastBinNeg), size_t(4)); + + float lastAnglePos = (M_PI + 0.5 * deltaPhi); + Vector3D lastBinPos(cos(lastAnglePos), sin(lastAnglePos), 0.); + BOOST_CHECK_EQUAL(phiData_mod.search(lastAnglePos), size_t(4)); + BOOST_CHECK_EQUAL(phiData_mod.searchGlobal(lastBinPos), size_t(4)); + + // now test the (remaining) phi scaling + float underscaledAngle = -M_PI - 0.5 * deltaPhi; + Vector3D underscaledPos(cos(underscaledAngle), sin(underscaledAngle), 0.); + BOOST_CHECK_EQUAL(phiData_mod.search(underscaledAngle), size_t(4)); + BOOST_CHECK_EQUAL(phiData_mod.searchGlobal(underscaledPos), size_t(4)); +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/Utilities/ExtendableTests.cpp b/Tests/Core/Utilities/ExtendableTests.cpp index f744152317ea6c28be61330adaf608d7b017cf61..df7cf6f0d7dcc6cb63bc5dd6658b3124a514f474 100644 --- a/Tests/Core/Utilities/ExtendableTests.cpp +++ b/Tests/Core/Utilities/ExtendableTests.cpp @@ -22,56 +22,52 @@ #include "Acts/Utilities/detail/Extendable.hpp" namespace bdata = boost::unit_test::data; -namespace tt = boost::test_tools; +namespace tt = boost::test_tools; namespace Acts { namespace Test { - // This tests the implementation of the ActionList - // and the standard aborters - BOOST_AUTO_TEST_CASE(Extendable_) - { - struct TypeA - { - double vaA = 0.; - }; - - struct TypeB - { - int vaB = 0; - }; - - struct TypeC - { - char vaC = '0'; - }; - - // Test the empty list - detail::Extendable<> nullist; - (void)nullist; - BOOST_CHECK_EQUAL(std::tuple_size<std::tuple<>>::value, 0); - - detail::Extendable<TypeA> alist; - auto& a0_object = alist.get<TypeA>(); - a0_object.vaA = 1.; - BOOST_CHECK_EQUAL(alist.get<TypeA>().vaA, 1.); - - detail::Extendable<TypeA, TypeB> ablist; - auto& a1_object = ablist.get<TypeA>(); - a1_object.vaA = 2.; - auto& b1_object = ablist.get<TypeB>(); - b1_object.vaB = 3; - BOOST_CHECK_EQUAL(ablist.get<TypeA>().vaA, 2.); - BOOST_CHECK_EQUAL(ablist.get<TypeB>().vaB, 3); - - TypeC c; - c.vaC = '4'; - detail::Extendable<TypeA, TypeB, TypeC> abcList = ablist.append<TypeC>(c); - BOOST_CHECK_EQUAL(abcList.get<TypeA>().vaA, 2.); - BOOST_CHECK_EQUAL(abcList.get<TypeB>().vaB, 3); - BOOST_CHECK_EQUAL(abcList.get<TypeC>().vaC, '4'); - } +// This tests the implementation of the ActionList +// and the standard aborters +BOOST_AUTO_TEST_CASE(Extendable_) { + struct TypeA { + double vaA = 0.; + }; + + struct TypeB { + int vaB = 0; + }; + + struct TypeC { + char vaC = '0'; + }; + + // Test the empty list + detail::Extendable<> nullist; + (void)nullist; + BOOST_CHECK_EQUAL(std::tuple_size<std::tuple<>>::value, 0); + + detail::Extendable<TypeA> alist; + auto& a0_object = alist.get<TypeA>(); + a0_object.vaA = 1.; + BOOST_CHECK_EQUAL(alist.get<TypeA>().vaA, 1.); + + detail::Extendable<TypeA, TypeB> ablist; + auto& a1_object = ablist.get<TypeA>(); + a1_object.vaA = 2.; + auto& b1_object = ablist.get<TypeB>(); + b1_object.vaB = 3; + BOOST_CHECK_EQUAL(ablist.get<TypeA>().vaA, 2.); + BOOST_CHECK_EQUAL(ablist.get<TypeB>().vaB, 3); + + TypeC c; + c.vaC = '4'; + detail::Extendable<TypeA, TypeB, TypeC> abcList = ablist.append<TypeC>(c); + BOOST_CHECK_EQUAL(abcList.get<TypeA>().vaA, 2.); + BOOST_CHECK_EQUAL(abcList.get<TypeB>().vaB, 3); + BOOST_CHECK_EQUAL(abcList.get<TypeC>().vaC, '4'); +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/Utilities/GeometryIDTests.cpp b/Tests/Core/Utilities/GeometryIDTests.cpp index 7cbe92eed527ab2259240f4a6b060c5fdd59a571..563aa8bd5c6f4088f7d2d0d1f116e445d94b4dbf 100644 --- a/Tests/Core/Utilities/GeometryIDTests.cpp +++ b/Tests/Core/Utilities/GeometryIDTests.cpp @@ -16,102 +16,99 @@ namespace Acts { namespace Test { - geo_id_value volume_mask = GeometryID::volume_mask; - geo_id_value boundary_mask = GeometryID::boundary_mask; - geo_id_value layer_mask = GeometryID::layer_mask; - geo_id_value approach_mask = GeometryID::approach_mask; - geo_id_value sensitive_mask = GeometryID::sensitive_mask; - - /// test of the geometry ID creation and consistency of the ranges - BOOST_AUTO_TEST_CASE(GeometryID_test) - { - // create the volume shift and range - geo_id_value volume_range = 64 - ACTS_BIT_SHIFT(volume_mask); - - geo_id_value boundary_range - = ACTS_BIT_SHIFT(volume_mask) - ACTS_BIT_SHIFT(boundary_mask); - - geo_id_value layer_range - = ACTS_BIT_SHIFT(boundary_mask) - ACTS_BIT_SHIFT(layer_mask); - - geo_id_value approach_range - = ACTS_BIT_SHIFT(layer_mask) - ACTS_BIT_SHIFT(approach_mask); - - geo_id_value sensitive_range - = ACTS_BIT_SHIFT(approach_mask) - ACTS_BIT_SHIFT(sensitive_mask); - - /// prepare all the masks and shifts - std::vector<std::pair<geo_id_value, geo_id_value>> masks_range - = {{volume_mask, volume_range}, - {boundary_mask, boundary_range}, - {layer_mask, layer_range}, - {approach_mask, approach_range}, - {sensitive_mask, sensitive_range}}; - - for (auto msr : masks_range) { - - auto mask = msr.first; - auto range = msr.second; - /// test range by [0, 1, 2^range-1] - std::vector<geo_id_value> range_values - = {0, 1, (geo_id_value(1) << range) - 1}; - for (auto& idv : range_values) { - // create the geometry ID - GeometryID geoID(idv, mask); - // encode - decode test - BOOST_CHECK_EQUAL(idv, - (ACTS_BIT_DECODE(ACTS_BIT_ENCODE(idv, mask), mask))); - // geo id decoding - BOOST_CHECK_EQUAL(idv, geoID.value(mask)); - } +geo_id_value volume_mask = GeometryID::volume_mask; +geo_id_value boundary_mask = GeometryID::boundary_mask; +geo_id_value layer_mask = GeometryID::layer_mask; +geo_id_value approach_mask = GeometryID::approach_mask; +geo_id_value sensitive_mask = GeometryID::sensitive_mask; + +/// test of the geometry ID creation and consistency of the ranges +BOOST_AUTO_TEST_CASE(GeometryID_test) { + // create the volume shift and range + geo_id_value volume_range = 64 - ACTS_BIT_SHIFT(volume_mask); + + geo_id_value boundary_range = + ACTS_BIT_SHIFT(volume_mask) - ACTS_BIT_SHIFT(boundary_mask); + + geo_id_value layer_range = + ACTS_BIT_SHIFT(boundary_mask) - ACTS_BIT_SHIFT(layer_mask); + + geo_id_value approach_range = + ACTS_BIT_SHIFT(layer_mask) - ACTS_BIT_SHIFT(approach_mask); + + geo_id_value sensitive_range = + ACTS_BIT_SHIFT(approach_mask) - ACTS_BIT_SHIFT(sensitive_mask); + + /// prepare all the masks and shifts + std::vector<std::pair<geo_id_value, geo_id_value>> masks_range = { + {volume_mask, volume_range}, + {boundary_mask, boundary_range}, + {layer_mask, layer_range}, + {approach_mask, approach_range}, + {sensitive_mask, sensitive_range}}; + + for (auto msr : masks_range) { + auto mask = msr.first; + auto range = msr.second; + /// test range by [0, 1, 2^range-1] + std::vector<geo_id_value> range_values = {0, 1, + (geo_id_value(1) << range) - 1}; + for (auto& idv : range_values) { + // create the geometry ID + GeometryID geoID(idv, mask); + // encode - decode test + BOOST_CHECK_EQUAL(idv, + (ACTS_BIT_DECODE(ACTS_BIT_ENCODE(idv, mask), mask))); + // geo id decoding + BOOST_CHECK_EQUAL(idv, geoID.value(mask)); } } - - /// test the full encoding / decoding chain - BOOST_AUTO_TEST_CASE(FullGeometryID_test) - { - // decode the IDs - GeometryID volumeID(1, GeometryID::volume_mask); - GeometryID boundaryID(2, GeometryID::boundary_mask); - GeometryID layerID(3, GeometryID::layer_mask); - GeometryID approachID(4, GeometryID::approach_mask); - GeometryID sensitiveID(5, GeometryID::sensitive_mask); - - // now check the validity before adding - BOOST_CHECK_EQUAL(1lu, volumeID.value(GeometryID::volume_mask)); - BOOST_CHECK_EQUAL(2lu, boundaryID.value(GeometryID::boundary_mask)); - BOOST_CHECK_EQUAL(3lu, layerID.value(GeometryID::layer_mask)); - BOOST_CHECK_EQUAL(4lu, approachID.value(GeometryID::approach_mask)); - BOOST_CHECK_EQUAL(5lu, sensitiveID.value(GeometryID::sensitive_mask)); - - // now create a compound ones - GeometryID compoundID_dconst; - compoundID_dconst += volumeID; - GeometryID compoundID_cconst(volumeID); - GeometryID compoundID_assign = volumeID; - - std::vector<GeometryID> compoundIDs - = {compoundID_dconst, compoundID_cconst, compoundID_assign}; - - /// check the validity after assigning/copying/constructing - BOOST_CHECK_EQUAL(1lu, compoundID_dconst.value(GeometryID::volume_mask)); - BOOST_CHECK_EQUAL(1lu, compoundID_cconst.value(GeometryID::volume_mask)); - BOOST_CHECK_EQUAL(1lu, compoundID_assign.value(GeometryID::volume_mask)); - - for (auto& cid : compoundIDs) { - // add the sub IDs - cid += boundaryID; - cid += layerID; - cid += approachID; - cid += sensitiveID; - // now check the cid - BOOST_CHECK_EQUAL(1lu, cid.value(GeometryID::volume_mask)); - BOOST_CHECK_EQUAL(2lu, cid.value(GeometryID::boundary_mask)); - BOOST_CHECK_EQUAL(3lu, cid.value(GeometryID::layer_mask)); - BOOST_CHECK_EQUAL(4lu, cid.value(GeometryID::approach_mask)); - BOOST_CHECK_EQUAL(5lu, cid.value(GeometryID::sensitive_mask)); - } +} + +/// test the full encoding / decoding chain +BOOST_AUTO_TEST_CASE(FullGeometryID_test) { + // decode the IDs + GeometryID volumeID(1, GeometryID::volume_mask); + GeometryID boundaryID(2, GeometryID::boundary_mask); + GeometryID layerID(3, GeometryID::layer_mask); + GeometryID approachID(4, GeometryID::approach_mask); + GeometryID sensitiveID(5, GeometryID::sensitive_mask); + + // now check the validity before adding + BOOST_CHECK_EQUAL(1lu, volumeID.value(GeometryID::volume_mask)); + BOOST_CHECK_EQUAL(2lu, boundaryID.value(GeometryID::boundary_mask)); + BOOST_CHECK_EQUAL(3lu, layerID.value(GeometryID::layer_mask)); + BOOST_CHECK_EQUAL(4lu, approachID.value(GeometryID::approach_mask)); + BOOST_CHECK_EQUAL(5lu, sensitiveID.value(GeometryID::sensitive_mask)); + + // now create a compound ones + GeometryID compoundID_dconst; + compoundID_dconst += volumeID; + GeometryID compoundID_cconst(volumeID); + GeometryID compoundID_assign = volumeID; + + std::vector<GeometryID> compoundIDs = {compoundID_dconst, compoundID_cconst, + compoundID_assign}; + + /// check the validity after assigning/copying/constructing + BOOST_CHECK_EQUAL(1lu, compoundID_dconst.value(GeometryID::volume_mask)); + BOOST_CHECK_EQUAL(1lu, compoundID_cconst.value(GeometryID::volume_mask)); + BOOST_CHECK_EQUAL(1lu, compoundID_assign.value(GeometryID::volume_mask)); + + for (auto& cid : compoundIDs) { + // add the sub IDs + cid += boundaryID; + cid += layerID; + cid += approachID; + cid += sensitiveID; + // now check the cid + BOOST_CHECK_EQUAL(1lu, cid.value(GeometryID::volume_mask)); + BOOST_CHECK_EQUAL(2lu, cid.value(GeometryID::boundary_mask)); + BOOST_CHECK_EQUAL(3lu, cid.value(GeometryID::layer_mask)); + BOOST_CHECK_EQUAL(4lu, cid.value(GeometryID::approach_mask)); + BOOST_CHECK_EQUAL(5lu, cid.value(GeometryID::sensitive_mask)); } +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/Utilities/GridTests.cpp b/Tests/Core/Utilities/GridTests.cpp index 30c971ce2f5df7c6da6e1bf1e865b879e62aecc9..2b35b90083141d0cf45f4273784f7efbd3521bdc 100644 --- a/Tests/Core/Utilities/GridTests.cpp +++ b/Tests/Core/Utilities/GridTests.cpp @@ -25,1025 +25,1002 @@ using namespace detail; namespace Test { - BOOST_AUTO_TEST_CASE(grid_test_1d_equidistant) - { - using Point = std::array<double, 1>; - using indices = std::array<size_t, 1>; - EquidistantAxis a(0.0, 4.0, 4u); - Grid<double, EquidistantAxis> g(std::make_tuple(std::move(a))); - - // test general properties - BOOST_CHECK_EQUAL(g.size(), 6u); - BOOST_CHECK_EQUAL(g.numLocalBins().at(0), 4u); - - // global bin index - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-0.3}})), 0u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-0.}})), 1u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.}})), 1u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.7}})), 1u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1}})), 2u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1.2}})), 2u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2.}})), 3u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2.7}})), 3u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{3.}})), 4u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{3.9999}})), 4u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{4.}})), 5u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{4.98}})), 5u); - - // global bin index -> local bin indices - BOOST_CHECK(g.localBinsFromGlobalBin(0) == indices({{0}})); - BOOST_CHECK(g.localBinsFromGlobalBin(1) == indices({{1}})); - BOOST_CHECK(g.localBinsFromGlobalBin(2) == indices({{2}})); - BOOST_CHECK(g.localBinsFromGlobalBin(3) == indices({{3}})); - BOOST_CHECK(g.localBinsFromGlobalBin(4) == indices({{4}})); - BOOST_CHECK(g.localBinsFromGlobalBin(5) == indices({{5}})); - - // local bin indices -> global bin index - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0}}), 0u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1}}), 1u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2}}), 2u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3}}), 3u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{4}}), 4u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{5}}), 5u); - - BOOST_CHECK( - g.localBinsFromGlobalBin(g.globalBinFromPosition(Point({{2.7}}))) - == indices({{3}})); - - // inside checks - BOOST_CHECK(not g.isInside(Point({{-2.}}))); - BOOST_CHECK(g.isInside(Point({{0.}}))); - BOOST_CHECK(g.isInside(Point({{2.5}}))); - BOOST_CHECK(not g.isInside(Point({{4.}}))); - BOOST_CHECK(not g.isInside(Point({{6.}}))); - - // test some bin centers - CHECK_CLOSE_ABS(g.binCenter({{1}}), Point({{0.5}}), 1e-6); - CHECK_CLOSE_ABS(g.binCenter({{2}}), Point({{1.5}}), 1e-6); - CHECK_CLOSE_ABS(g.binCenter({{3}}), Point({{2.5}}), 1e-6); - CHECK_CLOSE_ABS(g.binCenter({{4}}), Point({{3.5}}), 1e-6); - - // test some lower-left bin edges - CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{1}}), Point({{0.}}), 1e-6); - CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{2}}), Point({{1.}}), 1e-6); - CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{3}}), Point({{2.}}), 1e-6); - CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{4}}), Point({{3.}}), 1e-6); - - // test some upper right-bin edges - CHECK_CLOSE_ABS(g.upperRightBinEdge({{1}}), Point({{1.}}), 1e-6); - CHECK_CLOSE_ABS(g.upperRightBinEdge({{2}}), Point({{2.}}), 1e-6); - CHECK_CLOSE_ABS(g.upperRightBinEdge({{3}}), Point({{3.}}), 1e-6); - CHECK_CLOSE_ABS(g.upperRightBinEdge({{4}}), Point({{4.}}), 1e-6); - - // initialize grid - for (size_t bin = 0; bin < g.size(); ++bin) { - g.at(bin) = bin; - } - - // consistency of access - const auto& point = Point({{0.7}}); - size_t globalBin = g.globalBinFromPosition(point); - indices localBins = g.localBinsFromGlobalBin(globalBin); - - BOOST_CHECK_EQUAL(g.atPosition(point), g.at(globalBin)); - BOOST_CHECK_EQUAL(g.atPosition(point), g.atLocalBins(localBins)); +BOOST_AUTO_TEST_CASE(grid_test_1d_equidistant) { + using Point = std::array<double, 1>; + using indices = std::array<size_t, 1>; + EquidistantAxis a(0.0, 4.0, 4u); + Grid<double, EquidistantAxis> g(std::make_tuple(std::move(a))); + + // test general properties + BOOST_CHECK_EQUAL(g.size(), 6u); + BOOST_CHECK_EQUAL(g.numLocalBins().at(0), 4u); + + // global bin index + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-0.3}})), 0u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-0.}})), 1u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.}})), 1u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.7}})), 1u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1}})), 2u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1.2}})), 2u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2.}})), 3u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2.7}})), 3u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{3.}})), 4u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{3.9999}})), 4u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{4.}})), 5u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{4.98}})), 5u); + + // global bin index -> local bin indices + BOOST_CHECK(g.localBinsFromGlobalBin(0) == indices({{0}})); + BOOST_CHECK(g.localBinsFromGlobalBin(1) == indices({{1}})); + BOOST_CHECK(g.localBinsFromGlobalBin(2) == indices({{2}})); + BOOST_CHECK(g.localBinsFromGlobalBin(3) == indices({{3}})); + BOOST_CHECK(g.localBinsFromGlobalBin(4) == indices({{4}})); + BOOST_CHECK(g.localBinsFromGlobalBin(5) == indices({{5}})); + + // local bin indices -> global bin index + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0}}), 0u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1}}), 1u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2}}), 2u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3}}), 3u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{4}}), 4u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{5}}), 5u); + + BOOST_CHECK(g.localBinsFromGlobalBin( + g.globalBinFromPosition(Point({{2.7}}))) == indices({{3}})); + + // inside checks + BOOST_CHECK(not g.isInside(Point({{-2.}}))); + BOOST_CHECK(g.isInside(Point({{0.}}))); + BOOST_CHECK(g.isInside(Point({{2.5}}))); + BOOST_CHECK(not g.isInside(Point({{4.}}))); + BOOST_CHECK(not g.isInside(Point({{6.}}))); + + // test some bin centers + CHECK_CLOSE_ABS(g.binCenter({{1}}), Point({{0.5}}), 1e-6); + CHECK_CLOSE_ABS(g.binCenter({{2}}), Point({{1.5}}), 1e-6); + CHECK_CLOSE_ABS(g.binCenter({{3}}), Point({{2.5}}), 1e-6); + CHECK_CLOSE_ABS(g.binCenter({{4}}), Point({{3.5}}), 1e-6); + + // test some lower-left bin edges + CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{1}}), Point({{0.}}), 1e-6); + CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{2}}), Point({{1.}}), 1e-6); + CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{3}}), Point({{2.}}), 1e-6); + CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{4}}), Point({{3.}}), 1e-6); + + // test some upper right-bin edges + CHECK_CLOSE_ABS(g.upperRightBinEdge({{1}}), Point({{1.}}), 1e-6); + CHECK_CLOSE_ABS(g.upperRightBinEdge({{2}}), Point({{2.}}), 1e-6); + CHECK_CLOSE_ABS(g.upperRightBinEdge({{3}}), Point({{3.}}), 1e-6); + CHECK_CLOSE_ABS(g.upperRightBinEdge({{4}}), Point({{4.}}), 1e-6); + + // initialize grid + for (size_t bin = 0; bin < g.size(); ++bin) { + g.at(bin) = bin; } - BOOST_AUTO_TEST_CASE(grid_test_2d_equidistant) - { - using Point = std::array<double, 2>; - using indices = std::array<size_t, 2>; - EquidistantAxis a(0.0, 4.0, 4u); - EquidistantAxis b(0.0, 3.0, 3u); - Grid<double, EquidistantAxis, EquidistantAxis> g( - std::make_tuple(std::move(a), std::move(b))); - - // test general properties - BOOST_CHECK_EQUAL(g.size(), 30u); - BOOST_CHECK_EQUAL(g.numLocalBins().at(0), 4u); - BOOST_CHECK_EQUAL(g.numLocalBins().at(1), 3u); - - // global bin index - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-1, -1}})), 0u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-1, 0}})), 1u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-1, 1}})), 2u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-1, 2}})), 3u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-1, 3}})), 4u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, -1}})), 5u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 0}})), 6u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 1}})), 7u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 2}})), 8u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 3}})), 9u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, -1}})), 10u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 0}})), 11u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 1}})), 12u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 2}})), 13u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 3}})), 14u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, -1}})), 15u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, 0}})), 16u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, 1}})), 17u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, 2}})), 18u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, 3}})), 19u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{3, -1}})), 20u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{3, 0}})), 21u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{3, 1}})), 22u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{3, 2}})), 23u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{3, 3}})), 24u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{4, -1}})), 25u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{4, 0}})), 26u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{4, 1}})), 27u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{4, 2}})), 28u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{4, 3}})), 29u); - - // test some arbitrary points - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1.2, 0.3}})), 11u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2.2, 3.3}})), 19u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.9, 1.8}})), 7u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{3.7, 3.1}})), 24u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1.4, 2.3}})), 13u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-3, 3}})), 4u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{8, 1}})), 27u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, -3}})), 10u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{3, 11}})), 24u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-2, -3}})), 0u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-2, 7}})), 04u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{12, -1}})), 25u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{12, 11}})), 29u); - - // global bin index -> local bin indices - BOOST_CHECK(g.localBinsFromGlobalBin(0) == indices({{0, 0}})); - BOOST_CHECK(g.localBinsFromGlobalBin(1) == indices({{0, 1}})); - BOOST_CHECK(g.localBinsFromGlobalBin(2) == indices({{0, 2}})); - BOOST_CHECK(g.localBinsFromGlobalBin(3) == indices({{0, 3}})); - BOOST_CHECK(g.localBinsFromGlobalBin(4) == indices({{0, 4}})); - BOOST_CHECK(g.localBinsFromGlobalBin(5) == indices({{1, 0}})); - BOOST_CHECK(g.localBinsFromGlobalBin(6) == indices({{1, 1}})); - BOOST_CHECK(g.localBinsFromGlobalBin(7) == indices({{1, 2}})); - BOOST_CHECK(g.localBinsFromGlobalBin(8) == indices({{1, 3}})); - BOOST_CHECK(g.localBinsFromGlobalBin(9) == indices({{1, 4}})); - BOOST_CHECK(g.localBinsFromGlobalBin(10) == indices({{2, 0}})); - BOOST_CHECK(g.localBinsFromGlobalBin(11) == indices({{2, 1}})); - BOOST_CHECK(g.localBinsFromGlobalBin(12) == indices({{2, 2}})); - BOOST_CHECK(g.localBinsFromGlobalBin(13) == indices({{2, 3}})); - BOOST_CHECK(g.localBinsFromGlobalBin(14) == indices({{2, 4}})); - BOOST_CHECK(g.localBinsFromGlobalBin(15) == indices({{3, 0}})); - BOOST_CHECK(g.localBinsFromGlobalBin(16) == indices({{3, 1}})); - BOOST_CHECK(g.localBinsFromGlobalBin(17) == indices({{3, 2}})); - BOOST_CHECK(g.localBinsFromGlobalBin(18) == indices({{3, 3}})); - BOOST_CHECK(g.localBinsFromGlobalBin(19) == indices({{3, 4}})); - BOOST_CHECK(g.localBinsFromGlobalBin(20) == indices({{4, 0}})); - BOOST_CHECK(g.localBinsFromGlobalBin(21) == indices({{4, 1}})); - BOOST_CHECK(g.localBinsFromGlobalBin(22) == indices({{4, 2}})); - BOOST_CHECK(g.localBinsFromGlobalBin(23) == indices({{4, 3}})); - BOOST_CHECK(g.localBinsFromGlobalBin(24) == indices({{4, 4}})); - BOOST_CHECK(g.localBinsFromGlobalBin(25) == indices({{5, 0}})); - BOOST_CHECK(g.localBinsFromGlobalBin(26) == indices({{5, 1}})); - BOOST_CHECK(g.localBinsFromGlobalBin(27) == indices({{5, 2}})); - BOOST_CHECK(g.localBinsFromGlobalBin(28) == indices({{5, 3}})); - BOOST_CHECK(g.localBinsFromGlobalBin(29) == indices({{5, 4}})); - - // local bin indices -> global bin index - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 0}}), 0u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 1}}), 1u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 2}}), 2u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 3}}), 3u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 4}}), 4u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 0}}), 5u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 1}}), 6u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 2}}), 7u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 3}}), 8u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 4}}), 9u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 0}}), 10u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 1}}), 11u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 2}}), 12u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 3}}), 13u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 4}}), 14u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 0}}), 15u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 1}}), 16u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 2}}), 17u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 3}}), 18u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 4}}), 19u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{4, 0}}), 20u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{4, 1}}), 21u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{4, 2}}), 22u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{4, 3}}), 23u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{4, 4}}), 24u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{5, 0}}), 25u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{5, 1}}), 26u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{5, 2}}), 27u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{5, 3}}), 28u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{5, 4}}), 29u); - - BOOST_CHECK( - g.localBinsFromGlobalBin(g.globalBinFromPosition(Point({{1.2, 0.7}}))) - == indices({{2, 1}})); - - // inside checks - BOOST_CHECK(not g.isInside(Point({{-2., -1}}))); - BOOST_CHECK(not g.isInside(Point({{-2., 1.}}))); - BOOST_CHECK(not g.isInside(Point({{-2., 5.}}))); - BOOST_CHECK(not g.isInside(Point({{1., -1.}}))); - BOOST_CHECK(not g.isInside(Point({{6., -1.}}))); - BOOST_CHECK(g.isInside(Point({{0.5, 1.3}}))); - BOOST_CHECK(not g.isInside(Point({{4., -1.}}))); - BOOST_CHECK(not g.isInside(Point({{4., 0.3}}))); - BOOST_CHECK(not g.isInside(Point({{4., 3.}}))); - BOOST_CHECK(not g.isInside(Point({{-1., 3.}}))); - BOOST_CHECK(not g.isInside(Point({{2., 3.}}))); - BOOST_CHECK(not g.isInside(Point({{5., 3.}}))); - - // test some bin centers - CHECK_CLOSE_ABS(g.binCenter({{1, 1}}), Point({{0.5, 0.5}}), 1e-6); - CHECK_CLOSE_ABS(g.binCenter({{2, 3}}), Point({{1.5, 2.5}}), 1e-6); - CHECK_CLOSE_ABS(g.binCenter({{3, 1}}), Point({{2.5, 0.5}}), 1e-6); - CHECK_CLOSE_ABS(g.binCenter({{4, 2}}), Point({{3.5, 1.5}}), 1e-6); - - // test some lower-left bin edges - CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{1, 1}}), Point({{0., 0.}}), 1e-6); - CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{2, 3}}), Point({{1., 2.}}), 1e-6); - CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{3, 1}}), Point({{2., 0.}}), 1e-6); - CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{4, 2}}), Point({{3., 1.}}), 1e-6); - - // test some upper right-bin edges - CHECK_CLOSE_ABS(g.upperRightBinEdge({{1, 1}}), Point({{1., 1.}}), 1e-6); - CHECK_CLOSE_ABS(g.upperRightBinEdge({{2, 3}}), Point({{2., 3.}}), 1e-6); - CHECK_CLOSE_ABS(g.upperRightBinEdge({{3, 1}}), Point({{3., 1.}}), 1e-6); - CHECK_CLOSE_ABS(g.upperRightBinEdge({{4, 2}}), Point({{4., 2.}}), 1e-6); - - // initialize grid - for (size_t bin = 0; bin < g.size(); ++bin) { - g.at(bin) = bin; - } - - // consistency of access - const auto& point = Point({{0.7, 1.3}}); - size_t globalBin = g.globalBinFromPosition(point); - indices localBins = g.localBinsFromGlobalBin(globalBin); - - BOOST_CHECK_EQUAL(g.atPosition(point), g.at(globalBin)); - BOOST_CHECK_EQUAL(g.atPosition(point), g.atLocalBins(localBins)); + // consistency of access + const auto& point = Point({{0.7}}); + size_t globalBin = g.globalBinFromPosition(point); + indices localBins = g.localBinsFromGlobalBin(globalBin); + + BOOST_CHECK_EQUAL(g.atPosition(point), g.at(globalBin)); + BOOST_CHECK_EQUAL(g.atPosition(point), g.atLocalBins(localBins)); +} + +BOOST_AUTO_TEST_CASE(grid_test_2d_equidistant) { + using Point = std::array<double, 2>; + using indices = std::array<size_t, 2>; + EquidistantAxis a(0.0, 4.0, 4u); + EquidistantAxis b(0.0, 3.0, 3u); + Grid<double, EquidistantAxis, EquidistantAxis> g( + std::make_tuple(std::move(a), std::move(b))); + + // test general properties + BOOST_CHECK_EQUAL(g.size(), 30u); + BOOST_CHECK_EQUAL(g.numLocalBins().at(0), 4u); + BOOST_CHECK_EQUAL(g.numLocalBins().at(1), 3u); + + // global bin index + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-1, -1}})), 0u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-1, 0}})), 1u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-1, 1}})), 2u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-1, 2}})), 3u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-1, 3}})), 4u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, -1}})), 5u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 0}})), 6u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 1}})), 7u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 2}})), 8u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 3}})), 9u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, -1}})), 10u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 0}})), 11u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 1}})), 12u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 2}})), 13u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 3}})), 14u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, -1}})), 15u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, 0}})), 16u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, 1}})), 17u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, 2}})), 18u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, 3}})), 19u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{3, -1}})), 20u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{3, 0}})), 21u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{3, 1}})), 22u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{3, 2}})), 23u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{3, 3}})), 24u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{4, -1}})), 25u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{4, 0}})), 26u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{4, 1}})), 27u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{4, 2}})), 28u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{4, 3}})), 29u); + + // test some arbitrary points + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1.2, 0.3}})), 11u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2.2, 3.3}})), 19u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.9, 1.8}})), 7u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{3.7, 3.1}})), 24u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1.4, 2.3}})), 13u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-3, 3}})), 4u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{8, 1}})), 27u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, -3}})), 10u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{3, 11}})), 24u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-2, -3}})), 0u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-2, 7}})), 04u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{12, -1}})), 25u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{12, 11}})), 29u); + + // global bin index -> local bin indices + BOOST_CHECK(g.localBinsFromGlobalBin(0) == indices({{0, 0}})); + BOOST_CHECK(g.localBinsFromGlobalBin(1) == indices({{0, 1}})); + BOOST_CHECK(g.localBinsFromGlobalBin(2) == indices({{0, 2}})); + BOOST_CHECK(g.localBinsFromGlobalBin(3) == indices({{0, 3}})); + BOOST_CHECK(g.localBinsFromGlobalBin(4) == indices({{0, 4}})); + BOOST_CHECK(g.localBinsFromGlobalBin(5) == indices({{1, 0}})); + BOOST_CHECK(g.localBinsFromGlobalBin(6) == indices({{1, 1}})); + BOOST_CHECK(g.localBinsFromGlobalBin(7) == indices({{1, 2}})); + BOOST_CHECK(g.localBinsFromGlobalBin(8) == indices({{1, 3}})); + BOOST_CHECK(g.localBinsFromGlobalBin(9) == indices({{1, 4}})); + BOOST_CHECK(g.localBinsFromGlobalBin(10) == indices({{2, 0}})); + BOOST_CHECK(g.localBinsFromGlobalBin(11) == indices({{2, 1}})); + BOOST_CHECK(g.localBinsFromGlobalBin(12) == indices({{2, 2}})); + BOOST_CHECK(g.localBinsFromGlobalBin(13) == indices({{2, 3}})); + BOOST_CHECK(g.localBinsFromGlobalBin(14) == indices({{2, 4}})); + BOOST_CHECK(g.localBinsFromGlobalBin(15) == indices({{3, 0}})); + BOOST_CHECK(g.localBinsFromGlobalBin(16) == indices({{3, 1}})); + BOOST_CHECK(g.localBinsFromGlobalBin(17) == indices({{3, 2}})); + BOOST_CHECK(g.localBinsFromGlobalBin(18) == indices({{3, 3}})); + BOOST_CHECK(g.localBinsFromGlobalBin(19) == indices({{3, 4}})); + BOOST_CHECK(g.localBinsFromGlobalBin(20) == indices({{4, 0}})); + BOOST_CHECK(g.localBinsFromGlobalBin(21) == indices({{4, 1}})); + BOOST_CHECK(g.localBinsFromGlobalBin(22) == indices({{4, 2}})); + BOOST_CHECK(g.localBinsFromGlobalBin(23) == indices({{4, 3}})); + BOOST_CHECK(g.localBinsFromGlobalBin(24) == indices({{4, 4}})); + BOOST_CHECK(g.localBinsFromGlobalBin(25) == indices({{5, 0}})); + BOOST_CHECK(g.localBinsFromGlobalBin(26) == indices({{5, 1}})); + BOOST_CHECK(g.localBinsFromGlobalBin(27) == indices({{5, 2}})); + BOOST_CHECK(g.localBinsFromGlobalBin(28) == indices({{5, 3}})); + BOOST_CHECK(g.localBinsFromGlobalBin(29) == indices({{5, 4}})); + + // local bin indices -> global bin index + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 0}}), 0u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 1}}), 1u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 2}}), 2u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 3}}), 3u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 4}}), 4u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 0}}), 5u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 1}}), 6u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 2}}), 7u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 3}}), 8u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 4}}), 9u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 0}}), 10u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 1}}), 11u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 2}}), 12u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 3}}), 13u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 4}}), 14u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 0}}), 15u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 1}}), 16u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 2}}), 17u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 3}}), 18u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 4}}), 19u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{4, 0}}), 20u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{4, 1}}), 21u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{4, 2}}), 22u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{4, 3}}), 23u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{4, 4}}), 24u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{5, 0}}), 25u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{5, 1}}), 26u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{5, 2}}), 27u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{5, 3}}), 28u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{5, 4}}), 29u); + + BOOST_CHECK(g.localBinsFromGlobalBin(g.globalBinFromPosition( + Point({{1.2, 0.7}}))) == indices({{2, 1}})); + + // inside checks + BOOST_CHECK(not g.isInside(Point({{-2., -1}}))); + BOOST_CHECK(not g.isInside(Point({{-2., 1.}}))); + BOOST_CHECK(not g.isInside(Point({{-2., 5.}}))); + BOOST_CHECK(not g.isInside(Point({{1., -1.}}))); + BOOST_CHECK(not g.isInside(Point({{6., -1.}}))); + BOOST_CHECK(g.isInside(Point({{0.5, 1.3}}))); + BOOST_CHECK(not g.isInside(Point({{4., -1.}}))); + BOOST_CHECK(not g.isInside(Point({{4., 0.3}}))); + BOOST_CHECK(not g.isInside(Point({{4., 3.}}))); + BOOST_CHECK(not g.isInside(Point({{-1., 3.}}))); + BOOST_CHECK(not g.isInside(Point({{2., 3.}}))); + BOOST_CHECK(not g.isInside(Point({{5., 3.}}))); + + // test some bin centers + CHECK_CLOSE_ABS(g.binCenter({{1, 1}}), Point({{0.5, 0.5}}), 1e-6); + CHECK_CLOSE_ABS(g.binCenter({{2, 3}}), Point({{1.5, 2.5}}), 1e-6); + CHECK_CLOSE_ABS(g.binCenter({{3, 1}}), Point({{2.5, 0.5}}), 1e-6); + CHECK_CLOSE_ABS(g.binCenter({{4, 2}}), Point({{3.5, 1.5}}), 1e-6); + + // test some lower-left bin edges + CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{1, 1}}), Point({{0., 0.}}), 1e-6); + CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{2, 3}}), Point({{1., 2.}}), 1e-6); + CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{3, 1}}), Point({{2., 0.}}), 1e-6); + CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{4, 2}}), Point({{3., 1.}}), 1e-6); + + // test some upper right-bin edges + CHECK_CLOSE_ABS(g.upperRightBinEdge({{1, 1}}), Point({{1., 1.}}), 1e-6); + CHECK_CLOSE_ABS(g.upperRightBinEdge({{2, 3}}), Point({{2., 3.}}), 1e-6); + CHECK_CLOSE_ABS(g.upperRightBinEdge({{3, 1}}), Point({{3., 1.}}), 1e-6); + CHECK_CLOSE_ABS(g.upperRightBinEdge({{4, 2}}), Point({{4., 2.}}), 1e-6); + + // initialize grid + for (size_t bin = 0; bin < g.size(); ++bin) { + g.at(bin) = bin; } - BOOST_AUTO_TEST_CASE(grid_test_3d_equidistant) - { - using Point = std::array<double, 3>; - using indices = std::array<size_t, 3>; - EquidistantAxis a(0.0, 2.0, 2u); - EquidistantAxis b(0.0, 3.0, 3u); - EquidistantAxis c(0.0, 2.0, 2u); - Grid<double, EquidistantAxis, EquidistantAxis, EquidistantAxis> g( - std::make_tuple(std::move(a), std::move(b), std::move(c))); - - // test general properties - BOOST_CHECK_EQUAL(g.size(), 80u); - BOOST_CHECK_EQUAL(g.numLocalBins().at(0), 2u); - BOOST_CHECK_EQUAL(g.numLocalBins().at(1), 3u); - BOOST_CHECK_EQUAL(g.numLocalBins().at(2), 2u); - - // test grid points - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 0, 0}})), 25u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 0, 1}})), 26u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 0, 2}})), 27u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 1, 0}})), 29u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 1, 1}})), 30u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 1, 2}})), 31u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 2, 0}})), 33u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 2, 1}})), 34u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 2, 2}})), 35u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 3, 0}})), 37u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 3, 1}})), 38u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 3, 2}})), 39u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 0, 0}})), 45u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 0, 1}})), 46u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 0, 2}})), 47u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 1, 0}})), 49u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 1, 1}})), 50u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 1, 2}})), 51u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 2, 0}})), 53u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 2, 1}})), 54u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 2, 2}})), 55u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 3, 0}})), 57u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 3, 1}})), 58u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 3, 2}})), 59u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, 0, 0}})), 65u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, 0, 1}})), 66u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, 0, 2}})), 67u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, 1, 0}})), 69u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, 1, 1}})), 70u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, 1, 2}})), 71u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, 2, 0}})), 73u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, 2, 1}})), 74u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, 2, 2}})), 75u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, 3, 0}})), 77u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, 3, 1}})), 78u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, 3, 2}})), 79u); - - // global bin index -> local bin indices - BOOST_CHECK(g.localBinsFromGlobalBin(0) == indices({{0, 0, 0}})); - BOOST_CHECK(g.localBinsFromGlobalBin(1) == indices({{0, 0, 1}})); - BOOST_CHECK(g.localBinsFromGlobalBin(2) == indices({{0, 0, 2}})); - BOOST_CHECK(g.localBinsFromGlobalBin(3) == indices({{0, 0, 3}})); - BOOST_CHECK(g.localBinsFromGlobalBin(4) == indices({{0, 1, 0}})); - BOOST_CHECK(g.localBinsFromGlobalBin(5) == indices({{0, 1, 1}})); - BOOST_CHECK(g.localBinsFromGlobalBin(6) == indices({{0, 1, 2}})); - BOOST_CHECK(g.localBinsFromGlobalBin(7) == indices({{0, 1, 3}})); - BOOST_CHECK(g.localBinsFromGlobalBin(24) == indices({{1, 1, 0}})); - BOOST_CHECK(g.localBinsFromGlobalBin(25) == indices({{1, 1, 1}})); - BOOST_CHECK(g.localBinsFromGlobalBin(26) == indices({{1, 1, 2}})); - BOOST_CHECK(g.localBinsFromGlobalBin(27) == indices({{1, 1, 3}})); - BOOST_CHECK(g.localBinsFromGlobalBin(52) == indices({{2, 3, 0}})); - BOOST_CHECK(g.localBinsFromGlobalBin(53) == indices({{2, 3, 1}})); - BOOST_CHECK(g.localBinsFromGlobalBin(54) == indices({{2, 3, 2}})); - BOOST_CHECK(g.localBinsFromGlobalBin(55) == indices({{2, 3, 3}})); - BOOST_CHECK(g.localBinsFromGlobalBin(60) == indices({{3, 0, 0}})); - BOOST_CHECK(g.localBinsFromGlobalBin(61) == indices({{3, 0, 1}})); - BOOST_CHECK(g.localBinsFromGlobalBin(62) == indices({{3, 0, 2}})); - BOOST_CHECK(g.localBinsFromGlobalBin(63) == indices({{3, 0, 3}})); - BOOST_CHECK(g.localBinsFromGlobalBin(76) == indices({{3, 4, 0}})); - BOOST_CHECK(g.localBinsFromGlobalBin(77) == indices({{3, 4, 1}})); - BOOST_CHECK(g.localBinsFromGlobalBin(78) == indices({{3, 4, 2}})); - BOOST_CHECK(g.localBinsFromGlobalBin(79) == indices({{3, 4, 3}})); - - // local bin indices -> global bin index - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 0, 0}}), 0u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 0, 1}}), 1u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 0, 2}}), 2u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 0, 3}}), 3u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 1, 0}}), 4u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 1, 1}}), 5u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 1, 2}}), 6u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 1, 3}}), 7u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 1, 0}}), 24u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 1, 1}}), 25u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 1, 2}}), 26u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 1, 3}}), 27u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 3, 0}}), 52u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 3, 1}}), 53u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 3, 2}}), 54u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 3, 3}}), 55u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 0, 0}}), 60u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 0, 1}}), 61u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 0, 2}}), 62u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 0, 3}}), 63u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 4, 0}}), 76u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 4, 1}}), 77u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 4, 2}}), 78u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 4, 3}}), 79u); - - BOOST_CHECK(g.localBinsFromGlobalBin( - g.globalBinFromPosition(Point({{1.2, 0.7, 1.4}}))) - == indices({{2, 1, 2}})); - - // inside checks - BOOST_CHECK(not g.isInside(Point({{-2., -1, -2}}))); - BOOST_CHECK(not g.isInside(Point({{-2., 1., 0.}}))); - BOOST_CHECK(not g.isInside(Point({{-2., 5., -1}}))); - BOOST_CHECK(not g.isInside(Point({{1., -1., 1.}}))); - BOOST_CHECK(not g.isInside(Point({{6., -1., 4.}}))); - BOOST_CHECK(g.isInside(Point({{0.5, 1.3, 1.7}}))); - BOOST_CHECK(not g.isInside(Point({{2., -1., -0.4}}))); - BOOST_CHECK(not g.isInside(Point({{2., 0.3, 3.4}}))); - BOOST_CHECK(not g.isInside(Point({{2., 3., 0.8}}))); - BOOST_CHECK(not g.isInside(Point({{-1., 3., 5.}}))); - BOOST_CHECK(not g.isInside(Point({{2., 3., -1.}}))); - BOOST_CHECK(not g.isInside(Point({{5., 3., 0.5}}))); - - // test some bin centers - CHECK_CLOSE_ABS(g.binCenter({{1, 1, 1}}), Point({{0.5, 0.5, 0.5}}), 1e-6); - CHECK_CLOSE_ABS(g.binCenter({{2, 3, 2}}), Point({{1.5, 2.5, 1.5}}), 1e-6); - CHECK_CLOSE_ABS(g.binCenter({{1, 1, 2}}), Point({{0.5, 0.5, 1.5}}), 1e-6); - CHECK_CLOSE_ABS(g.binCenter({{2, 2, 1}}), Point({{1.5, 1.5, 0.5}}), 1e-6); - - // test some lower-left bin edges - CHECK_CLOSE_ABS( - g.lowerLeftBinEdge({{1, 1, 1}}), Point({{0., 0., 0.}}), 1e-6); - CHECK_CLOSE_ABS( - g.lowerLeftBinEdge({{2, 3, 2}}), Point({{1., 2., 1.}}), 1e-6); - CHECK_CLOSE_ABS( - g.lowerLeftBinEdge({{1, 1, 2}}), Point({{0., 0., 1.}}), 1e-6); - CHECK_CLOSE_ABS( - g.lowerLeftBinEdge({{2, 2, 1}}), Point({{1., 1., 0.}}), 1e-6); - - // test some upper right-bin edges - CHECK_CLOSE_ABS( - g.upperRightBinEdge({{1, 1, 1}}), Point({{1., 1., 1.}}), 1e-6); - CHECK_CLOSE_ABS( - g.upperRightBinEdge({{2, 3, 2}}), Point({{2., 3., 2.}}), 1e-6); - CHECK_CLOSE_ABS( - g.upperRightBinEdge({{1, 1, 2}}), Point({{1., 1., 2.}}), 1e-6); - CHECK_CLOSE_ABS( - g.upperRightBinEdge({{2, 2, 1}}), Point({{2., 2., 1.}}), 1e-6); - - // initialize grid - for (size_t bin = 0; bin < g.size(); ++bin) { - g.at(bin) = bin; - } - - // consistency of access - const auto& point = Point({{0.7, 2.3, 1.3}}); - size_t globalBin = g.globalBinFromPosition(point); - indices localBins = g.localBinsFromGlobalBin(globalBin); - - BOOST_CHECK_EQUAL(g.atPosition(point), g.at(globalBin)); - BOOST_CHECK_EQUAL(g.atPosition(point), g.atLocalBins(localBins)); + // consistency of access + const auto& point = Point({{0.7, 1.3}}); + size_t globalBin = g.globalBinFromPosition(point); + indices localBins = g.localBinsFromGlobalBin(globalBin); + + BOOST_CHECK_EQUAL(g.atPosition(point), g.at(globalBin)); + BOOST_CHECK_EQUAL(g.atPosition(point), g.atLocalBins(localBins)); +} + +BOOST_AUTO_TEST_CASE(grid_test_3d_equidistant) { + using Point = std::array<double, 3>; + using indices = std::array<size_t, 3>; + EquidistantAxis a(0.0, 2.0, 2u); + EquidistantAxis b(0.0, 3.0, 3u); + EquidistantAxis c(0.0, 2.0, 2u); + Grid<double, EquidistantAxis, EquidistantAxis, EquidistantAxis> g( + std::make_tuple(std::move(a), std::move(b), std::move(c))); + + // test general properties + BOOST_CHECK_EQUAL(g.size(), 80u); + BOOST_CHECK_EQUAL(g.numLocalBins().at(0), 2u); + BOOST_CHECK_EQUAL(g.numLocalBins().at(1), 3u); + BOOST_CHECK_EQUAL(g.numLocalBins().at(2), 2u); + + // test grid points + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 0, 0}})), 25u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 0, 1}})), 26u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 0, 2}})), 27u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 1, 0}})), 29u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 1, 1}})), 30u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 1, 2}})), 31u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 2, 0}})), 33u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 2, 1}})), 34u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 2, 2}})), 35u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 3, 0}})), 37u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 3, 1}})), 38u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 3, 2}})), 39u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 0, 0}})), 45u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 0, 1}})), 46u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 0, 2}})), 47u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 1, 0}})), 49u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 1, 1}})), 50u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 1, 2}})), 51u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 2, 0}})), 53u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 2, 1}})), 54u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 2, 2}})), 55u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 3, 0}})), 57u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 3, 1}})), 58u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 3, 2}})), 59u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, 0, 0}})), 65u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, 0, 1}})), 66u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, 0, 2}})), 67u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, 1, 0}})), 69u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, 1, 1}})), 70u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, 1, 2}})), 71u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, 2, 0}})), 73u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, 2, 1}})), 74u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, 2, 2}})), 75u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, 3, 0}})), 77u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, 3, 1}})), 78u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, 3, 2}})), 79u); + + // global bin index -> local bin indices + BOOST_CHECK(g.localBinsFromGlobalBin(0) == indices({{0, 0, 0}})); + BOOST_CHECK(g.localBinsFromGlobalBin(1) == indices({{0, 0, 1}})); + BOOST_CHECK(g.localBinsFromGlobalBin(2) == indices({{0, 0, 2}})); + BOOST_CHECK(g.localBinsFromGlobalBin(3) == indices({{0, 0, 3}})); + BOOST_CHECK(g.localBinsFromGlobalBin(4) == indices({{0, 1, 0}})); + BOOST_CHECK(g.localBinsFromGlobalBin(5) == indices({{0, 1, 1}})); + BOOST_CHECK(g.localBinsFromGlobalBin(6) == indices({{0, 1, 2}})); + BOOST_CHECK(g.localBinsFromGlobalBin(7) == indices({{0, 1, 3}})); + BOOST_CHECK(g.localBinsFromGlobalBin(24) == indices({{1, 1, 0}})); + BOOST_CHECK(g.localBinsFromGlobalBin(25) == indices({{1, 1, 1}})); + BOOST_CHECK(g.localBinsFromGlobalBin(26) == indices({{1, 1, 2}})); + BOOST_CHECK(g.localBinsFromGlobalBin(27) == indices({{1, 1, 3}})); + BOOST_CHECK(g.localBinsFromGlobalBin(52) == indices({{2, 3, 0}})); + BOOST_CHECK(g.localBinsFromGlobalBin(53) == indices({{2, 3, 1}})); + BOOST_CHECK(g.localBinsFromGlobalBin(54) == indices({{2, 3, 2}})); + BOOST_CHECK(g.localBinsFromGlobalBin(55) == indices({{2, 3, 3}})); + BOOST_CHECK(g.localBinsFromGlobalBin(60) == indices({{3, 0, 0}})); + BOOST_CHECK(g.localBinsFromGlobalBin(61) == indices({{3, 0, 1}})); + BOOST_CHECK(g.localBinsFromGlobalBin(62) == indices({{3, 0, 2}})); + BOOST_CHECK(g.localBinsFromGlobalBin(63) == indices({{3, 0, 3}})); + BOOST_CHECK(g.localBinsFromGlobalBin(76) == indices({{3, 4, 0}})); + BOOST_CHECK(g.localBinsFromGlobalBin(77) == indices({{3, 4, 1}})); + BOOST_CHECK(g.localBinsFromGlobalBin(78) == indices({{3, 4, 2}})); + BOOST_CHECK(g.localBinsFromGlobalBin(79) == indices({{3, 4, 3}})); + + // local bin indices -> global bin index + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 0, 0}}), 0u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 0, 1}}), 1u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 0, 2}}), 2u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 0, 3}}), 3u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 1, 0}}), 4u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 1, 1}}), 5u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 1, 2}}), 6u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 1, 3}}), 7u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 1, 0}}), 24u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 1, 1}}), 25u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 1, 2}}), 26u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 1, 3}}), 27u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 3, 0}}), 52u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 3, 1}}), 53u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 3, 2}}), 54u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 3, 3}}), 55u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 0, 0}}), 60u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 0, 1}}), 61u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 0, 2}}), 62u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 0, 3}}), 63u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 4, 0}}), 76u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 4, 1}}), 77u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 4, 2}}), 78u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 4, 3}}), 79u); + + BOOST_CHECK(g.localBinsFromGlobalBin(g.globalBinFromPosition( + Point({{1.2, 0.7, 1.4}}))) == indices({{2, 1, 2}})); + + // inside checks + BOOST_CHECK(not g.isInside(Point({{-2., -1, -2}}))); + BOOST_CHECK(not g.isInside(Point({{-2., 1., 0.}}))); + BOOST_CHECK(not g.isInside(Point({{-2., 5., -1}}))); + BOOST_CHECK(not g.isInside(Point({{1., -1., 1.}}))); + BOOST_CHECK(not g.isInside(Point({{6., -1., 4.}}))); + BOOST_CHECK(g.isInside(Point({{0.5, 1.3, 1.7}}))); + BOOST_CHECK(not g.isInside(Point({{2., -1., -0.4}}))); + BOOST_CHECK(not g.isInside(Point({{2., 0.3, 3.4}}))); + BOOST_CHECK(not g.isInside(Point({{2., 3., 0.8}}))); + BOOST_CHECK(not g.isInside(Point({{-1., 3., 5.}}))); + BOOST_CHECK(not g.isInside(Point({{2., 3., -1.}}))); + BOOST_CHECK(not g.isInside(Point({{5., 3., 0.5}}))); + + // test some bin centers + CHECK_CLOSE_ABS(g.binCenter({{1, 1, 1}}), Point({{0.5, 0.5, 0.5}}), 1e-6); + CHECK_CLOSE_ABS(g.binCenter({{2, 3, 2}}), Point({{1.5, 2.5, 1.5}}), 1e-6); + CHECK_CLOSE_ABS(g.binCenter({{1, 1, 2}}), Point({{0.5, 0.5, 1.5}}), 1e-6); + CHECK_CLOSE_ABS(g.binCenter({{2, 2, 1}}), Point({{1.5, 1.5, 0.5}}), 1e-6); + + // test some lower-left bin edges + CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{1, 1, 1}}), Point({{0., 0., 0.}}), 1e-6); + CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{2, 3, 2}}), Point({{1., 2., 1.}}), 1e-6); + CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{1, 1, 2}}), Point({{0., 0., 1.}}), 1e-6); + CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{2, 2, 1}}), Point({{1., 1., 0.}}), 1e-6); + + // test some upper right-bin edges + CHECK_CLOSE_ABS(g.upperRightBinEdge({{1, 1, 1}}), Point({{1., 1., 1.}}), + 1e-6); + CHECK_CLOSE_ABS(g.upperRightBinEdge({{2, 3, 2}}), Point({{2., 3., 2.}}), + 1e-6); + CHECK_CLOSE_ABS(g.upperRightBinEdge({{1, 1, 2}}), Point({{1., 1., 2.}}), + 1e-6); + CHECK_CLOSE_ABS(g.upperRightBinEdge({{2, 2, 1}}), Point({{2., 2., 1.}}), + 1e-6); + + // initialize grid + for (size_t bin = 0; bin < g.size(); ++bin) { + g.at(bin) = bin; } - BOOST_AUTO_TEST_CASE(grid_test_1d_variable) - { - using Point = std::array<double, 1>; - using indices = std::array<size_t, 1>; - VariableAxis a({0.0, 1.0, 4.0}); - Grid<double, VariableAxis> g(std::make_tuple(std::move(a))); - - // test general properties - BOOST_CHECK_EQUAL(g.size(), 4u); - BOOST_CHECK_EQUAL(g.numLocalBins().at(0), 2u); - - // global bin index - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-0.3}})), 0u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.}})), 1u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.7}})), 1u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1}})), 2u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1.2}})), 2u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2.7}})), 2u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{4.}})), 3u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{4.98}})), 3u); - - // global bin index -> local bin indices - BOOST_CHECK(g.localBinsFromGlobalBin(0) == indices({{0}})); - BOOST_CHECK(g.localBinsFromGlobalBin(1) == indices({{1}})); - BOOST_CHECK(g.localBinsFromGlobalBin(2) == indices({{2}})); - BOOST_CHECK(g.localBinsFromGlobalBin(3) == indices({{3}})); - - // local bin indices -> global bin index - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0}}), 0u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1}}), 1u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2}}), 2u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3}}), 3u); - - BOOST_CHECK( - g.localBinsFromGlobalBin(g.globalBinFromPosition(Point({{0.8}}))) - == indices({{1}})); - - // inside checks - BOOST_CHECK(not g.isInside(Point({{-2.}}))); - BOOST_CHECK(g.isInside(Point({{0.}}))); - BOOST_CHECK(g.isInside(Point({{2.5}}))); - BOOST_CHECK(not g.isInside(Point({{4.}}))); - BOOST_CHECK(not g.isInside(Point({{6.}}))); - - // test some bin centers - CHECK_CLOSE_ABS(g.binCenter({{1}}), Point({{0.5}}), 1e-6); - CHECK_CLOSE_ABS(g.binCenter({{2}}), Point({{2.5}}), 1e-6); - - // test some lower-left bin edges - CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{1}}), Point({{0.}}), 1e-6); - CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{2}}), Point({{1.}}), 1e-6); - - // test some upper right-bin edges - CHECK_CLOSE_ABS(g.upperRightBinEdge({{1}}), Point({{1.}}), 1e-6); - CHECK_CLOSE_ABS(g.upperRightBinEdge({{2}}), Point({{4.}}), 1e-6); - - // initialize grid - for (size_t bin = 0; bin < g.size(); ++bin) { - g.at(bin) = bin; - } - - // consistency of access - const auto& point = Point({{0.7}}); - size_t globalBin = g.globalBinFromPosition(point); - indices localBins = g.localBinsFromGlobalBin(globalBin); - - BOOST_CHECK_EQUAL(g.atPosition(point), g.at(globalBin)); - BOOST_CHECK_EQUAL(g.atPosition(point), g.atLocalBins(localBins)); + // consistency of access + const auto& point = Point({{0.7, 2.3, 1.3}}); + size_t globalBin = g.globalBinFromPosition(point); + indices localBins = g.localBinsFromGlobalBin(globalBin); + + BOOST_CHECK_EQUAL(g.atPosition(point), g.at(globalBin)); + BOOST_CHECK_EQUAL(g.atPosition(point), g.atLocalBins(localBins)); +} + +BOOST_AUTO_TEST_CASE(grid_test_1d_variable) { + using Point = std::array<double, 1>; + using indices = std::array<size_t, 1>; + VariableAxis a({0.0, 1.0, 4.0}); + Grid<double, VariableAxis> g(std::make_tuple(std::move(a))); + + // test general properties + BOOST_CHECK_EQUAL(g.size(), 4u); + BOOST_CHECK_EQUAL(g.numLocalBins().at(0), 2u); + + // global bin index + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-0.3}})), 0u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.}})), 1u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.7}})), 1u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1}})), 2u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1.2}})), 2u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2.7}})), 2u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{4.}})), 3u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{4.98}})), 3u); + + // global bin index -> local bin indices + BOOST_CHECK(g.localBinsFromGlobalBin(0) == indices({{0}})); + BOOST_CHECK(g.localBinsFromGlobalBin(1) == indices({{1}})); + BOOST_CHECK(g.localBinsFromGlobalBin(2) == indices({{2}})); + BOOST_CHECK(g.localBinsFromGlobalBin(3) == indices({{3}})); + + // local bin indices -> global bin index + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0}}), 0u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1}}), 1u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2}}), 2u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3}}), 3u); + + BOOST_CHECK(g.localBinsFromGlobalBin( + g.globalBinFromPosition(Point({{0.8}}))) == indices({{1}})); + + // inside checks + BOOST_CHECK(not g.isInside(Point({{-2.}}))); + BOOST_CHECK(g.isInside(Point({{0.}}))); + BOOST_CHECK(g.isInside(Point({{2.5}}))); + BOOST_CHECK(not g.isInside(Point({{4.}}))); + BOOST_CHECK(not g.isInside(Point({{6.}}))); + + // test some bin centers + CHECK_CLOSE_ABS(g.binCenter({{1}}), Point({{0.5}}), 1e-6); + CHECK_CLOSE_ABS(g.binCenter({{2}}), Point({{2.5}}), 1e-6); + + // test some lower-left bin edges + CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{1}}), Point({{0.}}), 1e-6); + CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{2}}), Point({{1.}}), 1e-6); + + // test some upper right-bin edges + CHECK_CLOSE_ABS(g.upperRightBinEdge({{1}}), Point({{1.}}), 1e-6); + CHECK_CLOSE_ABS(g.upperRightBinEdge({{2}}), Point({{4.}}), 1e-6); + + // initialize grid + for (size_t bin = 0; bin < g.size(); ++bin) { + g.at(bin) = bin; } - BOOST_AUTO_TEST_CASE(grid_test_2d_variable) - { - using Point = std::array<double, 2>; - using indices = std::array<size_t, 2>; - VariableAxis a({0.0, 0.5, 3.0}); - VariableAxis b({0.0, 1.0, 4.0}); - Grid<double, VariableAxis, VariableAxis> g( - std::make_tuple(std::move(a), std::move(b))); - - // test general properties - BOOST_CHECK_EQUAL(g.size(), 16u); - BOOST_CHECK_EQUAL(g.numLocalBins().at(0), 2u); - BOOST_CHECK_EQUAL(g.numLocalBins().at(1), 2u); - - // test grid points - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 0}})), 5u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 1}})), 6u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 4}})), 7u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.5, 0}})), 9u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.5, 1}})), 10u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.5, 4}})), 11u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{3, 0}})), 13u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{3, 1}})), 14u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{3, 4}})), 15u); - - // test some arbitrary points - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.3, 1.2}})), 6u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{3.3, 2.2}})), 14u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1.8, 0.9}})), 9u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{3.1, 0.7}})), 13u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2.3, 1.4}})), 10u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, -3}})), 8u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 8}})), 11u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-3, 1}})), 2u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{11, 3}})), 14u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-3, -2}})), 0u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{7, -2}})), 12u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-1, 12}})), 3u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{11, 12}})), 15u); - - // global bin index -> local bin indices - BOOST_CHECK(g.localBinsFromGlobalBin(0) == indices({{0, 0}})); - BOOST_CHECK(g.localBinsFromGlobalBin(1) == indices({{0, 1}})); - BOOST_CHECK(g.localBinsFromGlobalBin(2) == indices({{0, 2}})); - BOOST_CHECK(g.localBinsFromGlobalBin(3) == indices({{0, 3}})); - BOOST_CHECK(g.localBinsFromGlobalBin(4) == indices({{1, 0}})); - BOOST_CHECK(g.localBinsFromGlobalBin(5) == indices({{1, 1}})); - BOOST_CHECK(g.localBinsFromGlobalBin(6) == indices({{1, 2}})); - BOOST_CHECK(g.localBinsFromGlobalBin(7) == indices({{1, 3}})); - BOOST_CHECK(g.localBinsFromGlobalBin(8) == indices({{2, 0}})); - BOOST_CHECK(g.localBinsFromGlobalBin(9) == indices({{2, 1}})); - BOOST_CHECK(g.localBinsFromGlobalBin(10) == indices({{2, 2}})); - BOOST_CHECK(g.localBinsFromGlobalBin(11) == indices({{2, 3}})); - BOOST_CHECK(g.localBinsFromGlobalBin(12) == indices({{3, 0}})); - BOOST_CHECK(g.localBinsFromGlobalBin(13) == indices({{3, 1}})); - BOOST_CHECK(g.localBinsFromGlobalBin(14) == indices({{3, 2}})); - BOOST_CHECK(g.localBinsFromGlobalBin(15) == indices({{3, 3}})); - - // local bin indices -> global bin index - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 0}}), 0u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 1}}), 1u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 2}}), 2u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 3}}), 3u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 0}}), 4u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 1}}), 5u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 2}}), 6u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 3}}), 7u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 0}}), 8u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 1}}), 9u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 2}}), 10u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 3}}), 11u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 0}}), 12u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 1}}), 13u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 2}}), 14u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 3}}), 15u); - - BOOST_CHECK( - g.localBinsFromGlobalBin(g.globalBinFromPosition(Point({{3.2, 1.8}}))) - == indices({{3, 2}})); - - // inside checks - BOOST_CHECK(not g.isInside(Point({{-2., -1}}))); - BOOST_CHECK(not g.isInside(Point({{-2., 1.}}))); - BOOST_CHECK(not g.isInside(Point({{-2., 5.}}))); - BOOST_CHECK(not g.isInside(Point({{1., -1.}}))); - BOOST_CHECK(not g.isInside(Point({{6., -1.}}))); - BOOST_CHECK(g.isInside(Point({{0.5, 1.3}}))); - BOOST_CHECK(not g.isInside(Point({{3., -1.}}))); - BOOST_CHECK(not g.isInside(Point({{3., 0.3}}))); - BOOST_CHECK(not g.isInside(Point({{3., 4.}}))); - BOOST_CHECK(not g.isInside(Point({{-1., 4.}}))); - BOOST_CHECK(not g.isInside(Point({{2., 4.}}))); - BOOST_CHECK(not g.isInside(Point({{5., 4.}}))); - - // test some bin centers - CHECK_CLOSE_ABS(g.binCenter({{1, 1}}), Point({{0.25, 0.5}}), 1e-6); - CHECK_CLOSE_ABS(g.binCenter({{2, 1}}), Point({{1.75, 0.5}}), 1e-6); - CHECK_CLOSE_ABS(g.binCenter({{1, 2}}), Point({{0.25, 2.5}}), 1e-6); - CHECK_CLOSE_ABS(g.binCenter({{2, 2}}), Point({{1.75, 2.5}}), 1e-6); - - // test some lower-left bin edges - CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{1, 1}}), Point({{0., 0.}}), 1e-6); - CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{2, 1}}), Point({{0.5, 0.}}), 1e-6); - CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{1, 2}}), Point({{0., 1.}}), 1e-6); - CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{2, 2}}), Point({{0.5, 1.}}), 1e-6); - - // test some upper right-bin edges - CHECK_CLOSE_ABS(g.upperRightBinEdge({{1, 1}}), Point({{0.5, 1.}}), 1e-6); - CHECK_CLOSE_ABS(g.upperRightBinEdge({{2, 1}}), Point({{3., 1.}}), 1e-6); - CHECK_CLOSE_ABS(g.upperRightBinEdge({{1, 2}}), Point({{0.5, 4.}}), 1e-6); - CHECK_CLOSE_ABS(g.upperRightBinEdge({{2, 2}}), Point({{3., 4.}}), 1e-6); - - // initialize grid - for (size_t bin = 0; bin < g.size(); ++bin) { - g.at(bin) = bin; - } - - // consistency of access - const auto& point = Point({{0.7, 1.3}}); - size_t globalBin = g.globalBinFromPosition(point); - indices localBins = g.localBinsFromGlobalBin(globalBin); - - BOOST_CHECK_EQUAL(g.atPosition(point), g.at(globalBin)); - BOOST_CHECK_EQUAL(g.atPosition(point), g.atLocalBins(localBins)); + // consistency of access + const auto& point = Point({{0.7}}); + size_t globalBin = g.globalBinFromPosition(point); + indices localBins = g.localBinsFromGlobalBin(globalBin); + + BOOST_CHECK_EQUAL(g.atPosition(point), g.at(globalBin)); + BOOST_CHECK_EQUAL(g.atPosition(point), g.atLocalBins(localBins)); +} + +BOOST_AUTO_TEST_CASE(grid_test_2d_variable) { + using Point = std::array<double, 2>; + using indices = std::array<size_t, 2>; + VariableAxis a({0.0, 0.5, 3.0}); + VariableAxis b({0.0, 1.0, 4.0}); + Grid<double, VariableAxis, VariableAxis> g( + std::make_tuple(std::move(a), std::move(b))); + + // test general properties + BOOST_CHECK_EQUAL(g.size(), 16u); + BOOST_CHECK_EQUAL(g.numLocalBins().at(0), 2u); + BOOST_CHECK_EQUAL(g.numLocalBins().at(1), 2u); + + // test grid points + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 0}})), 5u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 1}})), 6u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 4}})), 7u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.5, 0}})), 9u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.5, 1}})), 10u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.5, 4}})), 11u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{3, 0}})), 13u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{3, 1}})), 14u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{3, 4}})), 15u); + + // test some arbitrary points + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.3, 1.2}})), 6u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{3.3, 2.2}})), 14u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1.8, 0.9}})), 9u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{3.1, 0.7}})), 13u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2.3, 1.4}})), 10u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{2, -3}})), 8u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 8}})), 11u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-3, 1}})), 2u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{11, 3}})), 14u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-3, -2}})), 0u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{7, -2}})), 12u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-1, 12}})), 3u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{11, 12}})), 15u); + + // global bin index -> local bin indices + BOOST_CHECK(g.localBinsFromGlobalBin(0) == indices({{0, 0}})); + BOOST_CHECK(g.localBinsFromGlobalBin(1) == indices({{0, 1}})); + BOOST_CHECK(g.localBinsFromGlobalBin(2) == indices({{0, 2}})); + BOOST_CHECK(g.localBinsFromGlobalBin(3) == indices({{0, 3}})); + BOOST_CHECK(g.localBinsFromGlobalBin(4) == indices({{1, 0}})); + BOOST_CHECK(g.localBinsFromGlobalBin(5) == indices({{1, 1}})); + BOOST_CHECK(g.localBinsFromGlobalBin(6) == indices({{1, 2}})); + BOOST_CHECK(g.localBinsFromGlobalBin(7) == indices({{1, 3}})); + BOOST_CHECK(g.localBinsFromGlobalBin(8) == indices({{2, 0}})); + BOOST_CHECK(g.localBinsFromGlobalBin(9) == indices({{2, 1}})); + BOOST_CHECK(g.localBinsFromGlobalBin(10) == indices({{2, 2}})); + BOOST_CHECK(g.localBinsFromGlobalBin(11) == indices({{2, 3}})); + BOOST_CHECK(g.localBinsFromGlobalBin(12) == indices({{3, 0}})); + BOOST_CHECK(g.localBinsFromGlobalBin(13) == indices({{3, 1}})); + BOOST_CHECK(g.localBinsFromGlobalBin(14) == indices({{3, 2}})); + BOOST_CHECK(g.localBinsFromGlobalBin(15) == indices({{3, 3}})); + + // local bin indices -> global bin index + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 0}}), 0u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 1}}), 1u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 2}}), 2u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 3}}), 3u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 0}}), 4u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 1}}), 5u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 2}}), 6u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 3}}), 7u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 0}}), 8u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 1}}), 9u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 2}}), 10u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 3}}), 11u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 0}}), 12u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 1}}), 13u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 2}}), 14u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 3}}), 15u); + + BOOST_CHECK(g.localBinsFromGlobalBin(g.globalBinFromPosition( + Point({{3.2, 1.8}}))) == indices({{3, 2}})); + + // inside checks + BOOST_CHECK(not g.isInside(Point({{-2., -1}}))); + BOOST_CHECK(not g.isInside(Point({{-2., 1.}}))); + BOOST_CHECK(not g.isInside(Point({{-2., 5.}}))); + BOOST_CHECK(not g.isInside(Point({{1., -1.}}))); + BOOST_CHECK(not g.isInside(Point({{6., -1.}}))); + BOOST_CHECK(g.isInside(Point({{0.5, 1.3}}))); + BOOST_CHECK(not g.isInside(Point({{3., -1.}}))); + BOOST_CHECK(not g.isInside(Point({{3., 0.3}}))); + BOOST_CHECK(not g.isInside(Point({{3., 4.}}))); + BOOST_CHECK(not g.isInside(Point({{-1., 4.}}))); + BOOST_CHECK(not g.isInside(Point({{2., 4.}}))); + BOOST_CHECK(not g.isInside(Point({{5., 4.}}))); + + // test some bin centers + CHECK_CLOSE_ABS(g.binCenter({{1, 1}}), Point({{0.25, 0.5}}), 1e-6); + CHECK_CLOSE_ABS(g.binCenter({{2, 1}}), Point({{1.75, 0.5}}), 1e-6); + CHECK_CLOSE_ABS(g.binCenter({{1, 2}}), Point({{0.25, 2.5}}), 1e-6); + CHECK_CLOSE_ABS(g.binCenter({{2, 2}}), Point({{1.75, 2.5}}), 1e-6); + + // test some lower-left bin edges + CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{1, 1}}), Point({{0., 0.}}), 1e-6); + CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{2, 1}}), Point({{0.5, 0.}}), 1e-6); + CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{1, 2}}), Point({{0., 1.}}), 1e-6); + CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{2, 2}}), Point({{0.5, 1.}}), 1e-6); + + // test some upper right-bin edges + CHECK_CLOSE_ABS(g.upperRightBinEdge({{1, 1}}), Point({{0.5, 1.}}), 1e-6); + CHECK_CLOSE_ABS(g.upperRightBinEdge({{2, 1}}), Point({{3., 1.}}), 1e-6); + CHECK_CLOSE_ABS(g.upperRightBinEdge({{1, 2}}), Point({{0.5, 4.}}), 1e-6); + CHECK_CLOSE_ABS(g.upperRightBinEdge({{2, 2}}), Point({{3., 4.}}), 1e-6); + + // initialize grid + for (size_t bin = 0; bin < g.size(); ++bin) { + g.at(bin) = bin; } - BOOST_AUTO_TEST_CASE(grid_test_3d_variable) - { - using Point = std::array<double, 3>; - using indices = std::array<size_t, 3>; - VariableAxis a({0.0, 1.0}); - VariableAxis b({0.0, 0.5, 3.0}); - VariableAxis c({0.0, 0.5, 3.0, 3.3}); - Grid<double, VariableAxis, VariableAxis, VariableAxis> g( - std::make_tuple(std::move(a), std::move(b), std::move(c))); - - // test general properties - BOOST_CHECK_EQUAL(g.size(), 60u); - BOOST_CHECK_EQUAL(g.numLocalBins().at(0), 1u); - BOOST_CHECK_EQUAL(g.numLocalBins().at(1), 2u); - BOOST_CHECK_EQUAL(g.numLocalBins().at(2), 3u); - - // test grid points - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 0, 0}})), 26u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 0, 0}})), 46u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 0.5, 0}})), 31u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 0.5, 0}})), 51u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 3, 0}})), 36u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 3, 0}})), 56u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 0, 0.5}})), 27u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 0, 0.5}})), 47u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 0.5, 0.5}})), 32u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 0.5, 0.5}})), 52u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 3, 0.5}})), 37u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 3, 0.5}})), 57u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 0, 3}})), 28u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 0, 3}})), 48u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 0.5, 3}})), 33u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 0.5, 3}})), 53u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 3, 3}})), 38u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 3, 3}})), 58u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 0, 3.3}})), 29u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 0, 3.3}})), 49u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 0.5, 3.3}})), 34u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 0.5, 3.3}})), 54u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 3, 3.3}})), 39u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 3, 3.3}})), 59u); - - // global bin index -> local bin indices - BOOST_CHECK(g.localBinsFromGlobalBin(0) == indices({{0, 0, 0}})); - BOOST_CHECK(g.localBinsFromGlobalBin(1) == indices({{0, 0, 1}})); - BOOST_CHECK(g.localBinsFromGlobalBin(2) == indices({{0, 0, 2}})); - BOOST_CHECK(g.localBinsFromGlobalBin(3) == indices({{0, 0, 3}})); - BOOST_CHECK(g.localBinsFromGlobalBin(4) == indices({{0, 0, 4}})); - BOOST_CHECK(g.localBinsFromGlobalBin(5) == indices({{0, 1, 0}})); - BOOST_CHECK(g.localBinsFromGlobalBin(21) == indices({{1, 0, 1}})); - BOOST_CHECK(g.localBinsFromGlobalBin(22) == indices({{1, 0, 2}})); - BOOST_CHECK(g.localBinsFromGlobalBin(23) == indices({{1, 0, 3}})); - BOOST_CHECK(g.localBinsFromGlobalBin(24) == indices({{1, 0, 4}})); - BOOST_CHECK(g.localBinsFromGlobalBin(25) == indices({{1, 1, 0}})); - BOOST_CHECK(g.localBinsFromGlobalBin(26) == indices({{1, 1, 1}})); - BOOST_CHECK(g.localBinsFromGlobalBin(57) == indices({{2, 3, 2}})); - BOOST_CHECK(g.localBinsFromGlobalBin(58) == indices({{2, 3, 3}})); - BOOST_CHECK(g.localBinsFromGlobalBin(59) == indices({{2, 3, 4}})); - - // local bin indices -> global bin index - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 0, 0}}), 0u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 0, 0}}), 20u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 0, 0}}), 40u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 1, 0}}), 5u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 1, 0}}), 25u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 1, 0}}), 45u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 3, 1}}), 16u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 3, 1}}), 36u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 3, 1}}), 56u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 0, 2}}), 2u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 0, 2}}), 22u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 0, 2}}), 42u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 3, 4}}), 19u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 3, 4}}), 39u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 3, 4}}), 59u); - - BOOST_CHECK(g.localBinsFromGlobalBin( - g.globalBinFromPosition(Point({{1.8, 0.7, 3.2}}))) - == indices({{2, 2, 3}})); - - // inside checks - BOOST_CHECK(not g.isInside(Point({{-2., -1, -2}}))); - BOOST_CHECK(not g.isInside(Point({{-2., 1., 0.}}))); - BOOST_CHECK(not g.isInside(Point({{-2., 5., -1}}))); - BOOST_CHECK(not g.isInside(Point({{1., -1., 1.}}))); - BOOST_CHECK(not g.isInside(Point({{6., -1., 4.}}))); - BOOST_CHECK(g.isInside(Point({{0.5, 1.3, 1.7}}))); - BOOST_CHECK(not g.isInside(Point({{1., -1., -0.4}}))); - BOOST_CHECK(not g.isInside(Point({{1., 0.3, 3.4}}))); - BOOST_CHECK(not g.isInside(Point({{1., 3., 0.8}}))); - BOOST_CHECK(not g.isInside(Point({{-1., 3., 5.}}))); - BOOST_CHECK(not g.isInside(Point({{2., 3., -1.}}))); - BOOST_CHECK(not g.isInside(Point({{5., 3., 0.5}}))); - - // test some bin centers - CHECK_CLOSE_ABS(g.binCenter({{1, 1, 1}}), Point({{0.5, 0.25, 0.25}}), 1e-6); - CHECK_CLOSE_ABS(g.binCenter({{1, 1, 2}}), Point({{0.5, 0.25, 1.75}}), 1e-6); - CHECK_CLOSE_ABS(g.binCenter({{1, 1, 3}}), Point({{0.5, 0.25, 3.15}}), 1e-6); - CHECK_CLOSE_ABS(g.binCenter({{1, 2, 1}}), Point({{0.5, 1.75, 0.25}}), 1e-6); - CHECK_CLOSE_ABS(g.binCenter({{1, 2, 2}}), Point({{0.5, 1.75, 1.75}}), 1e-6); - CHECK_CLOSE_ABS(g.binCenter({{1, 2, 3}}), Point({{0.5, 1.75, 3.15}}), 1e-6); - - // test some lower-left bin edges - CHECK_CLOSE_ABS( - g.lowerLeftBinEdge({{1, 1, 1}}), Point({{0., 0., 0.}}), 1e-6); - CHECK_CLOSE_ABS( - g.lowerLeftBinEdge({{1, 1, 2}}), Point({{0., 0., 0.5}}), 1e-6); - CHECK_CLOSE_ABS( - g.lowerLeftBinEdge({{1, 1, 3}}), Point({{0., 0., 3.}}), 1e-6); - CHECK_CLOSE_ABS( - g.lowerLeftBinEdge({{1, 2, 1}}), Point({{0., 0.5, 0.}}), 1e-6); - CHECK_CLOSE_ABS( - g.lowerLeftBinEdge({{1, 2, 2}}), Point({{0., 0.5, 0.5}}), 1e-6); - CHECK_CLOSE_ABS( - g.lowerLeftBinEdge({{1, 2, 3}}), Point({{0., 0.5, 3.}}), 1e-6); - - // test some upper right-bin edges - CHECK_CLOSE_ABS( - g.upperRightBinEdge({{1, 1, 1}}), Point({{1., 0.5, 0.5}}), 1e-6); - CHECK_CLOSE_ABS( - g.upperRightBinEdge({{1, 1, 2}}), Point({{1., 0.5, 3.}}), 1e-6); - CHECK_CLOSE_ABS( - g.upperRightBinEdge({{1, 1, 3}}), Point({{1., 0.5, 3.3}}), 1e-6); - CHECK_CLOSE_ABS( - g.upperRightBinEdge({{1, 2, 1}}), Point({{1., 3., 0.5}}), 1e-6); - CHECK_CLOSE_ABS( - g.upperRightBinEdge({{1, 2, 2}}), Point({{1., 3., 3.}}), 1e-6); - CHECK_CLOSE_ABS( - g.upperRightBinEdge({{1, 2, 3}}), Point({{1., 3., 3.3}}), 1e-6); - - // initialize grid - for (size_t bin = 0; bin < g.size(); ++bin) { - g.at(bin) = bin; - } - - // consistency of access - const auto& point = Point({{0.7, 1.3, 3.7}}); - size_t globalBin = g.globalBinFromPosition(point); - indices localBins = g.localBinsFromGlobalBin(globalBin); - - BOOST_CHECK_EQUAL(g.atPosition(point), g.at(globalBin)); - BOOST_CHECK_EQUAL(g.atPosition(point), g.atLocalBins(localBins)); + // consistency of access + const auto& point = Point({{0.7, 1.3}}); + size_t globalBin = g.globalBinFromPosition(point); + indices localBins = g.localBinsFromGlobalBin(globalBin); + + BOOST_CHECK_EQUAL(g.atPosition(point), g.at(globalBin)); + BOOST_CHECK_EQUAL(g.atPosition(point), g.atLocalBins(localBins)); +} + +BOOST_AUTO_TEST_CASE(grid_test_3d_variable) { + using Point = std::array<double, 3>; + using indices = std::array<size_t, 3>; + VariableAxis a({0.0, 1.0}); + VariableAxis b({0.0, 0.5, 3.0}); + VariableAxis c({0.0, 0.5, 3.0, 3.3}); + Grid<double, VariableAxis, VariableAxis, VariableAxis> g( + std::make_tuple(std::move(a), std::move(b), std::move(c))); + + // test general properties + BOOST_CHECK_EQUAL(g.size(), 60u); + BOOST_CHECK_EQUAL(g.numLocalBins().at(0), 1u); + BOOST_CHECK_EQUAL(g.numLocalBins().at(1), 2u); + BOOST_CHECK_EQUAL(g.numLocalBins().at(2), 3u); + + // test grid points + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 0, 0}})), 26u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 0, 0}})), 46u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 0.5, 0}})), 31u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 0.5, 0}})), 51u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 3, 0}})), 36u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 3, 0}})), 56u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 0, 0.5}})), 27u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 0, 0.5}})), 47u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 0.5, 0.5}})), 32u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 0.5, 0.5}})), 52u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 3, 0.5}})), 37u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 3, 0.5}})), 57u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 0, 3}})), 28u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 0, 3}})), 48u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 0.5, 3}})), 33u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 0.5, 3}})), 53u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 3, 3}})), 38u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 3, 3}})), 58u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 0, 3.3}})), 29u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 0, 3.3}})), 49u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 0.5, 3.3}})), 34u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 0.5, 3.3}})), 54u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 3, 3.3}})), 39u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 3, 3.3}})), 59u); + + // global bin index -> local bin indices + BOOST_CHECK(g.localBinsFromGlobalBin(0) == indices({{0, 0, 0}})); + BOOST_CHECK(g.localBinsFromGlobalBin(1) == indices({{0, 0, 1}})); + BOOST_CHECK(g.localBinsFromGlobalBin(2) == indices({{0, 0, 2}})); + BOOST_CHECK(g.localBinsFromGlobalBin(3) == indices({{0, 0, 3}})); + BOOST_CHECK(g.localBinsFromGlobalBin(4) == indices({{0, 0, 4}})); + BOOST_CHECK(g.localBinsFromGlobalBin(5) == indices({{0, 1, 0}})); + BOOST_CHECK(g.localBinsFromGlobalBin(21) == indices({{1, 0, 1}})); + BOOST_CHECK(g.localBinsFromGlobalBin(22) == indices({{1, 0, 2}})); + BOOST_CHECK(g.localBinsFromGlobalBin(23) == indices({{1, 0, 3}})); + BOOST_CHECK(g.localBinsFromGlobalBin(24) == indices({{1, 0, 4}})); + BOOST_CHECK(g.localBinsFromGlobalBin(25) == indices({{1, 1, 0}})); + BOOST_CHECK(g.localBinsFromGlobalBin(26) == indices({{1, 1, 1}})); + BOOST_CHECK(g.localBinsFromGlobalBin(57) == indices({{2, 3, 2}})); + BOOST_CHECK(g.localBinsFromGlobalBin(58) == indices({{2, 3, 3}})); + BOOST_CHECK(g.localBinsFromGlobalBin(59) == indices({{2, 3, 4}})); + + // local bin indices -> global bin index + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 0, 0}}), 0u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 0, 0}}), 20u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 0, 0}}), 40u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 1, 0}}), 5u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 1, 0}}), 25u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 1, 0}}), 45u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 3, 1}}), 16u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 3, 1}}), 36u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 3, 1}}), 56u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 0, 2}}), 2u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 0, 2}}), 22u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 0, 2}}), 42u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 3, 4}}), 19u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 3, 4}}), 39u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 3, 4}}), 59u); + + BOOST_CHECK(g.localBinsFromGlobalBin(g.globalBinFromPosition( + Point({{1.8, 0.7, 3.2}}))) == indices({{2, 2, 3}})); + + // inside checks + BOOST_CHECK(not g.isInside(Point({{-2., -1, -2}}))); + BOOST_CHECK(not g.isInside(Point({{-2., 1., 0.}}))); + BOOST_CHECK(not g.isInside(Point({{-2., 5., -1}}))); + BOOST_CHECK(not g.isInside(Point({{1., -1., 1.}}))); + BOOST_CHECK(not g.isInside(Point({{6., -1., 4.}}))); + BOOST_CHECK(g.isInside(Point({{0.5, 1.3, 1.7}}))); + BOOST_CHECK(not g.isInside(Point({{1., -1., -0.4}}))); + BOOST_CHECK(not g.isInside(Point({{1., 0.3, 3.4}}))); + BOOST_CHECK(not g.isInside(Point({{1., 3., 0.8}}))); + BOOST_CHECK(not g.isInside(Point({{-1., 3., 5.}}))); + BOOST_CHECK(not g.isInside(Point({{2., 3., -1.}}))); + BOOST_CHECK(not g.isInside(Point({{5., 3., 0.5}}))); + + // test some bin centers + CHECK_CLOSE_ABS(g.binCenter({{1, 1, 1}}), Point({{0.5, 0.25, 0.25}}), 1e-6); + CHECK_CLOSE_ABS(g.binCenter({{1, 1, 2}}), Point({{0.5, 0.25, 1.75}}), 1e-6); + CHECK_CLOSE_ABS(g.binCenter({{1, 1, 3}}), Point({{0.5, 0.25, 3.15}}), 1e-6); + CHECK_CLOSE_ABS(g.binCenter({{1, 2, 1}}), Point({{0.5, 1.75, 0.25}}), 1e-6); + CHECK_CLOSE_ABS(g.binCenter({{1, 2, 2}}), Point({{0.5, 1.75, 1.75}}), 1e-6); + CHECK_CLOSE_ABS(g.binCenter({{1, 2, 3}}), Point({{0.5, 1.75, 3.15}}), 1e-6); + + // test some lower-left bin edges + CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{1, 1, 1}}), Point({{0., 0., 0.}}), 1e-6); + CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{1, 1, 2}}), Point({{0., 0., 0.5}}), + 1e-6); + CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{1, 1, 3}}), Point({{0., 0., 3.}}), 1e-6); + CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{1, 2, 1}}), Point({{0., 0.5, 0.}}), + 1e-6); + CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{1, 2, 2}}), Point({{0., 0.5, 0.5}}), + 1e-6); + CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{1, 2, 3}}), Point({{0., 0.5, 3.}}), + 1e-6); + + // test some upper right-bin edges + CHECK_CLOSE_ABS(g.upperRightBinEdge({{1, 1, 1}}), Point({{1., 0.5, 0.5}}), + 1e-6); + CHECK_CLOSE_ABS(g.upperRightBinEdge({{1, 1, 2}}), Point({{1., 0.5, 3.}}), + 1e-6); + CHECK_CLOSE_ABS(g.upperRightBinEdge({{1, 1, 3}}), Point({{1., 0.5, 3.3}}), + 1e-6); + CHECK_CLOSE_ABS(g.upperRightBinEdge({{1, 2, 1}}), Point({{1., 3., 0.5}}), + 1e-6); + CHECK_CLOSE_ABS(g.upperRightBinEdge({{1, 2, 2}}), Point({{1., 3., 3.}}), + 1e-6); + CHECK_CLOSE_ABS(g.upperRightBinEdge({{1, 2, 3}}), Point({{1., 3., 3.3}}), + 1e-6); + + // initialize grid + for (size_t bin = 0; bin < g.size(); ++bin) { + g.at(bin) = bin; } - BOOST_AUTO_TEST_CASE(grid_test_2d_mixed) - { - using Point = std::array<double, 2>; - using indices = std::array<size_t, 2>; - EquidistantAxis a(0.0, 1.0, 4u); - VariableAxis b({0.0, 0.5, 3.0}); - Grid<double, EquidistantAxis, VariableAxis> g( - std::make_tuple(std::move(a), std::move(b))); - - // test general properties - BOOST_CHECK_EQUAL(g.size(), 24u); - BOOST_CHECK_EQUAL(g.numLocalBins().at(0), 4u); - BOOST_CHECK_EQUAL(g.numLocalBins().at(1), 2u); - - // test grid points - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 0}})), 5u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.25, 0}})), 9u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.5, 0}})), 13u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.75, 0}})), 17u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 0}})), 21u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 0.5}})), 6u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.25, 0.5}})), 10u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.5, 0.5}})), 14u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.75, 0.5}})), 18u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 0.5}})), 22u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 3}})), 7u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.25, 3}})), 11u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.5, 3}})), 15u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.75, 3}})), 19u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 3}})), 23u); - - // test some arbitrary points - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1.2, 0.3}})), 21u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.2, 1.3}})), 6u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.9, 1.8}})), 18u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.7, 2.1}})), 14u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.4, 0.3}})), 9u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-3, 2}})), 2u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{8, 1}})), 22u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.1, -3}})), 4u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.8, 11}})), 19u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-2, -3}})), 0u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-2, 7}})), 3u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{12, -1}})), 20u); - BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{12, 11}})), 23u); - - // global bin index -> local bin indices - using indices = std::array<size_t, 2>; - BOOST_CHECK(g.localBinsFromGlobalBin(0) == indices({{0, 0}})); - BOOST_CHECK(g.localBinsFromGlobalBin(1) == indices({{0, 1}})); - BOOST_CHECK(g.localBinsFromGlobalBin(2) == indices({{0, 2}})); - BOOST_CHECK(g.localBinsFromGlobalBin(3) == indices({{0, 3}})); - BOOST_CHECK(g.localBinsFromGlobalBin(4) == indices({{1, 0}})); - BOOST_CHECK(g.localBinsFromGlobalBin(5) == indices({{1, 1}})); - BOOST_CHECK(g.localBinsFromGlobalBin(6) == indices({{1, 2}})); - BOOST_CHECK(g.localBinsFromGlobalBin(7) == indices({{1, 3}})); - BOOST_CHECK(g.localBinsFromGlobalBin(8) == indices({{2, 0}})); - BOOST_CHECK(g.localBinsFromGlobalBin(9) == indices({{2, 1}})); - BOOST_CHECK(g.localBinsFromGlobalBin(10) == indices({{2, 2}})); - BOOST_CHECK(g.localBinsFromGlobalBin(11) == indices({{2, 3}})); - BOOST_CHECK(g.localBinsFromGlobalBin(12) == indices({{3, 0}})); - BOOST_CHECK(g.localBinsFromGlobalBin(13) == indices({{3, 1}})); - BOOST_CHECK(g.localBinsFromGlobalBin(14) == indices({{3, 2}})); - BOOST_CHECK(g.localBinsFromGlobalBin(15) == indices({{3, 3}})); - BOOST_CHECK(g.localBinsFromGlobalBin(16) == indices({{4, 0}})); - BOOST_CHECK(g.localBinsFromGlobalBin(17) == indices({{4, 1}})); - BOOST_CHECK(g.localBinsFromGlobalBin(18) == indices({{4, 2}})); - BOOST_CHECK(g.localBinsFromGlobalBin(19) == indices({{4, 3}})); - BOOST_CHECK(g.localBinsFromGlobalBin(20) == indices({{5, 0}})); - BOOST_CHECK(g.localBinsFromGlobalBin(21) == indices({{5, 1}})); - BOOST_CHECK(g.localBinsFromGlobalBin(22) == indices({{5, 2}})); - BOOST_CHECK(g.localBinsFromGlobalBin(23) == indices({{5, 3}})); - - // local bin indices -> global bin index - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 0}}), 0u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 1}}), 1u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 2}}), 2u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 3}}), 3u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 0}}), 4u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 1}}), 5u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 2}}), 6u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 3}}), 7u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 0}}), 8u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 1}}), 9u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 2}}), 10u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 3}}), 11u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 0}}), 12u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 1}}), 13u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 2}}), 14u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 3}}), 15u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{4, 0}}), 16u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{4, 1}}), 17u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{4, 2}}), 18u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{4, 3}}), 19u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{5, 0}}), 20u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{5, 1}}), 21u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{5, 2}}), 22u); - BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{5, 3}}), 23u); - - BOOST_CHECK( - g.localBinsFromGlobalBin(g.globalBinFromPosition(Point({{1.1, 1.7}}))) - == indices({{5, 2}})); - - // inside checks - BOOST_CHECK(not g.isInside(Point({{-2., -1}}))); - BOOST_CHECK(not g.isInside(Point({{-2., 1.}}))); - BOOST_CHECK(not g.isInside(Point({{-2., 5.}}))); - BOOST_CHECK(not g.isInside(Point({{0.1, -1.}}))); - BOOST_CHECK(not g.isInside(Point({{6., -1.}}))); - BOOST_CHECK(g.isInside(Point({{0.5, 1.3}}))); - BOOST_CHECK(not g.isInside(Point({{1., -1.}}))); - BOOST_CHECK(not g.isInside(Point({{1., 0.3}}))); - BOOST_CHECK(not g.isInside(Point({{1., 3.}}))); - BOOST_CHECK(not g.isInside(Point({{-1., 3.}}))); - BOOST_CHECK(not g.isInside(Point({{0.2, 3.}}))); - BOOST_CHECK(not g.isInside(Point({{5., 3.}}))); - - // test some bin centers - CHECK_CLOSE_ABS(g.binCenter({{1, 1}}), Point({{0.125, 0.25}}), 1e-6); - CHECK_CLOSE_ABS(g.binCenter({{1, 2}}), Point({{0.125, 1.75}}), 1e-6); - CHECK_CLOSE_ABS(g.binCenter({{2, 1}}), Point({{0.375, 0.25}}), 1e-6); - CHECK_CLOSE_ABS(g.binCenter({{2, 2}}), Point({{0.375, 1.75}}), 1e-6); - CHECK_CLOSE_ABS(g.binCenter({{3, 1}}), Point({{0.625, 0.25}}), 1e-6); - CHECK_CLOSE_ABS(g.binCenter({{3, 2}}), Point({{0.625, 1.75}}), 1e-6); - CHECK_CLOSE_ABS(g.binCenter({{4, 1}}), Point({{0.875, 0.25}}), 1e-6); - CHECK_CLOSE_ABS(g.binCenter({{4, 2}}), Point({{0.875, 1.75}}), 1e-6); - - // test some lower-left bin edges - CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{1, 1}}), Point({{0., 0.}}), 1e-6); - CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{1, 2}}), Point({{0., 0.5}}), 1e-6); - CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{2, 1}}), Point({{0.25, 0.}}), 1e-6); - CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{2, 2}}), Point({{0.25, 0.5}}), 1e-6); - CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{3, 1}}), Point({{0.5, 0.}}), 1e-6); - CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{3, 2}}), Point({{0.5, 0.5}}), 1e-6); - CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{4, 1}}), Point({{0.75, 0.}}), 1e-6); - CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{4, 2}}), Point({{0.75, 0.5}}), 1e-6); - - // test some upper-right bin edges - CHECK_CLOSE_ABS(g.upperRightBinEdge({{1, 1}}), Point({{0.25, 0.5}}), 1e-6); - CHECK_CLOSE_ABS(g.upperRightBinEdge({{1, 2}}), Point({{0.25, 3.}}), 1e-6); - CHECK_CLOSE_ABS(g.upperRightBinEdge({{2, 1}}), Point({{0.5, 0.5}}), 1e-6); - CHECK_CLOSE_ABS(g.upperRightBinEdge({{2, 2}}), Point({{0.5, 3.}}), 1e-6); - CHECK_CLOSE_ABS(g.upperRightBinEdge({{3, 1}}), Point({{0.75, 0.5}}), 1e-6); - CHECK_CLOSE_ABS(g.upperRightBinEdge({{3, 2}}), Point({{0.75, 3.}}), 1e-6); - CHECK_CLOSE_ABS(g.upperRightBinEdge({{4, 1}}), Point({{1., 0.5}}), 1e-6); - CHECK_CLOSE_ABS(g.upperRightBinEdge({{4, 2}}), Point({{1., 3.}}), 1e-6); - - // initialize grid - for (size_t bin = 0; bin < g.size(); ++bin) { - g.at(bin) = bin; - } - - // consistency of access - const auto& point = Point({{1.3, 3.7}}); - size_t globalBin = g.globalBinFromPosition(point); - indices localBins = g.localBinsFromGlobalBin(globalBin); - - BOOST_CHECK_EQUAL(g.atPosition(point), g.at(globalBin)); - BOOST_CHECK_EQUAL(g.atPosition(point), g.atLocalBins(localBins)); + // consistency of access + const auto& point = Point({{0.7, 1.3, 3.7}}); + size_t globalBin = g.globalBinFromPosition(point); + indices localBins = g.localBinsFromGlobalBin(globalBin); + + BOOST_CHECK_EQUAL(g.atPosition(point), g.at(globalBin)); + BOOST_CHECK_EQUAL(g.atPosition(point), g.atLocalBins(localBins)); +} + +BOOST_AUTO_TEST_CASE(grid_test_2d_mixed) { + using Point = std::array<double, 2>; + using indices = std::array<size_t, 2>; + EquidistantAxis a(0.0, 1.0, 4u); + VariableAxis b({0.0, 0.5, 3.0}); + Grid<double, EquidistantAxis, VariableAxis> g( + std::make_tuple(std::move(a), std::move(b))); + + // test general properties + BOOST_CHECK_EQUAL(g.size(), 24u); + BOOST_CHECK_EQUAL(g.numLocalBins().at(0), 4u); + BOOST_CHECK_EQUAL(g.numLocalBins().at(1), 2u); + + // test grid points + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 0}})), 5u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.25, 0}})), 9u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.5, 0}})), 13u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.75, 0}})), 17u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 0}})), 21u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 0.5}})), 6u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.25, 0.5}})), 10u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.5, 0.5}})), 14u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.75, 0.5}})), 18u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 0.5}})), 22u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0, 3}})), 7u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.25, 3}})), 11u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.5, 3}})), 15u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.75, 3}})), 19u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1, 3}})), 23u); + + // test some arbitrary points + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{1.2, 0.3}})), 21u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.2, 1.3}})), 6u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.9, 1.8}})), 18u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.7, 2.1}})), 14u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.4, 0.3}})), 9u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-3, 2}})), 2u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{8, 1}})), 22u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.1, -3}})), 4u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{0.8, 11}})), 19u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-2, -3}})), 0u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{-2, 7}})), 3u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{12, -1}})), 20u); + BOOST_CHECK_EQUAL(g.globalBinFromPosition(Point({{12, 11}})), 23u); + + // global bin index -> local bin indices + using indices = std::array<size_t, 2>; + BOOST_CHECK(g.localBinsFromGlobalBin(0) == indices({{0, 0}})); + BOOST_CHECK(g.localBinsFromGlobalBin(1) == indices({{0, 1}})); + BOOST_CHECK(g.localBinsFromGlobalBin(2) == indices({{0, 2}})); + BOOST_CHECK(g.localBinsFromGlobalBin(3) == indices({{0, 3}})); + BOOST_CHECK(g.localBinsFromGlobalBin(4) == indices({{1, 0}})); + BOOST_CHECK(g.localBinsFromGlobalBin(5) == indices({{1, 1}})); + BOOST_CHECK(g.localBinsFromGlobalBin(6) == indices({{1, 2}})); + BOOST_CHECK(g.localBinsFromGlobalBin(7) == indices({{1, 3}})); + BOOST_CHECK(g.localBinsFromGlobalBin(8) == indices({{2, 0}})); + BOOST_CHECK(g.localBinsFromGlobalBin(9) == indices({{2, 1}})); + BOOST_CHECK(g.localBinsFromGlobalBin(10) == indices({{2, 2}})); + BOOST_CHECK(g.localBinsFromGlobalBin(11) == indices({{2, 3}})); + BOOST_CHECK(g.localBinsFromGlobalBin(12) == indices({{3, 0}})); + BOOST_CHECK(g.localBinsFromGlobalBin(13) == indices({{3, 1}})); + BOOST_CHECK(g.localBinsFromGlobalBin(14) == indices({{3, 2}})); + BOOST_CHECK(g.localBinsFromGlobalBin(15) == indices({{3, 3}})); + BOOST_CHECK(g.localBinsFromGlobalBin(16) == indices({{4, 0}})); + BOOST_CHECK(g.localBinsFromGlobalBin(17) == indices({{4, 1}})); + BOOST_CHECK(g.localBinsFromGlobalBin(18) == indices({{4, 2}})); + BOOST_CHECK(g.localBinsFromGlobalBin(19) == indices({{4, 3}})); + BOOST_CHECK(g.localBinsFromGlobalBin(20) == indices({{5, 0}})); + BOOST_CHECK(g.localBinsFromGlobalBin(21) == indices({{5, 1}})); + BOOST_CHECK(g.localBinsFromGlobalBin(22) == indices({{5, 2}})); + BOOST_CHECK(g.localBinsFromGlobalBin(23) == indices({{5, 3}})); + + // local bin indices -> global bin index + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 0}}), 0u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 1}}), 1u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 2}}), 2u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{0, 3}}), 3u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 0}}), 4u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 1}}), 5u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 2}}), 6u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{1, 3}}), 7u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 0}}), 8u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 1}}), 9u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 2}}), 10u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{2, 3}}), 11u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 0}}), 12u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 1}}), 13u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 2}}), 14u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{3, 3}}), 15u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{4, 0}}), 16u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{4, 1}}), 17u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{4, 2}}), 18u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{4, 3}}), 19u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{5, 0}}), 20u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{5, 1}}), 21u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{5, 2}}), 22u); + BOOST_CHECK_EQUAL(g.globalBinFromLocalBins({{5, 3}}), 23u); + + BOOST_CHECK(g.localBinsFromGlobalBin(g.globalBinFromPosition( + Point({{1.1, 1.7}}))) == indices({{5, 2}})); + + // inside checks + BOOST_CHECK(not g.isInside(Point({{-2., -1}}))); + BOOST_CHECK(not g.isInside(Point({{-2., 1.}}))); + BOOST_CHECK(not g.isInside(Point({{-2., 5.}}))); + BOOST_CHECK(not g.isInside(Point({{0.1, -1.}}))); + BOOST_CHECK(not g.isInside(Point({{6., -1.}}))); + BOOST_CHECK(g.isInside(Point({{0.5, 1.3}}))); + BOOST_CHECK(not g.isInside(Point({{1., -1.}}))); + BOOST_CHECK(not g.isInside(Point({{1., 0.3}}))); + BOOST_CHECK(not g.isInside(Point({{1., 3.}}))); + BOOST_CHECK(not g.isInside(Point({{-1., 3.}}))); + BOOST_CHECK(not g.isInside(Point({{0.2, 3.}}))); + BOOST_CHECK(not g.isInside(Point({{5., 3.}}))); + + // test some bin centers + CHECK_CLOSE_ABS(g.binCenter({{1, 1}}), Point({{0.125, 0.25}}), 1e-6); + CHECK_CLOSE_ABS(g.binCenter({{1, 2}}), Point({{0.125, 1.75}}), 1e-6); + CHECK_CLOSE_ABS(g.binCenter({{2, 1}}), Point({{0.375, 0.25}}), 1e-6); + CHECK_CLOSE_ABS(g.binCenter({{2, 2}}), Point({{0.375, 1.75}}), 1e-6); + CHECK_CLOSE_ABS(g.binCenter({{3, 1}}), Point({{0.625, 0.25}}), 1e-6); + CHECK_CLOSE_ABS(g.binCenter({{3, 2}}), Point({{0.625, 1.75}}), 1e-6); + CHECK_CLOSE_ABS(g.binCenter({{4, 1}}), Point({{0.875, 0.25}}), 1e-6); + CHECK_CLOSE_ABS(g.binCenter({{4, 2}}), Point({{0.875, 1.75}}), 1e-6); + + // test some lower-left bin edges + CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{1, 1}}), Point({{0., 0.}}), 1e-6); + CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{1, 2}}), Point({{0., 0.5}}), 1e-6); + CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{2, 1}}), Point({{0.25, 0.}}), 1e-6); + CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{2, 2}}), Point({{0.25, 0.5}}), 1e-6); + CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{3, 1}}), Point({{0.5, 0.}}), 1e-6); + CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{3, 2}}), Point({{0.5, 0.5}}), 1e-6); + CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{4, 1}}), Point({{0.75, 0.}}), 1e-6); + CHECK_CLOSE_ABS(g.lowerLeftBinEdge({{4, 2}}), Point({{0.75, 0.5}}), 1e-6); + + // test some upper-right bin edges + CHECK_CLOSE_ABS(g.upperRightBinEdge({{1, 1}}), Point({{0.25, 0.5}}), 1e-6); + CHECK_CLOSE_ABS(g.upperRightBinEdge({{1, 2}}), Point({{0.25, 3.}}), 1e-6); + CHECK_CLOSE_ABS(g.upperRightBinEdge({{2, 1}}), Point({{0.5, 0.5}}), 1e-6); + CHECK_CLOSE_ABS(g.upperRightBinEdge({{2, 2}}), Point({{0.5, 3.}}), 1e-6); + CHECK_CLOSE_ABS(g.upperRightBinEdge({{3, 1}}), Point({{0.75, 0.5}}), 1e-6); + CHECK_CLOSE_ABS(g.upperRightBinEdge({{3, 2}}), Point({{0.75, 3.}}), 1e-6); + CHECK_CLOSE_ABS(g.upperRightBinEdge({{4, 1}}), Point({{1., 0.5}}), 1e-6); + CHECK_CLOSE_ABS(g.upperRightBinEdge({{4, 2}}), Point({{1., 3.}}), 1e-6); + + // initialize grid + for (size_t bin = 0; bin < g.size(); ++bin) { + g.at(bin) = bin; } - BOOST_AUTO_TEST_CASE(grid_test_2d_mixed_at) - { - EquidistantAxis a(0.0, 6.0, 4u); - VariableAxis b({0.0, 1.5, 3.0}); - Grid<double, EquidistantAxis, VariableAxis> g( - std::make_tuple(std::move(a), std::move(b))); - - // initialize the grid - using Point = std::array<double, 2>; - g.atPosition(Point({{0, 0}})) = 0.; - g.atPosition(Point({{1.5, 0}})) = 1.; - g.atPosition(Point({{3, 0}})) = 2.; - g.atPosition(Point({{4.5, 0}})) = 3.; - g.atPosition(Point({{6, 0}})) = 4.; - g.atPosition(Point({{0, 1.5}})) = 5.; - g.atPosition(Point({{1.5, 1.5}})) = 6.; - g.atPosition(Point({{3, 1.5}})) = 7.; - g.atPosition(Point({{4.5, 1.5}})) = 8.; - g.atPosition(Point({{6, 1.5}})) = 9.; - g.atPosition(Point({{0, 3}})) = 10.; - g.atPosition(Point({{1.5, 3}})) = 11.; - g.atPosition(Point({{3, 3}})) = 12.; - g.atPosition(Point({{4.5, 3}})) = 13.; - g.atPosition(Point({{6, 3}})) = 14.; - - // test general properties - BOOST_CHECK_EQUAL(g.size(), 24u); - - // test some arbitrary points - BOOST_CHECK_EQUAL(g.atPosition(Point({{1.2, 0.3}})), 0.); - BOOST_CHECK_EQUAL(g.atPosition(Point({{2.2, 1.3}})), 1.); - BOOST_CHECK_EQUAL(g.atPosition(Point({{4.9, 1.8}})), 8.); - BOOST_CHECK_EQUAL(g.atPosition(Point({{3.7, 2.1}})), 7.); - BOOST_CHECK_EQUAL(g.atPosition(Point({{0.4, 2.3}})), 5.); - } - - BOOST_AUTO_TEST_CASE(grid_interpolation) - { - using Point = std::array<double, 3>; - EquidistantAxis a(1.0, 3.0, 2u); - EquidistantAxis b(1.0, 5.0, 2u); - EquidistantAxis c(1.0, 7.0, 2u); - Grid<double, EquidistantAxis, EquidistantAxis, EquidistantAxis> g( - std::make_tuple(std::move(a), std::move(b), std::move(c))); - - g.atPosition(Point({{1., 1., 1.}})) = 10.; - g.atPosition(Point({{2., 1., 1.}})) = 20.; - g.atPosition(Point({{1., 3., 1.}})) = 30.; - g.atPosition(Point({{2., 3., 1.}})) = 40.; - g.atPosition(Point({{1., 1., 4.}})) = 50.; - g.atPosition(Point({{2., 1., 4.}})) = 60.; - g.atPosition(Point({{1., 3., 4.}})) = 70.; - g.atPosition(Point({{2., 3., 4.}})) = 80.; - - CHECK_CLOSE_REL(g.interpolate(Point({{1., 1., 1.}})), 10., 1e-6); - CHECK_CLOSE_REL(g.interpolate(Point({{2., 1., 1.}})), 20., 1e-6); - CHECK_CLOSE_REL(g.interpolate(Point({{1., 3., 1.}})), 30., 1e-6); - CHECK_CLOSE_REL(g.interpolate(Point({{2., 3., 1.}})), 40., 1e-6); - CHECK_CLOSE_REL(g.interpolate(Point({{1., 1., 4.}})), 50., 1e-6); - CHECK_CLOSE_REL(g.interpolate(Point({{2., 1., 4.}})), 60., 1e-6); - CHECK_CLOSE_REL(g.interpolate(Point({{1., 3., 4.}})), 70., 1e-6); - CHECK_CLOSE_REL(g.interpolate(Point({{2., 3., 4.}})), 80., 1e-6); - CHECK_CLOSE_REL(g.interpolate(Point({{1.5, 1., 1.}})), 15., 1e-6); - CHECK_CLOSE_REL(g.interpolate(Point({{1.5, 3., 1.}})), 35., 1e-6); - CHECK_CLOSE_REL(g.interpolate(Point({{1., 2., 1.}})), 20., 1e-6); - CHECK_CLOSE_REL(g.interpolate(Point({{2., 2., 1.}})), 30., 1e-6); - CHECK_CLOSE_REL(g.interpolate(Point({{1.5, 1., 4.}})), 55., 1e-6); - CHECK_CLOSE_REL(g.interpolate(Point({{1.5, 3., 4.}})), 75., 1e-6); - CHECK_CLOSE_REL(g.interpolate(Point({{1., 2., 4.}})), 60., 1e-6); - CHECK_CLOSE_REL(g.interpolate(Point({{2., 2., 4.}})), 70., 1e-6); - CHECK_CLOSE_REL(g.interpolate(Point({{1., 1., 2.5}})), 30., 1e-6); - CHECK_CLOSE_REL(g.interpolate(Point({{1., 3., 2.5}})), 50., 1e-6); - CHECK_CLOSE_REL(g.interpolate(Point({{2., 1., 2.5}})), 40., 1e-6); - CHECK_CLOSE_REL(g.interpolate(Point({{2., 3., 2.5}})), 60., 1e-6); - CHECK_CLOSE_REL(g.interpolate(Point({{1.5, 2., 2.5}})), 360. / 8, 1e-6); - CHECK_CLOSE_REL(g.interpolate(Point({{1.3, 2.1, 1.6}})), 32., 1e-6); - CHECK_CLOSE_REL(g.interpolate(Point({{2., 3., 4.}})), 80., 1e-6); - } - - BOOST_AUTO_TEST_CASE(neighborhood) - { - using bins_t = std::vector<size_t>; - using EAxis = EquidistantAxis; - using Grid1_t = Grid<double, EAxis>; - using Grid2_t = Grid<double, EAxis, EAxis>; - using Grid3_t = Grid<double, EAxis, EAxis, EAxis>; - - EAxis a(0.0, 1.0, 10u); - EAxis b(0.0, 1.0, 10u); - EAxis c(0.0, 1.0, 10u); - Grid1_t g1(std::make_tuple(a)); - Grid2_t g2(std::make_tuple(a, b)); - Grid3_t g3(std::make_tuple(std::move(a), std::move(b), std::move(c))); - - // clang-format off + // consistency of access + const auto& point = Point({{1.3, 3.7}}); + size_t globalBin = g.globalBinFromPosition(point); + indices localBins = g.localBinsFromGlobalBin(globalBin); + + BOOST_CHECK_EQUAL(g.atPosition(point), g.at(globalBin)); + BOOST_CHECK_EQUAL(g.atPosition(point), g.atLocalBins(localBins)); +} + +BOOST_AUTO_TEST_CASE(grid_test_2d_mixed_at) { + EquidistantAxis a(0.0, 6.0, 4u); + VariableAxis b({0.0, 1.5, 3.0}); + Grid<double, EquidistantAxis, VariableAxis> g( + std::make_tuple(std::move(a), std::move(b))); + + // initialize the grid + using Point = std::array<double, 2>; + g.atPosition(Point({{0, 0}})) = 0.; + g.atPosition(Point({{1.5, 0}})) = 1.; + g.atPosition(Point({{3, 0}})) = 2.; + g.atPosition(Point({{4.5, 0}})) = 3.; + g.atPosition(Point({{6, 0}})) = 4.; + g.atPosition(Point({{0, 1.5}})) = 5.; + g.atPosition(Point({{1.5, 1.5}})) = 6.; + g.atPosition(Point({{3, 1.5}})) = 7.; + g.atPosition(Point({{4.5, 1.5}})) = 8.; + g.atPosition(Point({{6, 1.5}})) = 9.; + g.atPosition(Point({{0, 3}})) = 10.; + g.atPosition(Point({{1.5, 3}})) = 11.; + g.atPosition(Point({{3, 3}})) = 12.; + g.atPosition(Point({{4.5, 3}})) = 13.; + g.atPosition(Point({{6, 3}})) = 14.; + + // test general properties + BOOST_CHECK_EQUAL(g.size(), 24u); + + // test some arbitrary points + BOOST_CHECK_EQUAL(g.atPosition(Point({{1.2, 0.3}})), 0.); + BOOST_CHECK_EQUAL(g.atPosition(Point({{2.2, 1.3}})), 1.); + BOOST_CHECK_EQUAL(g.atPosition(Point({{4.9, 1.8}})), 8.); + BOOST_CHECK_EQUAL(g.atPosition(Point({{3.7, 2.1}})), 7.); + BOOST_CHECK_EQUAL(g.atPosition(Point({{0.4, 2.3}})), 5.); +} + +BOOST_AUTO_TEST_CASE(grid_interpolation) { + using Point = std::array<double, 3>; + EquidistantAxis a(1.0, 3.0, 2u); + EquidistantAxis b(1.0, 5.0, 2u); + EquidistantAxis c(1.0, 7.0, 2u); + Grid<double, EquidistantAxis, EquidistantAxis, EquidistantAxis> g( + std::make_tuple(std::move(a), std::move(b), std::move(c))); + + g.atPosition(Point({{1., 1., 1.}})) = 10.; + g.atPosition(Point({{2., 1., 1.}})) = 20.; + g.atPosition(Point({{1., 3., 1.}})) = 30.; + g.atPosition(Point({{2., 3., 1.}})) = 40.; + g.atPosition(Point({{1., 1., 4.}})) = 50.; + g.atPosition(Point({{2., 1., 4.}})) = 60.; + g.atPosition(Point({{1., 3., 4.}})) = 70.; + g.atPosition(Point({{2., 3., 4.}})) = 80.; + + CHECK_CLOSE_REL(g.interpolate(Point({{1., 1., 1.}})), 10., 1e-6); + CHECK_CLOSE_REL(g.interpolate(Point({{2., 1., 1.}})), 20., 1e-6); + CHECK_CLOSE_REL(g.interpolate(Point({{1., 3., 1.}})), 30., 1e-6); + CHECK_CLOSE_REL(g.interpolate(Point({{2., 3., 1.}})), 40., 1e-6); + CHECK_CLOSE_REL(g.interpolate(Point({{1., 1., 4.}})), 50., 1e-6); + CHECK_CLOSE_REL(g.interpolate(Point({{2., 1., 4.}})), 60., 1e-6); + CHECK_CLOSE_REL(g.interpolate(Point({{1., 3., 4.}})), 70., 1e-6); + CHECK_CLOSE_REL(g.interpolate(Point({{2., 3., 4.}})), 80., 1e-6); + CHECK_CLOSE_REL(g.interpolate(Point({{1.5, 1., 1.}})), 15., 1e-6); + CHECK_CLOSE_REL(g.interpolate(Point({{1.5, 3., 1.}})), 35., 1e-6); + CHECK_CLOSE_REL(g.interpolate(Point({{1., 2., 1.}})), 20., 1e-6); + CHECK_CLOSE_REL(g.interpolate(Point({{2., 2., 1.}})), 30., 1e-6); + CHECK_CLOSE_REL(g.interpolate(Point({{1.5, 1., 4.}})), 55., 1e-6); + CHECK_CLOSE_REL(g.interpolate(Point({{1.5, 3., 4.}})), 75., 1e-6); + CHECK_CLOSE_REL(g.interpolate(Point({{1., 2., 4.}})), 60., 1e-6); + CHECK_CLOSE_REL(g.interpolate(Point({{2., 2., 4.}})), 70., 1e-6); + CHECK_CLOSE_REL(g.interpolate(Point({{1., 1., 2.5}})), 30., 1e-6); + CHECK_CLOSE_REL(g.interpolate(Point({{1., 3., 2.5}})), 50., 1e-6); + CHECK_CLOSE_REL(g.interpolate(Point({{2., 1., 2.5}})), 40., 1e-6); + CHECK_CLOSE_REL(g.interpolate(Point({{2., 3., 2.5}})), 60., 1e-6); + CHECK_CLOSE_REL(g.interpolate(Point({{1.5, 2., 2.5}})), 360. / 8, 1e-6); + CHECK_CLOSE_REL(g.interpolate(Point({{1.3, 2.1, 1.6}})), 32., 1e-6); + CHECK_CLOSE_REL(g.interpolate(Point({{2., 3., 4.}})), 80., 1e-6); +} + +BOOST_AUTO_TEST_CASE(neighborhood) { + using bins_t = std::vector<size_t>; + using EAxis = EquidistantAxis; + using Grid1_t = Grid<double, EAxis>; + using Grid2_t = Grid<double, EAxis, EAxis>; + using Grid3_t = Grid<double, EAxis, EAxis, EAxis>; + + EAxis a(0.0, 1.0, 10u); + EAxis b(0.0, 1.0, 10u); + EAxis c(0.0, 1.0, 10u); + Grid1_t g1(std::make_tuple(a)); + Grid2_t g2(std::make_tuple(a, b)); + Grid3_t g3(std::make_tuple(std::move(a), std::move(b), std::move(c))); + + // clang-format off // 1D case BOOST_CHECK(g1.neighborHoodIndices({{0}}, 1).collect() == bins_t({0, 1})); @@ -1097,60 +1074,60 @@ namespace Test { == bins_t({1556, 1557, 1558, 1568, 1569, 1570, 1580, 1581, 1582, 1700, 1701, 1702, 1712, 1713, 1714, 1724, 1725, 1726})); - // clang-format on - - using EAxisClosed = Axis<AxisType::Equidistant, AxisBoundaryType::Closed>; - using Grid1Closed_t = Grid<double, EAxisClosed>; - EAxisClosed d(0.0, 1.0, 10u); - - Grid1Closed_t g1Cl(std::make_tuple(std::move(d))); - BOOST_CHECK(g1Cl.neighborHoodIndices({{0}}, 1).collect() - == bins_t({})); // underflow, makes no sense - BOOST_CHECK(g1Cl.neighborHoodIndices({{11}}, 1).collect() - == bins_t({})); // overflow, makes no sense - BOOST_CHECK(g1Cl.neighborHoodIndices({{1}}, 1).collect() - == bins_t({10, 1, 2})); // overflow, makes no sense - BOOST_CHECK(g1Cl.neighborHoodIndices({{5}}, 1).collect() - == bins_t({4, 5, 6})); // overflow, makes no sense - - using Grid2Closed_t = Grid<double, EAxisClosed, EAxisClosed>; - // typedef Grid<double, EAxisClosed, EAxisClosed, EAxisClosed> - // Grid3Closed_t; - EAxisClosed e(0.0, 1.0, 5u); - EAxisClosed f(0.0, 1.0, 5u); - EAxisClosed g(0.0, 1.0, 5u); - Grid2Closed_t g2Cl(std::make_tuple(std::move(e), std::move(f))); - BOOST_CHECK(g2Cl.neighborHoodIndices({{3, 3}}, 1).collect() - == bins_t({16, 17, 18, 23, 24, 25, 30, 31, 32})); - BOOST_CHECK(g2Cl.neighborHoodIndices({{1, 1}}, 1).collect() - == bins_t({40, 36, 37, 12, 8, 9, 19, 15, 16})); - BOOST_CHECK(g2Cl.neighborHoodIndices({{1, 5}}, 1).collect() - == bins_t({39, 40, 36, 11, 12, 8, 18, 19, 15})); - BOOST_CHECK(g2Cl.neighborHoodIndices({{5, 1}}, 1).collect() - == bins_t({33, 29, 30, 40, 36, 37, 12, 8, 9})); - BOOST_CHECK(g2Cl.neighborHoodIndices({{5, 5}}, 1).collect() - == bins_t({32, 33, 29, 39, 40, 36, 11, 12, 8})); - - BOOST_CHECK(g2Cl.neighborHoodIndices({{3, 3}}, 2).collect() - == bins_t({8, 9, 10, 11, 12, 15, 16, 17, 18, 19, 22, 23, 24, - 25, 26, 29, 30, 31, 32, 33, 36, 37, 38, 39, 40})); - BOOST_CHECK(g2Cl.neighborHoodIndices({{1, 1}}, 2).collect() - == bins_t({32, 33, 29, 30, 31, 39, 40, 36, 37, 38, 11, 12, 8, - 9, 10, 18, 19, 15, 16, 17, 25, 26, 22, 23, 24})); - BOOST_CHECK(g2Cl.neighborHoodIndices({{1, 5}}, 2).collect() - == bins_t({31, 32, 33, 29, 30, 38, 39, 40, 36, 37, 10, 11, 12, - 8, 9, 17, 18, 19, 15, 16, 24, 25, 26, 22, 23})); - BOOST_CHECK(g2Cl.neighborHoodIndices({{5, 1}}, 2).collect() - == bins_t({25, 26, 22, 23, 24, 32, 33, 29, 30, 31, 39, 40, 36, - 37, 38, 11, 12, 8, 9, 10, 18, 19, 15, 16, 17})); - BOOST_CHECK(g2Cl.neighborHoodIndices({{5, 5}}, 2).collect() - == bins_t({24, 25, 26, 22, 23, 31, 32, 33, 29, 30, 38, 39, 40, - 36, 37, 10, 11, 12, 8, 9, 17, 18, 19, 15, 16})); - - // @TODO 3D test would be nice, but should essentially not be a problem if - // 2D works. - - // clang-format off + // clang-format on + + using EAxisClosed = Axis<AxisType::Equidistant, AxisBoundaryType::Closed>; + using Grid1Closed_t = Grid<double, EAxisClosed>; + EAxisClosed d(0.0, 1.0, 10u); + + Grid1Closed_t g1Cl(std::make_tuple(std::move(d))); + BOOST_CHECK(g1Cl.neighborHoodIndices({{0}}, 1).collect() == + bins_t({})); // underflow, makes no sense + BOOST_CHECK(g1Cl.neighborHoodIndices({{11}}, 1).collect() == + bins_t({})); // overflow, makes no sense + BOOST_CHECK(g1Cl.neighborHoodIndices({{1}}, 1).collect() == + bins_t({10, 1, 2})); // overflow, makes no sense + BOOST_CHECK(g1Cl.neighborHoodIndices({{5}}, 1).collect() == + bins_t({4, 5, 6})); // overflow, makes no sense + + using Grid2Closed_t = Grid<double, EAxisClosed, EAxisClosed>; + // typedef Grid<double, EAxisClosed, EAxisClosed, EAxisClosed> + // Grid3Closed_t; + EAxisClosed e(0.0, 1.0, 5u); + EAxisClosed f(0.0, 1.0, 5u); + EAxisClosed g(0.0, 1.0, 5u); + Grid2Closed_t g2Cl(std::make_tuple(std::move(e), std::move(f))); + BOOST_CHECK(g2Cl.neighborHoodIndices({{3, 3}}, 1).collect() == + bins_t({16, 17, 18, 23, 24, 25, 30, 31, 32})); + BOOST_CHECK(g2Cl.neighborHoodIndices({{1, 1}}, 1).collect() == + bins_t({40, 36, 37, 12, 8, 9, 19, 15, 16})); + BOOST_CHECK(g2Cl.neighborHoodIndices({{1, 5}}, 1).collect() == + bins_t({39, 40, 36, 11, 12, 8, 18, 19, 15})); + BOOST_CHECK(g2Cl.neighborHoodIndices({{5, 1}}, 1).collect() == + bins_t({33, 29, 30, 40, 36, 37, 12, 8, 9})); + BOOST_CHECK(g2Cl.neighborHoodIndices({{5, 5}}, 1).collect() == + bins_t({32, 33, 29, 39, 40, 36, 11, 12, 8})); + + BOOST_CHECK(g2Cl.neighborHoodIndices({{3, 3}}, 2).collect() == + bins_t({8, 9, 10, 11, 12, 15, 16, 17, 18, 19, 22, 23, 24, + 25, 26, 29, 30, 31, 32, 33, 36, 37, 38, 39, 40})); + BOOST_CHECK(g2Cl.neighborHoodIndices({{1, 1}}, 2).collect() == + bins_t({32, 33, 29, 30, 31, 39, 40, 36, 37, 38, 11, 12, 8, + 9, 10, 18, 19, 15, 16, 17, 25, 26, 22, 23, 24})); + BOOST_CHECK(g2Cl.neighborHoodIndices({{1, 5}}, 2).collect() == + bins_t({31, 32, 33, 29, 30, 38, 39, 40, 36, 37, 10, 11, 12, + 8, 9, 17, 18, 19, 15, 16, 24, 25, 26, 22, 23})); + BOOST_CHECK(g2Cl.neighborHoodIndices({{5, 1}}, 2).collect() == + bins_t({25, 26, 22, 23, 24, 32, 33, 29, 30, 31, 39, 40, 36, + 37, 38, 11, 12, 8, 9, 10, 18, 19, 15, 16, 17})); + BOOST_CHECK(g2Cl.neighborHoodIndices({{5, 5}}, 2).collect() == + bins_t({24, 25, 26, 22, 23, 31, 32, 33, 29, 30, 38, 39, 40, + 36, 37, 10, 11, 12, 8, 9, 17, 18, 19, 15, 16})); + + // @TODO 3D test would be nice, but should essentially not be a problem if + // 2D works. + + // clang-format off /* * 1 2 3 4 5 * |------------------------| @@ -1165,26 +1142,25 @@ namespace Test { * 5 | 36 | 37Â | 38 | 39 | 40 | * |------------------------| */ - // clang-format on - } - - BOOST_AUTO_TEST_CASE(closestPoints) - { - using Point = std::array<double, 3>; - using bins_t = std::vector<size_t>; - using EAxis = EquidistantAxis; - using Grid1_t = Grid<double, EAxis>; - using Grid2_t = Grid<double, EAxis, EAxis>; - using Grid3_t = Grid<double, EAxis, EAxis, EAxis>; - - EAxis a(0.0, 1.0, 10u); - EAxis b(0.0, 1.0, 5u); - EAxis c(0.0, 1.0, 3u); - Grid1_t g1(std::make_tuple(a)); - Grid2_t g2(std::make_tuple(a, b)); - Grid3_t g3(std::make_tuple(std::move(a), std::move(b), std::move(c))); - - // clang-format off + // clang-format on +} + +BOOST_AUTO_TEST_CASE(closestPoints) { + using Point = std::array<double, 3>; + using bins_t = std::vector<size_t>; + using EAxis = EquidistantAxis; + using Grid1_t = Grid<double, EAxis>; + using Grid2_t = Grid<double, EAxis, EAxis>; + using Grid3_t = Grid<double, EAxis, EAxis, EAxis>; + + EAxis a(0.0, 1.0, 10u); + EAxis b(0.0, 1.0, 5u); + EAxis c(0.0, 1.0, 3u); + Grid1_t g1(std::make_tuple(a)); + Grid2_t g2(std::make_tuple(a, b)); + Grid3_t g3(std::make_tuple(std::move(a), std::move(b), std::move(c))); + + // clang-format off // 1D case BOOST_CHECK(g1.closestPointsIndices(Point({{0.52}})).collect() == bins_t({6, 7})); @@ -1292,8 +1268,8 @@ namespace Test { * 77 78 79 80 81 82 83 */ - // clang-format on - } + // clang-format on +} } // namespace Test diff --git a/Tests/Core/Utilities/HelpersTests.cpp b/Tests/Core/Utilities/HelpersTests.cpp index d9e71a05d3eea89cd23ee5405b7da34382477d26..1d19656b4d2795bfba153777d4e119bdcf5af1bb 100644 --- a/Tests/Core/Utilities/HelpersTests.cpp +++ b/Tests/Core/Utilities/HelpersTests.cpp @@ -18,140 +18,131 @@ using namespace Acts::VectorHelpers; namespace Acts { namespace Test { - BOOST_AUTO_TEST_SUITE(Utilities) +BOOST_AUTO_TEST_SUITE(Utilities) - struct MyStruct - { - double - phi() const - { - return 42; - } - }; - - BOOST_AUTO_TEST_CASE(phi_helper_test) - { - Vector3D v(0, 1, 0); - CHECK_CLOSE_ABS(phi(v), M_PI / 2., 1e-9); +struct MyStruct { + double phi() const { return 42; } +}; - // should work with dynamic types as well - ActsVectorXd v2{3}; - v2 << 0, 1, 0; - CHECK_CLOSE_ABS(phi(v2), M_PI / 2., 1e-9); +BOOST_AUTO_TEST_CASE(phi_helper_test) { + Vector3D v(0, 1, 0); + CHECK_CLOSE_ABS(phi(v), M_PI / 2., 1e-9); - MyStruct s; - BOOST_CHECK_EQUAL(phi(s), 42); - } + // should work with dynamic types as well + ActsVectorXd v2{3}; + v2 << 0, 1, 0; + CHECK_CLOSE_ABS(phi(v2), M_PI / 2., 1e-9); - BOOST_AUTO_TEST_CASE(perp_helper_test) - { - Vector3D v(1, 2, 3); - CHECK_CLOSE_ABS(perp(v), std::sqrt(1 + 2 * 2), 1e-9); + MyStruct s; + BOOST_CHECK_EQUAL(phi(s), 42); +} - // should work with dynamic types as well - ActsVectorXd v2{3}; - v2 << 1, 2, 3; - CHECK_CLOSE_ABS(perp(v2), std::sqrt(1 + 2 * 2), 1e-9); - } +BOOST_AUTO_TEST_CASE(perp_helper_test) { + Vector3D v(1, 2, 3); + CHECK_CLOSE_ABS(perp(v), std::sqrt(1 + 2 * 2), 1e-9); + + // should work with dynamic types as well + ActsVectorXd v2{3}; + v2 << 1, 2, 3; + CHECK_CLOSE_ABS(perp(v2), std::sqrt(1 + 2 * 2), 1e-9); +} - BOOST_AUTO_TEST_CASE(theta_eta_test_helper) +BOOST_AUTO_TEST_CASE(theta_eta_test_helper) { + Vector3D v(1, 2, 3); + CHECK_CLOSE_ABS(theta(v), 0.640522, 1e-5); + CHECK_CLOSE_ABS(eta(v), 1.10359, 1e-5); + + // should work with dynamic types as well + ActsVectorXd v2{3}; + v2 << 1, 2, 3; + CHECK_CLOSE_ABS(theta(v2), 0.640522, 1e-5); + CHECK_CLOSE_ABS(eta(v2), 1.10359, 1e-5); +} + +BOOST_AUTO_TEST_CASE(cross_test_helper) { { Vector3D v(1, 2, 3); - CHECK_CLOSE_ABS(theta(v), 0.640522, 1e-5); - CHECK_CLOSE_ABS(eta(v), 1.10359, 1e-5); - - // should work with dynamic types as well - ActsVectorXd v2{3}; - v2 << 1, 2, 3; - CHECK_CLOSE_ABS(theta(v2), 0.640522, 1e-5); - CHECK_CLOSE_ABS(eta(v2), 1.10359, 1e-5); - } + ActsMatrixD<3, 3> mat; + mat << 1, 2, 3, 4, 5, 6, 7, 8, 9; - BOOST_AUTO_TEST_CASE(cross_test_helper) - { - { - Vector3D v(1, 2, 3); - ActsMatrixD<3, 3> mat; - mat << 1, 2, 3, 4, 5, 6, 7, 8, 9; - - ActsMatrixD<3, 3> act = cross(mat, v); - ActsMatrixD<3, 3> exp; - exp << -2, -1, 0, 4, 2, 0, -2, -1, 0; - - CHECK_CLOSE_ABS(act, exp, 1e-9); - } - - // should work with dynamic types as well - { - ActsVectorXd v{3}; - v << 1, 2, 3; - ActsMatrixXd mat{3, 3}; - mat << 1, 2, 3, 4, 5, 6, 7, 8, 9; - - ActsMatrixXd act = cross(mat, v); - ActsMatrixXd exp{3, 3}; - exp << -2, -1, 0, 4, 2, 0, -2, -1, 0; - - BOOST_CHECK(act.isApprox(exp, 1e-9)); - } + ActsMatrixD<3, 3> act = cross(mat, v); + ActsMatrixD<3, 3> exp; + exp << -2, -1, 0, 4, 2, 0, -2, -1, 0; + + CHECK_CLOSE_ABS(act, exp, 1e-9); } - BOOST_AUTO_TEST_CASE(toString_test_helper) + // should work with dynamic types as well { - ActsMatrixD<3, 3> mat; + ActsVectorXd v{3}; + v << 1, 2, 3; + ActsMatrixXd mat{3, 3}; mat << 1, 2, 3, 4, 5, 6, 7, 8, 9; - std::string out; - out = toString(mat); - BOOST_CHECK(out.size() > 0); - - Translation3D trl{Vector3D{1, 2, 3}}; - out = toString(trl); - BOOST_CHECK(out.size() > 0); - - Transform3D trf; - trf = trl; - out = toString(trf); - BOOST_CHECK(out.size() > 0); + + ActsMatrixXd act = cross(mat, v); + ActsMatrixXd exp{3, 3}; + exp << -2, -1, 0, 4, 2, 0, -2, -1, 0; + + BOOST_CHECK(act.isApprox(exp, 1e-9)); } +} - BOOST_AUTO_TEST_CASE(shared_vector_helper_test) +BOOST_AUTO_TEST_CASE(toString_test_helper) { + ActsMatrixD<3, 3> mat; + mat << 1, 2, 3, 4, 5, 6, 7, 8, 9; + std::string out; + out = toString(mat); + BOOST_CHECK(out.size() > 0); + + Translation3D trl{Vector3D{1, 2, 3}}; + out = toString(trl); + BOOST_CHECK(out.size() > 0); + + Transform3D trf; + trf = trl; + out = toString(trf); + BOOST_CHECK(out.size() > 0); +} + +BOOST_AUTO_TEST_CASE(shared_vector_helper_test) { { - { - std::vector<std::shared_ptr<int>> vec; - vec = {std::make_shared<int>(5), - std::make_shared<int>(9), - std::make_shared<int>(26), - std::make_shared<int>(18473)}; - - std::vector<int*> unpacked = unpack_shared_vector(vec); - - std::vector<int*> exp = { - vec[0].get(), vec[1].get(), vec[2].get(), vec[3].get(), - }; - - BOOST_CHECK_EQUAL_COLLECTIONS( - unpacked.begin(), unpacked.end(), exp.begin(), exp.end()); - } - - // same for const - { - std::vector<std::shared_ptr<const int>> vec; - vec = {std::make_shared<const int>(5), - std::make_shared<const int>(9), - std::make_shared<const int>(26), - std::make_shared<const int>(18473)}; - - std::vector<const int*> unpacked = unpack_shared_vector(vec); - - std::vector<const int*> exp = { - vec[0].get(), vec[1].get(), vec[2].get(), vec[3].get(), - }; - - BOOST_CHECK_EQUAL_COLLECTIONS( - unpacked.begin(), unpacked.end(), exp.begin(), exp.end()); - } + std::vector<std::shared_ptr<int>> vec; + vec = {std::make_shared<int>(5), std::make_shared<int>(9), + std::make_shared<int>(26), std::make_shared<int>(18473)}; + + std::vector<int*> unpacked = unpack_shared_vector(vec); + + std::vector<int*> exp = { + vec[0].get(), + vec[1].get(), + vec[2].get(), + vec[3].get(), + }; + + BOOST_CHECK_EQUAL_COLLECTIONS(unpacked.begin(), unpacked.end(), exp.begin(), + exp.end()); } - BOOST_AUTO_TEST_SUITE_END() -} + // same for const + { + std::vector<std::shared_ptr<const int>> vec; + vec = {std::make_shared<const int>(5), std::make_shared<const int>(9), + std::make_shared<const int>(26), std::make_shared<const int>(18473)}; + + std::vector<const int*> unpacked = unpack_shared_vector(vec); + + std::vector<const int*> exp = { + vec[0].get(), + vec[1].get(), + vec[2].get(), + vec[3].get(), + }; + + BOOST_CHECK_EQUAL_COLLECTIONS(unpacked.begin(), unpacked.end(), exp.begin(), + exp.end()); + } } + +BOOST_AUTO_TEST_SUITE_END() +} // namespace Test +} // namespace Acts diff --git a/Tests/Core/Utilities/InterpolationTests.cpp b/Tests/Core/Utilities/InterpolationTests.cpp index 6bad12c0c358aadfc5456666c65028363a163974..a445254363baf51bae99636b6ea2bb244673ddcd 100644 --- a/Tests/Core/Utilities/InterpolationTests.cpp +++ b/Tests/Core/Utilities/InterpolationTests.cpp @@ -23,135 +23,107 @@ using namespace detail; namespace Test { - BOOST_AUTO_TEST_CASE(interpolation_1d) - { - using Point = std::array<double, 1u>; - using Values = std::array<double, 2u>; - - Point low = {{1.}}; - Point high = {{2.}}; - Values v = {{10., 20.}}; - - CHECK_CLOSE_REL(interpolate(Point({{0.5}}), low, high, v), 5., 1e-6); - CHECK_CLOSE_REL(interpolate(Point({{1.}}), low, high, v), 10., 1e-6); - CHECK_CLOSE_REL(interpolate(Point({{1.3}}), low, high, v), 13., 1e-6); - CHECK_CLOSE_REL(interpolate(Point({{1.5}}), low, high, v), 15., 1e-6); - CHECK_CLOSE_REL(interpolate(Point({{1.8}}), low, high, v), 18., 1e-6); - CHECK_CLOSE_REL(interpolate(Point({{2.}}), low, high, v), 20., 1e-6); - CHECK_CLOSE_REL(interpolate(Point({{2.3}}), low, high, v), 23., 1e-6); - } - - BOOST_AUTO_TEST_CASE(interpolation_2d) - { - using Point = std::array<double, 2u>; - using Values = std::array<double, 4u>; - - Point low = {{1., 1.}}; - Point high = {{2., 3.}}; - Values v = {{10., 30., 20., 40.}}; - - CHECK_CLOSE_REL(interpolate(Point({{1., 1.}}), low, high, v), 10., 1e-6); - CHECK_CLOSE_REL(interpolate(Point({{2., 1.}}), low, high, v), 20., 1e-6); - CHECK_CLOSE_REL(interpolate(Point({{1., 3.}}), low, high, v), 30., 1e-6); - CHECK_CLOSE_REL(interpolate(Point({{2., 3.}}), low, high, v), 40., 1e-6); - CHECK_CLOSE_REL(interpolate(Point({{1.3, 1.}}), low, high, v), 13., 1e-6); - CHECK_CLOSE_REL(interpolate(Point({{1.5, 1.}}), low, high, v), 15., 1e-6); - CHECK_CLOSE_REL(interpolate(Point({{1.8, 1.}}), low, high, v), 18., 1e-6); - CHECK_CLOSE_REL(interpolate(Point({{1.3, 3.}}), low, high, v), 33., 1e-6); - CHECK_CLOSE_REL(interpolate(Point({{1.5, 3.}}), low, high, v), 35., 1e-6); - CHECK_CLOSE_REL(interpolate(Point({{1.8, 3.}}), low, high, v), 38., 1e-6); - CHECK_CLOSE_REL(interpolate(Point({{1., 1.7}}), low, high, v), 17., 1e-6); - CHECK_CLOSE_REL(interpolate(Point({{1., 2.}}), low, high, v), 20., 1e-6); - CHECK_CLOSE_REL(interpolate(Point({{1., 2.5}}), low, high, v), 25., 1e-6); - CHECK_CLOSE_REL(interpolate(Point({{2., 1.7}}), low, high, v), 27., 1e-6); - CHECK_CLOSE_REL(interpolate(Point({{2., 2.}}), low, high, v), 30., 1e-6); - CHECK_CLOSE_REL(interpolate(Point({{2., 2.5}}), low, high, v), 35., 1e-6); - CHECK_CLOSE_REL(interpolate(Point({{1.5, 2.}}), low, high, v), 25., 1e-6); - CHECK_CLOSE_REL(interpolate(Point({{1.3, 1.7}}), low, high, v), 20., 1e-6); - CHECK_CLOSE_REL(interpolate(Point({{1.3, 2.5}}), low, high, v), 28., 1e-6); - CHECK_CLOSE_REL(interpolate(Point({{1.8, 1.7}}), low, high, v), 25., 1e-6); - CHECK_CLOSE_REL(interpolate(Point({{1.8, 2.5}}), low, high, v), 33., 1e-6); - } - - BOOST_AUTO_TEST_CASE(interpolation_3d) - { - using Point = std::array<double, 3u>; - using Values = std::array<double, 8u>; - - Point low = {{1., 1., 1.}}; - Point high = {{2., 3., 4.}}; - Values v = {{10., 50., 30., 70., 20., 60., 40., 80.}}; - - CHECK_CLOSE_REL( - interpolate(Point({{1., 1., 1.}}), low, high, v), 10., 1e-6); - CHECK_CLOSE_REL( - interpolate(Point({{2., 1., 1.}}), low, high, v), 20., 1e-6); - CHECK_CLOSE_REL( - interpolate(Point({{1., 3., 1.}}), low, high, v), 30., 1e-6); - CHECK_CLOSE_REL( - interpolate(Point({{2., 3., 1.}}), low, high, v), 40., 1e-6); - CHECK_CLOSE_REL( - interpolate(Point({{1., 1., 4.}}), low, high, v), 50., 1e-6); - CHECK_CLOSE_REL( - interpolate(Point({{2., 1., 4.}}), low, high, v), 60., 1e-6); - CHECK_CLOSE_REL( - interpolate(Point({{1., 3., 4.}}), low, high, v), 70., 1e-6); - CHECK_CLOSE_REL( - interpolate(Point({{2., 3., 4.}}), low, high, v), 80., 1e-6); - CHECK_CLOSE_REL( - interpolate(Point({{1.5, 1., 1.}}), low, high, v), 15., 1e-6); - CHECK_CLOSE_REL( - interpolate(Point({{1.5, 3., 1.}}), low, high, v), 35., 1e-6); - CHECK_CLOSE_REL( - interpolate(Point({{1., 2., 1.}}), low, high, v), 20., 1e-6); - CHECK_CLOSE_REL( - interpolate(Point({{2., 2., 1.}}), low, high, v), 30., 1e-6); - CHECK_CLOSE_REL( - interpolate(Point({{1.5, 1., 4.}}), low, high, v), 55., 1e-6); - CHECK_CLOSE_REL( - interpolate(Point({{1.5, 3., 4.}}), low, high, v), 75., 1e-6); - CHECK_CLOSE_REL( - interpolate(Point({{1., 2., 4.}}), low, high, v), 60., 1e-6); - CHECK_CLOSE_REL( - interpolate(Point({{2., 2., 4.}}), low, high, v), 70., 1e-6); - CHECK_CLOSE_REL( - interpolate(Point({{1., 1., 2.5}}), low, high, v), 30., 1e-6); - CHECK_CLOSE_REL( - interpolate(Point({{1., 3., 2.5}}), low, high, v), 50., 1e-6); - CHECK_CLOSE_REL( - interpolate(Point({{2., 1., 2.5}}), low, high, v), 40., 1e-6); - CHECK_CLOSE_REL( - interpolate(Point({{2., 3., 2.5}}), low, high, v), 60., 1e-6); - CHECK_CLOSE_REL( - interpolate(Point({{1.5, 2., 2.5}}), low, high, v), 360. / 8, 1e-6); - CHECK_CLOSE_REL( - interpolate(Point({{1.3, 2.1, 1.6}}), low, high, v), 32., 1e-6); - } - - BOOST_AUTO_TEST_CASE(interpolation_mixed_point_values) - { - using Point1 = ActsVectorD<1>; - using Point2 = std::array<double, 1u>; - using Point3 = std::vector<double>; - using Values = std::array<double, 2u>; - - Point2 low = {{1.}}; - Point3 high = {2.}; - Values v = {{10., 20.}}; - - Point1 p; - CHECK_CLOSE_REL(interpolate((p << 0.5).finished(), low, high, v), 5., 1e-6); - CHECK_CLOSE_REL(interpolate((p << 1.).finished(), low, high, v), 10., 1e-6); - CHECK_CLOSE_REL( - interpolate((p << 1.3).finished(), low, high, v), 13., 1e-6); - CHECK_CLOSE_REL( - interpolate((p << 1.5).finished(), low, high, v), 15., 1e-6); - CHECK_CLOSE_REL( - interpolate((p << 1.8).finished(), low, high, v), 18., 1e-6); - CHECK_CLOSE_REL(interpolate((p << 2.).finished(), low, high, v), 20., 1e-6); - CHECK_CLOSE_REL( - interpolate((p << 2.3).finished(), low, high, v), 23., 1e-6); - } +BOOST_AUTO_TEST_CASE(interpolation_1d) { + using Point = std::array<double, 1u>; + using Values = std::array<double, 2u>; + + Point low = {{1.}}; + Point high = {{2.}}; + Values v = {{10., 20.}}; + + CHECK_CLOSE_REL(interpolate(Point({{0.5}}), low, high, v), 5., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{1.}}), low, high, v), 10., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{1.3}}), low, high, v), 13., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{1.5}}), low, high, v), 15., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{1.8}}), low, high, v), 18., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{2.}}), low, high, v), 20., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{2.3}}), low, high, v), 23., 1e-6); +} + +BOOST_AUTO_TEST_CASE(interpolation_2d) { + using Point = std::array<double, 2u>; + using Values = std::array<double, 4u>; + + Point low = {{1., 1.}}; + Point high = {{2., 3.}}; + Values v = {{10., 30., 20., 40.}}; + + CHECK_CLOSE_REL(interpolate(Point({{1., 1.}}), low, high, v), 10., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{2., 1.}}), low, high, v), 20., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{1., 3.}}), low, high, v), 30., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{2., 3.}}), low, high, v), 40., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{1.3, 1.}}), low, high, v), 13., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{1.5, 1.}}), low, high, v), 15., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{1.8, 1.}}), low, high, v), 18., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{1.3, 3.}}), low, high, v), 33., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{1.5, 3.}}), low, high, v), 35., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{1.8, 3.}}), low, high, v), 38., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{1., 1.7}}), low, high, v), 17., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{1., 2.}}), low, high, v), 20., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{1., 2.5}}), low, high, v), 25., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{2., 1.7}}), low, high, v), 27., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{2., 2.}}), low, high, v), 30., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{2., 2.5}}), low, high, v), 35., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{1.5, 2.}}), low, high, v), 25., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{1.3, 1.7}}), low, high, v), 20., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{1.3, 2.5}}), low, high, v), 28., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{1.8, 1.7}}), low, high, v), 25., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{1.8, 2.5}}), low, high, v), 33., 1e-6); +} + +BOOST_AUTO_TEST_CASE(interpolation_3d) { + using Point = std::array<double, 3u>; + using Values = std::array<double, 8u>; + + Point low = {{1., 1., 1.}}; + Point high = {{2., 3., 4.}}; + Values v = {{10., 50., 30., 70., 20., 60., 40., 80.}}; + + CHECK_CLOSE_REL(interpolate(Point({{1., 1., 1.}}), low, high, v), 10., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{2., 1., 1.}}), low, high, v), 20., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{1., 3., 1.}}), low, high, v), 30., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{2., 3., 1.}}), low, high, v), 40., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{1., 1., 4.}}), low, high, v), 50., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{2., 1., 4.}}), low, high, v), 60., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{1., 3., 4.}}), low, high, v), 70., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{2., 3., 4.}}), low, high, v), 80., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{1.5, 1., 1.}}), low, high, v), 15., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{1.5, 3., 1.}}), low, high, v), 35., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{1., 2., 1.}}), low, high, v), 20., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{2., 2., 1.}}), low, high, v), 30., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{1.5, 1., 4.}}), low, high, v), 55., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{1.5, 3., 4.}}), low, high, v), 75., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{1., 2., 4.}}), low, high, v), 60., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{2., 2., 4.}}), low, high, v), 70., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{1., 1., 2.5}}), low, high, v), 30., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{1., 3., 2.5}}), low, high, v), 50., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{2., 1., 2.5}}), low, high, v), 40., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{2., 3., 2.5}}), low, high, v), 60., 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{1.5, 2., 2.5}}), low, high, v), 360. / 8, + 1e-6); + CHECK_CLOSE_REL(interpolate(Point({{1.3, 2.1, 1.6}}), low, high, v), 32., + 1e-6); +} + +BOOST_AUTO_TEST_CASE(interpolation_mixed_point_values) { + using Point1 = ActsVectorD<1>; + using Point2 = std::array<double, 1u>; + using Point3 = std::vector<double>; + using Values = std::array<double, 2u>; + + Point2 low = {{1.}}; + Point3 high = {2.}; + Values v = {{10., 20.}}; + + Point1 p; + CHECK_CLOSE_REL(interpolate((p << 0.5).finished(), low, high, v), 5., 1e-6); + CHECK_CLOSE_REL(interpolate((p << 1.).finished(), low, high, v), 10., 1e-6); + CHECK_CLOSE_REL(interpolate((p << 1.3).finished(), low, high, v), 13., 1e-6); + CHECK_CLOSE_REL(interpolate((p << 1.5).finished(), low, high, v), 15., 1e-6); + CHECK_CLOSE_REL(interpolate((p << 1.8).finished(), low, high, v), 18., 1e-6); + CHECK_CLOSE_REL(interpolate((p << 2.).finished(), low, high, v), 20., 1e-6); + CHECK_CLOSE_REL(interpolate((p << 2.3).finished(), low, high, v), 23., 1e-6); +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/Utilities/IntersectionTests.cpp b/Tests/Core/Utilities/IntersectionTests.cpp index 393693edffe1a3306bc7efb5f3123b7690837597..4731c32d249dafcdb5ebd30e40e56ed48ffa499c 100644 --- a/Tests/Core/Utilities/IntersectionTests.cpp +++ b/Tests/Core/Utilities/IntersectionTests.cpp @@ -17,189 +17,179 @@ namespace Acts { namespace Test { - /// test of the intersection class - BOOST_AUTO_TEST_CASE(IntersectionTest) - { - - // a few valid intersections - // all positively sortered - Intersection fIp(Vector3D(0., 1., 0.), 1., true); - Intersection sIp(Vector3D(0., 2., 0.), 2., true); - Intersection tIp(Vector3D(0., 3., 0.), 3., true); - - // a non-valid intersection - Intersection nIp(Vector3D(3., 3., 0.), 3., false); - BOOST_CHECK(!nIp.valid); - - std::vector<Intersection> fstpIntersections = {fIp, sIp, tIp}; - std::vector<Intersection> tsfpIntersections = {tIp, sIp, fIp}; - - // let's sort the tsf intersection, it should give fst - std::sort(tsfpIntersections.begin(), tsfpIntersections.end()); - BOOST_CHECK_EQUAL(fstpIntersections[0].pathLength, - tsfpIntersections[0].pathLength); - BOOST_CHECK_EQUAL(fstpIntersections[1].pathLength, - tsfpIntersections[1].pathLength); - BOOST_CHECK_EQUAL(fstpIntersections[2].pathLength, - tsfpIntersections[2].pathLength); - - // let's sort them with greater - std::sort( - tsfpIntersections.begin(), tsfpIntersections.end(), std::greater<>()); - BOOST_CHECK_EQUAL(fstpIntersections[0].pathLength, - tsfpIntersections[2].pathLength); - BOOST_CHECK_EQUAL(fstpIntersections[1].pathLength, - tsfpIntersections[1].pathLength); - BOOST_CHECK_EQUAL(fstpIntersections[2].pathLength, - tsfpIntersections[0].pathLength); - - // now let's create one with a non-valid intersection, it should be shuffled - // last - std::vector<Intersection> ntfspIntersections = {nIp, tIp, fIp, sIp}; - std::vector<Intersection> tfnsnpIntersections = {tIp, fIp, nIp, sIp, nIp}; - - // shuffle the intersections - std::sort(ntfspIntersections.begin(), ntfspIntersections.end()); - BOOST_CHECK_EQUAL(fstpIntersections[0].pathLength, - ntfspIntersections[0].pathLength); - BOOST_CHECK_EQUAL(fstpIntersections[1].pathLength, - ntfspIntersections[1].pathLength); - BOOST_CHECK_EQUAL(fstpIntersections[2].pathLength, - ntfspIntersections[2].pathLength); - BOOST_CHECK_EQUAL(ntfspIntersections[3].valid, false); - - std::sort(tfnsnpIntersections.begin(), tfnsnpIntersections.end()); - BOOST_CHECK_EQUAL(fstpIntersections[0].pathLength, - tfnsnpIntersections[0].pathLength); - BOOST_CHECK_EQUAL(fstpIntersections[1].pathLength, - tfnsnpIntersections[1].pathLength); - BOOST_CHECK_EQUAL(fstpIntersections[2].pathLength, - tfnsnpIntersections[2].pathLength); - BOOST_CHECK_EQUAL(tfnsnpIntersections[3].valid, false); - BOOST_CHECK_EQUAL(tfnsnpIntersections[4].valid, false); - - /// let's make a bunch of negative solution - Intersection fIn(Vector3D(0., -1., 0.), -1., true); - Intersection sIn(Vector3D(0., -2., 0.), -2., true); - Intersection tIn(Vector3D(0., -3., 0.), -3., true); - - std::vector<Intersection> tsfnIntersections = {tIn, sIn, fIn}; - std::vector<Intersection> fstnIntersections = {fIn, sIn, tIn}; - - // this time around, sort the f-s-t-n to match the t-s-f-n - std::sort(fstnIntersections.begin(), fstnIntersections.end()); - BOOST_CHECK_EQUAL(fstnIntersections[0].pathLength, - tsfnIntersections[0].pathLength); - BOOST_CHECK_EQUAL(fstnIntersections[1].pathLength, - tsfnIntersections[1].pathLength); - BOOST_CHECK_EQUAL(fstnIntersections[2].pathLength, - tsfnIntersections[2].pathLength); - - // let's sort them with greater - std::sort( - fstnIntersections.begin(), fstnIntersections.end(), std::greater<>()); - BOOST_CHECK_EQUAL(fstnIntersections[0].pathLength, - tsfnIntersections[2].pathLength); - BOOST_CHECK_EQUAL(fstnIntersections[1].pathLength, - tsfnIntersections[1].pathLength); - BOOST_CHECK_EQUAL(fstnIntersections[2].pathLength, - tsfnIntersections[0].pathLength); - - // shuffle negative and positive solutions - std::vector<Intersection> pnsolutions = {tIp, sIn, sIp, fIn, tIn, fIp}; - std::sort(pnsolutions.begin(), pnsolutions.end()); - - BOOST_CHECK_EQUAL(pnsolutions[0].pathLength, -3.); - BOOST_CHECK_EQUAL(pnsolutions[1].pathLength, -2.); - BOOST_CHECK_EQUAL(pnsolutions[2].pathLength, -1.); - BOOST_CHECK_EQUAL(pnsolutions[3].pathLength, 1.); - BOOST_CHECK_EQUAL(pnsolutions[4].pathLength, 2.); - BOOST_CHECK_EQUAL(pnsolutions[5].pathLength, 3.); - - // sort intersections with zero path length - Intersection zI(Vector3D(0., 0., 0.), 0., true); - std::vector<Intersection> tszfpIntersections = {tIp, sIp, zI, fIp}; - - std::sort(tszfpIntersections.begin(), tszfpIntersections.end()); - BOOST_CHECK_EQUAL(tszfpIntersections[0].pathLength, 0.); - BOOST_CHECK_EQUAL(tszfpIntersections[1].pathLength, 1.); - BOOST_CHECK_EQUAL(tszfpIntersections[2].pathLength, 2.); - BOOST_CHECK_EQUAL(tszfpIntersections[3].pathLength, 3.); - - std::vector<Intersection> tfsznIntersections = {tIn, fIn, sIn, zI}; - std::vector<Intersection> ztfsnIntersections = {zI, tIn, fIn, sIn}; - - std::sort( - tfsznIntersections.begin(), tfsznIntersections.end(), std::greater<>()); - BOOST_CHECK_EQUAL(tfsznIntersections[0].pathLength, 0.); - BOOST_CHECK_EQUAL(tfsznIntersections[1].pathLength, -1.); - BOOST_CHECK_EQUAL(tfsznIntersections[2].pathLength, -2.); - BOOST_CHECK_EQUAL(tfsznIntersections[3].pathLength, -3.); - - std::sort( - ztfsnIntersections.begin(), ztfsnIntersections.end(), std::greater<>()); - BOOST_CHECK_EQUAL(ztfsnIntersections[0].pathLength, 0.); - BOOST_CHECK_EQUAL(ztfsnIntersections[1].pathLength, -1.); - BOOST_CHECK_EQUAL(ztfsnIntersections[2].pathLength, -2.); - BOOST_CHECK_EQUAL(ztfsnIntersections[3].pathLength, -3.); - } - - /// test of the object intersection class - BOOST_AUTO_TEST_CASE(ObjectIntersectionTest) - { - - auto psf6 = Surface::makeShared<PlaneSurface>(Vector3D(6., 0., 0.), - Vector3D(1., 0., 0.)); - auto psf7 = Surface::makeShared<PlaneSurface>(Vector3D(7., 0., 0.), - Vector3D(1., 0., 0.)); - auto psf8 = Surface::makeShared<PlaneSurface>(Vector3D(8., 0., 0.), - Vector3D(1., 0., 0.)); - auto psf9 = Surface::makeShared<PlaneSurface>(Vector3D(9., 0., 0.), - Vector3D(1., 0., 0.)); - auto psf10 = Surface::makeShared<PlaneSurface>(Vector3D(10., 0., 0.), - Vector3D(1., 0., 0.)); - - using PlaneIntersection = ObjectIntersection<PlaneSurface>; - - PlaneIntersection int6(Intersection(Vector3D(6., 0., 0.), 6., true), - psf6.get()); - PlaneIntersection int7(Intersection(Vector3D(7., 0., 0.), 7., true), - psf7.get()); - PlaneIntersection int8(Intersection(Vector3D(8., 0., 0.), 8., true), - psf8.get()); - PlaneIntersection int9a(Intersection(Vector3D(9., 0., 0.), 9., true), - psf9.get()); - PlaneIntersection int9b( - Intersection(Vector3D(9., 1., 0.), std::sqrt(9. * 9. + 1.), true), - psf9.get()); - PlaneIntersection int10(Intersection(Vector3D(10., 0., 0.), 10., true), - psf10.get()); - - std::vector<PlaneIntersection> firstSet = {int6, int7, int9b, int10}; - std::vector<PlaneIntersection> secondSet = {int8, int9a, int9b, int10}; - // result of the standard union set - std::vector<PlaneIntersection> unionSetStd = {}; - // result of the custominzed union set - std::vector<PlaneIntersection> unionSetCst = {}; - - // This should give 6 different intersections - std::set_union(firstSet.begin(), - firstSet.end(), - secondSet.begin(), - secondSet.end(), - std::back_inserter(unionSetStd)); - BOOST_CHECK_EQUAL(unionSetStd.size(), 6); - - // This should give 5 different inteseciton attempts (for each surface 1) - SameSurfaceIntersection onSameSurface; - std::set_union(firstSet.begin(), - firstSet.end(), - secondSet.begin(), - secondSet.end(), - std::back_inserter(unionSetCst), - onSameSurface); - BOOST_CHECK_EQUAL(unionSetCst.size(), 5); - } +/// test of the intersection class +BOOST_AUTO_TEST_CASE(IntersectionTest) { + // a few valid intersections + // all positively sortered + Intersection fIp(Vector3D(0., 1., 0.), 1., true); + Intersection sIp(Vector3D(0., 2., 0.), 2., true); + Intersection tIp(Vector3D(0., 3., 0.), 3., true); + + // a non-valid intersection + Intersection nIp(Vector3D(3., 3., 0.), 3., false); + BOOST_CHECK(!nIp.valid); + + std::vector<Intersection> fstpIntersections = {fIp, sIp, tIp}; + std::vector<Intersection> tsfpIntersections = {tIp, sIp, fIp}; + + // let's sort the tsf intersection, it should give fst + std::sort(tsfpIntersections.begin(), tsfpIntersections.end()); + BOOST_CHECK_EQUAL(fstpIntersections[0].pathLength, + tsfpIntersections[0].pathLength); + BOOST_CHECK_EQUAL(fstpIntersections[1].pathLength, + tsfpIntersections[1].pathLength); + BOOST_CHECK_EQUAL(fstpIntersections[2].pathLength, + tsfpIntersections[2].pathLength); + + // let's sort them with greater + std::sort(tsfpIntersections.begin(), tsfpIntersections.end(), + std::greater<>()); + BOOST_CHECK_EQUAL(fstpIntersections[0].pathLength, + tsfpIntersections[2].pathLength); + BOOST_CHECK_EQUAL(fstpIntersections[1].pathLength, + tsfpIntersections[1].pathLength); + BOOST_CHECK_EQUAL(fstpIntersections[2].pathLength, + tsfpIntersections[0].pathLength); + + // now let's create one with a non-valid intersection, it should be shuffled + // last + std::vector<Intersection> ntfspIntersections = {nIp, tIp, fIp, sIp}; + std::vector<Intersection> tfnsnpIntersections = {tIp, fIp, nIp, sIp, nIp}; + + // shuffle the intersections + std::sort(ntfspIntersections.begin(), ntfspIntersections.end()); + BOOST_CHECK_EQUAL(fstpIntersections[0].pathLength, + ntfspIntersections[0].pathLength); + BOOST_CHECK_EQUAL(fstpIntersections[1].pathLength, + ntfspIntersections[1].pathLength); + BOOST_CHECK_EQUAL(fstpIntersections[2].pathLength, + ntfspIntersections[2].pathLength); + BOOST_CHECK_EQUAL(ntfspIntersections[3].valid, false); + + std::sort(tfnsnpIntersections.begin(), tfnsnpIntersections.end()); + BOOST_CHECK_EQUAL(fstpIntersections[0].pathLength, + tfnsnpIntersections[0].pathLength); + BOOST_CHECK_EQUAL(fstpIntersections[1].pathLength, + tfnsnpIntersections[1].pathLength); + BOOST_CHECK_EQUAL(fstpIntersections[2].pathLength, + tfnsnpIntersections[2].pathLength); + BOOST_CHECK_EQUAL(tfnsnpIntersections[3].valid, false); + BOOST_CHECK_EQUAL(tfnsnpIntersections[4].valid, false); + + /// let's make a bunch of negative solution + Intersection fIn(Vector3D(0., -1., 0.), -1., true); + Intersection sIn(Vector3D(0., -2., 0.), -2., true); + Intersection tIn(Vector3D(0., -3., 0.), -3., true); + + std::vector<Intersection> tsfnIntersections = {tIn, sIn, fIn}; + std::vector<Intersection> fstnIntersections = {fIn, sIn, tIn}; + + // this time around, sort the f-s-t-n to match the t-s-f-n + std::sort(fstnIntersections.begin(), fstnIntersections.end()); + BOOST_CHECK_EQUAL(fstnIntersections[0].pathLength, + tsfnIntersections[0].pathLength); + BOOST_CHECK_EQUAL(fstnIntersections[1].pathLength, + tsfnIntersections[1].pathLength); + BOOST_CHECK_EQUAL(fstnIntersections[2].pathLength, + tsfnIntersections[2].pathLength); + + // let's sort them with greater + std::sort(fstnIntersections.begin(), fstnIntersections.end(), + std::greater<>()); + BOOST_CHECK_EQUAL(fstnIntersections[0].pathLength, + tsfnIntersections[2].pathLength); + BOOST_CHECK_EQUAL(fstnIntersections[1].pathLength, + tsfnIntersections[1].pathLength); + BOOST_CHECK_EQUAL(fstnIntersections[2].pathLength, + tsfnIntersections[0].pathLength); + + // shuffle negative and positive solutions + std::vector<Intersection> pnsolutions = {tIp, sIn, sIp, fIn, tIn, fIp}; + std::sort(pnsolutions.begin(), pnsolutions.end()); + + BOOST_CHECK_EQUAL(pnsolutions[0].pathLength, -3.); + BOOST_CHECK_EQUAL(pnsolutions[1].pathLength, -2.); + BOOST_CHECK_EQUAL(pnsolutions[2].pathLength, -1.); + BOOST_CHECK_EQUAL(pnsolutions[3].pathLength, 1.); + BOOST_CHECK_EQUAL(pnsolutions[4].pathLength, 2.); + BOOST_CHECK_EQUAL(pnsolutions[5].pathLength, 3.); + + // sort intersections with zero path length + Intersection zI(Vector3D(0., 0., 0.), 0., true); + std::vector<Intersection> tszfpIntersections = {tIp, sIp, zI, fIp}; + + std::sort(tszfpIntersections.begin(), tszfpIntersections.end()); + BOOST_CHECK_EQUAL(tszfpIntersections[0].pathLength, 0.); + BOOST_CHECK_EQUAL(tszfpIntersections[1].pathLength, 1.); + BOOST_CHECK_EQUAL(tszfpIntersections[2].pathLength, 2.); + BOOST_CHECK_EQUAL(tszfpIntersections[3].pathLength, 3.); + + std::vector<Intersection> tfsznIntersections = {tIn, fIn, sIn, zI}; + std::vector<Intersection> ztfsnIntersections = {zI, tIn, fIn, sIn}; + + std::sort(tfsznIntersections.begin(), tfsznIntersections.end(), + std::greater<>()); + BOOST_CHECK_EQUAL(tfsznIntersections[0].pathLength, 0.); + BOOST_CHECK_EQUAL(tfsznIntersections[1].pathLength, -1.); + BOOST_CHECK_EQUAL(tfsznIntersections[2].pathLength, -2.); + BOOST_CHECK_EQUAL(tfsznIntersections[3].pathLength, -3.); + + std::sort(ztfsnIntersections.begin(), ztfsnIntersections.end(), + std::greater<>()); + BOOST_CHECK_EQUAL(ztfsnIntersections[0].pathLength, 0.); + BOOST_CHECK_EQUAL(ztfsnIntersections[1].pathLength, -1.); + BOOST_CHECK_EQUAL(ztfsnIntersections[2].pathLength, -2.); + BOOST_CHECK_EQUAL(ztfsnIntersections[3].pathLength, -3.); +} + +/// test of the object intersection class +BOOST_AUTO_TEST_CASE(ObjectIntersectionTest) { + auto psf6 = Surface::makeShared<PlaneSurface>(Vector3D(6., 0., 0.), + Vector3D(1., 0., 0.)); + auto psf7 = Surface::makeShared<PlaneSurface>(Vector3D(7., 0., 0.), + Vector3D(1., 0., 0.)); + auto psf8 = Surface::makeShared<PlaneSurface>(Vector3D(8., 0., 0.), + Vector3D(1., 0., 0.)); + auto psf9 = Surface::makeShared<PlaneSurface>(Vector3D(9., 0., 0.), + Vector3D(1., 0., 0.)); + auto psf10 = Surface::makeShared<PlaneSurface>(Vector3D(10., 0., 0.), + Vector3D(1., 0., 0.)); + + using PlaneIntersection = ObjectIntersection<PlaneSurface>; + + PlaneIntersection int6(Intersection(Vector3D(6., 0., 0.), 6., true), + psf6.get()); + PlaneIntersection int7(Intersection(Vector3D(7., 0., 0.), 7., true), + psf7.get()); + PlaneIntersection int8(Intersection(Vector3D(8., 0., 0.), 8., true), + psf8.get()); + PlaneIntersection int9a(Intersection(Vector3D(9., 0., 0.), 9., true), + psf9.get()); + PlaneIntersection int9b( + Intersection(Vector3D(9., 1., 0.), std::sqrt(9. * 9. + 1.), true), + psf9.get()); + PlaneIntersection int10(Intersection(Vector3D(10., 0., 0.), 10., true), + psf10.get()); + + std::vector<PlaneIntersection> firstSet = {int6, int7, int9b, int10}; + std::vector<PlaneIntersection> secondSet = {int8, int9a, int9b, int10}; + // result of the standard union set + std::vector<PlaneIntersection> unionSetStd = {}; + // result of the custominzed union set + std::vector<PlaneIntersection> unionSetCst = {}; + + // This should give 6 different intersections + std::set_union(firstSet.begin(), firstSet.end(), secondSet.begin(), + secondSet.end(), std::back_inserter(unionSetStd)); + BOOST_CHECK_EQUAL(unionSetStd.size(), 6); + + // This should give 5 different inteseciton attempts (for each surface 1) + SameSurfaceIntersection onSameSurface; + std::set_union(firstSet.begin(), firstSet.end(), secondSet.begin(), + secondSet.end(), std::back_inserter(unionSetCst), + onSameSurface); + BOOST_CHECK_EQUAL(unionSetCst.size(), 5); +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/Utilities/LoggerTests.cpp b/Tests/Core/Utilities/LoggerTests.cpp index 14f7609a174ee89e54943494453c1797dc9bd69d..dc97dbcc829ceb5a17850dcfab6d31b873c14a08 100644 --- a/Tests/Core/Utilities/LoggerTests.cpp +++ b/Tests/Core/Utilities/LoggerTests.cpp @@ -18,224 +18,213 @@ namespace Acts { namespace Test { - using namespace Acts::Logging; - - /// @cond - namespace detail { - std::unique_ptr<const Logger> - create_logger(const std::string& logger_name, - std::ostream* logfile, - Logging::Level lvl) - { - auto output = std::make_unique<LevelOutputDecorator>( - std::make_unique<NamedOutputDecorator>( - std::make_unique<DefaultPrintPolicy>(logfile), logger_name)); - auto print = std::make_unique<DefaultFilterPolicy>(lvl); - return std::make_unique<const Logger>(std::move(output), - std::move(print)); - } - - std::string - failure_msg(const std::string& expected, const std::string& found) - { - return std::string("'") + expected + "' != '" + found + "'"; - } - } // namespace detail - /// @endcond - - /// @brief unit test for FATAL debug level - /// - /// This test checks for the expected output when using the - /// Acts::Logging::FATAL debug level as threshold. It also tests - /// - #ACTS_LOCAL_LOGGER - /// - Acts::getDefaultLogger - BOOST_AUTO_TEST_CASE(FATAL_test) - { - std::ofstream logfile("fatal_log.txt"); - - auto log = detail::create_logger("TestLogger", &logfile, FATAL); - ACTS_LOCAL_LOGGER(log); - ACTS_FATAL("fatal level"); - ACTS_ERROR("error level"); - ACTS_WARNING("warning level"); - ACTS_INFO("info level"); - ACTS_DEBUG("debug level"); - ACTS_VERBOSE("verbose level"); - logfile.close(); - - std::vector<std::string> lines; - lines.push_back("TestLogger FATAL fatal level"); - - std::ifstream infile("fatal_log.txt", std::ios::in); - size_t i = 0; - for (std::string line; std::getline(infile, line); ++i) { - BOOST_TEST(line == lines.at(i), detail::failure_msg(line, lines.at(i))); - } +using namespace Acts::Logging; + +/// @cond +namespace detail { +std::unique_ptr<const Logger> create_logger(const std::string& logger_name, + std::ostream* logfile, + Logging::Level lvl) { + auto output = std::make_unique<LevelOutputDecorator>( + std::make_unique<NamedOutputDecorator>( + std::make_unique<DefaultPrintPolicy>(logfile), logger_name)); + auto print = std::make_unique<DefaultFilterPolicy>(lvl); + return std::make_unique<const Logger>(std::move(output), std::move(print)); +} + +std::string failure_msg(const std::string& expected, const std::string& found) { + return std::string("'") + expected + "' != '" + found + "'"; +} +} // namespace detail +/// @endcond + +/// @brief unit test for FATAL debug level +/// +/// This test checks for the expected output when using the +/// Acts::Logging::FATAL debug level as threshold. It also tests +/// - #ACTS_LOCAL_LOGGER +/// - Acts::getDefaultLogger +BOOST_AUTO_TEST_CASE(FATAL_test) { + std::ofstream logfile("fatal_log.txt"); + + auto log = detail::create_logger("TestLogger", &logfile, FATAL); + ACTS_LOCAL_LOGGER(log); + ACTS_FATAL("fatal level"); + ACTS_ERROR("error level"); + ACTS_WARNING("warning level"); + ACTS_INFO("info level"); + ACTS_DEBUG("debug level"); + ACTS_VERBOSE("verbose level"); + logfile.close(); + + std::vector<std::string> lines; + lines.push_back("TestLogger FATAL fatal level"); + + std::ifstream infile("fatal_log.txt", std::ios::in); + size_t i = 0; + for (std::string line; std::getline(infile, line); ++i) { + BOOST_TEST(line == lines.at(i), detail::failure_msg(line, lines.at(i))); } - - /// @brief unit test for ERROR debug level - /// - /// This test checks for the expected output when using the - /// Acts::Logging::ERROR debug level as threshold. It also tests - /// - #ACTS_LOCAL_LOGGER - /// - Acts::getDefaultLogger - BOOST_AUTO_TEST_CASE(ERROR_test) - { - std::ofstream logfile("error_log.txt"); - - auto log = detail::create_logger("TestLogger", &logfile, ERROR); - ACTS_LOCAL_LOGGER(log); - ACTS_FATAL("fatal level"); - ACTS_ERROR("error level"); - ACTS_WARNING("warning level"); - ACTS_INFO("info level"); - ACTS_DEBUG("debug level"); - ACTS_VERBOSE("verbose level"); - logfile.close(); - - std::vector<std::string> lines; - lines.push_back("TestLogger FATAL fatal level"); - lines.push_back("TestLogger ERROR error level"); - - std::ifstream infile("error_log.txt", std::ios::in); - size_t i = 0; - for (std::string line; std::getline(infile, line); ++i) { - BOOST_TEST(line == lines.at(i), detail::failure_msg(line, lines.at(i))); - } +} + +/// @brief unit test for ERROR debug level +/// +/// This test checks for the expected output when using the +/// Acts::Logging::ERROR debug level as threshold. It also tests +/// - #ACTS_LOCAL_LOGGER +/// - Acts::getDefaultLogger +BOOST_AUTO_TEST_CASE(ERROR_test) { + std::ofstream logfile("error_log.txt"); + + auto log = detail::create_logger("TestLogger", &logfile, ERROR); + ACTS_LOCAL_LOGGER(log); + ACTS_FATAL("fatal level"); + ACTS_ERROR("error level"); + ACTS_WARNING("warning level"); + ACTS_INFO("info level"); + ACTS_DEBUG("debug level"); + ACTS_VERBOSE("verbose level"); + logfile.close(); + + std::vector<std::string> lines; + lines.push_back("TestLogger FATAL fatal level"); + lines.push_back("TestLogger ERROR error level"); + + std::ifstream infile("error_log.txt", std::ios::in); + size_t i = 0; + for (std::string line; std::getline(infile, line); ++i) { + BOOST_TEST(line == lines.at(i), detail::failure_msg(line, lines.at(i))); } - - /// @brief unit test for WARNING debug level - /// - /// This test checks for the expected output when using the - /// Acts::Logging::WARNING debug level as threshold. It also tests - /// - #ACTS_LOCAL_LOGGER - /// - Acts::getDefaultLogger - BOOST_AUTO_TEST_CASE(WARNING_test) - { - std::ofstream logfile("warning_log.txt"); - - auto log = detail::create_logger("TestLogger", &logfile, WARNING); - ACTS_LOCAL_LOGGER(log); - ACTS_FATAL("fatal level"); - ACTS_ERROR("error level"); - ACTS_WARNING("warning level"); - ACTS_INFO("info level"); - ACTS_DEBUG("debug level"); - ACTS_VERBOSE("verbose level"); - logfile.close(); - - std::vector<std::string> lines; - lines.push_back("TestLogger FATAL fatal level"); - lines.push_back("TestLogger ERROR error level"); - lines.push_back("TestLogger WARNING warning level"); - - std::ifstream infile("warning_log.txt", std::ios::in); - size_t i = 0; - for (std::string line; std::getline(infile, line); ++i) { - BOOST_TEST(line == lines.at(i), detail::failure_msg(line, lines.at(i))); - } +} + +/// @brief unit test for WARNING debug level +/// +/// This test checks for the expected output when using the +/// Acts::Logging::WARNING debug level as threshold. It also tests +/// - #ACTS_LOCAL_LOGGER +/// - Acts::getDefaultLogger +BOOST_AUTO_TEST_CASE(WARNING_test) { + std::ofstream logfile("warning_log.txt"); + + auto log = detail::create_logger("TestLogger", &logfile, WARNING); + ACTS_LOCAL_LOGGER(log); + ACTS_FATAL("fatal level"); + ACTS_ERROR("error level"); + ACTS_WARNING("warning level"); + ACTS_INFO("info level"); + ACTS_DEBUG("debug level"); + ACTS_VERBOSE("verbose level"); + logfile.close(); + + std::vector<std::string> lines; + lines.push_back("TestLogger FATAL fatal level"); + lines.push_back("TestLogger ERROR error level"); + lines.push_back("TestLogger WARNING warning level"); + + std::ifstream infile("warning_log.txt", std::ios::in); + size_t i = 0; + for (std::string line; std::getline(infile, line); ++i) { + BOOST_TEST(line == lines.at(i), detail::failure_msg(line, lines.at(i))); } - - /// @brief unit test for INFO debug level - /// - /// This test checks for the expected output when using the - /// Acts::Logging::INFO debug level as threshold. It also tests - /// - #ACTS_LOCAL_LOGGER - /// - Acts::getDefaultLogger - BOOST_AUTO_TEST_CASE(INFO_test) - { - std::ofstream logfile("info_log.txt"); - - auto log = detail::create_logger("TestLogger", &logfile, INFO); - ACTS_LOCAL_LOGGER(log); - ACTS_FATAL("fatal level"); - ACTS_ERROR("error level"); - ACTS_WARNING("warning level"); - ACTS_INFO("info level"); - ACTS_DEBUG("debug level"); - ACTS_VERBOSE("verbose level"); - logfile.close(); - - std::vector<std::string> lines; - lines.push_back("TestLogger FATAL fatal level"); - lines.push_back("TestLogger ERROR error level"); - lines.push_back("TestLogger WARNING warning level"); - lines.push_back("TestLogger INFO info level"); - - std::ifstream infile("info_log.txt", std::ios::in); - size_t i = 0; - for (std::string line; std::getline(infile, line); ++i) { - BOOST_TEST(line == lines.at(i), detail::failure_msg(line, lines.at(i))); - } +} + +/// @brief unit test for INFO debug level +/// +/// This test checks for the expected output when using the +/// Acts::Logging::INFO debug level as threshold. It also tests +/// - #ACTS_LOCAL_LOGGER +/// - Acts::getDefaultLogger +BOOST_AUTO_TEST_CASE(INFO_test) { + std::ofstream logfile("info_log.txt"); + + auto log = detail::create_logger("TestLogger", &logfile, INFO); + ACTS_LOCAL_LOGGER(log); + ACTS_FATAL("fatal level"); + ACTS_ERROR("error level"); + ACTS_WARNING("warning level"); + ACTS_INFO("info level"); + ACTS_DEBUG("debug level"); + ACTS_VERBOSE("verbose level"); + logfile.close(); + + std::vector<std::string> lines; + lines.push_back("TestLogger FATAL fatal level"); + lines.push_back("TestLogger ERROR error level"); + lines.push_back("TestLogger WARNING warning level"); + lines.push_back("TestLogger INFO info level"); + + std::ifstream infile("info_log.txt", std::ios::in); + size_t i = 0; + for (std::string line; std::getline(infile, line); ++i) { + BOOST_TEST(line == lines.at(i), detail::failure_msg(line, lines.at(i))); } - - /// @brief unit test for DEBUG debug level - /// - /// This test checks for the expected output when using the - /// Acts::Logging::DEBUG debug level as threshold. It also tests - /// - #ACTS_LOCAL_LOGGER - /// - Acts::getDefaultLogger - BOOST_AUTO_TEST_CASE(DEBUG_test) - { - std::ofstream logfile("debug_log.txt"); - - auto log = detail::create_logger("TestLogger", &logfile, DEBUG); - ACTS_LOCAL_LOGGER(log); - ACTS_FATAL("fatal level"); - ACTS_ERROR("error level"); - ACTS_WARNING("warning level"); - ACTS_INFO("info level"); - ACTS_DEBUG("debug level"); - ACTS_VERBOSE("verbose level"); - logfile.close(); - - std::vector<std::string> lines; - lines.push_back("TestLogger FATAL fatal level"); - lines.push_back("TestLogger ERROR error level"); - lines.push_back("TestLogger WARNING warning level"); - lines.push_back("TestLogger INFO info level"); - lines.push_back("TestLogger DEBUG debug level"); - - std::ifstream infile("debug_log.txt", std::ios::in); - size_t i = 0; - for (std::string line; std::getline(infile, line); ++i) { - BOOST_TEST(line == lines.at(i), detail::failure_msg(line, lines.at(i))); - } +} + +/// @brief unit test for DEBUG debug level +/// +/// This test checks for the expected output when using the +/// Acts::Logging::DEBUG debug level as threshold. It also tests +/// - #ACTS_LOCAL_LOGGER +/// - Acts::getDefaultLogger +BOOST_AUTO_TEST_CASE(DEBUG_test) { + std::ofstream logfile("debug_log.txt"); + + auto log = detail::create_logger("TestLogger", &logfile, DEBUG); + ACTS_LOCAL_LOGGER(log); + ACTS_FATAL("fatal level"); + ACTS_ERROR("error level"); + ACTS_WARNING("warning level"); + ACTS_INFO("info level"); + ACTS_DEBUG("debug level"); + ACTS_VERBOSE("verbose level"); + logfile.close(); + + std::vector<std::string> lines; + lines.push_back("TestLogger FATAL fatal level"); + lines.push_back("TestLogger ERROR error level"); + lines.push_back("TestLogger WARNING warning level"); + lines.push_back("TestLogger INFO info level"); + lines.push_back("TestLogger DEBUG debug level"); + + std::ifstream infile("debug_log.txt", std::ios::in); + size_t i = 0; + for (std::string line; std::getline(infile, line); ++i) { + BOOST_TEST(line == lines.at(i), detail::failure_msg(line, lines.at(i))); } - - /// @brief unit test for VERBOSE debug level - /// - /// This test checks for the expected output when using the - /// Acts::Logging::VERBOSE debug level as threshold. It also tests - /// - #ACTS_LOCAL_LOGGER - /// - Acts::getDefaultLogger - BOOST_AUTO_TEST_CASE(VERBOSE_test) - { - std::ofstream logfile("verbose_log.txt"); - - auto log = detail::create_logger("TestLogger", &logfile, VERBOSE); - ACTS_LOCAL_LOGGER(log); - ACTS_FATAL("fatal level"); - ACTS_ERROR("error level"); - ACTS_WARNING("warning level"); - ACTS_INFO("info level"); - ACTS_DEBUG("debug level"); - ACTS_VERBOSE("verbose level"); - logfile.close(); - - std::vector<std::string> lines; - lines.push_back("TestLogger FATAL fatal level"); - lines.push_back("TestLogger ERROR error level"); - lines.push_back("TestLogger WARNING warning level"); - lines.push_back("TestLogger INFO info level"); - lines.push_back("TestLogger DEBUG debug level"); - lines.push_back("TestLogger VERBOSE verbose level"); - - std::ifstream infile("verbose_log.txt", std::ios::in); - size_t i = 0; - for (std::string line; std::getline(infile, line); ++i) { - BOOST_TEST(line == lines.at(i), detail::failure_msg(line, lines.at(i))); - } +} + +/// @brief unit test for VERBOSE debug level +/// +/// This test checks for the expected output when using the +/// Acts::Logging::VERBOSE debug level as threshold. It also tests +/// - #ACTS_LOCAL_LOGGER +/// - Acts::getDefaultLogger +BOOST_AUTO_TEST_CASE(VERBOSE_test) { + std::ofstream logfile("verbose_log.txt"); + + auto log = detail::create_logger("TestLogger", &logfile, VERBOSE); + ACTS_LOCAL_LOGGER(log); + ACTS_FATAL("fatal level"); + ACTS_ERROR("error level"); + ACTS_WARNING("warning level"); + ACTS_INFO("info level"); + ACTS_DEBUG("debug level"); + ACTS_VERBOSE("verbose level"); + logfile.close(); + + std::vector<std::string> lines; + lines.push_back("TestLogger FATAL fatal level"); + lines.push_back("TestLogger ERROR error level"); + lines.push_back("TestLogger WARNING warning level"); + lines.push_back("TestLogger INFO info level"); + lines.push_back("TestLogger DEBUG debug level"); + lines.push_back("TestLogger VERBOSE verbose level"); + + std::ifstream infile("verbose_log.txt", std::ios::in); + size_t i = 0; + for (std::string line; std::getline(infile, line); ++i) { + BOOST_TEST(line == lines.at(i), detail::failure_msg(line, lines.at(i))); } +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/Utilities/MPLTests.cpp b/Tests/Core/Utilities/MPLTests.cpp index 765297ef37ebbbb0f2326096b1199f23b2235f9f..7351930665fa5f617881f98993f6ae69a936c440 100644 --- a/Tests/Core/Utilities/MPLTests.cpp +++ b/Tests/Core/Utilities/MPLTests.cpp @@ -35,284 +35,254 @@ namespace Acts { namespace Test { - BOOST_AUTO_TEST_CASE(all_of_test) - { - using detail::all_of_v; - - static_assert(not all_of_v<true, true, false>, - "all_of_v<true, true, false> failed"); - static_assert(not all_of_v<false, true, true, false>, - "all_of_v<false, true, true, false> failed"); - static_assert(all_of_v<true, true, true>, - "all_of_v<true, true, true> failed"); - static_assert(all_of_v<true>, "all_of_v<true> failed"); - static_assert(not all_of_v<false>, "all_of_v<false> failed"); - static_assert(all_of_v<>, "all_of_v<> failed"); - } - - BOOST_AUTO_TEST_CASE(hana_set_union_test) - { - // using first = typename bm::set<float, int, char, bool>::type; - constexpr auto first = hana::make_set(hana::type_c<float>, - hana::type_c<int>, - hana::type_c<char>, - hana::type_c<bool>); - // using second = typename bm::vector<long, int>::type; - constexpr auto second - = hana::make_set(hana::type_c<long>, hana::type_c<int>); - constexpr auto found = hana::union_(first, second); - // using found = typename detail::boost_set_merger_t<first, second>; - // using expected = typename bm::set<float, int, char, bool, long>::type; - constexpr auto expected = hana::make_set(hana::type_c<float>, - hana::type_c<int>, - hana::type_c<char>, - hana::type_c<bool>, - hana::type_c<long>); - - static_assert(found == expected, "union of hana::sets failed"); - } - - BOOST_AUTO_TEST_CASE(hana_set_to_tuple_test) - { - constexpr auto a_set = hana::make_set(hana::type_c<float>, - hana::type_c<int>, - hana::type_c<char>, - hana::type_c<bool>); - constexpr auto h_tuple = hana::make_tuple(hana::type_c<float>, - hana::type_c<int>, - hana::type_c<char>, - hana::type_c<bool>); - - static_assert(hana::to<hana::tuple_tag>(a_set) == h_tuple, "not equal"); - - // using std_tuple = decltype(hana::unpack(a_set, - // hana::template_<std::tuple>))::type; using expected = std::tuple<float, - // int, char>; static_assert(std::is_same<std_tuple, expected>::value, - // "using - // boost::mpl::set for variadic templates failed"); - } - - template <typename... args> - struct variadic_struct - { - using tuple = std::tuple<args...>; - }; - - BOOST_AUTO_TEST_CASE(unpack_boost_set_as_template_test) - { - constexpr auto hana_set = hana::make_set( - hana::type_c<float>, hana::type_c<int>, hana::type_c<char>); - using found = decltype( - hana::unpack(hana_set, hana::template_<variadic_struct>))::type; - - using expected = variadic_struct<float, int, char>; - - static_assert(std::is_same<found, expected>::value, - "using boost::mpl::set for variadic templates failed"); - - static_assert( - std::is_same<expected::tuple, std::tuple<float, int, char>>::value, - "not equal"); - } - - namespace { - struct traits1 - { - using result_type = int; - using action_type = char; - }; - - template <bool> - struct traits2; - - template <> - struct traits2<false> - { - using result_type = bool; - using action_type = float; - }; - - template <> - struct traits2<true> - { - using action_type = float; - }; - } // namespace - - template <typename... Args> - struct tuple_helper - { - using tuple = std::tuple<Args...>; - }; - - BOOST_AUTO_TEST_CASE(type_collector_test) - { - - // test some predicates - static_assert(detail::has_result_type_v<traits1>, - "Did not find result type"); - static_assert(detail::has_result_type_v<traits2<false>>, - "Did not find result type"); - static_assert(not detail::has_result_type_v<traits2<true>>, - "Did find result type"); - - static_assert(detail::has_action_type_v<traits1>, - "Did not find action type"); - static_assert(detail::has_action_type_v<traits2<false>>, - "Did not find action type"); - static_assert(detail::has_action_type_v<traits2<true>>, - "Did not find action type"); - - constexpr auto found_results - = detail::type_collector_t<detail::result_type_extractor, - traits1, - traits2<true>, - traits2<false>>; - constexpr auto expected_results - = hana::make_set(hana::type_c<int>, hana::type_c<bool>); - static_assert(found_results == expected_results, - "Didn't find expected results"); - - // check unpack - using found_results_tuple = decltype(hana::unpack( - found_results, hana::template_<tuple_helper>))::type::tuple; - using expected_results_tuple = std::tuple<int, bool>; - static_assert( - std::is_same<found_results_tuple, expected_results_tuple>::value, - "Unpacked results tuple not correct"); - - constexpr auto found_actions - = detail::type_collector_t<detail::action_type_extractor, - traits1, - traits2<true>, - traits2<false>>; - constexpr auto expected_actions - = hana::make_set(hana::type_c<char>, hana::type_c<float>); - static_assert(found_actions == expected_actions, - "Didn't find expected actions"); - - // check unpack - using found_actions_tuple = decltype(hana::unpack( - found_actions, hana::template_<tuple_helper>))::type::tuple; - using expected_actions_tuple = std::tuple<char, float>; - static_assert( - std::is_same<found_actions_tuple, expected_actions_tuple>::value, - "Unpacked actions tuple not correct"); - } - - BOOST_AUTO_TEST_CASE(has_duplicates_test) - { - using detail::has_duplicates_v; - static_assert(has_duplicates_v<int, float, char, int>, - "has_duplicates_v failed"); - static_assert(has_duplicates_v<int, int, char, float>, - "has_duplicates_v failed"); - static_assert(has_duplicates_v<int, char, float, float>, - "has_duplicates_v failed"); - static_assert(has_duplicates_v<int, char, char, float>, - "has_duplicates_v failed"); - static_assert(not has_duplicates_v<int, bool, char, float>, - "has_duplicates_v failed"); - } - - BOOST_AUTO_TEST_CASE(any_of_test) - { - using detail::any_of_v; - - static_assert(any_of_v<true, true, false>, - "any_of_v<true, true, false> failed"); - static_assert(any_of_v<false, true, true, false>, - "any_of_v<false, true, true, false> failed"); - static_assert(any_of_v<true, true, true>, - "any_of_v<true, true, true> failed"); - static_assert(not any_of_v<false, false>, "any_of_v<false, false> failed"); - static_assert(any_of_v<true>, "any_of_v<true> failed"); - static_assert(not any_of_v<false>, "any_of_v<false> failed"); - static_assert(not any_of_v<>, "any_of_v<> failed"); - } - - /** - * @brief Unit test for Acts::anonymous_namespace{ParameterSet.h}::are_sorted - * helper - * - * The test checks for correct behavior in the following cases (always using - * @c int - * as value type): - * -# test: ordered strictly ascending, input: ordered strictly ascending - * -# test: ordered strictly ascending, input: unordered - * -# test: ordered strictly ascending, input: ordered weakly ascending - * -# test: ordered weakly ascending, input: ordered strictly ascending - * -# test: ordered weakly ascending, input: unordered - * -# test: ordered weakly ascending, input: ordered weakly ascending - * -# test: ordered strictly descending, input: ordered strictly descending - * -# test: ordered strictly descending, input: unordered - * -# test: ordered strictly descending, input: ordered weakly descending - * -# test: ordered weakly descending, input: ordered strictly descending - * -# test: ordered weakly descending, input: unordered - * -# test: ordered weakly descending, input: ordered weakly descending - */ - BOOST_AUTO_TEST_CASE(are_sorted_helper_tests) - { - using detail::are_sorted; - // strictly ascending - BOOST_CHECK((are_sorted<true, true, int, -1, 3, 4, 12>::value)); - BOOST_CHECK((not are_sorted<true, true, int, -1, 13, 4>::value)); - BOOST_CHECK((not are_sorted<true, true, int, -1, 4, 4, 7>::value)); - // weakly ascending - BOOST_CHECK((are_sorted<true, false, int, -1, 3, 4, 12>::value)); - BOOST_CHECK((not are_sorted<true, false, int, -1, 13, 4>::value)); - BOOST_CHECK((are_sorted<true, false, int, -1, 4, 4, 7>::value)); - // strictly descending - BOOST_CHECK((are_sorted<false, true, int, 1, -3, -4, -12>::value)); - BOOST_CHECK((not are_sorted<false, true, int, 1, -13, -4>::value)); - BOOST_CHECK((not are_sorted<false, true, int, 1, -4, -4>::value)); - // weakly descending - BOOST_CHECK((are_sorted<false, false, int, 1, -3, -4, -12>::value)); - BOOST_CHECK((not are_sorted<false, false, int, -1, -13, -4>::value)); - BOOST_CHECK((are_sorted<false, false, int, -1, -4, -4, -7>::value)); - } - - /** - * @brief Unit test for Acts::anonymous_namespace{ParameterSet.h}::are_within - * helper - * - * The test checks for correct behavior in the following cases (always using - * @c int - * as value type): - * -# all values within (MIN,MAX) - * -# all values within [MIN,MAX) - * -# one value < MIN - * -# multiple values < MIN - * -# one value > MAX - * -# multiple values > Max - * -# one value == MAX - * -# contains values < MIN and >= MAX - */ - BOOST_AUTO_TEST_CASE(are_within_helper_tests) - { - using detail::are_within; - BOOST_CHECK((are_within<int, 0, 10, 1, 3, 7, 2>::value)); - BOOST_CHECK((are_within<int, 0, 10, 1, 3, 0, 2>::value)); - BOOST_CHECK((not are_within<int, 0, 10, -1, 3, 7, 2>::value)); - BOOST_CHECK((not are_within<int, 0, 10, -1, 3, 7, -2>::value)); - BOOST_CHECK((not are_within<int, 0, 10, 1, 3, 17, 2>::value)); - BOOST_CHECK((not are_within<int, 0, 10, 1, 3, 17, 12>::value)); - BOOST_CHECK((not are_within<int, 0, 10, 1, 10>::value)); - BOOST_CHECK((not are_within<int, 0, 10, 1, -2, 10, 14>::value)); - } - - /** - * @brief Unit test for Acts::details::at_index helper - */ - BOOST_AUTO_TEST_CASE(at_index_helper_tests) - { - using detail::at_index; - BOOST_CHECK((at_index<int, 0, 10, 1, 3, 7, 2>::value == 10)); - BOOST_CHECK((at_index<int, 1, 10, 1, 3, 7, 2>::value == 1)); - BOOST_CHECK((at_index<int, 2, 10, 1, 3, 7, 2>::value == 3)); - BOOST_CHECK((at_index<int, 3, 10, 1, 3, 7, 2>::value == 7)); - BOOST_CHECK((at_index<int, 4, 10, 1, 3, 7, 2>::value == 2)); - } +BOOST_AUTO_TEST_CASE(all_of_test) { + using detail::all_of_v; + + static_assert(not all_of_v<true, true, false>, + "all_of_v<true, true, false> failed"); + static_assert(not all_of_v<false, true, true, false>, + "all_of_v<false, true, true, false> failed"); + static_assert(all_of_v<true, true, true>, + "all_of_v<true, true, true> failed"); + static_assert(all_of_v<true>, "all_of_v<true> failed"); + static_assert(not all_of_v<false>, "all_of_v<false> failed"); + static_assert(all_of_v<>, "all_of_v<> failed"); +} + +BOOST_AUTO_TEST_CASE(hana_set_union_test) { + // using first = typename bm::set<float, int, char, bool>::type; + constexpr auto first = hana::make_set(hana::type_c<float>, hana::type_c<int>, + hana::type_c<char>, hana::type_c<bool>); + // using second = typename bm::vector<long, int>::type; + constexpr auto second = hana::make_set(hana::type_c<long>, hana::type_c<int>); + constexpr auto found = hana::union_(first, second); + // using found = typename detail::boost_set_merger_t<first, second>; + // using expected = typename bm::set<float, int, char, bool, long>::type; + constexpr auto expected = + hana::make_set(hana::type_c<float>, hana::type_c<int>, hana::type_c<char>, + hana::type_c<bool>, hana::type_c<long>); + + static_assert(found == expected, "union of hana::sets failed"); +} + +BOOST_AUTO_TEST_CASE(hana_set_to_tuple_test) { + constexpr auto a_set = hana::make_set(hana::type_c<float>, hana::type_c<int>, + hana::type_c<char>, hana::type_c<bool>); + constexpr auto h_tuple = + hana::make_tuple(hana::type_c<float>, hana::type_c<int>, + hana::type_c<char>, hana::type_c<bool>); + + static_assert(hana::to<hana::tuple_tag>(a_set) == h_tuple, "not equal"); + + // using std_tuple = decltype(hana::unpack(a_set, + // hana::template_<std::tuple>))::type; using expected = std::tuple<float, + // int, char>; static_assert(std::is_same<std_tuple, expected>::value, + // "using + // boost::mpl::set for variadic templates failed"); +} + +template <typename... args> +struct variadic_struct { + using tuple = std::tuple<args...>; +}; + +BOOST_AUTO_TEST_CASE(unpack_boost_set_as_template_test) { + constexpr auto hana_set = hana::make_set( + hana::type_c<float>, hana::type_c<int>, hana::type_c<char>); + using found = + decltype(hana::unpack(hana_set, hana::template_<variadic_struct>))::type; + + using expected = variadic_struct<float, int, char>; + + static_assert(std::is_same<found, expected>::value, + "using boost::mpl::set for variadic templates failed"); + + static_assert( + std::is_same<expected::tuple, std::tuple<float, int, char>>::value, + "not equal"); +} + +namespace { +struct traits1 { + using result_type = int; + using action_type = char; +}; + +template <bool> +struct traits2; + +template <> +struct traits2<false> { + using result_type = bool; + using action_type = float; +}; + +template <> +struct traits2<true> { + using action_type = float; +}; +} // namespace + +template <typename... Args> +struct tuple_helper { + using tuple = std::tuple<Args...>; +}; + +BOOST_AUTO_TEST_CASE(type_collector_test) { + // test some predicates + static_assert(detail::has_result_type_v<traits1>, "Did not find result type"); + static_assert(detail::has_result_type_v<traits2<false>>, + "Did not find result type"); + static_assert(not detail::has_result_type_v<traits2<true>>, + "Did find result type"); + + static_assert(detail::has_action_type_v<traits1>, "Did not find action type"); + static_assert(detail::has_action_type_v<traits2<false>>, + "Did not find action type"); + static_assert(detail::has_action_type_v<traits2<true>>, + "Did not find action type"); + + constexpr auto found_results = + detail::type_collector_t<detail::result_type_extractor, traits1, + traits2<true>, traits2<false>>; + constexpr auto expected_results = + hana::make_set(hana::type_c<int>, hana::type_c<bool>); + static_assert(found_results == expected_results, + "Didn't find expected results"); + + // check unpack + using found_results_tuple = decltype( + hana::unpack(found_results, hana::template_<tuple_helper>))::type::tuple; + using expected_results_tuple = std::tuple<int, bool>; + static_assert( + std::is_same<found_results_tuple, expected_results_tuple>::value, + "Unpacked results tuple not correct"); + + constexpr auto found_actions = + detail::type_collector_t<detail::action_type_extractor, traits1, + traits2<true>, traits2<false>>; + constexpr auto expected_actions = + hana::make_set(hana::type_c<char>, hana::type_c<float>); + static_assert(found_actions == expected_actions, + "Didn't find expected actions"); + + // check unpack + using found_actions_tuple = decltype( + hana::unpack(found_actions, hana::template_<tuple_helper>))::type::tuple; + using expected_actions_tuple = std::tuple<char, float>; + static_assert( + std::is_same<found_actions_tuple, expected_actions_tuple>::value, + "Unpacked actions tuple not correct"); +} + +BOOST_AUTO_TEST_CASE(has_duplicates_test) { + using detail::has_duplicates_v; + static_assert(has_duplicates_v<int, float, char, int>, + "has_duplicates_v failed"); + static_assert(has_duplicates_v<int, int, char, float>, + "has_duplicates_v failed"); + static_assert(has_duplicates_v<int, char, float, float>, + "has_duplicates_v failed"); + static_assert(has_duplicates_v<int, char, char, float>, + "has_duplicates_v failed"); + static_assert(not has_duplicates_v<int, bool, char, float>, + "has_duplicates_v failed"); +} + +BOOST_AUTO_TEST_CASE(any_of_test) { + using detail::any_of_v; + + static_assert(any_of_v<true, true, false>, + "any_of_v<true, true, false> failed"); + static_assert(any_of_v<false, true, true, false>, + "any_of_v<false, true, true, false> failed"); + static_assert(any_of_v<true, true, true>, + "any_of_v<true, true, true> failed"); + static_assert(not any_of_v<false, false>, "any_of_v<false, false> failed"); + static_assert(any_of_v<true>, "any_of_v<true> failed"); + static_assert(not any_of_v<false>, "any_of_v<false> failed"); + static_assert(not any_of_v<>, "any_of_v<> failed"); +} + +/** + * @brief Unit test for Acts::anonymous_namespace{ParameterSet.h}::are_sorted + * helper + * + * The test checks for correct behavior in the following cases (always using + * @c int + * as value type): + * -# test: ordered strictly ascending, input: ordered strictly ascending + * -# test: ordered strictly ascending, input: unordered + * -# test: ordered strictly ascending, input: ordered weakly ascending + * -# test: ordered weakly ascending, input: ordered strictly ascending + * -# test: ordered weakly ascending, input: unordered + * -# test: ordered weakly ascending, input: ordered weakly ascending + * -# test: ordered strictly descending, input: ordered strictly descending + * -# test: ordered strictly descending, input: unordered + * -# test: ordered strictly descending, input: ordered weakly descending + * -# test: ordered weakly descending, input: ordered strictly descending + * -# test: ordered weakly descending, input: unordered + * -# test: ordered weakly descending, input: ordered weakly descending + */ +BOOST_AUTO_TEST_CASE(are_sorted_helper_tests) { + using detail::are_sorted; + // strictly ascending + BOOST_CHECK((are_sorted<true, true, int, -1, 3, 4, 12>::value)); + BOOST_CHECK((not are_sorted<true, true, int, -1, 13, 4>::value)); + BOOST_CHECK((not are_sorted<true, true, int, -1, 4, 4, 7>::value)); + // weakly ascending + BOOST_CHECK((are_sorted<true, false, int, -1, 3, 4, 12>::value)); + BOOST_CHECK((not are_sorted<true, false, int, -1, 13, 4>::value)); + BOOST_CHECK((are_sorted<true, false, int, -1, 4, 4, 7>::value)); + // strictly descending + BOOST_CHECK((are_sorted<false, true, int, 1, -3, -4, -12>::value)); + BOOST_CHECK((not are_sorted<false, true, int, 1, -13, -4>::value)); + BOOST_CHECK((not are_sorted<false, true, int, 1, -4, -4>::value)); + // weakly descending + BOOST_CHECK((are_sorted<false, false, int, 1, -3, -4, -12>::value)); + BOOST_CHECK((not are_sorted<false, false, int, -1, -13, -4>::value)); + BOOST_CHECK((are_sorted<false, false, int, -1, -4, -4, -7>::value)); +} + +/** + * @brief Unit test for Acts::anonymous_namespace{ParameterSet.h}::are_within + * helper + * + * The test checks for correct behavior in the following cases (always using + * @c int + * as value type): + * -# all values within (MIN,MAX) + * -# all values within [MIN,MAX) + * -# one value < MIN + * -# multiple values < MIN + * -# one value > MAX + * -# multiple values > Max + * -# one value == MAX + * -# contains values < MIN and >= MAX + */ +BOOST_AUTO_TEST_CASE(are_within_helper_tests) { + using detail::are_within; + BOOST_CHECK((are_within<int, 0, 10, 1, 3, 7, 2>::value)); + BOOST_CHECK((are_within<int, 0, 10, 1, 3, 0, 2>::value)); + BOOST_CHECK((not are_within<int, 0, 10, -1, 3, 7, 2>::value)); + BOOST_CHECK((not are_within<int, 0, 10, -1, 3, 7, -2>::value)); + BOOST_CHECK((not are_within<int, 0, 10, 1, 3, 17, 2>::value)); + BOOST_CHECK((not are_within<int, 0, 10, 1, 3, 17, 12>::value)); + BOOST_CHECK((not are_within<int, 0, 10, 1, 10>::value)); + BOOST_CHECK((not are_within<int, 0, 10, 1, -2, 10, 14>::value)); +} + +/** + * @brief Unit test for Acts::details::at_index helper + */ +BOOST_AUTO_TEST_CASE(at_index_helper_tests) { + using detail::at_index; + BOOST_CHECK((at_index<int, 0, 10, 1, 3, 7, 2>::value == 10)); + BOOST_CHECK((at_index<int, 1, 10, 1, 3, 7, 2>::value == 1)); + BOOST_CHECK((at_index<int, 2, 10, 1, 3, 7, 2>::value == 3)); + BOOST_CHECK((at_index<int, 3, 10, 1, 3, 7, 2>::value == 7)); + BOOST_CHECK((at_index<int, 4, 10, 1, 3, 7, 2>::value == 2)); +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/Utilities/MaterialMapUtilsTests.cpp b/Tests/Core/Utilities/MaterialMapUtilsTests.cpp index 490ef45981ca21d1890e311f3a9c6a1b87b9d30d..f673ab9aedff62ea57c6409439760806d4c3635d 100644 --- a/Tests/Core/Utilities/MaterialMapUtilsTests.cpp +++ b/Tests/Core/Utilities/MaterialMapUtilsTests.cpp @@ -38,120 +38,112 @@ using Acts::VectorHelpers::perp; namespace Acts { namespace Test { - BOOST_AUTO_TEST_CASE(materialmap_creation) - { - // Create grid values - std::vector<double> rPos = {0., 1., 2.}; - std::vector<double> xPos = {0., 1., 2.}; - std::vector<double> yPos = {0., 1., 2.}; - std::vector<double> zPos = {0., 1., 2.}; +BOOST_AUTO_TEST_CASE(materialmap_creation) { + // Create grid values + std::vector<double> rPos = {0., 1., 2.}; + std::vector<double> xPos = {0., 1., 2.}; + std::vector<double> yPos = {0., 1., 2.}; + std::vector<double> zPos = {0., 1., 2.}; - // Create material association in rz - std::vector<Material> material_rz; - for (int i = 0; i < 9; i++) { - material_rz.push_back(Material(i, i, i, i, i)); - } + // Create material association in rz + std::vector<Material> material_rz; + for (int i = 0; i < 9; i++) { + material_rz.push_back(Material(i, i, i, i, i)); + } - auto localToGlobalBin_rz - = [](std::array<size_t, 2> binsRZ, std::array<size_t, 2> nBinsRZ) { - return (binsRZ.at(1) * nBinsRZ.at(0) + binsRZ.at(0)); - }; - // Create material mapper in rz - auto mapper_rz - = materialMapperRZ(localToGlobalBin_rz, rPos, zPos, material_rz); - // check number of bins, minima & maxima - std::vector<size_t> nBins_rz = {rPos.size(), zPos.size()}; - std::vector<double> minima_rz = {0., 0.}; - std::vector<double> maxima_rz = {3., 3.}; - BOOST_CHECK(mapper_rz.getNBins() == nBins_rz); - // Check minimum (should be first value because bin values are always - // assigned to the left boundary) - BOOST_CHECK(mapper_rz.getMin() == minima_rz); - // Check maximum (should be last value + 1 step because bin values are - // always assigned to the left boundary) - BOOST_CHECK(mapper_rz.getMax() == maxima_rz); + auto localToGlobalBin_rz = [](std::array<size_t, 2> binsRZ, + std::array<size_t, 2> nBinsRZ) { + return (binsRZ.at(1) * nBinsRZ.at(0) + binsRZ.at(0)); + }; + // Create material mapper in rz + auto mapper_rz = + materialMapperRZ(localToGlobalBin_rz, rPos, zPos, material_rz); + // check number of bins, minima & maxima + std::vector<size_t> nBins_rz = {rPos.size(), zPos.size()}; + std::vector<double> minima_rz = {0., 0.}; + std::vector<double> maxima_rz = {3., 3.}; + BOOST_CHECK(mapper_rz.getNBins() == nBins_rz); + // Check minimum (should be first value because bin values are always + // assigned to the left boundary) + BOOST_CHECK(mapper_rz.getMin() == minima_rz); + // Check maximum (should be last value + 1 step because bin values are + // always assigned to the left boundary) + BOOST_CHECK(mapper_rz.getMax() == maxima_rz); - // Create map in xyz - std::vector<Material> material_xyz; - for (int i = 0; i < 27; i++) { - material_xyz.push_back(Material(i, i, i, i, i)); - } + // Create map in xyz + std::vector<Material> material_xyz; + for (int i = 0; i < 27; i++) { + material_xyz.push_back(Material(i, i, i, i, i)); + } - auto localToGlobalBin_xyz - = [](std::array<size_t, 3> binsXYZ, std::array<size_t, 3> nBinsXYZ) { - return (binsXYZ.at(0) * (nBinsXYZ.at(1) * nBinsXYZ.at(2)) - + binsXYZ.at(1) * nBinsXYZ.at(2) - + binsXYZ.at(2)); - }; + auto localToGlobalBin_xyz = [](std::array<size_t, 3> binsXYZ, + std::array<size_t, 3> nBinsXYZ) { + return (binsXYZ.at(0) * (nBinsXYZ.at(1) * nBinsXYZ.at(2)) + + binsXYZ.at(1) * nBinsXYZ.at(2) + binsXYZ.at(2)); + }; - // Create material mapper in xyz - auto mapper_xyz = materialMapperXYZ( - localToGlobalBin_xyz, xPos, yPos, zPos, material_xyz); - // Check number of bins, minima & maxima - std::vector<size_t> nBins_xyz = {xPos.size(), yPos.size(), zPos.size()}; - std::vector<double> minima_xyz = {0., 0., 0.}; - std::vector<double> maxima_xyz = {3., 3., 3.}; - BOOST_CHECK(mapper_xyz.getNBins() == nBins_xyz); - // Check minimum (should be first value because bin values are always - // assigned to the left boundary) - BOOST_CHECK(mapper_xyz.getMin() == minima_xyz); - // Check maximum (should be last value + 1 step because bin values are - // always assigned to the left boundary) - BOOST_CHECK(mapper_xyz.getMax() == maxima_xyz); + // Create material mapper in xyz + auto mapper_xyz = + materialMapperXYZ(localToGlobalBin_xyz, xPos, yPos, zPos, material_xyz); + // Check number of bins, minima & maxima + std::vector<size_t> nBins_xyz = {xPos.size(), yPos.size(), zPos.size()}; + std::vector<double> minima_xyz = {0., 0., 0.}; + std::vector<double> maxima_xyz = {3., 3., 3.}; + BOOST_CHECK(mapper_xyz.getNBins() == nBins_xyz); + // Check minimum (should be first value because bin values are always + // assigned to the left boundary) + BOOST_CHECK(mapper_xyz.getMin() == minima_xyz); + // Check maximum (should be last value + 1 step because bin values are + // always assigned to the left boundary) + BOOST_CHECK(mapper_xyz.getMax() == maxima_xyz); - // Check if filled value is expected value in rz - Vector3D pos0_rz(0., 0., 0.); - Vector3D pos1_rz(1., 0., 1.); - Vector3D pos2_rz(0., 2., 2.); - auto value0_rz = mapper_rz.getMaterial(pos0_rz); - auto value1_rz = mapper_rz.getMaterial(pos1_rz); - auto value2_rz = mapper_rz.getMaterial(pos2_rz); - // Calculate what the value should be at this point - Material mat0_rz = material_rz.at( - localToGlobalBin_rz({{0, 0}}, {{rPos.size(), zPos.size()}})); - Material mat1_rz = material_rz.at( - localToGlobalBin_rz({{1, 1}}, {{rPos.size(), zPos.size()}})); - Material mat2_rz = material_rz.at( - localToGlobalBin_rz({{2, 2}}, {{rPos.size(), zPos.size()}})); + // Check if filled value is expected value in rz + Vector3D pos0_rz(0., 0., 0.); + Vector3D pos1_rz(1., 0., 1.); + Vector3D pos2_rz(0., 2., 2.); + auto value0_rz = mapper_rz.getMaterial(pos0_rz); + auto value1_rz = mapper_rz.getMaterial(pos1_rz); + auto value2_rz = mapper_rz.getMaterial(pos2_rz); + // Calculate what the value should be at this point + Material mat0_rz = material_rz.at( + localToGlobalBin_rz({{0, 0}}, {{rPos.size(), zPos.size()}})); + Material mat1_rz = material_rz.at( + localToGlobalBin_rz({{1, 1}}, {{rPos.size(), zPos.size()}})); + Material mat2_rz = material_rz.at( + localToGlobalBin_rz({{2, 2}}, {{rPos.size(), zPos.size()}})); - // Check the value - // in rz case material is phi symmetric (check radius) - CHECK_CLOSE_ABS(value0_rz.classificationNumbers(), - mat0_rz.classificationNumbers(), - 1e-9); - CHECK_CLOSE_ABS(value1_rz.classificationNumbers(), - mat1_rz.classificationNumbers(), - 1e-9); - CHECK_CLOSE_ABS(value2_rz.classificationNumbers(), - mat2_rz.classificationNumbers(), - 1e-9); + // Check the value + // in rz case material is phi symmetric (check radius) + CHECK_CLOSE_ABS(value0_rz.classificationNumbers(), + mat0_rz.classificationNumbers(), 1e-9); + CHECK_CLOSE_ABS(value1_rz.classificationNumbers(), + mat1_rz.classificationNumbers(), 1e-9); + CHECK_CLOSE_ABS(value2_rz.classificationNumbers(), + mat2_rz.classificationNumbers(), 1e-9); - // Check if filled value is expected value in xyz - Vector3D pos0_xyz(0., 0., 0.); - Vector3D pos1_xyz(1., 1., 1.); - Vector3D pos2_xyz(2., 2., 2.); - auto value0_xyz = mapper_xyz.getMaterial(pos0_xyz); - auto value1_xyz = mapper_xyz.getMaterial(pos1_xyz); - auto value2_xyz = mapper_xyz.getMaterial(pos2_xyz); - // Calculate what the value should be at this point - Material mat0_xyz = material_xyz.at(localToGlobalBin_xyz( - {{0, 0, 0}}, {{xPos.size(), yPos.size(), zPos.size()}})); - Material mat1_xyz = material_xyz.at(localToGlobalBin_xyz( - {{1, 1, 1}}, {{xPos.size(), yPos.size(), zPos.size()}})); - Material mat2_xyz = material_xyz.at(localToGlobalBin_xyz( - {{2, 2, 2}}, {{xPos.size(), yPos.size(), zPos.size()}})); + // Check if filled value is expected value in xyz + Vector3D pos0_xyz(0., 0., 0.); + Vector3D pos1_xyz(1., 1., 1.); + Vector3D pos2_xyz(2., 2., 2.); + auto value0_xyz = mapper_xyz.getMaterial(pos0_xyz); + auto value1_xyz = mapper_xyz.getMaterial(pos1_xyz); + auto value2_xyz = mapper_xyz.getMaterial(pos2_xyz); + // Calculate what the value should be at this point + Material mat0_xyz = material_xyz.at(localToGlobalBin_xyz( + {{0, 0, 0}}, {{xPos.size(), yPos.size(), zPos.size()}})); + Material mat1_xyz = material_xyz.at(localToGlobalBin_xyz( + {{1, 1, 1}}, {{xPos.size(), yPos.size(), zPos.size()}})); + Material mat2_xyz = material_xyz.at(localToGlobalBin_xyz( + {{2, 2, 2}}, {{xPos.size(), yPos.size(), zPos.size()}})); - // Check the value - // in xyz case material is phi symmetric (check radius) - CHECK_CLOSE_ABS(value0_xyz.classificationNumbers(), - mat0_xyz.classificationNumbers(), - 1e-9); - CHECK_CLOSE_ABS(value1_xyz.classificationNumbers(), - mat1_xyz.classificationNumbers(), - 1e-9); - CHECK_CLOSE_ABS(value2_xyz.classificationNumbers(), - mat2_xyz.classificationNumbers(), - 1e-9); - } + // Check the value + // in xyz case material is phi symmetric (check radius) + CHECK_CLOSE_ABS(value0_xyz.classificationNumbers(), + mat0_xyz.classificationNumbers(), 1e-9); + CHECK_CLOSE_ABS(value1_xyz.classificationNumbers(), + mat1_xyz.classificationNumbers(), 1e-9); + CHECK_CLOSE_ABS(value2_xyz.classificationNumbers(), + mat2_xyz.classificationNumbers(), 1e-9); +} } // namespace Test } // namespace Acts \ No newline at end of file diff --git a/Tests/Core/Utilities/RealQuadraticEquationTests.cpp b/Tests/Core/Utilities/RealQuadraticEquationTests.cpp index 63c900b3352ae19e5854232923a777b1a18a5b98..8570ce5592aafcce3f3701c928465b22608c8236 100644 --- a/Tests/Core/Utilities/RealQuadraticEquationTests.cpp +++ b/Tests/Core/Utilities/RealQuadraticEquationTests.cpp @@ -28,53 +28,50 @@ namespace utf = boost::unit_test; namespace Acts { namespace Test { - BOOST_AUTO_TEST_SUITE(Surfaces) - /// Unit test for creating RealQuadraticEquation object - BOOST_AUTO_TEST_CASE(RealQuadraticEquationConstruction) - { - double a(1.0), b(-3.), c(2.); - // test default construction: not deleted, not written - // RealQuadraticEquation defaultConstructedRealQuadraticEquation; - // - /// Test construction with parameters - BOOST_REQUIRE_NO_THROW(RealQuadraticEquation(a, b, c)); - // - /// Copy constructor (implicit), void removes 'unused' compiler warning - RealQuadraticEquation orig(a, b, c); - BOOST_REQUIRE_NO_THROW(RealQuadraticEquation copied(orig); (void)copied); - } - /// Unit test for RealQuadraticEquation properties - BOOST_AUTO_TEST_CASE(RealQuadraticEquationProperties) - { - double a(1.0), b(-3.), c(2.); - // - /// Test construction with parameters - RealQuadraticEquation equation(a, b, c); - // - /// Test for solutions - CHECK_CLOSE_REL(equation.first, 2., 1e-6); - CHECK_CLOSE_REL(equation.second, 1., 1e-6); - BOOST_CHECK_EQUAL(equation.solutions, 2); - } +BOOST_AUTO_TEST_SUITE(Surfaces) +/// Unit test for creating RealQuadraticEquation object +BOOST_AUTO_TEST_CASE(RealQuadraticEquationConstruction) { + double a(1.0), b(-3.), c(2.); + // test default construction: not deleted, not written + // RealQuadraticEquation defaultConstructedRealQuadraticEquation; + // + /// Test construction with parameters + BOOST_REQUIRE_NO_THROW(RealQuadraticEquation(a, b, c)); + // + /// Copy constructor (implicit), void removes 'unused' compiler warning + RealQuadraticEquation orig(a, b, c); + BOOST_REQUIRE_NO_THROW(RealQuadraticEquation copied(orig); (void)copied); +} +/// Unit test for RealQuadraticEquation properties +BOOST_AUTO_TEST_CASE(RealQuadraticEquationProperties) { + double a(1.0), b(-3.), c(2.); + // + /// Test construction with parameters + RealQuadraticEquation equation(a, b, c); + // + /// Test for solutions + CHECK_CLOSE_REL(equation.first, 2., 1e-6); + CHECK_CLOSE_REL(equation.second, 1., 1e-6); + BOOST_CHECK_EQUAL(equation.solutions, 2); +} - /// Unit test for testing RealQuadraticEquation assignment - BOOST_AUTO_TEST_CASE(RealQuadraticEquationAssignment) - { - double a(1.0), b(-3.), c(2.); - RealQuadraticEquation realQuadraticEquationObject(a, b, c); - // operator == not implemented in this class - // - /// Test assignment (implicit) - RealQuadraticEquation assignedRealQuadraticEquationObject(9., -3.5, 6.7); - assignedRealQuadraticEquationObject = realQuadraticEquationObject; - CHECK_CLOSE_REL(assignedRealQuadraticEquationObject.first, 2., 1e-6); - CHECK_CLOSE_REL(assignedRealQuadraticEquationObject.second, 1., 1e-6); - BOOST_CHECK_EQUAL(assignedRealQuadraticEquationObject.solutions, 2); - /// equality not written and not implicit - // BOOST_CHECK_EQUAL(assignedRealQuadraticEquationObject, - // realQuadraticEquationObject); - } - BOOST_AUTO_TEST_SUITE_END() +/// Unit test for testing RealQuadraticEquation assignment +BOOST_AUTO_TEST_CASE(RealQuadraticEquationAssignment) { + double a(1.0), b(-3.), c(2.); + RealQuadraticEquation realQuadraticEquationObject(a, b, c); + // operator == not implemented in this class + // + /// Test assignment (implicit) + RealQuadraticEquation assignedRealQuadraticEquationObject(9., -3.5, 6.7); + assignedRealQuadraticEquationObject = realQuadraticEquationObject; + CHECK_CLOSE_REL(assignedRealQuadraticEquationObject.first, 2., 1e-6); + CHECK_CLOSE_REL(assignedRealQuadraticEquationObject.second, 1., 1e-6); + BOOST_CHECK_EQUAL(assignedRealQuadraticEquationObject.solutions, 2); + /// equality not written and not implicit + // BOOST_CHECK_EQUAL(assignedRealQuadraticEquationObject, + // realQuadraticEquationObject); +} +BOOST_AUTO_TEST_SUITE_END() } // namespace Test diff --git a/Tests/Core/Utilities/ResultTests.cpp b/Tests/Core/Utilities/ResultTests.cpp index 61f777bf1ad1fc7c1019051338ab14ebdfe44d57..d0dbad3bd70738f79d93861e249adf545e2f21b9 100644 --- a/Tests/Core/Utilities/ResultTests.cpp +++ b/Tests/Core/Utilities/ResultTests.cpp @@ -23,268 +23,248 @@ using namespace std::string_literals; namespace { enum class MyError { Failure = 1, SomethingElse = 2 }; -std::error_code -make_error_code(MyError e) -{ +std::error_code make_error_code(MyError e) { return {static_cast<int>(e), std::generic_category()}; } -} +} // namespace namespace std { // register with STL template <> -struct is_error_code_enum<MyError> : std::true_type -{ -}; -} +struct is_error_code_enum<MyError> : std::true_type {}; +} // namespace std namespace Acts { namespace Test { - BOOST_AUTO_TEST_SUITE(Utilities) +BOOST_AUTO_TEST_SUITE(Utilities) - BOOST_AUTO_TEST_CASE(TestConstruction) +BOOST_AUTO_TEST_CASE(TestConstruction) { { + using Result = Result<int, char>; - { - using Result = Result<int, char>; - - Result res = Result::success(42); - BOOST_CHECK_EQUAL(*res, 42); - BOOST_CHECK_EQUAL(res.value(), 42); - BOOST_CHECK(res.ok()); - res = Result::success('e'); - BOOST_CHECK_EQUAL(*res, 'e'); - BOOST_CHECK_EQUAL(res.value(), 'e'); - BOOST_CHECK(res.ok()); - res = Result::failure(42); - BOOST_CHECK(!res.ok()); - BOOST_CHECK_EQUAL(res.error(), 42); - BOOST_CHECK_THROW(res.value(), std::runtime_error); - res = Result::failure('e'); - BOOST_CHECK(!res.ok()); - BOOST_CHECK_EQUAL(res.error(), 'e'); - BOOST_CHECK_THROW(res.value(), std::runtime_error); - } - - { - using Result = Result<double, std::string>; - - Result res1("hallo"); - BOOST_CHECK(!res1.ok()); - BOOST_CHECK_EQUAL(res1.error(), "hallo"); - BOOST_CHECK_THROW(res1.value(), std::runtime_error); - res1 = Result::failure("hallo"); - BOOST_CHECK(!res1.ok()); - BOOST_CHECK_EQUAL(res1.error(), "hallo"); - BOOST_CHECK_THROW(res1.value(), std::runtime_error); - - Result res2(4.5); - BOOST_CHECK(res2.ok()); - BOOST_CHECK(*res2 == 4.5); - BOOST_CHECK(res2.value() == 4.5); - res2 = Result::success(4.5); - BOOST_CHECK(res2.ok()); - BOOST_CHECK_EQUAL(*res2, 4.5); - BOOST_CHECK_EQUAL(res2.value(), 4.5); - } + Result res = Result::success(42); + BOOST_CHECK_EQUAL(*res, 42); + BOOST_CHECK_EQUAL(res.value(), 42); + BOOST_CHECK(res.ok()); + res = Result::success('e'); + BOOST_CHECK_EQUAL(*res, 'e'); + BOOST_CHECK_EQUAL(res.value(), 'e'); + BOOST_CHECK(res.ok()); + res = Result::failure(42); + BOOST_CHECK(!res.ok()); + BOOST_CHECK_EQUAL(res.error(), 42); + BOOST_CHECK_THROW(res.value(), std::runtime_error); + res = Result::failure('e'); + BOOST_CHECK(!res.ok()); + BOOST_CHECK_EQUAL(res.error(), 'e'); + BOOST_CHECK_THROW(res.value(), std::runtime_error); } - BOOST_AUTO_TEST_CASE(TestErrorCodes) { - auto err1 = MyError::Failure; - - std::error_code ec = err1; - - { - using Result = Result<double, MyError>; - - Result res(42); - BOOST_CHECK(res.ok()); - BOOST_CHECK_EQUAL(*res, 42.); - - Result res2(err1); - BOOST_CHECK(!res2.ok()); - BOOST_CHECK_EQUAL(res2.error(), err1); - BOOST_CHECK_THROW(res2.value(), std::runtime_error); - } - - { - using Result = Result<double, std::error_code>; - - Result res(42); - BOOST_CHECK(res.ok()); - BOOST_CHECK_EQUAL(*res, 42.); - BOOST_CHECK_EQUAL(res.value(), 42); - res = 46; - BOOST_CHECK(res.ok()); - BOOST_CHECK_EQUAL(*res, 46.); - BOOST_CHECK_EQUAL(res.value(), 46); - - Result res2(ec); - BOOST_CHECK(!res2.ok()); - BOOST_CHECK_EQUAL(res2.error(), ec); - BOOST_CHECK_EQUAL(res2.error(), err1); - - res2 = MyError::SomethingElse; - BOOST_CHECK(!res2.ok()); - BOOST_CHECK_EQUAL(res2.error(), MyError::SomethingElse); - BOOST_CHECK(res2.error() != MyError::Failure); - } - - { - using Result = Result<double>; - - Result res(42); - BOOST_CHECK(res.ok()); - BOOST_CHECK_EQUAL(*res, 42.); - BOOST_CHECK_EQUAL(res.value(), 42); - res = 46; - BOOST_CHECK(res.ok()); - BOOST_CHECK_EQUAL(*res, 46.); - BOOST_CHECK_EQUAL(res.value(), 46); - - Result res2(ec); - BOOST_CHECK(!res2.ok()); - BOOST_CHECK_EQUAL(res2.error(), ec); - BOOST_CHECK_EQUAL(res2.error(), err1); - - res2 = MyError::SomethingElse; - BOOST_CHECK(!res2.ok()); - BOOST_CHECK_EQUAL(res2.error(), MyError::SomethingElse); - BOOST_CHECK(res2.error() != MyError::Failure); - } - - { - using Result = Result<std::string>; - - Result res("hallo"); - - BOOST_CHECK(res.ok()); - BOOST_CHECK_EQUAL(*res, "hallo"); - BOOST_CHECK_EQUAL(res.value(), "hallo"); - - res = "something else"; - BOOST_CHECK(res.ok()); - BOOST_CHECK_EQUAL(*res, "something else"); - BOOST_CHECK_EQUAL(res.value(), "something else"); - - res = MyError::SomethingElse; - BOOST_CHECK(!res.ok()); - BOOST_CHECK_EQUAL(res.error(), MyError::SomethingElse); - BOOST_CHECK(res.error() != MyError::Failure); - } + using Result = Result<double, std::string>; + + Result res1("hallo"); + BOOST_CHECK(!res1.ok()); + BOOST_CHECK_EQUAL(res1.error(), "hallo"); + BOOST_CHECK_THROW(res1.value(), std::runtime_error); + res1 = Result::failure("hallo"); + BOOST_CHECK(!res1.ok()); + BOOST_CHECK_EQUAL(res1.error(), "hallo"); + BOOST_CHECK_THROW(res1.value(), std::runtime_error); + + Result res2(4.5); + BOOST_CHECK(res2.ok()); + BOOST_CHECK(*res2 == 4.5); + BOOST_CHECK(res2.value() == 4.5); + res2 = Result::success(4.5); + BOOST_CHECK(res2.ok()); + BOOST_CHECK_EQUAL(*res2, 4.5); + BOOST_CHECK_EQUAL(res2.value(), 4.5); } +} - struct NoCopy - { - NoCopy(int i) : num(i){}; - NoCopy(const NoCopy&) = delete; - NoCopy& - operator=(const NoCopy&) - = delete; - NoCopy(NoCopy&&) = default; - NoCopy& - operator=(NoCopy&&) - = default; - - int num; - }; - - Result<NoCopy> - make_nocopy(int i, bool v = true) - { - if (!v) { - return MyError::Failure; - } - return i; - } +BOOST_AUTO_TEST_CASE(TestErrorCodes) { + auto err1 = MyError::Failure; - BOOST_AUTO_TEST_CASE(CopyBehaviour) - { + std::error_code ec = err1; - using Result = Result<NoCopy>; + { + using Result = Result<double, MyError>; - NoCopy n(5); - Result res = std::move(n); + Result res(42); BOOST_CHECK(res.ok()); - BOOST_CHECK_EQUAL((*res).num, res.value().num); + BOOST_CHECK_EQUAL(*res, 42.); - res = make_nocopy(3); - BOOST_CHECK(res.ok()); - BOOST_CHECK_EQUAL((*res).num, res.value().num); - BOOST_CHECK_EQUAL((*res).num, 3); + Result res2(err1); + BOOST_CHECK(!res2.ok()); + BOOST_CHECK_EQUAL(res2.error(), err1); + BOOST_CHECK_THROW(res2.value(), std::runtime_error); + } + + { + using Result = Result<double, std::error_code>; - res = NoCopy(-4); + Result res(42); + BOOST_CHECK(res.ok()); + BOOST_CHECK_EQUAL(*res, 42.); + BOOST_CHECK_EQUAL(res.value(), 42); + res = 46; BOOST_CHECK(res.ok()); - BOOST_CHECK_EQUAL((*res).num, res.value().num); - BOOST_CHECK_EQUAL((*res).num, -4.); - - NoCopy n2 = make_nocopy(7).value(); - BOOST_CHECK_EQUAL(n2.num, 7); - BOOST_REQUIRE_THROW(make_nocopy(6, false).value();, std::runtime_error); - - Result n4r = make_nocopy(8); - BOOST_CHECK(n4r.ok()); - BOOST_CHECK_EQUAL((*n4r).num, 8); - NoCopy n4 = std::move(n4r.value()); - BOOST_CHECK_EQUAL(n4.num, 8); + BOOST_CHECK_EQUAL(*res, 46.); + BOOST_CHECK_EQUAL(res.value(), 46); + + Result res2(ec); + BOOST_CHECK(!res2.ok()); + BOOST_CHECK_EQUAL(res2.error(), ec); + BOOST_CHECK_EQUAL(res2.error(), err1); + + res2 = MyError::SomethingElse; + BOOST_CHECK(!res2.ok()); + BOOST_CHECK_EQUAL(res2.error(), MyError::SomethingElse); + BOOST_CHECK(res2.error() != MyError::Failure); } - Result<void> - void_res_func(int b) { - (void)b; - if (b > 5) { - return MyError::SomethingElse; - } - return {}; + using Result = Result<double>; + + Result res(42); + BOOST_CHECK(res.ok()); + BOOST_CHECK_EQUAL(*res, 42.); + BOOST_CHECK_EQUAL(res.value(), 42); + res = 46; + BOOST_CHECK(res.ok()); + BOOST_CHECK_EQUAL(*res, 46.); + BOOST_CHECK_EQUAL(res.value(), 46); + + Result res2(ec); + BOOST_CHECK(!res2.ok()); + BOOST_CHECK_EQUAL(res2.error(), ec); + BOOST_CHECK_EQUAL(res2.error(), err1); + + res2 = MyError::SomethingElse; + BOOST_CHECK(!res2.ok()); + BOOST_CHECK_EQUAL(res2.error(), MyError::SomethingElse); + BOOST_CHECK(res2.error() != MyError::Failure); } - BOOST_AUTO_TEST_CASE(VoidResult) { - using Result = Result<void>; + using Result = Result<std::string>; + + Result res("hallo"); - Result res; BOOST_CHECK(res.ok()); + BOOST_CHECK_EQUAL(*res, "hallo"); + BOOST_CHECK_EQUAL(res.value(), "hallo"); - Result res2 = Result::success(); - BOOST_CHECK(res2.ok()); + res = "something else"; + BOOST_CHECK(res.ok()); + BOOST_CHECK_EQUAL(*res, "something else"); + BOOST_CHECK_EQUAL(res.value(), "something else"); - res = MyError::Failure; + res = MyError::SomethingElse; BOOST_CHECK(!res.ok()); - BOOST_CHECK_EQUAL(res.error(), MyError::Failure); + BOOST_CHECK_EQUAL(res.error(), MyError::SomethingElse); + BOOST_CHECK(res.error() != MyError::Failure); + } +} - Result res3 = Result::failure(MyError::SomethingElse); - BOOST_CHECK(!res3.ok()); - BOOST_CHECK_EQUAL(res3.error(), MyError::SomethingElse); +struct NoCopy { + NoCopy(int i) : num(i){}; + NoCopy(const NoCopy&) = delete; + NoCopy& operator=(const NoCopy&) = delete; + NoCopy(NoCopy&&) = default; + NoCopy& operator=(NoCopy&&) = default; - Result res4 = void_res_func(4); - BOOST_CHECK(res4.ok()); + int num; +}; - Result res5 = void_res_func(42); - BOOST_CHECK(!res5.ok()); - BOOST_CHECK_EQUAL(res5.error(), MyError::SomethingElse); +Result<NoCopy> make_nocopy(int i, bool v = true) { + if (!v) { + return MyError::Failure; } + return i; +} - BOOST_AUTO_TEST_CASE(BoolResult) - { - using Result = Result<bool>; +BOOST_AUTO_TEST_CASE(CopyBehaviour) { + using Result = Result<NoCopy>; + + NoCopy n(5); + Result res = std::move(n); + BOOST_CHECK(res.ok()); + BOOST_CHECK_EQUAL((*res).num, res.value().num); + + res = make_nocopy(3); + BOOST_CHECK(res.ok()); + BOOST_CHECK_EQUAL((*res).num, res.value().num); + BOOST_CHECK_EQUAL((*res).num, 3); + + res = NoCopy(-4); + BOOST_CHECK(res.ok()); + BOOST_CHECK_EQUAL((*res).num, res.value().num); + BOOST_CHECK_EQUAL((*res).num, -4.); + + NoCopy n2 = make_nocopy(7).value(); + BOOST_CHECK_EQUAL(n2.num, 7); + BOOST_REQUIRE_THROW(make_nocopy(6, false).value();, std::runtime_error); + + Result n4r = make_nocopy(8); + BOOST_CHECK(n4r.ok()); + BOOST_CHECK_EQUAL((*n4r).num, 8); + NoCopy n4 = std::move(n4r.value()); + BOOST_CHECK_EQUAL(n4.num, 8); +} - Result res = Result::success(false); - BOOST_CHECK(res.ok()); - BOOST_CHECK_EQUAL(*res, false); +Result<void> void_res_func(int b) { + (void)b; + if (b > 5) { + return MyError::SomethingElse; + } + return {}; +} - res = Result::success(true); - BOOST_CHECK(res.ok()); - BOOST_CHECK_EQUAL(*res, true); +BOOST_AUTO_TEST_CASE(VoidResult) { + using Result = Result<void>; - res = Result::failure(MyError::Failure); - BOOST_CHECK(!res.ok()); - BOOST_CHECK_EQUAL(res.error(), MyError::Failure); - } + Result res; + BOOST_CHECK(res.ok()); + + Result res2 = Result::success(); + BOOST_CHECK(res2.ok()); + + res = MyError::Failure; + BOOST_CHECK(!res.ok()); + BOOST_CHECK_EQUAL(res.error(), MyError::Failure); + + Result res3 = Result::failure(MyError::SomethingElse); + BOOST_CHECK(!res3.ok()); + BOOST_CHECK_EQUAL(res3.error(), MyError::SomethingElse); + + Result res4 = void_res_func(4); + BOOST_CHECK(res4.ok()); - BOOST_AUTO_TEST_SUITE_END() + Result res5 = void_res_func(42); + BOOST_CHECK(!res5.ok()); + BOOST_CHECK_EQUAL(res5.error(), MyError::SomethingElse); } + +BOOST_AUTO_TEST_CASE(BoolResult) { + using Result = Result<bool>; + + Result res = Result::success(false); + BOOST_CHECK(res.ok()); + BOOST_CHECK_EQUAL(*res, false); + + res = Result::success(true); + BOOST_CHECK(res.ok()); + BOOST_CHECK_EQUAL(*res, true); + + res = Result::failure(MyError::Failure); + BOOST_CHECK(!res.ok()); + BOOST_CHECK_EQUAL(res.error(), MyError::Failure); } + +BOOST_AUTO_TEST_SUITE_END() +} // namespace Test +} // namespace Acts diff --git a/Tests/Core/Utilities/TypeTraitsTest.cpp b/Tests/Core/Utilities/TypeTraitsTest.cpp index 279798158cd6ed893eb12f7d47b1be685ca85047..635b42c46d61d6129eb8b4da3c0a8d62523027a2 100644 --- a/Tests/Core/Utilities/TypeTraitsTest.cpp +++ b/Tests/Core/Utilities/TypeTraitsTest.cpp @@ -16,297 +16,225 @@ #include "Acts/Utilities/TypeTraits.hpp" namespace bdata = boost::unit_test::data; -namespace tt = boost::test_tools; +namespace tt = boost::test_tools; using namespace Acts::concept; namespace Acts { namespace Test { - BOOST_AUTO_TEST_SUITE(Surfaces) - - // generate traits for methods named foo and bar - METHOD_TRAIT(foo_method_t, foo); - METHOD_TRAIT(bar_method_t, bar); - - struct E - { - int - bar(const double&) - { - return 5; - } - }; - - struct E2 - { - int - bar(const double&) const - { - return 5; - } - }; - - class E3 - { - int - bar(const double&) - { - return 5; - } - }; - - BOOST_AUTO_TEST_CASE(TypeTraitsMethods) - { - - // E does not have a method bar without arguments - static_assert(!has_method<E, int, bar_method_t>, "failed"); - // E does have a method like int bar(const double&) - static_assert(has_method<E, int, bar_method_t, const double&>, "failed"); - // E does not have method bar returning double instead of int - static_assert(!has_method<E, double, bar_method_t, const double&>, - "failed"); - // E does not have method taking non-ref const double argument - static_assert(!has_method<E, int, bar_method_t, const double>, "failed"); - // E does not have method taking non-const double ref argument - static_assert(!has_method<E, int, bar_method_t, double&>, "failed"); - // E does not have method taking plain double argument - static_assert(!has_method<E, int, bar_method_t, double>, "failed"); - // E does not have method const method with correct signature otherwise - // This test ensures a non-const method does not qualify for a - // check for a method on the const type - static_assert(!has_method<const E, int, bar_method_t, const double&>, - "failed"); - // E does not have a foo method - static_assert(!has_method<E, int, foo_method_t, const double&>, "failed"); - - // E2 doesnt have method like int bar() - static_assert(!has_method<E2, int, bar_method_t>, "failed"); - // E2 does not have non-const method with signature int bar(const double&) - // This means that a const method won't fulfill a non-const method - // requirement - static_assert(!has_method<E2, int, bar_method_t, const double&>, "failed"); - // E2 has method of signature int bar(const double&) const - static_assert(has_method<const E2, int, bar_method_t, const double&>, - "failed"); - // E2 does not have method taking non-ref const double - static_assert(!has_method<E2, int, bar_method_t, const double>, "failed"); - // E2 does not have method taking non-const ref double - static_assert(!has_method<E2, int, bar_method_t, double&>, "failed"); - // E2 does not have method taking plain double - static_assert(!has_method<E2, int, bar_method_t, double>, "failed"); - // E2 does not have method with char return type - static_assert(!has_method<const E2, char, bar_method_t, const double&>, - "failed"); - // E2 does not have foo method - static_assert(!has_method<const E2, int, foo_method_t, const double&>, - "failed"); - - // E3 does have a method like int bar(const double&) but is private - static_assert(!has_method<E3, int, bar_method_t, const double&>, "failed"); - } - - // trait for member named "member_a" - template <typename T> - using member_a_t = decltype(std::declval<T>().member_a); - // trait for member named "member_b" - template <typename T> - using member_b_t = decltype(std::declval<T>().member_b); - - struct M - { - int member_a; - double member_b; - }; - - struct M2 - { - double member_a; - }; - - struct M3 - { - char member_a; - }; - - struct M4 - { - char member_b; - }; - - class M5 - { - char member_b; - }; - - BOOST_AUTO_TEST_CASE(TypeTraitsMember) - { - static_assert(has_member<M, member_a_t, int>, "!"); - static_assert(has_member<M, member_b_t, double>, "!"); - // incorrect type - static_assert(!has_member<M, member_b_t, int>, "!"); - static_assert(!has_member<M, member_a_t, double>, "!"); - - static_assert(has_member<M2, member_a_t, double>, "!"); - static_assert(!has_member<M2, member_a_t, int>, "!"); - - static_assert(exists<member_a_t, M>, "!"); - static_assert(exists<member_a_t, M2>, "!"); - static_assert(exists<member_a_t, M3>, "!"); - static_assert(!exists<member_a_t, M4>, "!"); - - // private member is not detected - static_assert(!has_member<M5, member_b_t, char>, "!"); - - // private member is not detected. - static_assert(!exists<member_b_t, M5>, "!"); - } - - template <typename T> - using nested_a_t = typename T::NestedA; - template <typename T> - using nested_b_t = typename T::NestedB; - - struct N - { - struct NestedA; - class NestedB; - }; - - struct N2 - { - struct NestedA; - }; - - struct N3 - { - class NestedB; - }; - - BOOST_AUTO_TEST_CASE(TypeTraitsNestedType) - { - static_assert(exists<nested_a_t, N>, "!"); - static_assert(exists<nested_b_t, N>, "!"); - - static_assert(exists<nested_a_t, N2>, "!"); - static_assert(!exists<nested_b_t, N2>, "!"); - - static_assert(!exists<nested_a_t, N3>, "!"); - static_assert(exists<nested_b_t, N3>, "!"); - } - - // trait for member named "member" - template <typename T> - using member_t = decltype(std::declval<T>().member); - - // trait for nested type called "Nested" - template <typename T> - using nested_t = typename T::Nested; - - // trait for contained template "meta" with two template params - template <typename T> - using meta_t = typename T::template meta<void, void>; - - // combine it into a concept - template <typename T> - constexpr bool SomeConcept - = require<has_method<T, double, foo_method_t, double, int>, - has_method<const T, bool, bar_method_t, double&&>, - has_member<T, member_t, bool>, - exists<nested_t, T>, - exists<meta_t, T>>; - - struct A - { - bool member; - - struct Nested - { - }; - - template <typename U, typename V> - struct meta - { - }; - - double - foo(double, int) - { - return 5; - } - - bool - bar(double&&) const - { - return true; - } - }; - - struct A2 - { - bool member; - - struct Nested - { - }; - - template <typename U> - struct meta - { - }; - - double - foo(double, int) - { - return 5; - } - - bool - bar(double&&) const - { - return true; - } - }; - - struct B - { - bool different; - - int - foo(double) - { - return 5; - } - }; - - struct C - { - double - foo(int) - { - return 5; - } - }; - - struct D - { - double - bar(double) - { - return 5; - } - }; - - BOOST_AUTO_TEST_CASE(TypeTraitsConcepts) - { - - static_assert(SomeConcept<A>, "A does not fulfill \"SomeConcept\""); - static_assert(!SomeConcept<A2>, "A2 does not fulfill \"SomeConcept\""); - static_assert(!SomeConcept<B>, "B does fulfill \"SomeConcept\""); - static_assert(!SomeConcept<C>, "C does fulfill \"SomeConcept\""); - static_assert(!SomeConcept<D>, "D does fulfill \"SomeConcept\""); - } - - BOOST_AUTO_TEST_SUITE_END() +BOOST_AUTO_TEST_SUITE(Surfaces) + +// generate traits for methods named foo and bar +METHOD_TRAIT(foo_method_t, foo); +METHOD_TRAIT(bar_method_t, bar); + +struct E { + int bar(const double&) { return 5; } +}; + +struct E2 { + int bar(const double&) const { return 5; } +}; + +class E3 { + int bar(const double&) { return 5; } +}; + +BOOST_AUTO_TEST_CASE(TypeTraitsMethods) { + // E does not have a method bar without arguments + static_assert(!has_method<E, int, bar_method_t>, "failed"); + // E does have a method like int bar(const double&) + static_assert(has_method<E, int, bar_method_t, const double&>, "failed"); + // E does not have method bar returning double instead of int + static_assert(!has_method<E, double, bar_method_t, const double&>, "failed"); + // E does not have method taking non-ref const double argument + static_assert(!has_method<E, int, bar_method_t, const double>, "failed"); + // E does not have method taking non-const double ref argument + static_assert(!has_method<E, int, bar_method_t, double&>, "failed"); + // E does not have method taking plain double argument + static_assert(!has_method<E, int, bar_method_t, double>, "failed"); + // E does not have method const method with correct signature otherwise + // This test ensures a non-const method does not qualify for a + // check for a method on the const type + static_assert(!has_method<const E, int, bar_method_t, const double&>, + "failed"); + // E does not have a foo method + static_assert(!has_method<E, int, foo_method_t, const double&>, "failed"); + + // E2 doesnt have method like int bar() + static_assert(!has_method<E2, int, bar_method_t>, "failed"); + // E2 does not have non-const method with signature int bar(const double&) + // This means that a const method won't fulfill a non-const method + // requirement + static_assert(!has_method<E2, int, bar_method_t, const double&>, "failed"); + // E2 has method of signature int bar(const double&) const + static_assert(has_method<const E2, int, bar_method_t, const double&>, + "failed"); + // E2 does not have method taking non-ref const double + static_assert(!has_method<E2, int, bar_method_t, const double>, "failed"); + // E2 does not have method taking non-const ref double + static_assert(!has_method<E2, int, bar_method_t, double&>, "failed"); + // E2 does not have method taking plain double + static_assert(!has_method<E2, int, bar_method_t, double>, "failed"); + // E2 does not have method with char return type + static_assert(!has_method<const E2, char, bar_method_t, const double&>, + "failed"); + // E2 does not have foo method + static_assert(!has_method<const E2, int, foo_method_t, const double&>, + "failed"); + + // E3 does have a method like int bar(const double&) but is private + static_assert(!has_method<E3, int, bar_method_t, const double&>, "failed"); } + +// trait for member named "member_a" +template <typename T> +using member_a_t = decltype(std::declval<T>().member_a); +// trait for member named "member_b" +template <typename T> +using member_b_t = decltype(std::declval<T>().member_b); + +struct M { + int member_a; + double member_b; +}; + +struct M2 { + double member_a; +}; + +struct M3 { + char member_a; +}; + +struct M4 { + char member_b; +}; + +class M5 { + char member_b; +}; + +BOOST_AUTO_TEST_CASE(TypeTraitsMember) { + static_assert(has_member<M, member_a_t, int>, "!"); + static_assert(has_member<M, member_b_t, double>, "!"); + // incorrect type + static_assert(!has_member<M, member_b_t, int>, "!"); + static_assert(!has_member<M, member_a_t, double>, "!"); + + static_assert(has_member<M2, member_a_t, double>, "!"); + static_assert(!has_member<M2, member_a_t, int>, "!"); + + static_assert(exists<member_a_t, M>, "!"); + static_assert(exists<member_a_t, M2>, "!"); + static_assert(exists<member_a_t, M3>, "!"); + static_assert(!exists<member_a_t, M4>, "!"); + + // private member is not detected + static_assert(!has_member<M5, member_b_t, char>, "!"); + + // private member is not detected. + static_assert(!exists<member_b_t, M5>, "!"); +} + +template <typename T> +using nested_a_t = typename T::NestedA; +template <typename T> +using nested_b_t = typename T::NestedB; + +struct N { + struct NestedA; + class NestedB; +}; + +struct N2 { + struct NestedA; +}; + +struct N3 { + class NestedB; +}; + +BOOST_AUTO_TEST_CASE(TypeTraitsNestedType) { + static_assert(exists<nested_a_t, N>, "!"); + static_assert(exists<nested_b_t, N>, "!"); + + static_assert(exists<nested_a_t, N2>, "!"); + static_assert(!exists<nested_b_t, N2>, "!"); + + static_assert(!exists<nested_a_t, N3>, "!"); + static_assert(exists<nested_b_t, N3>, "!"); +} + +// trait for member named "member" +template <typename T> +using member_t = decltype(std::declval<T>().member); + +// trait for nested type called "Nested" +template <typename T> +using nested_t = typename T::Nested; + +// trait for contained template "meta" with two template params +template <typename T> +using meta_t = typename T::template meta<void, void>; + +// combine it into a concept +template <typename T> +constexpr bool SomeConcept = + require<has_method<T, double, foo_method_t, double, int>, + has_method<const T, bool, bar_method_t, double&&>, + has_member<T, member_t, bool>, exists<nested_t, T>, + exists<meta_t, T>>; + +struct A { + bool member; + + struct Nested {}; + + template <typename U, typename V> + struct meta {}; + + double foo(double, int) { return 5; } + + bool bar(double&&) const { return true; } +}; + +struct A2 { + bool member; + + struct Nested {}; + + template <typename U> + struct meta {}; + + double foo(double, int) { return 5; } + + bool bar(double&&) const { return true; } +}; + +struct B { + bool different; + + int foo(double) { return 5; } +}; + +struct C { + double foo(int) { return 5; } +}; + +struct D { + double bar(double) { return 5; } +}; + +BOOST_AUTO_TEST_CASE(TypeTraitsConcepts) { + static_assert(SomeConcept<A>, "A does not fulfill \"SomeConcept\""); + static_assert(!SomeConcept<A2>, "A2 does not fulfill \"SomeConcept\""); + static_assert(!SomeConcept<B>, "B does fulfill \"SomeConcept\""); + static_assert(!SomeConcept<C>, "C does fulfill \"SomeConcept\""); + static_assert(!SomeConcept<D>, "D does fulfill \"SomeConcept\""); } + +BOOST_AUTO_TEST_SUITE_END() +} // namespace Test +} // namespace Acts diff --git a/Tests/Core/Utilities/UnitConversionTests.cpp b/Tests/Core/Utilities/UnitConversionTests.cpp index a598c607920c37b2d7e0780f6654c8948ca77052..00ea6850d1caccaeac5a9c082b202f686e532274 100644 --- a/Tests/Core/Utilities/UnitConversionTests.cpp +++ b/Tests/Core/Utilities/UnitConversionTests.cpp @@ -17,12 +17,11 @@ using namespace Acts::units; namespace utf = boost::unit_test; -namespace tt = boost::test_tools; +namespace tt = boost::test_tools; BOOST_AUTO_TEST_SUITE(unit_conversion) -BOOST_AUTO_TEST_CASE(length_conversions) -{ +BOOST_AUTO_TEST_CASE(length_conversions) { CHECK_CLOSE_REL(_m, 1e-3 * _km, 1e-15); CHECK_CLOSE_REL(_m, 1e3 * _mm, 1e-15); CHECK_CLOSE_REL(_m, 1e6 * _um, 1e-15); @@ -31,21 +30,18 @@ BOOST_AUTO_TEST_CASE(length_conversions) CHECK_CLOSE_REL(_m, 1e15 * _fm, 1e-15); } -BOOST_AUTO_TEST_CASE(mass_conversions) -{ +BOOST_AUTO_TEST_CASE(mass_conversions) { CHECK_CLOSE_REL(_kg, 1e3 * _g, 1e-15); CHECK_CLOSE_REL(_kg, 1e6 * _mg, 1e-15); CHECK_CLOSE_REL(1.660539040e-27 * _kg, _u, 1e-15); } -BOOST_AUTO_TEST_CASE(time_conversions) -{ +BOOST_AUTO_TEST_CASE(time_conversions) { CHECK_CLOSE_REL(_s, 1e3 * _ms, 1e-15); CHECK_CLOSE_REL(3600 * _s, _h, 1e-15); } -BOOST_AUTO_TEST_CASE(energy_conversions) -{ +BOOST_AUTO_TEST_CASE(energy_conversions) { CHECK_CLOSE_REL(_MeV, 1e-3 * _GeV, 1e-15); CHECK_CLOSE_REL(_MeV, 1e-6 * _TeV, 1e-15); CHECK_CLOSE_REL(_MeV, 1e3 * _keV, 1e-15); diff --git a/Tests/Core/Utilities/VisualizationTests.cpp b/Tests/Core/Utilities/VisualizationTests.cpp index 1c38d40749958b438f95a8dc367302aeb01ee4d6..8c152ca96a0a9fb172fe09afc1226c304a89d234 100644 --- a/Tests/Core/Utilities/VisualizationTests.cpp +++ b/Tests/Core/Utilities/VisualizationTests.cpp @@ -22,30 +22,28 @@ using boost::test_tools::output_test_stream; namespace Acts { namespace Test { - BOOST_AUTO_TEST_SUITE(Utilities) - - BOOST_AUTO_TEST_CASE(construction_test) - { - // this doesn't really test anything, other than conformance to the - // IVisualization interface - PlyHelper ply; - ObjHelper obj; - - IVisualization* vis; - vis = &ply; - std::cout << *vis << std::endl; - vis = &obj; - std::cout << *vis << std::endl; - } - - BOOST_AUTO_TEST_CASE(ply_output_test) - { - PlyHelper ply; - output_test_stream output; - - ply.vertex({0, 0, 0}); - - std::string exp = R"(ply +BOOST_AUTO_TEST_SUITE(Utilities) + +BOOST_AUTO_TEST_CASE(construction_test) { + // this doesn't really test anything, other than conformance to the + // IVisualization interface + PlyHelper ply; + ObjHelper obj; + + IVisualization* vis; + vis = &ply; + std::cout << *vis << std::endl; + vis = &obj; + std::cout << *vis << std::endl; +} + +BOOST_AUTO_TEST_CASE(ply_output_test) { + PlyHelper ply; + output_test_stream output; + + ply.vertex({0, 0, 0}); + + std::string exp = R"(ply format ascii 1.0 element vertex 1 property float x @@ -66,13 +64,13 @@ end_header 0 0 0 120 120 120 )"; - output << ply; - BOOST_CHECK(output.is_equal(exp)); + output << ply; + BOOST_CHECK(output.is_equal(exp)); - ply.clear(); - ply.vertex({0, 1, 0}); + ply.clear(); + ply.vertex({0, 1, 0}); - exp = R"(ply + exp = R"(ply format ascii 1.0 element vertex 1 property float x @@ -93,15 +91,15 @@ end_header 0 1 0 120 120 120 )"; - output << ply; - BOOST_CHECK(output.is_equal(exp)); + output << ply; + BOOST_CHECK(output.is_equal(exp)); - ply.clear(); - ply.line({0, 0, 1}, {1, 0, 0}); + ply.clear(); + ply.line({0, 0, 1}, {1, 0, 0}); - output << ply; + output << ply; - exp = R"(ply + exp = R"(ply format ascii 1.0 element vertex 2 property float x @@ -124,14 +122,14 @@ end_header 0 1 120 120 120 )"; - BOOST_CHECK(output.is_equal(exp)); + BOOST_CHECK(output.is_equal(exp)); - ply.clear(); - ply.face({{1, 0, 0}, {1, 1, 0}, {0, 1, 0}}); + ply.clear(); + ply.face({{1, 0, 0}, {1, 1, 0}, {0, 1, 0}}); - output << ply; + output << ply; - exp = R"(ply + exp = R"(ply format ascii 1.0 element vertex 3 property float x @@ -155,41 +153,40 @@ end_header 3 0 1 2 )"; - BOOST_CHECK(output.is_equal(exp)); - } + BOOST_CHECK(output.is_equal(exp)); +} - BOOST_AUTO_TEST_CASE(obj_output_test) - { - ObjHelper obj; +BOOST_AUTO_TEST_CASE(obj_output_test) { + ObjHelper obj; - output_test_stream output; + output_test_stream output; - obj.vertex({1, 0, 0}); + obj.vertex({1, 0, 0}); - output << obj; + output << obj; - std::string exp = R"(v 1 0 0 + std::string exp = R"(v 1 0 0 )"; - BOOST_CHECK(output.is_equal(exp)); + BOOST_CHECK(output.is_equal(exp)); - obj.clear(); + obj.clear(); - BOOST_CHECK_THROW(obj.line({1, 0, 0}, {0, 1, 0}), std::runtime_error); + BOOST_CHECK_THROW(obj.line({1, 0, 0}, {0, 1, 0}), std::runtime_error); - obj.clear(); - obj.face({{1, 0, 0}, {1, 1, 0}, {0, 1, 0}}); - output << obj; + obj.clear(); + obj.face({{1, 0, 0}, {1, 1, 0}, {0, 1, 0}}); + output << obj; - exp = R"(v 1 0 0 + exp = R"(v 1 0 0 v 1 1 0 v 0 1 0 f 1 2 3 )"; - BOOST_CHECK(output.is_equal(exp)); - } - - BOOST_AUTO_TEST_SUITE_END() -} + BOOST_CHECK(output.is_equal(exp)); } + +BOOST_AUTO_TEST_SUITE_END() +} // namespace Test +} // namespace Acts diff --git a/Tests/Core/Vertexing/FullBilloirVertexFitterTests.cpp b/Tests/Core/Vertexing/FullBilloirVertexFitterTests.cpp index 9950861eb35e6eeff4959a8d92f2c3ceaf9442ec..cacf963bc73d49af287965dda5f915ce8f5497f3 100644 --- a/Tests/Core/Vertexing/FullBilloirVertexFitterTests.cpp +++ b/Tests/Core/Vertexing/FullBilloirVertexFitterTests.cpp @@ -31,40 +31,125 @@ namespace bdata = boost::unit_test::data; namespace Acts { namespace Test { - // Create a test context - GeometryContext tgContext = GeometryContext(); - MagneticFieldContext mfContext = MagneticFieldContext(); - - template <typename InputTrack_t, typename Propagator_t> - Vertex<InputTrack_t> - myFitWrapper(IVertexFitter<InputTrack_t, Propagator_t>* fitter, - std::vector<InputTrack_t>& tracks, - VertexFitterOptions<InputTrack_t> vfOptions) - { - return fitter->fit(tracks, vfOptions).value(); - } - - /// @brief Unit test for FullBilloirVertexFitter - /// - BOOST_AUTO_TEST_CASE(billoir_vertex_fitter_empty_input_test) - { - - // Set up constant B-Field - ConstantBField bField(Vector3D(0., 0., 1.) * units::_T); - - // Set up Eigenstepper - EigenStepper<ConstantBField> stepper(bField); - - // Set up propagator with void navigator - Propagator<EigenStepper<ConstantBField>> propagator(stepper); +// Create a test context +GeometryContext tgContext = GeometryContext(); +MagneticFieldContext mfContext = MagneticFieldContext(); + +template <typename InputTrack_t, typename Propagator_t> +Vertex<InputTrack_t> myFitWrapper( + IVertexFitter<InputTrack_t, Propagator_t>* fitter, + std::vector<InputTrack_t>& tracks, + VertexFitterOptions<InputTrack_t> vfOptions) { + return fitter->fit(tracks, vfOptions).value(); +} + +/// @brief Unit test for FullBilloirVertexFitter +/// +BOOST_AUTO_TEST_CASE(billoir_vertex_fitter_empty_input_test) { + // Set up constant B-Field + ConstantBField bField(Vector3D(0., 0., 1.) * units::_T); + + // Set up Eigenstepper + EigenStepper<ConstantBField> stepper(bField); + + // Set up propagator with void navigator + Propagator<EigenStepper<ConstantBField>> propagator(stepper); + + // Set up Billoir Vertex Fitter + FullBilloirVertexFitter<ConstantBField, BoundParameters, + Propagator<EigenStepper<ConstantBField>>>::Config + vertexFitterCfg(bField, propagator); + FullBilloirVertexFitter<ConstantBField, BoundParameters, + Propagator<EigenStepper<ConstantBField>>> + billoirFitter(vertexFitterCfg); + + // Constraint for vertex fit + Vertex<BoundParameters> myConstraint; + // Some abitrary values + ActsSymMatrixD<3> myCovMat = ActsSymMatrixD<3>::Zero(); + myCovMat(0, 0) = 30.; + myCovMat(1, 1) = 30.; + myCovMat(2, 2) = 30.; + myConstraint.setCovariance(std::move(myCovMat)); + myConstraint.setPosition(Vector3D(0, 0, 0)); + + std::vector<BoundParameters> emptyVector; + + VertexFitterOptions<BoundParameters> vfOptions(tgContext, mfContext, + myConstraint); + + Vertex<BoundParameters> fittedVertex = + billoirFitter.fit(emptyVector, vfOptions).value(); + + Vector3D origin(0., 0., 0.); + BOOST_CHECK_EQUAL(fittedVertex.position(), origin); + + ActsSymMatrixD<3> zeroMat = ActsSymMatrixD<3>::Zero(); + BOOST_CHECK_EQUAL(fittedVertex.covariance(), zeroMat); + + fittedVertex = billoirFitter.fit(emptyVector, vfOptions).value(); + + BOOST_CHECK_EQUAL(fittedVertex.position(), origin); + BOOST_CHECK_EQUAL(fittedVertex.covariance(), zeroMat); +} + +// Vertex x/y position distribution +std::uniform_real_distribution<> vXYDist(-0.1 * units::_mm, 0.1 * units::_mm); +// Vertex z position distribution +std::uniform_real_distribution<> vZDist(-20 * units::_mm, 20 * units::_mm); +// Track d0 distribution +std::uniform_real_distribution<> d0Dist(-0.01 * units::_mm, 0.01 * units::_mm); +// Track z0 distribution +std::uniform_real_distribution<> z0Dist(-0.2 * units::_mm, 0.2 * units::_mm); +// Track pT distribution +std::uniform_real_distribution<> pTDist(0.4 * units::_GeV, 10. * units::_GeV); +// Track phi distribution +std::uniform_real_distribution<> phiDist(-M_PI, M_PI); +// Track theta distribution +std::uniform_real_distribution<> thetaDist(1.0, M_PI - 1.0); +// Track charge helper distribution +std::uniform_real_distribution<> qDist(-1, 1); +// Track IP resolution distribution +std::uniform_real_distribution<> resIPDist(0., 100. * units::_um); +// Track angular distribution +std::uniform_real_distribution<> resAngDist(0., 0.1); +// Track q/p resolution distribution +std::uniform_real_distribution<> resQoPDist(-0.1, 0.1); +// Number of tracks distritbution +std::uniform_int_distribution<> nTracksDist(3, 10); + +/// +/// @brief Unit test for FullBilloirVertexFitter +/// with default input track type (= BoundParameters) +/// +BOOST_AUTO_TEST_CASE(billoir_vertex_fitter_defaulttrack_test) { + bool debugMode = false; + + // Set up RNG + int mySeed = 31415; + std::mt19937 gen(mySeed); + + // Set up constant B-Field + ConstantBField bField(Vector3D(0., 0., 1.) * units::_T); + + // Set up Eigenstepper + EigenStepper<ConstantBField> stepper(bField); + + // Set up propagator with void navigator + Propagator<EigenStepper<ConstantBField>> propagator(stepper); + + // Number of events + const int nEvents = 10; + + for (int eventIdx = 0; eventIdx < nEvents; ++eventIdx) { + // Number of tracks + unsigned int nTracks = nTracksDist(gen); // Set up Billoir Vertex Fitter - FullBilloirVertexFitter<ConstantBField, - BoundParameters, + FullBilloirVertexFitter<ConstantBField, BoundParameters, Propagator<EigenStepper<ConstantBField>>>::Config vertexFitterCfg(bField, propagator); - FullBilloirVertexFitter<ConstantBField, - BoundParameters, + FullBilloirVertexFitter<ConstantBField, BoundParameters, Propagator<EigenStepper<ConstantBField>>> billoirFitter(vertexFitterCfg); @@ -78,335 +163,225 @@ namespace Test { myConstraint.setCovariance(std::move(myCovMat)); myConstraint.setPosition(Vector3D(0, 0, 0)); - std::vector<BoundParameters> emptyVector; + VertexFitterOptions<BoundParameters> vfOptions(tgContext, mfContext); + + VertexFitterOptions<BoundParameters> vfOptionsConstr(tgContext, mfContext, + myConstraint); + + // Create position of vertex and perigee surface + double x = vXYDist(gen); + double y = vXYDist(gen); + double z = vZDist(gen); + + Vector3D vertexPosition(x, y, z); + std::shared_ptr<PerigeeSurface> perigeeSurface = + Surface::makeShared<PerigeeSurface>(Vector3D(0., 0., 0.)); + + // Calculate d0 and z0 corresponding to vertex position + double d0V = sqrt(x * x + y * y); + double z0V = z; + + // Start constructing nTracks tracks in the following + std::vector<BoundParameters> tracks; + + // Construct random track emerging from vicinity of vertex position + // Vector to store track objects used for vertex fit + for (unsigned int iTrack = 0; iTrack < nTracks; iTrack++) { + // Construct positive or negative charge randomly + double q = qDist(gen) < 0 ? -1. : 1.; + + // Construct random track parameters + TrackParametersBase::ParVector_t paramVec; + paramVec << d0V + d0Dist(gen), z0V + z0Dist(gen), phiDist(gen), + thetaDist(gen), q / pTDist(gen); + + // Fill vector of track objects with simple covariance matrix + std::unique_ptr<ActsSymMatrixD<5>> covMat = + std::make_unique<ActsSymMatrixD<5>>(); + + // Resolutions + double resD0 = resIPDist(gen); + double resZ0 = resIPDist(gen); + double resPh = resAngDist(gen); + double resTh = resAngDist(gen); + double resQp = resQoPDist(gen); + + (*covMat) << resD0 * resD0, 0., 0., 0., 0., 0., resZ0 * resZ0, 0., 0., 0., + 0., 0., resPh * resPh, 0., 0., 0., 0., 0., resTh * resTh, 0., 0., 0., + 0., 0., resQp * resQp; + tracks.push_back(BoundParameters(tgContext, std::move(covMat), paramVec, + perigeeSurface)); + } - VertexFitterOptions<BoundParameters> vfOptions( - tgContext, mfContext, myConstraint); + // Do the actual fit with 4 tracks without constraint + Vertex<BoundParameters> fittedVertex = + billoirFitter.fit(tracks, vfOptions).value(); + if (fittedVertex.tracks().size() > 0) { + CHECK_CLOSE_ABS(fittedVertex.position(), vertexPosition, 1 * units::_mm); + } + // Do the fit with a constraint + Vertex<BoundParameters> fittedVertexConstraint = + billoirFitter.fit(tracks, vfOptionsConstr).value(); + if (fittedVertexConstraint.tracks().size() > 0) { + CHECK_CLOSE_ABS(fittedVertexConstraint.position(), vertexPosition, + 1 * units::_mm); + } + // Test the IVertexFitter interface + Vertex<BoundParameters> testVertex = + myFitWrapper(&billoirFitter, tracks, vfOptions); + if (testVertex.tracks().size() > 0) { + CHECK_CLOSE_ABS(testVertex.position(), vertexPosition, 1 * units::_mm); + } - Vertex<BoundParameters> fittedVertex - = billoirFitter.fit(emptyVector, vfOptions).value(); + if (debugMode) { + std::cout << "Fitting nTracks: " << nTracks << std::endl; + std::cout << "True Vertex: " << x << ", " << y << ", " << z << std::endl; + std::cout << "Fitted Vertex: " << fittedVertex.position() << std::endl; + std::cout << "Fitted constraint Vertex: " + << fittedVertexConstraint.position() << std::endl; + } + } +} - Vector3D origin(0., 0., 0.); - BOOST_CHECK_EQUAL(fittedVertex.position(), origin); +// Dummy user-defined InputTrack type +struct InputTrack { + InputTrack(const BoundParameters& params) : m_parameters(params) {} - ActsSymMatrixD<3> zeroMat = ActsSymMatrixD<3>::Zero(); - BOOST_CHECK_EQUAL(fittedVertex.covariance(), zeroMat); + const BoundParameters& parameters() const { return m_parameters; } - fittedVertex = billoirFitter.fit(emptyVector, vfOptions).value(); + // store e.g. link to original objects here - BOOST_CHECK_EQUAL(fittedVertex.position(), origin); - BOOST_CHECK_EQUAL(fittedVertex.covariance(), zeroMat); - } + private: + BoundParameters m_parameters; +}; - // Vertex x/y position distribution - std::uniform_real_distribution<> vXYDist(-0.1 * units::_mm, 0.1 * units::_mm); - // Vertex z position distribution - std::uniform_real_distribution<> vZDist(-20 * units::_mm, 20 * units::_mm); - // Track d0 distribution - std::uniform_real_distribution<> d0Dist(-0.01 * units::_mm, - 0.01 * units::_mm); - // Track z0 distribution - std::uniform_real_distribution<> z0Dist(-0.2 * units::_mm, 0.2 * units::_mm); - // Track pT distribution - std::uniform_real_distribution<> pTDist(0.4 * units::_GeV, 10. * units::_GeV); - // Track phi distribution - std::uniform_real_distribution<> phiDist(-M_PI, M_PI); - // Track theta distribution - std::uniform_real_distribution<> thetaDist(1.0, M_PI - 1.0); - // Track charge helper distribution - std::uniform_real_distribution<> qDist(-1, 1); - // Track IP resolution distribution - std::uniform_real_distribution<> resIPDist(0., 100. * units::_um); - // Track angular distribution - std::uniform_real_distribution<> resAngDist(0., 0.1); - // Track q/p resolution distribution - std::uniform_real_distribution<> resQoPDist(-0.1, 0.1); - // Number of tracks distritbution - std::uniform_int_distribution<> nTracksDist(3, 10); - - /// - /// @brief Unit test for FullBilloirVertexFitter - /// with default input track type (= BoundParameters) - /// - BOOST_AUTO_TEST_CASE(billoir_vertex_fitter_defaulttrack_test) - { - - bool debugMode = false; - - // Set up RNG - int mySeed = 31415; - std::mt19937 gen(mySeed); - - // Set up constant B-Field - ConstantBField bField(Vector3D(0., 0., 1.) * units::_T); - - // Set up Eigenstepper - EigenStepper<ConstantBField> stepper(bField); - - // Set up propagator with void navigator - Propagator<EigenStepper<ConstantBField>> propagator(stepper); - - // Number of events - const int nEvents = 10; - - for (int eventIdx = 0; eventIdx < nEvents; ++eventIdx) { - - // Number of tracks - unsigned int nTracks = nTracksDist(gen); - - // Set up Billoir Vertex Fitter - FullBilloirVertexFitter<ConstantBField, - BoundParameters, - Propagator<EigenStepper<ConstantBField>>>::Config - vertexFitterCfg(bField, propagator); - FullBilloirVertexFitter<ConstantBField, - BoundParameters, - Propagator<EigenStepper<ConstantBField>>> - billoirFitter(vertexFitterCfg); - - // Constraint for vertex fit - Vertex<BoundParameters> myConstraint; - // Some abitrary values - ActsSymMatrixD<3> myCovMat = ActsSymMatrixD<3>::Zero(); - myCovMat(0, 0) = 30.; - myCovMat(1, 1) = 30.; - myCovMat(2, 2) = 30.; - myConstraint.setCovariance(std::move(myCovMat)); - myConstraint.setPosition(Vector3D(0, 0, 0)); - - VertexFitterOptions<BoundParameters> vfOptions(tgContext, mfContext); - - VertexFitterOptions<BoundParameters> vfOptionsConstr( - tgContext, mfContext, myConstraint); - - // Create position of vertex and perigee surface - double x = vXYDist(gen); - double y = vXYDist(gen); - double z = vZDist(gen); - - Vector3D vertexPosition(x, y, z); - std::shared_ptr<PerigeeSurface> perigeeSurface - = Surface::makeShared<PerigeeSurface>(Vector3D(0., 0., 0.)); - - // Calculate d0 and z0 corresponding to vertex position - double d0V = sqrt(x * x + y * y); - double z0V = z; - - // Start constructing nTracks tracks in the following - std::vector<BoundParameters> tracks; - - // Construct random track emerging from vicinity of vertex position - // Vector to store track objects used for vertex fit - for (unsigned int iTrack = 0; iTrack < nTracks; iTrack++) { - // Construct positive or negative charge randomly - double q = qDist(gen) < 0 ? -1. : 1.; - - // Construct random track parameters - TrackParametersBase::ParVector_t paramVec; - paramVec << d0V + d0Dist(gen), z0V + z0Dist(gen), phiDist(gen), - thetaDist(gen), q / pTDist(gen); - - // Fill vector of track objects with simple covariance matrix - std::unique_ptr<ActsSymMatrixD<5>> covMat - = std::make_unique<ActsSymMatrixD<5>>(); - - // Resolutions - double resD0 = resIPDist(gen); - double resZ0 = resIPDist(gen); - double resPh = resAngDist(gen); - double resTh = resAngDist(gen); - double resQp = resQoPDist(gen); - - (*covMat) << resD0 * resD0, 0., 0., 0., 0., 0., resZ0 * resZ0, 0., 0., - 0., 0., 0., resPh * resPh, 0., 0., 0., 0., 0., resTh * resTh, 0., - 0., 0., 0., 0., resQp * resQp; - tracks.push_back(BoundParameters( - tgContext, std::move(covMat), paramVec, perigeeSurface)); - } - - // Do the actual fit with 4 tracks without constraint - Vertex<BoundParameters> fittedVertex - = billoirFitter.fit(tracks, vfOptions).value(); - if (fittedVertex.tracks().size() > 0) { - CHECK_CLOSE_ABS( - fittedVertex.position(), vertexPosition, 1 * units::_mm); - } - // Do the fit with a constraint - Vertex<BoundParameters> fittedVertexConstraint - = billoirFitter.fit(tracks, vfOptionsConstr).value(); - if (fittedVertexConstraint.tracks().size() > 0) { - CHECK_CLOSE_ABS( - fittedVertexConstraint.position(), vertexPosition, 1 * units::_mm); - } - // Test the IVertexFitter interface - Vertex<BoundParameters> testVertex - = myFitWrapper(&billoirFitter, tracks, vfOptions); - if (testVertex.tracks().size() > 0) { - CHECK_CLOSE_ABS(testVertex.position(), vertexPosition, 1 * units::_mm); - } - - if (debugMode) { - std::cout << "Fitting nTracks: " << nTracks << std::endl; - std::cout << "True Vertex: " << x << ", " << y << ", " << z - << std::endl; - std::cout << "Fitted Vertex: " << fittedVertex.position() << std::endl; - std::cout << "Fitted constraint Vertex: " - << fittedVertexConstraint.position() << std::endl; - } - } - } +/// +/// @brief Unit test for FullBilloirVertexFitter with user-defined InputTrack +/// type +/// +BOOST_AUTO_TEST_CASE(billoir_vertex_fitter_usertrack_test) { + bool debugMode = false; + + // Set up RNG + int mySeed = 31415; + std::mt19937 gen(mySeed); + + // Set up constant B-Field + ConstantBField bField(Vector3D(0., 0., 1.) * units::_T); + + // Set up Eigenstepper + EigenStepper<ConstantBField> stepper(bField); + + // Set up propagator with void navigator + Propagator<EigenStepper<ConstantBField>> propagator(stepper); - // Dummy user-defined InputTrack type - struct InputTrack - { - InputTrack(const BoundParameters& params) : m_parameters(params) {} + const int nEvents = 10; - const BoundParameters& - parameters() const - { - return m_parameters; + for (int eventIdx = 0; eventIdx < nEvents; ++eventIdx) { + unsigned int nTracks = nTracksDist(gen); + + // Create a custom std::function to extract BoundParameters from + // user-defined InputTrack + std::function<BoundParameters(InputTrack)> extractParameters = + [](InputTrack params) { return params.parameters(); }; + + // Set up Billoir Vertex Fitter + FullBilloirVertexFitter<ConstantBField, InputTrack, + Propagator<EigenStepper<ConstantBField>>>::Config + vertexFitterCfg(bField, propagator); + FullBilloirVertexFitter<ConstantBField, InputTrack, + Propagator<EigenStepper<ConstantBField>>> + billoirFitter(vertexFitterCfg, extractParameters); + + // Constraint for vertex fit + Vertex<InputTrack> myConstraint; + // Some abitrary values + ActsSymMatrixD<3> myCovMat = ActsSymMatrixD<3>::Zero(); + myCovMat(0, 0) = 30.; + myCovMat(1, 1) = 30.; + myCovMat(2, 2) = 30.; + myConstraint.setCovariance(std::move(myCovMat)); + myConstraint.setPosition(Vector3D(0, 0, 0)); + + VertexFitterOptions<InputTrack> vfOptions(tgContext, mfContext); + + VertexFitterOptions<InputTrack> vfOptionsConstr(tgContext, mfContext, + myConstraint); + + // Create position of vertex and perigee surface + double x = vXYDist(gen); + double y = vXYDist(gen); + double z = vZDist(gen); + + Vector3D vertexPosition(x, y, z); + std::shared_ptr<PerigeeSurface> perigeeSurface = + Surface::makeShared<PerigeeSurface>(Vector3D(0., 0., 0.)); + + // Calculate d0 and z0 corresponding to vertex position + double d0V = sqrt(x * x + y * y); + double z0V = z; + + // Start constructing nTracks tracks in the following + std::vector<InputTrack> tracks; + + // Construct random track emerging from vicinity of vertex position + // Vector to store track objects used for vertex fit + for (unsigned int iTrack = 0; iTrack < nTracks; iTrack++) { + // Construct positive or negative charge randomly + double q = qDist(gen) < 0 ? -1. : 1.; + + // Construct random track parameters + TrackParametersBase::ParVector_t paramVec; + paramVec << d0V + d0Dist(gen), z0V + z0Dist(gen), phiDist(gen), + thetaDist(gen), q / pTDist(gen); + + // Fill vector of track objects with simple covariance matrix + std::unique_ptr<ActsSymMatrixD<5>> covMat = + std::make_unique<ActsSymMatrixD<5>>(); + + // Resolutions + double resD0 = resIPDist(gen); + double resZ0 = resIPDist(gen); + double resPh = resAngDist(gen); + double resTh = resAngDist(gen); + double resQp = resQoPDist(gen); + + (*covMat) << resD0 * resD0, 0., 0., 0., 0., 0., resZ0 * resZ0, 0., 0., 0., + 0., 0., resPh * resPh, 0., 0., 0., 0., 0., resTh * resTh, 0., 0., 0., + 0., 0., resQp * resQp; + tracks.push_back(InputTrack(BoundParameters(tgContext, std::move(covMat), + paramVec, perigeeSurface))); } - // store e.g. link to original objects here + // Do the actual fit with 4 tracks without constraint + Vertex<InputTrack> fittedVertex = + billoirFitter.fit(tracks, vfOptions).value(); + if (fittedVertex.tracks().size() > 0) { + CHECK_CLOSE_ABS(fittedVertex.position(), vertexPosition, 1 * units::_mm); + } + // Do the fit with a constraint + Vertex<InputTrack> fittedVertexConstraint = + billoirFitter.fit(tracks, vfOptionsConstr).value(); + if (fittedVertexConstraint.tracks().size() > 0) { + CHECK_CLOSE_ABS(fittedVertexConstraint.position(), vertexPosition, + 1 * units::_mm); + } - private: - BoundParameters m_parameters; - }; - - /// - /// @brief Unit test for FullBilloirVertexFitter with user-defined InputTrack - /// type - /// - BOOST_AUTO_TEST_CASE(billoir_vertex_fitter_usertrack_test) - { - - bool debugMode = false; - - // Set up RNG - int mySeed = 31415; - std::mt19937 gen(mySeed); - - // Set up constant B-Field - ConstantBField bField(Vector3D(0., 0., 1.) * units::_T); - - // Set up Eigenstepper - EigenStepper<ConstantBField> stepper(bField); - - // Set up propagator with void navigator - Propagator<EigenStepper<ConstantBField>> propagator(stepper); - - const int nEvents = 10; - - for (int eventIdx = 0; eventIdx < nEvents; ++eventIdx) { - - unsigned int nTracks = nTracksDist(gen); - - // Create a custom std::function to extract BoundParameters from - // user-defined InputTrack - std::function<BoundParameters(InputTrack)> extractParameters - = [](InputTrack params) { return params.parameters(); }; - - // Set up Billoir Vertex Fitter - FullBilloirVertexFitter<ConstantBField, - InputTrack, - Propagator<EigenStepper<ConstantBField>>>::Config - vertexFitterCfg(bField, propagator); - FullBilloirVertexFitter<ConstantBField, - InputTrack, - Propagator<EigenStepper<ConstantBField>>> - billoirFitter(vertexFitterCfg, extractParameters); - - // Constraint for vertex fit - Vertex<InputTrack> myConstraint; - // Some abitrary values - ActsSymMatrixD<3> myCovMat = ActsSymMatrixD<3>::Zero(); - myCovMat(0, 0) = 30.; - myCovMat(1, 1) = 30.; - myCovMat(2, 2) = 30.; - myConstraint.setCovariance(std::move(myCovMat)); - myConstraint.setPosition(Vector3D(0, 0, 0)); - - VertexFitterOptions<InputTrack> vfOptions(tgContext, mfContext); - - VertexFitterOptions<InputTrack> vfOptionsConstr( - tgContext, mfContext, myConstraint); - - // Create position of vertex and perigee surface - double x = vXYDist(gen); - double y = vXYDist(gen); - double z = vZDist(gen); - - Vector3D vertexPosition(x, y, z); - std::shared_ptr<PerigeeSurface> perigeeSurface - = Surface::makeShared<PerigeeSurface>(Vector3D(0., 0., 0.)); - - // Calculate d0 and z0 corresponding to vertex position - double d0V = sqrt(x * x + y * y); - double z0V = z; - - // Start constructing nTracks tracks in the following - std::vector<InputTrack> tracks; - - // Construct random track emerging from vicinity of vertex position - // Vector to store track objects used for vertex fit - for (unsigned int iTrack = 0; iTrack < nTracks; iTrack++) { - // Construct positive or negative charge randomly - double q = qDist(gen) < 0 ? -1. : 1.; - - // Construct random track parameters - TrackParametersBase::ParVector_t paramVec; - paramVec << d0V + d0Dist(gen), z0V + z0Dist(gen), phiDist(gen), - thetaDist(gen), q / pTDist(gen); - - // Fill vector of track objects with simple covariance matrix - std::unique_ptr<ActsSymMatrixD<5>> covMat - = std::make_unique<ActsSymMatrixD<5>>(); - - // Resolutions - double resD0 = resIPDist(gen); - double resZ0 = resIPDist(gen); - double resPh = resAngDist(gen); - double resTh = resAngDist(gen); - double resQp = resQoPDist(gen); - - (*covMat) << resD0 * resD0, 0., 0., 0., 0., 0., resZ0 * resZ0, 0., 0., - 0., 0., 0., resPh * resPh, 0., 0., 0., 0., 0., resTh * resTh, 0., - 0., 0., 0., 0., resQp * resQp; - tracks.push_back(InputTrack(BoundParameters( - tgContext, std::move(covMat), paramVec, perigeeSurface))); - } - - // Do the actual fit with 4 tracks without constraint - Vertex<InputTrack> fittedVertex - = billoirFitter.fit(tracks, vfOptions).value(); - if (fittedVertex.tracks().size() > 0) { - CHECK_CLOSE_ABS( - fittedVertex.position(), vertexPosition, 1 * units::_mm); - } - // Do the fit with a constraint - Vertex<InputTrack> fittedVertexConstraint - = billoirFitter.fit(tracks, vfOptionsConstr).value(); - if (fittedVertexConstraint.tracks().size() > 0) { - CHECK_CLOSE_ABS( - fittedVertexConstraint.position(), vertexPosition, 1 * units::_mm); - } - - // Test the IVertexFitter interface - Vertex<InputTrack> testVertex - = myFitWrapper(&billoirFitter, tracks, vfOptions); + // Test the IVertexFitter interface + Vertex<InputTrack> testVertex = + myFitWrapper(&billoirFitter, tracks, vfOptions); - CHECK_CLOSE_ABS(testVertex.position(), vertexPosition, 1 * units::_mm); + CHECK_CLOSE_ABS(testVertex.position(), vertexPosition, 1 * units::_mm); - if (debugMode) { - std::cout << "Fitting nTracks: " << nTracks << std::endl; - std::cout << "True Vertex: " << x << ", " << y << ", " << z - << std::endl; - std::cout << "Fitted Vertex: " << fittedVertex.position() << std::endl; - std::cout << "Fitted constraint Vertex: " - << fittedVertexConstraint.position() << std::endl; - } + if (debugMode) { + std::cout << "Fitting nTracks: " << nTracks << std::endl; + std::cout << "True Vertex: " << x << ", " << y << ", " << z << std::endl; + std::cout << "Fitted Vertex: " << fittedVertex.position() << std::endl; + std::cout << "Fitted constraint Vertex: " + << fittedVertexConstraint.position() << std::endl; } } +} } // namespace Test } // namespace Acts diff --git a/Tests/Core/Vertexing/LinearizedTrackFactoryTests.cpp b/Tests/Core/Vertexing/LinearizedTrackFactoryTests.cpp index 6ff093bdc711c2c9469c0ff572558bc2b7cc2994..c236bc72b5365081ec9344fd1b09eea53cbc8a87 100644 --- a/Tests/Core/Vertexing/LinearizedTrackFactoryTests.cpp +++ b/Tests/Core/Vertexing/LinearizedTrackFactoryTests.cpp @@ -29,168 +29,160 @@ namespace bdata = boost::unit_test::data; namespace Acts { namespace Test { - // Create a test context - GeometryContext tgContext = GeometryContext(); - MagneticFieldContext mfContext = MagneticFieldContext(); - - // Vertex x/y position distribution - std::uniform_real_distribution<> vXYDist(-0.1 * units::_mm, 0.1 * units::_mm); - // Vertex z position distribution - std::uniform_real_distribution<> vZDist(-20 * units::_mm, 20 * units::_mm); - // Track d0 distribution - std::uniform_real_distribution<> d0Dist(-0.01 * units::_mm, - 0.01 * units::_mm); - // Track z0 distribution - std::uniform_real_distribution<> z0Dist(-0.2 * units::_mm, 0.2 * units::_mm); - // Track pT distribution - std::uniform_real_distribution<> pTDist(0.4 * units::_GeV, 10. * units::_GeV); - // Track phi distribution - std::uniform_real_distribution<> phiDist(-M_PI, M_PI); - // Track theta distribution - std::uniform_real_distribution<> thetaDist(1.0, M_PI - 1.0); - // Track charge helper distribution - std::uniform_real_distribution<> qDist(-1, 1); - // Track IP resolution distribution - std::uniform_real_distribution<> resIPDist(0., 100. * units::_um); - // Track angular distribution - std::uniform_real_distribution<> resAngDist(0., 0.1); - // Track q/p resolution distribution - std::uniform_real_distribution<> resQoPDist(-0.1, 0.1); - - /// - /// @brief Unit test for LinearizedTrackFactory - /// - BOOST_AUTO_TEST_CASE(linearized_track_factory_test) - { - - // Number of tracks - unsigned int nTracks = 100; - - // Set up RNG - int mySeed = 31415; - std::mt19937 gen(mySeed); - - // Set up constant B-Field - ConstantBField bField(Vector3D(0., 0., 1.) * units::_T); - - // Set up Eigenstepper - EigenStepper<ConstantBField> stepper(bField); - - // Set up propagator with void navigator - Propagator<EigenStepper<ConstantBField>> propagator(stepper); - - // Create perigee surface - std::shared_ptr<PerigeeSurface> perigeeSurface - = Surface::makeShared<PerigeeSurface>(Vector3D(0., 0., 0.)); - - // Create position of vertex and perigee surface - double x = vXYDist(gen); - double y = vXYDist(gen); - double z = vZDist(gen); - - // Calculate d0 and z0 corresponding to vertex position - double d0v = sqrt(x * x + y * y); - double z0v = z; - - // Start constructing nTracks tracks in the following - std::vector<BoundParameters> tracks; - - // Construct random track emerging from vicinity of vertex position - // Vector to store track objects used for vertex fit - for (unsigned int iTrack = 0; iTrack < nTracks; iTrack++) { - // Construct positive or negative charge randomly - double q = qDist(gen) < 0 ? -1. : 1.; - - // Construct random track parameters - TrackParametersBase::ParVector_t paramVec; - paramVec << d0v + d0Dist(gen), z0v + z0Dist(gen), phiDist(gen), - thetaDist(gen), q / pTDist(gen); - - // Fill vector of track objects with simple covariance matrix - std::unique_ptr<ActsSymMatrixD<5>> covMat - = std::make_unique<ActsSymMatrixD<5>>(); - - // Resolutions - double resD0 = resIPDist(gen); - double resZ0 = resIPDist(gen); - double resPh = resAngDist(gen); - double resTh = resAngDist(gen); - double resQp = resQoPDist(gen); - - (*covMat) << resD0 * resD0, 0., 0., 0., 0., 0., resZ0 * resZ0, 0., 0., 0., - 0., 0., resPh * resPh, 0., 0., 0., 0., 0., resTh * resTh, 0., 0., 0., - 0., 0., resQp * resQp; - tracks.push_back(BoundParameters( - tgContext, std::move(covMat), paramVec, perigeeSurface)); - } - - LinearizedTrackFactory<ConstantBField, - Propagator<EigenStepper<ConstantBField>>>::Config - ltConfig(bField); - LinearizedTrackFactory<ConstantBField, - Propagator<EigenStepper<ConstantBField>>> - linFactory(ltConfig); - - ActsVectorD<5> vec5Zero = ActsVectorD<5>::Zero(); - ActsSymMatrixD<5> mat5Zero = ActsSymMatrixD<5>::Zero(); - Vector3D vec3Zero = Vector3D::Zero(); - ActsMatrixD<5, 3> mat53Zero = ActsMatrixD<5, 3>::Zero(); - - for (const BoundParameters& parameters : tracks) { - LinearizedTrack linTrack = linFactory - .linearizeTrack(tgContext, - mfContext, - ¶meters, - Vector3D(0., 0., 0.), - propagator) - .value(); - - BOOST_CHECK_NE(linTrack.parametersAtPCA, vec5Zero); - BOOST_CHECK_NE(linTrack.covarianceAtPCA, mat5Zero); - BOOST_CHECK_EQUAL(linTrack.linearizationPoint, vec3Zero); - BOOST_CHECK_NE(linTrack.positionJacobian, mat53Zero); - BOOST_CHECK_NE(linTrack.momentumJacobian, mat53Zero); - BOOST_CHECK_NE(linTrack.constantTerm, vec5Zero); - } +// Create a test context +GeometryContext tgContext = GeometryContext(); +MagneticFieldContext mfContext = MagneticFieldContext(); + +// Vertex x/y position distribution +std::uniform_real_distribution<> vXYDist(-0.1 * units::_mm, 0.1 * units::_mm); +// Vertex z position distribution +std::uniform_real_distribution<> vZDist(-20 * units::_mm, 20 * units::_mm); +// Track d0 distribution +std::uniform_real_distribution<> d0Dist(-0.01 * units::_mm, 0.01 * units::_mm); +// Track z0 distribution +std::uniform_real_distribution<> z0Dist(-0.2 * units::_mm, 0.2 * units::_mm); +// Track pT distribution +std::uniform_real_distribution<> pTDist(0.4 * units::_GeV, 10. * units::_GeV); +// Track phi distribution +std::uniform_real_distribution<> phiDist(-M_PI, M_PI); +// Track theta distribution +std::uniform_real_distribution<> thetaDist(1.0, M_PI - 1.0); +// Track charge helper distribution +std::uniform_real_distribution<> qDist(-1, 1); +// Track IP resolution distribution +std::uniform_real_distribution<> resIPDist(0., 100. * units::_um); +// Track angular distribution +std::uniform_real_distribution<> resAngDist(0., 0.1); +// Track q/p resolution distribution +std::uniform_real_distribution<> resQoPDist(-0.1, 0.1); + +/// +/// @brief Unit test for LinearizedTrackFactory +/// +BOOST_AUTO_TEST_CASE(linearized_track_factory_test) { + // Number of tracks + unsigned int nTracks = 100; + + // Set up RNG + int mySeed = 31415; + std::mt19937 gen(mySeed); + + // Set up constant B-Field + ConstantBField bField(Vector3D(0., 0., 1.) * units::_T); + + // Set up Eigenstepper + EigenStepper<ConstantBField> stepper(bField); + + // Set up propagator with void navigator + Propagator<EigenStepper<ConstantBField>> propagator(stepper); + + // Create perigee surface + std::shared_ptr<PerigeeSurface> perigeeSurface = + Surface::makeShared<PerigeeSurface>(Vector3D(0., 0., 0.)); + + // Create position of vertex and perigee surface + double x = vXYDist(gen); + double y = vXYDist(gen); + double z = vZDist(gen); + + // Calculate d0 and z0 corresponding to vertex position + double d0v = sqrt(x * x + y * y); + double z0v = z; + + // Start constructing nTracks tracks in the following + std::vector<BoundParameters> tracks; + + // Construct random track emerging from vicinity of vertex position + // Vector to store track objects used for vertex fit + for (unsigned int iTrack = 0; iTrack < nTracks; iTrack++) { + // Construct positive or negative charge randomly + double q = qDist(gen) < 0 ? -1. : 1.; + + // Construct random track parameters + TrackParametersBase::ParVector_t paramVec; + paramVec << d0v + d0Dist(gen), z0v + z0Dist(gen), phiDist(gen), + thetaDist(gen), q / pTDist(gen); + + // Fill vector of track objects with simple covariance matrix + std::unique_ptr<ActsSymMatrixD<5>> covMat = + std::make_unique<ActsSymMatrixD<5>>(); + + // Resolutions + double resD0 = resIPDist(gen); + double resZ0 = resIPDist(gen); + double resPh = resAngDist(gen); + double resTh = resAngDist(gen); + double resQp = resQoPDist(gen); + + (*covMat) << resD0 * resD0, 0., 0., 0., 0., 0., resZ0 * resZ0, 0., 0., 0., + 0., 0., resPh * resPh, 0., 0., 0., 0., 0., resTh * resTh, 0., 0., 0., + 0., 0., resQp * resQp; + tracks.push_back(BoundParameters(tgContext, std::move(covMat), paramVec, + perigeeSurface)); } - BOOST_AUTO_TEST_CASE(linearized_track_factory_empty_test) - { - ConstantBField bField(Vector3D(0., 0., 1.) * units::_T); - - // Set up Eigenstepper - EigenStepper<ConstantBField> stepper(bField); - - // Set up propagator with void navigator - Propagator<EigenStepper<ConstantBField>> propagator(stepper); - - LinearizedTrackFactory<ConstantBField, - Propagator<EigenStepper<ConstantBField>>>::Config - ltConfig(bField); - LinearizedTrackFactory<ConstantBField, - Propagator<EigenStepper<ConstantBField>>> - linFactory(ltConfig); - - ActsVectorD<5> vec5Zero = ActsVectorD<5>::Zero(); - ActsSymMatrixD<5> mat5Zero = ActsSymMatrixD<5>::Zero(); - Vector3D vec3Zero = Vector3D::Zero(); - ActsMatrixD<5, 3> mat53Zero = ActsMatrixD<5, 3>::Zero(); - - LinearizedTrack linTrack = linFactory - .linearizeTrack(tgContext, - mfContext, - nullptr, - Vector3D(1., 2., 3.), - propagator) - .value(); - - BOOST_CHECK_EQUAL(linTrack.parametersAtPCA, vec5Zero); - BOOST_CHECK_EQUAL(linTrack.covarianceAtPCA, mat5Zero); + LinearizedTrackFactory<ConstantBField, + Propagator<EigenStepper<ConstantBField>>>::Config + ltConfig(bField); + LinearizedTrackFactory<ConstantBField, + Propagator<EigenStepper<ConstantBField>>> + linFactory(ltConfig); + + ActsVectorD<5> vec5Zero = ActsVectorD<5>::Zero(); + ActsSymMatrixD<5> mat5Zero = ActsSymMatrixD<5>::Zero(); + Vector3D vec3Zero = Vector3D::Zero(); + ActsMatrixD<5, 3> mat53Zero = ActsMatrixD<5, 3>::Zero(); + + for (const BoundParameters& parameters : tracks) { + LinearizedTrack linTrack = + linFactory + .linearizeTrack(tgContext, mfContext, ¶meters, + Vector3D(0., 0., 0.), propagator) + .value(); + + BOOST_CHECK_NE(linTrack.parametersAtPCA, vec5Zero); + BOOST_CHECK_NE(linTrack.covarianceAtPCA, mat5Zero); BOOST_CHECK_EQUAL(linTrack.linearizationPoint, vec3Zero); - BOOST_CHECK_EQUAL(linTrack.positionJacobian, mat53Zero); - BOOST_CHECK_EQUAL(linTrack.momentumJacobian, mat53Zero); - BOOST_CHECK_EQUAL(linTrack.constantTerm, vec5Zero); + BOOST_CHECK_NE(linTrack.positionJacobian, mat53Zero); + BOOST_CHECK_NE(linTrack.momentumJacobian, mat53Zero); + BOOST_CHECK_NE(linTrack.constantTerm, vec5Zero); } +} + +BOOST_AUTO_TEST_CASE(linearized_track_factory_empty_test) { + ConstantBField bField(Vector3D(0., 0., 1.) * units::_T); + + // Set up Eigenstepper + EigenStepper<ConstantBField> stepper(bField); + + // Set up propagator with void navigator + Propagator<EigenStepper<ConstantBField>> propagator(stepper); + + LinearizedTrackFactory<ConstantBField, + Propagator<EigenStepper<ConstantBField>>>::Config + ltConfig(bField); + LinearizedTrackFactory<ConstantBField, + Propagator<EigenStepper<ConstantBField>>> + linFactory(ltConfig); + + ActsVectorD<5> vec5Zero = ActsVectorD<5>::Zero(); + ActsSymMatrixD<5> mat5Zero = ActsSymMatrixD<5>::Zero(); + Vector3D vec3Zero = Vector3D::Zero(); + ActsMatrixD<5, 3> mat53Zero = ActsMatrixD<5, 3>::Zero(); + + LinearizedTrack linTrack = + linFactory + .linearizeTrack(tgContext, mfContext, nullptr, Vector3D(1., 2., 3.), + propagator) + .value(); + + BOOST_CHECK_EQUAL(linTrack.parametersAtPCA, vec5Zero); + BOOST_CHECK_EQUAL(linTrack.covarianceAtPCA, mat5Zero); + BOOST_CHECK_EQUAL(linTrack.linearizationPoint, vec3Zero); + BOOST_CHECK_EQUAL(linTrack.positionJacobian, mat53Zero); + BOOST_CHECK_EQUAL(linTrack.momentumJacobian, mat53Zero); + BOOST_CHECK_EQUAL(linTrack.constantTerm, vec5Zero); +} } // namespace Test } // namespace Acts diff --git a/Tests/Examples/src/CustomDefaultLogger.cpp b/Tests/Examples/src/CustomDefaultLogger.cpp index 07119386e2e728d5d3a7a7669175f2b7eea45125..67b61e3985224f0146f1e5fbf02a562e32c9cc3d 100644 --- a/Tests/Examples/src/CustomDefaultLogger.cpp +++ b/Tests/Examples/src/CustomDefaultLogger.cpp @@ -14,42 +14,37 @@ namespace Acts { namespace Logging { - /// @brief mirror debug message +/// @brief mirror debug message +/// +/// This is just a fun example decorator which mirrors the debug message. +class MirrorOutputDecorator final : public OutputDecorator { + public: + /// @brief constructor /// - /// This is just a fun example decorator which mirrors the debug message. - class MirrorOutputDecorator final : public OutputDecorator - { - public: - /// @brief constructor - /// - /// @param [in] wrappee output print policy object to be wrapped - /// @param [in] maxWidth maximum width of field used for name - MirrorOutputDecorator(std::unique_ptr<OutputPrintPolicy> wrappee, - unsigned int maxWidth = 180) - : OutputDecorator(std::move(wrappee)), m_maxWidth(maxWidth) - { - } + /// @param [in] wrappee output print policy object to be wrapped + /// @param [in] maxWidth maximum width of field used for name + MirrorOutputDecorator(std::unique_ptr<OutputPrintPolicy> wrappee, + unsigned int maxWidth = 180) + : OutputDecorator(std::move(wrappee)), m_maxWidth(maxWidth) {} - /// @brief flush the debug message to the destination stream - /// - /// @param [in] lvl debug level of debug message - /// @param [in] input text of debug message - /// - /// This function inverts the given string and flushes it to the right. - void - flush(const Level& lvl, const std::ostringstream& input) override - { - std::ostringstream os; - std::string text = input.str(); - std::reverse(text.begin(), text.end()); - os << std::right << std::setw(m_maxWidth) << text; - OutputDecorator::flush(lvl, os); - } + /// @brief flush the debug message to the destination stream + /// + /// @param [in] lvl debug level of debug message + /// @param [in] input text of debug message + /// + /// This function inverts the given string and flushes it to the right. + void flush(const Level& lvl, const std::ostringstream& input) override { + std::ostringstream os; + std::string text = input.str(); + std::reverse(text.begin(), text.end()); + os << std::right << std::setw(m_maxWidth) << text; + OutputDecorator::flush(lvl, os); + } - private: - /// maximum width of field for printing the name - unsigned int m_maxWidth; - }; + private: + /// maximum width of field for printing the name + unsigned int m_maxWidth; +}; } // namespace Logging @@ -64,11 +59,9 @@ namespace Logging { /// from right to left. /// /// @return pointer to logging instance -std::unique_ptr<const Logger> -getDefaultLogger(const std::string& name, - const Logging::Level& lvl, - std::ostream* log_stream) -{ +std::unique_ptr<const Logger> getDefaultLogger(const std::string& name, + const Logging::Level& lvl, + std::ostream* log_stream) { using namespace Logging; auto output = std::make_unique<LevelOutputDecorator>( std::make_unique<NamedOutputDecorator>( diff --git a/Tests/Integration/ATLSeedingIntegrationTest.cpp b/Tests/Integration/ATLSeedingIntegrationTest.cpp index 948b2f6722536071d92bea0abfa029c5af8935ab..a8703bf18b21a639fe55cff0007f73f1124af423 100644 --- a/Tests/Integration/ATLSeedingIntegrationTest.cpp +++ b/Tests/Integration/ATLSeedingIntegrationTest.cpp @@ -15,8 +15,7 @@ // space point structure with the bare minimum and reasonable default // covariances. clusterList default is SCT (strip detector) -struct SpacePoint -{ +struct SpacePoint { float x; float y; float z; @@ -24,30 +23,22 @@ struct SpacePoint float covr = 0.03; float covz = 0.03; std::pair<int, int> m_clusterList = std::pair<int, int>(1, 1); - void - setClusterList(int first, int second) - { + void setClusterList(int first, int second) { m_clusterList = std::pair<int, int>(first, second); } - const std::pair<int, int> - clusterList() const - { - return m_clusterList; - } + const std::pair<int, int> clusterList() const { return m_clusterList; } int surface; }; // call sequence to create seeds. Seeds are copied as the // call to next() overwrites the previous seed object -std::vector<Acts::Legacy::Seed<SpacePoint>> -runSeeding(std::vector<SpacePoint*> spVec) -{ - +std::vector<Acts::Legacy::Seed<SpacePoint>> runSeeding( + std::vector<SpacePoint*> spVec) { Acts::Legacy::AtlasSeedfinder<SpacePoint> seedMaker; seedMaker.newEvent(0, spVec.begin(), spVec.end()); seedMaker.find3Sp(); - const Acts::Legacy::Seed<SpacePoint>* seed = seedMaker.next(); - int numSeeds = 0; + const Acts::Legacy::Seed<SpacePoint>* seed = seedMaker.next(); + int numSeeds = 0; std::vector<Acts::Legacy::Seed<SpacePoint>> seedVec; while (seed != 0) { numSeeds++; @@ -61,13 +52,10 @@ runSeeding(std::vector<SpacePoint*> spVec) } // used to sort seeds, ignores z -class seedComparator -{ -public: - bool - operator()(const Acts::Legacy::Seed<SpacePoint>& s1, - const Acts::Legacy::Seed<SpacePoint>& s2) - { +class seedComparator { + public: + bool operator()(const Acts::Legacy::Seed<SpacePoint>& s1, + const Acts::Legacy::Seed<SpacePoint>& s2) { auto sp1It = s1.spacePoints().begin(); auto sp2It = s2.spacePoints().begin(); for (int i = 0; i < 3; i++) { @@ -81,11 +69,10 @@ public: } }; -BOOST_AUTO_TEST_CASE(number_of_seeds_correct_) -{ +BOOST_AUTO_TEST_CASE(number_of_seeds_correct_) { // single particle event with 405MeV (just above default pT-cut) std::vector<SpacePoint*> spVec; - std::vector<int> layerVec{1, 2, 2, 3, 4, 11, 13, 14}; + std::vector<int> layerVec{1, 2, 2, 3, 4, 11, 13, 14}; // clang-format off std::vector<float> xVec{-33.3403, -48.2369, @@ -119,11 +106,11 @@ BOOST_AUTO_TEST_CASE(number_of_seeds_correct_) // the detector region of the pixel detector for (unsigned int i = 0; i < layerVec.size(); i++) { SpacePoint* sp = new SpacePoint(); - sp->surface = layerVec.at(i); - sp->x = xVec.at(i); - sp->y = yVec.at(i); - sp->z = zVec.at(i); - sp->r = std::sqrt(sp->x * sp->x + sp->y * sp->y); + sp->surface = layerVec.at(i); + sp->x = xVec.at(i); + sp->y = yVec.at(i); + sp->z = zVec.at(i); + sp->r = std::sqrt(sp->x * sp->x + sp->y * sp->y); if (sp->r < 200.) { sp->setClusterList(1, 0); } @@ -159,11 +146,8 @@ BOOST_AUTO_TEST_CASE(number_of_seeds_correct_) // difference between reference and result shows if results exactly the same // (i.e. difference is 0) std::vector<Acts::Legacy::Seed<SpacePoint>> diff; - std::set_difference(refVec.begin(), - refVec.end(), - seedVec.begin(), - seedVec.end(), - std::inserter(diff, diff.begin()), + std::set_difference(refVec.begin(), refVec.end(), seedVec.begin(), + seedVec.end(), std::inserter(diff, diff.begin()), seedComparator()); BOOST_CHECK(diff.empty()); for (auto sp : spVec) { diff --git a/Tests/Integration/InterpolatedSolenoidBFieldTest.cpp b/Tests/Integration/InterpolatedSolenoidBFieldTest.cpp index 8d4cc3a577056513245ccc9abc7331d6c5f0c7dc..2d986619995aeadc6fa3fe0076f9af9bf00ca265 100644 --- a/Tests/Integration/InterpolatedSolenoidBFieldTest.cpp +++ b/Tests/Integration/InterpolatedSolenoidBFieldTest.cpp @@ -27,129 +27,116 @@ #include "Acts/Utilities/detail/Axis.hpp" #include "Acts/Utilities/detail/Grid.hpp" -using Acts::VectorHelpers::phi; using Acts::VectorHelpers::perp; +using Acts::VectorHelpers::phi; namespace bdata = boost::unit_test::data; -namespace tt = boost::test_tools; +namespace tt = boost::test_tools; namespace Acts { namespace IntegrationTest { - const double L = 5.8 * Acts::units::_m; - const double R = (2.56 + 2.46) * 0.5 * 0.5 * Acts::units::_m; - const size_t nCoils = 1154; - const double bMagCenter = 2. * Acts::units::_T; - const size_t nBinsR = 150; - const size_t nBinsZ = 200; - - auto - makeFieldMap(const SolenoidBField& field) - { - - std::ofstream ostr("solenoidmap.csv"); - ostr << "i;j;r;z;B_r;B_z" << std::endl; - - double rMin = 0; - double rMax = R * 2.; - double zMin = 2 * (-L / 2.); - double zMax = 2 * (L / 2.); - - std::cout << "rMin = " << rMin << std::endl; - std::cout << "rMax = " << rMax << std::endl; - std::cout << "zMin = " << zMin << std::endl; - std::cout << "zMax = " << zMax << std::endl; - - auto mapper = solenoidFieldMapper( - {rMin, rMax}, {zMin, zMax}, {nBinsR, nBinsZ}, field); - // I know this is the correct grid type - using Grid_t = Acts::detail::Grid<Acts::Vector2D, - Acts::detail::EquidistantAxis, - Acts::detail::EquidistantAxis>; - const Grid_t& grid = mapper.getGrid(); - using index_t = Grid_t::index_t; - using point_t = Grid_t::point_t; - using BField_t = Acts::InterpolatedBFieldMap<decltype(mapper)>; - - for (size_t i = 0; i <= nBinsR + 1; i++) { - for (size_t j = 0; j <= nBinsZ + 1; j++) { - // std::cout << "(i,j) = " << i << "," << j << std::endl; - index_t index({i, j}); - if (i == 0 || j == 0 || i == nBinsR + 1 || j == nBinsZ + 1) { - // under or overflow bin - } else { - point_t lowerLeft = grid.lowerLeftBinEdge(index); - Vector2D B = grid.atLocalBins(index); - ostr << i << ";" << j << ";" << lowerLeft[0] << ";" << lowerLeft[1]; - ostr << ";" << B[0] << ";" << B[1] << std::endl; - } +const double L = 5.8 * Acts::units::_m; +const double R = (2.56 + 2.46) * 0.5 * 0.5 * Acts::units::_m; +const size_t nCoils = 1154; +const double bMagCenter = 2. * Acts::units::_T; +const size_t nBinsR = 150; +const size_t nBinsZ = 200; + +auto makeFieldMap(const SolenoidBField& field) { + std::ofstream ostr("solenoidmap.csv"); + ostr << "i;j;r;z;B_r;B_z" << std::endl; + + double rMin = 0; + double rMax = R * 2.; + double zMin = 2 * (-L / 2.); + double zMax = 2 * (L / 2.); + + std::cout << "rMin = " << rMin << std::endl; + std::cout << "rMax = " << rMax << std::endl; + std::cout << "zMin = " << zMin << std::endl; + std::cout << "zMax = " << zMax << std::endl; + + auto mapper = + solenoidFieldMapper({rMin, rMax}, {zMin, zMax}, {nBinsR, nBinsZ}, field); + // I know this is the correct grid type + using Grid_t = + Acts::detail::Grid<Acts::Vector2D, Acts::detail::EquidistantAxis, + Acts::detail::EquidistantAxis>; + const Grid_t& grid = mapper.getGrid(); + using index_t = Grid_t::index_t; + using point_t = Grid_t::point_t; + using BField_t = Acts::InterpolatedBFieldMap<decltype(mapper)>; + + for (size_t i = 0; i <= nBinsR + 1; i++) { + for (size_t j = 0; j <= nBinsZ + 1; j++) { + // std::cout << "(i,j) = " << i << "," << j << std::endl; + index_t index({i, j}); + if (i == 0 || j == 0 || i == nBinsR + 1 || j == nBinsZ + 1) { + // under or overflow bin + } else { + point_t lowerLeft = grid.lowerLeftBinEdge(index); + Vector2D B = grid.atLocalBins(index); + ostr << i << ";" << j << ";" << lowerLeft[0] << ";" << lowerLeft[1]; + ostr << ";" << B[0] << ";" << B[1] << std::endl; } } - - BField_t::Config cfg(std::move(mapper)); - return BField_t(std::move(cfg)); } - Acts::SolenoidBField bSolenoidField({R, L, nCoils, bMagCenter}); - auto bFieldMap = makeFieldMap(bSolenoidField); + BField_t::Config cfg(std::move(mapper)); + return BField_t(std::move(cfg)); +} - struct StreamWrapper - { - StreamWrapper(std::ofstream ofstr) : m_ofstr(std::move(ofstr)) - { - m_ofstr << "x;y;z;B_x;B_y;B_z;Bm_x;Bm_y;Bm_z" << std::endl; - } +Acts::SolenoidBField bSolenoidField({R, L, nCoils, bMagCenter}); +auto bFieldMap = makeFieldMap(bSolenoidField); - std::ofstream m_ofstr; - }; - - StreamWrapper valid(std::ofstream("magfield_lookup.csv")); - - const int ntests = 10000; - BOOST_DATA_TEST_CASE( - solenoid_interpolated_bfield_comparison, - bdata::random((bdata::seed = 1, - bdata::engine = std::mt19937(), - bdata::distribution - = std::uniform_real_distribution<>(1.5 * (-L / 2.), - 1.5 * L / 2.))) - ^ bdata::random((bdata::seed = 2, - bdata::engine = std::mt19937(), - bdata::distribution - = std::uniform_real_distribution<>(0, R * 1.5))) - ^ bdata::random((bdata::seed = 3, - bdata::engine = std::mt19937(), - bdata::distribution - = std::uniform_real_distribution<>(-M_PI, M_PI))) - ^ bdata::xrange(ntests), - z, - r, - phi, - index) - { - (void)index; - if (index % 1000 == 0) { - std::cout << index << std::endl; - } +struct StreamWrapper { + StreamWrapper(std::ofstream ofstr) : m_ofstr(std::move(ofstr)) { + m_ofstr << "x;y;z;B_x;B_y;B_z;Bm_x;Bm_y;Bm_z" << std::endl; + } - Vector3D pos(r * std::cos(phi), r * std::sin(phi), z); - Vector3D B = bSolenoidField.getField(pos) / Acts::units::_T; - Vector3D Bm = bFieldMap.getField(pos) / Acts::units::_T; + std::ofstream m_ofstr; +}; + +StreamWrapper valid(std::ofstream("magfield_lookup.csv")); + +const int ntests = 10000; +BOOST_DATA_TEST_CASE( + solenoid_interpolated_bfield_comparison, + bdata::random((bdata::seed = 1, bdata::engine = std::mt19937(), + bdata::distribution = std::uniform_real_distribution<>( + 1.5 * (-L / 2.), 1.5 * L / 2.))) ^ + bdata::random((bdata::seed = 2, bdata::engine = std::mt19937(), + bdata::distribution = + std::uniform_real_distribution<>(0, R * 1.5))) ^ + bdata::random((bdata::seed = 3, bdata::engine = std::mt19937(), + bdata::distribution = + std::uniform_real_distribution<>(-M_PI, M_PI))) ^ + bdata::xrange(ntests), + z, r, phi, index) { + (void)index; + if (index % 1000 == 0) { + std::cout << index << std::endl; + } - // test less than 5% deviation - if (std::abs(r - R) > 10 && (std::abs(z) < L / 3. || r > 20)) { - // only if more than 10mm away from coil for all z - // only if not close to r=0 for large z - CHECK_CLOSE_REL(Bm.norm(), B.norm(), 0.05); - } + Vector3D pos(r * std::cos(phi), r * std::sin(phi), z); + Vector3D B = bSolenoidField.getField(pos) / Acts::units::_T; + Vector3D Bm = bFieldMap.getField(pos) / Acts::units::_T; - std::ofstream& ofstr = valid.m_ofstr; - ofstr << pos.x() << ";" << pos.y() << ";" << pos.z() << ";"; - ofstr << B.x() << ";" << B.y() << ";" << B.z() << ";"; - ofstr << Bm.x() << ";" << Bm.y() << ";" << Bm.z() << std::endl; + // test less than 5% deviation + if (std::abs(r - R) > 10 && (std::abs(z) < L / 3. || r > 20)) { + // only if more than 10mm away from coil for all z + // only if not close to r=0 for large z + CHECK_CLOSE_REL(Bm.norm(), B.norm(), 0.05); } + std::ofstream& ofstr = valid.m_ofstr; + ofstr << pos.x() << ";" << pos.y() << ";" << pos.z() << ";"; + ofstr << B.x() << ";" << B.y() << ";" << B.z() << ";"; + ofstr << Bm.x() << ";" << Bm.y() << ";" << Bm.z() << std::endl; +} + } // namespace IntegrationTest } // namespace Acts diff --git a/Tests/Integration/PropagationTestBase.hpp b/Tests/Integration/PropagationTestBase.hpp index 18a4cab4bab2bc88d56bff385c0c738025e93a5c..35a1fff41ae855e14fd5ecaf7ac54dc244ab746c 100644 --- a/Tests/Integration/PropagationTestBase.hpp +++ b/Tests/Integration/PropagationTestBase.hpp @@ -23,29 +23,22 @@ BOOST_DATA_TEST_CASE( forward_backward_propagation_, bdata::random((bdata::seed = 0, - bdata::distribution - = std::uniform_real_distribution<>(0.4 * units::_GeV, - 10. * units::_GeV))) - ^ bdata::random((bdata::seed = 1, - bdata::distribution - = std::uniform_real_distribution<>(-M_PI, M_PI))) - ^ bdata::random((bdata::seed = 2, - bdata::distribution - = std::uniform_real_distribution<>(0.1, M_PI - 0.1))) - ^ bdata::random((bdata::seed = 3, - bdata::distribution - = std::uniform_int_distribution<>(0, 1))) - ^ bdata::random((bdata::seed = 4, - bdata::distribution - = std::uniform_real_distribution<>(0, 1. * units::_m))) - ^ bdata::xrange(ntests), - pT, - phi, - theta, - charge, - plimit, - index) -{ + bdata::distribution = std::uniform_real_distribution<>( + 0.4 * units::_GeV, 10. * units::_GeV))) ^ + bdata::random((bdata::seed = 1, + bdata::distribution = + std::uniform_real_distribution<>(-M_PI, M_PI))) ^ + bdata::random((bdata::seed = 2, + bdata::distribution = + std::uniform_real_distribution<>(0.1, M_PI - 0.1))) ^ + bdata::random( + (bdata::seed = 3, + bdata::distribution = std::uniform_int_distribution<>(0, 1))) ^ + bdata::random((bdata::seed = 4, + bdata::distribution = std::uniform_real_distribution<>( + 0, 1. * units::_m))) ^ + bdata::xrange(ntests), + pT, phi, theta, charge, plimit, index) { if (index < skip) { return; } @@ -53,68 +46,42 @@ BOOST_DATA_TEST_CASE( double dcharge = -1 + 2 * charge; // foward backward check atlas stepper - foward_backward(apropagator, - pT, - phi, - theta, - dcharge, - plimit, - index, - 1e-3, - Acts::units::_eV, - debug); + foward_backward(apropagator, pT, phi, theta, dcharge, plimit, index, 1e-3, + Acts::units::_eV, debug); // foward backward check eigen stepper - foward_backward(epropagator, - pT, - phi, - theta, - dcharge, - plimit, - index, - 1e-3, - Acts::units::_eV, - debug); + foward_backward(epropagator, pT, phi, theta, dcharge, plimit, index, 1e-3, + Acts::units::_eV, debug); } /// test consistency of propagators when approaching a cylinder BOOST_DATA_TEST_CASE( propagation_to_cylinder_, bdata::random((bdata::seed = 1010, - bdata::distribution - = std::uniform_real_distribution<>(0.4 * units::_GeV, - 10. * units::_GeV))) - ^ bdata::random((bdata::seed = 1111, - bdata::distribution - = std::uniform_real_distribution<>(-M_PI, M_PI))) - ^ bdata::random((bdata::seed = 1212, - bdata::distribution - = std::uniform_real_distribution<>(0.1, 0.9 * M_PI))) - ^ bdata::random((bdata::seed = 1313, - bdata::distribution - = std::uniform_int_distribution<>(0, 1))) - ^ bdata::random((bdata::seed = 1414, - bdata::distribution - = std::uniform_real_distribution<>(0.5, 1.))) - ^ bdata::random((bdata::seed = 1515, - bdata::distribution - = std::uniform_real_distribution<>(-1., 1.))) - ^ bdata::random((bdata::seed = 1616, - bdata::distribution - = std::uniform_real_distribution<>(-1., 1.))) - ^ bdata::random((bdata::seed = 1717, - bdata::distribution - = std::uniform_real_distribution<>(-1., 1.))) - ^ bdata::xrange(ntests), - pT, - phi, - theta, - charge, - rfrac, - rand1, - rand2, - rand3, - index) -{ + bdata::distribution = std::uniform_real_distribution<>( + 0.4 * units::_GeV, 10. * units::_GeV))) ^ + bdata::random((bdata::seed = 1111, + bdata::distribution = + std::uniform_real_distribution<>(-M_PI, M_PI))) ^ + bdata::random((bdata::seed = 1212, + bdata::distribution = + std::uniform_real_distribution<>(0.1, 0.9 * M_PI))) ^ + bdata::random( + (bdata::seed = 1313, + bdata::distribution = std::uniform_int_distribution<>(0, 1))) ^ + bdata::random( + (bdata::seed = 1414, + bdata::distribution = std::uniform_real_distribution<>(0.5, 1.))) ^ + bdata::random( + (bdata::seed = 1515, + bdata::distribution = std::uniform_real_distribution<>(-1., 1.))) ^ + bdata::random( + (bdata::seed = 1616, + bdata::distribution = std::uniform_real_distribution<>(-1., 1.))) ^ + bdata::random( + (bdata::seed = 1717, + bdata::distribution = std::uniform_real_distribution<>(-1., 1.))) ^ + bdata::xrange(ntests), + pT, phi, theta, charge, rfrac, rand1, rand2, rand3, index) { if (index < skip) { return; } @@ -122,32 +89,14 @@ BOOST_DATA_TEST_CASE( double dcharge = -1 + 2 * charge; // just make sure we can reach it double r = rfrac * std::abs(Nat2SI<units::MOMENTUM>(pT) / (1. * Bz)); - r = (r > 2.5 * Acts::units::_m) ? 2.5 * Acts::units::_m : r; + r = (r > 2.5 * Acts::units::_m) ? 2.5 * Acts::units::_m : r; // check atlas stepper - auto a_at_cylinder = to_cylinder(apropagator, - pT, - phi, - theta, - dcharge, - r, - rand1, - rand2, - rand3, - covtpr, - debug); + auto a_at_cylinder = to_cylinder(apropagator, pT, phi, theta, dcharge, r, + rand1, rand2, rand3, covtpr, debug); // check eigen stepper - auto e_at_cylinder = to_cylinder(epropagator, - pT, - phi, - theta, - dcharge, - r, - rand1, - rand2, - rand3, - covtpr, - debug); + auto e_at_cylinder = to_cylinder(epropagator, pT, phi, theta, dcharge, r, + rand1, rand2, rand3, covtpr, debug); CHECK_CLOSE_ABS(e_at_cylinder.first, a_at_cylinder.first, 10. * units::_um); } @@ -155,72 +104,44 @@ BOOST_DATA_TEST_CASE( BOOST_DATA_TEST_CASE( propagation_to_plane_, bdata::random((bdata::seed = 0, - bdata::distribution - = std::uniform_real_distribution<>(0.4 * units::_GeV, - 10. * units::_GeV))) - ^ bdata::random((bdata::seed = 1, - bdata::distribution - = std::uniform_real_distribution<>(-M_PI, M_PI))) - ^ bdata::random((bdata::seed = 2, - bdata::distribution - = std::uniform_real_distribution<>(0., M_PI))) - ^ bdata::random((bdata::seed = 3, - bdata::distribution - = std::uniform_int_distribution<>(0, 1))) - ^ bdata::random((bdata::seed = 4, - bdata::distribution - = std::uniform_real_distribution<>(0.5, 1.))) - ^ bdata::random((bdata::seed = 5, - bdata::distribution - = std::uniform_real_distribution<>(-1., 1.))) - ^ bdata::random((bdata::seed = 6, - bdata::distribution - = std::uniform_real_distribution<>(-1., 1.))) - ^ bdata::random((bdata::seed = 7, - bdata::distribution - = std::uniform_real_distribution<>(-1., 1.))) - ^ bdata::xrange(ntests), - pT, - phi, - theta, - charge, - pfrac, - rand1, - rand2, - rand3, - index) -{ + bdata::distribution = std::uniform_real_distribution<>( + 0.4 * units::_GeV, 10. * units::_GeV))) ^ + bdata::random((bdata::seed = 1, + bdata::distribution = + std::uniform_real_distribution<>(-M_PI, M_PI))) ^ + bdata::random(( + bdata::seed = 2, + bdata::distribution = std::uniform_real_distribution<>(0., M_PI))) ^ + bdata::random( + (bdata::seed = 3, + bdata::distribution = std::uniform_int_distribution<>(0, 1))) ^ + bdata::random( + (bdata::seed = 4, + bdata::distribution = std::uniform_real_distribution<>(0.5, 1.))) ^ + bdata::random( + (bdata::seed = 5, + bdata::distribution = std::uniform_real_distribution<>(-1., 1.))) ^ + bdata::random( + (bdata::seed = 6, + bdata::distribution = std::uniform_real_distribution<>(-1., 1.))) ^ + bdata::random( + (bdata::seed = 7, + bdata::distribution = std::uniform_real_distribution<>(-1., 1.))) ^ + bdata::xrange(ntests), + pT, phi, theta, charge, pfrac, rand1, rand2, rand3, index) { if (index < skip) { return; } double dcharge = -1 + 2 * charge; // to a plane with the atlas stepper - auto a_at_plane - = to_surface<AtlasPropagatorType, PlaneSurface>(apropagator, - pT, - phi, - theta, - dcharge, - pfrac * Acts::units::_m, - rand1, - rand2, - rand3, - true, - covtpr); + auto a_at_plane = to_surface<AtlasPropagatorType, PlaneSurface>( + apropagator, pT, phi, theta, dcharge, pfrac * Acts::units::_m, rand1, + rand2, rand3, true, covtpr); // to a plane with the eigen stepper - auto e_at_plane - = to_surface<EigenPropagatorType, PlaneSurface>(epropagator, - pT, - phi, - theta, - dcharge, - pfrac * Acts::units::_m, - rand1, - rand2, - rand3, - true, - covtpr); + auto e_at_plane = to_surface<EigenPropagatorType, PlaneSurface>( + epropagator, pT, phi, theta, dcharge, pfrac * Acts::units::_m, rand1, + rand2, rand3, true, covtpr); CHECK_CLOSE_ABS(e_at_plane.first, a_at_plane.first, 1 * units::_um); } @@ -229,72 +150,44 @@ BOOST_DATA_TEST_CASE( BOOST_DATA_TEST_CASE( propagation_to_disc_, bdata::random((bdata::seed = 0, - bdata::distribution - = std::uniform_real_distribution<>(0.4 * units::_GeV, - 10. * units::_GeV))) - ^ bdata::random((bdata::seed = 1, - bdata::distribution - = std::uniform_real_distribution<>(-M_PI, M_PI))) - ^ bdata::random((bdata::seed = 2, - bdata::distribution - = std::uniform_real_distribution<>(0.1, M_PI - 0.1))) - ^ bdata::random((bdata::seed = 3, - bdata::distribution - = std::uniform_int_distribution<>(0, 1))) - ^ bdata::random((bdata::seed = 4, - bdata::distribution - = std::uniform_real_distribution<>(0.5, 1.))) - ^ bdata::random((bdata::seed = 5, - bdata::distribution - = std::uniform_real_distribution<>(-1., 1.))) - ^ bdata::random((bdata::seed = 6, - bdata::distribution - = std::uniform_real_distribution<>(-1., 1.))) - ^ bdata::random((bdata::seed = 7, - bdata::distribution - = std::uniform_real_distribution<>(-1., 1.))) - ^ bdata::xrange(ntests), - pT, - phi, - theta, - charge, - pfrac, - rand1, - rand2, - rand3, - index) -{ + bdata::distribution = std::uniform_real_distribution<>( + 0.4 * units::_GeV, 10. * units::_GeV))) ^ + bdata::random((bdata::seed = 1, + bdata::distribution = + std::uniform_real_distribution<>(-M_PI, M_PI))) ^ + bdata::random((bdata::seed = 2, + bdata::distribution = + std::uniform_real_distribution<>(0.1, M_PI - 0.1))) ^ + bdata::random( + (bdata::seed = 3, + bdata::distribution = std::uniform_int_distribution<>(0, 1))) ^ + bdata::random( + (bdata::seed = 4, + bdata::distribution = std::uniform_real_distribution<>(0.5, 1.))) ^ + bdata::random( + (bdata::seed = 5, + bdata::distribution = std::uniform_real_distribution<>(-1., 1.))) ^ + bdata::random( + (bdata::seed = 6, + bdata::distribution = std::uniform_real_distribution<>(-1., 1.))) ^ + bdata::random( + (bdata::seed = 7, + bdata::distribution = std::uniform_real_distribution<>(-1., 1.))) ^ + bdata::xrange(ntests), + pT, phi, theta, charge, pfrac, rand1, rand2, rand3, index) { if (index < skip) { return; } double dcharge = -1 + 2 * charge; // to a disc with the atlas stepper - auto a_at_disc - = to_surface<AtlasPropagatorType, DiscSurface>(apropagator, - pT, - phi, - theta, - dcharge, - pfrac * Acts::units::_m, - rand1, - rand2, - rand3, - true, - covtpr); + auto a_at_disc = to_surface<AtlasPropagatorType, DiscSurface>( + apropagator, pT, phi, theta, dcharge, pfrac * Acts::units::_m, rand1, + rand2, rand3, true, covtpr); // to a disc with the eigen stepper - auto e_at_disc - = to_surface<EigenPropagatorType, DiscSurface>(epropagator, - pT, - phi, - theta, - dcharge, - pfrac * Acts::units::_m, - rand1, - rand2, - rand3, - true, - covtpr); + auto e_at_disc = to_surface<EigenPropagatorType, DiscSurface>( + epropagator, pT, phi, theta, dcharge, pfrac * Acts::units::_m, rand1, + rand2, rand3, true, covtpr); CHECK_CLOSE_ABS(e_at_disc.first, a_at_disc.first, 1 * units::_um); } @@ -303,41 +196,31 @@ BOOST_DATA_TEST_CASE( BOOST_DATA_TEST_CASE( propagation_to_line_, bdata::random((bdata::seed = 1000, - bdata::distribution - = std::uniform_real_distribution<>(0.4 * units::_GeV, - 10. * units::_GeV))) - ^ bdata::random((bdata::seed = 1001, - bdata::distribution - = std::uniform_real_distribution<>(-M_PI, M_PI))) - ^ bdata::random((bdata::seed = 1002, - bdata::distribution - = std::uniform_real_distribution<>(0.1, M_PI - 0.1))) - ^ bdata::random((bdata::seed = 1003, - bdata::distribution - = std::uniform_int_distribution<>(0, 1))) - ^ bdata::random((bdata::seed = 1004, - bdata::distribution - = std::uniform_real_distribution<>(0.5, 1.))) - ^ bdata::random((bdata::seed = 1005, - bdata::distribution - = std::uniform_real_distribution<>(-1., 1.))) - ^ bdata::random((bdata::seed = 1006, - bdata::distribution - = std::uniform_real_distribution<>(-1., 1.))) - ^ bdata::random((bdata::seed = 1007, - bdata::distribution - = std::uniform_real_distribution<>(-1., 1.))) - ^ bdata::xrange(ntests), - pT, - phi, - theta, - charge, - pfrac, - rand1, - rand2, - rand3, - index) -{ + bdata::distribution = std::uniform_real_distribution<>( + 0.4 * units::_GeV, 10. * units::_GeV))) ^ + bdata::random((bdata::seed = 1001, + bdata::distribution = + std::uniform_real_distribution<>(-M_PI, M_PI))) ^ + bdata::random((bdata::seed = 1002, + bdata::distribution = + std::uniform_real_distribution<>(0.1, M_PI - 0.1))) ^ + bdata::random( + (bdata::seed = 1003, + bdata::distribution = std::uniform_int_distribution<>(0, 1))) ^ + bdata::random( + (bdata::seed = 1004, + bdata::distribution = std::uniform_real_distribution<>(0.5, 1.))) ^ + bdata::random( + (bdata::seed = 1005, + bdata::distribution = std::uniform_real_distribution<>(-1., 1.))) ^ + bdata::random( + (bdata::seed = 1006, + bdata::distribution = std::uniform_real_distribution<>(-1., 1.))) ^ + bdata::random( + (bdata::seed = 1007, + bdata::distribution = std::uniform_real_distribution<>(-1., 1.))) ^ + bdata::xrange(ntests), + pT, phi, theta, charge, pfrac, rand1, rand2, rand3, index) { if (index < skip) { return; } @@ -348,36 +231,16 @@ BOOST_DATA_TEST_CASE( if (debug) { std::cout << "[ >>>> Testing Atlas Propagator <<<< ]" << std::endl; } - auto a_at_line - = to_surface<AtlasPropagatorType, StrawSurface>(apropagator, - pT, - phi, - theta, - dcharge, - pfrac * Acts::units::_m, - rand1, - rand2, - rand3, - false, - covtpr, - debug); + auto a_at_line = to_surface<AtlasPropagatorType, StrawSurface>( + apropagator, pT, phi, theta, dcharge, pfrac * Acts::units::_m, rand1, + rand2, rand3, false, covtpr, debug); // to a line with the eigen stepper if (debug) { std::cout << "[ >>>> Testing Eigen Propagator <<<< ]" << std::endl; } - auto e_at_line - = to_surface<EigenPropagatorType, StrawSurface>(epropagator, - pT, - phi, - theta, - dcharge, - pfrac * Acts::units::_m, - rand1, - rand2, - rand3, - false, - covtpr, - debug); + auto e_at_line = to_surface<EigenPropagatorType, StrawSurface>( + epropagator, pT, phi, theta, dcharge, pfrac * Acts::units::_m, rand1, + rand2, rand3, false, covtpr, debug); CHECK_CLOSE_ABS(e_at_line.first, a_at_line.first, 1 * units::_um); } @@ -388,82 +251,65 @@ BOOST_DATA_TEST_CASE( BOOST_DATA_TEST_CASE( covariance_transport_curvilinear_curvilinear_, bdata::random((bdata::seed = 2000, - bdata::distribution - = std::uniform_real_distribution<>(0.4 * units::_GeV, - 10. * units::_GeV))) - ^ bdata::random((bdata::seed = 2001, - bdata::distribution - = std::uniform_real_distribution<>(-M_PI, M_PI))) - ^ bdata::random((bdata::seed = 2002, - bdata::distribution - = std::uniform_real_distribution<>(0.10, M_PI - 0.10))) - ^ bdata::random((bdata::seed = 2003, - bdata::distribution - = std::uniform_int_distribution<>(0, 1))) - ^ bdata::random((bdata::seed = 2004, - bdata::distribution - = std::uniform_real_distribution<>(0.5, 1.))) - ^ bdata::xrange(ntests), - pT, - phi, - theta, - charge, - plimit, - index) -{ + bdata::distribution = std::uniform_real_distribution<>( + 0.4 * units::_GeV, 10. * units::_GeV))) ^ + bdata::random((bdata::seed = 2001, + bdata::distribution = + std::uniform_real_distribution<>(-M_PI, M_PI))) ^ + bdata::random((bdata::seed = 2002, + bdata::distribution = std::uniform_real_distribution<>( + 0.10, M_PI - 0.10))) ^ + bdata::random( + (bdata::seed = 2003, + bdata::distribution = std::uniform_int_distribution<>(0, 1))) ^ + bdata::random( + (bdata::seed = 2004, + bdata::distribution = std::uniform_real_distribution<>(0.5, 1.))) ^ + bdata::xrange(ntests), + pT, phi, theta, charge, plimit, index) { if (index < skip) { return; } double dcharge = -1 + 2 * charge; // covariance check for eigen stepper - covariance_curvilinear( - epropagator, pT, phi, theta, dcharge, plimit * Acts::units::_m, index); + covariance_curvilinear(epropagator, pT, phi, theta, dcharge, + plimit * Acts::units::_m, index); // covariance check for eigen stepper in dense environment // covariance check fo atlas stepper - covariance_curvilinear( - apropagator, pT, phi, theta, dcharge, plimit * Acts::units::_m, index); + covariance_curvilinear(apropagator, pT, phi, theta, dcharge, + plimit * Acts::units::_m, index); } // test correct covariance transport from disc to disc BOOST_DATA_TEST_CASE( covariance_transport_disc_disc_, bdata::random((bdata::seed = 3000, - bdata::distribution - = std::uniform_real_distribution<>(0.4 * units::_GeV, - 10. * units::_GeV))) - ^ bdata::random((bdata::seed = 3001, - bdata::distribution - = std::uniform_real_distribution<>(-M_PI, M_PI))) - ^ bdata::random((bdata::seed = 3002, - bdata::distribution - = std::uniform_real_distribution<>(0.1, M_PI - 0.1))) - ^ bdata::random((bdata::seed = 3003, - bdata::distribution - = std::uniform_int_distribution<>(0, 1))) - ^ bdata::random((bdata::seed = 3004, - bdata::distribution - = std::uniform_real_distribution<>(0.5, 1.))) - ^ bdata::random((bdata::seed = 3005, - bdata::distribution - = std::uniform_real_distribution<>(-1., 1.))) - ^ bdata::random((bdata::seed = 3006, - bdata::distribution - = std::uniform_real_distribution<>(-1., 1.))) - ^ bdata::random((bdata::seed = 3007, - bdata::distribution - = std::uniform_real_distribution<>(-1., 1.))) - ^ bdata::xrange(ntests), - pT, - phi, - theta, - charge, - plimit, - rand1, - rand2, - rand3, - index) -{ + bdata::distribution = std::uniform_real_distribution<>( + 0.4 * units::_GeV, 10. * units::_GeV))) ^ + bdata::random((bdata::seed = 3001, + bdata::distribution = + std::uniform_real_distribution<>(-M_PI, M_PI))) ^ + bdata::random((bdata::seed = 3002, + bdata::distribution = + std::uniform_real_distribution<>(0.1, M_PI - 0.1))) ^ + bdata::random( + (bdata::seed = 3003, + bdata::distribution = std::uniform_int_distribution<>(0, 1))) ^ + bdata::random( + (bdata::seed = 3004, + bdata::distribution = std::uniform_real_distribution<>(0.5, 1.))) ^ + bdata::random( + (bdata::seed = 3005, + bdata::distribution = std::uniform_real_distribution<>(-1., 1.))) ^ + bdata::random( + (bdata::seed = 3006, + bdata::distribution = std::uniform_real_distribution<>(-1., 1.))) ^ + bdata::random( + (bdata::seed = 3007, + bdata::distribution = std::uniform_real_distribution<>(-1., 1.))) ^ + bdata::xrange(ntests), + pT, phi, theta, charge, plimit, rand1, rand2, rand3, index) { if (index < skip) { return; } @@ -471,76 +317,44 @@ BOOST_DATA_TEST_CASE( double dcharge = -1 + 2 * charge; // covariance check for atlas stepper covariance_bound<AtlasPropagatorType, DiscSurface, DiscSurface>( - apropagator, - pT, - phi, - theta, - dcharge, - plimit * Acts::units::_m, - rand1, - rand2, - rand3, - index, - true, - true, - 1e-1); + apropagator, pT, phi, theta, dcharge, plimit * Acts::units::_m, rand1, + rand2, rand3, index, true, true, 1e-1); // covariance check for eigen stepper covariance_bound<EigenPropagatorType, DiscSurface, DiscSurface>( - epropagator, - pT, - phi, - theta, - dcharge, - plimit * Acts::units::_m, - rand1, - rand2, - rand3, - index, - true, - true, - 1e-1); + epropagator, pT, phi, theta, dcharge, plimit * Acts::units::_m, rand1, + rand2, rand3, index, true, true, 1e-1); } // test correct covariance transport from plane to plane BOOST_DATA_TEST_CASE( covariance_transport_plane_plane_, bdata::random((bdata::seed = 4000, - bdata::distribution - = std::uniform_real_distribution<>(0.4 * units::_GeV, - 10. * units::_GeV))) - ^ bdata::random((bdata::seed = 4001, - bdata::distribution - = std::uniform_real_distribution<>(-M_PI, M_PI))) - ^ bdata::random((bdata::seed = 4002, - bdata::distribution - = std::uniform_real_distribution<>(0.1, M_PI - 0.1))) - ^ bdata::random((bdata::seed = 4003, - bdata::distribution - = std::uniform_int_distribution<>(0, 1))) - ^ bdata::random((bdata::seed = 4004, - bdata::distribution - = std::uniform_real_distribution<>(0.5, 1.))) - ^ bdata::random((bdata::seed = 4005, - bdata::distribution - = std::uniform_real_distribution<>(-1., 1.))) - ^ bdata::random((bdata::seed = 4006, - bdata::distribution - = std::uniform_real_distribution<>(-1., 1.))) - ^ bdata::random((bdata::seed = 4007, - bdata::distribution - = std::uniform_real_distribution<>(-1., 1.))) - ^ bdata::xrange(ntests), - pT, - phi, - theta, - charge, - plimit, - rand1, - rand2, - rand3, - index) -{ + bdata::distribution = std::uniform_real_distribution<>( + 0.4 * units::_GeV, 10. * units::_GeV))) ^ + bdata::random((bdata::seed = 4001, + bdata::distribution = + std::uniform_real_distribution<>(-M_PI, M_PI))) ^ + bdata::random((bdata::seed = 4002, + bdata::distribution = + std::uniform_real_distribution<>(0.1, M_PI - 0.1))) ^ + bdata::random( + (bdata::seed = 4003, + bdata::distribution = std::uniform_int_distribution<>(0, 1))) ^ + bdata::random( + (bdata::seed = 4004, + bdata::distribution = std::uniform_real_distribution<>(0.5, 1.))) ^ + bdata::random( + (bdata::seed = 4005, + bdata::distribution = std::uniform_real_distribution<>(-1., 1.))) ^ + bdata::random( + (bdata::seed = 4006, + bdata::distribution = std::uniform_real_distribution<>(-1., 1.))) ^ + bdata::random( + (bdata::seed = 4007, + bdata::distribution = std::uniform_real_distribution<>(-1., 1.))) ^ + bdata::xrange(ntests), + pT, phi, theta, charge, plimit, rand1, rand2, rand3, index) { if (index < skip) { return; } @@ -548,29 +362,13 @@ BOOST_DATA_TEST_CASE( double dcharge = -1 + 2 * charge; // covariance check for atlas stepper covariance_bound<AtlasPropagatorType, PlaneSurface, PlaneSurface>( - apropagator, - pT, - phi, - theta, - dcharge, - plimit * Acts::units::_m, - rand1, - rand2, - rand3, - index); + apropagator, pT, phi, theta, dcharge, plimit * Acts::units::_m, rand1, + rand2, rand3, index); // covariance check for eigen stepper covariance_bound<EigenPropagatorType, PlaneSurface, PlaneSurface>( - epropagator, - pT, - phi, - theta, - dcharge, - plimit * Acts::units::_m, - rand1, - rand2, - rand3, - index); + epropagator, pT, phi, theta, dcharge, plimit * Acts::units::_m, rand1, + rand2, rand3, index); } // test correct covariance transport from straw to straw @@ -579,41 +377,31 @@ BOOST_DATA_TEST_CASE( BOOST_DATA_TEST_CASE( covariance_transport_line_line_, bdata::random((bdata::seed = 1000, - bdata::distribution - = std::uniform_real_distribution<>(0.4 * units::_GeV, - 10. * units::_GeV))) - ^ bdata::random((bdata::seed = 1001, - bdata::distribution - = std::uniform_real_distribution<>(-M_PI, M_PI))) - ^ bdata::random((bdata::seed = 1002, - bdata::distribution - = std::uniform_real_distribution<>(0.15, M_PI - 0.15))) - ^ bdata::random((bdata::seed = 1003, - bdata::distribution - = std::uniform_int_distribution<>(0, 1))) - ^ bdata::random((bdata::seed = 1004, - bdata::distribution - = std::uniform_real_distribution<>(0.1, 0.2))) - ^ bdata::random((bdata::seed = 1005, - bdata::distribution - = std::uniform_real_distribution<>(-0.25, 0.25))) - ^ bdata::random((bdata::seed = 1006, - bdata::distribution - = std::uniform_real_distribution<>(-0.25, 0.25))) - ^ bdata::random((bdata::seed = 1007, - bdata::distribution - = std::uniform_real_distribution<>(-0.25, 0.25))) - ^ bdata::xrange(ntests), - pT, - phi, - theta, - charge, - plimit, - rand1, - rand2, - rand3, - index) -{ + bdata::distribution = std::uniform_real_distribution<>( + 0.4 * units::_GeV, 10. * units::_GeV))) ^ + bdata::random((bdata::seed = 1001, + bdata::distribution = + std::uniform_real_distribution<>(-M_PI, M_PI))) ^ + bdata::random((bdata::seed = 1002, + bdata::distribution = std::uniform_real_distribution<>( + 0.15, M_PI - 0.15))) ^ + bdata::random( + (bdata::seed = 1003, + bdata::distribution = std::uniform_int_distribution<>(0, 1))) ^ + bdata::random(( + bdata::seed = 1004, + bdata::distribution = std::uniform_real_distribution<>(0.1, 0.2))) ^ + bdata::random((bdata::seed = 1005, + bdata::distribution = + std::uniform_real_distribution<>(-0.25, 0.25))) ^ + bdata::random((bdata::seed = 1006, + bdata::distribution = + std::uniform_real_distribution<>(-0.25, 0.25))) ^ + bdata::random((bdata::seed = 1007, + bdata::distribution = + std::uniform_real_distribution<>(-0.25, 0.25))) ^ + bdata::xrange(ntests), + pT, phi, theta, charge, plimit, rand1, rand2, rand3, index) { if (index < skip) { return; } @@ -622,35 +410,13 @@ BOOST_DATA_TEST_CASE( // covariance check for atlas stepper covariance_bound<AtlasPropagatorType, StrawSurface, StrawSurface>( - apropagator, - pT, - phi, - theta, - dcharge, - plimit * Acts::units::_m, - rand1, - rand2, - rand3, - index, - false, - false, - 1e-1); + apropagator, pT, phi, theta, dcharge, plimit * Acts::units::_m, rand1, + rand2, rand3, index, false, false, 1e-1); // covariance check for eigen stepper covariance_bound<EigenPropagatorType, StrawSurface, StrawSurface>( - epropagator, - pT, - phi, - theta, - dcharge, - plimit * Acts::units::_m, - rand1, - rand2, - rand3, - index, - false, - false, - 1e-1); + epropagator, pT, phi, theta, dcharge, plimit * Acts::units::_m, rand1, + rand2, rand3, index, false, false, 1e-1); } /// test correct covariance transport for curvilinear parameters in dense @@ -660,62 +426,36 @@ BOOST_DATA_TEST_CASE( BOOST_DATA_TEST_CASE( dense_covariance_transport_curvilinear_curvilinear_, bdata::random((bdata::seed = 2000, - bdata::distribution - = std::uniform_real_distribution<>(3. * units::_GeV, - 10. * units::_GeV))) - ^ bdata::random((bdata::seed = 2004, - bdata::distribution - = std::uniform_real_distribution<>(0.5, 1.))) - ^ bdata::random((bdata::seed = 3005, - bdata::distribution - = std::uniform_real_distribution<>(-1., 1.))) - ^ bdata::random((bdata::seed = 3006, - bdata::distribution - = std::uniform_real_distribution<>(-1., 1.))) - ^ bdata::random((bdata::seed = 3007, - bdata::distribution - = std::uniform_real_distribution<>(-1., 1.))) - ^ bdata::xrange(ntests), - pT, - plimit, - rand1, - rand2, - rand3, - index) -{ + bdata::distribution = std::uniform_real_distribution<>( + 3. * units::_GeV, 10. * units::_GeV))) ^ + bdata::random( + (bdata::seed = 2004, + bdata::distribution = std::uniform_real_distribution<>(0.5, 1.))) ^ + bdata::random( + (bdata::seed = 3005, + bdata::distribution = std::uniform_real_distribution<>(-1., 1.))) ^ + bdata::random( + (bdata::seed = 3006, + bdata::distribution = std::uniform_real_distribution<>(-1., 1.))) ^ + bdata::random( + (bdata::seed = 3007, + bdata::distribution = std::uniform_real_distribution<>(-1., 1.))) ^ + bdata::xrange(ntests), + pT, plimit, rand1, rand2, rand3, index) { if (index < skip) { return; } // covariance check for eigen stepper in dense environment DensePropagatorType dpropagator = setupDensePropagator(); - covariance_curvilinear( - dpropagator, pT, 0., M_PI / 2., 1, plimit * Acts::units::_m, index); + covariance_curvilinear(dpropagator, pT, 0., M_PI / 2., 1, + plimit * Acts::units::_m, index); covariance_bound<DensePropagatorType, DiscSurface, DiscSurface>( - dpropagator, - pT, - 0., - M_PI / 2., - 1, - plimit * Acts::units::_m, - rand1, - rand2, - rand3, - index, - true, - true, - 1e-1); + dpropagator, pT, 0., M_PI / 2., 1, plimit * Acts::units::_m, rand1, rand2, + rand3, index, true, true, 1e-1); covariance_bound<DensePropagatorType, PlaneSurface, PlaneSurface>( - dpropagator, - pT, - 0., - M_PI / 2., - 1, - plimit * Acts::units::_m, - rand1, - rand2, - rand3, - index); + dpropagator, pT, 0., M_PI / 2., 1, plimit * Acts::units::_m, rand1, rand2, + rand3, index); } diff --git a/Tests/Integration/PropagationTestHelper.hpp b/Tests/Integration/PropagationTestHelper.hpp index 74370393ccfc198e3edfeb8d5615b12b1da58610..8facfc3624d85877a52c58d4bce1c84f67041aff 100644 --- a/Tests/Integration/PropagationTestHelper.hpp +++ b/Tests/Integration/PropagationTestHelper.hpp @@ -24,525 +24,461 @@ using units::Nat2SI; namespace IntegrationTest { - // Create a test context - GeometryContext tgContext = GeometryContext(); - MagneticFieldContext mfContext = MagneticFieldContext(); - - /// Helper method to create a transform for a plane - /// to mimic detector situations, the plane is roughly - /// perpendicular to the track - /// - /// @param nnomal The nominal normal direction - /// @param angleT Rotation around the norminal normal - /// @param angleU Roation around the original U axis - std::shared_ptr<Transform3D> - createPlanarTransform(const Vector3D& nposition, - const Vector3D& nnormal, - double angleT, - double angleU) - { - // the rotation of the destination surface - Vector3D T = nnormal.normalized(); - Vector3D U = std::abs(T.dot(Vector3D::UnitZ())) < 0.99 - ? Vector3D::UnitZ().cross(T).normalized() - : Vector3D::UnitX().cross(T).normalized(); - Vector3D V = T.cross(U); - // that's the plane curvilinear Rotation - RotationMatrix3D curvilinearRotation; - curvilinearRotation.col(0) = U; - curvilinearRotation.col(1) = V; - curvilinearRotation.col(2) = T; - // curvilinear surfaces are boundless - Transform3D ctransform{curvilinearRotation}; - ctransform.pretranslate(nposition); - ctransform.prerotate(AngleAxis3D(angleT, T)); - ctransform.prerotate(AngleAxis3D(angleU, U)); - // - return std::make_shared<Transform3D>(ctransform); - } +// Create a test context +GeometryContext tgContext = GeometryContext(); +MagneticFieldContext mfContext = MagneticFieldContext(); + +/// Helper method to create a transform for a plane +/// to mimic detector situations, the plane is roughly +/// perpendicular to the track +/// +/// @param nnomal The nominal normal direction +/// @param angleT Rotation around the norminal normal +/// @param angleU Roation around the original U axis +std::shared_ptr<Transform3D> createPlanarTransform(const Vector3D& nposition, + const Vector3D& nnormal, + double angleT, + double angleU) { + // the rotation of the destination surface + Vector3D T = nnormal.normalized(); + Vector3D U = std::abs(T.dot(Vector3D::UnitZ())) < 0.99 + ? Vector3D::UnitZ().cross(T).normalized() + : Vector3D::UnitX().cross(T).normalized(); + Vector3D V = T.cross(U); + // that's the plane curvilinear Rotation + RotationMatrix3D curvilinearRotation; + curvilinearRotation.col(0) = U; + curvilinearRotation.col(1) = V; + curvilinearRotation.col(2) = T; + // curvilinear surfaces are boundless + Transform3D ctransform{curvilinearRotation}; + ctransform.pretranslate(nposition); + ctransform.prerotate(AngleAxis3D(angleT, T)); + ctransform.prerotate(AngleAxis3D(angleU, U)); + // + return std::make_shared<Transform3D>(ctransform); +} - /// Helper method to create a transform for a plane - /// to mimic detector situations, the plane is roughly - /// perpendicular to the track - /// - /// @param nnomal The nominal normal direction - /// @param angleT Rotation around the norminal normal - /// @param angleU Roation around the original U axis - std::shared_ptr<Transform3D> - createCylindricTransform(const Vector3D& nposition, - double angleX, - double angleY) - { - Transform3D ctransform; - ctransform.setIdentity(); - ctransform.pretranslate(nposition); - ctransform.prerotate(AngleAxis3D(angleX, Vector3D::UnitX())); - ctransform.prerotate(AngleAxis3D(angleY, Vector3D::UnitY())); - return std::make_shared<Transform3D>(ctransform); - } +/// Helper method to create a transform for a plane +/// to mimic detector situations, the plane is roughly +/// perpendicular to the track +/// +/// @param nnomal The nominal normal direction +/// @param angleT Rotation around the norminal normal +/// @param angleU Roation around the original U axis +std::shared_ptr<Transform3D> createCylindricTransform(const Vector3D& nposition, + double angleX, + double angleY) { + Transform3D ctransform; + ctransform.setIdentity(); + ctransform.pretranslate(nposition); + ctransform.prerotate(AngleAxis3D(angleX, Vector3D::UnitX())); + ctransform.prerotate(AngleAxis3D(angleY, Vector3D::UnitY())); + return std::make_shared<Transform3D>(ctransform); +} - template <typename Propagator_type> - Vector3D - constant_field_propagation(const Propagator_type& propagator, - double pT, - double phi, - double theta, - double charge, - int /*index*/, - double Bz, - double disttol = 0.1 * units::_um, - bool debug = false) - { - - namespace VH = VectorHelpers; - - // setup propagation options - PropagatorOptions<> options(tgContext, mfContext); - options.pathLimit = 5 * units::_m; - options.maxStepSize = 1 * units::_cm; - options.debug = debug; - - // define start parameters - double x = 0; - double y = 0; - double z = 0; - double px = pT * cos(phi); - double py = pT * sin(phi); - double pz = pT / tan(theta); - double q = charge; - Vector3D pos(x, y, z); - Vector3D mom(px, py, pz); - CurvilinearParameters pars(nullptr, pos, mom, q); - - // do propagation - const auto& tp = propagator.propagate(pars, options).value().endParameters; - - // test propagation invariants - // clang-format off +template <typename Propagator_type> +Vector3D constant_field_propagation(const Propagator_type& propagator, + double pT, double phi, double theta, + double charge, int /*index*/, double Bz, + double disttol = 0.1 * units::_um, + bool debug = false) { + namespace VH = VectorHelpers; + + // setup propagation options + PropagatorOptions<> options(tgContext, mfContext); + options.pathLimit = 5 * units::_m; + options.maxStepSize = 1 * units::_cm; + options.debug = debug; + + // define start parameters + double x = 0; + double y = 0; + double z = 0; + double px = pT * cos(phi); + double py = pT * sin(phi); + double pz = pT / tan(theta); + double q = charge; + Vector3D pos(x, y, z); + Vector3D mom(px, py, pz); + CurvilinearParameters pars(nullptr, pos, mom, q); + + // do propagation + const auto& tp = propagator.propagate(pars, options).value().endParameters; + + // test propagation invariants + // clang-format off CHECK_CLOSE_ABS(pT, VH::perp(tp->momentum()), 1 * units::_keV); CHECK_CLOSE_ABS(pz, tp->momentum()(2), 1 * units::_keV); CHECK_CLOSE_ABS(theta, VH::theta(tp->momentum()), 1e-4); - // clang-format on + // clang-format on - double r = std::abs(Nat2SI<units::MOMENTUM>(pT) / (q * Bz)); + double r = std::abs(Nat2SI<units::MOMENTUM>(pT) / (q * Bz)); - // calculate number of turns of helix - double turns = options.pathLimit / (2 * M_PI * r) * sin(theta); - // respect direction of curl - turns = (q * Bz < 0) ? turns : -turns; + // calculate number of turns of helix + double turns = options.pathLimit / (2 * M_PI * r) * sin(theta); + // respect direction of curl + turns = (q * Bz < 0) ? turns : -turns; - // calculate expected final momentum direction in phi in [-pi,pi] - double exp_phi = std::fmod(phi + turns * 2 * M_PI, 2 * M_PI); - if (exp_phi < -M_PI) { - exp_phi += 2 * M_PI; - } - if (exp_phi > M_PI) { - exp_phi -= 2 * M_PI; - } + // calculate expected final momentum direction in phi in [-pi,pi] + double exp_phi = std::fmod(phi + turns * 2 * M_PI, 2 * M_PI); + if (exp_phi < -M_PI) { + exp_phi += 2 * M_PI; + } + if (exp_phi > M_PI) { + exp_phi -= 2 * M_PI; + } - // calculate expected position - double exp_z = z + pz / pT * 2 * M_PI * r * std::abs(turns); - - // calculate center of bending circle in transverse plane - double xc, yc; - // offset with respect to starting point - double dx = r * cos(M_PI / 2 - phi); - double dy = r * sin(M_PI / 2 - phi); - if (q * Bz < 0) { - xc = x - dx; - yc = y + dy; - } else { - xc = x + dx; - yc = y - dy; - } - // phi position of starting point in bending circle - double phi0 = std::atan2(y - yc, x - xc); + // calculate expected position + double exp_z = z + pz / pT * 2 * M_PI * r * std::abs(turns); + + // calculate center of bending circle in transverse plane + double xc, yc; + // offset with respect to starting point + double dx = r * cos(M_PI / 2 - phi); + double dy = r * sin(M_PI / 2 - phi); + if (q * Bz < 0) { + xc = x - dx; + yc = y + dy; + } else { + xc = x + dx; + yc = y - dy; + } + // phi position of starting point in bending circle + double phi0 = std::atan2(y - yc, x - xc); - // calculated expected position in transverse plane - double exp_x = xc + r * cos(phi0 + turns * 2 * M_PI); - double exp_y = yc + r * sin(phi0 + turns * 2 * M_PI); + // calculated expected position in transverse plane + double exp_x = xc + r * cos(phi0 + turns * 2 * M_PI); + double exp_y = yc + r * sin(phi0 + turns * 2 * M_PI); - // clang-format off + // clang-format off CHECK_CLOSE_ABS(exp_phi, VH::phi(tp->momentum()), 1e-4); CHECK_CLOSE_ABS(exp_x, tp->position()(0), disttol); CHECK_CLOSE_ABS(exp_y, tp->position()(1), disttol); CHECK_CLOSE_ABS(exp_z, tp->position()(2), disttol); - // clang-format on - return tp->position(); - } + // clang-format on + return tp->position(); +} - template <typename Propagator_type> - void - foward_backward(const Propagator_type& propagator, - double pT, - double phi, - double theta, - double charge, - double plimit, - int /*index*/, - double disttol = 1. * units::_um, - double momtol = 10. * units::_keV, - bool debug = false) - { - - // setup propagation options - // Action list and abort list - using DebugOutput = Acts::detail::DebugOutputActor; - using ActionList = Acts::ActionList<DebugOutput>; - - PropagatorOptions<ActionList> fwdOptions(tgContext, mfContext); - fwdOptions.pathLimit = plimit; - fwdOptions.maxStepSize = 1 * units::_cm; - fwdOptions.debug = debug; - - PropagatorOptions<ActionList> bwdOptions(tgContext, mfContext); - bwdOptions.direction = backward; - bwdOptions.pathLimit = -plimit; - bwdOptions.maxStepSize = 1 * units::_cm; - bwdOptions.debug = debug; - - // define start parameters - double x = 0; - double y = 0; - double z = 0; - double px = pT * cos(phi); - double py = pT * sin(phi); - double pz = pT / tan(theta); - double q = charge; - Vector3D pos(x, y, z); - Vector3D mom(px, py, pz); - CurvilinearParameters start(nullptr, pos, mom, q); - - // do forward-backward propagation - const auto& fwdResult = propagator.propagate(start, fwdOptions).value(); - const auto& bwdResult - = propagator.propagate(*fwdResult.endParameters, bwdOptions).value(); - - const Vector3D& bwdPosition = bwdResult.endParameters->position(); - const Vector3D& bwdMomentum = bwdResult.endParameters->momentum(); - - // test propagation invariants - // clang-format off +template <typename Propagator_type> +void foward_backward(const Propagator_type& propagator, double pT, double phi, + double theta, double charge, double plimit, int /*index*/, + double disttol = 1. * units::_um, + double momtol = 10. * units::_keV, bool debug = false) { + // setup propagation options + // Action list and abort list + using DebugOutput = Acts::detail::DebugOutputActor; + using ActionList = Acts::ActionList<DebugOutput>; + + PropagatorOptions<ActionList> fwdOptions(tgContext, mfContext); + fwdOptions.pathLimit = plimit; + fwdOptions.maxStepSize = 1 * units::_cm; + fwdOptions.debug = debug; + + PropagatorOptions<ActionList> bwdOptions(tgContext, mfContext); + bwdOptions.direction = backward; + bwdOptions.pathLimit = -plimit; + bwdOptions.maxStepSize = 1 * units::_cm; + bwdOptions.debug = debug; + + // define start parameters + double x = 0; + double y = 0; + double z = 0; + double px = pT * cos(phi); + double py = pT * sin(phi); + double pz = pT / tan(theta); + double q = charge; + Vector3D pos(x, y, z); + Vector3D mom(px, py, pz); + CurvilinearParameters start(nullptr, pos, mom, q); + + // do forward-backward propagation + const auto& fwdResult = propagator.propagate(start, fwdOptions).value(); + const auto& bwdResult = + propagator.propagate(*fwdResult.endParameters, bwdOptions).value(); + + const Vector3D& bwdPosition = bwdResult.endParameters->position(); + const Vector3D& bwdMomentum = bwdResult.endParameters->momentum(); + + // test propagation invariants + // clang-format off CHECK_CLOSE_ABS(x, bwdPosition(0), disttol); CHECK_CLOSE_ABS(y, bwdPosition(1), disttol); CHECK_CLOSE_ABS(z, bwdPosition(2), disttol); CHECK_CLOSE_ABS(px, bwdMomentum(0), momtol); CHECK_CLOSE_ABS(py, bwdMomentum(1), momtol); CHECK_CLOSE_ABS(pz, bwdMomentum(2), momtol); - // clang-format on - - if (debug) { - auto fwdOutput = fwdResult.template get<DebugOutput::result_type>(); - std::cout << ">>>>> Output for forward propagation " << std::endl; - std::cout << fwdOutput.debugString << std::endl; - std::cout << " - resulted at position : " - << fwdResult.endParameters->position() << std::endl; - - auto bwdOutput = fwdResult.template get<DebugOutput::result_type>(); - std::cout << ">>>>> Output for backward propagation " << std::endl; - std::cout << bwdOutput.debugString << std::endl; - std::cout << " - resulted at position : " - << bwdResult.endParameters->position() << std::endl; - } - } - - // test propagation to cylinder - template <typename Propagator_type> - std::pair<Vector3D, double> - to_cylinder(const Propagator_type& propagator, - double pT, - double phi, - double theta, - double charge, - double plimit, - double rand1, - double rand2, - double /*rand3*/, - bool covtransport = false, - bool debug = false) - { - // setup propagation options - PropagatorOptions<> options(tgContext, mfContext); - // setup propagation options - options.maxStepSize = plimit; - options.pathLimit = plimit; - options.debug = debug; - - // define start parameters - double x = 0; - double y = 0; - double z = 0; - double px = pT * cos(phi); - double py = pT * sin(phi); - double pz = pT / tan(theta); - double q = charge; - Vector3D pos(x, y, z); - Vector3D mom(px, py, pz); - - std::unique_ptr<const ActsSymMatrixD<5>> covPtr = nullptr; - if (covtransport) { - ActsSymMatrixD<5> cov; - // take some major correlations (off-diagonals) - cov << 10 * units::_mm, 0, 0.123, 0, 0.5, 0, 10 * units::_mm, 0, 0.162, 0, - 0.123, 0, 0.1, 0, 0, 0, 0.162, 0, 0.1, 0, 0.5, 0, 0, 0, - 1. / (10 * units::_GeV); - covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); - } - // do propagation of the start parameters - CurvilinearParameters start(std::move(covPtr), pos, mom, q); - - // The transform at the destination - auto seTransform = createCylindricTransform( - Vector3D(0., 0., 0.), 0.05 * rand1, 0.05 * rand2); - auto endSurface = Surface::makeShared<CylinderSurface>( - seTransform, plimit * units::_m, std::numeric_limits<double>::max()); - - // Increase the path limit - to be safe hitting the surface - options.pathLimit *= 2; - const auto result - = propagator.propagate(start, *endSurface, options).value(); - const auto& tp = result.endParameters; - // check for null pointer - BOOST_CHECK(tp != nullptr); - // The position and path length - return std::pair<Vector3D, double>(tp->position(), result.pathLength); + // clang-format on + + if (debug) { + auto fwdOutput = fwdResult.template get<DebugOutput::result_type>(); + std::cout << ">>>>> Output for forward propagation " << std::endl; + std::cout << fwdOutput.debugString << std::endl; + std::cout << " - resulted at position : " + << fwdResult.endParameters->position() << std::endl; + + auto bwdOutput = fwdResult.template get<DebugOutput::result_type>(); + std::cout << ">>>>> Output for backward propagation " << std::endl; + std::cout << bwdOutput.debugString << std::endl; + std::cout << " - resulted at position : " + << bwdResult.endParameters->position() << std::endl; } +} - // test propagation to most surfaces - template <typename Propagator_type, typename Surface_type> - std::pair<Vector3D, double> - to_surface(const Propagator_type& propagator, - double pT, - double phi, - double theta, - double charge, - double plimit, - double rand1, - double rand2, - double rand3, - bool planar = true, - bool covtransport = false, - bool debug = false) - { - - using DebugOutput = detail::DebugOutputActor; - - // setup propagation options - PropagatorOptions<ActionList<DebugOutput>> options(tgContext, mfContext); - // setup propagation options - options.maxStepSize = plimit; - options.pathLimit = plimit; - options.debug = debug; - - // define start parameters - double x = 0; - double y = 0; - double z = 0; - double px = pT * cos(phi); - double py = pT * sin(phi); - double pz = pT / tan(theta); - double q = charge; - Vector3D pos(x, y, z); - Vector3D mom(px, py, pz); - - std::unique_ptr<const ActsSymMatrixD<5>> covPtr = nullptr; - if (covtransport) { - ActsSymMatrixD<5> cov; - // take some major correlations (off-diagonals) - cov << 10 * units::_mm, 0, 0.123, 0, 0.5, 0, 10 * units::_mm, 0, 0.162, 0, - 0.123, 0, 0.1, 0, 0, 0, 0.162, 0, 0.1, 0, 0.5, 0, 0, 0, - 1. / (10 * units::_GeV); - covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); - } - // Create curvilinear start parameters - CurvilinearParameters start(std::move(covPtr), pos, mom, q); - const auto result_s = propagator.propagate(start, options).value(); - const auto& tp_s = result_s.endParameters; - - // The transform at the destination - auto seTransform = planar - ? createPlanarTransform(tp_s->position(), - tp_s->momentum().normalized(), - 0.1 * rand3, - 0.1 * rand1) - : createCylindricTransform( - tp_s->position(), 0.05 * rand1, 0.05 * rand2); - - auto endSurface = Surface::makeShared<Surface_type>(seTransform, nullptr); - // Increase the path limit - to be safe hitting the surface - options.pathLimit *= 2; - - if (debug) { - std::cout << ">>> Path limit for this propgation is set to: " - << options.pathLimit << std::endl; - } - - auto result = propagator.propagate(start, *endSurface, options); - const auto& propRes = *result; - const auto& tp = propRes.endParameters; - // check the result for nullptr - BOOST_CHECK(tp != nullptr); - - // screen output in case you are running in debug mode - if (debug) { - const auto& debugOutput - = propRes.template get<DebugOutput::result_type>(); - std::cout << ">>> Debug output of this propagation " << std::endl; - std::cout << debugOutput.debugString << std::endl; - std::cout << ">>> Propagation status is : "; - if (result.ok()) { - std::cout << "success"; - } else { - std::cout << result.error(); - } - std::cout << std::endl; - } - - // The position and path length - return std::pair<Vector3D, double>(tp->position(), propRes.pathLength); +// test propagation to cylinder +template <typename Propagator_type> +std::pair<Vector3D, double> to_cylinder( + const Propagator_type& propagator, double pT, double phi, double theta, + double charge, double plimit, double rand1, double rand2, double /*rand3*/, + bool covtransport = false, bool debug = false) { + // setup propagation options + PropagatorOptions<> options(tgContext, mfContext); + // setup propagation options + options.maxStepSize = plimit; + options.pathLimit = plimit; + options.debug = debug; + + // define start parameters + double x = 0; + double y = 0; + double z = 0; + double px = pT * cos(phi); + double py = pT * sin(phi); + double pz = pT / tan(theta); + double q = charge; + Vector3D pos(x, y, z); + Vector3D mom(px, py, pz); + + std::unique_ptr<const ActsSymMatrixD<5>> covPtr = nullptr; + if (covtransport) { + ActsSymMatrixD<5> cov; + // take some major correlations (off-diagonals) + cov << 10 * units::_mm, 0, 0.123, 0, 0.5, 0, 10 * units::_mm, 0, 0.162, 0, + 0.123, 0, 0.1, 0, 0, 0, 0.162, 0, 0.1, 0, 0.5, 0, 0, 0, + 1. / (10 * units::_GeV); + covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); } + // do propagation of the start parameters + CurvilinearParameters start(std::move(covPtr), pos, mom, q); + + // The transform at the destination + auto seTransform = createCylindricTransform(Vector3D(0., 0., 0.), + 0.05 * rand1, 0.05 * rand2); + auto endSurface = Surface::makeShared<CylinderSurface>( + seTransform, plimit * units::_m, std::numeric_limits<double>::max()); + + // Increase the path limit - to be safe hitting the surface + options.pathLimit *= 2; + const auto result = propagator.propagate(start, *endSurface, options).value(); + const auto& tp = result.endParameters; + // check for null pointer + BOOST_CHECK(tp != nullptr); + // The position and path length + return std::pair<Vector3D, double>(tp->position(), result.pathLength); +} - template <typename Propagator_type> - void - covariance_curvilinear(const Propagator_type& propagator, - double pT, - double phi, - double theta, - double charge, - double plimit, - int /*index*/, - double reltol = 1e-3, - bool debug = false) - { - covariance_validation_fixture<Propagator_type> fixture(propagator); - // setup propagation options - DenseStepperPropagatorOptions<> options(tgContext, mfContext); - // setup propagation options - options.maxStepSize = plimit; - options.pathLimit = plimit; - options.debug = debug; - options.tolerance = 1e-7; - - // define start parameters - double x = 1.; - double y = 0.; - double z = 0.; - double px = pT * cos(phi); - double py = pT * sin(phi); - double pz = pT / tan(theta); - double q = charge; - Vector3D pos(x, y, z); - Vector3D mom(px, py, pz); - +// test propagation to most surfaces +template <typename Propagator_type, typename Surface_type> +std::pair<Vector3D, double> to_surface( + const Propagator_type& propagator, double pT, double phi, double theta, + double charge, double plimit, double rand1, double rand2, double rand3, + bool planar = true, bool covtransport = false, bool debug = false) { + using DebugOutput = detail::DebugOutputActor; + + // setup propagation options + PropagatorOptions<ActionList<DebugOutput>> options(tgContext, mfContext); + // setup propagation options + options.maxStepSize = plimit; + options.pathLimit = plimit; + options.debug = debug; + + // define start parameters + double x = 0; + double y = 0; + double z = 0; + double px = pT * cos(phi); + double py = pT * sin(phi); + double pz = pT / tan(theta); + double q = charge; + Vector3D pos(x, y, z); + Vector3D mom(px, py, pz); + + std::unique_ptr<const ActsSymMatrixD<5>> covPtr = nullptr; + if (covtransport) { ActsSymMatrixD<5> cov; // take some major correlations (off-diagonals) - cov << 10. * units::_mm, 0, 0.123, 0, 0.5, 0, 10. * units::_mm, 0, 0.162, 0, + cov << 10 * units::_mm, 0, 0.123, 0, 0.5, 0, 10 * units::_mm, 0, 0.162, 0, 0.123, 0, 0.1, 0, 0, 0, 0.162, 0, 0.1, 0, 0.5, 0, 0, 0, - 1. / (10. * units::_GeV); - auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); - - // do propagation of the start parameters - CurvilinearParameters start(std::move(covPtr), pos, mom, q); - CurvilinearParameters start_wo_c(nullptr, pos, mom, q); - - const auto result = propagator.propagate(start, options).value(); - const auto& tp = result.endParameters; + 1. / (10 * units::_GeV); + covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); + } + // Create curvilinear start parameters + CurvilinearParameters start(std::move(covPtr), pos, mom, q); + const auto result_s = propagator.propagate(start, options).value(); + const auto& tp_s = result_s.endParameters; + + // The transform at the destination + auto seTransform = planar + ? createPlanarTransform(tp_s->position(), + tp_s->momentum().normalized(), + 0.1 * rand3, 0.1 * rand1) + : createCylindricTransform(tp_s->position(), + 0.05 * rand1, 0.05 * rand2); + + auto endSurface = Surface::makeShared<Surface_type>(seTransform, nullptr); + // Increase the path limit - to be safe hitting the surface + options.pathLimit *= 2; + + if (debug) { + std::cout << ">>> Path limit for this propgation is set to: " + << options.pathLimit << std::endl; + } - // get numerically propagated covariance matrix - ActsSymMatrixD<5> calculated_cov = fixture.calculateCovariance( - start_wo_c, *(start.covariance()), *tp, options); - ActsSymMatrixD<5> obtained_cov = (*(tp->covariance())); - CHECK_CLOSE_COVARIANCE(calculated_cov, obtained_cov, reltol); + auto result = propagator.propagate(start, *endSurface, options); + const auto& propRes = *result; + const auto& tp = propRes.endParameters; + // check the result for nullptr + BOOST_CHECK(tp != nullptr); + + // screen output in case you are running in debug mode + if (debug) { + const auto& debugOutput = propRes.template get<DebugOutput::result_type>(); + std::cout << ">>> Debug output of this propagation " << std::endl; + std::cout << debugOutput.debugString << std::endl; + std::cout << ">>> Propagation status is : "; + if (result.ok()) { + std::cout << "success"; + } else { + std::cout << result.error(); + } + std::cout << std::endl; } - template <typename Propagator_type, - typename StartSurface_type, - typename DestSurface_type> - void - covariance_bound(const Propagator_type& propagator, - double pT, - double phi, - double theta, - double charge, - double plimit, - double rand1, - double rand2, - double rand3, - int /*index*/, - bool startPlanar = true, - bool destPlanar = true, - double reltol = 1e-3, - bool debug = false) - { - covariance_validation_fixture<Propagator_type> fixture(propagator); - // setup propagation options - DenseStepperPropagatorOptions<> options(tgContext, mfContext); - options.maxStepSize = plimit; - options.pathLimit = plimit; - options.debug = debug; - - // define start parameters - double x = 1.; - double y = 0.; - double z = 0.; - double px = pT * cos(phi); - double py = pT * sin(phi); - double pz = pT / tan(theta); - double q = charge; - Vector3D pos(x, y, z); - Vector3D mom(px, py, pz); - ActsSymMatrixD<5> cov; + // The position and path length + return std::pair<Vector3D, double>(tp->position(), propRes.pathLength); +} - // take some major correlations (off-diagonals) - // cov << 10 * units::_mm, 0, 0.123, 0, 0.5, 0, 10 * units::_mm, 0, 0.162, - // 0, - // 0.123, 0, 0.1, 0, 0, 0, 0.162, 0, 0.1, 0, 0.5, 0, 0, 0, - // 1. / (10 * units::_GeV); - - cov << 10. * units::_mm, 0, 0, 0, 0, 0, 10. * units::_mm, 0, 0, 0, 0, 0, - 0.1, 0, 0, 0, 0, 0, 0.1, 0, 0, 0, 0, 0, 1. / (10. * units::_GeV); - - auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); - - // create curvilinear start parameters - CurvilinearParameters start_c(nullptr, pos, mom, q); - const auto result_c = propagator.propagate(start_c, options).value(); - const auto& tp_c = result_c.endParameters; - - auto ssTransform = startPlanar - ? createPlanarTransform(pos, mom.normalized(), 0.1 * rand1, 0.1 * rand2) - : createCylindricTransform(pos, 0.05 * rand1, 0.05 * rand2); - auto seTransform = destPlanar - ? createPlanarTransform(tp_c->position(), - tp_c->momentum().normalized(), - 0.1 * rand3, - 0.1 * rand1) - : createCylindricTransform( - tp_c->position(), 0.05 * rand1, 0.05 * rand2); - - auto startSurface - = Surface::makeShared<StartSurface_type>(ssTransform, nullptr); - BoundParameters start( - tgContext, std::move(covPtr), pos, mom, q, startSurface); - BoundParameters start_wo_c(tgContext, nullptr, pos, mom, q, startSurface); - - // increase the path limit - to be safe hitting the surface - options.pathLimit *= 2; - - auto endSurface - = Surface::makeShared<DestSurface_type>(seTransform, nullptr); - const auto result - = propagator.propagate(start, *endSurface, options).value(); - const auto& tp = result.endParameters; - - // get obtained covariance matrix - ActsSymMatrixD<5> obtained_cov = (*(tp->covariance())); - - // get numerically propagated covariance matrix - ActsSymMatrixD<5> calculated_cov = fixture.calculateCovariance( - start_wo_c, *(start.covariance()), *tp, options); - - CHECK_CLOSE_COVARIANCE(calculated_cov, obtained_cov, reltol); - } +template <typename Propagator_type> +void covariance_curvilinear(const Propagator_type& propagator, double pT, + double phi, double theta, double charge, + double plimit, int /*index*/, double reltol = 1e-3, + bool debug = false) { + covariance_validation_fixture<Propagator_type> fixture(propagator); + // setup propagation options + DenseStepperPropagatorOptions<> options(tgContext, mfContext); + // setup propagation options + options.maxStepSize = plimit; + options.pathLimit = plimit; + options.debug = debug; + options.tolerance = 1e-7; + + // define start parameters + double x = 1.; + double y = 0.; + double z = 0.; + double px = pT * cos(phi); + double py = pT * sin(phi); + double pz = pT / tan(theta); + double q = charge; + Vector3D pos(x, y, z); + Vector3D mom(px, py, pz); + + ActsSymMatrixD<5> cov; + // take some major correlations (off-diagonals) + cov << 10. * units::_mm, 0, 0.123, 0, 0.5, 0, 10. * units::_mm, 0, 0.162, 0, + 0.123, 0, 0.1, 0, 0, 0, 0.162, 0, 0.1, 0, 0.5, 0, 0, 0, + 1. / (10. * units::_GeV); + auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); + + // do propagation of the start parameters + CurvilinearParameters start(std::move(covPtr), pos, mom, q); + CurvilinearParameters start_wo_c(nullptr, pos, mom, q); + + const auto result = propagator.propagate(start, options).value(); + const auto& tp = result.endParameters; + + // get numerically propagated covariance matrix + ActsSymMatrixD<5> calculated_cov = fixture.calculateCovariance( + start_wo_c, *(start.covariance()), *tp, options); + ActsSymMatrixD<5> obtained_cov = (*(tp->covariance())); + CHECK_CLOSE_COVARIANCE(calculated_cov, obtained_cov, reltol); } + +template <typename Propagator_type, typename StartSurface_type, + typename DestSurface_type> +void covariance_bound(const Propagator_type& propagator, double pT, double phi, + double theta, double charge, double plimit, double rand1, + double rand2, double rand3, int /*index*/, + bool startPlanar = true, bool destPlanar = true, + double reltol = 1e-3, bool debug = false) { + covariance_validation_fixture<Propagator_type> fixture(propagator); + // setup propagation options + DenseStepperPropagatorOptions<> options(tgContext, mfContext); + options.maxStepSize = plimit; + options.pathLimit = plimit; + options.debug = debug; + + // define start parameters + double x = 1.; + double y = 0.; + double z = 0.; + double px = pT * cos(phi); + double py = pT * sin(phi); + double pz = pT / tan(theta); + double q = charge; + Vector3D pos(x, y, z); + Vector3D mom(px, py, pz); + ActsSymMatrixD<5> cov; + + // take some major correlations (off-diagonals) + // cov << 10 * units::_mm, 0, 0.123, 0, 0.5, 0, 10 * units::_mm, 0, 0.162, + // 0, + // 0.123, 0, 0.1, 0, 0, 0, 0.162, 0, 0.1, 0, 0.5, 0, 0, 0, + // 1. / (10 * units::_GeV); + + cov << 10. * units::_mm, 0, 0, 0, 0, 0, 10. * units::_mm, 0, 0, 0, 0, 0, 0.1, + 0, 0, 0, 0, 0, 0.1, 0, 0, 0, 0, 0, 1. / (10. * units::_GeV); + + auto covPtr = std::make_unique<const ActsSymMatrixD<5>>(cov); + + // create curvilinear start parameters + CurvilinearParameters start_c(nullptr, pos, mom, q); + const auto result_c = propagator.propagate(start_c, options).value(); + const auto& tp_c = result_c.endParameters; + + auto ssTransform = + startPlanar ? createPlanarTransform(pos, mom.normalized(), 0.1 * rand1, + 0.1 * rand2) + : createCylindricTransform(pos, 0.05 * rand1, 0.05 * rand2); + auto seTransform = destPlanar + ? createPlanarTransform(tp_c->position(), + tp_c->momentum().normalized(), + 0.1 * rand3, 0.1 * rand1) + : createCylindricTransform(tp_c->position(), + 0.05 * rand1, 0.05 * rand2); + + auto startSurface = + Surface::makeShared<StartSurface_type>(ssTransform, nullptr); + BoundParameters start(tgContext, std::move(covPtr), pos, mom, q, + startSurface); + BoundParameters start_wo_c(tgContext, nullptr, pos, mom, q, startSurface); + + // increase the path limit - to be safe hitting the surface + options.pathLimit *= 2; + + auto endSurface = Surface::makeShared<DestSurface_type>(seTransform, nullptr); + const auto result = propagator.propagate(start, *endSurface, options).value(); + const auto& tp = result.endParameters; + + // get obtained covariance matrix + ActsSymMatrixD<5> obtained_cov = (*(tp->covariance())); + + // get numerically propagated covariance matrix + ActsSymMatrixD<5> calculated_cov = fixture.calculateCovariance( + start_wo_c, *(start.covariance()), *tp, options); + + CHECK_CLOSE_COVARIANCE(calculated_cov, obtained_cov, reltol); } +} // namespace IntegrationTest +} // namespace Acts diff --git a/Tests/Integration/PropagationTests.cpp b/Tests/Integration/PropagationTests.cpp index dda90fdfbba47f0e28dc011c5cf215935b1b4bf3..5e2b45a4666a0d28c9fc1cd47d3919b404a05d78 100644 --- a/Tests/Integration/PropagationTests.cpp +++ b/Tests/Integration/PropagationTests.cpp @@ -38,106 +38,97 @@ #include "PropagationTestHelper.hpp" namespace bdata = boost::unit_test::data; -namespace tt = boost::test_tools; +namespace tt = boost::test_tools; namespace Acts { namespace IntegrationTest { - using BFieldType = ConstantBField; - using EigenStepperType = EigenStepper<BFieldType>; - using DenseStepperType - = EigenStepper<BFieldType, - VoidIntersectionCorrector, - StepperExtensionList<DenseEnvironmentExtension>>; - using AtlasStepperType = AtlasStepper<BFieldType>; - using EigenPropagatorType = Propagator<EigenStepperType>; - using DensePropagatorType = Propagator<DenseStepperType, Navigator>; - using AtlasPropagatorType = Propagator<AtlasStepperType>; - - // number of tests - const int ntests = 100; - const int skip = 0; - const bool covtpr = true; - const bool debug = false; - - // setup propagator with constant B-field - const double Bz = 2. * units::_T; - BFieldType bField(0, 0, Bz); - EigenStepperType estepper(bField); - DenseStepperType dstepper(bField); - EigenPropagatorType epropagator(std::move(estepper)); - AtlasStepperType astepper(bField); - AtlasPropagatorType apropagator(std::move(astepper)); - - DensePropagatorType - setupDensePropagator() - { - CuboidVolumeBuilder::VolumeConfig vConf; - vConf.position = {1.5 * units::_m, 0., 0.}; - vConf.length = {3. * units::_m, 1. * units::_m, 1. * units::_m}; - vConf.volumeMaterial = std::make_shared<const HomogeneousVolumeMaterial>( - Material(352.8, 407., 9.012, 4., 1.848e-3)); - CuboidVolumeBuilder::Config conf; - conf.volumeCfg.push_back(vConf); - conf.position = {1.5 * units::_m, 0., 0.}; - conf.length = {3. * units::_m, 1. * units::_m, 1. * units::_m}; - CuboidVolumeBuilder cvb(conf); - TrackingGeometryBuilder::Config tgbCfg; - tgbCfg.trackingVolumeBuilders.push_back( - [=](const auto& context, const auto& inner, const auto&) { - return cvb.trackingVolume(context, inner, nullptr); - }); - TrackingGeometryBuilder tgb(tgbCfg); - std::shared_ptr<const TrackingGeometry> detector - = tgb.trackingGeometry(tgContext); - Navigator navi(detector); - return DensePropagatorType(dstepper, std::move(navi)); +using BFieldType = ConstantBField; +using EigenStepperType = EigenStepper<BFieldType>; +using DenseStepperType = + EigenStepper<BFieldType, VoidIntersectionCorrector, + StepperExtensionList<DenseEnvironmentExtension>>; +using AtlasStepperType = AtlasStepper<BFieldType>; +using EigenPropagatorType = Propagator<EigenStepperType>; +using DensePropagatorType = Propagator<DenseStepperType, Navigator>; +using AtlasPropagatorType = Propagator<AtlasStepperType>; + +// number of tests +const int ntests = 100; +const int skip = 0; +const bool covtpr = true; +const bool debug = false; + +// setup propagator with constant B-field +const double Bz = 2. * units::_T; +BFieldType bField(0, 0, Bz); +EigenStepperType estepper(bField); +DenseStepperType dstepper(bField); +EigenPropagatorType epropagator(std::move(estepper)); +AtlasStepperType astepper(bField); +AtlasPropagatorType apropagator(std::move(astepper)); + +DensePropagatorType setupDensePropagator() { + CuboidVolumeBuilder::VolumeConfig vConf; + vConf.position = {1.5 * units::_m, 0., 0.}; + vConf.length = {3. * units::_m, 1. * units::_m, 1. * units::_m}; + vConf.volumeMaterial = std::make_shared<const HomogeneousVolumeMaterial>( + Material(352.8, 407., 9.012, 4., 1.848e-3)); + CuboidVolumeBuilder::Config conf; + conf.volumeCfg.push_back(vConf); + conf.position = {1.5 * units::_m, 0., 0.}; + conf.length = {3. * units::_m, 1. * units::_m, 1. * units::_m}; + CuboidVolumeBuilder cvb(conf); + TrackingGeometryBuilder::Config tgbCfg; + tgbCfg.trackingVolumeBuilders.push_back( + [=](const auto& context, const auto& inner, const auto&) { + return cvb.trackingVolume(context, inner, nullptr); + }); + TrackingGeometryBuilder tgb(tgbCfg); + std::shared_ptr<const TrackingGeometry> detector = + tgb.trackingGeometry(tgContext); + Navigator navi(detector); + return DensePropagatorType(dstepper, std::move(navi)); +} + +// The constant field test +/// test forward propagation in constant magnetic field +BOOST_DATA_TEST_CASE( + constant_bfieldforward_propagation_, + bdata::random((bdata::seed = 0, + bdata::distribution = std::uniform_real_distribution<>( + 0.4 * units::_GeV, 10. * units::_GeV))) ^ + bdata::random((bdata::seed = 1, + bdata::distribution = + std::uniform_real_distribution<>(-M_PI, M_PI))) ^ + bdata::random((bdata::seed = 2, + bdata::distribution = + std::uniform_real_distribution<>(0.1, M_PI - 0.1))) ^ + bdata::random( + (bdata::seed = 3, + bdata::distribution = std::uniform_int_distribution<>(0, 1))) ^ + bdata::xrange(ntests), + pT, phi, theta, charge, index) { + if (index < skip) { + return; } - // The constant field test - /// test forward propagation in constant magnetic field - BOOST_DATA_TEST_CASE( - constant_bfieldforward_propagation_, - bdata::random((bdata::seed = 0, - bdata::distribution - = std::uniform_real_distribution<>(0.4 * units::_GeV, - 10. * units::_GeV))) - ^ bdata::random((bdata::seed = 1, - bdata::distribution - = std::uniform_real_distribution<>(-M_PI, M_PI))) - ^ bdata::random((bdata::seed = 2, - bdata::distribution - = std::uniform_real_distribution<>(0.1, M_PI - 0.1))) - ^ bdata::random((bdata::seed = 3, - bdata::distribution - = std::uniform_int_distribution<>(0, 1))) - ^ bdata::xrange(ntests), - pT, - phi, - theta, - charge, - index) - { - if (index < skip) { - return; - } - - double dcharge = -1 + 2 * charge; - // constant field propagation atlas stepper - auto aposition = constant_field_propagation( - apropagator, pT, phi, theta, dcharge, index, Bz); - // constant field propagation eigen stepper - auto eposition = constant_field_propagation( - epropagator, pT, phi, theta, dcharge, index, Bz); - // check consistency - CHECK_CLOSE_REL(eposition, aposition, 1e-6); - } + double dcharge = -1 + 2 * charge; + // constant field propagation atlas stepper + auto aposition = constant_field_propagation(apropagator, pT, phi, theta, + dcharge, index, Bz); + // constant field propagation eigen stepper + auto eposition = constant_field_propagation(epropagator, pT, phi, theta, + dcharge, index, Bz); + // check consistency + CHECK_CLOSE_REL(eposition, aposition, 1e-6); +} // The actual test - needs to be included to avoid // template inside template definition through boost #include "PropagationTestBase.hpp" -} // namespace Test +} // namespace IntegrationTest } // namespace Acts diff --git a/Tests/Integration/PropagationTestsAtlasField.cpp b/Tests/Integration/PropagationTestsAtlasField.cpp index 5b0bb2bc6db208b802a63de02cbd3eabde331b24..3e7242c4a6178d06cad91fd1d1dad5f63deb19ff 100644 --- a/Tests/Integration/PropagationTestsAtlasField.cpp +++ b/Tests/Integration/PropagationTestsAtlasField.cpp @@ -33,7 +33,7 @@ #include "PropagationTestHelper.hpp" namespace bdata = boost::unit_test::data; -namespace tt = boost::test_tools; +namespace tt = boost::test_tools; namespace Acts { @@ -43,101 +43,87 @@ namespace Acts { namespace IntegrationTest { - // Create a mapper from the a text file - InterpolatedBFieldMap::FieldMapper<3, 3> readFieldXYZ( - std::function<size_t(std::array<size_t, 3> binsXYZ, - std::array<size_t, 3> nBinsXYZ)> localToGlobalBin, - std::string fieldMapFile = "Field.txt", - double lengthUnit = 1., - double BFieldUnit = 1., - size_t nPoints = 100000, - bool firstOctant = false) - { - /// [1] Read in field map file - // Grid position points in x, y and z - std::vector<double> xPos; - std::vector<double> yPos; - std::vector<double> zPos; - // components of magnetic field on grid points - std::vector<Acts::Vector3D> bField; - // reserve estimated size - xPos.reserve(nPoints); - yPos.reserve(nPoints); - zPos.reserve(nPoints); - bField.reserve(nPoints); - // [1] Read in file and fill values - std::ifstream map_file(fieldMapFile.c_str(), std::ios::in); - std::string line; - double x = 0., y = 0., z = 0.; - double bx = 0., by = 0., bz = 0.; - while (std::getline(map_file, line)) { - if (line.empty() || line[0] == '%' || line[0] == '#' - || line.find_first_not_of(' ') == std::string::npos) - continue; - - std::istringstream tmp(line); - tmp >> x >> y >> z >> bx >> by >> bz; - xPos.push_back(x); - yPos.push_back(y); - zPos.push_back(z); - bField.push_back(Acts::Vector3D(bx, by, bz)); - } - map_file.close(); - - return fieldMapperXYZ(localToGlobalBin, - xPos, - yPos, - zPos, - bField, - lengthUnit, - BFieldUnit, - firstOctant); +// Create a mapper from the a text file +InterpolatedBFieldMap::FieldMapper<3, 3> readFieldXYZ( + std::function<size_t(std::array<size_t, 3> binsXYZ, + std::array<size_t, 3> nBinsXYZ)> + localToGlobalBin, + std::string fieldMapFile = "Field.txt", double lengthUnit = 1., + double BFieldUnit = 1., size_t nPoints = 100000, bool firstOctant = false) { + /// [1] Read in field map file + // Grid position points in x, y and z + std::vector<double> xPos; + std::vector<double> yPos; + std::vector<double> zPos; + // components of magnetic field on grid points + std::vector<Acts::Vector3D> bField; + // reserve estimated size + xPos.reserve(nPoints); + yPos.reserve(nPoints); + zPos.reserve(nPoints); + bField.reserve(nPoints); + // [1] Read in file and fill values + std::ifstream map_file(fieldMapFile.c_str(), std::ios::in); + std::string line; + double x = 0., y = 0., z = 0.; + double bx = 0., by = 0., bz = 0.; + while (std::getline(map_file, line)) { + if (line.empty() || line[0] == '%' || line[0] == '#' || + line.find_first_not_of(' ') == std::string::npos) + continue; + + std::istringstream tmp(line); + tmp >> x >> y >> z >> bx >> by >> bz; + xPos.push_back(x); + yPos.push_back(y); + zPos.push_back(z); + bField.push_back(Acts::Vector3D(bx, by, bz)); } - - // create a bfiel map from a mapper - std::shared_ptr<const InterpolatedBFieldMap> - atlasBField(std::string fieldMapFile = "Field.txt") - { - - // Declare the mapper - concept::AnyFieldLookup<> mapper; - double lengthUnit = units::_mm; - double BFieldUnit = units::_T; - // read the field x,y,z from a text file - mapper = readFieldXYZ( - [](std::array<size_t, 3> binsXYZ, std::array<size_t, 3> nBinsXYZ) { - return (binsXYZ.at(0) * (nBinsXYZ.at(1) * nBinsXYZ.at(2)) - + binsXYZ.at(1) * nBinsXYZ.at(2) - + binsXYZ.at(2)); - }, - fieldMapFile, - lengthUnit, - BFieldUnit); - // create the config - InterpolatedBFieldMap::Config config; - config.scale = 1.; - config.mapper = std::move(mapper); - // make the interpolated field - return std::make_shared<const InterpolatedBFieldMap>(std::move(config)); - } - - double Bz = 2. * units::_T; - - using BFieldType = InterpolatedBFieldMap; - using SharedFieldType = SharedBField<InterpolatedBFieldMap>; - using EigenStepperType = EigenStepper<SharedFieldType>; - using AtlasStepperType = AtlasStepper<SharedFieldType>; - using EigenPropagatorType = Propagator<EigenStepperType>; - using AtlasPropagatorType = Propagator<AtlasStepperType>; - - auto bField = atlasBField("Field.txt"); - auto bFieldSharedA = SharedFieldType(bField); - auto bFieldSharedE = SharedFieldType(bField); - - EigenStepperType estepper(bFieldSharedE); - EigenPropagatorType epropagator(std::move(estepper)); - AtlasStepperType astepper(bFieldSharedA); - AtlasPropagatorType apropagator(std::move(astepper)); + map_file.close(); + + return fieldMapperXYZ(localToGlobalBin, xPos, yPos, zPos, bField, lengthUnit, + BFieldUnit, firstOctant); +} + +// create a bfiel map from a mapper +std::shared_ptr<const InterpolatedBFieldMap> atlasBField( + std::string fieldMapFile = "Field.txt") { + // Declare the mapper + concept ::AnyFieldLookup<> mapper; + double lengthUnit = units::_mm; + double BFieldUnit = units::_T; + // read the field x,y,z from a text file + mapper = readFieldXYZ( + [](std::array<size_t, 3> binsXYZ, std::array<size_t, 3> nBinsXYZ) { + return (binsXYZ.at(0) * (nBinsXYZ.at(1) * nBinsXYZ.at(2)) + + binsXYZ.at(1) * nBinsXYZ.at(2) + binsXYZ.at(2)); + }, + fieldMapFile, lengthUnit, BFieldUnit); + // create the config + InterpolatedBFieldMap::Config config; + config.scale = 1.; + config.mapper = std::move(mapper); + // make the interpolated field + return std::make_shared<const InterpolatedBFieldMap>(std::move(config)); +} + +double Bz = 2. * units::_T; + +using BFieldType = InterpolatedBFieldMap; +using SharedFieldType = SharedBField<InterpolatedBFieldMap>; +using EigenStepperType = EigenStepper<SharedFieldType>; +using AtlasStepperType = AtlasStepper<SharedFieldType>; +using EigenPropagatorType = Propagator<EigenStepperType>; +using AtlasPropagatorType = Propagator<AtlasStepperType>; + +auto bField = atlasBField("Field.txt"); +auto bFieldSharedA = SharedFieldType(bField); +auto bFieldSharedE = SharedFieldType(bField); + +EigenStepperType estepper(bFieldSharedE); +EigenPropagatorType epropagator(std::move(estepper)); +AtlasStepperType astepper(bFieldSharedA); +AtlasPropagatorType apropagator(std::move(astepper)); // The actual test - needs to be included to avoid // template inside template definition through boost diff --git a/Tests/Integration/covariance_validation_fixture.hpp b/Tests/Integration/covariance_validation_fixture.hpp index 666ea8403c0aba563416e74030785ebb93f1e8a2..e3ce056afd46ab5751af926ba39a5986538a7243 100644 --- a/Tests/Integration/covariance_validation_fixture.hpp +++ b/Tests/Integration/covariance_validation_fixture.hpp @@ -18,150 +18,141 @@ namespace Acts { namespace IntegrationTest { - template <typename T> - struct covariance_validation_fixture - { - public: - covariance_validation_fixture(T propagator) - : m_propagator(std::move(propagator)) - { +template <typename T> +struct covariance_validation_fixture { + public: + covariance_validation_fixture(T propagator) + : m_propagator(std::move(propagator)) {} + + /// Numerical transport of covariance using the ridder's algorithm + /// this is for covariance propagation validation + /// it can either be used for curvilinear transport + template <typename StartParameters, typename EndParameters, typename U> + ActsSymMatrixD<5> calculateCovariance(const StartParameters& startPars, + const ActsSymMatrixD<5>& startCov, + const EndParameters& endPars, + const U& options) const { + // steps for estimating derivatives + const std::array<double, 4> h_steps = {{-2e-4, -1e-4, 1e-4, 2e-4}}; + + // nominal propagation + const auto& nominal = endPars.parameters(); + const Surface& dest = endPars.referenceSurface(); + + // - for planar surfaces the dest surface is a perfect destination + // surface for the numerical propagation, as reference frame + // aligns with the referenceSurface.transform().rotation() at + // at any given time + // + // - for straw & cylinder, where the error is given + // in the reference frame that re-aligns with a slightly different + // intersection solution + + // avoid stopping before the surface because of path length reached + U var_options = options; + var_options.pathLimit *= 2; + + // variation in x + std::vector<ActsVectorD<5>> x_derivatives; + x_derivatives.reserve(h_steps.size()); + for (double h : h_steps) { + StartParameters tp = startPars; + tp.template set<Acts::eLOC_0>(options.geoContext, + tp.template get<Acts::eLOC_0>() + h); + const auto& r = m_propagator.propagate(tp, dest, var_options).value(); + x_derivatives.push_back((r.endParameters->parameters() - nominal) / h); } - /// Numerical transport of covariance using the ridder's algorithm - /// this is for covariance propagation validation - /// it can either be used for curvilinear transport - template <typename StartParameters, typename EndParameters, typename U> - ActsSymMatrixD<5> - calculateCovariance(const StartParameters& startPars, - const ActsSymMatrixD<5>& startCov, - const EndParameters& endPars, - const U& options) const - { - // steps for estimating derivatives - const std::array<double, 4> h_steps = {{-2e-4, -1e-4, 1e-4, 2e-4}}; - - // nominal propagation - const auto& nominal = endPars.parameters(); - const Surface& dest = endPars.referenceSurface(); - - // - for planar surfaces the dest surface is a perfect destination - // surface for the numerical propagation, as reference frame - // aligns with the referenceSurface.transform().rotation() at - // at any given time - // - // - for straw & cylinder, where the error is given - // in the reference frame that re-aligns with a slightly different - // intersection solution - - // avoid stopping before the surface because of path length reached - U var_options = options; - var_options.pathLimit *= 2; - - // variation in x - std::vector<ActsVectorD<5>> x_derivatives; - x_derivatives.reserve(h_steps.size()); - for (double h : h_steps) { - StartParameters tp = startPars; - tp.template set<Acts::eLOC_0>(options.geoContext, - tp.template get<Acts::eLOC_0>() + h); - const auto& r = m_propagator.propagate(tp, dest, var_options).value(); - x_derivatives.push_back((r.endParameters->parameters() - nominal) / h); - } - - // variation in y - std::vector<ActsVectorD<5>> y_derivatives; - y_derivatives.reserve(h_steps.size()); - for (double h : h_steps) { - StartParameters tp = startPars; - tp.template set<Acts::eLOC_1>(options.geoContext, - tp.template get<Acts::eLOC_1>() + h); - const auto& r = m_propagator.propagate(tp, dest, var_options).value(); - y_derivatives.push_back((r.endParameters->parameters() - nominal) / h); - } + // variation in y + std::vector<ActsVectorD<5>> y_derivatives; + y_derivatives.reserve(h_steps.size()); + for (double h : h_steps) { + StartParameters tp = startPars; + tp.template set<Acts::eLOC_1>(options.geoContext, + tp.template get<Acts::eLOC_1>() + h); + const auto& r = m_propagator.propagate(tp, dest, var_options).value(); + y_derivatives.push_back((r.endParameters->parameters() - nominal) / h); + } - // variation in phi - std::vector<ActsVectorD<5>> phi_derivatives; - phi_derivatives.reserve(h_steps.size()); - for (double h : h_steps) { - StartParameters tp = startPars; - tp.template set<Acts::ePHI>(options.geoContext, - tp.template get<Acts::ePHI>() + h); - const auto& r = m_propagator.propagate(tp, dest, var_options).value(); - phi_derivatives.push_back((r.endParameters->parameters() - nominal) - / h); - } + // variation in phi + std::vector<ActsVectorD<5>> phi_derivatives; + phi_derivatives.reserve(h_steps.size()); + for (double h : h_steps) { + StartParameters tp = startPars; + tp.template set<Acts::ePHI>(options.geoContext, + tp.template get<Acts::ePHI>() + h); + const auto& r = m_propagator.propagate(tp, dest, var_options).value(); + phi_derivatives.push_back((r.endParameters->parameters() - nominal) / h); + } - // variation in theta - std::vector<ActsVectorD<5>> theta_derivatives; - theta_derivatives.reserve(h_steps.size()); - for (double h : h_steps) { - StartParameters tp = startPars; - const double current_theta = tp.template get<Acts::eTHETA>(); - if (current_theta + h > M_PI) { - h = M_PI - current_theta; - } - if (current_theta + h < 0) { - h = -current_theta; - } - tp.template set<Acts::eTHETA>(options.geoContext, - tp.template get<Acts::eTHETA>() + h); - const auto& r = m_propagator.propagate(tp, dest, var_options).value(); - theta_derivatives.push_back((r.endParameters->parameters() - nominal) - / h); + // variation in theta + std::vector<ActsVectorD<5>> theta_derivatives; + theta_derivatives.reserve(h_steps.size()); + for (double h : h_steps) { + StartParameters tp = startPars; + const double current_theta = tp.template get<Acts::eTHETA>(); + if (current_theta + h > M_PI) { + h = M_PI - current_theta; } - - // variation in q/p - std::vector<ActsVectorD<5>> qop_derivatives; - qop_derivatives.reserve(h_steps.size()); - for (double h : h_steps) { - StartParameters tp = startPars; - tp.template set<Acts::eQOP>(options.geoContext, - tp.template get<Acts::eQOP>() + h); - const auto& r = m_propagator.propagate(tp, dest, var_options).value(); - qop_derivatives.push_back((r.endParameters->parameters() - nominal) - / h); + if (current_theta + h < 0) { + h = -current_theta; } + tp.template set<Acts::eTHETA>(options.geoContext, + tp.template get<Acts::eTHETA>() + h); + const auto& r = m_propagator.propagate(tp, dest, var_options).value(); + theta_derivatives.push_back((r.endParameters->parameters() - nominal) / + h); + } - ActsSymMatrixD<5> jacobian; - jacobian.setIdentity(); - jacobian.col(Acts::eLOC_0) = fitLinear(x_derivatives, h_steps); - jacobian.col(Acts::eLOC_1) = fitLinear(y_derivatives, h_steps); - jacobian.col(Acts::ePHI) = fitLinear(phi_derivatives, h_steps); - jacobian.col(Acts::eTHETA) = fitLinear(theta_derivatives, h_steps); - jacobian.col(Acts::eQOP) = fitLinear(qop_derivatives, h_steps); - - return jacobian * startCov * jacobian.transpose(); + // variation in q/p + std::vector<ActsVectorD<5>> qop_derivatives; + qop_derivatives.reserve(h_steps.size()); + for (double h : h_steps) { + StartParameters tp = startPars; + tp.template set<Acts::eQOP>(options.geoContext, + tp.template get<Acts::eQOP>() + h); + const auto& r = m_propagator.propagate(tp, dest, var_options).value(); + qop_derivatives.push_back((r.endParameters->parameters() - nominal) / h); } - private: - template <unsigned long int N> - static ActsVectorD<5> - fitLinear(const std::vector<ActsVectorD<5>>& values, - const std::array<double, N>& h) - { - ActsVectorD<5> A; - ActsVectorD<5> C; - A.setZero(); - C.setZero(); - double B = 0; - double D = 0; - - for (unsigned int i = 0; i < N; ++i) { - A += h.at(i) * values.at(i); - B += h.at(i); - C += values.at(i); - D += h.at(i) * h.at(i); - } + ActsSymMatrixD<5> jacobian; + jacobian.setIdentity(); + jacobian.col(Acts::eLOC_0) = fitLinear(x_derivatives, h_steps); + jacobian.col(Acts::eLOC_1) = fitLinear(y_derivatives, h_steps); + jacobian.col(Acts::ePHI) = fitLinear(phi_derivatives, h_steps); + jacobian.col(Acts::eTHETA) = fitLinear(theta_derivatives, h_steps); + jacobian.col(Acts::eQOP) = fitLinear(qop_derivatives, h_steps); + + return jacobian * startCov * jacobian.transpose(); + } + + private: + template <unsigned long int N> + static ActsVectorD<5> fitLinear(const std::vector<ActsVectorD<5>>& values, + const std::array<double, N>& h) { + ActsVectorD<5> A; + ActsVectorD<5> C; + A.setZero(); + C.setZero(); + double B = 0; + double D = 0; + + for (unsigned int i = 0; i < N; ++i) { + A += h.at(i) * values.at(i); + B += h.at(i); + C += values.at(i); + D += h.at(i) * h.at(i); + } - ActsVectorD<5> b = (N * A - B * C) / (N * D - B * B); - ActsVectorD<5> a = (C - B * b) / N; + ActsVectorD<5> b = (N * A - B * C) / (N * D - B * B); + ActsVectorD<5> a = (C - B * b) / N; - return a; - } + return a; + } - T m_propagator; - }; + T m_propagator; +}; -} // namespace Test +} // namespace IntegrationTest } // namespace Acts diff --git a/Tests/Plugins/Digitization/CartesianSegmentationTests.cpp b/Tests/Plugins/Digitization/CartesianSegmentationTests.cpp index e9e8f808e9a3421e25cc7bb32b74c5debff3524a..5c38a579902ebef529e547f90eff2289a1db29f6 100644 --- a/Tests/Plugins/Digitization/CartesianSegmentationTests.cpp +++ b/Tests/Plugins/Digitization/CartesianSegmentationTests.cpp @@ -22,110 +22,108 @@ #include "Acts/Tests/CommonHelpers/FloatComparisons.hpp" namespace bdata = boost::unit_test::data; -namespace tt = boost::test_tools; +namespace tt = boost::test_tools; namespace Acts { namespace Test { - size_t nbinsx = 100; - size_t nbinsy = 200; - double hThickness = 75 * units::_um; - double lAngle = 0.1; +size_t nbinsx = 100; +size_t nbinsy = 200; +double hThickness = 75 * units::_um; +double lAngle = 0.1; - // Module bounds - auto moduleBounds = std::make_shared<const RectangleBounds>(5 * units::_mm, - 10 * units::_mm); - CartesianSegmentation cSegmentation(moduleBounds, nbinsx, nbinsy); +// Module bounds +auto moduleBounds = + std::make_shared<const RectangleBounds>(5 * units::_mm, 10 * units::_mm); +CartesianSegmentation cSegmentation(moduleBounds, nbinsx, nbinsy); - // Create a test context - GeometryContext tgContext = GeometryContext(); +// Create a test context +GeometryContext tgContext = GeometryContext(); - /// @brief Unit test for the Cartesian segmentation - /// - BOOST_AUTO_TEST_CASE(cartesian_segmentation) - { +/// @brief Unit test for the Cartesian segmentation +/// +BOOST_AUTO_TEST_CASE(cartesian_segmentation) { + // The surface vectors: positive readout, zero lorentz angle + // -> PZL + SurfacePtrVector boundariesPZL; + SurfacePtrVector segSurfacesXPZL; + SurfacePtrVector segSurfacesYPZL; - // The surface vectors: positive readout, zero lorentz angle - // -> PZL - SurfacePtrVector boundariesPZL; - SurfacePtrVector segSurfacesXPZL; - SurfacePtrVector segSurfacesYPZL; + cSegmentation.createSegmentationSurfaces(boundariesPZL, segSurfacesXPZL, + segSurfacesYPZL, hThickness, 1, 0.); - cSegmentation.createSegmentationSurfaces( - boundariesPZL, segSurfacesXPZL, segSurfacesYPZL, hThickness, 1, 0.); + BOOST_CHECK_EQUAL(boundariesPZL.size(), 6); - BOOST_CHECK_EQUAL(boundariesPZL.size(), 6); + // There's one less because of the boundary and lorentz plane + BOOST_CHECK_EQUAL(segSurfacesXPZL.size(), size_t(nbinsx - 1)); + BOOST_CHECK_EQUAL(segSurfacesYPZL.size(), size_t(nbinsy - 1)); - // There's one less because of the boundary and lorentz plane - BOOST_CHECK_EQUAL(segSurfacesXPZL.size(), size_t(nbinsx - 1)); - BOOST_CHECK_EQUAL(segSurfacesYPZL.size(), size_t(nbinsy - 1)); + // Check the boundary surfaces are thickness away + auto centerReadoutPZL = boundariesPZL[0]->center(tgContext); + auto centerCounterPZL = boundariesPZL[1]->center(tgContext); + auto centerDiffPZL = centerReadoutPZL - centerCounterPZL; + double thicknessPZL = centerDiffPZL.norm(); - // Check the boundary surfaces are thickness away - auto centerReadoutPZL = boundariesPZL[0]->center(tgContext); - auto centerCounterPZL = boundariesPZL[1]->center(tgContext); - auto centerDiffPZL = centerReadoutPZL - centerCounterPZL; - double thicknessPZL = centerDiffPZL.norm(); + CHECK_CLOSE_REL(thicknessPZL, 2 * hThickness, 10e-6); - CHECK_CLOSE_REL(thicknessPZL, 2 * hThickness, 10e-6); + // The surface vectors: negative readout, zero lorentz angle + // -> NZL + SurfacePtrVector boundariesNZL; + SurfacePtrVector segSurfacesXNZL; + SurfacePtrVector segSurfacesYNZL; - // The surface vectors: negative readout, zero lorentz angle - // -> NZL - SurfacePtrVector boundariesNZL; - SurfacePtrVector segSurfacesXNZL; - SurfacePtrVector segSurfacesYNZL; + cSegmentation.createSegmentationSurfaces(boundariesNZL, segSurfacesXNZL, + segSurfacesYNZL, hThickness, -1, 0.); - cSegmentation.createSegmentationSurfaces( - boundariesNZL, segSurfacesXNZL, segSurfacesYNZL, hThickness, -1, 0.); + BOOST_CHECK_EQUAL(boundariesNZL.size(), 6); - BOOST_CHECK_EQUAL(boundariesNZL.size(), 6); + // There's one less because of the boundary and lorentz plane + BOOST_CHECK_EQUAL(segSurfacesXNZL.size(), size_t(nbinsx - 1)); + BOOST_CHECK_EQUAL(segSurfacesYNZL.size(), size_t(nbinsy - 1)); - // There's one less because of the boundary and lorentz plane - BOOST_CHECK_EQUAL(segSurfacesXNZL.size(), size_t(nbinsx - 1)); - BOOST_CHECK_EQUAL(segSurfacesYNZL.size(), size_t(nbinsy - 1)); + // Check the boundary surfaces are thickness away + auto centerReadoutNZL = boundariesNZL[0]->center(tgContext); + auto centerCounterNZL = boundariesNZL[1]->center(tgContext); + auto centerDiffNZL = centerReadoutNZL - centerCounterNZL; + double thicknessNZL = centerDiffNZL.norm(); - // Check the boundary surfaces are thickness away - auto centerReadoutNZL = boundariesNZL[0]->center(tgContext); - auto centerCounterNZL = boundariesNZL[1]->center(tgContext); - auto centerDiffNZL = centerReadoutNZL - centerCounterNZL; - double thicknessNZL = centerDiffNZL.norm(); + CHECK_CLOSE_REL(thicknessNZL, 2 * hThickness, 10e-6); - CHECK_CLOSE_REL(thicknessNZL, 2 * hThickness, 10e-6); + // Check that the readout / counter surfaces are reversed + CHECK_CLOSE_OR_SMALL(centerReadoutPZL, centerCounterNZL, 10e-6, 10e-9); + CHECK_CLOSE_OR_SMALL(centerReadoutNZL, centerCounterPZL, 10e-6, 10e-9); - // Check that the readout / counter surfaces are reversed - CHECK_CLOSE_OR_SMALL(centerReadoutPZL, centerCounterNZL, 10e-6, 10e-9); - CHECK_CLOSE_OR_SMALL(centerReadoutNZL, centerCounterPZL, 10e-6, 10e-9); + // The surface vectors: positive readout, lorentz angle + // -> PL + SurfacePtrVector boundariesPL; + SurfacePtrVector segSurfacesXPL; + SurfacePtrVector segSurfacesYPL; - // The surface vectors: positive readout, lorentz angle - // -> PL - SurfacePtrVector boundariesPL; - SurfacePtrVector segSurfacesXPL; - SurfacePtrVector segSurfacesYPL; + cSegmentation.createSegmentationSurfaces( + boundariesPL, segSurfacesXPL, segSurfacesYPL, hThickness, 1, lAngle); - cSegmentation.createSegmentationSurfaces( - boundariesPL, segSurfacesXPL, segSurfacesYPL, hThickness, 1, lAngle); + BOOST_CHECK_EQUAL(boundariesPL.size(), 6); - BOOST_CHECK_EQUAL(boundariesPL.size(), 6); + // There's one less because of the boundary and lorentz plane + BOOST_CHECK_EQUAL(segSurfacesXPL.size(), size_t(nbinsx - 1)); + BOOST_CHECK_EQUAL(segSurfacesYPL.size(), size_t(nbinsy - 1)); - // There's one less because of the boundary and lorentz plane - BOOST_CHECK_EQUAL(segSurfacesXPL.size(), size_t(nbinsx - 1)); - BOOST_CHECK_EQUAL(segSurfacesYPL.size(), size_t(nbinsy - 1)); + // Check the boundary surfaces are thickness away + auto centerReadoutPL = boundariesPL[0]->center(tgContext); + auto centerCoutnerPL = boundariesPL[1]->center(tgContext); + double thicknessPL = abs((centerReadoutPL - centerCoutnerPL).z()); - // Check the boundary surfaces are thickness away - auto centerReadoutPL = boundariesPL[0]->center(tgContext); - auto centerCoutnerPL = boundariesPL[1]->center(tgContext); - double thicknessPL = abs((centerReadoutPL - centerCoutnerPL).z()); + CHECK_CLOSE_REL(thicknessPL, 2 * hThickness, 10e-6); - CHECK_CLOSE_REL(thicknessPL, 2 * hThickness, 10e-6); + // check the lorentz angle - let's take the second one + auto nLorentzPlane = segSurfacesXPL[2]->normal(tgContext); - // check the lorentz angle - let's take the second one - auto nLorentzPlane = segSurfacesXPL[2]->normal(tgContext); + Vector3D nNominal(1., 0., 0.); + double tAngle = acos(nLorentzPlane.dot(nNominal)); - Vector3D nNominal(1., 0., 0.); - double tAngle = acos(nLorentzPlane.dot(nNominal)); + CHECK_CLOSE_REL(tAngle, lAngle, 0.001); +} - CHECK_CLOSE_REL(tAngle, lAngle, 0.001); - } - -} // namespace -} // namespace \ No newline at end of file +} // namespace Test +} // namespace Acts \ No newline at end of file diff --git a/Tests/Plugins/Digitization/ClusterizationTests.cpp b/Tests/Plugins/Digitization/ClusterizationTests.cpp index dcfcb65c78b5b49ba4e6612b1a1c3c7e50340487..572988f6581bde3e46152a923df8603f7c357d39 100644 --- a/Tests/Plugins/Digitization/ClusterizationTests.cpp +++ b/Tests/Plugins/Digitization/ClusterizationTests.cpp @@ -25,519 +25,504 @@ #include "Acts/Tests/CommonHelpers/FloatComparisons.hpp" namespace bdata = boost::unit_test::data; -namespace tt = boost::test_tools; +namespace tt = boost::test_tools; namespace Acts { namespace Test { - /// This test tests the clusterization of cells which belong to the same - /// cluster for 8-cell/4-cell merging, digital/analogue readout and with a - /// possible energy cut applied - /// The grid with cells should cover all different cases: - /// - /// 1 0 0 0 2 0 0 0 0 2 - /// 0 2 0 1 0 0 0 2 0 2 - /// 0 0 0 0 0 0 0 1 1 2 - /// 2 0 0 0 0 1 0 0 0 0 - /// 1 0 0 1 0 2 0 0 0 2 - /// 0 0 2 0 0 1 0 1 0 1 - /// 0 0 0 1 1 0 0 2 0 1 - /// 0 0 0 0 0 0 0 0 2 0 - /// 1 2 2 0 0 0 0 0 0 0 - BOOST_AUTO_TEST_CASE(create_Clusters1) - { - size_t nBins0 = 10; - std::vector<size_t> clusterSizes = {2, 2, 2, 3, 6, 6, 7}; - std::vector<size_t> clusterSizesCut = {1, 1, 1, 1, 1, 1, 1, 2, 2, 3}; - std::vector<size_t> clusterSizesEdge - = {1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 6}; - size_t nClusters = clusterSizes.size(); - size_t nClustersCut = clusterSizesCut.size(); - size_t nClustersEdge = clusterSizesEdge.size(); - - auto globalIndex = [&nBins0](const size_t& a, const size_t& b) { - return (a + nBins0 * b); - }; - - std::unordered_map<size_t, std::pair<Acts::DigitizationCell, bool>> - testCells; - // add cells covering all cases - testCells.insert( - {globalIndex(0, 0), {Acts::DigitizationCell(0, 0, 1), false}}); - testCells.insert( - {globalIndex(0, 3), {Acts::DigitizationCell(0, 3, 1), false}}); - testCells.insert( - {globalIndex(0, 4), {Acts::DigitizationCell(0, 4, 1), false}}); - testCells.insert( - {globalIndex(0, 8), {Acts::DigitizationCell(0, 8, 1), false}}); - testCells.insert( - {globalIndex(1, 1), {Acts::DigitizationCell(1, 1, 1), false}}); - testCells.insert( - {globalIndex(1, 8), {Acts::DigitizationCell(1, 8, 1), false}}); - testCells.insert( - {globalIndex(2, 5), {Acts::DigitizationCell(2, 5, 1), false}}); - testCells.insert( - {globalIndex(2, 8), {Acts::DigitizationCell(2, 8, 1), false}}); - testCells.insert( - {globalIndex(3, 1), {Acts::DigitizationCell(3, 1, 1), false}}); - testCells.insert( - {globalIndex(3, 4), {Acts::DigitizationCell(3, 4, 1), false}}); - testCells.insert( - {globalIndex(3, 6), {Acts::DigitizationCell(3, 6, 1), false}}); - testCells.insert( - {globalIndex(4, 0), {Acts::DigitizationCell(4, 0, 1), false}}); - testCells.insert( - {globalIndex(4, 6), {Acts::DigitizationCell(4, 6, 1), false}}); - testCells.insert( - {globalIndex(5, 3), {Acts::DigitizationCell(5, 3, 1), false}}); - testCells.insert( - {globalIndex(5, 5), {Acts::DigitizationCell(5, 5, 1), false}}); - testCells.insert( - {globalIndex(5, 4), {Acts::DigitizationCell(5, 4, 1), false}}); - testCells.insert( - {globalIndex(5, 5), {Acts::DigitizationCell(5, 5, 1), false}}); - testCells.insert( - {globalIndex(7, 1), {Acts::DigitizationCell(7, 1, 1), false}}); - testCells.insert( - {globalIndex(7, 2), {Acts::DigitizationCell(7, 2, 1), false}}); - testCells.insert( - {globalIndex(7, 5), {Acts::DigitizationCell(7, 5, 1), false}}); - testCells.insert( - {globalIndex(7, 6), {Acts::DigitizationCell(7, 6, 1), false}}); - testCells.insert( - {globalIndex(8, 2), {Acts::DigitizationCell(8, 2, 1), false}}); - testCells.insert( - {globalIndex(8, 7), {Acts::DigitizationCell(8, 7, 1), false}}); - testCells.insert( - {globalIndex(9, 0), {Acts::DigitizationCell(9, 0, 1), false}}); - testCells.insert( - {globalIndex(9, 1), {Acts::DigitizationCell(9, 1, 1), false}}); - testCells.insert( - {globalIndex(9, 2), {Acts::DigitizationCell(9, 2, 1), false}}); - testCells.insert( - {globalIndex(9, 4), {Acts::DigitizationCell(9, 4, 1), false}}); - testCells.insert( - {globalIndex(9, 5), {Acts::DigitizationCell(9, 5, 1), false}}); - testCells.insert( - {globalIndex(9, 6), {Acts::DigitizationCell(9, 6, 1), false}}); - - size_t nCellsWithoutDuplicates = testCells.size(); - - std::unordered_map<size_t, std::pair<Acts::DigitizationCell, bool>> - testCells1; - // add cells covering all cases - testCells1.insert( - {globalIndex(0, 0), {Acts::DigitizationCell(0, 0, 1), false}}); - testCells1.insert( - {globalIndex(0, 3), {Acts::DigitizationCell(0, 3, 2), false}}); - testCells1.insert( - {globalIndex(0, 4), {Acts::DigitizationCell(0, 4, 1), false}}); - testCells1.insert( - {globalIndex(0, 8), {Acts::DigitizationCell(0, 8, 1), false}}); - testCells1.insert( - {globalIndex(1, 1), {Acts::DigitizationCell(1, 1, 2), false}}); - testCells1.insert( - {globalIndex(1, 8), {Acts::DigitizationCell(1, 8, 2), false}}); - testCells1.insert( - {globalIndex(2, 5), {Acts::DigitizationCell(2, 5, 2), false}}); - testCells1.insert( - {globalIndex(2, 8), {Acts::DigitizationCell(2, 8, 2), false}}); - testCells1.insert( - {globalIndex(3, 1), {Acts::DigitizationCell(3, 1, 1), false}}); - testCells1.insert( - {globalIndex(3, 4), {Acts::DigitizationCell(3, 4, 1), false}}); - testCells1.insert( - {globalIndex(3, 6), {Acts::DigitizationCell(3, 6, 1), false}}); - testCells1.insert( - {globalIndex(4, 0), {Acts::DigitizationCell(4, 0, 2), false}}); - testCells1.insert( - {globalIndex(4, 6), {Acts::DigitizationCell(4, 6, 1), false}}); - testCells1.insert( - {globalIndex(5, 3), {Acts::DigitizationCell(5, 3, 1), false}}); - testCells1.insert( - {globalIndex(5, 5), {Acts::DigitizationCell(5, 5, 1), false}}); - testCells1.insert( - {globalIndex(5, 4), {Acts::DigitizationCell(5, 4, 2), false}}); - testCells1.insert( - {globalIndex(5, 5), {Acts::DigitizationCell(5, 5, 1), false}}); - testCells1.insert( - {globalIndex(7, 1), {Acts::DigitizationCell(7, 1, 2), false}}); - testCells1.insert( - {globalIndex(7, 2), {Acts::DigitizationCell(7, 2, 1), false}}); - testCells1.insert( - {globalIndex(7, 5), {Acts::DigitizationCell(7, 5, 1), false}}); - testCells1.insert( - {globalIndex(7, 6), {Acts::DigitizationCell(7, 6, 2), false}}); - testCells1.insert( - {globalIndex(8, 2), {Acts::DigitizationCell(8, 2, 1), false}}); - testCells1.insert( - {globalIndex(8, 7), {Acts::DigitizationCell(8, 7, 2), false}}); - testCells1.insert( - {globalIndex(9, 0), {Acts::DigitizationCell(9, 0, 2), false}}); - testCells1.insert( - {globalIndex(9, 1), {Acts::DigitizationCell(9, 1, 2), false}}); - testCells1.insert( - {globalIndex(9, 2), {Acts::DigitizationCell(9, 2, 2), false}}); - testCells1.insert( - {globalIndex(9, 4), {Acts::DigitizationCell(9, 4, 2), false}}); - testCells1.insert( - {globalIndex(9, 5), {Acts::DigitizationCell(9, 5, 1), false}}); - testCells1.insert( - {globalIndex(9, 6), {Acts::DigitizationCell(9, 6, 1), false}}); - - // add duplicates - - size_t nCells = testCells1.size(); - - // make copies for all the tests (the boolean in the map gets changed) - auto testCells2 = testCells; - auto testCells3 = testCells; - auto testCells4 = testCells1; - - // Common Corner, digital,no energy cut - // createClusters - auto mergedCells1 = Acts::createClusters<Acts::DigitizationCell>( - testCells, nBins0, true, 0.); - // check number of clusters - BOOST_CHECK_EQUAL(mergedCells1.size(), nClusters); - - float data1 = 0; - std::vector<size_t> clusterSizes1; - for (size_t i = 0; i < mergedCells1.size(); i++) { - auto cells = mergedCells1.at(i); - for (auto& cell : cells) { - data1 += cell.data; - } - // check the cluster sizes - clusterSizes1.push_back(cells.size()); +/// This test tests the clusterization of cells which belong to the same +/// cluster for 8-cell/4-cell merging, digital/analogue readout and with a +/// possible energy cut applied +/// The grid with cells should cover all different cases: +/// +/// 1 0 0 0 2 0 0 0 0 2 +/// 0 2 0 1 0 0 0 2 0 2 +/// 0 0 0 0 0 0 0 1 1 2 +/// 2 0 0 0 0 1 0 0 0 0 +/// 1 0 0 1 0 2 0 0 0 2 +/// 0 0 2 0 0 1 0 1 0 1 +/// 0 0 0 1 1 0 0 2 0 1 +/// 0 0 0 0 0 0 0 0 2 0 +/// 1 2 2 0 0 0 0 0 0 0 +BOOST_AUTO_TEST_CASE(create_Clusters1) { + size_t nBins0 = 10; + std::vector<size_t> clusterSizes = {2, 2, 2, 3, 6, 6, 7}; + std::vector<size_t> clusterSizesCut = {1, 1, 1, 1, 1, 1, 1, 2, 2, 3}; + std::vector<size_t> clusterSizesEdge = {1, 1, 1, 1, 1, 1, 1, + 2, 2, 2, 3, 3, 3, 6}; + size_t nClusters = clusterSizes.size(); + size_t nClustersCut = clusterSizesCut.size(); + size_t nClustersEdge = clusterSizesEdge.size(); + + auto globalIndex = [&nBins0](const size_t& a, const size_t& b) { + return (a + nBins0 * b); + }; + + std::unordered_map<size_t, std::pair<Acts::DigitizationCell, bool>> testCells; + // add cells covering all cases + testCells.insert( + {globalIndex(0, 0), {Acts::DigitizationCell(0, 0, 1), false}}); + testCells.insert( + {globalIndex(0, 3), {Acts::DigitizationCell(0, 3, 1), false}}); + testCells.insert( + {globalIndex(0, 4), {Acts::DigitizationCell(0, 4, 1), false}}); + testCells.insert( + {globalIndex(0, 8), {Acts::DigitizationCell(0, 8, 1), false}}); + testCells.insert( + {globalIndex(1, 1), {Acts::DigitizationCell(1, 1, 1), false}}); + testCells.insert( + {globalIndex(1, 8), {Acts::DigitizationCell(1, 8, 1), false}}); + testCells.insert( + {globalIndex(2, 5), {Acts::DigitizationCell(2, 5, 1), false}}); + testCells.insert( + {globalIndex(2, 8), {Acts::DigitizationCell(2, 8, 1), false}}); + testCells.insert( + {globalIndex(3, 1), {Acts::DigitizationCell(3, 1, 1), false}}); + testCells.insert( + {globalIndex(3, 4), {Acts::DigitizationCell(3, 4, 1), false}}); + testCells.insert( + {globalIndex(3, 6), {Acts::DigitizationCell(3, 6, 1), false}}); + testCells.insert( + {globalIndex(4, 0), {Acts::DigitizationCell(4, 0, 1), false}}); + testCells.insert( + {globalIndex(4, 6), {Acts::DigitizationCell(4, 6, 1), false}}); + testCells.insert( + {globalIndex(5, 3), {Acts::DigitizationCell(5, 3, 1), false}}); + testCells.insert( + {globalIndex(5, 5), {Acts::DigitizationCell(5, 5, 1), false}}); + testCells.insert( + {globalIndex(5, 4), {Acts::DigitizationCell(5, 4, 1), false}}); + testCells.insert( + {globalIndex(5, 5), {Acts::DigitizationCell(5, 5, 1), false}}); + testCells.insert( + {globalIndex(7, 1), {Acts::DigitizationCell(7, 1, 1), false}}); + testCells.insert( + {globalIndex(7, 2), {Acts::DigitizationCell(7, 2, 1), false}}); + testCells.insert( + {globalIndex(7, 5), {Acts::DigitizationCell(7, 5, 1), false}}); + testCells.insert( + {globalIndex(7, 6), {Acts::DigitizationCell(7, 6, 1), false}}); + testCells.insert( + {globalIndex(8, 2), {Acts::DigitizationCell(8, 2, 1), false}}); + testCells.insert( + {globalIndex(8, 7), {Acts::DigitizationCell(8, 7, 1), false}}); + testCells.insert( + {globalIndex(9, 0), {Acts::DigitizationCell(9, 0, 1), false}}); + testCells.insert( + {globalIndex(9, 1), {Acts::DigitizationCell(9, 1, 1), false}}); + testCells.insert( + {globalIndex(9, 2), {Acts::DigitizationCell(9, 2, 1), false}}); + testCells.insert( + {globalIndex(9, 4), {Acts::DigitizationCell(9, 4, 1), false}}); + testCells.insert( + {globalIndex(9, 5), {Acts::DigitizationCell(9, 5, 1), false}}); + testCells.insert( + {globalIndex(9, 6), {Acts::DigitizationCell(9, 6, 1), false}}); + + size_t nCellsWithoutDuplicates = testCells.size(); + + std::unordered_map<size_t, std::pair<Acts::DigitizationCell, bool>> + testCells1; + // add cells covering all cases + testCells1.insert( + {globalIndex(0, 0), {Acts::DigitizationCell(0, 0, 1), false}}); + testCells1.insert( + {globalIndex(0, 3), {Acts::DigitizationCell(0, 3, 2), false}}); + testCells1.insert( + {globalIndex(0, 4), {Acts::DigitizationCell(0, 4, 1), false}}); + testCells1.insert( + {globalIndex(0, 8), {Acts::DigitizationCell(0, 8, 1), false}}); + testCells1.insert( + {globalIndex(1, 1), {Acts::DigitizationCell(1, 1, 2), false}}); + testCells1.insert( + {globalIndex(1, 8), {Acts::DigitizationCell(1, 8, 2), false}}); + testCells1.insert( + {globalIndex(2, 5), {Acts::DigitizationCell(2, 5, 2), false}}); + testCells1.insert( + {globalIndex(2, 8), {Acts::DigitizationCell(2, 8, 2), false}}); + testCells1.insert( + {globalIndex(3, 1), {Acts::DigitizationCell(3, 1, 1), false}}); + testCells1.insert( + {globalIndex(3, 4), {Acts::DigitizationCell(3, 4, 1), false}}); + testCells1.insert( + {globalIndex(3, 6), {Acts::DigitizationCell(3, 6, 1), false}}); + testCells1.insert( + {globalIndex(4, 0), {Acts::DigitizationCell(4, 0, 2), false}}); + testCells1.insert( + {globalIndex(4, 6), {Acts::DigitizationCell(4, 6, 1), false}}); + testCells1.insert( + {globalIndex(5, 3), {Acts::DigitizationCell(5, 3, 1), false}}); + testCells1.insert( + {globalIndex(5, 5), {Acts::DigitizationCell(5, 5, 1), false}}); + testCells1.insert( + {globalIndex(5, 4), {Acts::DigitizationCell(5, 4, 2), false}}); + testCells1.insert( + {globalIndex(5, 5), {Acts::DigitizationCell(5, 5, 1), false}}); + testCells1.insert( + {globalIndex(7, 1), {Acts::DigitizationCell(7, 1, 2), false}}); + testCells1.insert( + {globalIndex(7, 2), {Acts::DigitizationCell(7, 2, 1), false}}); + testCells1.insert( + {globalIndex(7, 5), {Acts::DigitizationCell(7, 5, 1), false}}); + testCells1.insert( + {globalIndex(7, 6), {Acts::DigitizationCell(7, 6, 2), false}}); + testCells1.insert( + {globalIndex(8, 2), {Acts::DigitizationCell(8, 2, 1), false}}); + testCells1.insert( + {globalIndex(8, 7), {Acts::DigitizationCell(8, 7, 2), false}}); + testCells1.insert( + {globalIndex(9, 0), {Acts::DigitizationCell(9, 0, 2), false}}); + testCells1.insert( + {globalIndex(9, 1), {Acts::DigitizationCell(9, 1, 2), false}}); + testCells1.insert( + {globalIndex(9, 2), {Acts::DigitizationCell(9, 2, 2), false}}); + testCells1.insert( + {globalIndex(9, 4), {Acts::DigitizationCell(9, 4, 2), false}}); + testCells1.insert( + {globalIndex(9, 5), {Acts::DigitizationCell(9, 5, 1), false}}); + testCells1.insert( + {globalIndex(9, 6), {Acts::DigitizationCell(9, 6, 1), false}}); + + // add duplicates + + size_t nCells = testCells1.size(); + + // make copies for all the tests (the boolean in the map gets changed) + auto testCells2 = testCells; + auto testCells3 = testCells; + auto testCells4 = testCells1; + + // Common Corner, digital,no energy cut + // createClusters + auto mergedCells1 = + Acts::createClusters<Acts::DigitizationCell>(testCells, nBins0, true, 0.); + // check number of clusters + BOOST_CHECK_EQUAL(mergedCells1.size(), nClusters); + + float data1 = 0; + std::vector<size_t> clusterSizes1; + for (size_t i = 0; i < mergedCells1.size(); i++) { + auto cells = mergedCells1.at(i); + for (auto& cell : cells) { + data1 += cell.data; } // check the cluster sizes - std::sort(clusterSizes1.begin(), clusterSizes1.end()); - BOOST_CHECK_EQUAL_COLLECTIONS(clusterSizes.begin(), - clusterSizes.end(), - clusterSizes1.begin(), - clusterSizes1.end()); - // check cells - CHECK_CLOSE_REL(data1, nCellsWithoutDuplicates, 1e-5); - - // Common Edge, digital,no energy cut - // createClusters - auto mergedCells2 = Acts::createClusters<Acts::DigitizationCell>( - testCells2, nBins0, false, 0.); - // check number of clusters - BOOST_CHECK_EQUAL(mergedCells2.size(), nClustersEdge); - - float data2 = 0; - std::vector<size_t> clusterSizes2; - for (size_t i = 0; i < mergedCells2.size(); i++) { - auto cells = mergedCells2.at(i); - for (auto& cell : cells) { - data2 += cell.data; - } - // check the cluster sizes - clusterSizes2.push_back(cells.size()); + clusterSizes1.push_back(cells.size()); + } + // check the cluster sizes + std::sort(clusterSizes1.begin(), clusterSizes1.end()); + BOOST_CHECK_EQUAL_COLLECTIONS(clusterSizes.begin(), clusterSizes.end(), + clusterSizes1.begin(), clusterSizes1.end()); + // check cells + CHECK_CLOSE_REL(data1, nCellsWithoutDuplicates, 1e-5); + + // Common Edge, digital,no energy cut + // createClusters + auto mergedCells2 = Acts::createClusters<Acts::DigitizationCell>( + testCells2, nBins0, false, 0.); + // check number of clusters + BOOST_CHECK_EQUAL(mergedCells2.size(), nClustersEdge); + + float data2 = 0; + std::vector<size_t> clusterSizes2; + for (size_t i = 0; i < mergedCells2.size(); i++) { + auto cells = mergedCells2.at(i); + for (auto& cell : cells) { + data2 += cell.data; } // check the cluster sizes - std::sort(clusterSizes2.begin(), clusterSizes2.end()); - BOOST_CHECK_EQUAL_COLLECTIONS(clusterSizesEdge.begin(), - clusterSizesEdge.end(), - clusterSizes2.begin(), - clusterSizes2.end()); - // check cells - CHECK_CLOSE_REL(data2, nCellsWithoutDuplicates, 1e-5); - - // Common Corner, analogue,no energy cut - // createClusters - auto mergedCells3 = Acts::createClusters<Acts::DigitizationCell>( - testCells3, nBins0, true, 0.); - // check number of clusters - BOOST_CHECK_EQUAL(mergedCells3.size(), nClusters); - - float data3 = 0; - std::vector<size_t> clusterSizes3; - for (size_t i = 0; i < mergedCells3.size(); i++) { - auto cells = mergedCells3.at(i); - for (auto& cell : cells) { - data3 += cell.data; - } - // check the cluster sizes - clusterSizes3.push_back(cells.size()); + clusterSizes2.push_back(cells.size()); + } + // check the cluster sizes + std::sort(clusterSizes2.begin(), clusterSizes2.end()); + BOOST_CHECK_EQUAL_COLLECTIONS(clusterSizesEdge.begin(), + clusterSizesEdge.end(), clusterSizes2.begin(), + clusterSizes2.end()); + // check cells + CHECK_CLOSE_REL(data2, nCellsWithoutDuplicates, 1e-5); + + // Common Corner, analogue,no energy cut + // createClusters + auto mergedCells3 = Acts::createClusters<Acts::DigitizationCell>( + testCells3, nBins0, true, 0.); + // check number of clusters + BOOST_CHECK_EQUAL(mergedCells3.size(), nClusters); + + float data3 = 0; + std::vector<size_t> clusterSizes3; + for (size_t i = 0; i < mergedCells3.size(); i++) { + auto cells = mergedCells3.at(i); + for (auto& cell : cells) { + data3 += cell.data; } // check the cluster sizes - std::sort(clusterSizes3.begin(), clusterSizes3.end()); - BOOST_CHECK_EQUAL_COLLECTIONS(clusterSizes.begin(), - clusterSizes.end(), - clusterSizes3.begin(), - clusterSizes3.end()); - // check cells - CHECK_CLOSE_REL(data3, nCells, 1e-5); - - // Common Corner, analogue, energy cut - // createClusters - auto mergedCells4 = Acts::createClusters<Acts::DigitizationCell>( - testCells4, nBins0, true, 1.5); - // check number of clusters - - BOOST_CHECK_EQUAL(mergedCells4.size(), nClustersCut); - - float data4 = 0; - std::vector<size_t> clusterSizes4; - for (size_t i = 0; i < mergedCells4.size(); i++) { - auto cells = mergedCells4.at(i); - for (auto& cell : cells) { - data4 += cell.data; - } - // check the cluster sizes - clusterSizes4.push_back(cells.size()); + clusterSizes3.push_back(cells.size()); + } + // check the cluster sizes + std::sort(clusterSizes3.begin(), clusterSizes3.end()); + BOOST_CHECK_EQUAL_COLLECTIONS(clusterSizes.begin(), clusterSizes.end(), + clusterSizes3.begin(), clusterSizes3.end()); + // check cells + CHECK_CLOSE_REL(data3, nCells, 1e-5); + + // Common Corner, analogue, energy cut + // createClusters + auto mergedCells4 = Acts::createClusters<Acts::DigitizationCell>( + testCells4, nBins0, true, 1.5); + // check number of clusters + + BOOST_CHECK_EQUAL(mergedCells4.size(), nClustersCut); + + float data4 = 0; + std::vector<size_t> clusterSizes4; + for (size_t i = 0; i < mergedCells4.size(); i++) { + auto cells = mergedCells4.at(i); + for (auto& cell : cells) { + data4 += cell.data; } // check the cluster sizes - std::sort(clusterSizes4.begin(), clusterSizes4.end()); - BOOST_CHECK_EQUAL_COLLECTIONS(clusterSizesCut.begin(), - clusterSizesCut.end(), - clusterSizes4.begin(), - clusterSizes4.end()); - // check cells - CHECK_CLOSE_REL(data4, nCells, 1e-5); + clusterSizes4.push_back(cells.size()); } + // check the cluster sizes + std::sort(clusterSizes4.begin(), clusterSizes4.end()); + BOOST_CHECK_EQUAL_COLLECTIONS(clusterSizesCut.begin(), clusterSizesCut.end(), + clusterSizes4.begin(), clusterSizes4.end()); + // check cells + CHECK_CLOSE_REL(data4, nCells, 1e-5); +} - /// This test tests the clusterization of cells which belong to the same - /// cluster for 8-cell/4-cell merging, digital/analogue readout and with a - /// possible energy cut applied and a bigger grid than in create_Clusters1 - BOOST_AUTO_TEST_CASE(create_Clusters2) - { - - std::unordered_map<size_t, std::pair<Acts::DigitizationCell, bool>> - testCells1; - - size_t nCells = 99; - size_t delta = 3; - size_t nClustersNoTouch = (nCells / delta) * (nCells / delta); - size_t nCellsInClusters = nClustersNoTouch * 3; - - auto globalIndex = [&nCells](const size_t& a, const size_t& b) { - return (a + nCells * b); - }; - - // Create clusters which are separated by one cell always - // Clusters have the following shape: - // ----- - // --##- - // ---#- - // ----- - for (size_t i = 0; i < nCells; i += delta) { - for (size_t j = 0; j < nCells; j += delta) { - auto cellA = Acts::DigitizationCell(i, j, 1); - auto cellB = Acts::DigitizationCell(i, j + 1, 1); - auto cellC = Acts::DigitizationCell(i + 1, j + 1, 1); - - auto insertCellA - = testCells1.insert({globalIndex(i, j), {cellA, false}}); - if (!insertCellA.second) { - // check if there is already a cell at same position and merge in that - // case - insertCellA.first->second.first.addCell(cellA, false); - } - auto insertCellB - = testCells1.insert({globalIndex(i, j + 1), {cellB, false}}); - if (!insertCellB.second) { - // check if there is already a cell at same position and merge in that - // case - insertCellB.first->second.first.addCell(cellB, false); - } - auto insertCellC - = testCells1.insert({globalIndex(i + 1, j + 1), {cellC, false}}); - if (!insertCellC.second) { - // check if there is already a cell at same position and merge in that - // case - insertCellC.first->second.first.addCell(cellC, false); - } +/// This test tests the clusterization of cells which belong to the same +/// cluster for 8-cell/4-cell merging, digital/analogue readout and with a +/// possible energy cut applied and a bigger grid than in create_Clusters1 +BOOST_AUTO_TEST_CASE(create_Clusters2) { + std::unordered_map<size_t, std::pair<Acts::DigitizationCell, bool>> + testCells1; + + size_t nCells = 99; + size_t delta = 3; + size_t nClustersNoTouch = (nCells / delta) * (nCells / delta); + size_t nCellsInClusters = nClustersNoTouch * 3; + + auto globalIndex = [&nCells](const size_t& a, const size_t& b) { + return (a + nCells * b); + }; + + // Create clusters which are separated by one cell always + // Clusters have the following shape: + // ----- + // --##- + // ---#- + // ----- + for (size_t i = 0; i < nCells; i += delta) { + for (size_t j = 0; j < nCells; j += delta) { + auto cellA = Acts::DigitizationCell(i, j, 1); + auto cellB = Acts::DigitizationCell(i, j + 1, 1); + auto cellC = Acts::DigitizationCell(i + 1, j + 1, 1); + + auto insertCellA = testCells1.insert({globalIndex(i, j), {cellA, false}}); + if (!insertCellA.second) { + // check if there is already a cell at same position and merge in that + // case + insertCellA.first->second.first.addCell(cellA, false); } - } - // copy - auto testCells2 = testCells1; - auto testCells3 = testCells1; - auto testCells5 = testCells1; - auto testCells7 = testCells1; - auto testCells8 = testCells1; - - // in a 99x99 grid we get 33x33=1089 clusters - // Now we should have the same number of cluster for common corner and - // common edge case - // common edge - auto mergedCells1 = Acts::createClusters<Acts::DigitizationCell>( - testCells1, nCells, true, 0.); - BOOST_CHECK_EQUAL(mergedCells1.size(), nClustersNoTouch); - // common corner - auto mergedCells2 = Acts::createClusters<Acts::DigitizationCell>( - testCells2, nCells, false, 0.); - BOOST_CHECK_EQUAL(mergedCells2.size(), nClustersNoTouch); - - // now test merging - there is no merging at the moment - float data1 = 0; - for (auto& cells : mergedCells1) { - for (auto& i : cells) { - data1 += i.data; - // check cluster sizes - BOOST_CHECK_EQUAL(cells.size(), delta); + auto insertCellB = + testCells1.insert({globalIndex(i, j + 1), {cellB, false}}); + if (!insertCellB.second) { + // check if there is already a cell at same position and merge in that + // case + insertCellB.first->second.first.addCell(cellB, false); } - } - CHECK_CLOSE_REL(data1, nCellsInClusters, 1e-5); - - // now test merging - there is no merging at the moment - float data2 = 0; - for (auto& cells : mergedCells2) { - for (auto& i : cells) { - data2 += i.data; - // check cluster sizes - BOOST_CHECK_EQUAL(cells.size(), delta); + auto insertCellC = + testCells1.insert({globalIndex(i + 1, j + 1), {cellC, false}}); + if (!insertCellC.second) { + // check if there is already a cell at same position and merge in that + // case + insertCellC.first->second.first.addCell(cellC, false); } } - CHECK_CLOSE_REL(data2, nCellsInClusters, 1e-5); - - // now we add some cells which lead to merging only for common corner and - // create new clusters for edge case) - size_t delta2 = 9; - size_t nCornerCells = nCells / delta2 * nCells / delta2; - size_t nClusters_merged = nClustersNoTouch - nCornerCells * 2; - - for (size_t i = 2; i < nCells; i += delta2) { - for (size_t j = 2; j < nCells; j += delta2) { - auto cell = Acts::DigitizationCell(i, j, 1); - auto insertCell = testCells3.insert({globalIndex(i, j), {cell, false}}); - if (!insertCell.second) { - // check if there is already a cell at same position and merge in that - // case - insertCell.first->second.first.addCell(cell, false); - } - } + } + // copy + auto testCells2 = testCells1; + auto testCells3 = testCells1; + auto testCells5 = testCells1; + auto testCells7 = testCells1; + auto testCells8 = testCells1; + + // in a 99x99 grid we get 33x33=1089 clusters + // Now we should have the same number of cluster for common corner and + // common edge case + // common edge + auto mergedCells1 = Acts::createClusters<Acts::DigitizationCell>( + testCells1, nCells, true, 0.); + BOOST_CHECK_EQUAL(mergedCells1.size(), nClustersNoTouch); + // common corner + auto mergedCells2 = Acts::createClusters<Acts::DigitizationCell>( + testCells2, nCells, false, 0.); + BOOST_CHECK_EQUAL(mergedCells2.size(), nClustersNoTouch); + + // now test merging - there is no merging at the moment + float data1 = 0; + for (auto& cells : mergedCells1) { + for (auto& i : cells) { + data1 += i.data; + // check cluster sizes + BOOST_CHECK_EQUAL(cells.size(), delta); } - auto testCells4 = testCells3; - - // common corner - auto mergedCells3 = Acts::createClusters<Acts::DigitizationCell>( - testCells3, nCells, true, 0.); - BOOST_CHECK_EQUAL(mergedCells3.size(), nClusters_merged); - - // common edge - auto mergedCells4 = Acts::createClusters<Acts::DigitizationCell>( - testCells4, nCells, false, 0.); - BOOST_CHECK_EQUAL(mergedCells4.size(), nClustersNoTouch + nCornerCells); - - // now we add some cells which lead to merging also for edge case - for (size_t i = 2; i < nCells; i += delta2) { - for (size_t j = 2; j < nCells; j += delta2) { - - auto cellA = Acts::DigitizationCell(i, j - 1, 1); - auto insertCellA - = testCells5.insert({globalIndex(i, j - 1), {cellA, false}}); - if (!insertCellA.second) { - // check if there is already a cell at same position and merge in that - // case - insertCellA.first->second.first.addCell(cellA, false); - } - auto cellB = Acts::DigitizationCell(i + 1, j, 1); - auto insertCellB - = testCells5.insert({globalIndex(i + 1, j), {cellB, false}}); - if (!insertCellB.second) { - // check if there is already a cell at same position and merge in that - // case - insertCellB.first->second.first.addCell(cellB, false); - } - } + } + CHECK_CLOSE_REL(data1, nCellsInClusters, 1e-5); + + // now test merging - there is no merging at the moment + float data2 = 0; + for (auto& cells : mergedCells2) { + for (auto& i : cells) { + data2 += i.data; + // check cluster sizes + BOOST_CHECK_EQUAL(cells.size(), delta); } - auto testCells6 = testCells5; - - // common corner - auto mergedCells5 = Acts::createClusters<Acts::DigitizationCell>( - testCells5, nCells, true, 0.); - BOOST_CHECK_EQUAL(mergedCells5.size(), nClusters_merged); - - // common edge - auto mergedCells6 = Acts::createClusters<Acts::DigitizationCell>( - testCells6, nCells, false, 0.); - BOOST_CHECK_EQUAL(mergedCells6.size(), nClusters_merged); - - // now adding the same cells again on two positions of clusters - digital - // readout - for (size_t i = 0; i < nCells; i += delta) { - for (size_t j = 0; j < nCells; j += delta) { - auto cellA = Acts::DigitizationCell(i, j, 1); - auto cellB = Acts::DigitizationCell(i, j + 1, 1); - - auto insertCellA - = testCells7.insert({globalIndex(i, j), {cellA, false}}); - if (!insertCellA.second) { - // check if there is already a cell at same position and merge in that - // case - insertCellA.first->second.first.addCell(cellA, false); - } - auto insertCellB - = testCells7.insert({globalIndex(i, j + 1), {cellB, false}}); - if (!insertCellB.second) { - // check if there is already a cell at same position and merge in that - // case - insertCellB.first->second.first.addCell(cellB, false); - } - // analogue readout - insertCellA = testCells8.insert({globalIndex(i, j), {cellA, false}}); - if (!insertCellA.second) { - // check if there is already a cell at same position and merge in that - // case - insertCellA.first->second.first.addCell(cellA, true); - } - insertCellB - = testCells8.insert({globalIndex(i, j + 1), {cellB, false}}); - if (!insertCellB.second) { - // check if there is already a cell at same position and merge in that - // case - insertCellB.first->second.first.addCell(cellB, true); - } + } + CHECK_CLOSE_REL(data2, nCellsInClusters, 1e-5); + + // now we add some cells which lead to merging only for common corner and + // create new clusters for edge case) + size_t delta2 = 9; + size_t nCornerCells = nCells / delta2 * nCells / delta2; + size_t nClusters_merged = nClustersNoTouch - nCornerCells * 2; + + for (size_t i = 2; i < nCells; i += delta2) { + for (size_t j = 2; j < nCells; j += delta2) { + auto cell = Acts::DigitizationCell(i, j, 1); + auto insertCell = testCells3.insert({globalIndex(i, j), {cell, false}}); + if (!insertCell.second) { + // check if there is already a cell at same position and merge in that + // case + insertCell.first->second.first.addCell(cell, false); } } - auto testCells9 = testCells8; - - size_t nCellsInClustersDuplicated - = nClustersNoTouch * 3 + nClustersNoTouch * 2; - - // digital readout - auto mergedCells7 = Acts::createClusters<Acts::DigitizationCell>( - testCells7, nCells, true, 0.); - BOOST_CHECK_EQUAL(mergedCells7.size(), nClustersNoTouch); - float data7 = 0; - for (auto& cells : mergedCells7) { - for (auto& i : cells) { - data7 += i.data; + } + auto testCells4 = testCells3; + + // common corner + auto mergedCells3 = Acts::createClusters<Acts::DigitizationCell>( + testCells3, nCells, true, 0.); + BOOST_CHECK_EQUAL(mergedCells3.size(), nClusters_merged); + + // common edge + auto mergedCells4 = Acts::createClusters<Acts::DigitizationCell>( + testCells4, nCells, false, 0.); + BOOST_CHECK_EQUAL(mergedCells4.size(), nClustersNoTouch + nCornerCells); + + // now we add some cells which lead to merging also for edge case + for (size_t i = 2; i < nCells; i += delta2) { + for (size_t j = 2; j < nCells; j += delta2) { + auto cellA = Acts::DigitizationCell(i, j - 1, 1); + auto insertCellA = + testCells5.insert({globalIndex(i, j - 1), {cellA, false}}); + if (!insertCellA.second) { + // check if there is already a cell at same position and merge in that + // case + insertCellA.first->second.first.addCell(cellA, false); } - BOOST_CHECK_EQUAL(cells.size(), 3); - } - CHECK_CLOSE_REL(data7, nCellsInClusters, 1e-5); - - // analougue readout - auto mergedCells8 = Acts::createClusters<Acts::DigitizationCell>( - testCells8, nCells, true, 0.); - BOOST_CHECK_EQUAL(mergedCells8.size(), nClustersNoTouch); - float data8 = 0; - for (auto& cells : mergedCells8) { - for (auto& i : cells) { - data8 += i.data; + auto cellB = Acts::DigitizationCell(i + 1, j, 1); + auto insertCellB = + testCells5.insert({globalIndex(i + 1, j), {cellB, false}}); + if (!insertCellB.second) { + // check if there is already a cell at same position and merge in that + // case + insertCellB.first->second.first.addCell(cellB, false); } - BOOST_CHECK_EQUAL(cells.size(), 3); } - CHECK_CLOSE_REL(data8, nCellsInClustersDuplicated, 1e-5); - - // analougue readout & energy cut - auto mergedCells9 = Acts::createClusters<Acts::DigitizationCell>( - testCells9, nCells, true, 1.5); - BOOST_CHECK_EQUAL(mergedCells9.size(), nClustersNoTouch); - float data9 = 0; - for (auto& cells : mergedCells9) { - for (auto& i : cells) { - data9 += i.data; + } + auto testCells6 = testCells5; + + // common corner + auto mergedCells5 = Acts::createClusters<Acts::DigitizationCell>( + testCells5, nCells, true, 0.); + BOOST_CHECK_EQUAL(mergedCells5.size(), nClusters_merged); + + // common edge + auto mergedCells6 = Acts::createClusters<Acts::DigitizationCell>( + testCells6, nCells, false, 0.); + BOOST_CHECK_EQUAL(mergedCells6.size(), nClusters_merged); + + // now adding the same cells again on two positions of clusters - digital + // readout + for (size_t i = 0; i < nCells; i += delta) { + for (size_t j = 0; j < nCells; j += delta) { + auto cellA = Acts::DigitizationCell(i, j, 1); + auto cellB = Acts::DigitizationCell(i, j + 1, 1); + + auto insertCellA = testCells7.insert({globalIndex(i, j), {cellA, false}}); + if (!insertCellA.second) { + // check if there is already a cell at same position and merge in that + // case + insertCellA.first->second.first.addCell(cellA, false); + } + auto insertCellB = + testCells7.insert({globalIndex(i, j + 1), {cellB, false}}); + if (!insertCellB.second) { + // check if there is already a cell at same position and merge in that + // case + insertCellB.first->second.first.addCell(cellB, false); + } + // analogue readout + insertCellA = testCells8.insert({globalIndex(i, j), {cellA, false}}); + if (!insertCellA.second) { + // check if there is already a cell at same position and merge in that + // case + insertCellA.first->second.first.addCell(cellA, true); + } + insertCellB = testCells8.insert({globalIndex(i, j + 1), {cellB, false}}); + if (!insertCellB.second) { + // check if there is already a cell at same position and merge in that + // case + insertCellB.first->second.first.addCell(cellB, true); } - BOOST_CHECK_EQUAL(cells.size(), 2); } - CHECK_CLOSE_REL(data9, (nClustersNoTouch * 2) * 2, 1e-5); } + auto testCells9 = testCells8; + + size_t nCellsInClustersDuplicated = + nClustersNoTouch * 3 + nClustersNoTouch * 2; + + // digital readout + auto mergedCells7 = Acts::createClusters<Acts::DigitizationCell>( + testCells7, nCells, true, 0.); + BOOST_CHECK_EQUAL(mergedCells7.size(), nClustersNoTouch); + float data7 = 0; + for (auto& cells : mergedCells7) { + for (auto& i : cells) { + data7 += i.data; + } + BOOST_CHECK_EQUAL(cells.size(), 3); + } + CHECK_CLOSE_REL(data7, nCellsInClusters, 1e-5); + + // analougue readout + auto mergedCells8 = Acts::createClusters<Acts::DigitizationCell>( + testCells8, nCells, true, 0.); + BOOST_CHECK_EQUAL(mergedCells8.size(), nClustersNoTouch); + float data8 = 0; + for (auto& cells : mergedCells8) { + for (auto& i : cells) { + data8 += i.data; + } + BOOST_CHECK_EQUAL(cells.size(), 3); + } + CHECK_CLOSE_REL(data8, nCellsInClustersDuplicated, 1e-5); + + // analougue readout & energy cut + auto mergedCells9 = Acts::createClusters<Acts::DigitizationCell>( + testCells9, nCells, true, 1.5); + BOOST_CHECK_EQUAL(mergedCells9.size(), nClustersNoTouch); + float data9 = 0; + for (auto& cells : mergedCells9) { + for (auto& i : cells) { + data9 += i.data; + } + BOOST_CHECK_EQUAL(cells.size(), 2); + } + CHECK_CLOSE_REL(data9, (nClustersNoTouch * 2) * 2, 1e-5); } -} +} // namespace Test +} // namespace Acts diff --git a/Tests/Plugins/Digitization/DoubleHitSpacePointBuilderTests.cpp b/Tests/Plugins/Digitization/DoubleHitSpacePointBuilderTests.cpp index 1eeb9953ccb6a456ffa1f2eb70210e99328d913a..1ed624d08b843012ba375301e18957d3e7823d5b 100644 --- a/Tests/Plugins/Digitization/DoubleHitSpacePointBuilderTests.cpp +++ b/Tests/Plugins/Digitization/DoubleHitSpacePointBuilderTests.cpp @@ -20,153 +20,133 @@ #include "Acts/Tests/CommonHelpers/DetectorElementStub.hpp" namespace bdata = boost::unit_test::data; -namespace tt = boost::test_tools; +namespace tt = boost::test_tools; namespace Acts { namespace Test { - // Create a test context - GeometryContext tgContext = GeometryContext(); - - /// Unit test for testing the main functions of DoubleHitSpacePointBuilder - /// 1) A pair of hits gets added and resolved. - /// 2) A pair of hits gets added and rejected. - BOOST_DATA_TEST_CASE(DoubleHitsSpacePointBuilder_basic, - bdata::xrange(1), - index) - { - (void)index; - - std::cout << "Create first hit" << std::endl; - - // Build Bounds - std::shared_ptr<const RectangleBounds> recBounds( - new RectangleBounds(35. * Acts::units::_um, 25. * units::_mm)); - - // Build binning and segmentation - std::vector<float> boundariesX, boundariesY; - boundariesX.push_back(-35. * units::_um); - boundariesX.push_back(35. * units::_um); - boundariesY.push_back(-25. * units::_mm); - boundariesY.push_back(25. * units::_mm); - - BinningData binDataX(BinningOption::open, BinningValue::binX, boundariesX); - std::shared_ptr<BinUtility> buX(new BinUtility(binDataX)); - BinningData binDataY(BinningOption::open, BinningValue::binY, boundariesY); - std::shared_ptr<BinUtility> buY(new BinUtility(binDataY)); - (*buX) += (*buY); - - std::shared_ptr<const Segmentation> segmentation( - new CartesianSegmentation(buX, recBounds)); - - // Build translation - - double rotation = 0.026; - RotationMatrix3D rotationPos; - Vector3D xPos(cos(rotation), sin(rotation), 0.); - Vector3D yPos(-sin(rotation), cos(rotation), 0.); - Vector3D zPos(0., 0., 1.); - rotationPos.col(0) = xPos; - rotationPos.col(1) = yPos; - rotationPos.col(2) = zPos; - Transform3D t3d(Transform3D::Identity() * rotationPos); - t3d.translation() = Vector3D(0., 0., 10. * units::_m); - - // Build Digitization - const DigitizationModule digMod(segmentation, 1., 1., 0.); - DetectorElementStub detElem(std::make_shared<const Transform3D>(t3d)); - auto pSur = Surface::makeShared<PlaneSurface>(recBounds, detElem); - ActsSymMatrixD<2> cov; - cov << 0., 0., 0., 0.; - Vector2D local = {0.1, -0.1}; - - // Build PlanarModuleCluster - PlanarModuleCluster* pmc - = new PlanarModuleCluster(pSur, - 0, - cov, - local[0], - local[1], - {DigitizationCell(0, 0, 1.)}, - &digMod); - - std::cout << "Create second hit" << std::endl; - - // Build second PlanarModuleCluster - - double rotation2 = -0.026; - RotationMatrix3D rotationNeg; - Vector3D xNeg(cos(rotation2), sin(rotation2), 0.); - Vector3D yNeg(-sin(rotation2), cos(rotation2), 0.); - Vector3D zNeg(0., 0., 1.); - rotationNeg.col(0) = xNeg; - rotationNeg.col(1) = yNeg; - rotationNeg.col(2) = zNeg; - Transform3D t3d2(Transform3D::Identity() * rotationNeg); - t3d2.translation() = Vector3D(0., 0., 10.005 * units::_m); - - DetectorElementStub detElem2(std::make_shared<const Transform3D>(t3d2)); - - auto pSur2 = Surface::makeShared<PlaneSurface>(recBounds, detElem2); - - PlanarModuleCluster* pmc2 - = new PlanarModuleCluster(pSur2, - 1, - cov, - local[0], - local[1], - {DigitizationCell(0, 0, 1.)}, - &digMod); - - std::cout << "Store both hits" << std::endl; - - std::vector<DoubleHitSpacePoint> resultSP; - std::vector<std::pair<Acts::PlanarModuleCluster const*, - Acts::PlanarModuleCluster const*>> - clusterPairs; - SpacePointBuilder<DoubleHitSpacePoint>::DoubleHitSpacePointConfig dhsp_cfg; - - // Combine two PlanarModuleClusters - SpacePointBuilder<DoubleHitSpacePoint> dhsp(dhsp_cfg); - dhsp.makeClusterPairs(tgContext, {pmc}, {pmc2}, clusterPairs); - - BOOST_CHECK_EQUAL(clusterPairs.size(), 1); - BOOST_CHECK_EQUAL(*(clusterPairs[0].first), *pmc); - BOOST_CHECK_EQUAL(*(clusterPairs[0].second), *pmc2); - - std::cout << "Calculate space point" << std::endl; - - dhsp.calculateSpacePoints(tgContext, clusterPairs, resultSP); - - BOOST_CHECK_EQUAL(resultSP.size(), 1); - - std::cout << "Create third hit" << std::endl; - - // Build third PlanarModuleCluster - Transform3D t3d3(Transform3D::Identity() * rotationNeg); - t3d3.translation() = Vector3D(0., 0., 10.005 * units::_m); - - DetectorElementStub detElem3(std::make_shared<const Transform3D>(t3d3)); - auto pSur3 = Surface::makeShared<PlaneSurface>(recBounds, detElem3); - - PlanarModuleCluster* pmc3 - = new PlanarModuleCluster(pSur3, - 2, - cov, - local[0], - local[1], - {DigitizationCell(0, 0, 1.)}, - &digMod); - - std::cout << "Try to store hits" << std::endl; - - // Combine points - dhsp.makeClusterPairs(tgContext, {pmc}, {pmc3}, clusterPairs); - - // Test for rejecting unconnected hits - BOOST_CHECK_EQUAL(resultSP.size(), 1); - } +// Create a test context +GeometryContext tgContext = GeometryContext(); + +/// Unit test for testing the main functions of DoubleHitSpacePointBuilder +/// 1) A pair of hits gets added and resolved. +/// 2) A pair of hits gets added and rejected. +BOOST_DATA_TEST_CASE(DoubleHitsSpacePointBuilder_basic, bdata::xrange(1), + index) { + (void)index; + + std::cout << "Create first hit" << std::endl; + + // Build Bounds + std::shared_ptr<const RectangleBounds> recBounds( + new RectangleBounds(35. * Acts::units::_um, 25. * units::_mm)); + + // Build binning and segmentation + std::vector<float> boundariesX, boundariesY; + boundariesX.push_back(-35. * units::_um); + boundariesX.push_back(35. * units::_um); + boundariesY.push_back(-25. * units::_mm); + boundariesY.push_back(25. * units::_mm); + + BinningData binDataX(BinningOption::open, BinningValue::binX, boundariesX); + std::shared_ptr<BinUtility> buX(new BinUtility(binDataX)); + BinningData binDataY(BinningOption::open, BinningValue::binY, boundariesY); + std::shared_ptr<BinUtility> buY(new BinUtility(binDataY)); + (*buX) += (*buY); + + std::shared_ptr<const Segmentation> segmentation( + new CartesianSegmentation(buX, recBounds)); + + // Build translation + + double rotation = 0.026; + RotationMatrix3D rotationPos; + Vector3D xPos(cos(rotation), sin(rotation), 0.); + Vector3D yPos(-sin(rotation), cos(rotation), 0.); + Vector3D zPos(0., 0., 1.); + rotationPos.col(0) = xPos; + rotationPos.col(1) = yPos; + rotationPos.col(2) = zPos; + Transform3D t3d(Transform3D::Identity() * rotationPos); + t3d.translation() = Vector3D(0., 0., 10. * units::_m); + + // Build Digitization + const DigitizationModule digMod(segmentation, 1., 1., 0.); + DetectorElementStub detElem(std::make_shared<const Transform3D>(t3d)); + auto pSur = Surface::makeShared<PlaneSurface>(recBounds, detElem); + ActsSymMatrixD<2> cov; + cov << 0., 0., 0., 0.; + Vector2D local = {0.1, -0.1}; + + // Build PlanarModuleCluster + PlanarModuleCluster* pmc = new PlanarModuleCluster( + pSur, 0, cov, local[0], local[1], {DigitizationCell(0, 0, 1.)}, &digMod); + + std::cout << "Create second hit" << std::endl; + + // Build second PlanarModuleCluster + + double rotation2 = -0.026; + RotationMatrix3D rotationNeg; + Vector3D xNeg(cos(rotation2), sin(rotation2), 0.); + Vector3D yNeg(-sin(rotation2), cos(rotation2), 0.); + Vector3D zNeg(0., 0., 1.); + rotationNeg.col(0) = xNeg; + rotationNeg.col(1) = yNeg; + rotationNeg.col(2) = zNeg; + Transform3D t3d2(Transform3D::Identity() * rotationNeg); + t3d2.translation() = Vector3D(0., 0., 10.005 * units::_m); + + DetectorElementStub detElem2(std::make_shared<const Transform3D>(t3d2)); + + auto pSur2 = Surface::makeShared<PlaneSurface>(recBounds, detElem2); + + PlanarModuleCluster* pmc2 = new PlanarModuleCluster( + pSur2, 1, cov, local[0], local[1], {DigitizationCell(0, 0, 1.)}, &digMod); + + std::cout << "Store both hits" << std::endl; + + std::vector<DoubleHitSpacePoint> resultSP; + std::vector<std::pair<Acts::PlanarModuleCluster const*, + Acts::PlanarModuleCluster const*>> + clusterPairs; + SpacePointBuilder<DoubleHitSpacePoint>::DoubleHitSpacePointConfig dhsp_cfg; + + // Combine two PlanarModuleClusters + SpacePointBuilder<DoubleHitSpacePoint> dhsp(dhsp_cfg); + dhsp.makeClusterPairs(tgContext, {pmc}, {pmc2}, clusterPairs); + + BOOST_CHECK_EQUAL(clusterPairs.size(), 1); + BOOST_CHECK_EQUAL(*(clusterPairs[0].first), *pmc); + BOOST_CHECK_EQUAL(*(clusterPairs[0].second), *pmc2); + + std::cout << "Calculate space point" << std::endl; + + dhsp.calculateSpacePoints(tgContext, clusterPairs, resultSP); + + BOOST_CHECK_EQUAL(resultSP.size(), 1); + + std::cout << "Create third hit" << std::endl; + + // Build third PlanarModuleCluster + Transform3D t3d3(Transform3D::Identity() * rotationNeg); + t3d3.translation() = Vector3D(0., 0., 10.005 * units::_m); + + DetectorElementStub detElem3(std::make_shared<const Transform3D>(t3d3)); + auto pSur3 = Surface::makeShared<PlaneSurface>(recBounds, detElem3); + + PlanarModuleCluster* pmc3 = new PlanarModuleCluster( + pSur3, 2, cov, local[0], local[1], {DigitizationCell(0, 0, 1.)}, &digMod); + + std::cout << "Try to store hits" << std::endl; + + // Combine points + dhsp.makeClusterPairs(tgContext, {pmc}, {pmc3}, clusterPairs); + + // Test for rejecting unconnected hits + BOOST_CHECK_EQUAL(resultSP.size(), 1); +} } // end of namespace Test } // end of namespace Acts diff --git a/Tests/Plugins/Digitization/PlanarModuleStepperTests.cpp b/Tests/Plugins/Digitization/PlanarModuleStepperTests.cpp index c7bfcfb9f001b3221ead93079d1544d0f1b93e6a..ec41a1fa539d04ee5921ebc91de40255bed8993b 100644 --- a/Tests/Plugins/Digitization/PlanarModuleStepperTests.cpp +++ b/Tests/Plugins/Digitization/PlanarModuleStepperTests.cpp @@ -24,91 +24,81 @@ #include "Acts/Plugins/Digitization/PlanarModuleStepper.hpp" namespace bdata = boost::unit_test::data; -namespace tt = boost::test_tools; +namespace tt = boost::test_tools; namespace Acts { namespace Test { - double halfX = 5 * units::_mm; - double halfY = 10 * units::_mm; - size_t ntests = 100; - size_t nbinsx = 100; - size_t nbinsy = 200; - double hThickness = 75 * units::_um; - double lAngle = 0.1; - double tanAlpha = tan(lAngle); - double sguardX = 2 * hThickness * abs(tanAlpha); - - // Module bounds - auto moduleBounds = std::make_shared<const RectangleBounds>(halfX, halfY); - auto cSegmentation - = std::make_shared<const CartesianSegmentation>(moduleBounds, - nbinsx, - nbinsy); - - // Create digitisation modules - // (1) positive readout - DigitizationModule pdModule(cSegmentation, hThickness, 1, lAngle, 0., true); - // (2) negative readout - DigitizationModule ndModule(cSegmentation, hThickness, -1, lAngle, 0., true); - std::vector<DigitizationModule> testModules - = {std::move(pdModule), std::move(ndModule)}; - - /// The Planar module stepper - PlanarModuleStepper pmStepper; - - // Create a test context - GeometryContext tgContext = GeometryContext(); - - /// The following test checks test cases where the entry and exit is - /// guaranteed to be in on the readout/counter plane - BOOST_DATA_TEST_CASE( - readout_counter_test, - bdata::random((bdata::seed = 0, - bdata::distribution - = std::uniform_real_distribution<>(-halfX + sguardX, - halfX - sguardX))) - ^ bdata::random((bdata::seed = 1, - bdata::distribution - = std::uniform_real_distribution<>(-halfX + sguardX, - halfX - sguardX))) - ^ bdata::random((bdata::seed = 2, - bdata::distribution - = std::uniform_real_distribution<>(-halfY, halfY))) - ^ bdata::random((bdata::seed = 3, - bdata::distribution - = std::uniform_int_distribution<>(-halfY, halfY))) - ^ bdata::xrange(ntests), - entryX, - entryY, - exitX, - exitY, - index) - { - - // avoid warning with void - (void)index; - - // Entry and exit point - Vector3D entry(entryX, entryY, -hThickness); - Vector3D exit(exitX, exitY, hThickness); - - // test the module flavours - for (auto& dm : testModules) { - // retrieve the digitiztion steps - auto cSteps = pmStepper.cellSteps(tgContext, dm, entry, exit); - BOOST_TEST(cSteps.size() != 0); - - // Test if the longitudinal distance between first and last step - // is equal/close to the thickness of the module - auto fPosition = cSteps.begin()->stepEntry; - auto lPosition = cSteps.rbegin()->stepExit; - double zDiff = (lPosition - fPosition).z(); - - CHECK_CLOSE_REL(zDiff, 2 * hThickness, 10e-6); - } +double halfX = 5 * units::_mm; +double halfY = 10 * units::_mm; +size_t ntests = 100; +size_t nbinsx = 100; +size_t nbinsy = 200; +double hThickness = 75 * units::_um; +double lAngle = 0.1; +double tanAlpha = tan(lAngle); +double sguardX = 2 * hThickness * abs(tanAlpha); + +// Module bounds +auto moduleBounds = std::make_shared<const RectangleBounds>(halfX, halfY); +auto cSegmentation = + std::make_shared<const CartesianSegmentation>(moduleBounds, nbinsx, nbinsy); + +// Create digitisation modules +// (1) positive readout +DigitizationModule pdModule(cSegmentation, hThickness, 1, lAngle, 0., true); +// (2) negative readout +DigitizationModule ndModule(cSegmentation, hThickness, -1, lAngle, 0., true); +std::vector<DigitizationModule> testModules = {std::move(pdModule), + std::move(ndModule)}; + +/// The Planar module stepper +PlanarModuleStepper pmStepper; + +// Create a test context +GeometryContext tgContext = GeometryContext(); + +/// The following test checks test cases where the entry and exit is +/// guaranteed to be in on the readout/counter plane +BOOST_DATA_TEST_CASE( + readout_counter_test, + bdata::random((bdata::seed = 0, + bdata::distribution = std::uniform_real_distribution<>( + -halfX + sguardX, halfX - sguardX))) ^ + bdata::random((bdata::seed = 1, + bdata::distribution = std::uniform_real_distribution<>( + -halfX + sguardX, halfX - sguardX))) ^ + bdata::random((bdata::seed = 2, + bdata::distribution = + std::uniform_real_distribution<>(-halfY, halfY))) ^ + bdata::random((bdata::seed = 3, + bdata::distribution = + std::uniform_int_distribution<>(-halfY, halfY))) ^ + bdata::xrange(ntests), + entryX, entryY, exitX, exitY, index) { + // avoid warning with void + (void)index; + + // Entry and exit point + Vector3D entry(entryX, entryY, -hThickness); + Vector3D exit(exitX, exitY, hThickness); + + // test the module flavours + for (auto& dm : testModules) { + // retrieve the digitiztion steps + auto cSteps = pmStepper.cellSteps(tgContext, dm, entry, exit); + BOOST_TEST(cSteps.size() != 0); + + // Test if the longitudinal distance between first and last step + // is equal/close to the thickness of the module + auto fPosition = cSteps.begin()->stepEntry; + auto lPosition = cSteps.rbegin()->stepExit; + double zDiff = (lPosition - fPosition).z(); + + CHECK_CLOSE_REL(zDiff, 2 * hThickness, 10e-6); } +} -} // namespace -} // namespace \ No newline at end of file +} // namespace Test +} // namespace Acts \ No newline at end of file diff --git a/Tests/Plugins/Digitization/SingleHitSpacePointBuilderTests.cpp b/Tests/Plugins/Digitization/SingleHitSpacePointBuilderTests.cpp index 3dea6d410a12907ebcf979b218c78119f4356b4b..3246103354201b4872487d2f78e2e67b27c9fe5c 100644 --- a/Tests/Plugins/Digitization/SingleHitSpacePointBuilderTests.cpp +++ b/Tests/Plugins/Digitization/SingleHitSpacePointBuilderTests.cpp @@ -20,81 +20,79 @@ #include "Acts/Tests/CommonHelpers/DetectorElementStub.hpp" namespace bdata = boost::unit_test::data; -namespace tt = boost::test_tools; +namespace tt = boost::test_tools; namespace Acts { namespace Test { - // Create a test context - GeometryContext tgContext = GeometryContext(); - - /// Unit test for testing the main functions of OneHitSpacePointBuilder - /// 1) A resolved dummy hit gets created and added. - /// 2) A hit gets added and resolved. - BOOST_DATA_TEST_CASE(SingleHitSpacePointBuilder_basic, - bdata::xrange(1), - index) - { - (void)index; - - // Build bounds - std::shared_ptr<const RectangleBounds> recBounds( - new RectangleBounds(35. * units::_um, 25. * units::_mm)); - - // Build binning and segmentation - std::vector<float> boundariesX, boundariesY; - boundariesX.push_back(-35. * units::_um); - boundariesX.push_back(35. * units::_um); - boundariesY.push_back(-25. * units::_mm); - boundariesY.push_back(25. * units::_mm); - - BinningData binDataX(BinningOption::open, BinningValue::binX, boundariesX); - std::shared_ptr<BinUtility> buX(new BinUtility(binDataX)); - BinningData binDataY(BinningOption::open, BinningValue::binY, boundariesY); - std::shared_ptr<BinUtility> buY(new BinUtility(binDataY)); - (*buX) += (*buY); - - std::shared_ptr<const Segmentation> segmentation( - new CartesianSegmentation(buX, recBounds)); - - // Build translation - - double rotation = 0.026; - RotationMatrix3D rotationPos; - Vector3D xPos(cos(rotation), sin(rotation), 0.); - Vector3D yPos(-sin(rotation), cos(rotation), 0.); - Vector3D zPos(0., 0., 1.); - rotationPos.col(0) = xPos; - rotationPos.col(1) = yPos; - rotationPos.col(2) = zPos; - Transform3D t3d(Transform3D::Identity() * rotationPos); - t3d.translation() = Vector3D(0., 0., 10. * units::_m); - - // Build Digitization - const DigitizationModule digMod(segmentation, 1., 1., 0.); - DetectorElementStub detElem(std::make_shared<const Transform3D>(t3d)); - auto pSur = Surface::makeShared<PlaneSurface>(recBounds, detElem); - ActsSymMatrixD<2> cov; - cov << 0., 0., 0., 0.; - Vector2D local = {0.1, -0.1}; - - // Build PlanarModuleCluster - PlanarModuleCluster* pmc = new PlanarModuleCluster( - pSur, 0, cov, local[0], local[1], {DigitizationCell(0, 0, 1.)}); - - std::cout << "Hit created" << std::endl; - - std::vector<SingleHitSpacePoint> data; - SpacePointBuilder<SingleHitSpacePoint> shsp; - - std::cout << "Hit added to storage" << std::endl; - - shsp.calculateSpacePoints(tgContext, {pmc}, data); - BOOST_CHECK_NE(data[0].spacePoint, Vector3D::Zero(3)); - - std::cout << "Space point calculated" << std::endl; - } +// Create a test context +GeometryContext tgContext = GeometryContext(); + +/// Unit test for testing the main functions of OneHitSpacePointBuilder +/// 1) A resolved dummy hit gets created and added. +/// 2) A hit gets added and resolved. +BOOST_DATA_TEST_CASE(SingleHitSpacePointBuilder_basic, bdata::xrange(1), + index) { + (void)index; + + // Build bounds + std::shared_ptr<const RectangleBounds> recBounds( + new RectangleBounds(35. * units::_um, 25. * units::_mm)); + + // Build binning and segmentation + std::vector<float> boundariesX, boundariesY; + boundariesX.push_back(-35. * units::_um); + boundariesX.push_back(35. * units::_um); + boundariesY.push_back(-25. * units::_mm); + boundariesY.push_back(25. * units::_mm); + + BinningData binDataX(BinningOption::open, BinningValue::binX, boundariesX); + std::shared_ptr<BinUtility> buX(new BinUtility(binDataX)); + BinningData binDataY(BinningOption::open, BinningValue::binY, boundariesY); + std::shared_ptr<BinUtility> buY(new BinUtility(binDataY)); + (*buX) += (*buY); + + std::shared_ptr<const Segmentation> segmentation( + new CartesianSegmentation(buX, recBounds)); + + // Build translation + + double rotation = 0.026; + RotationMatrix3D rotationPos; + Vector3D xPos(cos(rotation), sin(rotation), 0.); + Vector3D yPos(-sin(rotation), cos(rotation), 0.); + Vector3D zPos(0., 0., 1.); + rotationPos.col(0) = xPos; + rotationPos.col(1) = yPos; + rotationPos.col(2) = zPos; + Transform3D t3d(Transform3D::Identity() * rotationPos); + t3d.translation() = Vector3D(0., 0., 10. * units::_m); + + // Build Digitization + const DigitizationModule digMod(segmentation, 1., 1., 0.); + DetectorElementStub detElem(std::make_shared<const Transform3D>(t3d)); + auto pSur = Surface::makeShared<PlaneSurface>(recBounds, detElem); + ActsSymMatrixD<2> cov; + cov << 0., 0., 0., 0.; + Vector2D local = {0.1, -0.1}; + + // Build PlanarModuleCluster + PlanarModuleCluster* pmc = new PlanarModuleCluster( + pSur, 0, cov, local[0], local[1], {DigitizationCell(0, 0, 1.)}); + + std::cout << "Hit created" << std::endl; + + std::vector<SingleHitSpacePoint> data; + SpacePointBuilder<SingleHitSpacePoint> shsp; + + std::cout << "Hit added to storage" << std::endl; + + shsp.calculateSpacePoints(tgContext, {pmc}, data); + BOOST_CHECK_NE(data[0].spacePoint, Vector3D::Zero(3)); + + std::cout << "Space point calculated" << std::endl; +} } // end of namespace Test } // end of namespace Acts