diff --git a/core/include/detray/builders/surface_factory.hpp b/core/include/detray/builders/surface_factory.hpp index 0528efd7c..18e6b0293 100644 --- a/core/include/detray/builders/surface_factory.hpp +++ b/core/include/detray/builders/surface_factory.hpp @@ -87,7 +87,8 @@ class surface_factory : public surface_factory_interface { DETRAY_HOST void push_back(surface_data_t &&sf_data) override { - auto [type, vlink, index, source, bounds, trf] = sf_data.get_data(); + auto [type, vlink, index, source, bounds, trf] = + std::move(sf_data).get_data(); assert(bounds.size() == mask_shape_t::boundaries::e_size); diff --git a/core/include/detray/definitions/detail/math.hpp b/core/include/detray/definitions/detail/math.hpp index 0ffd6c1bc..2ec8ced1e 100644 --- a/core/include/detray/definitions/detail/math.hpp +++ b/core/include/detray/definitions/detail/math.hpp @@ -147,31 +147,6 @@ namespace detail { using math::copysign; using math::signbit; -/// Composes a floating point value with the magnitude of @param mag and the -/// sign of @param sgn -/*template -DETRAY_HOST_DEVICE inline scalar_t copysign(scalar_t mag, scalar_t sgn) { -#if defined(__CUDACC__) - if constexpr (std::is_same_v) { - return copysignf(mag, sgn); - } else { - return copysign(mag, sgn); - } -#elif !defined(__CUDACC__) - return math::copysign(mag, sgn); -#endif -} - -/// Gets the signbit from a variable -template -DETRAY_HOST_DEVICE inline bool signbit(scalar_t arg) { -#if defined(__CUDACC__) - return signbit(arg); -#elif !defined(__CUDACC__) - return math::signbit(arg); -#endif -}*/ - } // namespace detail } // namespace detray diff --git a/core/include/detray/geometry/detail/shape_utils.hpp b/core/include/detray/geometry/detail/shape_utils.hpp index 5fa52d421..23cd46b28 100644 --- a/core/include/detray/geometry/detail/shape_utils.hpp +++ b/core/include/detray/geometry/detail/shape_utils.hpp @@ -17,7 +17,7 @@ namespace detray::detail { /// @return the opening angle of a chord the size of tol (= 2*arcsin(c/(2r))) /// using a small angle approximation template -inline constexpr scalar_t phi_tolerance(scalar_t tol, scalar_t radius) { +constexpr scalar_t phi_tolerance(scalar_t tol, scalar_t radius) { return tol / radius; } diff --git a/core/include/detray/geometry/detail/volume_descriptor.hpp b/core/include/detray/geometry/detail/volume_descriptor.hpp index 193eecef5..4634a258f 100644 --- a/core/include/detray/geometry/detail/volume_descriptor.hpp +++ b/core/include/detray/geometry/detail/volume_descriptor.hpp @@ -200,8 +200,7 @@ class volume_descriptor { -> void { auto& rg = sf_link(); // Range not set yet - initialize - constexpr typename sf_link_type::index_type empty{}; - if (rg == empty) { + if (constexpr typename sf_link_type::index_type empty{}; rg == empty) { rg = {0u, static_cast(n_surfaces)}; } // Update diff --git a/core/include/detray/geometry/mask.hpp b/core/include/detray/geometry/mask.hpp index 9f5dc30b0..323a8861d 100644 --- a/core/include/detray/geometry/mask.hpp +++ b/core/include/detray/geometry/mask.hpp @@ -76,7 +76,8 @@ class mask { : _volume_link(link) { assert(values.size() == boundaries::e_size && " Given number of boundaries does not match mask shape."); - std::copy(std::cbegin(values), std::cend(values), std::begin(_values)); + std::ranges::copy(std::cbegin(values), std::cend(values), + std::begin(_values)); } /// Assignment operator from an array, convenience function diff --git a/core/include/detray/grids/axis.hpp b/core/include/detray/grids/axis.hpp index a5f585e37..35b0fd780 100644 --- a/core/include/detray/grids/axis.hpp +++ b/core/include/detray/grids/axis.hpp @@ -331,8 +331,7 @@ struct circular { std::ranges::for_each(sequence, [&](auto &n) { n += m++; }); return sequence; } - dindex vl = - static_cast(n_bins - nh_range[0] + nh_range[1] + 1u); + dindex vl = n_bins - nh_range[0] + nh_range[1] + 1u; dindex mi = 0; dindex mo = 0; dindex_sequence sequence(static_cast(vl), @@ -521,9 +520,9 @@ struct irregular { int bins = static_cast(boundaries.size()) - 1; int ibinmin = static_cast(ibin) - static_cast(nhood[0]); int ibinmax = static_cast(ibin + nhood[1]); - dindex min_bin = (ibinmin >= 0) ? static_cast(ibinmin) : 0u; - dindex max_bin = (ibinmax < bins) ? static_cast(ibinmax) - : static_cast(bins - 1); + auto min_bin = (ibinmin >= 0) ? static_cast(ibinmin) : 0u; + auto max_bin = (ibinmax < bins) ? static_cast(ibinmax) + : static_cast(bins - 1); return {min_bin, max_bin}; } diff --git a/core/include/detray/navigation/volume_graph.hpp b/core/include/detray/navigation/volume_graph.hpp index 58766b0e6..9599f6ea2 100644 --- a/core/include/detray/navigation/volume_graph.hpp +++ b/core/include/detray/navigation/volume_graph.hpp @@ -124,18 +124,13 @@ class volume_graph { /// Constructor from an iterator on the detector volume container /// and a reference to its surface container. iterator(volume_iter &&vol_itr, const detector_t &det) - : m_vol_itr(vol_itr), m_det(det) {} + : m_vol_itr(std::move(vol_itr)), m_det(det) {} /// Equality operator bool operator==(const iterator &rhs) const { return m_vol_itr == rhs.m_vol_itr; } - /// Inequality operator - bool operator!=(const iterator &rhs) const { - return not(*this == rhs); - } - /// Dereference operator @returns a graph node node operator*() { return node({m_det, m_vol_itr->index()}); } @@ -151,24 +146,6 @@ class volume_graph { return *this; } - /// @returns an iterator that has been advanced by @param j - constexpr auto operator+(const difference_type j) const - -> iterator { - return {m_vol_itr + j, m_det}; - } - - /// @returns an iterator that has been advanced by - @param j - constexpr auto operator-(const difference_type j) const - -> iterator { - return *this + -j; - } - - /// @returns distance between two iterators - constexpr auto operator-(const iterator &other) const - -> difference_type { - return m_vol_itr - other.m_vol_itr; - } - /// Advances iterator by @param j constexpr auto operator+=(const difference_type j) -> iterator & { m_vol_itr += j; @@ -180,6 +157,27 @@ class volume_graph { return *this += -j; } + protected: + /// @returns an iterator that has been advanced by @param j + friend constexpr auto operator+(const difference_type j, + const iterator &itr) -> iterator { + return {itr.m_vol_itr + j, itr.m_det}; + } + + /// @returns an iterator that has been advanced by - @param j + friend constexpr auto operator-(const difference_type j, + const iterator &itr) -> iterator { + return itr + -j; + } + + /// @returns distance between two iterators + friend constexpr auto operator-(const iterator &lhs, + const iterator &rhs) + -> difference_type { + return lhs.m_vol_itr - rhs.m_vol_itr; + } + + private: /// Iterator over the detector volume container. volume_iter m_vol_itr; /// Access to detector surfaces @@ -230,7 +228,8 @@ class volume_graph { dindex from() const { return _from; } dindex to() const { return _to; } - dindex _from, _to; + dindex _from; + dindex _to; }; /// Nested functor that fills the edges from a mask container @@ -388,7 +387,7 @@ class volume_graph { }*/ /// @returns the linking description as a string. - inline const std::string to_string() const { + inline std::string to_string() const { std::stringstream stream; dindex dim = n_nodes() + 1u; for (const auto &n : _nodes) { @@ -415,7 +414,7 @@ class volume_graph { } /// @returns the linking description as a string in DOT syntax. - inline const std::string to_dot_string() const { + inline std::string to_dot_string() const { std::stringstream stream; dindex dim = n_nodes() + 1u; @@ -426,7 +425,7 @@ class volume_graph { stream << " splines=true;" << std::endl; stream << " mode=KK;" << std::endl; stream << std::endl; - stream << " exit [label=\"OOB\",fillcolor=\"firebrick1\"];" + stream << R"( exit [label="OOB",fillcolor="firebrick1"];)" << std::endl; for (const auto &n : _nodes) { diff --git a/core/include/detray/propagator/base_stepper.hpp b/core/include/detray/propagator/base_stepper.hpp index 15fde1349..8ea616767 100644 --- a/core/include/detray/propagator/base_stepper.hpp +++ b/core/include/detray/propagator/base_stepper.hpp @@ -73,7 +73,7 @@ class base_stepper { matrix_operator() .template identity()); - // A dummy barcode - should not be used + // An invalid barcode - should not be used m_bound_params.set_surface_link(geometry::barcode{}); // Reset jacobian transport to identity matrix diff --git a/core/include/detray/utils/consistency_checker.hpp b/core/include/detray/utils/consistency_checker.hpp index cb0f589c3..223e38d1b 100644 --- a/core/include/detray/utils/consistency_checker.hpp +++ b/core/include/detray/utils/consistency_checker.hpp @@ -226,22 +226,15 @@ inline void check_empty(const detector_t &det, const bool verbose) { } // In the brute force finder, also other surfaces can be contained, e.g. // passive surfaces (depends on the detector) - for (const auto &pt_desc : det.portals()) { - if (pt_desc.is_portal()) { - return true; - } - } - return false; + return std::ranges::any_of( + det.portals(), [](auto pt_desc) { return pt_desc.is_portal(); }); }; // Check if there is at least one volume in the detector volume finder auto find_volumes = [](const typename detector_t::volume_finder &vf) { - for (const auto &v : vf.all()) { - if (!detail::is_invalid_value(v)) { - return true; - } - } - return false; + return std::ranges::any_of(vf.all(), [](const auto &v) { + return !detail::is_invalid_value(v); + }); }; // Fatal errors diff --git a/core/include/detray/utils/grid/detail/axis_bounds.hpp b/core/include/detray/utils/grid/detail/axis_bounds.hpp index b598517ec..12a664a6e 100644 --- a/core/include/detray/utils/grid/detail/axis_bounds.hpp +++ b/core/include/detray/utils/grid/detail/axis_bounds.hpp @@ -210,7 +210,7 @@ struct circular { /// @returns an index of a remapped bin DETRAY_HOST_DEVICE constexpr int wrap(const int ibin, const std::size_t nbins) const { - const int bins = static_cast(nbins); + const auto bins = static_cast(nbins); return (bins + (ibin % bins)) % bins; } diff --git a/core/include/detray/utils/grid/detail/simple_serializer.hpp b/core/include/detray/utils/grid/detail/simple_serializer.hpp index 9fad99b0f..734bed394 100644 --- a/core/include/detray/utils/grid/detail/simple_serializer.hpp +++ b/core/include/detray/utils/grid/detail/simple_serializer.hpp @@ -78,7 +78,7 @@ struct simple_serializer<2> { dindex nbins_axis0 = axes.template get_axis<0>().nbins(); dindex bin0{gbin % nbins_axis0}; - auto bin1{static_cast(gbin / nbins_axis0)}; + dindex bin1{gbin / nbins_axis0}; return {bin0, bin1}; } @@ -124,8 +124,9 @@ struct simple_serializer<3> { dindex nbins_axis1 = axes.template get_axis<1>().nbins(); dindex bin0{gbin % nbins_axis0}; - auto bin1{static_cast(gbin / nbins_axis0) % nbins_axis1}; - auto bin2{static_cast(gbin / (nbins_axis0 * nbins_axis1))}; + dindex bin1{(gbin / nbins_axis0) % nbins_axis1}; + dindex bin2{gbin / (nbins_axis0 * nbins_axis1)}; + return {bin0, bin1, bin2}; } }; diff --git a/core/include/detray/utils/ranges/static_join.hpp b/core/include/detray/utils/ranges/static_join.hpp index 53d2baea8..2c3ea05ea 100644 --- a/core/include/detray/utils/ranges/static_join.hpp +++ b/core/include/detray/utils/ranges/static_join.hpp @@ -178,7 +178,7 @@ requires std::input_iterator< DETRAY_HOST_DEVICE constexpr static_join_iterator(const iterator_coll_t &begins, const iterator_coll_t &ends) - : m_begins(&begins), m_ends(&ends), m_iter{(*m_begins)[0]}, m_idx{0u} {} + : m_begins(&begins), m_ends(&ends), m_iter{(*m_begins)[0]} {} /// Fully parametrized construction DETRAY_HOST_DEVICE diff --git a/core/include/detray/utils/string_view_concat.hpp b/core/include/detray/utils/string_view_concat.hpp index 6296767bd..34d20f80b 100644 --- a/core/include/detray/utils/string_view_concat.hpp +++ b/core/include/detray/utils/string_view_concat.hpp @@ -16,6 +16,8 @@ struct string_view_concat2 { std::string_view s1; std::string_view s2; - operator std::string() const { return std::string(s1) + std::string(s2); } + explicit operator std::string() const { + return std::string(s1) + std::string(s2); + } }; } // namespace detray diff --git a/io/include/detray/io/common/detail/basic_converter.hpp b/io/include/detray/io/common/detail/basic_converter.hpp index 43d4a4e7d..02c17f2b5 100644 --- a/io/include/detray/io/common/detail/basic_converter.hpp +++ b/io/include/detray/io/common/detail/basic_converter.hpp @@ -14,10 +14,8 @@ // System include(s) #include -namespace detray::io::detail { - // Convert basic information like links and header data -namespace basic_converter { +namespace detray::io::detail::basic_converter { /// @returns a link from its io payload @param link_data inline dindex convert(const single_link_payload& link_data) { @@ -60,6 +58,4 @@ inline common_header_payload convert(const std::string_view det_name, return header_data; } -} // namespace basic_converter - -} // namespace detray::io::detail +} // namespace detray::io::detail::basic_converter diff --git a/io/include/detray/io/common/detail/grid_reader.hpp b/io/include/detray/io/common/detail/grid_reader.hpp index 2bb278a1d..28684108b 100644 --- a/io/include/detray/io/common/detail/grid_reader.hpp +++ b/io/include/detray/io/common/detail/grid_reader.hpp @@ -212,7 +212,7 @@ class grid_reader { using algebra_t = typename detector_t::algebra_type; // Throw expection if the accelerator link type id is invalid - auto print_error = [](io::accel_id grid_link) -> void { + auto print_error = [](io::accel_id grid_link) { if (grid_link == io::accel_id::unknown) { throw std::invalid_argument( "Unknown accelerator id in geometry file!"); diff --git a/io/include/detray/io/common/geometry_reader.hpp b/io/include/detray/io/common/geometry_reader.hpp index 979e7f0a0..46534fcfa 100644 --- a/io/include/detray/io/common/geometry_reader.hpp +++ b/io/include/detray/io/common/geometry_reader.hpp @@ -64,8 +64,7 @@ class geometry_reader { // Convert the volumes one-by-one for (const auto& vol_data : det_data.volumes) { // Get a generic volume builder first and decorate it later - auto vbuilder = - det_builder.new_volume(static_cast(vol_data.type)); + auto vbuilder = det_builder.new_volume(vol_data.type); // Set the volume name name_map[vbuilder->vol_index() + 1u] = vol_data.name; @@ -75,7 +74,8 @@ class geometry_reader { convert(vol_data.transform)); // Prepare the surface factories (one per shape and surface type) - std::map pt_factories, sf_factories; + std::map pt_factories; + std::map sf_factories; // Add the surfaces to the factories for (const auto& sf_data : vol_data.surfaces) { @@ -210,8 +210,8 @@ class geometry_reader { } } // Test next shape id - constexpr int current_id{static_cast(I)}; - if constexpr (current_id > 0) { + if constexpr (constexpr int current_id{static_cast(I)}; + current_id > 0) { return init_factory(current_id - 1), detector_t>(shape_id); } diff --git a/io/include/detray/io/common/geometry_writer.hpp b/io/include/detray/io/common/geometry_writer.hpp index 0560b8684..d7b3804a8 100644 --- a/io/include/detray/io/common/geometry_writer.hpp +++ b/io/include/detray/io/common/geometry_writer.hpp @@ -53,7 +53,7 @@ class geometry_writer { static detector_payload convert( const detector_t& det, const typename detector_t::name_map& names) { detector_payload det_data; - det_data.volumes.reserve((det.volumes().size())); + det_data.volumes.reserve(det.volumes().size()); for (const auto& vol : det.volumes()) { const auto map_itr = names.find(vol.index() + 1u); @@ -122,7 +122,7 @@ class geometry_writer { template static volume_payload convert( const typename detector_t::volume_type& vol_desc, const detector_t& det, - const std::string& name) { + const std::string_view name) { volume_payload vol_data; vol_data.index = detail::basic_converter::convert(vol_desc.index()); @@ -165,8 +165,8 @@ class geometry_writer { /// Retrieve @c mask_payload from mask_store element struct get_mask_payload { template - inline auto operator()(const mask_group_t& mask_group, - const index_t& index) const { + constexpr auto operator()(const mask_group_t& mask_group, + const index_t& index) const { return geometry_writer::convert(mask_group[index]); } }; @@ -174,8 +174,8 @@ class geometry_writer { /// Retrieve @c material_link_payload from material_store element struct get_material_payload { template - inline auto operator()(const material_group_t&, - const index_t& index) const { + constexpr auto operator()(const material_group_t&, + const index_t& index) const { using material_t = typename material_group_t::value_type; // Find the correct material type index @@ -187,8 +187,8 @@ class geometry_writer { /// Retrieve @c acc_links_payload from surface_tore collection struct get_acc_link_payload { template - constexpr inline auto operator()(const acc_group_t&, - const index_t& index) const { + constexpr auto operator()(const acc_group_t&, + const index_t& index) const { using accel_t = typename acc_group_t::value_type; diff --git a/io/include/detray/io/common/homogeneous_material_writer.hpp b/io/include/detray/io/common/homogeneous_material_writer.hpp index 23fa943d0..f6715ad34 100644 --- a/io/include/detray/io/common/homogeneous_material_writer.hpp +++ b/io/include/detray/io/common/homogeneous_material_writer.hpp @@ -62,7 +62,7 @@ class homogeneous_material_writer { static detector_homogeneous_material_payload convert( const detector_t& det, const typename detector_t::name_map&) { detector_homogeneous_material_payload dm_data; - dm_data.volumes.reserve((det.volumes().size())); + dm_data.volumes.reserve(det.volumes().size()); for (const auto& vol : det.volumes()) { dm_data.volumes.push_back(convert(vol, det)); @@ -99,16 +99,18 @@ class homogeneous_material_writer { } // Find all surfaces that belong to the volume and count them - std::size_t sf_idx{0u}, slab_idx{0u}, rod_idx{0u}; + std::size_t sf_idx{0u}; + std::size_t slab_idx{0u}; + std::size_t rod_idx{0u}; auto vol = tracking_volume{det, vol_desc}; for (const auto& sf_desc : vol.surfaces()) { // Convert material slabs and rods const auto sf = tracking_surface{det, sf_desc}; - material_slab_payload mslp = - sf.template visit_material(sf_idx); - if (mslp.type == material_type::slab) { + if (material_slab_payload mslp = + sf.template visit_material(sf_idx); + mslp.type == material_type::slab) { mslp.index_in_coll = slab_idx++; mv_data.mat_slabs.push_back(mslp); } else if (mslp.type == material_type::rod) { diff --git a/io/include/detray/io/frontend/detail/detector_components_reader.hpp b/io/include/detray/io/frontend/detail/detector_components_reader.hpp index e18c3c14c..54fa988d3 100644 --- a/io/include/detray/io/frontend/detail/detector_components_reader.hpp +++ b/io/include/detray/io/frontend/detail/detector_components_reader.hpp @@ -58,9 +58,9 @@ class detector_components_reader final { /// Reads the full detector into @param det by calling the readers, while /// using the name map @param volume_names for to write the volume names. - virtual void read(detector_builder& det_builder, - typename detector_t::name_map& volume_names) { + void read(detector_builder& + det_builder, + typename detector_t::name_map& volume_names) { // We have to at least read a geometry assert(size() != 0u && diff --git a/io/include/detray/io/frontend/detail/detector_components_writer.hpp b/io/include/detray/io/frontend/detail/detector_components_writer.hpp index 59fe777d4..3d2289fff 100644 --- a/io/include/detray/io/frontend/detail/detector_components_writer.hpp +++ b/io/include/detray/io/frontend/detail/detector_components_writer.hpp @@ -49,10 +49,10 @@ class detector_components_writer final { /// Writes the full detector data of @param det to file by calling the /// writers, while using the name map @param names for the detector - virtual void write(const detector_t& det, - const typename detector_t::name_map& names, - const std::ios_base::openmode mode, - const std::filesystem::path& file_path) { + void write(const detector_t& det, + const typename detector_t::name_map& names, + const std::ios_base::openmode mode, + const std::filesystem::path& file_path) { // We have to at least write a geometry assert(m_writers.size() != 0u && "No writers registered! Need at least a geometry writer"); diff --git a/io/include/detray/io/frontend/detector_reader_config.hpp b/io/include/detray/io/frontend/detector_reader_config.hpp index 2e9d47422..3d5b0ead4 100644 --- a/io/include/detray/io/frontend/detector_reader_config.hpp +++ b/io/include/detray/io/frontend/detector_reader_config.hpp @@ -33,8 +33,8 @@ struct detector_reader_config { /// Setters /// @{ - detector_reader_config& add_file(const std::string file_name) { - m_files.push_back(std::move(file_name)); + detector_reader_config& add_file(const std::string& file_name) { + m_files.push_back(file_name); return *this; } detector_reader_config& do_check(const bool check) { @@ -49,20 +49,20 @@ struct detector_reader_config { return *this; } /// @} -}; -/// Print the detector reader configuration -inline std::ostream& operator<<(std::ostream& out, - const detector_reader_config& cfg) { + /// Print the detector reader configuration + friend std::ostream& operator<<(std::ostream& out, + const detector_reader_config& cfg) { - out << "\nDetector reader\n" - << "----------------------------\n" - << " Detector files: : \n"; - for (const auto& file_name : cfg.files()) { - out << " -> " << file_name << "\n"; - } + out << "\nDetector reader\n" + << "----------------------------\n" + << " Detector files: : \n"; + for (const auto& file_name : cfg.files()) { + out << " -> " << file_name << "\n"; + } - return out; -} + return out; + } +}; } // namespace detray::io diff --git a/io/include/detray/io/frontend/detector_writer_config.hpp b/io/include/detray/io/frontend/detector_writer_config.hpp index bc4f4d16c..c5fcfc624 100644 --- a/io/include/detray/io/frontend/detector_writer_config.hpp +++ b/io/include/detray/io/frontend/detector_writer_config.hpp @@ -68,25 +68,26 @@ struct detector_writer_config { return *this; } /// @} -}; -/// Print the detector writer configuration -inline std::ostream& operator<<(std::ostream& out, - const detector_writer_config& cfg) { - out << "\nDetector writer\n" - << "----------------------------\n" - << " Path : " << cfg.path() << "\n" - << " Write grids : " << std::boolalpha << cfg.write_grids() - << "\n" - << " Write material : " << cfg.write_material() << "\n"; + /// Print the detector writer configuration + friend std::ostream& operator<<(std::ostream& out, + const detector_writer_config& cfg) { + out << "\nDetector writer\n" + << "----------------------------\n" + << " Path : " << cfg.path() << "\n" + << " Write grids : " << std::boolalpha + << cfg.write_grids() << "\n" + << " Write material : " << cfg.write_material() << "\n"; - if (cfg.format() == detray::io::format::json) { - out << " Compactify json : " << cfg.compactify_json() << "\n"; - } - // Reset state - out << std::noboolalpha; + if (cfg.format() == detray::io::format::json) { + out << " Compactify json : " << cfg.compactify_json() + << "\n"; + } + // Reset state + out << std::noboolalpha; - return out; -} + return out; + } +}; } // namespace detray::io diff --git a/io/include/detray/io/frontend/implementation/json_readers.hpp b/io/include/detray/io/frontend/implementation/json_readers.hpp index 5572ac9bb..f1d51f58a 100644 --- a/io/include/detray/io/frontend/implementation/json_readers.hpp +++ b/io/include/detray/io/frontend/implementation/json_readers.hpp @@ -63,7 +63,7 @@ inline void add_json_readers( io::detail::detector_components_reader& reader, const std::vector& files) noexcept(false) { - for (const std::string& file_name : files) { + for (const std::filesystem::path file_name : files) { if (file_name.empty()) { std::cout << "WARNING: Empty file name. Component will not be built" @@ -71,10 +71,8 @@ inline void add_json_readers( continue; } - std::string extension{std::filesystem::path{file_name}.extension()}; - // Only add readers for json files - if (extension != ".json") { + if (file_name.extension() != ".json") { continue; } @@ -123,8 +121,9 @@ inline void add_json_readers( print_type_warning(header.tag); } } else { - throw std::invalid_argument("Unsupported file tag '" + header.tag + - "' in input file: " + file_name); + throw std::invalid_argument( + "Unsupported file tag '" + header.tag + + "' in input file: " + file_name.string()); } } } diff --git a/io/include/detray/io/frontend/payloads.hpp b/io/include/detray/io/frontend/payloads.hpp index 47d1bb9a2..aaf208c7f 100644 --- a/io/include/detray/io/frontend/payloads.hpp +++ b/io/include/detray/io/frontend/payloads.hpp @@ -62,7 +62,8 @@ struct typed_link_payload { /// @brief a payload for the geometry specific part of the file header struct geo_sub_header_payload { - std::size_t n_volumes{0ul}, n_surfaces{0ul}; + std::size_t n_volumes{0ul}; + std::size_t n_surfaces{0ul}; }; /// @brief a payload for the geometry file header @@ -122,7 +123,8 @@ struct volume_payload { /// @brief a payload for the material specific part of the file header struct homogeneous_material_sub_header_payload { - std::size_t n_slabs{0ul}, n_rods{0ul}; + std::size_t n_slabs{0ul}; + std::size_t n_rods{0ul}; }; /// @brief a payload for the homogeneous material file header diff --git a/io/include/detray/io/json/json_reader.hpp b/io/include/detray/io/json/json_reader.hpp index f70b5aaad..c7d3015a5 100644 --- a/io/include/detray/io/json/json_reader.hpp +++ b/io/include/detray/io/json/json_reader.hpp @@ -40,10 +40,10 @@ class json_reader final : public reader_interface { json_reader() : reader_interface(".json") {} /// Writes the geometry to file with a given name - virtual void read(detector_builder& det_builder, - typename detector_t::name_map& name_map, - const std::string& file_name) override { + void read(detector_builder& + det_builder, + typename detector_t::name_map& name_map, + const std::string& file_name) override { // Read json from file io::file_handle file{file_name, diff --git a/io/include/detray/io/json/json_writer.hpp b/io/include/detray/io/json/json_writer.hpp index b54ddab3b..a111e198a 100644 --- a/io/include/detray/io/json/json_writer.hpp +++ b/io/include/detray/io/json/json_writer.hpp @@ -41,7 +41,7 @@ class json_writer final : public writer_interface { json_writer() : writer_interface(".json") {} /// Writes the geometry to file with a given name - virtual std::string write( + std::string write( const detector_t &det, const typename detector_t::name_map &names, const std::ios_base::openmode mode = std::ios::out | std::ios::binary, const std::filesystem::path &file_path = {"./"}) override { diff --git a/io/include/detray/io/utils/create_path.hpp b/io/include/detray/io/utils/create_path.hpp index f061a7d9f..6512c0168 100644 --- a/io/include/detray/io/utils/create_path.hpp +++ b/io/include/detray/io/utils/create_path.hpp @@ -30,7 +30,7 @@ inline std::string alt_file_name(const std::string& name) { /// @returns alternate file stem upon collision auto get_alternate_file_stem = [](std::string& file_stem, - const std::size_t n) -> std::string { + const std::size_t n) { const std::string delim{"_"}; // File stem already comes with a number, simply update it diff --git a/plugins/svgtools/include/detray/plugins/svgtools/conversion/grid.hpp b/plugins/svgtools/include/detray/plugins/svgtools/conversion/grid.hpp index 665297ae3..d7762a7b9 100644 --- a/plugins/svgtools/include/detray/plugins/svgtools/conversion/grid.hpp +++ b/plugins/svgtools/include/detray/plugins/svgtools/conversion/grid.hpp @@ -31,7 +31,11 @@ namespace detray::svgtools::conversion { namespace detail { -enum grid_type : std::uint8_t { e_barrel = 0, e_endcap = 1, e_unknown = 2 }; +enum class grid_type : std::uint8_t { + e_barrel = 0, + e_endcap = 1, + e_unknown = 2 +}; /// @returns the actsvg grid type and edge values for a detray 2D cylinder grid. template diff --git a/plugins/svgtools/include/detray/plugins/svgtools/conversion/surface_grid.hpp b/plugins/svgtools/include/detray/plugins/svgtools/conversion/surface_grid.hpp index 161d9204e..a6a974ab3 100644 --- a/plugins/svgtools/include/detray/plugins/svgtools/conversion/surface_grid.hpp +++ b/plugins/svgtools/include/detray/plugins/svgtools/conversion/surface_grid.hpp @@ -190,10 +190,10 @@ std::vector> get_bin_association( using geo_object_ids = typename detector_t::geo_obj_ids; const auto& vol_desc = det.volume(vol.index()); - const auto& link = - vol_desc.template accel_link(); - if (!link.is_invalid()) { + if (const auto& link = + vol_desc.template accel_link(); + !link.is_invalid()) { return det.accelerator_store() .template visit(link, vol_desc, search_window); diff --git a/plugins/svgtools/include/detray/plugins/svgtools/illustrator.hpp b/plugins/svgtools/include/detray/plugins/svgtools/illustrator.hpp index 12ebca55d..310f1ad78 100644 --- a/plugins/svgtools/include/detray/plugins/svgtools/illustrator.hpp +++ b/plugins/svgtools/include/detray/plugins/svgtools/illustrator.hpp @@ -109,7 +109,8 @@ class illustrator { const auto surface = detray::tracking_surface{_detector, index}; - actsvg::svg::object ret, material; + actsvg::svg::object ret; + actsvg::svg::object material; const auto& style = _style._detector_style._volume_style; if (surface.is_portal()) { @@ -215,20 +216,21 @@ class illustrator { const styling::surface_material_style* mat_style{nullptr}; const auto& vol_style = _style._detector_style._volume_style; switch (surface.id()) { - case surface_id::e_portal: { + using enum surface_id; + case e_portal: { mat_style = &vol_style._portal_style._surface_style._material_style; break; } - case surface_id::e_sensitive: { + case e_sensitive: { mat_style = &vol_style._sensitive_surface_style._material_style; break; } - case surface_id::e_passive: { + case e_passive: { mat_style = &vol_style._passive_surface_style._material_style; break; } - case surface_id::e_unknown: { + case e_unknown: { throw std::runtime_error( "Encountered surface of unknown type."); break; diff --git a/plugins/svgtools/include/detray/plugins/svgtools/styling/colors.hpp b/plugins/svgtools/include/detray/plugins/svgtools/styling/colors.hpp index db2da5051..35b5a9a2f 100644 --- a/plugins/svgtools/include/detray/plugins/svgtools/styling/colors.hpp +++ b/plugins/svgtools/include/detray/plugins/svgtools/styling/colors.hpp @@ -12,6 +12,7 @@ // System include(s) #include +#include #include #include @@ -20,8 +21,10 @@ namespace detray::svgtools::styling::colors { /// @brief Picks a random element in the container. template inline auto pick_random(container_t container) { - const auto idx = static_cast(std::rand()) % container.size(); - return container[idx]; + typename container_t::value_type c{}; + std::sample(container.cbegin(), container.cend(), &c, 1, + std::mt19937{std::random_device{}()}); + return c; } // Black diff --git a/plugins/svgtools/include/detray/plugins/svgtools/styling/styling.hpp b/plugins/svgtools/include/detray/plugins/svgtools/styling/styling.hpp index 991993cdb..f05748be3 100644 --- a/plugins/svgtools/include/detray/plugins/svgtools/styling/styling.hpp +++ b/plugins/svgtools/include/detray/plugins/svgtools/styling/styling.hpp @@ -40,7 +40,6 @@ struct grid_style { /// Style applied to an actsvg proto surface_material struct surface_material_style { actsvg::point2 _info_pos; - // unsigned int _info_font_size; actsvg::point2 _gradient_pos; std::array _gradient_box; @@ -48,7 +47,6 @@ struct surface_material_style { actsvg::style::label _gradient_label; actsvg::style::color _gradient_stroke_color; actsvg::scalar _gradient_stroke_width; - // unsigned int _gradient_font_size; std::vector _gradient_color_scale; unsigned int _gradient_n_stops; @@ -67,14 +65,10 @@ struct surface_style { _material_style{mat_style} { _stroke_color = fill_color; - _highlight_rgb = colors::macaroni_and_cheese; - _highlights = {}; _highlight_stroke_rgb = _highlight_rgb; _highlight_stroke_width = stroke_width; - _font_size = 22u; _material_style._gradient_font._size = 26u; _material_style._gradient_label._font._size = 26u; - _n_segments = 72u; } // Fill color actsvg::style::color _fill_color; @@ -84,14 +78,14 @@ struct surface_style { actsvg::style::color _stroke_color; // Highlights - std::array _highlight_rgb; - std::vector _highlights; + std::array _highlight_rgb{colors::macaroni_and_cheese}; + std::vector _highlights{}; std::array _highlight_stroke_rgb; actsvg::scalar _highlight_stroke_width; - unsigned int _font_size; + unsigned int _font_size{22u}; // Granularity of vertex approximation of arcs - unsigned int _n_segments; + unsigned int _n_segments{72u}; surface_material_style _material_style; }; diff --git a/tests/benchmarks/cpu/grid.cpp b/tests/benchmarks/cpu/grid.cpp index 3fcd49550..bd61086c8 100644 --- a/tests/benchmarks/cpu/grid.cpp +++ b/tests/benchmarks/cpu/grid.cpp @@ -26,6 +26,7 @@ // System include(s) #include #include +#include #include // Use the detray:: namespace implicitly. @@ -41,12 +42,14 @@ const auto tp = test::point2{12.f, 30.f}; /// Prepare test points auto make_random_points() { - std::srand(42); + std::random_device rd; + std::mt19937_64 gen(rd()); + std::uniform_real_distribution dist1(0.f, 24.f); + std::uniform_real_distribution dist2(0.f, 59.f); std::vector points{}; for (unsigned int itest = 0u; itest < 1000000u; ++itest) { - points.push_back({static_cast((std::rand() % 50)) * 0.5f, - static_cast((std::rand() % 120)) * 0.5f}); + points.push_back({dist1(gen), dist2(gen)}); } return points; diff --git a/tests/benchmarks/cpu/grid2.cpp b/tests/benchmarks/cpu/grid2.cpp index 038e96749..865c686cc 100644 --- a/tests/benchmarks/cpu/grid2.cpp +++ b/tests/benchmarks/cpu/grid2.cpp @@ -26,6 +26,7 @@ // System include(s) #include #include +#include // Use the detray:: namespace implicitly. using namespace detray; @@ -40,12 +41,14 @@ const auto tp = test::point2{12.f, 30.f}; /// Prepare test points auto make_random_points() { - std::srand(42); + std::random_device rd; + std::mt19937_64 gen(rd()); + std::uniform_real_distribution dist1(0.f, 24.f); + std::uniform_real_distribution dist2(0.f, 59.f); std::vector points{}; for (unsigned int itest = 0u; itest < 1000000u; ++itest) { - points.push_back({static_cast((std::rand() % 50)) * 0.5f, - static_cast((std::rand() % 120)) * 0.5f}); + points.push_back({dist1(gen), dist2(gen)}); } return points; @@ -74,7 +77,8 @@ template xboundaries, yboundaries; + dvector xboundaries; + dvector yboundaries; xboundaries.reserve(25u); yboundaries.reserve(60u); for (scalar i = 0.f; i < 61.f; i += 1.f) { diff --git a/tests/benchmarks/cpu/intersect_surfaces.cpp b/tests/benchmarks/cpu/intersect_surfaces.cpp index 2c98e9c9b..ed64df357 100644 --- a/tests/benchmarks/cpu/intersect_surfaces.cpp +++ b/tests/benchmarks/cpu/intersect_surfaces.cpp @@ -79,13 +79,13 @@ BENCHMARK(BM_INTERSECT_PLANES) namespace { -enum mask_ids : unsigned int { +enum class mask_ids : unsigned int { e_rectangle2 = 0, e_cylinder2 = 1, e_conc_cylinder3 = 2, }; -enum material_ids : unsigned int { +enum class material_ids : unsigned int { e_slab = 0, }; diff --git a/tests/benchmarks/cpu/intersectors.cpp b/tests/benchmarks/cpu/intersectors.cpp index 2bab91620..d1abb1719 100644 --- a/tests/benchmarks/cpu/intersectors.cpp +++ b/tests/benchmarks/cpu/intersectors.cpp @@ -45,13 +45,13 @@ constexpr std::size_t simd_size{dscalar::size()}; namespace { -enum mask_ids : unsigned int { +enum class mask_ids : unsigned int { e_rectangle2 = 0, e_cylinder2 = 1, e_conc_cylinder3 = 2, }; -enum material_ids : unsigned int { +enum class material_ids : unsigned int { e_slab = 0, }; diff --git a/tests/benchmarks/cuda/benchmark_propagator_cuda_kernel.hpp b/tests/benchmarks/cuda/benchmark_propagator_cuda_kernel.hpp index cea3f58a2..ee2f505cb 100644 --- a/tests/benchmarks/cuda/benchmark_propagator_cuda_kernel.hpp +++ b/tests/benchmarks/cuda/benchmark_propagator_cuda_kernel.hpp @@ -1,6 +1,6 @@ /** Detray library, part of the ACTS project (R&D line) * - * (c) 2022-2023 CERN for the benefit of the ACTS project + * (c) 2022-2024 CERN for the benefit of the ACTS project * * Mozilla Public License Version 2.0 */ @@ -23,27 +23,25 @@ #include "detray/propagator/rk_stepper.hpp" #include "detray/tracks/tracks.hpp" -using namespace detray; - using algebra_t = ALGEBRA_PLUGIN; -using detector_host_type = detector; -using detector_device_type = detector; - -using intersection_t = - intersection2D; - -using navigator_host_type = navigator; -using navigator_device_type = navigator; -using field_type = bfield::const_field_t; -using rk_stepper_type = rk_stepper; -using actor_chain_t = actor_chain, - pointwise_material_interactor, - parameter_resetter>; +using detector_host_type = + detray::detector; +using detector_device_type = + detray::detector; + +using navigator_host_type = detray::navigator; +using navigator_device_type = detray::navigator; +using field_type = detray::bfield::const_field_t; +using rk_stepper_type = detray::rk_stepper; +using actor_chain_t = + detray::actor_chain, + detray::pointwise_material_interactor, + detray::parameter_resetter>; using propagator_host_type = - propagator; + detray::propagator; using propagator_device_type = - propagator; + detray::propagator; enum class propagate_option { e_unsync = 0, diff --git a/tests/include/detray/test/common/detail/whiteboard.hpp b/tests/include/detray/test/common/detail/whiteboard.hpp index c2042cb61..e4f8b0b42 100644 --- a/tests/include/detray/test/common/detail/whiteboard.hpp +++ b/tests/include/detray/test/common/detail/whiteboard.hpp @@ -69,7 +69,7 @@ inline void detray::test::whiteboard::add(const std::string& name, T&& object) { if (name.empty()) { throw std::invalid_argument("Object cannot have an empty name"); } - if (0 < m_store.count(name)) { + if (m_store.contains(name)) { throw std::invalid_argument("Object '" + name + "' already exists"); } m_store.emplace(name, std::forward(object)); @@ -98,7 +98,7 @@ inline T& detray::test::whiteboard::get(const std::string& name) noexcept( } inline bool detray::test::whiteboard::exists(const std::string& name) const { - return m_store.find(name) != m_store.end(); + return m_store.contains(name); } } // namespace detray::test diff --git a/tests/include/detray/test/common/detector_scan_config.hpp b/tests/include/detray/test/common/detector_scan_config.hpp index 75709f20e..f471133c1 100644 --- a/tests/include/detray/test/common/detector_scan_config.hpp +++ b/tests/include/detray/test/common/detector_scan_config.hpp @@ -71,16 +71,16 @@ struct detector_scan_config : public test::fixture_base<>::configuration { /// Setters /// @{ - detector_scan_config &name(const std::string n) { + detector_scan_config &name(const std::string_view n) { m_name = n; return *this; } - detector_scan_config &intersection_file(const std::string f) { - m_intersection_file = std::move(f); + detector_scan_config &intersection_file(const std::string_view f) { + m_intersection_file = f; return *this; } - detector_scan_config &track_param_file(const std::string f) { - m_track_param_file = std::move(f); + detector_scan_config &track_param_file(const std::string_view f) { + m_track_param_file = f; return *this; } detector_scan_config &mask_tolerance(const std::array tol) { diff --git a/tests/include/detray/test/common/fixture_base.hpp b/tests/include/detray/test/common/fixture_base.hpp index f02ad3163..2550bf1fc 100644 --- a/tests/include/detray/test/common/fixture_base.hpp +++ b/tests/include/detray/test/common/fixture_base.hpp @@ -87,7 +87,7 @@ class fixture_base : public scope { }; /// Constructor - fixture_base(const configuration& cfg = {}) + explicit fixture_base(const configuration& cfg = {}) : tolerance{cfg.tol()}, inf{cfg.inf}, epsilon{cfg.epsilon}, @@ -99,13 +99,22 @@ class fixture_base : public scope { std::string name() const { return "detray_test"; }; protected: - float tolerance{}, inf{}, epsilon{}, path_limit{}, overstep_tolerance{}, - step_constraint{}; - - static void SetUpTestSuite() {} - static void TearDownTestSuite() {} - virtual void SetUp() override {} - virtual void TearDown() override {} + static void SetUpTestSuite() { /* Do nothing */ + } + static void TearDownTestSuite() { /* Do nothing */ + } + void SetUp() override { /* Do nothing */ + } + void TearDown() override { /* Do nothing */ + } + + private: + float tolerance{}; + float inf{}; + float epsilon{}; + float path_limit{}; + float overstep_tolerance{}; + float step_constraint{}; }; } // namespace detray::test diff --git a/tests/include/detray/test/common/material_validation_config.hpp b/tests/include/detray/test/common/material_validation_config.hpp index 8b96bb2be..14ea10262 100644 --- a/tests/include/detray/test/common/material_validation_config.hpp +++ b/tests/include/detray/test/common/material_validation_config.hpp @@ -56,7 +56,7 @@ struct material_validation_config : public test::fixture_base<>::configuration { /// Setters /// @{ - material_validation_config &name(const std::string n) { + material_validation_config &name(const std::string &n) { m_name = n; return *this; } @@ -73,8 +73,8 @@ struct material_validation_config : public test::fixture_base<>::configuration { m_white_board = std::move(w_board); return *this; } - material_validation_config &material_file(const std::string f) { - m_material_file = std::move(f); + material_validation_config &material_file(const std::string &f) { + m_material_file = f; return *this; } material_validation_config &n_tracks(std::size_t n) { diff --git a/tests/include/detray/test/common/navigation_validation_config.hpp b/tests/include/detray/test/common/navigation_validation_config.hpp index 6742a51e9..b76f89ce0 100644 --- a/tests/include/detray/test/common/navigation_validation_config.hpp +++ b/tests/include/detray/test/common/navigation_validation_config.hpp @@ -61,7 +61,7 @@ struct navigation_validation_config /// Setters /// @{ - navigation_validation_config &name(const std::string n) { + navigation_validation_config &name(const std::string &n) { m_name = n; return *this; } @@ -74,12 +74,12 @@ struct navigation_validation_config m_white_board = std::move(w_board); return *this; } - navigation_validation_config &intersection_file(const std::string f) { - m_intersection_file = std::move(f); + navigation_validation_config &intersection_file(const std::string &f) { + m_intersection_file = f; return *this; } - navigation_validation_config &track_param_file(const std::string f) { - m_track_param_file = std::move(f); + navigation_validation_config &track_param_file(const std::string &f) { + m_track_param_file = f; return *this; } navigation_validation_config &n_tracks(std::size_t n) { diff --git a/tests/include/detray/test/cpu/detector_consistency.hpp b/tests/include/detray/test/cpu/detector_consistency.hpp index 20a9b382e..e37ef7505 100644 --- a/tests/include/detray/test/cpu/detector_consistency.hpp +++ b/tests/include/detray/test/cpu/detector_consistency.hpp @@ -34,7 +34,7 @@ struct consistency_check_config /// Setters /// @{ - consistency_check_config &name(const std::string n) { + consistency_check_config &name(const std::string &n) { m_name = n; return *this; } diff --git a/tests/include/detray/test/device/cuda/navigation_validation.hpp b/tests/include/detray/test/device/cuda/navigation_validation.hpp index 729277fb9..7a28ff474 100644 --- a/tests/include/detray/test/device/cuda/navigation_validation.hpp +++ b/tests/include/detray/test/device/cuda/navigation_validation.hpp @@ -262,8 +262,12 @@ class navigation_validation : public test::fixture_base<> { truth_intersection_traces); // Collect some statistics - std::size_t n_tracks{0u}, n_surfaces{0u}, n_miss_nav{0u}, - n_miss_truth{0u}, n_matching_error{0u}, n_fatal{0u}; + std::size_t n_tracks{0u}; + std::size_t n_surfaces{0u}; + std::size_t n_miss_nav{0u}; + std::size_t n_miss_truth{0u}; + std::size_t n_matching_error{0u}; + std::size_t n_fatal{0u}; std::vector>> missed_intersections{}; diff --git a/tests/include/detray/test/device/propagator_test.hpp b/tests/include/detray/test/device/propagator_test.hpp index 58b3cb2db..9a11c2691 100644 --- a/tests/include/detray/test/device/propagator_test.hpp +++ b/tests/include/detray/test/device/propagator_test.hpp @@ -123,7 +123,6 @@ inline auto run_propagation_host(vecmem::memory_resource *mr, rk_stepper_t::view_t>; using host_navigator_t = navigator_w_insp_t; - // using host_navigator_t = navigator_t; using propagator_host_t = propagator; diff --git a/tests/include/detray/test/utils/detectors/build_toy_detector.hpp b/tests/include/detray/test/utils/detectors/build_toy_detector.hpp index cee8e27d6..77cc5d0bd 100644 --- a/tests/include/detray/test/utils/detectors/build_toy_detector.hpp +++ b/tests/include/detray/test/utils/detectors/build_toy_detector.hpp @@ -264,48 +264,53 @@ struct toy_det_config { } constexpr bool do_check() const { return m_do_check; } /// @} -}; -/// Print the toy detector configuration -inline std::ostream &operator<<(std::ostream &out, const toy_det_config &cfg) { - out << "\nToy Detector\n" - << "----------------------------\n" - << " No. barrel layers : " << cfg.n_brl_layers() << "\n" - << " No. endcap layers : " << cfg.n_edc_layers() << "\n" - << " Portal envelope : " << cfg.envelope() << " [mm]\n"; + /// Print the toy detector configuration + friend std::ostream &operator<<(std::ostream &out, + const toy_det_config &cfg) { + out << "\nToy Detector\n" + << "----------------------------\n" + << " No. barrel layers : " << cfg.n_brl_layers() << "\n" + << " No. endcap layers : " << cfg.n_edc_layers() << "\n" + << " Portal envelope : " << cfg.envelope() << " [mm]\n"; - if (cfg.use_material_maps()) { - const auto &cyl_map_bins = cfg.cyl_map_bins(); - const auto &disc_map_bins = cfg.disc_map_bins(); - - out << " Material maps \n" - << " -> cyl. map bins : (phi: " << cyl_map_bins[0] - << ", z: " << cyl_map_bins[1] << ")\n" - << " -> disc map bins : (r: " << disc_map_bins[0] - << ", phi: " << disc_map_bins[1] << ")\n" - << " -> cyl. min. thickness: " - << cfg.cyl_material_map().thickness / detray::unit::mm - << " [mm]\n" - << " -> disc min. thickness: " - << cfg.disc_material_map().thickness / detray::unit::mm - << " [mm]\n" - << " -> Material : " << cfg.mapped_material() << "\n"; - } else { - out << " Homogeneous material \n" - << " -> Thickness : " - << cfg.module_mat_thickness() / detray::unit::mm << " [mm]\n" - << " -> Material : " << silicon_tml() << "\n"; - } + if (cfg.use_material_maps()) { + const auto &cyl_map_bins = cfg.cyl_map_bins(); + const auto &disc_map_bins = cfg.disc_map_bins(); + + out << " Material maps \n" + << " -> cyl. map bins : (phi: " << cyl_map_bins[0] + << ", z: " << cyl_map_bins[1] << ")\n" + << " -> disc map bins : (r: " << disc_map_bins[0] + << ", phi: " << disc_map_bins[1] << ")\n" + << " -> cyl. min. thickness: " + << cfg.cyl_material_map().thickness / detray::unit::mm + << " [mm]\n" + << " -> disc min. thickness: " + << cfg.disc_material_map().thickness / detray::unit::mm + << " [mm]\n" + << " -> Material : " << cfg.mapped_material() + << "\n"; + } else { + out << " Homogeneous material \n" + << " -> Thickness : " + << cfg.module_mat_thickness() / detray::unit::mm + << " [mm]\n" + << " -> Material : " << silicon_tml() + << "\n"; + } - return out; -} + return out; + } +}; namespace detail { // Helper type, used to define the r- or z-extent of detector volumes template struct extent2D { - scalar_t lower, upper; + scalar_t lower; + scalar_t upper; }; /// Helper method to decorate a volume builder with material diff --git a/tests/include/detray/test/utils/detectors/factories/endcap_generator.hpp b/tests/include/detray/test/utils/detectors/factories/endcap_generator.hpp index fa3eb78f1..16805e3f0 100644 --- a/tests/include/detray/test/utils/detectors/factories/endcap_generator.hpp +++ b/tests/include/detray/test/utils/detectors/factories/endcap_generator.hpp @@ -242,11 +242,10 @@ class endcap_generator final : public surface_factory_interface { // Generate the position in z (observe ring stagger) // Convention: inner ring is closer to origin const scalar_t center{m_cfg.center()}; - const scalar_t rz{ - radii.size() == 1u - ? center - : (ir % 2u ? center + 0.5f * m_cfg.ring_stagger() - : center - 0.5f * m_cfg.ring_stagger())}; + const scalar_t staggered_center{ + (ir % 2u ? center + 0.5f * m_cfg.ring_stagger() + : center - 0.5f * m_cfg.ring_stagger())}; + const scalar_t rz{radii.size() == 1u ? center : staggered_center}; // Generate the ring module positions (observe phi stagger) const scalar_t sub_stagger{m_cfg.phi_sub_stagger().size() > 1u diff --git a/tests/include/detray/test/utils/hash_tree.hpp b/tests/include/detray/test/utils/hash_tree.hpp index 48a4cff14..2a8deee14 100644 --- a/tests/include/detray/test/utils/hash_tree.hpp +++ b/tests/include/detray/test/utils/hash_tree.hpp @@ -57,14 +57,13 @@ requires std::is_invocable_v /// Default node in the hash tree. struct hashed_node { - hashed_node(hash_t hash) - : _key(hash), - _parent(detail::invalid_value()), - _left_child(detail::invalid_value()), - _right_child(detail::invalid_value()) {} + explicit hashed_node(hash_t hash) : _key(hash) {} hash_t _key; - dindex _parent, _left_child, _right_child; + dindex _parent{detail::invalid_value()}; + dindex _left_child{detail::invalid_value()}; + dindex _right_child{detail::invalid_value()}; + const hash_t &key() const { return _key; } hash_t &key() { return _key; } @@ -84,8 +83,7 @@ requires std::is_invocable_v /// @param volumes geometry volumes that become the graph nodes /// @param portals geometry portals link volumes and become edges hash_tree(const input_collection_t &data, - const hash_function_t & /*hf*/ = {}) - : _hash(hash_function_t{}) { + const hash_function_t & /*hf*/ = {}) { build(data); } @@ -98,7 +96,7 @@ requires std::is_invocable_v auto root() { return _tree.back().key(); } /// @returns the hash tree as a string - inline const std::string to_string() const { + inline std::string to_string() const { std::stringstream ss; for (const auto &n : _tree) { ss << n.key() << std::endl; @@ -171,7 +169,7 @@ requires std::is_invocable_v } /// How to encode tha node data - hash_function_t _hash; + hash_function_t _hash{hash_function_t{}}; /// Tree nodes vector_t _tree = {}; diff --git a/tests/include/detray/test/utils/inspectors.hpp b/tests/include/detray/test/utils/inspectors.hpp index d07a0d476..3a4cdd514 100644 --- a/tests/include/detray/test/utils/inspectors.hpp +++ b/tests/include/detray/test/utils/inspectors.hpp @@ -315,6 +315,8 @@ struct print_inspector { case e_on_portal: debug_stream << "status" << tabs << "on_portal" << std::endl; break; + default: + break; } debug_stream << "current object\t\t\t"; @@ -345,6 +347,8 @@ struct print_inspector { case e_full: debug_stream << "trust" << tabs << "full_trust" << std::endl; break; + default: + break; } debug_stream << std::endl; } @@ -415,6 +419,8 @@ struct print_inspector { case e_backward: debug_stream << "direction" << tabs << "backward" << std::endl; break; + default: + break; } auto pos = state().pos(); diff --git a/tests/include/detray/test/utils/planes_along_direction.hpp b/tests/include/detray/test/utils/planes_along_direction.hpp index e92160972..948ebaa13 100644 --- a/tests/include/detray/test/utils/planes_along_direction.hpp +++ b/tests/include/detray/test/utils/planes_along_direction.hpp @@ -18,11 +18,11 @@ namespace detray::test { -enum plane_mask_ids : unsigned int { +enum class plane_mask_ids : unsigned int { e_plane_rectangle2 = 0u, }; -enum plane_material_ids : unsigned int { +enum class plane_material_ids : unsigned int { e_plane_slab = 0u, }; diff --git a/tests/include/detray/test/utils/simulation/event_generator/random_numbers.hpp b/tests/include/detray/test/utils/simulation/event_generator/random_numbers.hpp index 299dfd137..ad7e747ed 100644 --- a/tests/include/detray/test/utils/simulation/event_generator/random_numbers.hpp +++ b/tests/include/detray/test/utils/simulation/event_generator/random_numbers.hpp @@ -54,7 +54,8 @@ struct random_numbers { DETRAY_HOST auto operator()(const std::array range = { -std::numeric_limits::max(), std::numeric_limits::max()}) { - const scalar_t min{range[0]}, max{range[1]}; + const scalar_t min{range[0]}; + const scalar_t max{range[1]}; assert(min <= max); // Uniform diff --git a/tests/include/detray/test/utils/simulation/event_generator/random_track_generator.hpp b/tests/include/detray/test/utils/simulation/event_generator/random_track_generator.hpp index 55891a3e3..7b8950541 100644 --- a/tests/include/detray/test/utils/simulation/event_generator/random_track_generator.hpp +++ b/tests/include/detray/test/utils/simulation/event_generator/random_track_generator.hpp @@ -78,12 +78,6 @@ class random_track_generator return rhs.m_tracks == m_tracks; } - /// @returns whether we reached the end of iteration - DETRAY_HOST_DEVICE - constexpr bool operator!=(const iterator& rhs) const { - return not(*this == rhs); - } - /// @returns the generator at its next position (prefix) DETRAY_HOST_DEVICE constexpr auto operator++() -> iterator& { diff --git a/tests/include/detray/test/utils/simulation/event_generator/random_track_generator_config.hpp b/tests/include/detray/test/utils/simulation/event_generator/random_track_generator_config.hpp index fbf1b9c7f..7d2482810 100644 --- a/tests/include/detray/test/utils/simulation/event_generator/random_track_generator_config.hpp +++ b/tests/include/detray/test/utils/simulation/event_generator/random_track_generator_config.hpp @@ -51,14 +51,15 @@ struct random_track_generator_config { bool m_is_pT{false}; /// Track origin - std::array m_origin{0.f, 0.f, 0.f}, - m_origin_stddev{0.f, 0.f, 0.f}; + std::array m_origin{0.f, 0.f, 0.f}; + std::array m_origin_stddev{0.f, 0.f, 0.f}; /// Randomly flip the charge sign? bool m_randomize_charge{false}; /// Time parameter and charge of the track - scalar m_time{0.f * unit::us}, m_charge{-1.f * unit::e}; + scalar m_time{0.f * unit::us}; + scalar m_charge{-1.f * unit::e}; /// Setters /// @{ @@ -228,56 +229,57 @@ struct random_track_generator_config { DETRAY_HOST_DEVICE constexpr scalar time() const { return m_time; } DETRAY_HOST_DEVICE constexpr scalar charge() const { return m_charge; } /// @} -}; -/// Print the random track generator configuration -DETRAY_HOST -inline std::ostream& operator<<(std::ostream& out, - const random_track_generator_config& cfg) { - const auto& ori = cfg.origin(); - const auto& mom_range = cfg.mom_range(); - const auto& phi_range = cfg.phi_range(); - const auto& theta_range = cfg.theta_range(); + /// Print the random track generator configuration + DETRAY_HOST + friend std::ostream& operator<<(std::ostream& out, + const random_track_generator_config& cfg) { + const auto& ori = cfg.origin(); + const auto& mom_range = cfg.mom_range(); + const auto& phi_range = cfg.phi_range(); + const auto& theta_range = cfg.theta_range(); - // General - out << "\nRandom track generator\n" - << "----------------------------\n" - << " No. tracks : " << cfg.n_tracks() << "\n" - << " Charge : " - << cfg.charge() / detray::unit::e << " [e]\n" - << " Rand. charge : " << std::boolalpha - << cfg.randomize_charge() << std::noboolalpha << "\n"; + // General + out << "\nRandom track generator\n" + << "----------------------------\n" + << " No. tracks : " << cfg.n_tracks() << "\n" + << " Charge : " + << cfg.charge() / detray::unit::e << " [e]\n" + << " Rand. charge : " << std::boolalpha + << cfg.randomize_charge() << std::noboolalpha << "\n"; - // Momentum and direction - if (cfg.is_pT()) { - out << " Transverse mom. : ["; - } else { - out << " Momentum : ["; - } - out << mom_range[0] / detray::unit::GeV << ", " - << mom_range[1] / detray::unit::GeV << ") [GeV]\n" - << " Phi range : [" - << phi_range[0] / detray::unit::rad << ", " - << phi_range[1] / detray::unit::rad << ") [rad]\n" - << " Theta range : [" - << theta_range[0] / detray::unit::rad << ", " - << theta_range[1] / detray::unit::rad << ") [rad]\n" - << " Origin : [" << ori[0] / detray::unit::mm - << ", " << ori[1] / detray::unit::mm << ", " - << ori[2] / detray::unit::mm << "] [mm]\n" - << " Do vertex smearing : " << std::boolalpha - << cfg.do_vertex_smearing() << "\n" - << std::noboolalpha; + // Momentum and direction + if (cfg.is_pT()) { + out << " Transverse mom. : ["; + } else { + out << " Momentum : ["; + } + out << mom_range[0] / detray::unit::GeV << ", " + << mom_range[1] / detray::unit::GeV << ") [GeV]\n" + << " Phi range : [" + << phi_range[0] / detray::unit::rad << ", " + << phi_range[1] / detray::unit::rad << ") [rad]\n" + << " Theta range : [" + << theta_range[0] / detray::unit::rad << ", " + << theta_range[1] / detray::unit::rad << ") [rad]\n" + << " Origin : [" + << ori[0] / detray::unit::mm << ", " + << ori[1] / detray::unit::mm << ", " + << ori[2] / detray::unit::mm << "] [mm]\n" + << " Do vertex smearing : " << std::boolalpha + << cfg.do_vertex_smearing() << "\n" + << std::noboolalpha; - if (cfg.do_vertex_smearing()) { - const auto& ori_stddev = cfg.origin_stddev(); - out << " Origin stddev : [" - << ori_stddev[0] / detray::unit::mm << ", " - << ori_stddev[1] / detray::unit::mm << ", " - << ori_stddev[2] / detray::unit::mm << "] [mm]\n"; - } + if (cfg.do_vertex_smearing()) { + const auto& ori_stddev = cfg.origin_stddev(); + out << " Origin stddev : [" + << ori_stddev[0] / detray::unit::mm << ", " + << ori_stddev[1] / detray::unit::mm << ", " + << ori_stddev[2] / detray::unit::mm << "] [mm]\n"; + } - return out; -} + return out; + } +}; } // namespace detray diff --git a/tests/include/detray/test/utils/simulation/event_generator/uniform_track_generator_config.hpp b/tests/include/detray/test/utils/simulation/event_generator/uniform_track_generator_config.hpp index ce9862ecd..c4bcbcd2a 100644 --- a/tests/include/detray/test/utils/simulation/event_generator/uniform_track_generator_config.hpp +++ b/tests/include/detray/test/utils/simulation/event_generator/uniform_track_generator_config.hpp @@ -213,56 +213,57 @@ struct uniform_track_generator_config { DETRAY_HOST_DEVICE constexpr scalar time() const { return m_time; } DETRAY_HOST_DEVICE constexpr scalar charge() const { return m_charge; } /// @} -}; -/// Print the unifrom track generator configuration -DETRAY_HOST -inline std::ostream& operator<<(std::ostream& out, - const uniform_track_generator_config& cfg) { - const auto& ori = cfg.origin(); - const auto& phi_range = cfg.phi_range(); + /// Print the unifrom track generator configuration + DETRAY_HOST + friend std::ostream& operator<<(std::ostream& out, + const uniform_track_generator_config& cfg) { + const auto& ori = cfg.origin(); + const auto& phi_range = cfg.phi_range(); - // General - out << "\nUnform track generator\n" - << "----------------------------\n" - << " No. tracks : " << cfg.n_tracks() << "\n" - << " -> phi steps : " << cfg.phi_steps() << "\n" - << " -> theta/eta steps : " << cfg.theta_steps() << "\n" - << " Charge : " - << cfg.charge() / detray::unit::e << " [e]\n" - << " Rand. charge : " << std::boolalpha - << cfg.randomize_charge() << std::noboolalpha << "\n"; + // General + out << "\nUnform track generator\n" + << "----------------------------\n" + << " No. tracks : " << cfg.n_tracks() << "\n" + << " -> phi steps : " << cfg.phi_steps() << "\n" + << " -> theta/eta steps : " << cfg.theta_steps() << "\n" + << " Charge : " + << cfg.charge() / detray::unit::e << " [e]\n" + << " Rand. charge : " << std::boolalpha + << cfg.randomize_charge() << std::noboolalpha << "\n"; - // Momentum - if (cfg.is_pT()) { - out << " Transverse mom. : " - << cfg.m_p_mag / detray::unit::GeV << " [GeV]\n"; - } else { - out << " Momentum : " - << cfg.m_p_mag / detray::unit::GeV << " [GeV]\n"; - } + // Momentum + if (cfg.is_pT()) { + out << " Transverse mom. : " + << cfg.m_p_mag / detray::unit::GeV << " [GeV]\n"; + } else { + out << " Momentum : " + << cfg.m_p_mag / detray::unit::GeV << " [GeV]\n"; + } - // Direction - out << " Phi range : [" - << phi_range[0] / detray::unit::rad << ", " - << phi_range[1] / detray::unit::rad << ") [rad]\n"; - if (cfg.uniform_eta()) { - const auto& eta_range = cfg.eta_range(); - out << " Eta range : [" << eta_range[0] << ", " - << eta_range[1] << "]\n"; - } else { - const auto& theta_range = cfg.theta_range(); - out << " Theta range : [" - << theta_range[0] / detray::unit::rad << ", " - << theta_range[1] / detray::unit::rad << ") [rad]\n"; - } + // Direction + out << " Phi range : [" + << phi_range[0] / detray::unit::rad << ", " + << phi_range[1] / detray::unit::rad << ") [rad]\n"; + if (cfg.uniform_eta()) { + const auto& eta_range = cfg.eta_range(); + out << " Eta range : [" << eta_range[0] << ", " + << eta_range[1] << "]\n"; + } else { + const auto& theta_range = cfg.theta_range(); + out << " Theta range : [" + << theta_range[0] / detray::unit::rad << ", " + << theta_range[1] / detray::unit::rad << ") [rad]\n"; + } - // Origin - out << " Origin : [" << ori[0] / detray::unit::mm - << ", " << ori[1] / detray::unit::mm << ", " - << ori[2] / detray::unit::mm << "] [mm]\n"; + // Origin + out << " Origin : [" + << ori[0] / detray::unit::mm << ", " + << ori[1] / detray::unit::mm << ", " + << ori[2] / detray::unit::mm << "] [mm]\n"; - return out; -} + return out; + } +}; } // namespace detray diff --git a/tests/include/detray/test/utils/simulation/landau_distribution.hpp b/tests/include/detray/test/utils/simulation/landau_distribution.hpp index 5388e97c2..ee6d1c498 100644 --- a/tests/include/detray/test/utils/simulation/landau_distribution.hpp +++ b/tests/include/detray/test/utils/simulation/landau_distribution.hpp @@ -53,7 +53,7 @@ class landau_distribution { private: scalar_type quantile(const scalar_type z) const { - static const double f[982] = { + static const std::array f{ 0., 0., 0., 0., 0., -2.244733, -2.204365, -2.168163, -2.135219, -2.104898, -2.076740, -2.050397, -2.025605, -2.002150, -1.979866, -1.958612, -1.938275, -1.918760, @@ -220,25 +220,29 @@ class landau_distribution { 51.005773, 53.437996, 56.123356, 59.103894}; if (z <= 0) { - // Is using max OK? + // @TODO: Is using max OK? return -std::numeric_limits::max(); } if (z >= 1) { return std::numeric_limits::max(); } - double ranlan = 0., u = 0., v = 0.; + double ranlan = 0.; + double u = 0.; + double v = 0.; u = 1000. * z; - int i = static_cast(u); - u -= static_cast(i); - if (i >= 70 && i < 800) { + auto k = static_cast(u); + u -= static_cast(k); + if (k >= 70 && k < 800) { + auto i{static_cast(k)}; ranlan = f[i - 1] + u * (f[i] - f[i - 1]); - } else if (i >= 7 && i <= 980) { + } else if (k >= 7 && k <= 980) { + auto i{static_cast(k)}; ranlan = f[i - 1] + u * (f[i] - f[i - 1] - 0.25 * (1 - u) * (f[i + 1] - f[i] - f[i - 1] + f[i - 2])); - } else if (i < 7) { + } else if (k < 7) { v = math::log(z); u = 1 / v; ranlan = ((0.99858950 + (3.45213058E1 + 1.70854528E1 * u) * u) / diff --git a/tests/include/detray/test/utils/simulation/random_scatterer.hpp b/tests/include/detray/test/utils/simulation/random_scatterer.hpp index bb272430a..592b30863 100644 --- a/tests/include/detray/test/utils/simulation/random_scatterer.hpp +++ b/tests/include/detray/test/utils/simulation/random_scatterer.hpp @@ -216,7 +216,6 @@ struct random_scatterer : actor { const vector3_type& dir, const scalar_type projected_scattering_angle, generator_t& generator) const { - // Scattering angle = sqrt(2) * projected_scattering_angle const auto scattering_angle = constant::sqrt2 * projected_scattering_angle; diff --git a/tests/include/detray/test/validation/detector_scan_utils.hpp b/tests/include/detray/test/validation/detector_scan_utils.hpp index a80067a7e..90da9af62 100644 --- a/tests/include/detray/test/validation/detector_scan_utils.hpp +++ b/tests/include/detray/test/validation/detector_scan_utils.hpp @@ -96,11 +96,12 @@ inline bool check_connectivity( std::function get_connected_record; if constexpr (check_sorted_trace) { // Get the next record - get_connected_record = [&](index_t next) -> records_iterator_t { - auto rec = trace.begin() + next; + get_connected_record = + [&trace, ¤t_volume](index_t next) -> records_iterator_t { // Make sure that the record contains the volume that is currently // being checked for connectivity - if (rec != trace.end() && + if (auto rec = trace.begin() + next; + rec != trace.end() && ((std::get<1>(rec->first) == current_volume) || (std::get<1>(rec->second) == current_volume))) { return rec; @@ -109,8 +110,9 @@ inline bool check_connectivity( }; } else { // Search for the existence of a fitting record over the entire trace - get_connected_record = [&](index_t /*next*/) -> records_iterator_t { - return find_if( + get_connected_record = + [&trace, ¤t_volume](index_t /*next*/) -> records_iterator_t { + return std::ranges::find_if( trace.begin(), trace.end(), [&](const std::pair &rec) -> bool { return (std::get<1>(rec.first) == current_volume) || @@ -165,8 +167,7 @@ inline bool check_connectivity( err_stream << record_stream.str(); err_stream << "\nPairs left to match:" << std::endl; - for (std::size_t j = static_cast(i); j < trace.size(); - ++j) { + for (auto j = static_cast(i); j < trace.size(); ++j) { auto first_vol = std::get<1>(trace[j].first); auto second_vol = std::get<1>(trace[j].second); diff --git a/tests/include/detray/test/validation/navigation_validation_utils.hpp b/tests/include/detray/test/validation/navigation_validation_utils.hpp index 2c0171720..33403beb6 100644 --- a/tests/include/detray/test/validation/navigation_validation_utils.hpp +++ b/tests/include/detray/test/validation/navigation_validation_utils.hpp @@ -125,7 +125,8 @@ auto compare_traces(truth_trace_t &truth_trace, using truth_record_t = typename truth_trace_t::value_type; using intersection_t = typename truth_record_t::intersection_type; - std::stringstream debug_stream, matching_stream; + std::stringstream debug_stream; + std::stringstream matching_stream; std::size_t n_inters_nav{recorded_trace.size()}; std::size_t max_entries{math::max(n_inters_nav, truth_trace.size())}; std::size_t min_entries{math::min(n_inters_nav, truth_trace.size())}; diff --git a/tests/integration_tests/cpu/builders/grid_builder.cpp b/tests/integration_tests/cpu/builders/grid_builder.cpp index 383bbd6de..0349ad69a 100644 --- a/tests/integration_tests/cpu/builders/grid_builder.cpp +++ b/tests/integration_tests/cpu/builders/grid_builder.cpp @@ -76,7 +76,8 @@ GTEST_TEST(detray_builders, decorator_grid_builder) { // The cylinder portals are at the end of the surface range by construction const auto cyl_mask = mask{0u, 10.f, -500.f, 500.f}; - std::size_t n_phi_bins{5u}, n_z_bins{4u}; + std::size_t n_phi_bins{5u}; + std::size_t n_z_bins{4u}; // Build empty grid gbuilder.init_grid(cyl_mask, {n_phi_bins, n_z_bins}); diff --git a/tests/integration_tests/cpu/builders/material_map_builder.cpp b/tests/integration_tests/cpu/builders/material_map_builder.cpp index 0c11de477..c5937be2b 100644 --- a/tests/integration_tests/cpu/builders/material_map_builder.cpp +++ b/tests/integration_tests/cpu/builders/material_map_builder.cpp @@ -199,7 +199,9 @@ GTEST_TEST(detray_builders, decorator_material_map_builder) { EXPECT_EQ(d.material_store().template size(), 3u); // Check the material links - std::size_t pt_cyl_idx{0u}, cyl_idx{0u}, cart_idx{0u}; + std::size_t pt_cyl_idx{0u}; + std::size_t cyl_idx{0u}; + std::size_t cart_idx{0u}; for (auto& sf_desc : d.surfaces()) { const auto& mat_link = sf_desc.material(); switch (mat_link.id()) { diff --git a/tests/integration_tests/cpu/material/material_interaction.cpp b/tests/integration_tests/cpu/material/material_interaction.cpp index b9ef2823e..fff5e6b77 100644 --- a/tests/integration_tests/cpu/material/material_interaction.cpp +++ b/tests/integration_tests/cpu/material/material_interaction.cpp @@ -203,7 +203,6 @@ GTEST_TEST(detray_material, telescope_geometry_energy_loss) { // Terminate the propagation if the next sensitive surface was not found if (!next_surface_aborter_state.success) { - // if (alt_state._navigation.is_complete()){ const scalar altP = alt_state._stepping.bound_params().p(ptc.charge()); altE = std::hypot(altP, mass); diff --git a/tests/integration_tests/cpu/propagator/covariance_transport.cpp b/tests/integration_tests/cpu/propagator/covariance_transport.cpp index a5575c264..6badeb32c 100644 --- a/tests/integration_tests/cpu/propagator/covariance_transport.cpp +++ b/tests/integration_tests/cpu/propagator/covariance_transport.cpp @@ -255,12 +255,12 @@ class detray_propagation_HelixCovarianceTransportValidation return ret; } - const intersection_t get_intersection( + intersection_t get_intersection( const std::array& inters) const { return inters[0]; } - const intersection_t get_intersection(const intersection_t& inters) const { + intersection_t get_intersection(const intersection_t& inters) const { return inters; } }; diff --git a/tests/integration_tests/cpu/propagator/propagator.cpp b/tests/integration_tests/cpu/propagator/propagator.cpp index 316790076..2a0cb2d10 100644 --- a/tests/integration_tests/cpu/propagator/propagator.cpp +++ b/tests/integration_tests/cpu/propagator/propagator.cpp @@ -164,7 +164,8 @@ class PropagatorWithRkStepper } /// Clean up - virtual void TearDown() {} + virtual void TearDown() { /* Do nothing */ + } protected: /// Detector configuration @@ -177,7 +178,8 @@ class PropagatorWithRkStepper generator_t::configuration trk_gen_cfg{}; /// Stepper configuration - scalar_t overstep_tol, step_constr; + scalar_t overstep_tol; + scalar_t step_constr; }; /// Test propagation in a constant magnetic field using a Runge-Kutta stepper diff --git a/tests/integration_tests/io/io_json_detector_roundtrip.cpp b/tests/integration_tests/io/io_json_detector_roundtrip.cpp index e074e4ef6..1f688ebed 100644 --- a/tests/integration_tests/io/io_json_detector_roundtrip.cpp +++ b/tests/integration_tests/io/io_json_detector_roundtrip.cpp @@ -46,7 +46,8 @@ bool compare_files(const std::string& file_name1, const std::string& file_name2, auto file2 = io::file_handle(file_name2, std::ios_base::in | std::ios_base::binary); - std::string line1, line2; + std::string line1; + std::string line2; // Check files line by line std::size_t i{1u}; @@ -82,10 +83,10 @@ bool compare_files(const std::string& file_name1, const std::string& file_name2, /// Full IO round trip for a given detector /// @returns a detector read back in from the writter files template -auto test_detector_json_io(const detector_t& det, - const typename detector_t::name_map& names, - std::map& file_names, - vecmem::host_memory_resource& host_mr) { +auto test_detector_json_io( + const detector_t& det, const typename detector_t::name_map& names, + std::map>& file_names, + vecmem::host_memory_resource& host_mr) { auto writer_cfg = io::detector_writer_config{} .format(io::format::json) @@ -159,7 +160,7 @@ GTEST_TEST(io, json_telescope_detector_reader) { vecmem::host_memory_resource host_mr; auto [tel_det, tel_names] = build_telescope_detector(host_mr, tel_cfg); - std::map file_names; + std::map> file_names; file_names["geometry"] = "telescope_detector_geometry.json"; file_names["homogeneous_material"] = "telescope_detector_homogeneous_material.json"; @@ -238,7 +239,7 @@ GTEST_TEST(io, json_toy_detector_roundtrip_homogeneous_material) { toy_cfg.use_material_maps(false); const auto [toy_det, toy_names] = build_toy_detector(host_mr, toy_cfg); - std::map file_names; + std::map> file_names; file_names["geometry"] = "toy_detector_geometry.json"; file_names["homogeneous_material"] = "toy_detector_homogeneous_material.json"; @@ -264,7 +265,7 @@ GTEST_TEST(io, json_toy_detector_roundtrip_material_maps) { toy_cfg.use_material_maps(true); const auto [toy_det, toy_names] = build_toy_detector(host_mr, toy_cfg); - std::map file_names; + std::map> file_names; file_names["geometry"] = "toy_detector_geometry.json"; file_names["homogeneous_material"] = "toy_detector_homogeneous_material.json"; @@ -286,7 +287,7 @@ GTEST_TEST(io, json_wire_chamber_reader) { wire_chamber_config<> wire_cfg{}; auto [wire_det, wire_names] = build_wire_chamber(host_mr, wire_cfg); - std::map file_names; + std::map> file_names; file_names["geometry"] = "wire_chamber_geometry.json"; file_names["homogeneous_material"] = "wire_chamber_homogeneous_material.json"; diff --git a/tests/tools/python/file_checker.py b/tests/tools/python/file_checker.py index 43dd86c0e..2458d2bdf 100644 --- a/tests/tools/python/file_checker.py +++ b/tests/tools/python/file_checker.py @@ -1,16 +1,16 @@ -# Detray library, part of the ACTS project (R&D line) +#Detray library, part of the ACTS project(R& D line) # -# (c) 2023 CERN for the benefit of the ACTS project +#(c) 2023 CERN for the benefit of the ACTS project # -# Mozilla Public License Version 2.0 +#Mozilla Public License Version 2.0 -# detray json schema definitions +#detray json schema definitions from json_schema import geometry_schema from json_schema import homogeneous_material_schema from json_schema import material_map_schema from json_schema import surface_grid_schema -# python includes +#python includes import argparse import json import os @@ -18,7 +18,7 @@ from jsonschema import validate def __main__(): -#----------------------------------------------------------------arg parsing +#-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- arg parsing parser = argparse.ArgumentParser(description = "Detray File Validation") @@ -37,11 +37,11 @@ def __main__(): args = parser.parse_args() - # Check input json files +#Check input json files filename_dict = {} geo_file = args.geometry_file - if not geo_file == "": + if geo_file != "": if not os.path.isfile(geo_file): print(f"Geometry file does not exist! ({geo_file})") sys.exit(1) @@ -49,7 +49,7 @@ def __main__(): filename_dict[geo_file] = geometry_schema hom_mat_file = args.homogeneous_material_file - if not hom_mat_file == "": + if hom_mat_file != "": if not os.path.isfile(hom_mat_file): print(f"Homogeneous material file does not exist! ({hom_mat_file})") sys.exit(1) @@ -57,7 +57,7 @@ def __main__(): filename_dict[hom_mat_file] = homogeneous_material_schema mat_map_file = args.material_map_file - if not mat_map_file == "": + if mat_map_file != "": if not os.path.isfile(mat_map_file): print(f"Material map file does not exist! ({mat_map_file})") sys.exit(1) @@ -65,28 +65,25 @@ def __main__(): filename_dict[mat_map_file] = material_map_schema grid_file = args.grid_file - if not grid_file == "": + if grid_file != "": if not os.path.isfile(grid_file): print(f"Surface grid file does not exist! ({grid_file})") sys.exit(1) else: filename_dict[grid_file] = surface_grid_schema -#------------------------------------------------------------------------run +#-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- run for filename, schema in filename_dict.items(): with open(filename) as file: try: - input_json = json.load(file) - except json.decoder.JSONDecodeError: - print(f"Invalid json file: {filename}") - else: - validate(instance=input_json, schema=schema) - print(f"{filename}: OK") + input_json += json.load(file) except json.decoder.JSONDecodeError + : print(f "Invalid json file: {filename}") else + : validate(instance = input_json, schema = schema) print(f "{filename}: OK") -#------------------------------------------------------------------------------- +#-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - -if __name__ == "__main__": - __main__() + if __name__ == "__main__" : __main__() -#------------------------------------------------------------------------------- +#-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - diff --git a/tests/tools/python/impl/plot_material_scan.py b/tests/tools/python/impl/plot_material_scan.py index 16ca57ea5..d3fb02b6e 100644 --- a/tests/tools/python/impl/plot_material_scan.py +++ b/tests/tools/python/impl/plot_material_scan.py @@ -1,306 +1,174 @@ -# Detray library, part of the ACTS project (R&D line) +#Detray library, part of the ACTS project(R& D line) # -# (c) 2023-2024 CERN for the benefit of the ACTS project +#(c) 2023 - 2024 CERN for the benefit of the ACTS project # -# Mozilla Public License Version 2.0 +#Mozilla Public License Version 2.0 -# detray includes +#detray includes import plotting -# python includes -import math -import numpy as np -import os -import pandas as pd - - -""" Read the material scan data from file and prepare data frame """ -def read_material_data(inputdir, logging, det_name, read_cuda): - - # Input data directory - data_dir = os.fsencode(inputdir) - - detector_name = "default_detector" - material_scan_file = cpu_material_trace_file = cuda_material_trace_file = "" - - # Find the data files by naming convention - for file in os.listdir(data_dir): - filename = os.fsdecode(file) - - if filename.find(det_name + '_material_scan') != -1: - material_scan_file = inputdir + "/" + filename - elif filename.find(det_name + '_cpu_navigation_material_trace') != -1: - cpu_material_trace_file = inputdir + "/" + filename - elif read_cuda and filename.find(det_name + '_cuda_navigation_material_trace') != -1: - cuda_material_trace_file = inputdir + "/" + filename - - df_scan = pd.read_csv(material_scan_file, - float_precision='round_trip') - df_cpu_trace = pd.read_csv(cpu_material_trace_file, - float_precision='round_trip') - df_cuda_trace = pd.DataFrame({}) - if read_cuda: - df_cuda_trace = pd.read_csv(cuda_material_trace_file, - float_precision='round_trip') - - return df_scan, df_cpu_trace, df_cuda_trace - - -""" Calculate edges of bins to plot the mateiral data """ -def get_n_bins(df): - # Find the number of ray directions - row_count = df.groupby(df['eta']).count() - yBins = row_count['phi'].max() - xBins = int(len(df['eta']) / yBins) - assert len(df['eta']) == xBins * yBins, "Could not infer the number of rays correctly" - - # Get the axis spacing - x_range = np.max(df['eta']) - np.min(df['eta']) - xBinning = np.linspace(np.min(df['eta']) - 0.5 * x_range/xBins, np.max(df['eta']) + 0.5 * x_range/xBins, xBins + 1) - - y_range = np.max(df['phi']) - np.min(df['phi']) - yBinning = np.linspace(np.min(df['phi']) - 0.5 * y_range/yBins, np.max(df['phi']) + 0.5 * y_range/yBins, yBins + 1) - - return xBinning, yBinning - - -""" Calculate the binwise errors: Standard Error on the Mean """ -def get_errors(df, n, name): - # Number of entries per bin - errors = [] - # Iterate over data per bin - for i in range(0, n): - # Project the next n rows of the data frame (the bin content is the - # mean of the material along phi) - bin_data = df.iloc[i * n:(i + 1) * n] - # Caluculate the error on the mean: stddev/sqrt(n) - errors.append(np.std(bin_data[name], axis=0) / math.sqrt(n)) - - return errors - - -""" Plot the material thickenss vs phi and eta in units of X_0 """ -def X0_vs_eta_phi(df, label, detector, plotFactory, out_format = "pdf"): - - # Histogram bin edges - xBinning, yBinning = get_n_bins(df) - - # Plot the thickness of every material slab in units of X_0 - hist_data = plotFactory.hist2D( - x = df["eta"], - y = df["phi"], - z = df['mat_tX0'], - label = detector, - xLabel = r'$\eta$', - yLabel = r'$\phi\,\mathrm{[rad]}$', - zLabel = r'thickness / $X_0$', - xBins = xBinning, yBins = yBinning, - figsize = (9, 7), - showStats = False) - - plotFactory.write_plot(hist_data, detector + "_" + label + "_t_X0_map", out_format) - - # Plot path length through material of the respective ray in units of X_0 - hist_data = plotFactory.hist2D( - x = df["eta"], - y = df["phi"], - z = df['mat_sX0'], - label = detector, - xLabel = r'$\eta$', - yLabel = r'$\phi\,\mathrm{[rad]}$', - zLabel = r'path length / $X_0$', - xBins = xBinning, yBins = yBinning, - figsize = (9, 7), - showStats = False) - - plotFactory.write_plot(hist_data, detector + "_" + label + "_s_X0_map", out_format) - - -""" Plot the material thickenss vs phi and eta in units of L_0 """ -def L0_vs_eta_phi(df, label, detector, plotFactory, out_format = "pdf"): - - # Histogram bin edges - xBinning, yBinning = get_n_bins(df) - - # Plot the thickness of every material slab in units of L_0 - hist_data = plotFactory.hist2D( - x = df["eta"], - y = df["phi"], - z = df['mat_tL0'], - label = detector, - xLabel = r'$\eta$', - yLabel = r'$\phi\,\mathrm{[rad]}$', - zLabel = r'thickness / $\Lambda_0$', - xBins = xBinning, yBins = yBinning, - figsize = (9, 7), - showStats = False) - - plotFactory.write_plot(hist_data, detector + "_" + label + "_t_L0_map", out_format) - - # Plot path length through material of the respective ray in units of L_0 - hist_data = plotFactory.hist2D( - x = df["eta"], - y = df["phi"], - z = df['mat_sL0'], - label = detector, - xLabel = r'$\eta$', - yLabel = r'$\phi\,\mathrm{[rad]}$', - zLabel = r'path length / $\Lambda_0$', - xBins = xBinning, yBins = yBinning, - figsize = (9, 7), - showStats = False) - - plotFactory.write_plot(hist_data, detector + "_" + label + "_s_L0_map", out_format) - - -""" Plot the material thickness in units of X_0 vs eta """ -def X0_vs_eta(df, label, detector, plotFactory, out_format = "pdf"): - # Where to place the legend box - box_anchor_x = 1.02 - box_anchor_y = 1.145 - - # Histogram bin edges - xBinning, yBinning = get_n_bins(df) - lgd_ops = plotting.get_legend_options() - lgd_ops._replace(loc = 'upper center') - - # Same number of entries in every bin as per uniform ray scan - n_phi = len(yBinning) - 1 - - hist_data = plotFactory.hist1D( - x = df['eta'], - w = df['mat_tX0'] / n_phi, - errors = get_errors(df, n_phi, 'mat_tX0'), - normalize = False, - label = rf'{detector}', - xLabel = r'$\eta$', - yLabel = r'thickness / $X_0$', - bins = xBinning, - showStats = False, - figsize = (9, 7), - lgd_ops = lgd_ops) - - # Move the legend ouside plot - hist_data.lgd.set_bbox_to_anchor((box_anchor_x, box_anchor_y)) - - plotFactory.write_plot(hist_data, detector + "_" + label + "_t_X0", out_format) - - hist_data = plotFactory.hist1D( - x = df['eta'], - w = df['mat_sX0'] / n_phi, - errors = get_errors(df, n_phi, 'mat_sX0'), - normalize = False, - label = rf'{detector}', - xLabel = r'$\eta$', - yLabel = r'path length / $X_0$', - bins = xBinning, - showStats = False, - figsize = (9, 7), - lgd_ops = lgd_ops) - - # Move the legend ouside plot - hist_data.lgd.set_bbox_to_anchor((box_anchor_x, box_anchor_y)) - - plotFactory.write_plot(hist_data, detector + "_" + label + "_s_X0", out_format) - - -""" Plot the material thickness in units of L_0 vs eta """ -def L0_vs_eta(df, label, detector, plotFactory, out_format = "pdf"): - # Where to place the legend box - box_anchor_x = 1.02 - box_anchor_y = 1.145 - - # Histogram bin edges - xBinning, yBinning = get_n_bins(df) - lgd_ops = plotting.get_legend_options() - lgd_ops._replace(loc = 'upper center') - - # Same number of entries in every bin as per uniform ray scan - n_phi = len(yBinning) - 1 - - hist_data = plotFactory.hist1D( - x = df['eta'], - w = df['mat_tL0'] / n_phi, - errors = get_errors(df, n_phi, 'mat_tL0'), - normalize = False, - label = rf'{detector}', - xLabel = r'$\eta$', - yLabel = r'thickness / $\Lambda_0$', - bins = xBinning, - showStats = False, - figsize = (9, 7), - lgd_ops = lgd_ops) - - # Move the legend ouside plot - hist_data.lgd.set_bbox_to_anchor((box_anchor_x, box_anchor_y)) - - plotFactory.write_plot(hist_data, detector + "_" + label + "_t_L0", out_format) - - hist_data = plotFactory.hist1D( - x = df['eta'], - w = df['mat_sL0'] / n_phi, - errors = get_errors(df, n_phi, 'mat_sL0'), - normalize = False, - label = rf'{detector}', - xLabel = r'$\eta$', - yLabel = r'path length / $\Lambda_0$', - bins = xBinning, - showStats = False, - figsize = (9, 7), - lgd_ops = lgd_ops) - - # Move the legend ouside plot - hist_data.lgd.set_bbox_to_anchor((box_anchor_x, box_anchor_y)) - - plotFactory.write_plot(hist_data, detector + "_" + label + "_s_L0", out_format) - - -""" Compare two material distributions """ -def compare_mat(df_truth, df_rec, label, detector, plotFactory, out_format = "pdf"): - # Where to place the legend box - box_anchor_x = 1.02 - box_anchor_y = 1.29 - - # Histogram bin edges - xBinning, yBinning = get_n_bins(df_truth) - lgd_ops = plotting.get_legend_options() - lgd_ops._replace(loc = 'upper center') - - # Same number of entries in every bin as per uniform ray scan - n_phi = len(yBinning) - 1 - - truth_data = plotFactory.hist1D( - x = df_truth['eta'], - w = df_truth['mat_sX0'] / n_phi, - errors = get_errors(df_truth, n_phi, 'mat_sX0'), - normalize = False, - label = rf'{detector}: scan', - xLabel = r'$\eta$', - yLabel = r'path length / $X_0$', - bins = xBinning, - showStats = False, - figsize = (10, 10), - layout = 'tight', - lgd_ops = lgd_ops) - - # Move the legend ouside plot - truth_data.lgd.set_bbox_to_anchor((box_anchor_x, box_anchor_y)) - - # Add recorded data for comparison - rec_data = plotFactory.add_plot( - oldHist = truth_data, - x = df_rec['eta'].to_numpy(dtype = np.double), - w = df_rec['mat_sX0'] / n_phi, - errors = get_errors(df_rec, n_phi, 'mat_sX0'), - normalize = False, - label = rf'{detector}: navigator') - - # Add a ratio plot to hist_data - ratio_data = plotFactory.add_ratio( - nom = truth_data, - denom = rec_data, - label = 'scan/navigation', - setLog = False, - showErrors = True) - - plotFactory.write_plot(ratio_data, detector + "_" + label + "_comparison_s_X0", out_format) +#python includes + import math import numpy as np import os import pandas as pd + +#Common plot labels + label_eta = r '$\eta$' label_phi = r '$\phi\,\mathrm{[rad]}$' label_thickness_x0 = r 'thickness / $X_0$' label_path_x0 = r 'path length / $X_0$' label_thickness_l0 = r 'thickness / $\Lambda_0$' label_path_l0 = r 'path length / $\Lambda_0$' + +#Common options + ldg_loc = 'upper center' + + "" + " Read the material scan data from file and prepare data frame " + "" def read_material_data(inputdir, logging, det_name, read_cuda) : + +#Input data directory + data_dir = os.fsencode(inputdir) + + material_scan_file = cpu_material_trace_file = cuda_material_trace_file = "" + +#Find the data files by naming convention + for file in os.listdir(data_dir) : filename = os.fsdecode(file) + + if filename.find(det_name + '_material_scan') != - 1 : material_scan_file = inputdir + "/" + filename elif filename.find(det_name + '_cpu_navigation_material_trace') != - 1 : cpu_material_trace_file = inputdir + "/" + filename elif read_cuda and filename.find(det_name + '_cuda_navigation_material_trace') != - 1 : cuda_material_trace_file = inputdir + "/" + filename + + df_scan = pd.read_csv(material_scan_file, float_precision = 'round_trip') df_cpu_trace = pd.read_csv(cpu_material_trace_file, float_precision = 'round_trip') df_cuda_trace = pd.DataFrame({}) if read_cuda : df_cuda_trace = pd.read_csv(cuda_material_trace_file, float_precision = 'round_trip') + + return df_scan, df_cpu_trace, df_cuda_trace + + "" + " Calculate edges of bins to plot the mateiral data " + "" def get_n_bins(df) : +#Find the number of ray directions + row_count = df.groupby(df['eta']).count() y_bins = row_count['phi'].max() x_bins = int(len(df['eta']) / y_bins) assert len(df['eta']) == x_bins * y_bins, "Could not infer the number of rays correctly" + +#Get the axis spacing + x_range = np.max(df['eta']) - np.min(df['eta']) x_binning = np.linspace(np.min(df['eta']) - 0.5 * x_range / x_bins, np.max(df['eta']) + 0.5 * x_range / x_bins, x_bins + 1) + + y_range = np.max(df['phi']) - np.min(df['phi']) y_binning = np.linspace(np.min(df['phi']) - 0.5 * y_range / y_bins, np.max(df['phi']) + 0.5 * y_range / y_bins, y_bins + 1) + + return x_binning, y_binning + + "" + " Calculate the binwise errors: Standard Error on the Mean " + "" def get_errors(df, n, name) : +#Number of entries per bin + errors =[] +#Iterate over data per bin + for i in range(0, n) : +#Project the next n rows of the data frame(the bin content is the +#mean of the material along phi) + bin_data = df.iloc[i * n : (i + 1) * n] +#Caluculate the error on the mean : stddev / sqrt(n) + errors.append(np.std(bin_data[name], axis = 0) / math.sqrt(n)) + + return errors + + "" + " Plot the material thickenss vs phi and eta in units of X_0 " + "" def X0_vs_eta_phi(df, label, detector, plot_factory, out_format = "pdf") : + +#Histogram bin edges + x_binning, y_binning = get_n_bins(df) + +#Plot the thickness of every material slab in units of X_0 + hist_data = plot_factory.hist2D(x = df["eta"], y = df["phi"], z = df['mat_tX0'], label = detector, x_label = label_eta, y_label = label_phi, z_label = label_thickness_x0, xBins = x_binning, yBins = y_binning, figsize =(9, 7), show_stats = False) + + plot_factory.write_plot(hist_data, detector + "_" + label + "_t_X0_map", out_format) + +#Plot path length through material of the respective ray in units of X_0 + hist_data = plot_factory.hist2D(x = df["eta"], y = df["phi"], z = df['mat_sX0'], label = detector, x_label = label_eta, y_label = label_phi, z_label = label_path_x0, xBins = x_binning, yBins = y_binning, figsize =(9, 7), show_stats = False) + + plot_factory.write_plot(hist_data, detector + "_" + label + "_s_X0_map", out_format) + + "" + " Plot the material thickenss vs phi and eta in units of L_0 " + "" def L0_vs_eta_phi(df, label, detector, plot_factory, out_format = "pdf") : + +#Histogram bin edges + x_binning, y_binning = get_n_bins(df) + +#Plot the thickness of every material slab in units of L_0 + hist_data = plot_factory.hist2D(x = df["eta"], y = df["phi"], z = df['mat_tL0'], label = detector, x_label = label_eta, y_label = label_phi, z_label = label_thickness_l0, xBins = x_binning, yBins = y_binning, figsize =(9, 7), show_stats = False) + + plot_factory.write_plot(hist_data, detector + "_" + label + "_t_L0_map", out_format) + +#Plot path length through material of the respective ray in units of L_0 + hist_data = plot_factory.hist2D(x = df["eta"], y = df["phi"], z = df['mat_sL0'], label = detector, x_label = label_eta, y_label = label_phi, z_label = label_path_l0, xBins = x_binning, yBins = y_binning, figsize =(9, 7), show_stats = False) + + plot_factory.write_plot(hist_data, detector + "_" + label + "_s_L0_map", out_format) + + "" + " Plot the material thickness in units of X_0 vs eta " + "" def X0_vs_eta(df, label, detector, plot_factory, out_format = "pdf") : +#Where to place the legend box + box_anchor_x = 1.02 box_anchor_y = 1.145 + +#Histogram bin edges + x_binning, y_binning = get_n_bins(df) lgd_ops = plotting.get_legend_options() lgd_ops._replace(loc = ldg_loc) + +#Same number of entries in every bin as per uniform ray scan + n_phi = len(y_binning) - 1 + + hist_data = plot_factory.hist1D(x = df['eta'], w = df['mat_tX0'] / n_phi, errors = get_errors(df, n_phi, 'mat_tX0'), normalize = False, label = rf '{detector}', x_label = label_eta, y_label = label_thickness_x0, bins = x_binning, show_stats = False, figsize =(9, 7), lgd_ops = lgd_ops) + +#Move the legend ouside plot + hist_data.lgd.set_bbox_to_anchor((box_anchor_x, box_anchor_y)) + + plot_factory.write_plot(hist_data, detector + "_" + label + "_t_X0", out_format) + + hist_data = plot_factory.hist1D(x = df['eta'], w = df['mat_sX0'] / n_phi, errors = get_errors(df, n_phi, 'mat_sX0'), normalize = False, label = rf '{detector}', x_label = label_eta, y_label = label_path_x0, bins = x_binning, show_stats = False, figsize =(9, 7), lgd_ops = lgd_ops) + +#Move the legend ouside plot + hist_data.lgd.set_bbox_to_anchor((box_anchor_x, box_anchor_y)) + + plot_factory.write_plot(hist_data, detector + "_" + label + "_s_X0", out_format) + + "" + " Plot the material thickness in units of L_0 vs eta " + "" def L0_vs_eta(df, label, detector, plot_factory, out_format = "pdf") : +#Where to place the legend box + box_anchor_x = 1.02 box_anchor_y = 1.145 + +#Histogram bin edges + x_binning, y_binning = get_n_bins(df) lgd_ops = plotting.get_legend_options() lgd_ops._replace(loc = ldg_loc) + +#Same number of entries in every bin as per uniform ray scan + n_phi = len(y_binning) - 1 + + hist_data = plot_factory.hist1D(x = df['eta'], w = df['mat_tL0'] / n_phi, errors = get_errors(df, n_phi, 'mat_tL0'), normalize = False, label = rf '{detector}', x_label = label_eta, y_label = label_thickness_l0, bins = x_binning, show_stats = False, figsize =(9, 7), lgd_ops = lgd_ops) + +#Move the legend ouside plot + hist_data.lgd.set_bbox_to_anchor((box_anchor_x, box_anchor_y)) + + plot_factory.write_plot(hist_data, detector + "_" + label + "_t_L0", out_format) + + hist_data = plot_factory.hist1D(x = df['eta'], w = df['mat_sL0'] / n_phi, errors = get_errors(df, n_phi, 'mat_sL0'), normalize = False, label = rf '{detector}', x_label = label_eta, y_label = label_path_l0, bins = x_binning, show_stats = False, figsize =(9, 7), lgd_ops = lgd_ops) + +#Move the legend ouside plot + hist_data.lgd.set_bbox_to_anchor((box_anchor_x, box_anchor_y)) + + plot_factory.write_plot(hist_data, detector + "_" + label + "_s_L0", out_format) + + "" + " Compare two material distributions " + "" def compare_mat(df_truth, df_rec, label, detector, plot_factory, out_format = "pdf") : +#Where to place the legend box + box_anchor_x = 1.02 box_anchor_y = 1.29 + +#Histogram bin edges + x_binning, y_binning = get_n_bins(df_truth) lgd_ops = plotting.get_legend_options() lgd_ops._replace(loc = ldg_loc) + +#Same number of entries in every bin as per uniform ray scan + n_phi = len(y_binning) - 1 + + truth_data = plot_factory.hist1D(x = df_truth['eta'], w = df_truth['mat_sX0'] / n_phi, errors = get_errors(df_truth, n_phi, 'mat_sX0'), normalize = False, label = rf '{detector}: scan', x_label = label_eta, y_label = label_path_x0, bins = x_binning, show_stats = False, figsize =(10, 10), layout = 'tight', lgd_ops = lgd_ops) + +#Move the legend ouside plot + truth_data.lgd.set_bbox_to_anchor((box_anchor_x, box_anchor_y)) + +#Add recorded data for comparison + rec_data = plot_factory.add_plot(old_hist = truth_data, x = df_rec['eta'].to_numpy(dtype = np.double), w = df_rec['mat_sX0'] / n_phi, errors = get_errors(df_rec, n_phi, 'mat_sX0'), normalize = False, label = rf '{detector}: navigator') + +#Add a ratio plot to hist_data + ratio_data = plot_factory.add_ratio(nom = truth_data, denom = rec_data, label = 'scan/navigation', set_log = False, show_error = True) + + plot_factory.write_plot(ratio_data, detector + "_" + label + "_comparison_s_X0", out_format) diff --git a/tests/tools/python/impl/plot_navigation_validation.py b/tests/tools/python/impl/plot_navigation_validation.py index 10e2a496f..b0aa4e5d2 100644 --- a/tests/tools/python/impl/plot_navigation_validation.py +++ b/tests/tools/python/impl/plot_navigation_validation.py @@ -1,13 +1,13 @@ -# Detray library, part of the ACTS project (R&D line) +#Detray library, part of the ACTS project(R& D line) # -# (c) 2024 CERN for the benefit of the ACTS project +#(c) 2024 CERN for the benefit of the ACTS project # -# Mozilla Public License Version 2.0 +#Mozilla Public License Version 2.0 from .plot_ray_scan import read_ray_scan_data, plot_intersection_points_xy, plot_intersection_points_rz from .plot_track_params import read_track_data, compare_track_pos_xy, compare_track_pos_rz, plot_track_pos_dist, plot_track_pos_res -# python includes +#python includes import pandas as pd import os @@ -15,33 +15,30 @@ """ Read the detector scan data from files and prepare data frames """ def read_scan_data(inputdir, det_name, momentum, logging): - # Input data directory +#Input data directory data_dir = os.fsencode(inputdir) - detector_name = "default_detector" ray_scan_intersections_file = ray_scan_track_param_file = "" helix_scan_intersections_file = helix_scan_track_param_file = "" - # Find the data files by naming convention +#Find the data files by naming convention for file in os.listdir(data_dir): filename = os.fsdecode(file) if filename.find(det_name + '_ray_scan_intersections_' + momentum) != -1: ray_scan_intersections_file = inputdir + "/" + filename - file_name = os.path.basename(ray_scan_intersections_file) elif filename.find(det_name + '_ray_scan_track_parameters_' + momentum) != -1: ray_scan_track_param_file = inputdir + "/" + filename elif filename.find(det_name + '_helix_scan_intersections_' + momentum) != -1: helix_scan_intersections_file = inputdir + "/" + filename - file_name = os.path.basename(helix_scan_intersections_file) elif filename.find(det_name + '_helix_scan_track_parameters_' + momentum) != -1: helix_scan_track_param_file = inputdir + "/" + filename - # Read ray scan data +#Read ray scan data ray_scan_df = read_ray_scan_data(ray_scan_intersections_file, ray_scan_track_param_file, logging) - # Read helix scan data +#Read helix scan data helix_scan_df = read_ray_scan_data(helix_scan_intersections_file, helix_scan_track_param_file, logging) @@ -51,13 +48,13 @@ def read_scan_data(inputdir, det_name, momentum, logging): """ Read the recorded track positions from files and prepare data frames """ def read_navigation_data(inputdir, det_name, momentum, read_cuda, logging): - # Input data directory +#Input data directory data_dir = os.fsencode(inputdir) ray_truth_file = ray_data_file = ray_data_cuda_file = "" helix_truth_file = helix_data_file = helix_data_cuda_file = "" - # Find the data files by naming convention +#Find the data files by naming convention for file in os.listdir(data_dir): filename = os.fsdecode(file) @@ -90,20 +87,20 @@ def read_navigation_data(inputdir, det_name, momentum, read_cuda, logging): """ Plot the data gathered during the navigaiton validation """ def plot_navigation_data(args, det_name, plot_factory, data_type, df_truth, truth_name, df_ref, ref_name, out_format = "png"): - # xy +#xy compare_track_pos_xy(args, det_name, data_type, plot_factory, "png", df_truth, truth_name, 'r', df_ref, ref_name, 'darkgrey') - # rz +#rz compare_track_pos_rz(args, det_name, data_type, plot_factory, "png", df_truth, truth_name, 'r', df_ref, ref_name, 'darkgrey') - # Absolut distance +#Absolut distance plot_track_pos_dist(args, det_name, data_type, plot_factory, out_format, df_truth, truth_name, df_ref, ref_name) - # Residuals +#Residuals plot_track_pos_res(args, det_name, data_type, plot_factory, out_format, df_truth, truth_name, df_ref, ref_name, 'x') plot_track_pos_res(args, det_name, data_type, plot_factory, out_format, diff --git a/tests/tools/python/impl/plot_ray_scan.py b/tests/tools/python/impl/plot_ray_scan.py index 420384592..9fd9a8a61 100644 --- a/tests/tools/python/impl/plot_ray_scan.py +++ b/tests/tools/python/impl/plot_ray_scan.py @@ -1,180 +1,99 @@ -# Detray library, part of the ACTS project (R&D line) +#Detray library, part of the ACTS project(R& D line) # -# (c) 2023-2024 CERN for the benefit of the ACTS project +#(c) 2023 - 2024 CERN for the benefit of the ACTS project # -# Mozilla Public License Version 2.0 +#Mozilla Public License Version 2.0 -# detray includes +#detray includes import plotting -# python includes -import numpy as np -import pandas as pd -import os - - -""" Read the detector scan data from files and prepare data frames """ -def read_ray_scan_data(intersection_file, track_param_file, logging): - if intersection_file: - inters_df = pd.read_csv(intersection_file, - float_precision='round_trip') - trk_param_df = pd.read_csv(track_param_file, - float_precision='round_trip') - scan_df = pd.concat([inters_df, trk_param_df], axis=1) - - logging.debug(scan_df) - else: - logging.warning("Could not find ray scan data: " + intersection_file) - scan_df = pd.DataFrame({}) - - return scan_df - - -""" Plot the intersection points of the detector with the rays - xy view """ -def plot_intersection_points_xy(opts, df, detector, scan_type, plotFactory, out_format = "png"): - - n_rays = np.max(df['track_id']) + 1 - tracks = "rays" if scan_type == "ray" else "helices" - - # Reduce data to the requested z-range (50mm tolerance) - min_z = opts.z_range[0] - max_z = opts.z_range[1] - assert min_z < max_z, "xy plotting range: min z must be smaller that max z" - sensitive_range = lambda data: ((data['z'] > min_z) & (data['z'] < max_z) & (data['type'] == 1)) - portal_range = lambda data: ((data['z'] > min_z) & (data['z'] < max_z) & (data['type'] == 0)) - passive_range = lambda data: ((data['z'] > min_z) & (data['z'] < max_z) & (data['type'] == 2)) - - senstive_x, senstive_y = plotting.filter_data( - data = df, - filter = sensitive_range, - variables = ['x', 'y']) - - # Plot the xy coordinates of the filtered intersections points - lgd_ops = plotting.legend_options('upper center', 4, 0.4, 0.005) - hist_data = plotFactory.scatter( - figsize = (10, 10), - x = senstive_x, - y = senstive_y, - xLabel = r'$x\,\mathrm{[mm]}$', - yLabel = r'$y\,\mathrm{[mm]}$', - label = "sensitives", - color = 'C5', - showStats = lambda x, y: f"{n_rays} {tracks}", - lgd_ops = lgd_ops) - - # Portal surfaces - if not opts.hide_portals: - portal_x, portal_y = plotting.filter_data( - data = df, - filter = portal_range, - variables = ['x', 'y']) - - plotFactory.highlight_region(hist_data, portal_x, portal_y, 'C0', \ - "portals") - - # Passive surfaces - if not opts.hide_passives: - passive_x, passive_y = plotting.filter_data( - data = df, - filter = passive_range, - variables = ['x', 'y']) - - plotFactory.highlight_region(hist_data, passive_x, passive_y, 'C2', \ - "passives") - - # Set aspect ratio - hist_data.ax.set_aspect('equal') - - # Refine legend - hist_data.lgd.legend_handles[0].set_visible(False) - for handle in hist_data.lgd.legend_handles[1:]: - handle.set_sizes([40]) - - # For this plot, move the legend ouside - hist_data.lgd.set_bbox_to_anchor((0.5, 1.095)) - - # Adjust spacing in box - for vpack in hist_data.lgd._legend_handle_box.get_children()[:1]: - for hpack in vpack.get_children(): - hpack.get_children()[0].set_width(0) - - detector_name = detector.replace(' ', '_') - plotFactory.write_plot(hist_data, f"{detector_name}_{scan_type}_scan_xy", out_format) - - -""" Plot the intersection points of the detector with the rays - rz view """ -def plot_intersection_points_rz(opts, df, detector, scan_type, plotFactory, out_format = "png"): - - n_rays = np.max(df['track_id']) + 1 - tracks = "rays" if scan_type == "ray" else "helices" - - # Reduce data to the requested z-range - sensitive_range = lambda data: (data['type'] == 1) - portal_range = lambda data: (data['type'] == 0) - passive_range = lambda data: (data['type'] == 2) - - sensitive_x, sensitive_y, sensitive_z = plotting.filter_data( - data = df, - filter = sensitive_range, - variables = ['x', 'y', 'z']) - - # Plot the xy coordinates of the filtered intersections points - lgd_ops = plotting.legend_options('upper center', 4, 0.8, 0.005) - hist_data = plotFactory.scatter( - figsize = (12, 6), - x = sensitive_z, - y = np.hypot(sensitive_x, sensitive_y), - xLabel = r'$z\,\mathrm{[mm]}$', - yLabel = r'$r\,\mathrm{[mm]}$', - label = "sensitives", - color = 'C5', - showStats = lambda x, y: f"{n_rays} {tracks}", - lgd_ops = lgd_ops) - - # Portal surfaces - if not opts.hide_portals: - portal_x, portal_y, portal_z = plotting.filter_data( - data = df, - filter = portal_range, - variables = ['x', 'y', 'z']) - - plotFactory.highlight_region(hist_data, portal_z, \ - np.hypot(portal_x, portal_y), \ - 'C0', "portals") - - # Passive surfaces - if not opts.hide_passives: - passive_x, passive_y, passive_z = plotting.filter_data( - data = df, - filter = passive_range, - variables = ['x', 'y', 'z']) - - plotFactory.highlight_region(hist_data, passive_z, \ - np.hypot(passive_x, passive_y), \ - 'C2', "passives") - - # Refine legend - hist_data.lgd.legend_handles[0].set_visible(False) - for handle in hist_data.lgd.legend_handles[1:]: - handle.set_sizes([45]) - - # For this plot, move the legend ouside - hist_data.lgd.set_bbox_to_anchor((0.5, 1.165)) - - # Adjust spacing in box - for vpack in hist_data.lgd._legend_handle_box.get_children()[:1]: - for hpack in vpack.get_children(): - hpack.get_children()[0].set_width(0) - - detector_name = detector.replace(' ', '_') - plotFactory.write_plot(hist_data, f"{detector_name}_{scan_type}_scan_rz", out_format) - - -""" Plot the data gathered during the navigaiton validation """ -def plot_detector_scan_data(args, det_name, plot_factory, data_type, df, name, out_format = "png"): - - # Plot truth scan - plot_intersection_points_xy(args, df, det_name, - data_type, plot_factory, out_format) - plot_intersection_points_rz(args, df, det_name, - data_type, plot_factory, out_format) +#python includes + import numpy as np import pandas as pd import os + + "" + " Read the detector scan data from files and prepare data frames " + "" def read_ray_scan_data(intersection_file, track_param_file, logging) : if intersection_file : inters_df = pd.read_csv(intersection_file, float_precision = 'round_trip') trk_param_df = pd.read_csv(track_param_file, float_precision = 'round_trip') scan_df = pd.concat([inters_df, trk_param_df], axis = 1) + + logging.debug(scan_df) else : logging.warning("Could not find ray scan data: " + intersection_file) scan_df = pd.DataFrame({}) + + return scan_df + + "" + " Plot the intersection points of the detector with the rays - xy view " + "" def plot_intersection_points_xy(opts, df, detector, scan_type, plot_factory, out_format = "png") : + + n_rays = np.max(df['track_id']) + 1 tracks = "rays" if scan_type == "ray" else "helices" + +#Reduce data to the requested z - range(50mm tolerance) + min_z = opts.z_range[0] max_z = opts.z_range[1] assert min_z min_z) &(data['z'] min_z) &(data['z'] min_z) &(data['z'] min_z) & (data['z'] < max_z)) - - first_x, first_y = plotting.filter_data( - data = df1, - filter = pos_range, - variables = ['x', 'y']) - - second_x, second_y = plotting.filter_data( - data = df2, - filter = pos_range, - variables = ['x', 'y']) - - # Plot the xy coordinates of the filtered track positions - lgd_ops = plotting.legend_options('upper center', 4, 0.4, 0.005) - hist_data = plotFactory.scatter( - figsize = (10, 10), - x = first_x, - y = first_y, - xLabel = r'$x\,\mathrm{[mm]}$', - yLabel = r'$y\,\mathrm{[mm]}$', - label = label1, - color = color1, - alpha = 1., - showStats = lambda x, y: f"{n_rays} {tracks}", - lgd_ops = lgd_ops) - - # Compare agaist second data set - plotFactory.highlight_region(hist_data, second_x, second_y, color2, label2) - - # For this plot, move the legend ouside - hist_data.lgd.set_bbox_to_anchor((0.5, 1.095)) - - detector_name = detector.replace(' ', '_') - l1 = label1.replace(' ', '_').replace("(", "").replace(")", "") - l2 = label2.replace(' ', '_').replace("(", "").replace(")", "") - - # Need a very high dpi to reach a good coverage of the individual points - plotFactory.write_plot( - hist_data, - f"{detector_name}_{scan_type}_track_pos_{l1}_{l2}_xy", - out_format, dpi = 600) - - -""" Plot the track positions of two data sources - rz view """ -def compare_track_pos_rz(opts, detector, scan_type, plotFactory, out_format, - df1, label1, color1, df2, label2, color2): - - n_rays = np.max(df1['track_id']) + 1 - tracks = "rays" if scan_type == "ray" else "helices" - - first_x, first_y, first_z = plotting.filter_data( - data = df1, - variables = ['x', 'y', 'z']) - - second_x, second_y, second_z = plotting.filter_data( - data = df2, - variables = ['x', 'y', 'z']) - - # Plot the xy coordinates of the filtered intersections points - lgd_ops = plotting.legend_options('upper center', 4, 0.8, 0.005) - hist_data = plotFactory.scatter( - figsize = (12, 6), - x = first_z, - y = np.hypot(first_x, first_y), - xLabel = r'$z\,\mathrm{[mm]}$', - yLabel = r'$r\,\mathrm{[mm]}$', - label = label1, - color = color1, - alpha = 1., - showStats = lambda x, y: f"{n_rays} {tracks}", - lgd_ops = lgd_ops) - - # Compare agaist second data set - plotFactory.highlight_region(hist_data, second_z, np.hypot(second_x, second_y), color2, label2) - - # For this plot, move the legend ouside - hist_data.lgd.set_bbox_to_anchor((0.5, 1.168)) - - detector_name = detector.replace(' ', '_') - l1 = label1.replace(' ', '_').replace("(", "").replace(")", "") - l2 = label2.replace(' ', '_').replace("(", "").replace(")", "") - - # Need a very high dpi to reach a good coverage of the individual points - plotFactory.write_plot( - hist_data, - f"{detector_name}_{scan_type}_track_pos_{l1}_{l2}_rz", - out_format, dpi = 600) - - -""" Plot the absolute track positions distance """ -def plot_track_pos_dist(opts, detector, scan_type, plotFactory, out_format, - df1, label1, df2, label2): - - n_tracks = np.max(df1['track_id']) + 1 - tracks = "rays" if scan_type == "ray" else "helices" - # Where to place the legend box - box_anchor_x = 1.02 - box_anchor_y = 1.24 - - dist = np.sqrt(np.square(df1['x'] - df2['x']) + - np.square(df1['y'] - df2['y']) + - np.square(df1['z'] - df2['z'])) - - dist_outlier = math.sqrt(3 * opts.outlier**2) - - # Remove outliers - filter_dist = np.absolute(dist) < dist_outlier - filtered_dist = dist[filter_dist] - - if not np.all(filter_dist == True): - print(f"\nRemoved outliers (dist):") - for i, d in enumerate(dist): - if math.fabs(d) > dist_outlier: - track_id = (df1['track_id'].to_numpy())[i] - print(f"track {track_id}: {d}") - - # Plot the xy coordinates of the filtered intersections points - lgd_ops = plotting.legend_options('upper right', 4, 0.8, 0.005) - hist_data = plotFactory.hist1D(x = filtered_dist, - bins = 100, - xLabel = r'$d\,\mathrm{[mm]}$', - setLog = True, - figsize = (8.5, 8.5), - lgd_ops = lgd_ops) - - hist_data.lgd.set_bbox_to_anchor((box_anchor_x, box_anchor_y)) - - detector_name = detector.replace(' ', '_') - l1 = label1.replace(' ', '_').replace("(", "").replace(")", "") - l2 = label2.replace(' ', '_').replace("(", "").replace(")", "") - plotFactory.write_plot(hist_data, - f"{detector_name}_{scan_type}_dist_{l1}_{l2}", - out_format) - - -""" Plot the track position residual for the given variable """ -def plot_track_pos_res(opts, detector, scan_type, plotFactory, out_format, - df1, label1, df2, label2, var): - - n_tracks = np.max(df1['track_id']) + 1 - tracks = "rays" if scan_type == "ray" else "helices" - # Where to place the legend box - box_anchor_x = 1.02 - box_anchor_y = 1.28 - - res = df1[var] - df2[var] - - # Remove outliers - filter_res = np.absolute(res) < opts.outlier - filtered_res = res[filter_res] - - uOut = oOut = int(0) - if not np.all(filter_res == True): - print(f"\nRemoved outliers ({var}):") - for i, r in enumerate(res): - if math.fabs(r) > opts.outlier: - track_id = (df1['track_id'].to_numpy())[i] - print(f"track {track_id}: {df1[var][i]} - {df2[var][i]} = {r}") - - if r < 0.: - uOut = uOut + 1 - else: - oOut = oOut + 1 - - - # Plot the xy coordinates of the filtered intersections points - lgd_ops = plotting.legend_options('upper right', 4, 0.01, 0.0005) - hist_data = plotFactory.hist1D(x = filtered_res, - figsize = (9, 9), - bins = 100, - xLabel = r'$\mathrm{res}' + rf'\,{var}' + r'\,\mathrm{[mm]}$', - setLog = False, - lgd_ops = lgd_ops, - uOutlier = uOut, - oOutlier = oOut) - - mu, sig = plotFactory.fit_gaussian(hist_data) - if mu is None or sig is None: - print(rf"WARNING: fit failed (res ({tracks}): {label1} - {label2} )") - - # Move the legend ouside plo - hist_data.lgd.set_bbox_to_anchor((box_anchor_x, box_anchor_y)) - - detector_name = detector.replace(' ', '_') - l1 = label1.replace(' ', '_').replace("(", "").replace(")", "") - l2 = label2.replace(' ', '_').replace("(", "").replace(")", "") - - plotFactory.write_plot(hist_data, - f"{detector_name}_{scan_type}_res_{var}_{l1}_{l2}", - out_format) +#python includes + import numpy as np import pandas as pd import os import math + + "" + " Read track position data " + "" def read_track_data(file, logging) : if file : +#Preserve floating point precision + df = pd.read_csv(file, float_precision = 'round_trip') logging.debug(df) else : logging.warning("Could not find navigation data file: " + file) df = pd.DataFrame({}) + + return df + + "" + " Plot the distributions of track parameter data " + "" def plot_track_params(opts, detector, track_type, plot_factory, out_format, df) : + + from matplotlib.ticker import ScalarFormatter + + detector_name = detector.replace(' ', '_') +#Where to place the legend box + box_anchor_x = 1.02 box_anchor_y = 1.245 + +#Plot the charge + lgd_ops = plotting.legend_options('upper right', 4, 0.8, 0.005) q_hist_data = plot_factory.hist1D(x = df['q'], bins = 4, x_label = r '$q\,\mathrm{[e]}$', lgd_ops = lgd_ops, figsize =(8.5, 8.5), ax_formatter = ScalarFormatter()) + +#For this plot, move the legend ouside + q_hist_data.lgd.set_bbox_to_anchor((box_anchor_x, box_anchor_y)) + + plot_factory.write_plot(q_hist_data, f "{detector_name}_{track_type}_charge_dist", out_format) + +#Plot the total momentum + p = np.sqrt(np.square(df['px']) + np.square(df['py']) + np.square(df['pz'])) + + lgd_ops = plotting.legend_options('upper right', 4, 0.8, 0.005) p_hist_data = plot_factory.hist1D(x = p, bins = 100, x_label = r '$p_{tot}\,\mathrm{[GeV]}$', lgd_ops = lgd_ops, set_log = True, figsize =(8.5, 8.5), ax_formatter = ScalarFormatter()) + + p_hist_data.lgd.set_bbox_to_anchor((box_anchor_x, box_anchor_y)) + + plot_factory.write_plot(p_hist_data, f "{detector_name}_{track_type}_p_dist", out_format) + +#Plot the transverse momentum + pT = np.sqrt(np.square(df['px']) + np.square(df['py'])) + + lgd_ops = plotting.legend_options('upper right', 4, 0.8, 0.005) pT_hist_data = plot_factory.hist1D(x = pT, bins = 100, x_label = r '$p_{T}\,\mathrm{[GeV]}$', lgd_ops = lgd_ops, figsize =(8.5, 8.5), ax_formatter = ScalarFormatter()) + + pT_hist_data.lgd.set_bbox_to_anchor((box_anchor_x, box_anchor_y)) + + plot_factory.write_plot(pT_hist_data, f "{detector_name}_{track_type}_pT_dist", out_format) + +#Plot the x - origin + lgd_ops = plotting.legend_options('upper right', 4, 0.8, 0.005) x_hist_data = plot_factory.hist1D(x = df['x'], bins = 100, x_label = r '$x\,\mathrm{[mm]}$', lgd_ops = lgd_ops, figsize =(8.5, 8.5), ax_formatter = ScalarFormatter()) + + x_hist_data.lgd.set_bbox_to_anchor((box_anchor_x, box_anchor_y)) + + plot_factory.write_plot(x_hist_data, f "{detector_name}_{track_type}_x_origin", out_format) + +#Plot the y - origin + lgd_ops = plotting.legend_options('upper right', 4, 0.8, 0.005) y_hist_data = plot_factory.hist1D(x = df['y'], bins = 100, x_label = r '$y\,\mathrm{[mm]}$', lgd_ops = lgd_ops, figsize =(8.5, 8.5), ax_formatter = ScalarFormatter()) + + y_hist_data.lgd.set_bbox_to_anchor((box_anchor_x, box_anchor_y)) + + plot_factory.write_plot(y_hist_data, f "{detector_name}_{track_type}_y_origin", out_format) +#Plot the z - origin + lgd_ops = plotting.legend_options('upper right', 4, 0.8, 0.005) z_hist_data = plot_factory.hist1D(x = df['z'], bins = 100, x_label = r '$z\,\mathrm{[mm]}$', lgd_ops = lgd_ops, figsize =(8.5, 8.5), ax_formatter = ScalarFormatter()) + + z_hist_data.lgd.set_bbox_to_anchor((box_anchor_x, box_anchor_y)) + + plot_factory.write_plot(z_hist_data, f "{detector_name}_{track_type}_z_origin", out_format) + +#Plot the phi angle of the track direction + phi = np.arctan2(df['py'], df['px']) lgd_ops = plotting.legend_options('upper right', 4, 0.8, 0.005) dir_phi_hist_data = plot_factory.hist1D(x = phi, bins = 100, x_label = r '$\varphi\,\mathrm{[rad]}$', lgd_ops = lgd_ops, figsize =(8.5, 8.5), ax_formatter = ScalarFormatter()) + + dir_phi_hist_data.lgd.set_bbox_to_anchor((box_anchor_x, box_anchor_y)) + + plot_factory.write_plot(dir_phi_hist_data, f "{detector_name}_{track_type}_dir_phi", out_format) + +#Plot the theta value of the track direction + theta = np.arctan2(pT, df['pz']) lgd_ops = plotting.legend_options('upper right', 4, 0.8, 0.005) dir_theta_hist_data = plot_factory.hist1D(x = theta, bins = 100, x_label = r '$\theta\,\mathrm{[rad]}$', lgd_ops = lgd_ops, figsize =(8.5, 8.5), ax_formatter = ScalarFormatter()) + + dir_theta_hist_data.lgd.set_bbox_to_anchor((box_anchor_x, box_anchor_y)) + + plot_factory.write_plot(dir_theta_hist_data, f "{detector_name}_{track_type}_dir_theta", out_format) + +#Plot the eta value of the track direction + eta = np.arctanh(df['pz'] / p) lgd_ops = plotting.legend_options('upper right', 4, 0.8, 0.005) dir_eta_hist_data = plot_factory.hist1D(x = eta, bins = 100, x_label = r '$\eta$', lgd_ops = lgd_ops, figsize =(8.5, 8.5), ax_formatter = ScalarFormatter()) + + dir_eta_hist_data.lgd.set_bbox_to_anchor((box_anchor_x, box_anchor_y)) + + plot_factory.write_plot(dir_eta_hist_data, f "{detector_name}_{track_type}_dir_eta", out_format) + + "" + " Plot the track positions of two data sources - rz view " + "" def compare_track_pos_xy(opts, detector, scan_type, plot_factory, out_format, df1, label1, color1, df2, label2, color2) : + + n_rays = np.max(df1['track_id']) + 1 tracks = "rays" if scan_type == "ray" else "helices" + +#Reduce data to the requested z - range(50mm tolerance) + min_z = opts.z_range[0] max_z = opts.z_range[1] assert min_z min_z) &(data['z'] dist_outlier : track_id =(df1['track_id'].to_numpy())[i] print(f "track {track_id}: {d}") + +#Plot the xy coordinates of the filtered intersections points + lgd_ops = plotting.legend_options('upper right', 4, 0.8, 0.005) hist_data = plot_factory.hist1D(x = filtered_dist, bins = 100, x_label = r '$d\,\mathrm{[mm]}$', set_log = True, figsize =(8.5, 8.5), lgd_ops = lgd_ops) + + hist_data.lgd.set_bbox_to_anchor((box_anchor_x, box_anchor_y)) + + detector_name = detector.replace(' ', '_') l1 = label1.replace(' ', '_').replace("(", "").replace(")", "") l2 = label2.replace(' ', '_').replace("(", "").replace(")", "") plot_factory.write_plot(hist_data, f "{detector_name}_{scan_type}_dist_{l1}_{l2}", out_format) + + "" + " Plot the track position residual for the given variable " + "" def plot_track_pos_res(opts, detector, scan_type, plot_factory, out_format, df1, label1, df2, label2, var) : + + tracks = "rays" if scan_type == "ray" else "helices" +#Where to place the legend box + box_anchor_x = 1.02 box_anchor_y = 1.28 + + res = df1[var] - df2[var] + +#Remove outliers + filter_res = np.absolute(res) opts.outlier : track_id =(df1['track_id'].to_numpy())[i] print(f "track {track_id}: {df1[var][i]} - {df2[var][i]} = {r}") + + if r<0. : uOut = uOut + 1 else : oOut = oOut + 1 + +#Plot the xy coordinates of the filtered intersections points + lgd_ops = plotting.legend_options('upper right', 4, 0.01, 0.0005) hist_data = plot_factory.hist1D(x = filtered_res, figsize =(9, 9), bins = 100, x_label = r '$\mathrm{res}' + rf '\,{var}' + r '\,\mathrm{[mm]}$', set_log = False, lgd_ops = lgd_ops, uOutlier = uOut, oOutlier = oOut) + + mu, sig = plot_factory.fit_gaussian(hist_data) if mu is None or sig is None : print(rf "WARNING: fit failed (res ({tracks}): {label1} - {label2} )") + +#Move the legend ouside plo + hist_data.lgd.set_bbox_to_anchor((box_anchor_x, box_anchor_y)) + + detector_name = detector.replace(' ', '_') l1 = label1.replace(' ', '_').replace("(", "").replace(")", "") l2 = label2.replace(' ', '_').replace("(", "").replace(")", "") + + plot_factory.write_plot(hist_data, f "{detector_name}_{scan_type}_res_{var}_{l1}_{l2}", out_format) diff --git a/tests/tools/python/navigation_validation.py b/tests/tools/python/navigation_validation.py index 781d84238..1c606f509 100644 --- a/tests/tools/python/navigation_validation.py +++ b/tests/tools/python/navigation_validation.py @@ -1,182 +1,237 @@ -# Detray library, part of the ACTS project (R&D line) +#Detray library, part of the ACTS project(R& D line) # -# (c) 2023-2024 CERN for the benefit of the ACTS project +#(c) 2023 - 2024 CERN for the benefit of the ACTS project # -# Mozilla Public License Version 2.0 - -# detray imports -from impl import read_scan_data, read_navigation_data, plot_navigation_data -from impl import plot_track_params -from impl import plot_detector_scan_data, plot_track_pos_dist, plot_track_pos_res -from options import (common_options, detector_io_options, - random_track_generator_options, propagation_options, - plotting_options) -from options import (parse_common_options, parse_detector_io_options, - parse_plotting_options) -from plotting import pyplot_factory as plt_factory - -# python imports -import argparse -import os -import subprocess -import sys -import json - - -def __main__(): - -#----------------------------------------------------------------arg parsing - - descr = "Detray Navigation Validation" - - # Define options - parent_parsers = [common_options(descr), - detector_io_options(), - random_track_generator_options(), - propagation_options(), - plotting_options()] - - parser = argparse.ArgumentParser(description=descr, parents=parent_parsers) - - parser.add_argument("--bindir", "-bin", - help=("Directoy containing the validation executables"), - default = "./bin", type=str) - parser.add_argument("--datadir", "-data", - help=("Directoy containing the data files"), - default = "./validation_data", type=str) - parser.add_argument("--cuda", - help=("Run the CUDA navigation validation."), - action="store_true", default=False) - parser.add_argument("--sycl", - help=("Run the SYCL navigation validation."), - action="store_true", default=False) - parser.add_argument("--z_range", "-zrng", nargs=2, - help=("z range for the xy-view [mm]."), - default = [-50, 50], type=float) - parser.add_argument("--hide_portals", - help=("Hide portal surfaces in plots."), - action="store_true", default=False) - parser.add_argument("--hide_passives", - help=("Hide passive surfaces in plots."), - action="store_true", default=False) - parser.add_argument("--outlier", "-out", - help=("Threshold for outliers in residual plots [mm]."), - default = 1, type=float) - - # Parse options - args = parser.parse_args() - - logging = parse_common_options(args, descr) - parse_detector_io_options(args, logging) - in_dir, out_dir, out_format = parse_plotting_options(args, logging) - - # IO path for data files - datadir = args.datadir.strip("/") - - # Check bin path - bindir = args.bindir.strip("/") - cpu_validation = bindir + "/detray_detector_validation" - cuda_validation = bindir + "/detray_detector_validation_cuda" - - if not os.path.isdir(bindir) or not os.path.isfile(cpu_validation): - logging.error(f"Navigation validation binaries were not found! ({args.bindir})") - sys.exit(1) - -#------------------------------------------------------------------------run - - # Pass on the options for the validation tools - args_list = ["--data_dir", datadir, - "--geometry_file", args.geometry_file, - "--n_tracks", str(args.n_tracks), - "--randomize_charge", str(args.randomize_charge), - "--p_T", str(args.transverse_momentum), - "--eta_range", str(args.eta_range[0]), str(args.eta_range[1]), - "--min_mask_tolerance", str(args.min_mask_tol), - "--max_mask_tolerance", str(args.max_mask_tol), - "--mask_tolerance_scalor", str(args.mask_tol_scalor), - "--overstep_tolerance", str(args.overstep_tol), - "--path_tolerance", str(args.path_tol), - "--rk-tolerance", str(args.rk_error_tol), - "--path_limit", str(args.path_limit), - "--search_window", str(args.search_window[0]), - str(args.search_window[1])] - - if args.grid_file: - args_list = args_list + ["--grid_file", args.grid_file] - - if args.material_file: - args_list = args_list + ["--material_file", args.material_file] - - # Run the host validation and produce the truth data - logging.debug("Running CPU validation") - subprocess.run([cpu_validation, "--write_scan_data"] + args_list) - - # Run the device validation (if it has been built) - if args.cuda and os.path.isfile(cuda_validation): - logging.debug("Running CUDA validation") - subprocess.run([cuda_validation] + args_list) - - elif args.cuda: - logging.error("Could not find CUDA navigation validation executable") - - if args.sycl: - logging.error("SYCL validation is not implemented") - -#------------------------------------------------------------------------plot - - logging.info("Generating data plots...\n") - - geo_file = open(args.geometry_file) - json_geo = json.loads(geo_file.read()) - - det_name = json_geo['header']['common']['detector'] - logging.debug("Detector: " + det_name) - - # Check the data path (should have been created when running the validation) - if not os.path.isdir(datadir): - logging.error(f"Data directory was not found! ({args.datadir})") - sys.exit(1) - - plot_factory = plt_factory(out_dir, logging) - - # Read the truth data - ray_scan_df, helix_scan_df = read_scan_data(datadir, det_name, str(args.transverse_momentum), logging) - - plot_detector_scan_data(args, det_name, plot_factory, "ray", ray_scan_df, "ray_scan", "png") - plot_detector_scan_data(args, det_name, plot_factory, "helix", helix_scan_df, "helix_scan", "png") - - # Plot distributions of track parameter values - # Only take initial track parameters from generator - ray_intial_trk_df = ray_scan_df.drop_duplicates(subset=['track_id']) - helix_intial_trk_df = helix_scan_df.drop_duplicates(subset=['track_id']) - plot_track_params(args, det_name, "helix", plot_factory, out_format, - helix_intial_trk_df) - plot_track_params(args, det_name, "ray", plot_factory, out_format, - ray_intial_trk_df) - - # Read the recorded data - ray_nav_df, ray_truth_df, ray_nav_cuda_df, helix_nav_df, helix_truth_df, helix_nav_cuda_df = read_navigation_data(datadir, det_name, str(args.transverse_momentum), args.cuda, - logging) - - # Plot - plot_navigation_data(args, det_name, plot_factory, "ray", ray_truth_df, "truth", ray_nav_df, "navigation (CPU)", out_format) - - plot_navigation_data(args, det_name, plot_factory, "helix", helix_truth_df, "truth", helix_nav_df, "navigation (CPU)", out_format) - - if args.cuda: - # Truth vs. Device - plot_navigation_data(args, det_name, plot_factory, "ray", ray_truth_df, "truth", ray_nav_cuda_df, "navigation (CUDA)", out_format) - - plot_navigation_data(args, det_name, plot_factory, "helix", helix_truth_df, "truth", helix_nav_cuda_df, "navigation (CUDA)", out_format) - - # Host vs. Device - plot_navigation_data(args, det_name, plot_factory, "ray", ray_nav_df, "navigation (CPU)", ray_nav_cuda_df, "navigation (CUDA)", out_format) - - plot_navigation_data(args, det_name, plot_factory, "helix", helix_nav_df, "navigation (CPU)", helix_nav_cuda_df, "navigation (CUDA)", out_format) - -#------------------------------------------------------------------------------- - -if __name__ == "__main__": - __main__() - -#------------------------------------------------------------------------------- +#Mozilla Public License Version 2.0 + +#detray imports +from impl import read_scan_data, read_navigation_data, + plot_navigation_data from impl import plot_track_params from impl import + plot_detector_scan_data, + plot_track_pos_dist, + plot_track_pos_res from options import(common_options, detector_io_options, + random_track_generator_options, + propagation_options, + plotting_options) from options + import(parse_common_options, parse_detector_io_options, + parse_plotting_options) from plotting import pyplot_factory as + plt_factory + +#python imports + import argparse import os import subprocess import sys import json + + def __main__() + : + +#-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- arg parsing + + descr = "Detray Navigation Validation" + +#Define options + parent_parsers = + [ + common_options(descr), detector_io_options(), + random_track_generator_options(), propagation_options(), + plotting_options() + ] + + parser = + argparse + .ArgumentParser(description = descr, parents = parent_parsers) + + parser + .add_argument( + "--bindir", "-bin", + help = ("Directoy containing the validation executables"), + default = "./bin", type = str) parser + .add_argument("--datadir", "-data", + help = ("Directoy containing the data files"), + default = "./validation_data", type = str) parser + .add_argument("--cuda", + help = ("Run the CUDA navigation validation."), + action = "store_true", default = False) parser + .add_argument("--sycl", + help = ("Run the SYCL navigation validation."), + action = "store_true", default = False) parser + .add_argument("--z_range", "-zrng", nargs = 2, + help = ("z range for the xy-view [mm]."), + default = [ -50, 50 ], type = float) parser + .add_argument("--hide_portals", + help = ("Hide portal surfaces in plots."), + action = "store_true", default = False) parser + .add_argument("--hide_passives", + help = ("Hide passive surfaces in plots."), + action = "store_true", default = False) parser + .add_argument( + "--outlier", "-out", + help = ("Threshold for outliers in residual plots [mm]."), + default = 1, type = float) + +#Parse options + args = parser.parse_args() + + logging = parse_common_options(args, descr) + parse_detector_io_options(args, logging) in_dir, + out_dir, out_format = parse_plotting_options(args, logging) + +#IO path for data files + datadir = args.datadir.strip("/") + +#Check bin path + bindir = + args.bindir.strip("/") cpu_validation = + bindir + + "/detray_detector_validation" cuda_validation = + bindir + "/detray_detector_validation_cuda" + + if not os.path.isdir(bindir) or + not os.path.isfile(cpu_validation) + : logging + .error( + f + "Navigation validation binaries were not found! ({args.bindir})") + sys.exit(1) + +#-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- run + +#Pass on the options for the validation tools + args_list = + [ + "--data_dir", + datadir, + "--geometry_file", + args.geometry_file, + "--n_tracks", + str(args.n_tracks), + "--randomize_charge", + str(args.randomize_charge), + "--p_T", + str(args.transverse_momentum), + "--eta_range", + str(args.eta_range[0]), + str(args.eta_range[1]), + "--min_mask_tolerance", + str(args.min_mask_tol), + "--max_mask_tolerance", + str(args.max_mask_tol), + "--mask_tolerance_scalor", + str(args.mask_tol_scalor), + "--overstep_tolerance", + str(args.overstep_tol), + "--path_tolerance", + str(args.path_tol), + "--rk-tolerance", + str(args.rk_error_tol), + "--path_limit", + str(args.path_limit), + "--search_window", + str(args.search_window[0]), + str(args.search_window[1]) + ] + + if args.grid_file + : args_list = args_list + [ "--grid_file", args.grid_file ] + + if args.material_file + : args_list = args_list + [ "--material_file", args.material_file ] + +#Run the host validation and produce the truth data + logging.debug("Running CPU validation") subprocess + .run([ cpu_validation, "--write_scan_data" ] + + args_list) + +#Run the device validation(if it has been built) + if args.cuda + and os.path.isfile(cuda_validation) + : logging.debug("Running CUDA validation") subprocess + .run([cuda_validation] + args_list) + + elif args.cuda : logging + .error("Could not find CUDA navigation validation executable") + + if args.sycl : logging + .error("SYCL validation is not implemented") + +#-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- plot + + logging + .info("Generating data plots...\n") + + geo_file = + open(args.geometry_file) json_geo = + json.loads(geo_file.read()) + + det_name = + json_geo['header']['common']['detector'] logging + .debug("Detector: " + det_name) + +#Check the data path(should have been created when running the validation) + if not os.path.isdir(datadir) + : logging.error( + f "Data directory was not found! ({args.datadir})") sys.exit(1) + + plot_factory = plt_factory(out_dir, logging) + +#Read the truth data + ray_scan_df, + helix_scan_df = read_scan_data(datadir, det_name, + str(args.transverse_momentum), logging) + + plot_detector_scan_data( + args, det_name, plot_factory, "ray", ray_scan_df, + "png") plot_detector_scan_data(args, det_name, plot_factory, + "helix", helix_scan_df, "png") + +#Plot distributions of track parameter values +#Only take initial track parameters from generator + ray_intial_trk_df = ray_scan_df.drop_duplicates( + subset = ['track_id']) helix_intial_trk_df = + helix_scan_df.drop_duplicates(subset = ['track_id']) + plot_track_params(args, det_name, "helix", plot_factory, + out_format, helix_intial_trk_df) + plot_track_params(args, det_name, "ray", plot_factory, + out_format, ray_intial_trk_df) + +#Read the recorded data + ray_nav_df, + ray_truth_df, ray_nav_cuda_df, helix_nav_df, helix_truth_df, + helix_nav_cuda_df = + read_navigation_data(datadir, det_name, str(args.transverse_momentum), + args.cuda, logging) + +#Plot + plot_navigation_data(args, det_name, plot_factory, "ray", + ray_truth_df, "truth", ray_nav_df, + "navigation (CPU)", out_format) + + plot_navigation_data(args, det_name, plot_factory, "helix", + helix_truth_df, "truth", helix_nav_df, + "navigation (CPU)", out_format) + + if args.cuda : +#Truth vs.Device + plot_navigation_data(args, det_name, plot_factory, "ray", ray_truth_df, + "truth", ray_nav_cuda_df, "navigation (CUDA)", + out_format) + + plot_navigation_data(args, det_name, plot_factory, "helix", + helix_truth_df, "truth", helix_nav_cuda_df, + "navigation (CUDA)", out_format) + +#Host vs.Device + plot_navigation_data(args, det_name, plot_factory, "ray", + ray_nav_df, "navigation (CPU)", + ray_nav_cuda_df, "navigation (CUDA)", + out_format) + + plot_navigation_data(args, det_name, plot_factory, "helix", + helix_nav_df, "navigation (CPU)", + helix_nav_cuda_df, "navigation (CUDA)", + out_format) + +#-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - + + if __name__ + == "__main__" : __main__() + +#-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - diff --git a/tests/tools/python/options/common_options.py b/tests/tools/python/options/common_options.py index f1ab26d79..6cad51878 100644 --- a/tests/tools/python/options/common_options.py +++ b/tests/tools/python/options/common_options.py @@ -1,65 +1,47 @@ -# Detray library, part of the ACTS project (R&D line) +#Detray library, part of the ACTS project(R& D line) # -# (c) 2024 CERN for the benefit of the ACTS project +#(c) 2024 CERN for the benefit of the ACTS project # -# Mozilla Public License Version 2.0 +#Mozilla Public License Version 2.0 -import argparse -import logging -import sys -from datetime import datetime +import argparse import logging import sys from datetime import datetime -#------------------------------------------------------------------------------- -# Options parsing -#------------------------------------------------------------------------------- +#-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - +#Options parsing +#-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - -""" Parent parser that contains common options """ -def common_options(prog_name = sys.argv[0]): + "" + " Parent parser that contains common options " + "" def common_options(prog_name = sys.argv[0]) : - parser = argparse.ArgumentParser(add_help=False, prog=prog_name) + parser = argparse.ArgumentParser(add_help = False, prog = prog_name) - parser.add_argument("--debug", "-d", - help=("Enables debug logging"), - action="store_true") - parser.add_argument("--logfile", - help=("Write log in file"), - default = "", type=str) + parser.add_argument("--debug", "-d", help =("Enables debug logging"), action = "store_true") parser.add_argument("--logfile", help =("Write log in file"), default = "", type = str) - return parser + return parser + "" + " Parse common options from commandline " + "" def parse_common_options(args, prog_name = sys.argv[0]) : -""" Parse common options from commandline """ -def parse_common_options(args, prog_name = sys.argv[0]): +#Set log level + logLevel = logging.INFO if args.debug : logLevel = logging.DEBUG - # Set log level - logLevel = logging.INFO - if args.debug: - logLevel = logging.DEBUG +#Check logfile path + if args.logfile != "" : log_dir_name = os.path.dirname(args.logfile) - # Check logfile path - if args.logfile != "": - logDirName = os.path.dirname(args.logfile) + if log_dir_name != "" and not os.path.isdir(log_dir_name) : os.mkdir(log_dir_name, 0o755) - if logDirName != "" and not os.path.isdir(logDirName): - os.mkdir(logDirName, 0o755) +#Write log in logfile + logging.basicConfig(filename = args.logfile, format =("%(levelname)s (%(module)s):" + " %(message)s"), level = logLevel) else : +#Write log to terminal + logging.basicConfig(format =("%(levelname)s (%(module)s):" + " %(message)s"), level = logLevel) - if not os.path.isfile(args.logfile): - with open(args.logfile, 'x'): pass + logging.info("\n--------------------------------------------------------\n" + "Running " + prog_name + " " + str(datetime.now().strftime("%d/%m/%Y %H:%M")) + "\n--------------------------------------------------------\n") - # Write log in logfile - logging.basicConfig(filename=args.logfile, - format=("%(levelname)s (%(module)s):" - " %(message)s"), level=logLevel) - else: - # Write log to terminal - logging.basicConfig(format=("%(levelname)s (%(module)s):" - " %(message)s"), level=logLevel) + return logging - logging.info("\n--------------------------------------------------------\n" - "Running "+ prog_name + " " +\ - str(datetime.now().strftime("%d/%m/%Y %H:%M"))+\ - "\n--------------------------------------------------------\n") - - return logging - -#------------------------------------------------------------------------------- +#-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - diff --git a/tests/tools/python/options/plotting_options.py b/tests/tools/python/options/plotting_options.py index 6c83787ed..97ccf21d2 100644 --- a/tests/tools/python/options/plotting_options.py +++ b/tests/tools/python/options/plotting_options.py @@ -1,51 +1,37 @@ -# Detray library, part of the ACTS project (R&D line) +#Detray library, part of the ACTS project(R& D line) # -# (c) 2024 CERN for the benefit of the ACTS project +#(c) 2024 CERN for the benefit of the ACTS project # -# Mozilla Public License Version 2.0 +#Mozilla Public License Version 2.0 -import argparse -import os -import sys +import argparse import os import sys -#------------------------------------------------------------------------------- -# Options parsing -#------------------------------------------------------------------------------- +#-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - +#Options parsing +#-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - -""" Parent parser that contains plotting options """ -def plotting_options(): + "" + " Parent parser that contains plotting options " + "" def plotting_options() : - parser = argparse.ArgumentParser(add_help=False) + parser = argparse.ArgumentParser(add_help = False) - parser.add_argument("--inputdir", "-i", - help=("Directory containing input data files."), - default = "./", type=str) - parser.add_argument("--outdir", "-o", - help=("Output directory for plots."), - default = "./plots/", type=str) - parser.add_argument("--output_format", "-of", - help=("Format of the plot files (svg|png|pdf)."), - default = "png", type=str) + parser.add_argument("--inputdir", "-i", help =("Directory containing input data files."), default = "./", type = str) parser.add_argument("--outdir", "-o", help =("Output directory for plots."), default = "./plots/", type = str) parser.add_argument("--output_format", "-of", help =("Format of the plot files (svg|png|pdf)."), default = "png", type = str) - return parser + return parser + "" + " Parse plotting options from commandline " + "" def parse_plotting_options(args, logging) : -""" Parse plotting options from commandline """ -def parse_plotting_options(args, logging): +#Check input path + if args.inputdir and not os.path.isdir(args.inputdir) : logging.error(f "Plot data director does not exist! ({args.inputdir})") sys.exit(1) - # Check input path - if args.inputdir and not os.path.isdir(args.inputdir): - logging.error(f"Plot data director does not exist! ({args.inputdir})") - sys.exit(1) +#Check output path + if not os.path.isdir(args.outdir) : os.mkdir(args.outdir, 0o755) - # Check output path - if not os.path.isdir(args.outdir): - os.mkdir(args.outdir, 0o755) + if args.output_format not in["svg", "png", "pdf"] : logging.error(f "Unknown output file format: {out_format}") sys.exit(1) - if not args.output_format in ["svg", "png", "pdf"]: - logging.error(f"Unknown output file format: {out_format}") - sys.exit(1) + return args.inputdir, args.outdir, args.output_format - return args.inputdir, args.outdir, args.output_format - -#------------------------------------------------------------------------------- +#-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - diff --git a/tests/tools/python/plotting/plot_helpers.py b/tests/tools/python/plotting/plot_helpers.py index a538dbc75..3200c8e96 100644 --- a/tests/tools/python/plotting/plot_helpers.py +++ b/tests/tools/python/plotting/plot_helpers.py @@ -1,31 +1,31 @@ -# Detray library, part of the ACTS project (R&D line) +#Detray library, part of the ACTS project(R& D line) # -# (c) 2023 CERN for the benefit of the ACTS project +#(c) 2023 CERN for the benefit of the ACTS project # -# Mozilla Public License Version 2.0 +#Mozilla Public License Version 2.0 from collections import namedtuple import numpy as np -#------------------------------------------------------------------------------- -# Common helpers for plotting measurement data -#------------------------------------------------------------------------------- +#-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - +#Common helpers for plotting measurement data +#-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - """ Filter the data in a data frame by a given prescription """ def filter_data(data, filter = lambda df: [], variables = []): - dataColl = [] + data_coll = [] - # Get global data +#Get global data if len(filter(data)) == 0: for var in variables: - dataColl.append(data[var].to_numpy(dtype = np.double)) + data_coll.append(data[var].to_numpy(dtype = np.double)) - # Filtered data +#Filtered data else: filtered = data.loc[filter] for var in variables: - dataColl.append(filtered[var].to_numpy(dtype = np.double)) + data_coll.append(filtered[var].to_numpy(dtype = np.double)) - return tuple(dataColl) + return tuple(data_coll) -#------------------------------------------------------------------------------- +#-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - diff --git a/tests/tools/python/plotting/pyplot_factory.py b/tests/tools/python/plotting/pyplot_factory.py index ee64943af..5eea1d457 100644 --- a/tests/tools/python/plotting/pyplot_factory.py +++ b/tests/tools/python/plotting/pyplot_factory.py @@ -1,15 +1,15 @@ -# Detray library, part of the ACTS project (R&D line) +#Detray library, part of the ACTS project(R& D line) # -# (c) 2023 CERN for the benefit of the ACTS project +#(c) 2023 CERN for the benefit of the ACTS project # -# Mozilla Public License Version 2.0 +#Mozilla Public License Version 2.0 -# python includes +#python includes from collections import namedtuple import math import numpy as np -# python based plotting +#python based plotting import matplotlib.pyplot as plt import matplotlib.colors as mcolors from matplotlib.ticker import ScalarFormatter @@ -25,14 +25,14 @@ 'font.family': 'serif', }) -# See: https://stackoverflow.com/questions/42142144/displaying-first-decimal-digit-in-scientific-notation-in-matplotlib +#See : https: // stackoverflow.com/questions/42142144/displaying-first-decimal-digit-in-scientific-notation-in-matplotlib class ScalarFormatterForceFormat(ScalarFormatter): def _set_format(self): self.format = "%3.1f" -#------------------------------------------------------------------------------- -# Global identifiers -#------------------------------------------------------------------------------- +#-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - +#Global identifiers +#-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - """ Pass plotting data between functions """ plt_data = namedtuple('plt_data', 'fig ax lgd data bins mu rms errors') @@ -44,18 +44,18 @@ def _set_format(self): def get_legend_options(): return legend_options('upper right', 1, 1, 1) -#------------------------------------------------------------------------------- -# Data Plotting -#------------------------------------------------------------------------------- +#-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - +#Data Plotting +#-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - """ Plotter interface that uses pyplot/matplotlib. """ class pyplot_factory(): - def __init__(self, outDir, logger, atlas_badge = ""): + def __init__(self, out_dir, logger, atlas_badge = ""): self.name = 'Pyplot', - self.outputPrefix = outDir + self.outputPrefix = out_dir self.logger = logger self.atlas_badge = atlas_badge self.badge_scale = 1.1 @@ -78,21 +78,21 @@ def add_legend(self, ax, options = get_legend_options()): calculated as the square root of the bin content. """ def hist1D(self, x, errors = None, w = None, - xLabel = 'x', yLabel = '', title = "", label = "", - xMin = None, xMax = None, bins = 1, + x_label = 'x', y_label = '', title = "", label = "", + x_min = None, x_max = None, bins = 1, color = 'tab:blue', alpha = 0.75, - setLog = False, + set_log = False, normalize = False, - showError = False, - showStats = True, - uOutlier = -1, - oOutlier = -1, + show_error = False, + show_stats = True, + u_outlier = -1, + o_outlier = -1, figsize = (8, 8), lgd_ops = get_legend_options(), layout = 'constrained', ax_formatter = None): - # Create fresh plot +#Create fresh plot fig = plt.figure(figsize = figsize, layout=layout) ax = fig.add_subplot(1, 1, 1) @@ -103,42 +103,42 @@ def hist1D(self, x, errors = None, w = None, ax.xaxis.set_major_formatter(ScalarFormatter(useOffset=False)) - # Do calculations on data in the range of the histogram - if not xMin is None and not xMax is None: - x = x[np.nonzero(x >= xMin)] - x = x[np.nonzero(x <= xMax)] +#Do calculations on data in the range of the histogram + if x_min is not None and x_max is not None: + x = x[np.nonzero(x >= x_min)] + x = x[np.nonzero(x <= x_max)] else: - xMin = np.min(x) - xMax = np.max(x) + x_min = np.min(x) + x_max = np.max(x) - # Display number of entries in under- and overflow bins - underflow = len(np.argwhere(x < xMin)) - overflow = len(np.argwhere(x > xMax)) - if uOutlier >= 0 or oOutlier >= 0: - underflow = underflow + uOutlier - overflow = overflow + oOutlier +#Display number of entries in under - and overflow bins + underflow = len(np.argwhere(x < x_min)) + overflow = len(np.argwhere(x > x_max)) + if u_outlier >= 0 or o_outlier >= 0: + underflow = underflow + u_outlier + overflow = overflow + o_outlier - # Nothing left to do +#Nothing left to do if len(x) == 0: self.logger.debug(rf" create hist: empty data {label}") return plt_data(fig, ax, None, None, None, None, None, None) - # Histogram normalization +#Histogram normalization scale = 1./len(x) if normalize else 1. - # Format the 'newline' +#Format the 'newline' newline = '\n' - # Name of the datat collection +#Name of the datat collection label_str = f'{label} ({len(x)} entries)' - if uOutlier >= 0 or oOutlier >= 0: + if u_outlier >= 0 or o_outlier >= 0: label_str = label_str + f'{newline} underflow: {underflow}' + \ f'{newline} overflow: {overflow}' - # Fill data - data, bins, hist = ax.hist(x, +#Fill data + data, bins, _ = ax.hist(x, weights = w, - range = (xMin, xMax), + range = (x_min, x_max), bins = bins, label = label_str, histtype = 'stepfilled', @@ -146,13 +146,13 @@ def hist1D(self, x, errors = None, w = None, facecolor = mcolors.to_rgba(color, alpha), edgecolor = color) - # Add some additional information - if showStats: +#Add some additional information + if show_stats: mean = np.mean(x, axis=0) - #rms = np.sqrt(np.mean(np.square(x))) +#rms = np.sqrt(np.mean(np.square(x))) stdev = np.std(x, axis=0) - # Create empty plot with blank marker containing the extra label +#Create empty plot with blank marker containing the extra label ax.plot([], [], ' ', label= rf'data:' rf'{newline}mean = {mean:.2e}' rf'{newline}stddev = {stdev:.2e}') @@ -160,28 +160,28 @@ def hist1D(self, x, errors = None, w = None, mean = None stdev = None - # Refine plot +#Refine plot ax.set_title(title) - ax.set_xlabel(xLabel) - ax.set_ylabel(yLabel) + ax.set_xlabel(x_label) + ax.set_ylabel(y_label) ax.grid(True, alpha = 0.25) - # Add legend +#Add legend lgd = self.add_legend(ax, lgd_ops) - # Adjust spacing in box +#Adjust spacing in box lgd.legend_handles[0].set_visible(False) - if showStats: + if show_stats: lgd.legend_handles[1].set_visible(False) for vpack in lgd._legend_handle_box.get_children(): for hpack in vpack.get_children(): hpack.get_children()[0].set_width(0) - # Calculate the bin error - binCenters = 0.5 * (bins[1:] + bins[:-1]) +#Calculate the bin error + bin_centers = 0.5 * (bins[1:] + bins[:-1]) err = np.sqrt(scale * data) if errors is None else errors - if showError or not errors is None: - ax.errorbar(binCenters, data, + if show_error or not errors is None: + ax.errorbar(bin_centers, data, yerr = err, fmt = '.', linestyle = '', @@ -189,55 +189,55 @@ def hist1D(self, x, errors = None, w = None, color = 'black', capsize = 2.5) - # Plot log scale - if setLog: +#Plot log scale + if set_log: ax.set_yscale('log') return plt_data(fig, ax, lgd, data, bins, mean, stdev, err) """ Add new data to an existing plot """ - def add_plot(self, oldHist, x, errors = None, w = None, + def add_plot(self, old_hist, x, errors = None, w = None, label = "", color = 'tab:orange', alpha = 0.75, normalize = False, - showError = False): + show_error = False): - # do calculations on data in the range of the histogram - xMin = np.min(oldHist.bins) - xMax = np.max(oldHist.bins) +#do calculations on data in the range of the histogram + x_min = np.min(old_hist.bins) + x_max = np.max(old_hist.bins) - x = x[np.nonzero(x >= xMin)] - x = x[np.nonzero(x <= xMax)] + x = x[np.nonzero(x >= x_min)] + x = x[np.nonzero(x <= x_max)] - # Nothing left to do - if len(x) == 0 or oldHist.data is None: +#Nothing left to do + if len(x) == 0 or old_hist.data is None: self.logger.debug(rf" add hist: empty data {label}") - return oldHist + return old_hist - # Add new data to old hist axis +#Add new data to old hist axis scale = 1./len(x) if normalize else 1. - data, bins, hist = oldHist.ax.hist(x = x, bins = oldHist.bins, + data, bins, _ = old_hist.ax.hist(x = x, bins = old_hist.bins, label = f"{label} ({len(x)} entries)", weights = w, histtype ='stepfilled', facecolor = mcolors.to_rgba(color, alpha), edgecolor = color) - # Update legend - lgd = oldHist.lgd +#Update legend + lgd = old_hist.lgd handles, labels = lgd.axes.get_legend_handles_labels() lgd._legend_box = None lgd._init_legend_box(handles, labels) lgd._set_loc(lgd._loc) lgd.set_title(lgd.get_title().get_text()) - # Calculate the bin error - binCenters = 0.5 * (bins[1:] + bins[:-1]) +#Calculate the bin error + bin_centers = 0.5 * (bins[1:] + bins[:-1]) err = np.sqrt(scale * data) if errors is None else errors - if showError or not errors is None: - oldHist.ax.errorbar(binCenters, data, + if show_error or errors is not None: + old_hist.ax.errorbar(bin_centers, data, yerr = err, fmt = '.', linestyle = '', @@ -245,20 +245,20 @@ def add_plot(self, oldHist, x, errors = None, w = None, color = 'black', capsize = 2.5) - return plt_data(oldHist.fig, oldHist.ax, oldHist.lgd, data, bins, None,\ - None, err) + return plt_data(old_hist.fig, old_hist.ax, old_hist.lgd, data, bins, \ + None, None, err) """ Plot the ratio of two histograms. The data is assumed to be uncorrelated. """ def add_ratio(self, nom, denom, label, - nBins = 20, + n_bins = 20, color = 'tab:red', - setLog = False, - showErrors = False): + set_log = False, + show_error = False): - # Resize figure +#Resize figure nom.fig.set_figheight(7) nom.fig.set_figwidth(8) @@ -268,7 +268,7 @@ def add_ratio(self, nom, denom, label, if len(nom.bins) != len(denom.bins): return plt_data(nom.fig, nom.ax, None, None, None, None, None, None) - # Remove ticks/labels that are already visible on the ratio plot +#Remove ticks / labels that are already visible on the ratio plot old_x_label = nom.ax.xaxis.get_label().get_text() nom.ax.tick_params(axis = 'x', which = 'both', @@ -277,58 +277,58 @@ def add_ratio(self, nom, denom, label, labelbottom = False) nom.ax.set_xlabel("") - # Don't print a warning when dividing by zero +#Don't print a warning when dividing by zero with np.errstate(divide='ignore'), np.errstate(invalid='ignore'): - # Filter out nan results from division by zero +#Filter out nan results from division by zero ratio = np.nan_to_num(nom.data/denom.data, nan = 0, posinf = 0) - # Calculate errors by Gaussian propagation - binCenters = 0.5 * (nom.bins[1:] + nom.bins[:-1]) +#Calculate errors by Gaussian propagation + bin_centers = 0.5 * (nom.bins[1:] + nom.bins[:-1]) n_data, d_data = (nom.data, denom.data) - # Gaussian approximation for large number of events in bin - # Note: Should be Clopper-Pearson +#Gaussian approximation for large number of events in bin +#Note : Should be Clopper - Pearson n_err, d_err = (nom.errors, denom.errors) errors = np.nan_to_num(np.sqrt(np.square(n_err / d_data) \ + np.square(n_data * d_err / np.square(d_data))), \ nan = 0, posinf = 0) - # create new axes on the bottom of the current axes - # The first argument of the new_vertical(new_horizontal) method is - # the height (width) of the axes to be created in inches. +#create new axes on the bottom of the current axes +#The first argument of the new_vertical(new_horizontal) method is +#the height(width) of the axes to be created in inches. divider = make_axes_locatable(nom.ax) ratio_plot = divider.append_axes("bottom", 1.2, pad = 0.2, sharex = nom.ax) - if showErrors: - ratio_plot.errorbar(binCenters, ratio, + if show_error: + ratio_plot.errorbar(bin_centers, ratio, yerr = errors, label = label, color = color, fmt = '.') else: - ratio_plot.plot(binCenters, ratio, + ratio_plot.plot(bin_centers, ratio, label = label, color = color, marker = '.', linestyle = '',) - # Refine plot +#Refine plot ratio_plot.set_xlabel(old_x_label) ratio_plot.set_ylabel("ratio") ratio_plot.grid(True, alpha = 0.25) - # Plot log scale - if setLog: +#Plot log scale + if set_log: ratio_plot.set_yscale('log') - # Add a horizontal blue line at y = 1. +#Add a horizontal blue line at y = 1. ratio_plot.axline((nom.bins[0], 1), (nom.bins[-1], 1), linewidth = 1, color ='b') - # Add legend - #lgd = self.add_legend(ratio_plot) - # Move the legend - #lgd.set_bbox_to_anchor((box_anchor_x, box_anchor_y)) +#Add legend +#lgd = self.add_legend(ratio_plot) +#Move the legend +#lgd.set_bbox_to_anchor((box_anchor_x, box_anchor_y)) nom.fig.set_size_inches((9, 9)) return plt_data(nom.fig, ratio_plot, None, None, None, None, None, @@ -340,87 +340,87 @@ def add_ratio(self, nom, denom, label, be used as weights per bin. """ def hist2D(self, x, y, z = None, - xLabel = 'x', yLabel = 'y', zLabel = '', title = "", label = "", - xMin = None, xMax = None, xBins = 1, - yMin = None, yMax = None, yBins = 1, + x_label = 'x', y_label = 'y', z_label = '', title = "", label = "", + x_min = None, x_max = None, xBins = 1, + y_min = None, y_max = None, yBins = 1, color = 'tab:blue', alpha = 0.75, - setLog = False, - showError = False, - showStats = True, + set_log = False, + show_error = False, + show_stats = True, figsize = (8, 6)): - # Create fresh plot +#Create fresh plot fig = plt.figure(figsize = figsize, layout='constrained') ax = fig.add_subplot(1, 1, 1) - # Do calculations on data in the range of the histogram - if not xMin is None and not xMax is None: - x = x[np.nonzero(x >= xMin)] - x = x[np.nonzero(x <= xMax)] +#Do calculations on data in the range of the histogram + if x_min is not None and x_max is not None: + x = x[np.nonzero(x >= x_min)] + x = x[np.nonzero(x <= x_max)] else: - xMin = np.min(x) - xMax = np.max(x) + x_min = np.min(x) + x_max = np.max(x) - if not yMin is None and not yMax is None: - y = y[np.nonzero(y >= yMin)] - y = y[np.nonzero(y <= yMax)] + if y_min is not None and y_max is not None: + y = y[np.nonzero(y >= y_min)] + y = y[np.nonzero(y <= y_max)] else: - yMin = np.min(y) - yMax = np.max(y) + y_min = np.min(y) + y_max = np.max(y) - # Nothing left to do +#Nothing left to do if len(x) == 0 or len(y) == 0: self.logger.debug(rf" create hist: empty data {label}") return plt_data(fig, ax, None, None, None, None, None, None) - # Fill data - data, xbins, ybins, hist = ax.hist2d( +#Fill data + data, _, _, hist = ax.hist2d( x, y, weights = z, - range = [(xMin, xMax), (yMin, yMax)], + range = [(x_min, x_max), (y_min, y_max)], bins = (xBins, yBins), label=f"{label} ({len(x)*len(y)} entries)", facecolor = mcolors.to_rgba(color, alpha), edgecolor = None, rasterized = True) - # Add some additional information - if showStats: - xMean = np.mean(x, axis=0) - xRms = np.sqrt(np.mean(np.square(x))) - yMean = np.mean(y, axis=0) - yRms = np.sqrt(np.mean(np.square(y))) +#Add some additional information + if show_stats: + x_mean = np.mean(x, axis=0) + x_rms = np.sqrt(np.mean(np.square(x))) + y_mean = np.mean(y, axis=0) + y_rms = np.sqrt(np.mean(np.square(y))) - # Create empty plot with blank marker containing the extra label +#Create empty plot with blank marker containing the extra label newline = '\n' - ax.plot([], [], ' ', label= rf'xMean = {xMean:.2e}' - rf'{newline}xRMS = {xRms:.2e}' - rf'yMean = {yMean:.2e}' - rf'{newline}yRMS = {yRms:.2e}') + ax.plot([], [], ' ', label= rf'xMean = {x_mean:.2e}' + rf'{newline}xRMS = {x_rms:.2e}' + rf'yMean = {y_mean:.2e}' + rf'{newline}yRMS = {y_rms:.2e}') - # Refine plot +#Refine plot ax.set_title(title) - ax.set_xlabel(xLabel) - ax.set_ylabel(yLabel) + ax.set_xlabel(x_label) + ax.set_ylabel(y_label) - # Add the colorbar - fig.colorbar(hist, label = zLabel) +#Add the colorbar + fig.colorbar(hist, label = z_label) return plt_data(fig, ax, None, data, None, None, None, None) """ Create a 2D scatter plot """ def scatter(self, x, y, - xLabel = "", yLabel = "", title = "", label = "", + x_label = "", y_label = "", title = "", label = "", color = 'tab:blue', alpha = 1, figsize = (8, 6), - showStats = lambda x, _: f"{len(x)} entries", + show_stats = lambda x, _: f"{len(x)} entries", lgd_ops = get_legend_options()): fig = plt.figure(figsize = figsize, layout='constrained') ax = fig.add_subplot(1, 1, 1) - # Create empty plot with blank marker containing the extra label - ax.plot([], [], ' ', label=showStats(x, y)) +#Create empty plot with blank marker containing the extra label + ax.plot([], [], ' ', label=show_stats(x, y)) scatter = ax.scatter(x, y, label = label, c = color, @@ -428,21 +428,21 @@ def scatter(self, x, y, alpha = alpha, rasterized=True) - # Refine plot +#Refine plot ax.set_title(title) - ax.set_xlabel(xLabel) - ax.set_ylabel(yLabel) + ax.set_xlabel(x_label) + ax.set_ylabel(y_label) ax.grid(True, alpha = 0.25) - # Add legend +#Add legend lgd = self.add_legend(ax, lgd_ops) - # Refine legend +#Refine legend lgd.legend_handles[0].set_visible(False) for handle in lgd.legend_handles[1:]: handle.set_sizes([40]) - # Adjust spacing in box +#Adjust spacing in box for vpack in lgd._legend_handle_box.get_children()[:1]: for hpack in vpack.get_children(): hpack.get_children()[0].set_width(0) @@ -451,29 +451,29 @@ def scatter(self, x, y, """ Add new data in a different color to a scatter plot """ - def highlight_region(self, plotData, x, y, color, label = ""): + def highlight_region(self, plot_data, x, y, color, label = ""): if label == "": - plotData.ax.scatter(x, y, c = color, alpha = 1, s = 0.1, + plot_data.ax.scatter(x, y, c = color, alpha = 1, s = 0.1, rasterized=True) else: - plotData.ax.scatter(x, y, c = color, alpha = 1, s = 0.1, + plot_data.ax.scatter(x, y, c = color, alpha = 1, s = 0.1, label=label, rasterized=True) - # Update legend - lgd = plotData.lgd +#Update legend + lgd = plot_data.lgd handles, labels = lgd.axes.get_legend_handles_labels() lgd._legend_box = None lgd._init_legend_box(handles, labels) lgd._set_loc(lgd._loc) lgd.set_title(lgd.get_title().get_text()) - # Refine legend +#Refine legend lgd.legend_handles[0].set_visible(False) for handle in lgd.legend_handles[1:]: handle.set_sizes([40]) - # Adjust spacing in box +#Adjust spacing in box for vpack in lgd._legend_handle_box.get_children()[:1]: for hpack in vpack.get_children(): hpack.get_children()[0].set_width(0) @@ -482,53 +482,51 @@ def highlight_region(self, plotData, x, y, color, label = ""): """ Fit a Gaussian to a 1D distribution and plot in the same figure. """ def fit_gaussian(self, dist): - # Calculate bin centers from bin edges +#Calculate bin centers from bin edges bins = dist.bins if bins is None: - # If fit failed, return empty result +#If fit failed, return empty result return None, None bin_centers = [(b1 + b2) / 2 for b1, b2 in zip(bins, bins[1:])] - # Gaussian distribution with all fit parameters +#Gaussian distribution with all fit parameters def gaussian(x, a, mean, sigma): return a / (math.sqrt(2*math.pi)*sigma) \ * np.exp(-((x - mean)**2 / (2 * sigma**2))) - # Gaussian fit +#Gaussian fit try: - from scipy.optimize import curve_fit - except ImportError: - print("WARNING: Could not find scipy: Skipping fit") - else: - try: - # Initial estimators - mean = np.mean(bin_centers, axis=0) + from scipy + .optimize import curve_fit except ImportError + : print("WARNING: Could not find scipy: Skipping fit") else : try : +#Initial estimators + mean = np.mean(bin_centers, axis=0) sigma = np.std(bin_centers, axis=0) a = np.max(dist.data) * (math.sqrt(2*math.pi)*sigma) - popt, pcov = curve_fit(gaussian, bin_centers, dist.data, p0 = [a, mean, sigma]) + popt, _ = curve_fit(gaussian, bin_centers, dist.data, p0 = [a, mean, sigma]) except RuntimeError: - # If fit failed, return empty result +#If fit failed, return empty result return None, None - # If the fitting was successful, plot the curve +#If the fitting was successful, plot the curve mu = float(f"{popt[1]:.2e}") # < formatting the sig. digits sig = float(f"{popt[2]:.2e}") newline = '\n' - # Generate points for the curve +#Generate points for the curve min_val = min(bin_centers) max_val = max(bin_centers) step = (max_val - min_val)/1000 x = [v for v in np.arange(min_val, max_val + step, step)] - fit = dist.ax.plot(x, gaussian(x, *popt), + dist.ax.plot(x, gaussian(x, *popt), label = rf'gaussian fit:{newline}$\mu$ = {mu:.2e}' + \ rf'{newline}$\sigma$ = {abs(sig):.2e}', \ color = 'tab:orange') - # Update legend +#Update legend lgd = dist.lgd handles, labels = lgd.axes.get_legend_handles_labels() lgd._legend_box = None @@ -536,7 +534,7 @@ def gaussian(x, a, mean, sigma): lgd._set_loc(lgd._loc) lgd.set_title(lgd.get_title().get_text()) - # Adjust spacing in box +#Adjust spacing in box lgd.legend_handles[0].set_visible(False) for vpack in lgd._legend_handle_box.get_children()[:-1]: for hpack in vpack.get_children(): @@ -549,29 +547,29 @@ def gaussian(x, a, mean, sigma): """ Safe a plot to disk """ def write_plot(self, plot_data, name = "plot", file_format = "svg", - outPrefix = "", dpi = 450): - if (outPrefix == ""): - fileName = self.outputPrefix + name + "." + file_format + out_prefix = "", dpi = 450): + if (out_prefix == ""): + file_name = self.outputPrefix + name + "." + file_format else: - fileName = outPrefix + name + "." + file_format + file_name = out_prefix + name + "." + file_format - plot_data.fig.savefig(fileName, dpi=dpi) + plot_data.fig.savefig(file_name, dpi=dpi) plt.close(plot_data.fig) """ Safe a plot as svg """ - def write_svg(self, plot_data, name, outPrefix = ""): + def write_svg(self, plot_data, name, out_prefix = ""): - self.write_plot(plot_data, name, ".svg", outPrefix) + self.write_plot(plot_data, name, ".svg", out_prefix) """ Safe a plot as pdf """ - def write_pdf(self, plot_data, name, outPrefix = ""): + def write_pdf(self, plot_data, name, out_prefix = ""): - self.write_plot(plot_data, name, ".pdf", outPrefix) + self.write_plot(plot_data, name, ".pdf", out_prefix) """ Safe a plot as png """ - def write_png(self, plot_data, name, outPrefix = ""): + def write_png(self, plot_data, name, out_prefix = ""): - self.write_plot(plot_data, name, ".png", outPrefix) + self.write_plot(plot_data, name, ".png", out_prefix) diff --git a/tests/tools/root/covariance_validation.C b/tests/tools/root/covariance_validation.C index 75f25d3ad..f71656e13 100644 --- a/tests/tools/root/covariance_validation.C +++ b/tests/tools/root/covariance_validation.C @@ -30,41 +30,41 @@ #include namespace { -double x_pos = 0.205f; -double title_x = x_pos; -double title_y = 0.8197f; -double y_gap = -0.0505; -double header_text_size = 0.055; -double geom_text_size = 0.0434028; - -double pull_fit_title_x = x_pos; -double pull_fit_title_y = 0.700f; -double pval_fit_title_x = x_pos; -double pval_fit_title_y = 0.700f; -double gaus_fit_par_x = x_pos; -double number_offset = 0.125; -double gaus_fit_par_y = pull_fit_title_y - 0.065; -double const_fit_par_x = x_pos; -double const_fit_par_y = pval_fit_title_y - 0.0459; -double tolerance_x = 0.7f; -double tolerance_y = 0.67f; -double pull_text_size = 0.0434028; -double pval_text_size = 0.0434028; -double pad_x0 = 0.00f; -double pad_x1 = 1.f; -double pad_y0 = 0.00f; -double pad_y1 = 1.f; -int label_font = 132; -double label_font_size = 0.055; -double titleX_font_size = 0.055; -double titleY_font_size = 0.055; -double x_title_offset = 1.25; -double y_title_offset = 1.34; -double y_title_offset_pval = 0.9; -double x_label_offset = 0.015; -double y_label_offset = 0.015; -double pull_min = -6.5f; -double pull_max = 6.5f; +const double x_pos = 0.205; +const double title_x = x_pos; +const double title_y = 0.8197; +const double y_gap = -0.0505; +const double header_text_size = 0.055; +const double geom_text_size = 0.0434028; + +const double pull_fit_title_x = x_pos; +const double pull_fit_title_y = 0.700; +const double pval_fit_title_x = x_pos; +const double pval_fit_title_y = 0.700; +const double gaus_fit_par_x = x_pos; +const double number_offset = 0.125; +const double gaus_fit_par_y = pull_fit_title_y - 0.065; +const double const_fit_par_x = x_pos; +const double const_fit_par_y = pval_fit_title_y - 0.0459; +const double tolerance_x = 0.7; +const double tolerance_y = 0.67; +const double pull_text_size = 0.0434028; +const double pval_text_size = 0.0434028; +const double pad_x0 = 0.00; +const double pad_x1 = 1.; +const double pad_y0 = 0.00; +const double pad_y1 = 1.; +const int label_font = 132; +const double label_font_size = 0.055; +const double titleX_font_size = 0.055; +const double titleY_font_size = 0.055; +const double x_title_offset = 1.25; +const double y_title_offset = 1.34; +const double y_title_offset_pval = 0.9; +const double x_label_offset = 0.015; +const double y_label_offset = 0.015; +const double pull_min = -6.5; +const double pull_max = 6.5; } // namespace @@ -588,4 +588,4 @@ void covariance_validation() { std::string wire_name = "wire_cov_transport"; auto wire_tree = get_tree(wire_name); read_tree(wire_tree, "perigee_to_perigee", wire_title, geom_title); -} \ No newline at end of file +} diff --git a/tests/tools/root/jacobian_comparison.C b/tests/tools/root/jacobian_comparison.C index 1ec5055d9..4d3f7c089 100755 --- a/tests/tools/root/jacobian_comparison.C +++ b/tests/tools/root/jacobian_comparison.C @@ -27,27 +27,27 @@ #include namespace { -double labelx_font_size = 0.055; -double labelx_offset = 0.0065; -double labely_font_size = 0.055; -double labely_offset = 0.01; -double title_font_size = 0.055; -double title_offset = 0.71; -double marker_size = 1.3875; -double legend_margin = 0.12; -int title_font = 132; -int label_font = 132; -int legend_font = 132; -double legend_font_size = 0.045; -double y_min = -15; -double y_max = 10; -double y_margin = 1; -double header_size = 0.05; -std::array ldim{0.59015, 0.62395, 0.942404, 0.880252}; -double pad_x0 = 0.00; -double pad_x1 = 1; -double pad_y0 = 0.00; -double pad_y1 = 1; +const double labelx_font_size = 0.055; +const double labelx_offset = 0.0065; +const double labely_font_size = 0.055; +const double labely_offset = 0.01; +const double title_font_size = 0.055; +const double title_offset = 0.71; +const double marker_size = 1.3875; +const double legend_margin = 0.12; +const int title_font = 132; +const int label_font = 132; +const int legend_font = 132; +const double legend_font_size = 0.045; +const double y_min = -15; +const double y_max = 10; +const double y_margin = 1; +const double header_size = 0.05; +const std::array ldim{0.59015, 0.62395, 0.942404, 0.880252}; +const double pad_x0 = 0.00; +const double pad_x1 = 1; +const double pad_y0 = 0.00; +const double pad_y1 = 1; } // namespace @@ -366,4 +366,4 @@ void jacobian_comparison() { wire_canvas->Draw(); wire_canvas->SaveAs(wire_pdf.c_str()); -} \ No newline at end of file +} diff --git a/tests/tools/root/jacobian_histogram.C b/tests/tools/root/jacobian_histogram.C index 3d792e112..2eb3c2388 100644 --- a/tests/tools/root/jacobian_histogram.C +++ b/tests/tools/root/jacobian_histogram.C @@ -30,36 +30,36 @@ namespace { -double x_pos1 = -13.4f; -double x_pos2 = 0.06f; -double y_pos1 = 2e5; -double y_pos2 = 6.75e4; - -// double title_x = x_pos; -// double title_y = 0.8197f; - -int label_font = 132; -double label_font_size = 0.055; -double header_text_size = 0.055; -double geom_text_size = 0.0434028; -double titleX_font_size = 0.05; -double titleY_font_size = 0.055; -double x_title_offset = 1.75; -double y_title_offset = 1.34; -double x_label_offset = 0.015; -double y_label_offset = 0.015; -int fill_style = 1001; -double color_alpha = 0.5; +const double x_pos1 = -13.4; +const double x_pos2 = 0.06; +const double y_pos1 = 2e5; +const double y_pos2 = 6.75e4; + +// const double title_x = x_pos; +// const double title_y = 0.8197; + +const int label_font = 132; +const double label_font_size = 0.055; +const double header_text_size = 0.055; +const double geom_text_size = 0.0434028; +const double titleX_font_size = 0.05; +const double titleY_font_size = 0.055; +const double x_title_offset = 1.75; +const double y_title_offset = 1.34; +const double x_label_offset = 0.015; +const double y_label_offset = 0.015; +const int fill_style = 1001; +const double color_alpha = 0.5; const std::array cdim{700, 600}; -double maximum = 1e6; +const double maximum = 1e6; -double pad_x0 = 0.00f; -double pad_x1 = 1.f; -double pad_y0 = 0.00f; -double pad_y1 = 1.f; +const double pad_x0 = 0.00; +const double pad_x1 = 1.; +const double pad_y0 = 0.00; +const double pad_y1 = 1.; -double bin_width = 0.2f; +const double bin_width = 0.2; } // namespace void draw_text(double x1, double y1, double y2, double s1, double s2, @@ -190,4 +190,4 @@ void jacobian_histogram(int num) { rdf.Snapshot("inhom_rect_material", root_name.c_str()); draw_histogram(root_name, num); -} \ No newline at end of file +} diff --git a/tests/tools/root/rk_tolerance_comparison.C b/tests/tools/root/rk_tolerance_comparison.C index 1e29652e8..9d64d4e97 100644 --- a/tests/tools/root/rk_tolerance_comparison.C +++ b/tests/tools/root/rk_tolerance_comparison.C @@ -28,34 +28,34 @@ #include namespace { -double step_title_x_offset = 1.4; -double step_title_x = 0.175; -double step_title_y = 0.835; -double step_ygap = -0.0505; -double x_label_offset = 0.015; -double x_margin = 1; -double y_label_offset = 0.015; -double rk_title_x_offset = 0.9; -double rk_title_offset_fraction = 0.0218; -double rk_title_y = 14.69; -double rk_ygap = -0.83; -double rk_header_text_size = 0.046; -double rk_geom_text_size = 0.0362903; -double step_header_text_size = 0.055; -double step_geom_text_size = 0.0434028; -double label_font_size_step = 0.055; -double title_font_size_step = 0.055; -double label_font_size_rk_tol = 0.046; -double title_font_size_rk_tol = 0.046; -int title_font = 132; -int label_font = 132; -int legend_font = 132; -double pad_x0 = 0.005f; -double pad_x1 = 1.f; -double pad_y0 = 0.005f; -double pad_y1 = 1.f; -double ymin = -2; -double ymax = 4.; +const double step_title_x_offset = 1.4; +const double step_title_x = 0.175; +const double step_title_y = 0.835; +const double step_ygap = -0.0505; +const double x_label_offset = 0.015; +const double x_margin = 1.; +const double y_label_offset = 0.015; +const double rk_title_x_offset = 0.9; +const double rk_title_offset_fraction = 0.0218; +const double rk_title_y = 14.69; +const double rk_ygap = -0.83; +const double rk_header_text_size = 0.046; +const double rk_geom_text_size = 0.0362903; +const double step_header_text_size = 0.055; +const double step_geom_text_size = 0.0434028; +const double label_font_size_step = 0.055; +const double title_font_size_step = 0.055; +const double label_font_size_rk_tol = 0.046; +const double title_font_size_rk_tol = 0.046; +const int title_font = 132; +const int label_font = 132; +const int legend_font = 132; +const double pad_x0 = 0.005; +const double pad_x1 = 1.; +const double pad_y0 = 0.005; +const double pad_y1 = 1.; +const double ymin = -2.; +const double ymax = 4.; std::array ldim{0.20985, 0.533, 0.87997, 0.939}; } // namespace @@ -454,4 +454,4 @@ void rk_tolerance_comparison(int min, int max) { draw_mean_step_size(wire_header, geom_header, x_vec, wire_mean_step_sizes); wire_canvas2->SaveAs(wire_mean_step_pdf.c_str()); -} \ No newline at end of file +} diff --git a/tests/tools/src/cpu/detector_display.cpp b/tests/tools/src/cpu/detector_display.cpp index 915922c5c..3267847f0 100644 --- a/tests/tools/src/cpu/detector_display.cpp +++ b/tests/tools/src/cpu/detector_display.cpp @@ -51,7 +51,9 @@ int main(int argc, char** argv) { // Specific options for this test po::options_description desc("\ndetray detector validation options"); - std::vector volumes, surfaces, window; + std::vector volumes; + std::vector surfaces; + std::vector window; desc.add_options()("outdir", po::value(), "Output directory for plots")( "context", po::value(), "Number of the geometry context")( @@ -163,13 +165,9 @@ int main(int argc, char** argv) { [[maybe_unused]] const auto [sf_zr_svg, mat_zr_svg] = il.draw_surfaces(surfaces, zr, gctx); detray::svgtools::write_svg(path / sf_zr_svg._id, {zr_axis, sf_zr_svg}); - /*detray::svgtools::write_svg(path / mat_zr_svg._id, - {zr_axis, mat_zr_svg});*/ [[maybe_unused]] const auto [sf_zphi_svg, mat_zphi_svg] = il.draw_surfaces(surfaces, zphi, gctx); - /*detray::svgtools::write_svg(path / sf_zphi_svg._id, - {zphi_axis, sf_zphi_svg});*/ detray::svgtools::write_svg(path / mat_zphi_svg._id, {zphi_axis, mat_zphi_svg}); } diff --git a/tests/unit_tests/cpu/builders/grid_builder.cpp b/tests/unit_tests/cpu/builders/grid_builder.cpp index 25b6f5100..f1679cfac 100644 --- a/tests/unit_tests/cpu/builders/grid_builder.cpp +++ b/tests/unit_tests/cpu/builders/grid_builder.cpp @@ -134,8 +134,6 @@ GTEST_TEST(detray_builders, grid_factory_static) { EXPECT_EQ(bin2[0], 3u); EXPECT_EQ(bin2[1], 5u); - // gr_builder.to_string(ann_gr); - // Build from parameters const std::vector bin_edges_z{-10.f, -8.f, -6.5f, -1.f, 4.f, 5.f, 6.f, 9.f}; @@ -213,9 +211,8 @@ GTEST_TEST(detray_builders, grid_factory_dynamic) { auto bin_indexer2D = detray::views::cartesian_product{ detray::views::iota{0u, 2u}, detray::views::iota{0u, 3u}}; dindex capacity{0u}; - for (const auto& bin_idx : bin_indexer2D) { - typename ann_grid_t::loc_bin_index mbin{std::get<0>(bin_idx), - std::get<1>(bin_idx)}; + for (const auto [bin_idx0, bin_idx1] : bin_indexer2D) { + typename ann_grid_t::loc_bin_index mbin{bin_idx0, bin_idx1}; capacities.emplace_back(mbin, ++capacity); } @@ -262,8 +259,6 @@ GTEST_TEST(detray_builders, grid_factory_dynamic) { EXPECT_EQ(ann_gr.size(), 2u); - // gr_builder.to_string(ann_gr); - // Build from parameters const std::vector bin_edges_z{-10.f, -8.f, -6.5f, -1.f, 4.f, 5.f, 6.f, 9.f}; @@ -273,9 +268,8 @@ GTEST_TEST(detray_builders, grid_factory_dynamic) { detray::views::iota{0u, 10u}, detray::views::iota{0u, 7u}}; capacity = 0u; capacities.clear(); - for (const auto& bin_idx : bin_indexer2D) { - typename ann_grid_t::loc_bin_index mbin{std::get<0>(bin_idx), - std::get<1>(bin_idx)}; + for (const auto [bin_idx0, bin_idx1] : bin_indexer2D) { + typename ann_grid_t::loc_bin_index mbin{bin_idx0, bin_idx1}; capacities.emplace_back(mbin, ++capacity); } @@ -367,7 +361,8 @@ GTEST_TEST(detray_builders, grid_builder) { // The cylinder portals are at the end of the surface range by construction const auto cyl_mask = mask{0u, 10.f, -500.f, 500.f}; - std::size_t n_phi_bins{5u}, n_z_bins{4u}; + std::size_t n_phi_bins{5u}; + std::size_t n_z_bins{4u}; // Build empty grid gbuilder.init_grid(cyl_mask, {n_phi_bins, n_z_bins}); diff --git a/tests/unit_tests/cpu/builders/homogeneous_material_builder.cpp b/tests/unit_tests/cpu/builders/homogeneous_material_builder.cpp index ce2f248b5..0c61a6e70 100644 --- a/tests/unit_tests/cpu/builders/homogeneous_material_builder.cpp +++ b/tests/unit_tests/cpu/builders/homogeneous_material_builder.cpp @@ -55,7 +55,6 @@ TEST(detray_builders, homogeneous_material_factory) { vecmem::host_memory_resource host_mr; detector_t d(host_mr); - // auto geo_ctx = typename detector_t::geometry_context{}; EXPECT_TRUE(d.material_store().template empty()); EXPECT_TRUE(d.material_store().template empty()); diff --git a/tests/unit_tests/cpu/core/mask_store.cpp b/tests/unit_tests/cpu/core/mask_store.cpp index 0856e8496..f4f47c7b3 100644 --- a/tests/unit_tests/cpu/core/mask_store.cpp +++ b/tests/unit_tests/cpu/core/mask_store.cpp @@ -26,13 +26,13 @@ GTEST_TEST(detray_core, static_mask_store) { using namespace detray; - enum mask_ids : unsigned int { - e_rectangle2 = 0, - e_trapezoid2 = 1, - e_annulus2 = 2, - e_cylinder3 = 3, - e_ring2 = 4, - e_single3 = 5, + enum class mask_ids : unsigned int { + e_rectangle2 = 0u, + e_trapezoid2 = 1u, + e_annulus2 = 2u, + e_cylinder3 = 3u, + e_ring2 = 4u, + e_single3 = 5u, }; using rectangle = mask; diff --git a/tests/unit_tests/cpu/core/typed_index.cpp b/tests/unit_tests/cpu/core/typed_index.cpp index 4c64ec9c4..6f30e3d0f 100644 --- a/tests/unit_tests/cpu/core/typed_index.cpp +++ b/tests/unit_tests/cpu/core/typed_index.cpp @@ -16,7 +16,7 @@ using namespace detray; namespace { /// Define mask types -enum mask_ids : unsigned int { +enum class mask_ids : unsigned int { e_unmasked = 0u, }; @@ -29,7 +29,7 @@ GTEST_TEST(detray_core, typed_index) { auto ti = index_t{}; // Check a empty barcode - EXPECT_EQ(ti.id(), static_cast((1u << 4) - 1u)); + EXPECT_EQ(ti.id(), static_cast((1u << 4) - 1u)); EXPECT_EQ(ti.index(), static_cast((1u << 28) - 1u)); ti.set_id(mask_ids::e_unmasked).set_index(42u); diff --git a/tests/unit_tests/cpu/detectors/telescope_detector.cpp b/tests/unit_tests/cpu/detectors/telescope_detector.cpp index 819ebc8cb..c74aba4f9 100644 --- a/tests/unit_tests/cpu/detectors/telescope_detector.cpp +++ b/tests/unit_tests/cpu/detectors/telescope_detector.cpp @@ -56,9 +56,9 @@ struct prop_state { : _stepping(t_in, field), _navigation(det) {} }; -static constexpr bool verbose_check = true; +inline constexpr bool verbose_check = true; -propagation::config prop_cfg{}; +const propagation::config prop_cfg{}; } // anonymous namespace diff --git a/tests/unit_tests/cpu/geometry/masks/annulus2D.cpp b/tests/unit_tests/cpu/geometry/masks/annulus2D.cpp index 65b63563d..f84918443 100644 --- a/tests/unit_tests/cpu/geometry/masks/annulus2D.cpp +++ b/tests/unit_tests/cpu/geometry/masks/annulus2D.cpp @@ -120,11 +120,7 @@ GTEST_TEST(detray_masks, annulus2D) { ASSERT_NEAR(loc_bounds[cuboid3D::e_max_y], 10.89317f + envelope, tol); ASSERT_NEAR(loc_bounds[cuboid3D::e_max_z], envelope, tol); - // TODO: Check against visualization - /*const auto centroid = ann2.centroid(); - ASSERT_NEAR(centroid[0], 0.f, tol); - ASSERT_NEAR(centroid[1], 0.f, tol); - ASSERT_NEAR(centroid[2], 0.f, tol);*/ + // TODO: Check centroid against visualization } /// This tests the inside/outside method of the mask diff --git a/tests/unit_tests/cpu/geometry/tracking_surface.cpp b/tests/unit_tests/cpu/geometry/tracking_surface.cpp index 25bed70a6..32236e94c 100644 --- a/tests/unit_tests/cpu/geometry/tracking_surface.cpp +++ b/tests/unit_tests/cpu/geometry/tracking_surface.cpp @@ -24,12 +24,12 @@ namespace { /// Define mask types -enum mask_ids : unsigned int { +enum class mask_ids : unsigned int { e_unmasked = 0u, }; /// Define material types -enum material_ids : unsigned int { +enum class material_ids : unsigned int { e_slab = 0u, }; diff --git a/tests/unit_tests/cpu/geometry/tracking_volume.cpp b/tests/unit_tests/cpu/geometry/tracking_volume.cpp index 2393c676d..37714b02c 100644 --- a/tests/unit_tests/cpu/geometry/tracking_volume.cpp +++ b/tests/unit_tests/cpu/geometry/tracking_volume.cpp @@ -24,16 +24,16 @@ namespace { // geo object ids for testing enum geo_objects : unsigned int { - e_sensitive = 0, - e_portal = 1, - e_size = 2, + e_sensitive = 0u, + e_portal = 1u, + e_size = 2u, e_all = e_size, }; // surface finder ids for testing -enum accel_ids : unsigned int { - e_default = 0, - e_grid = 1, +enum class accel_ids : unsigned int { + e_default = 0u, + e_grid = 1u, }; } // namespace diff --git a/tests/unit_tests/cpu/grid2/axis.cpp b/tests/unit_tests/cpu/grid2/axis.cpp index 235bf73e8..fc25ba845 100644 --- a/tests/unit_tests/cpu/grid2/axis.cpp +++ b/tests/unit_tests/cpu/grid2/axis.cpp @@ -178,7 +178,6 @@ GTEST_TEST(detray_grid2, irregular_closed_axis) { EXPECT_EQ(nonreg.bin(14), 4u); // Axis range access - binned (symmetric & asymmetric) - // darray zone00 = {0u, 0u}; darray zone01 = {0u, 1u}; darray zone11 = {1u, 1u}; darray zone22 = {2u, 2u}; diff --git a/tests/unit_tests/cpu/material/bethe_equation.cpp b/tests/unit_tests/cpu/material/bethe_equation.cpp index d685d256b..b1ea5fb0c 100644 --- a/tests/unit_tests/cpu/material/bethe_equation.cpp +++ b/tests/unit_tests/cpu/material/bethe_equation.cpp @@ -95,7 +95,7 @@ INSTANTIATE_TEST_SUITE_P( 0.1003f * unit::GeV, 3.082f))); /* -//@ NOTE: Test fails with He Gas and 10 GeV muons (18 % difference) +//@fixme: Test fails with He Gas and 10 GeV muons (18 % difference) INSTANTIATE_TEST_SUITE_P( detray_material_Bethe_1GeV_HeGas, EnergyLossBetheValidation, ::testing::Values(std::make_tuple(helium_gas(), muon(), @@ -181,9 +181,8 @@ INSTANTIATE_TEST_SUITE_P( ::testing::Values(std::make_tuple(argon_liquid(), muon(), 0.1003f * unit::GeV, 2.34f))); -/* -~6% discrepancy -INSTANTIATE_TEST_SUITE_P( +// @fixme ~6% discrepancy +/*INSTANTIATE_TEST_SUITE_P( detray_material_Bethe_1GeV_ArLiquid, EnergyLossBetheValidation, ::testing::Values(std::make_tuple(argon_liquid(), muon(), 1.101f * unit::GeV, 1.644f))); @@ -204,9 +203,8 @@ INSTANTIATE_TEST_SUITE_P( ::testing::Values(std::make_tuple(iron(), muon(), 0.1003f * unit::GeV, 2.274f))); -/* -// ~6% discrepancy -INSTANTIATE_TEST_SUITE_P( +// @fixme ~6% discrepancy +/*INSTANTIATE_TEST_SUITE_P( detray_material_Bethe_1GeV_Fe, EnergyLossBetheValidation, ::testing::Values(std::make_tuple(iron(), muon(), 1.101f * unit::GeV, 1.581f))); @@ -247,8 +245,8 @@ INSTANTIATE_TEST_SUITE_P( ::testing::Values(std::make_tuple(copper(), muon(), 0.1003f * unit::GeV, 2.198f))); -/* -INSTANTIATE_TEST_SUITE_P( +// @fixme +/*INSTANTIATE_TEST_SUITE_P( detray_material_Bethe_1GeV_Cu, EnergyLossBetheValidation, ::testing::Values(std::make_tuple(copper(), muon(), 1.101f * unit::GeV, 1.532f))); @@ -284,17 +282,15 @@ INSTANTIATE_TEST_SUITE_P( ::testing::Values(std::make_tuple(copper_with_ded(), muon(), 100.1f * unit::GeV, 2.155f))); -/* -// ~10% discrepancy -INSTANTIATE_TEST_SUITE_P( +// @fixme ~10% discrepancy +/*INSTANTIATE_TEST_SUITE_P( detray_material_Bethe_0p1GeV_CsI, EnergyLossBetheValidation, ::testing::Values(std::make_tuple(cesium_iodide(), muon(), 0.1003f * unit::GeV, 1.869f))); */ -/* -// ~10% discrepancy -INSTANTIATE_TEST_SUITE_P( +// @fixme ~10% discrepancy +/*INSTANTIATE_TEST_SUITE_P( detray_material_Bethe_1GeV_CsI, EnergyLossBetheValidation, ::testing::Values(std::make_tuple(cesium_iodide(), muon(), 1.101f * unit::GeV, 1.391f))); diff --git a/tests/unit_tests/cpu/navigation/intersection/intersection2D.cpp b/tests/unit_tests/cpu/navigation/intersection/intersection2D.cpp index c38589fe6..5a0975400 100644 --- a/tests/unit_tests/cpu/navigation/intersection/intersection2D.cpp +++ b/tests/unit_tests/cpu/navigation/intersection/intersection2D.cpp @@ -25,12 +25,12 @@ using namespace detray; namespace { /// Define mask types -enum mask_ids : unsigned int { +enum class mask_ids : unsigned int { e_unmasked = 0u, }; /// Define material types -enum material_ids : unsigned int { +enum class material_ids : unsigned int { e_slab = 0u, }; diff --git a/tests/unit_tests/cpu/navigation/intersection/intersection_kernel.cpp b/tests/unit_tests/cpu/navigation/intersection/intersection_kernel.cpp index 147f13266..655e5cc57 100644 --- a/tests/unit_tests/cpu/navigation/intersection/intersection_kernel.cpp +++ b/tests/unit_tests/cpu/navigation/intersection/intersection_kernel.cpp @@ -36,7 +36,7 @@ namespace { constexpr const scalar tol{1e-3f}; constexpr const scalar is_close{1e-5f}; -enum mask_ids : unsigned int { +enum class mask_ids : unsigned int { e_rectangle2 = 0u, e_trapezoid2 = 1u, e_annulus2 = 2u, @@ -44,7 +44,7 @@ enum mask_ids : unsigned int { e_cylinder2_portal = 4u, }; -enum material_ids : unsigned int { +enum class material_ids : unsigned int { e_slab = 0u, }; @@ -109,23 +109,30 @@ GTEST_TEST(detray_intersection, intersection_kernel_ray) { const cylinder_t cyl{0u, 5.f, -10.f, 10.f}; const cylinder_portal_t cyl_portal{0u, 1.f, 0.f, 1000.f}; - mask_store.template push_back(rect, empty_context{}); - mask_store.template push_back(trap, empty_context{}); - mask_store.template push_back(annl, empty_context{}); - mask_store.template push_back(cyl, empty_context{}); - mask_store.template push_back(cyl_portal, - empty_context{}); + mask_store.template push_back(rect, + empty_context{}); + mask_store.template push_back(trap, + empty_context{}); + mask_store.template push_back(annl, empty_context{}); + mask_store.template push_back(cyl, empty_context{}); + mask_store.template push_back( + cyl_portal, empty_context{}); // The surfaces and their store - surface_t rectangle_surface(0u, {e_rectangle2, 0u}, {e_slab, 0u}, 0u, + surface_t rectangle_surface(0u, {mask_ids::e_rectangle2, 0u}, + {material_ids::e_slab, 0u}, 0u, surface_id::e_sensitive); - surface_t trapezoid_surface(1u, {e_trapezoid2, 0u}, {e_slab, 1u}, 0u, + surface_t trapezoid_surface(1u, {mask_ids::e_trapezoid2, 0u}, + {material_ids::e_slab, 1u}, 0u, surface_id::e_sensitive); - surface_t annulus_surface(2u, {e_annulus2, 0u}, {e_slab, 2u}, 0u, + surface_t annulus_surface(2u, {mask_ids::e_annulus2, 0u}, + {material_ids::e_slab, 2u}, 0u, surface_id::e_sensitive); - surface_t cyl_surface(3u, {e_cylinder2, 0u}, {e_slab, 2u}, 0u, + surface_t cyl_surface(3u, {mask_ids::e_cylinder2, 0u}, + {material_ids::e_slab, 2u}, 0u, surface_id::e_passive); - surface_t cyl_portal_surface(4u, {e_cylinder2_portal, 0u}, {e_slab, 2u}, 0u, + surface_t cyl_portal_surface(4u, {mask_ids::e_cylinder2_portal, 0u}, + {material_ids::e_slab, 2u}, 0u, surface_id::e_portal); surface_container_t surfaces = {rectangle_surface, trapezoid_surface, annulus_surface, cyl_surface, @@ -167,19 +174,20 @@ GTEST_TEST(detray_intersection, intersection_kernel_ray) { vector3 global; - if (sfi_init[i].sf_desc.mask().id() == e_rectangle2) { + if (sfi_init[i].sf_desc.mask().id() == mask_ids::e_rectangle2) { global = rect.to_global_frame(transform_store.at(0), sfi_init[i].local); - } else if (sfi_init[i].sf_desc.mask().id() == e_trapezoid2) { + } else if (sfi_init[i].sf_desc.mask().id() == mask_ids::e_trapezoid2) { global = trap.to_global_frame(transform_store.at(1), sfi_init[i].local); - } else if (sfi_init[i].sf_desc.mask().id() == e_annulus2) { + } else if (sfi_init[i].sf_desc.mask().id() == mask_ids::e_annulus2) { global = annl.to_global_frame(transform_store.at(2), sfi_init[i].local); - } else if (sfi_init[i].sf_desc.mask().id() == e_cylinder2) { + } else if (sfi_init[i].sf_desc.mask().id() == mask_ids::e_cylinder2) { global = cyl.to_global_frame(transform_store.at(3), sfi_init[i].local); - } else if (sfi_init[i].sf_desc.mask().id() == e_cylinder2_portal) { + } else if (sfi_init[i].sf_desc.mask().id() == + mask_ids::e_cylinder2_portal) { global = cyl_portal.to_global_frame(transform_store.at(4), sfi_init[i].local); } @@ -247,16 +255,21 @@ GTEST_TEST(detray_intersection, intersection_kernel_helix) { const rectangle_t rect{0u, 10.f, 10.f}; const trapezoid_t trap{0u, 10.f, 20.f, 30.f, 1.f / 60.f}; const annulus_t annl{0u, 15.f, 55.f, 0.75f, 1.95f, 0.f, 2.f, -2.f}; - mask_store.template push_back(rect, empty_context{}); - mask_store.template push_back(trap, empty_context{}); - mask_store.template push_back(annl, empty_context{}); + mask_store.template push_back(rect, + empty_context{}); + mask_store.template push_back(trap, + empty_context{}); + mask_store.template push_back(annl, empty_context{}); // The surfaces and their store - const surface_t rectangle_surface(0u, {e_rectangle2, 0u}, {e_slab, 0u}, 0u, + const surface_t rectangle_surface(0u, {mask_ids::e_rectangle2, 0u}, + {material_ids::e_slab, 0u}, 0u, surface_id::e_sensitive); - const surface_t trapezoid_surface(1u, {e_trapezoid2, 0u}, {e_slab, 1u}, 0u, + const surface_t trapezoid_surface(1u, {mask_ids::e_trapezoid2, 0u}, + {material_ids::e_slab, 1u}, 0u, surface_id::e_sensitive); - const surface_t annulus_surface(2u, {e_annulus2, 0u}, {e_slab, 2u}, 0u, + const surface_t annulus_surface(2u, {mask_ids::e_annulus2, 0u}, + {material_ids::e_slab, 2u}, 0u, surface_id::e_sensitive); surface_container_t surfaces = {rectangle_surface, trapezoid_surface, annulus_surface}; @@ -283,13 +296,13 @@ GTEST_TEST(detray_intersection, intersection_kernel_helix) { vector3 global; - if (surface.mask().id() == e_rectangle2) { + if (surface.mask().id() == mask_ids::e_rectangle2) { global = rect.to_global_frame(transform_store.at(0), sfi_helix[0].local); - } else if (surface.mask().id() == e_trapezoid2) { + } else if (surface.mask().id() == mask_ids::e_trapezoid2) { global = trap.to_global_frame(transform_store.at(1), sfi_helix[0].local); - } else if (surface.mask().id() == e_annulus2) { + } else if (surface.mask().id() == mask_ids::e_annulus2) { global = annl.to_global_frame(transform_store.at(2), sfi_helix[0].local); } diff --git a/tests/unit_tests/cpu/propagator/actor_chain.cpp b/tests/unit_tests/cpu/propagator/actor_chain.cpp index 4fd8d4092..99c76210c 100644 --- a/tests/unit_tests/cpu/propagator/actor_chain.cpp +++ b/tests/unit_tests/cpu/propagator/actor_chain.cpp @@ -78,7 +78,8 @@ struct example_actor : detray::actor { template requires(!std::is_same_v) void operator()( state & /*example_state*/, const subj_state_t & /*subject_state*/, - const propagator_state_t & /*p_state*/) const {} + const propagator_state_t & /*p_state*/) const { /*Do nothing*/ + } }; using example_actor_t = example_actor; diff --git a/tests/unit_tests/cpu/propagator/covariance_transport.cpp b/tests/unit_tests/cpu/propagator/covariance_transport.cpp index f1322caeb..a8b696fb9 100644 --- a/tests/unit_tests/cpu/propagator/covariance_transport.cpp +++ b/tests/unit_tests/cpu/propagator/covariance_transport.cpp @@ -104,9 +104,6 @@ GTEST_TEST(detray_propagator, covariance_transport) { // Bound state after one turn propagation const auto& bound_param1 = propagation._stepping.bound_params(); - // const auto bound_vec0 = bound_param0; - // const auto bound_vec1 = bound_param1; - // Check if the track reaches the final surface EXPECT_EQ(bound_param0.surface_link().volume(), 4095u); EXPECT_EQ(bound_param0.surface_link().index(), 0u); diff --git a/tests/unit_tests/cpu/propagator/jacobian_line.cpp b/tests/unit_tests/cpu/propagator/jacobian_line.cpp index 93e84cc28..3dc4c9bc4 100644 --- a/tests/unit_tests/cpu/propagator/jacobian_line.cpp +++ b/tests/unit_tests/cpu/propagator/jacobian_line.cpp @@ -32,8 +32,9 @@ using matrix_type = test::matrix; constexpr scalar isclose{1e-5f}; -const scalar r{2.f}, hz{50.f}; -mask> ln{0u, r, hz}; +const scalar r{2.f}; +const scalar hz{50.f}; +const mask> ln{0u, r, hz}; GTEST_TEST(detray_propagator, jacobian_line2D_case1) { diff --git a/tests/unit_tests/cpu/propagator/rk_stepper.cpp b/tests/unit_tests/cpu/propagator/rk_stepper.cpp index 203e1ca37..cc241ca77 100644 --- a/tests/unit_tests/cpu/propagator/rk_stepper.cpp +++ b/tests/unit_tests/cpu/propagator/rk_stepper.cpp @@ -48,7 +48,7 @@ namespace { constexpr scalar_t tol{1e-3f}; -stepping::config step_cfg{}; +const stepping::config step_cfg{}; constexpr scalar_t step_size{1.f * unit::mm}; constexpr material vol_mat{ detray::cesium_iodide_with_ded()}; diff --git a/tests/unit_tests/cpu/simulation/landau_sampling.cpp b/tests/unit_tests/cpu/simulation/landau_sampling.cpp index 7c1da8a32..4f2ee0bae 100644 --- a/tests/unit_tests/cpu/simulation/landau_sampling.cpp +++ b/tests/unit_tests/cpu/simulation/landau_sampling.cpp @@ -27,7 +27,7 @@ class detray_simulation_LandauSamplingValidation : public ::testing::Test { using scalar_type = T; // Function for getting the corresponding index of a value - std::size_t get_index(const scalar_type value) { + std::size_t get_index(const scalar_type value) const { return static_cast((value - min) / bin_size); } @@ -80,7 +80,7 @@ TYPED_TEST(detray_simulation_LandauSamplingValidation, landau_sampling) { const std::size_t mpv_index = this->get_index(this->mpv); - const std::size_t max_index = static_cast( + const auto max_index = static_cast( std::distance(counter.begin(), std::ranges::max_element(counter))); // Bin range for i index: [ -2 + 0.05 * i, -2 + 0.05 * (i+1) ] diff --git a/tests/unit_tests/cpu/simulation/track_generators.cpp b/tests/unit_tests/cpu/simulation/track_generators.cpp index 58a3fd01c..e6162c512 100644 --- a/tests/unit_tests/cpu/simulation/track_generators.cpp +++ b/tests/unit_tests/cpu/simulation/track_generators.cpp @@ -137,7 +137,7 @@ GTEST_TEST(detray_simulation, uniform_track_generator_eta) { // Loop over eta values [-5, 5] for (std::size_t ieta{0u}; ieta < eta_steps; ++ieta) { - const scalar_t eta{-5.f + static_cast(ieta) * (10.f) / + const scalar_t eta{-5.f + static_cast(ieta) * 10.f / static_cast(eta_steps - 1u)}; const scalar_t theta{2.f * std::atan(std::exp(-eta))}; diff --git a/tests/unit_tests/cpu/utils/grids/grid_collection.cpp b/tests/unit_tests/cpu/utils/grids/grid_collection.cpp index 7e4c942a7..ccb1bcacb 100644 --- a/tests/unit_tests/cpu/utils/grids/grid_collection.cpp +++ b/tests/unit_tests/cpu/utils/grids/grid_collection.cpp @@ -151,7 +151,8 @@ GTEST_TEST(detray_grid, grid_collection_dynamic_bin) { bin_data.entries.resize(4u * 197u); int i{0}; - dindex entry{0u}, offset{0u}; + dindex entry{0u}; + dindex offset{0u}; attach<> attacher{}; for (auto& data : bin_data.bins) { diff --git a/tests/unit_tests/cpu/utils/hash_tree.cpp b/tests/unit_tests/cpu/utils/hash_tree.cpp index e4abfea97..f920406c8 100644 --- a/tests/unit_tests/cpu/utils/hash_tree.cpp +++ b/tests/unit_tests/cpu/utils/hash_tree.cpp @@ -31,7 +31,7 @@ void test_hash(std::size_t first_child, std::size_t n_prev_level, auto digest = hasher_t{}(digests[i], digests[i + 1u]); digests.push_back(digest); } - std::size_t n_level = + auto n_level = static_cast(0.5f * static_cast(n_prev_level)); // Need dummy leaf node for next level? if (n_level % 2u != 0u && n_level > 1u) { diff --git a/tests/unit_tests/cpu/utils/ranges.cpp b/tests/unit_tests/cpu/utils/ranges.cpp index 5fac6e6ba..7a4f4e001 100644 --- a/tests/unit_tests/cpu/utils/ranges.cpp +++ b/tests/unit_tests/cpu/utils/ranges.cpp @@ -254,9 +254,9 @@ GTEST_TEST(detray_utils, ranges_iota_interval) { // Unittest for the generation of a cartesian product (trivial case) GTEST_TEST(detray_utils, ranges_cartesian_product_trivial) { - const auto seq1 = detray::views::iota(dindex_range{1u, 2u}); - const auto seq2 = detray::views::iota(dindex_range{2u, 3u}); - const auto seq3 = detray::views::iota(dindex_range{3u, 4u}); + auto seq1 = detray::views::iota(dindex_range{1u, 2u}); + auto seq2 = detray::views::iota(dindex_range{2u, 3u}); + auto seq3 = detray::views::iota(dindex_range{3u, 4u}); detray::views::cartesian_product cp{std::move(seq1), std::move(seq2), std::move(seq3)}; @@ -292,9 +292,11 @@ GTEST_TEST(detray_utils, ranges_cartesian_product_trivial) { // Unittest for the generation of a cartesian product from a range of intervals GTEST_TEST(detray_utils, ranges_cartesian_product) { - const auto seq1 = detray::views::iota(dindex_range{2u, 7u}); - const auto seq2 = detray::views::iota(dindex_range{1u, 10u}); - const auto seq3 = detray::views::iota(dindex_range{3u, 4u}); + auto seq1 = detray::views::iota(dindex_range{2u, 7u}); + auto seq2 = detray::views::iota(dindex_range{1u, 10u}); + auto seq3 = detray::views::iota(dindex_range{3u, 4u}); + + const std::size_t size{seq1.size() * seq2.size() * seq3.size()}; detray::views::cartesian_product cp{std::move(seq1), std::move(seq2), std::move(seq3)}; @@ -315,7 +317,7 @@ GTEST_TEST(detray_utils, ranges_cartesian_product) { static_assert(std::is_destructible_v); // Test size - ASSERT_EQ(cp.size(), seq1.size() * seq2.size() * seq3.size()); + ASSERT_EQ(cp.size(), size); // Generate truth std::vector> result; diff --git a/tests/unit_tests/device/cuda/detector_cuda_kernel.hpp b/tests/unit_tests/device/cuda/detector_cuda_kernel.hpp index a74f5e97f..2d1353cb9 100644 --- a/tests/unit_tests/device/cuda/detector_cuda_kernel.hpp +++ b/tests/unit_tests/device/cuda/detector_cuda_kernel.hpp @@ -13,8 +13,6 @@ #include "detray/detectors/toy_metadata.hpp" #include "detray/utils/ranges.hpp" -using namespace detray; - namespace detray { // some useful type declarations diff --git a/tests/unit_tests/device/cuda/grids_grid2_cuda.cpp b/tests/unit_tests/device/cuda/grids_grid2_cuda.cpp index 77ffd045f..7851cb52a 100644 --- a/tests/unit_tests/device/cuda/grids_grid2_cuda.cpp +++ b/tests/unit_tests/device/cuda/grids_grid2_cuda.cpp @@ -119,7 +119,7 @@ TEST(grids_cuda, grid2_replace_populator_ci) { // Equality operator in complete populator does not work correctly in CUDA // (!constexpr) -/*TEST(grids_cuda, grid2_complete_populator) { +TEST(grids_cuda, grid2_complete_populator) { // memory resource vecmem::cuda::managed_memory_resource mng_mr; @@ -168,13 +168,12 @@ TEST(grids_cuda, grid2_replace_populator_ci) { static_cast(i_p + bin_id * data.size()); test::point3 tp({xaxis.min + gid * x_interval, - yaxis.min + gid * y_interval, - 0.5f}); + yaxis.min + gid * y_interval, 0.5f}); EXPECT_EQ(pt, tp); } } } -}*/ +} TEST(grids_cuda, grid2_attach_populator) { diff --git a/tests/unit_tests/device/cuda/grids_grid2_cuda_kernel.cu b/tests/unit_tests/device/cuda/grids_grid2_cuda_kernel.cu index 13d86ca80..707b150bb 100644 --- a/tests/unit_tests/device/cuda/grids_grid2_cuda_kernel.cu +++ b/tests/unit_tests/device/cuda/grids_grid2_cuda_kernel.cu @@ -99,12 +99,11 @@ void grid_replace_ci_test(grid2_view grid_view) { ---------------------------------------------------------------*/ // cuda kernel for grid_complete_test -/*__global__ void grid_complete_kernel( +__global__ void grid_complete_kernel( grid2_view grid_view) { // Let's try building the grid object - device_grid2_complete g2_device( - grid_view, test::point3{0.f, 0.f, 0.f}); + device_grid2_complete g2_device(grid_view, test::point3{0.f, 0.f, 0.f}); const auto& axis0 = g2_device.axis_p0(); const auto& axis1 = g2_device.axis_p1(); @@ -116,9 +115,8 @@ void grid_replace_ci_test(grid2_view grid_view) { for (int i_p = 0; i_p < n_points; i_p++) { auto gid = i_p + bin_id * n_points; - auto pt = test::point3{ - axis0.min + gid * x_interval, axis1.min + gid * y_interval, 0.5f}; - // printf("%f %f %f \n", pt[0], pt[1], pt[2]); + auto pt = test::point3{axis0.min + gid * x_interval, + axis1.min + gid * y_interval, 0.5f}; g2_device.populate(threadIdx.x, threadIdx.y, std::move(pt)); } } @@ -138,7 +136,7 @@ void grid_complete_test(grid2_view grid_view) { // cuda error check DETRAY_CUDA_ERROR_CHECK(cudaGetLastError()); DETRAY_CUDA_ERROR_CHECK(cudaDeviceSynchronize()); -}*/ +} /*--------------------------------------------------------- read test function for grid with attach populator diff --git a/tests/unit_tests/device/cuda/mask_store_cuda.cpp b/tests/unit_tests/device/cuda/mask_store_cuda.cpp index dc8c33569..7a5dc2b60 100644 --- a/tests/unit_tests/device/cuda/mask_store_cuda.cpp +++ b/tests/unit_tests/device/cuda/mask_store_cuda.cpp @@ -17,6 +17,9 @@ // System include(s) #include #include +#include + +using namespace detray; TEST(mask_store_cuda, mask_store) { @@ -26,50 +29,53 @@ TEST(mask_store_cuda, mask_store) { // Types must be sorted according to their id (here: masks/mask_identifier) host_store_type store(mng_mr); - ASSERT_TRUE(store.template empty()); - ASSERT_TRUE(store.template empty()); - ASSERT_TRUE(store.template empty()); - ASSERT_TRUE(store.template empty()); - ASSERT_TRUE(store.template empty()); - ASSERT_TRUE(store.template empty()); - - store.template emplace_back(empty_context{}, 0u, 1.0f, 2.0f); - store.template emplace_back(empty_context{}, 0u, 0.5f, 1.5f, - 4.0f, 1.f / 8.f); - store.template emplace_back(empty_context{}, 0u, 1.0f, 10.0f); - store.template emplace_back(empty_context{}, 0u, 1.f, 0.5f, - 2.0f); - store.template emplace_back(empty_context{}, 0u, 1.f, 2.f, 3.f, - 4.f, 5.f, 6.f, 7.f); - - ASSERT_FALSE(store.empty()); - ASSERT_FALSE(store.empty()); - ASSERT_FALSE(store.empty()); - ASSERT_FALSE(store.empty()); - ASSERT_TRUE(store.empty()); - ASSERT_FALSE(store.empty()); - - /** Generate random points for test **/ + ASSERT_TRUE(store.template empty()); + ASSERT_TRUE(store.template empty()); + ASSERT_TRUE(store.template empty()); + ASSERT_TRUE(store.template empty()); + ASSERT_TRUE(store.template empty()); + ASSERT_TRUE(store.template empty()); + + store.template emplace_back(empty_context{}, 0u, + 1.0f, 2.0f); + store.template emplace_back( + empty_context{}, 0u, 0.5f, 1.5f, 4.0f, 1.f / 8.f); + store.template emplace_back(empty_context{}, 0u, 1.0f, + 10.0f); + store.template emplace_back(empty_context{}, 0u, 1.f, + 0.5f, 2.0f); + store.template emplace_back( + empty_context{}, 0u, 1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f); + + ASSERT_FALSE(store.empty()); + ASSERT_FALSE(store.empty()); + ASSERT_FALSE(store.empty()); + ASSERT_FALSE(store.empty()); + ASSERT_TRUE(store.empty()); + ASSERT_FALSE(store.empty()); + + // Generate random points for test vecmem::vector input_point3(n_points, &mng_mr); + std::random_device rd; + std::mt19937_64 gen(rd()); + std::uniform_real_distribution> dist(0.f, 9.9f); for (unsigned int i = 0u; i < n_points; i++) { - point3 rand_point3 = {static_cast(rand() % 100) / 10.f, - static_cast(rand() % 100) / 10.f, - static_cast(rand() % 100) / 10.f}; + point3 rand_point3 = {dist(gen), dist(gen), dist(gen)}; input_point3[i] = rand_point3; } - /** host output for intersection status **/ + // host output for intersection status vecmem::jagged_vector output_host(5, &mng_mr); - /** get mask objects **/ - const auto& rectangle_mask = store.get()[0]; - const auto& trapezoid_mask = store.get()[0]; - const auto& ring_mask = store.get()[0]; - const auto& cylinder_mask = store.get()[0]; - const auto& annulus_mask = store.get()[0]; + // get mask objects + const auto& rectangle_mask = store.get()[0]; + const auto& trapezoid_mask = store.get()[0]; + const auto& ring_mask = store.get()[0]; + const auto& cylinder_mask = store.get()[0]; + const auto& annulus_mask = store.get()[0]; - /** get host results from is_inside function **/ + // get host results from is_inside function for (unsigned int i = 0u; i < n_points; i++) { output_host[0].push_back(rectangle_mask.is_inside(input_point3[i])); output_host[1].push_back(trapezoid_mask.is_inside(input_point3[i])); @@ -78,10 +84,10 @@ TEST(mask_store_cuda, mask_store) { output_host[4].push_back(annulus_mask.is_inside(input_point3[i])); } - /** Helper object for performing memory copies. **/ + // Helper object for performing memory copies vecmem::cuda::copy copy; - /** device output for intersection status **/ + // device output for intersection status vecmem::data::jagged_vector_buffer output_buffer( {n_points, n_points, n_points, n_points, n_points}, mng_mr, nullptr, vecmem::data::buffer_type::resizable); @@ -89,16 +95,15 @@ TEST(mask_store_cuda, mask_store) { copy.setup(output_buffer); auto input_point3_data = vecmem::get_data(input_point3); - // auto input_point3_data = vecmem::get_data(input_point3); auto store_data = get_data(store); - /** run the kernel **/ + // run the kernel mask_test(store_data, input_point3_data, output_buffer); vecmem::jagged_vector output_device(&mng_mr); copy(output_buffer, output_device); - /** Compare the values **/ + // Compare the values for (unsigned int i = 0u; i < n_points; i++) { ASSERT_EQ(output_host[0][i], output_device[0][i]); ASSERT_EQ(output_host[0][i], output_device[0][i]); diff --git a/tests/unit_tests/device/cuda/mask_store_cuda_kernel.cu b/tests/unit_tests/device/cuda/mask_store_cuda_kernel.cu index f96b9df11..fcdb1fb1b 100644 --- a/tests/unit_tests/device/cuda/mask_store_cuda_kernel.cu +++ b/tests/unit_tests/device/cuda/mask_store_cuda_kernel.cu @@ -19,20 +19,20 @@ __global__ void mask_test_kernel( vecmem::data::vector_view input_point3_data, vecmem::data::jagged_vector_view output_data) { - /** get mask store **/ + // get mask store device_store_type store(store_data); - /** get mask objects **/ + // get mask objects vecmem::device_vector input_point3(input_point3_data); vecmem::jagged_device_vector output_device(output_data); - const auto& rectangle_mask = store.get()[0]; - const auto& trapezoid_mask = store.get()[0]; - const auto& ring_mask = store.get()[0]; - const auto& cylinder_mask = store.get()[0]; - const auto& annulus_mask = store.get()[0]; + const auto& rectangle_mask = store.get()[0]; + const auto& trapezoid_mask = store.get()[0]; + const auto& ring_mask = store.get()[0]; + const auto& cylinder_mask = store.get()[0]; + const auto& annulus_mask = store.get()[0]; - /** get device results from is_inside function **/ + // get device results from is_inside function for (int i = 0; i < n_points; i++) { output_device[0].push_back(rectangle_mask.is_inside(input_point3[i])); output_device[1].push_back(trapezoid_mask.is_inside(input_point3[i])); diff --git a/tests/unit_tests/device/cuda/mask_store_cuda_kernel.hpp b/tests/unit_tests/device/cuda/mask_store_cuda_kernel.hpp index 18b9baa51..ff16e7de8 100644 --- a/tests/unit_tests/device/cuda/mask_store_cuda_kernel.hpp +++ b/tests/unit_tests/device/cuda/mask_store_cuda_kernel.hpp @@ -1,6 +1,6 @@ /** Detray library, part of the ACTS project (R&D line) * - * (c) 2021 CERN for the benefit of the ACTS project + * (c) 2021-2024 CERN for the benefit of the ACTS project * * Mozilla Public License Version 2.0 */ @@ -19,15 +19,13 @@ #include #include -using namespace detray; +namespace detray { using algebra_t = ALGEBRA_PLUGIN; -using point3 = dpoint3D; -using transform3 = dtransform3D; +using point3 = detray::dpoint3D; +using transform3 = detray::dtransform3D; const int n_points = 1000; -namespace detray { - using annulus = mask; using cylinder = mask; using rectangle = mask; @@ -35,9 +33,8 @@ using ring = mask; using single = mask>; using trapezoid = mask; -/** Enumerate different mask types for convenience - **/ -enum mask_ids : unsigned int { +/// Enumerate different mask types for convenience +enum class mask_ids : unsigned int { e_rectangle2 = 0u, e_trapezoid2 = 1u, e_ring2 = 2u, diff --git a/tests/unit_tests/device/cuda/navigator_cuda.cpp b/tests/unit_tests/device/cuda/navigator_cuda.cpp index e76719237..0a5713beb 100644 --- a/tests/unit_tests/device/cuda/navigator_cuda.cpp +++ b/tests/unit_tests/device/cuda/navigator_cuda.cpp @@ -19,8 +19,12 @@ // GTest include(s) #include +using namespace detray; + TEST(navigator_cuda, navigator) { + using scalar_t = dscalar; + // Helper object for performing memory copies. vecmem::cuda::copy copy; diff --git a/tests/unit_tests/device/cuda/navigator_cuda_kernel.hpp b/tests/unit_tests/device/cuda/navigator_cuda_kernel.hpp index eb000a86f..c0cf7c912 100644 --- a/tests/unit_tests/device/cuda/navigator_cuda_kernel.hpp +++ b/tests/unit_tests/device/cuda/navigator_cuda_kernel.hpp @@ -18,11 +18,10 @@ // Detray test include(s) #include "detray/test/utils/simulation/event_generator/track_generators.hpp" -using namespace detray; +namespace detray { using algebra_t = ALGEBRA_PLUGIN; using point3 = dpoint3D; -using scalar_t = dscalar; // some useful type declarations using detector_host_t = detector; @@ -43,7 +42,7 @@ constexpr std::size_t n_edc_layers{3u}; constexpr unsigned int theta_steps{100u}; constexpr unsigned int phi_steps{100u}; -constexpr scalar_t pos_diff_tolerance{1e-3f}; +constexpr dscalar pos_diff_tolerance{1e-3f}; // dummy propagator state template @@ -52,8 +51,6 @@ struct prop_state { navigation_t _navigation; }; -namespace detray { - /// test function for navigator with single state void navigator_test( typename detector_host_t::view_type det_data, propagation::config& cfg, diff --git a/tests/unit_tests/device/cuda/sf_finders_grid_cuda.cpp b/tests/unit_tests/device/cuda/sf_finders_grid_cuda.cpp index 3f701e274..2c0e282a0 100644 --- a/tests/unit_tests/device/cuda/sf_finders_grid_cuda.cpp +++ b/tests/unit_tests/device/cuda/sf_finders_grid_cuda.cpp @@ -37,7 +37,8 @@ void test_entry_collection(const content_t& bin_content, // Running indices for the points in the collection and the elements of a // single point3 - unsigned int i = 0u, j = 0u; + unsigned int i = 0u; + unsigned int j = 0u; for (const auto& entry : bin_content) { const auto& expt_entry = expected[i++]; j = 0u; diff --git a/tests/unit_tests/device/cuda/transform_store_cuda.cpp b/tests/unit_tests/device/cuda/transform_store_cuda.cpp index 066fb729d..2a03dcb79 100644 --- a/tests/unit_tests/device/cuda/transform_store_cuda.cpp +++ b/tests/unit_tests/device/cuda/transform_store_cuda.cpp @@ -21,6 +21,8 @@ // System include(s) #include +using namespace detray; + TEST(transform_store_cuda, transform_store) { using algebra_t = ALGEBRA_PLUGIN; diff --git a/tests/unit_tests/device/cuda/transform_store_cuda_kernel.hpp b/tests/unit_tests/device/cuda/transform_store_cuda_kernel.hpp index 480b34650..112150885 100644 --- a/tests/unit_tests/device/cuda/transform_store_cuda_kernel.hpp +++ b/tests/unit_tests/device/cuda/transform_store_cuda_kernel.hpp @@ -14,8 +14,6 @@ // Vecmem include(s) #include -using namespace detray; - namespace detray { using algebra_t = ALGEBRA_PLUGIN; diff --git a/tutorials/include/detray/tutorial/square_surface_generator.hpp b/tutorials/include/detray/tutorial/square_surface_generator.hpp index 8c2425552..076ec40b0 100644 --- a/tutorials/include/detray/tutorial/square_surface_generator.hpp +++ b/tutorials/include/detray/tutorial/square_surface_generator.hpp @@ -74,7 +74,7 @@ class square_surface_generator final // The material will be added in a later step constexpr auto no_material = surface_t::material_id::e_none; // In case the surfaces container is prefilled with other surfaces - dindex surfaces_offset = static_cast(surfaces.size()); + auto surfaces_offset = static_cast(surfaces.size()); constexpr auto invalid_src_link{detail::invalid_value()};