diff --git a/localization/autoware_ndt_scan_matcher/CMakeLists.txt b/localization/autoware_ndt_scan_matcher/CMakeLists.txt index dbbe71129f..cce3cfd0d9 100644 --- a/localization/autoware_ndt_scan_matcher/CMakeLists.txt +++ b/localization/autoware_ndt_scan_matcher/CMakeLists.txt @@ -32,7 +32,6 @@ include_directories(${PCL_INCLUDE_DIRS}) ament_auto_add_library(multigrid_ndt_omp SHARED src/ndt_omp/multi_voxel_grid_covariance_omp.cpp src/ndt_omp/multigrid_ndt_omp.cpp - src/ndt_omp/estimate_covariance.cpp ) target_link_libraries(multigrid_ndt_omp ${PCL_LIBRARIES}) @@ -42,8 +41,11 @@ else() message(WARNING "OpenMP not found") endif() -ament_auto_add_library(${PROJECT_NAME} SHARED +# NO_TARGET_LINK_LIBRARIES: the node does not use ndt_omp. Only the backend "ndt_omp" does. +ament_auto_add_library(${PROJECT_NAME} SHARED NO_TARGET_LINK_LIBRARIES src/map_update_module.cpp + src/ndt_backend_loader.cpp + src/ndt_omp/estimate_covariance.cpp src/ndt_scan_matcher_core.cpp src/ndt_scan_matcher_helper.cpp src/particle.cpp @@ -51,7 +53,7 @@ ament_auto_add_library(${PROJECT_NAME} SHARED ) link_directories(${PCL_LIBRARY_DIRS}) -target_link_libraries(${PROJECT_NAME} ${PCL_LIBRARIES} multigrid_ndt_omp) +target_link_libraries(${PROJECT_NAME} ${PCL_LIBRARIES}) autoware_agnocast_wrapper_register_node(${PROJECT_NAME} PLUGIN "autoware::ndt_scan_matcher::NDTScanMatcher" @@ -60,7 +62,52 @@ autoware_agnocast_wrapper_register_node(${PROJECT_NAME} AGNOCAST_EXECUTOR AgnocastOnlyCallbackIsolatedExecutor ) +# The NDT backend "ndt_omp". The node loads it with pluginlib, so no other library may link it. It +# is a plain library: ament_auto exports every library that ament_auto_add_library() adds, and it +# links them into the later libraries and tests of this package and into the packages that depend on +# it. +add_library(${PROJECT_NAME}_omp_backend SHARED + src/omp_ndt_backend.cpp +) +target_link_libraries(${PROJECT_NAME}_omp_backend multigrid_ndt_omp ${PCL_LIBRARIES}) +ament_target_dependencies(${PROJECT_NAME}_omp_backend autoware_ndt_scan_matcher_common pluginlib) +install(TARGETS ${PROJECT_NAME}_omp_backend + LIBRARY DESTINATION lib +) +pluginlib_export_plugin_description_file(autoware_ndt_scan_matcher_common plugins.xml) + if(BUILD_TESTING) + # Three test backends in an install prefix inside the build directory, for the tests of the + # error messages. pluginlib finds them only in a test that has this prefix in AMENT_PREFIX_PATH. + set(test_backend_prefix ${CMAKE_CURRENT_BINARY_DIR}/test_ndt_backend_prefix) + set(test_backend_index ${test_backend_prefix}/share/ament_index/resource_index) + file(WRITE ${test_backend_index}/packages/test_ndt_backend "") + file(WRITE + ${test_backend_index}/autoware_ndt_scan_matcher_common__pluginlib__plugin/test_ndt_backend + "share/test_ndt_backend/test_ndt_backend_plugins.xml\n") + file(WRITE ${test_backend_prefix}/share/test_ndt_backend/package.xml + "test_ndt_backend\n") + # configure_file() copies the file again when it changes. + # cspell: ignore COPYONLY + configure_file(test/test_ndt_backend_plugins.xml + ${test_backend_prefix}/share/test_ndt_backend/test_ndt_backend_plugins.xml COPYONLY) + foreach(variant constructor_throws initialize_throws other_abi) + add_library(test_ndt_backend_${variant} MODULE test/test_ndt_backend.cpp) + ament_target_dependencies(test_ndt_backend_${variant} + autoware_ndt_scan_matcher_common pluginlib) + # $<1:...> keeps a multi-config generator from adding a directory for each configuration. + set_target_properties(test_ndt_backend_${variant} PROPERTIES + LIBRARY_OUTPUT_DIRECTORY $<1:${test_backend_prefix}/lib>) + endforeach() + target_compile_definitions(test_ndt_backend_constructor_throws PRIVATE + TEST_NDT_BACKEND_CONSTRUCTOR_THROWS) + target_compile_definitions(test_ndt_backend_initialize_throws PRIVATE + TEST_NDT_BACKEND_INITIALIZE_THROWS) + # The other heap allocator of Eigen. test_ndt_backend_loader skips its test in a build where + # this definition does not change the allocator. + target_compile_definitions(test_ndt_backend_other_abi PRIVATE + EIGEN_MALLOC_ALREADY_ALIGNED=0) + if(NOT (DEFINED ENV{ENABLE_AGNOCAST} AND "$ENV{ENABLE_AGNOCAST}" STREQUAL "1")) add_launch_test( test/test_ndt_scan_matcher_launch.py @@ -100,7 +147,9 @@ if(BUILD_TESTING) ament_add_ros_isolated_gtest(test_ndt_scan_matcher_characteristics test/test_ndt_scan_matcher_characteristics.cpp TIMEOUT "600" + APPEND_ENV AMENT_PREFIX_PATH=${test_backend_prefix} ) + add_dependencies(test_ndt_scan_matcher_characteristics test_ndt_backend_initialize_throws) target_link_libraries(test_ndt_scan_matcher_characteristics ${PROJECT_NAME}) ament_target_dependencies(test_ndt_scan_matcher_characteristics ament_index_cpp rcl_yaml_param_parser) @@ -110,7 +159,7 @@ if(BUILD_TESTING) ament_auto_add_gtest(test_estimate_covariance test/test_estimate_covariance.cpp ) - target_link_libraries(test_estimate_covariance multigrid_ndt_omp ${PCL_LIBRARIES}) + target_link_libraries(test_estimate_covariance ${PROJECT_NAME} ${PCL_LIBRARIES}) ament_auto_add_gtest(test_ndt_scan_matcher_helper test/test_ndt_scan_matcher_helper.cpp @@ -126,7 +175,23 @@ if(BUILD_TESTING) ament_auto_add_gtest(test_map_update_module test/test_map_update_module.cpp ) - target_link_libraries(test_map_update_module ${PROJECT_NAME} multigrid_ndt_omp ${PCL_LIBRARIES}) + target_link_libraries(test_map_update_module ${PROJECT_NAME} ${PCL_LIBRARIES}) + + # The OMP backend against ndt_omp, and its copies. + ament_auto_add_gtest(test_omp_ndt_backend + test/test_omp_ndt_backend.cpp + ) + target_include_directories(test_omp_ndt_backend PRIVATE src) + target_link_libraries(test_omp_ndt_backend ${PROJECT_NAME}_omp_backend ${PCL_LIBRARIES}) + + # pluginlib loads the backend library here. The test does not link it. + ament_auto_add_gtest(test_ndt_backend_loader + test/test_ndt_backend_loader.cpp + APPEND_ENV AMENT_PREFIX_PATH=${test_backend_prefix} + ) + target_link_libraries(test_ndt_backend_loader ${PROJECT_NAME} ${CMAKE_DL_LIBS}) + add_dependencies(test_ndt_backend_loader + test_ndt_backend_constructor_throws test_ndt_backend_other_abi) endif() autoware_ament_auto_package( diff --git a/localization/autoware_ndt_scan_matcher/README.md b/localization/autoware_ndt_scan_matcher/README.md index 4cde8f97d6..e390982e1b 100644 --- a/localization/autoware_ndt_scan_matcher/README.md +++ b/localization/autoware_ndt_scan_matcher/README.md @@ -84,6 +84,14 @@ One optional function is regularization. Please see the regularization chapter i {{ json_to_markdown("localization/autoware_ndt_scan_matcher/schema/sub/covariance.json") }} +## NDT backends + +The node does the NDT computations through a backend, which it loads with [pluginlib](https://github.com/ros/pluginlib). The parameter `ndt.backend` sets the name of the backend. This package has one backend, `ndt_omp`, which is ndt_omp on the CPU. The parameter file of this package sets `ndt_omp`. + +A backend is a class that implements `autoware::ndt_scan_matcher::NdtBackend` from [autoware_ndt_scan_matcher_common](../autoware_ndt_scan_matcher_common/README.md). That README explains how another package adds a backend. + +If the node cannot load the backend, the node throws an exception at startup. For an unknown name, the message lists the available backends. + ## Regularization ### Abstract diff --git a/localization/autoware_ndt_scan_matcher/include/autoware/ndt_scan_matcher/hyper_parameters.hpp b/localization/autoware_ndt_scan_matcher/include/autoware/ndt_scan_matcher/hyper_parameters.hpp index e0c18ab01f..4460127ca0 100644 --- a/localization/autoware_ndt_scan_matcher/include/autoware/ndt_scan_matcher/hyper_parameters.hpp +++ b/localization/autoware_ndt_scan_matcher/include/autoware/ndt_scan_matcher/hyper_parameters.hpp @@ -15,13 +15,14 @@ #ifndef AUTOWARE__NDT_SCAN_MATCHER__HYPER_PARAMETERS_HPP_ #define AUTOWARE__NDT_SCAN_MATCHER__HYPER_PARAMETERS_HPP_ -#include "ndt_omp/multigrid_ndt_omp.h" +#include "autoware/ndt_scan_matcher_common/ndt_types.hpp" #include #include #include #include +#include #include #include @@ -55,7 +56,8 @@ struct HyperParameters double required_distance{}; } sensor_points{}; - pclomp::NdtParams ndt{}; + NdtParams ndt{}; + std::string ndt_backend{}; bool ndt_regularization_enable{}; struct InitialPoseEstimation @@ -124,6 +126,14 @@ struct HyperParameters ndt.max_iterations = static_cast(node->declare_parameter("ndt.max_iterations")); ndt.num_threads = static_cast(node->declare_parameter("ndt.num_threads")); ndt.num_threads = std::max(ndt.num_threads, 1); + try { + ndt_backend = node->declare_parameter("ndt.backend"); + } catch (const rclcpp::ParameterTypeException &) { + // The parameter is new, so a parameter file from before it does not have it. + throw std::runtime_error( + "The parameter 'ndt.backend' is not set. Add the line `backend: \"ndt_omp\"` under `ndt:` " + "in the parameter file of autoware_ndt_scan_matcher."); + } ndt_regularization_enable = node->declare_parameter("ndt.regularization.enable"); ndt.regularization_scale_factor = static_cast(node->declare_parameter("ndt.regularization.scale_factor")); diff --git a/localization/autoware_ndt_scan_matcher/include/autoware/ndt_scan_matcher/map_update_module.hpp b/localization/autoware_ndt_scan_matcher/include/autoware/ndt_scan_matcher/map_update_module.hpp index b2387d3666..c70fc340ae 100644 --- a/localization/autoware_ndt_scan_matcher/include/autoware/ndt_scan_matcher/map_update_module.hpp +++ b/localization/autoware_ndt_scan_matcher/include/autoware/ndt_scan_matcher/map_update_module.hpp @@ -15,10 +15,10 @@ #ifndef AUTOWARE__NDT_SCAN_MATCHER__MAP_UPDATE_MODULE_HPP_ #define AUTOWARE__NDT_SCAN_MATCHER__MAP_UPDATE_MODULE_HPP_ +#include "autoware/ndt_scan_matcher_common/ndt_backend.hpp" #include "diagnostics_report.hpp" #include "guarded.hpp" #include "hyper_parameters.hpp" -#include "ndt_omp/multigrid_ndt_omp.h" #include #include @@ -46,8 +46,8 @@ class MapUpdateModule public: using PointSource = pcl::PointXYZ; using PointTarget = pcl::PointXYZ; - using NdtType = pclomp::MultiGridNormalDistributionsTransform; - using NdtPtrType = std::shared_ptr; + using NdtType = NdtBackend; + using NdtPtrType = NdtBackend::SharedPtr; using GetDifferentialPointCloudMap = autoware_map_msgs::srv::GetDifferentialPointCloudMap; diff --git a/localization/autoware_ndt_scan_matcher/include/autoware/ndt_scan_matcher/ndt_backend_loader.hpp b/localization/autoware_ndt_scan_matcher/include/autoware/ndt_scan_matcher/ndt_backend_loader.hpp new file mode 100644 index 0000000000..58b0b83521 --- /dev/null +++ b/localization/autoware_ndt_scan_matcher/include/autoware/ndt_scan_matcher/ndt_backend_loader.hpp @@ -0,0 +1,34 @@ +// Copyright 2026 Autoware Foundation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef AUTOWARE__NDT_SCAN_MATCHER__NDT_BACKEND_LOADER_HPP_ +#define AUTOWARE__NDT_SCAN_MATCHER__NDT_BACKEND_LOADER_HPP_ + +#include "autoware/ndt_scan_matcher_common/ndt_backend.hpp" + +#include + +namespace autoware::ndt_scan_matcher +{ + +/// Makes the NDT backend with this pluginlib lookup name. Throws std::runtime_error if the backend +/// cannot be made. For an unknown name, the message lists the declared backends. +/// +/// A backend library stays loaded until the process ends, so instances that a backend makes +/// without pluginlib (for example, in clone()) stay valid. +NdtBackend::SharedPtr load_ndt_backend(const std::string & backend_name); + +} // namespace autoware::ndt_scan_matcher + +#endif // AUTOWARE__NDT_SCAN_MATCHER__NDT_BACKEND_LOADER_HPP_ diff --git a/localization/autoware_ndt_scan_matcher/include/autoware/ndt_scan_matcher/ndt_omp/estimate_covariance.hpp b/localization/autoware_ndt_scan_matcher/include/autoware/ndt_scan_matcher/ndt_omp/estimate_covariance.hpp index 1d962e34ac..03eec8357a 100644 --- a/localization/autoware_ndt_scan_matcher/include/autoware/ndt_scan_matcher/ndt_omp/estimate_covariance.hpp +++ b/localization/autoware_ndt_scan_matcher/include/autoware/ndt_scan_matcher/ndt_omp/estimate_covariance.hpp @@ -15,7 +15,7 @@ #ifndef AUTOWARE__NDT_SCAN_MATCHER__NDT_OMP__ESTIMATE_COVARIANCE_HPP_ #define AUTOWARE__NDT_SCAN_MATCHER__NDT_OMP__ESTIMATE_COVARIANCE_HPP_ -#include "multigrid_ndt_omp.h" +#include "autoware/ndt_scan_matcher_common/ndt_backend.hpp" #include @@ -31,21 +31,21 @@ struct ResultOfMultiNdtCovarianceEstimation Eigen::Vector2d mean; Eigen::Matrix2d covariance; std::vector ndt_initial_poses; - std::vector ndt_results; + std::vector ndt_results; }; /** \brief Estimate functions */ Eigen::Matrix2d estimate_xy_covariance_by_laplace_approximation( const Eigen::Matrix & hessian); ResultOfMultiNdtCovarianceEstimation estimate_xy_covariance_by_multi_ndt( - const NdtResult & ndt_result, - pclomp::MultiGridNormalDistributionsTransform & ndt_ref, + const autoware::ndt_scan_matcher::NdtResult & ndt_result, + autoware::ndt_scan_matcher::NdtBackend & ndt_ref, const std::vector & poses_to_search, const pcl::shared_ptr> & source); ResultOfMultiNdtCovarianceEstimation estimate_xy_covariance_by_multi_ndt_score( - const NdtResult & ndt_result, - pclomp::MultiGridNormalDistributionsTransform & ndt_ref, + const autoware::ndt_scan_matcher::NdtResult & ndt_result, + autoware::ndt_scan_matcher::NdtBackend & ndt_ref, const std::vector & poses_to_search, const pcl::shared_ptr> & source, const double temperature); @@ -55,7 +55,7 @@ ResultOfMultiNdtCovarianceEstimation estimate_xy_covariance_by_multi_ndt_score( * (3) Propose search points by adding offset_x and offset_y to the center_pose */ std::vector propose_poses_to_search( - const NdtResult & ndt_result, const std::vector & offset_x, + const autoware::ndt_scan_matcher::NdtResult & ndt_result, const std::vector & offset_x, const std::vector & offset_y); /** \brief Calculate weights by exponential */ diff --git a/localization/autoware_ndt_scan_matcher/include/autoware/ndt_scan_matcher/ndt_scan_matcher_core.hpp b/localization/autoware_ndt_scan_matcher/include/autoware/ndt_scan_matcher/ndt_scan_matcher_core.hpp index 96987fbbaa..266d849a3a 100644 --- a/localization/autoware_ndt_scan_matcher/include/autoware/ndt_scan_matcher/ndt_scan_matcher_core.hpp +++ b/localization/autoware_ndt_scan_matcher/include/autoware/ndt_scan_matcher/ndt_scan_matcher_core.hpp @@ -17,10 +17,10 @@ #define FMT_HEADER_ONLY +#include "autoware/ndt_scan_matcher_common/ndt_backend.hpp" #include "guarded.hpp" #include "hyper_parameters.hpp" #include "map_update_module.hpp" -#include "ndt_omp/multigrid_ndt_omp.h" #include "scan_match_diagnostics.hpp" #include @@ -73,8 +73,6 @@ class NDTScanMatcher : public autoware::agnocast_wrapper::Node { using PointSource = pcl::PointXYZ; using PointTarget = pcl::PointXYZ; - using NormalDistributionsTransform = - pclomp::MultiGridNormalDistributionsTransform; public: explicit NDTScanMatcher(const rclcpp::NodeOptions & options = rclcpp::NodeOptions()); @@ -121,7 +119,7 @@ class NDTScanMatcher : public autoware::agnocast_wrapper::Node std::tuple align_pose( const geometry_msgs::msg::PoseWithCovarianceStamped & initial_pose_with_cov, - NormalDistributionsTransform & ndt_ref); + NdtBackend & ndt_ref); void transform_sensor_measurement( const std::string & source_frame, const std::string & target_frame, @@ -138,7 +136,7 @@ class NDTScanMatcher : public autoware::agnocast_wrapper::Node const pcl::shared_ptr> & sensor_points_in_map_ptr); void publish_marker( const rclcpp::Time & sensor_ros_time, const std::vector & pose_array, - NormalDistributionsTransform & ndt_ref); + NdtBackend & ndt_ref); void publish_initial_to_result( const rclcpp::Time & sensor_ros_time, const geometry_msgs::msg::Pose & result_pose_msg, const geometry_msgs::msg::PoseWithCovarianceStamped & initial_pose_cov_msg, @@ -150,15 +148,16 @@ class NDTScanMatcher : public autoware::agnocast_wrapper::Node static int count_oscillation(const std::vector & result_pose_msg_array); Eigen::Matrix2d estimate_covariance( - const pclomp::NdtResult & ndt_result, const Eigen::Matrix4f & initial_pose_matrix, - const rclcpp::Time & sensor_ros_time, NormalDistributionsTransform & ndt_ref); + const NdtResult & ndt_result, const Eigen::Matrix4f & initial_pose_matrix, + const rclcpp::Time & sensor_ros_time, NdtBackend & ndt_ref); pcl::PointCloud::Ptr visualize_point_score( const pcl::shared_ptr> & sensor_points_in_map_ptr, - const float & lower_nvs, const float & upper_nvs, NormalDistributionsTransform & ndt_ref); + const float & lower_nvs, const float & upper_nvs, NdtBackend & ndt_ref); - void add_regularization_pose( - const rclcpp::Time & sensor_ros_time, NormalDistributionsTransform & ndt_ref); + void add_regularization_pose(const rclcpp::Time & sensor_ros_time, NdtBackend & ndt_ref); + + NdtBackend::SharedPtr create_ndt_backend(const std::string & backend_name); // Performs the pcd_loader service call for MapUpdateModule, returning nullptr on failure. MapUpdateModule::GetDifferentialPointCloudMap::Response::ConstSharedPtr @@ -219,8 +218,7 @@ class NDTScanMatcher : public autoware::agnocast_wrapper::Node rclcpp::CallbackGroup::SharedPtr timer_callback_group_; - Guarded> ndt_ptr_{ - std::make_shared()}; + Guarded ndt_ptr_; pcl::shared_ptr> sensor_points_in_baselink_frame_; diff --git a/localization/autoware_ndt_scan_matcher/package.xml b/localization/autoware_ndt_scan_matcher/package.xml index 2867e41955..154af0360d 100644 --- a/localization/autoware_ndt_scan_matcher/package.xml +++ b/localization/autoware_ndt_scan_matcher/package.xml @@ -19,6 +19,7 @@ autoware_internal_localization_msgs autoware_localization_util autoware_map_msgs + autoware_ndt_scan_matcher_common autoware_qos_utils autoware_utils_diagnostics autoware_utils_geometry @@ -34,6 +35,7 @@ libpcl-all nav_msgs pcl_conversions + pluginlib rclcpp rclcpp_components sensor_msgs @@ -51,6 +53,7 @@ ament_cmake_ros ament_index_cpp ament_lint_auto + console_bridge_vendor launch_testing_ament_cmake rcl_yaml_param_parser ros_testing diff --git a/localization/autoware_ndt_scan_matcher/plugins.xml b/localization/autoware_ndt_scan_matcher/plugins.xml new file mode 100644 index 0000000000..d119da2426 --- /dev/null +++ b/localization/autoware_ndt_scan_matcher/plugins.xml @@ -0,0 +1,5 @@ + + + NDT on the CPU with OpenMP (ndt_omp). + + diff --git a/localization/autoware_ndt_scan_matcher/src/map_update_module.cpp b/localization/autoware_ndt_scan_matcher/src/map_update_module.cpp index 9035740e04..e3297ff247 100644 --- a/localization/autoware_ndt_scan_matcher/src/map_update_module.cpp +++ b/localization/autoware_ndt_scan_matcher/src/map_update_module.cpp @@ -38,11 +38,9 @@ MapUpdateModule::MapUpdateModule( // and ndt_ptr_ is only locked when swapping its pointer with // secondary_ndt_ptr_. builder_state.need_rebuild = true; - builder_state.secondary_ndt_ptr.reset(new NdtType); - return ndt_ptr_.with([&](const auto & ptr) { if (ptr) { - *builder_state.secondary_ndt_ptr = *ptr; + builder_state.secondary_ndt_ptr = ptr->clone(); return true; } else { return false; @@ -135,14 +133,11 @@ bool MapUpdateModule::update_map_internal( if (builder_state.need_rebuild) { bool updated = false; ndt_ptr_.with([&](auto & ndt_ptr) { - auto param = ndt_ptr->get_params(); - - ndt_ptr.reset(new NdtType); + // A new backend of the same type and parameters, without a map. + ndt_ptr = ndt_ptr->clone_empty(); // The map is rebuilt from scratch, so reset the accumulated debug map as well. loaded_pcd_map_.clear(); - ndt_ptr->set_params(param); - updated = update_ndt(position, *ndt_ptr, diagnostics); }); @@ -158,10 +153,14 @@ bool MapUpdateModule::update_map_internal( return false; } + // Destroy the old secondary before the copy, outside the lock of ndt_ptr_, so that at most two + // maps exist at the same time. need_rebuild stays true until the copy exists. No caller catches + // an exception of the copy today. If a caller does that later, the next update is a rebuild, + // and the null secondary is never used. + builder_state.secondary_ndt_ptr.reset(); + builder_state.secondary_ndt_ptr = + ndt_ptr_.with([](const auto & ndt_ptr) { return ndt_ptr->clone(); }); builder_state.need_rebuild = false; - - builder_state.secondary_ndt_ptr.reset(new NdtType); - ndt_ptr_.with([&](const auto & ndt_ptr) { *builder_state.secondary_ndt_ptr = *ndt_ptr; }); } else { // Load map to the secondary_ndt_ptr, which does not require a mutex lock // Since the update of the secondary ndt ptr and the NDT align (done on @@ -183,7 +182,7 @@ bool MapUpdateModule::update_map_internal( // while only the fast pointer swap is performed inside the lock scope. // 1. Clone the contents of secondary_ndt_ptr to create new_ndt_ptr. - auto new_ndt_ptr = std::make_shared(*builder_state.secondary_ndt_ptr); + auto new_ndt_ptr = builder_state.secondary_ndt_ptr->clone(); // 2. Swap the pointers inside the ndt_ptr_'s lock. // - During the swap, the reference count does not decrease to zero, @@ -279,7 +278,7 @@ bool MapUpdateModule::update_ndt( } } - ndt.create_voxel_kdtree(); + ndt.commit_target(); const auto exe_end_time = std::chrono::system_clock::now(); const auto duration_micro_sec = diff --git a/localization/autoware_ndt_scan_matcher/src/ndt_backend_loader.cpp b/localization/autoware_ndt_scan_matcher/src/ndt_backend_loader.cpp new file mode 100644 index 0000000000..db82a371cf --- /dev/null +++ b/localization/autoware_ndt_scan_matcher/src/ndt_backend_loader.cpp @@ -0,0 +1,71 @@ +// Copyright 2026 Autoware Foundation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "autoware/ndt_scan_matcher/ndt_backend_loader.hpp" + +#include + +#include +#include +#include + +namespace autoware::ndt_scan_matcher +{ +namespace +{ + +// pluginlib unloads the libraries of a class loader when the loader is destroyed. This loader is +// never destroyed, so a backend library stays loaded until the process ends. +pluginlib::ClassLoader & class_loader() +{ + static auto & loader = *new pluginlib::ClassLoader( // NOLINT + "autoware_ndt_scan_matcher_common", "autoware::ndt_scan_matcher::NdtBackend"); + return loader; +} + +// pluginlib::ClassLoader is not thread safe, and several nodes can load backends at the same time +// in one process. +std::mutex & class_loader_mutex() +{ + static std::mutex mutex; + return mutex; +} + +} // namespace + +NdtBackend::SharedPtr load_ndt_backend(const std::string & backend_name) +{ + const std::lock_guard lock(class_loader_mutex()); + try { + return class_loader().createSharedInstance(backend_name); + } catch (const pluginlib::CreateClassException & e) { + // The library is loaded, but it has no factory for this class and this version of the + // interface. See the inline namespace in ndt_types.hpp. + throw std::runtime_error( + "Failed to create the NDT backend '" + backend_name + "'. " + std::string(e.what()) + + ". The backend was possibly built against another version of autoware_ndt_scan_matcher_common" + ", or with SIMD options that change the alignment of Eigen (for example AVX), or the class " + "type in its plugin description differs from the class that it exports."); + } catch (const pluginlib::PluginlibException & e) { + // The message of pluginlib lists the declared backends. + throw std::runtime_error( + "Failed to load the NDT backend '" + backend_name + "'. " + std::string(e.what())); + } catch (const std::exception & e) { + // From the constructor of the backend. + throw std::runtime_error( + "Failed to create the NDT backend '" + backend_name + "': " + std::string(e.what())); + } +} + +} // namespace autoware::ndt_scan_matcher diff --git a/localization/autoware_ndt_scan_matcher/src/ndt_omp/estimate_covariance.cpp b/localization/autoware_ndt_scan_matcher/src/ndt_omp/estimate_covariance.cpp index a324b120d2..40d905ac62 100644 --- a/localization/autoware_ndt_scan_matcher/src/ndt_omp/estimate_covariance.cpp +++ b/localization/autoware_ndt_scan_matcher/src/ndt_omp/estimate_covariance.cpp @@ -14,6 +14,8 @@ #include +#include + #include #include #include @@ -33,8 +35,8 @@ Eigen::Matrix2d estimate_xy_covariance_by_laplace_approximation( } ResultOfMultiNdtCovarianceEstimation estimate_xy_covariance_by_multi_ndt( - const NdtResult & ndt_result, - pclomp::MultiGridNormalDistributionsTransform & ndt_ref, + const autoware::ndt_scan_matcher::NdtResult & ndt_result, + autoware::ndt_scan_matcher::NdtBackend & ndt_ref, const std::vector & poses_to_search, const pcl::shared_ptr> & source) { @@ -43,11 +45,9 @@ ResultOfMultiNdtCovarianceEstimation estimate_xy_covariance_by_multi_ndt( std::vector ndt_pose_2d_vec{ndt_pose_2d}; // multiple searches - std::vector ndt_results; + std::vector ndt_results; for (const Eigen::Matrix4f & curr_pose : poses_to_search) { - auto sub_output_cloud = std::make_shared>(); - ndt_ref.align(*sub_output_cloud, curr_pose, source); - const NdtResult sub_ndt_result = ndt_ref.get_result(); + const autoware::ndt_scan_matcher::NdtResult sub_ndt_result = ndt_ref.align(curr_pose, source); ndt_results.push_back(sub_ndt_result); const Eigen::Matrix4f sub_ndt_pose = sub_ndt_result.pose; @@ -69,8 +69,8 @@ ResultOfMultiNdtCovarianceEstimation estimate_xy_covariance_by_multi_ndt( } ResultOfMultiNdtCovarianceEstimation estimate_xy_covariance_by_multi_ndt_score( - const NdtResult & ndt_result, - pclomp::MultiGridNormalDistributionsTransform & ndt_ref, + const autoware::ndt_scan_matcher::NdtResult & ndt_result, + autoware::ndt_scan_matcher::NdtBackend & ndt_ref, const std::vector & poses_to_search, const pcl::shared_ptr> & source, const double temperature) { @@ -82,7 +82,7 @@ ResultOfMultiNdtCovarianceEstimation estimate_xy_covariance_by_multi_ndt_score( pcl::PointCloud trans_cloud; // multiple searches - std::vector ndt_results; + std::vector ndt_results; for (const Eigen::Matrix4f & curr_pose : poses_to_search) { const Eigen::Vector2d sub_ndt_pose_2d = curr_pose.topRightCorner<2, 1>().cast(); ndt_pose_2d_vec.emplace_back(sub_ndt_pose_2d); @@ -91,7 +91,7 @@ ResultOfMultiNdtCovarianceEstimation estimate_xy_covariance_by_multi_ndt_score( const double nvtl = ndt_ref.calculate_nearest_voxel_transformation_likelihood(trans_cloud); score_vec.emplace_back(nvtl); - NdtResult sub_ndt_result{}; + autoware::ndt_scan_matcher::NdtResult sub_ndt_result{}; sub_ndt_result.pose = curr_pose; sub_ndt_result.iteration_num = 0; sub_ndt_result.nearest_voxel_transformation_likelihood = static_cast(nvtl); @@ -107,7 +107,7 @@ ResultOfMultiNdtCovarianceEstimation estimate_xy_covariance_by_multi_ndt_score( } std::vector propose_poses_to_search( - const NdtResult & ndt_result, const std::vector & offset_x, + const autoware::ndt_scan_matcher::NdtResult & ndt_result, const std::vector & offset_x, const std::vector & offset_y) { assert(offset_x.size() == offset_y.size()); diff --git a/localization/autoware_ndt_scan_matcher/src/ndt_scan_matcher_core.cpp b/localization/autoware_ndt_scan_matcher/src/ndt_scan_matcher_core.cpp index 3e71dba6f8..62f3dfc0ca 100644 --- a/localization/autoware_ndt_scan_matcher/src/ndt_scan_matcher_core.cpp +++ b/localization/autoware_ndt_scan_matcher/src/ndt_scan_matcher_core.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -44,6 +45,7 @@ #include #include #include +#include #include #include #include @@ -79,6 +81,11 @@ NDTScanMatcher::NDTScanMatcher(const rclcpp::NodeOptions & options) is_activated_(false), param_(this) { + // Load the backend first, so that a wrong backend name stops the node before the constructor + // body creates publishers, subscriptions, services and timers. Only the tf broadcaster and the + // tf listener exist earlier, because they are members. + ndt_ptr_.with([&](auto & ndt_ptr) { ndt_ptr = create_ndt_backend(param_.ndt_backend); }); + timer_callback_group_ = this->create_callback_group(rclcpp::CallbackGroupType::MutuallyExclusive); rclcpp::CallbackGroup::SharedPtr initial_pose_callback_group = this->create_callback_group(rclcpp::CallbackGroupType::MutuallyExclusive); @@ -186,8 +193,6 @@ NDTScanMatcher::NDTScanMatcher(const rclcpp::NodeOptions & options) &NDTScanMatcher::service_trigger_node, this, std::placeholders::_1, std::placeholders::_2), service_qos, sensor_callback_group); - ndt_ptr_.with([&](const auto & ndt_ptr) { ndt_ptr->set_params(param_.ndt); }); - initial_pose_buffer_ = std::make_unique( this->get_logger(), param_.validation.initial_pose_timeout_sec, param_.validation.initial_pose_distance_tolerance_m); @@ -220,6 +225,19 @@ NDTScanMatcher::NDTScanMatcher(const rclcpp::NodeOptions & options) autoware_utils_logging::BasicLoggerLevelConfigure>(this); } +NdtBackend::SharedPtr NDTScanMatcher::create_ndt_backend(const std::string & backend_name) +{ + NdtBackend::SharedPtr backend = load_ndt_backend(backend_name); + try { + backend->initialize(param_.ndt); + } catch (const std::exception & e) { + throw std::runtime_error( + "Failed to initialize the NDT backend '" + backend_name + "': " + std::string(e.what())); + } + RCLCPP_INFO_STREAM(get_logger(), "NDT backend: " << backend->name()); + return backend; +} + MapUpdateModule::GetDifferentialPointCloudMap::Response::ConstSharedPtr NDTScanMatcher::get_differential_point_cloud_map( const MapUpdateModule::GetDifferentialPointCloudMap::Request::SharedPtr & request) @@ -550,9 +568,8 @@ bool NDTScanMatcher::callback_sensor_points_main( // perform ndt scan matching const Eigen::Matrix4f initial_pose_matrix = pose_to_matrix4f(interpolation_result.interpolated_pose.pose.pose); - auto output_cloud = std::make_shared>(); - ndt_ptr->align(*output_cloud, initial_pose_matrix, sensor_points_in_baselink_frame_); - const pclomp::NdtResult ndt_result = ndt_ptr->get_result(); + const NdtResult ndt_result = + ndt_ptr->align(initial_pose_matrix, sensor_points_in_baselink_frame_); const geometry_msgs::msg::Pose result_pose_msg = matrix4f_to_pose(ndt_result.pose); std::vector transformation_msg_array; @@ -563,7 +580,7 @@ bool NDTScanMatcher::callback_sensor_points_main( ScanMatchDiagnosticValues diagnostic_values; diagnostic_values.iteration_num = ndt_result.iteration_num; - diagnostic_values.maximum_iterations = ndt_ptr->get_maximum_iterations(); + diagnostic_values.maximum_iterations = ndt_ptr->get_params().max_iterations; diagnostic_values.transform_probability = ndt_result.transform_probability; diagnostic_values.nearest_voxel_transformation_likelihood = ndt_result.nearest_voxel_transformation_likelihood; @@ -572,7 +589,8 @@ bool NDTScanMatcher::callback_sensor_points_main( ndt_result.nearest_voxel_transformation_likelihood_array; // check iteration_num - const bool is_ok_iteration_num = (ndt_result.iteration_num < ndt_ptr->get_maximum_iterations()); + const bool is_ok_iteration_num = + (ndt_result.iteration_num < ndt_ptr->get_params().max_iterations); diagnostic_values.is_ok_iteration_num = is_ok_iteration_num; // check local_optimal_solution_oscillation_num @@ -802,7 +820,7 @@ void NDTScanMatcher::publish_point_cloud( void NDTScanMatcher::publish_marker( const rclcpp::Time & sensor_ros_time, const std::vector & pose_array, - NormalDistributionsTransform & ndt_ref) + NdtBackend & ndt_ref) { auto marker_array = ALLOCATE_OUTPUT_MESSAGE_UNIQUE(ndt_marker_pub_); visualization_msgs::msg::Marker marker; @@ -822,7 +840,8 @@ void NDTScanMatcher::publish_marker( } // TODO(Tier IV): delete old marker - for (; i < ndt_ref.get_maximum_iterations() + 2;) { + const int max_iterations = ndt_ref.get_params().max_iterations; + for (; i < max_iterations + 2;) { marker.id = i++; marker.pose = geometry_msgs::msg::Pose(); marker.color = exchange_color_crc(0); @@ -868,8 +887,8 @@ int NDTScanMatcher::count_oscillation( } Eigen::Matrix2d NDTScanMatcher::estimate_covariance( - const pclomp::NdtResult & ndt_result, const Eigen::Matrix4f & initial_pose_matrix, - const rclcpp::Time & sensor_ros_time, NormalDistributionsTransform & ndt_ref) + const NdtResult & ndt_result, const Eigen::Matrix4f & initial_pose_matrix, + const rclcpp::Time & sensor_ros_time, NdtBackend & ndt_ref) { geometry_msgs::msg::PoseArray multi_ndt_result_msg; geometry_msgs::msg::PoseArray multi_initial_pose_msg; @@ -891,7 +910,7 @@ Eigen::Matrix2d NDTScanMatcher::estimate_covariance( ndt_result, param_.covariance.covariance_estimation.initial_pose_offset_model_x, param_.covariance.covariance_estimation.initial_pose_offset_model_y); const pclomp::ResultOfMultiNdtCovarianceEstimation result_of_multi_ndt_covariance_estimation = - estimate_xy_covariance_by_multi_ndt( + pclomp::estimate_xy_covariance_by_multi_ndt( ndt_result, ndt_ref, poses_to_search, sensor_points_in_baselink_frame_); for (size_t i = 0; i < result_of_multi_ndt_covariance_estimation.ndt_initial_poses.size(); i++) { @@ -910,9 +929,10 @@ Eigen::Matrix2d NDTScanMatcher::estimate_covariance( ndt_result, param_.covariance.covariance_estimation.initial_pose_offset_model_x, param_.covariance.covariance_estimation.initial_pose_offset_model_y); const pclomp::ResultOfMultiNdtCovarianceEstimation - result_of_multi_ndt_score_covariance_estimation = estimate_xy_covariance_by_multi_ndt_score( - ndt_result, ndt_ref, poses_to_search, sensor_points_in_baselink_frame_, - param_.covariance.covariance_estimation.temperature); + result_of_multi_ndt_score_covariance_estimation = + pclomp::estimate_xy_covariance_by_multi_ndt_score( + ndt_result, ndt_ref, poses_to_search, sensor_points_in_baselink_frame_, + param_.covariance.covariance_estimation.temperature); for (const auto & sub_initial_pose_matrix : poses_to_search) { multi_initial_pose_msg.poses.push_back(matrix4f_to_pose(sub_initial_pose_matrix)); } @@ -925,7 +945,7 @@ Eigen::Matrix2d NDTScanMatcher::estimate_covariance( pcl::PointCloud::Ptr NDTScanMatcher::visualize_point_score( const pcl::shared_ptr> & sensor_points_in_map_ptr, - const float & lower_nvs, const float & upper_nvs, NormalDistributionsTransform & ndt_ref) + const float & lower_nvs, const float & upper_nvs, NdtBackend & ndt_ref) { pcl::PointCloud nvs_points_in_map_ptr_i; nvs_points_in_map_ptr_i = @@ -950,7 +970,7 @@ pcl::PointCloud::Ptr NDTScanMatcher::visualize_point_score( } void NDTScanMatcher::add_regularization_pose( - const rclcpp::Time & sensor_ros_time, NormalDistributionsTransform & ndt_ref) + const rclcpp::Time & sensor_ros_time, NdtBackend & ndt_ref) { ndt_ref.unset_regularization_pose(); std::optional interpolation_result_opt = @@ -1092,8 +1112,7 @@ void NDTScanMatcher::service_ndt_align_main( } std::tuple NDTScanMatcher::align_pose( - const geometry_msgs::msg::PoseWithCovarianceStamped & initial_pose_with_cov, - NormalDistributionsTransform & ndt_ref) + const geometry_msgs::msg::PoseWithCovarianceStamped & initial_pose_with_cov, NdtBackend & ndt_ref) { autoware::localization_util::output_pose_with_cov_to_log( get_logger(), "align_pose_input", initial_pose_with_cov); @@ -1123,7 +1142,6 @@ std::tuple NDTScanMatcher param_.initial_pose_estimation.n_startup_trials, sample_mean, sample_stddev); std::vector particle_array; - auto output_cloud = std::make_shared>(); // publish the estimated poses in 20 times to see the progress and to avoid dropping data visualization_msgs::msg::MarkerArray marker_array; @@ -1147,8 +1165,8 @@ std::tuple NDTScanMatcher initial_pose.orientation = tf2::toMsg(tf_quaternion); const Eigen::Matrix4f initial_pose_matrix = pose_to_matrix4f(initial_pose); - ndt_ref.align(*output_cloud, initial_pose_matrix, sensor_points_in_baselink_frame_); - const pclomp::NdtResult ndt_result = ndt_ref.get_result(); + const NdtResult ndt_result = + ndt_ref.align(initial_pose_matrix, sensor_points_in_baselink_frame_); Particle particle( initial_pose, matrix4f_to_pose(ndt_result.pose), diff --git a/localization/autoware_ndt_scan_matcher/src/omp_ndt_backend.cpp b/localization/autoware_ndt_scan_matcher/src/omp_ndt_backend.cpp new file mode 100644 index 0000000000..194a2aeddc --- /dev/null +++ b/localization/autoware_ndt_scan_matcher/src/omp_ndt_backend.cpp @@ -0,0 +1,171 @@ +// Copyright 2026 Autoware Foundation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "omp_ndt_backend.hpp" + +#include + +#include +#include +#include +#include + +namespace autoware::ndt_scan_matcher +{ +namespace +{ + +pclomp::NdtParams to_omp_params(const NdtParams & params) +{ + // The other fields of pclomp::NdtParams keep their default values: the KD-tree search and no line + // search. + pclomp::NdtParams omp_params{}; + omp_params.trans_epsilon = params.trans_epsilon; + omp_params.step_size = params.step_size; + omp_params.resolution = params.resolution; + omp_params.max_iterations = params.max_iterations; + omp_params.num_threads = params.num_threads; + omp_params.regularization_scale_factor = params.regularization_scale_factor; + return omp_params; +} + +NdtParams from_omp_params(const pclomp::NdtParams & omp_params) +{ + NdtParams params; + params.trans_epsilon = omp_params.trans_epsilon; + params.step_size = omp_params.step_size; + params.resolution = omp_params.resolution; + params.max_iterations = omp_params.max_iterations; + params.num_threads = omp_params.num_threads; + params.regularization_scale_factor = omp_params.regularization_scale_factor; + return params; +} + +NdtResult from_omp_result(pclomp::NdtResult && omp_result) +{ + NdtResult result; + result.pose = omp_result.pose; + result.transform_probability = omp_result.transform_probability; + result.nearest_voxel_transformation_likelihood = + omp_result.nearest_voxel_transformation_likelihood; + result.iteration_num = omp_result.iteration_num; + result.transformation_array = std::move(omp_result.transformation_array); + result.hessian = omp_result.hessian; + result.transform_probability_array = std::move(omp_result.transform_probability_array); + result.nearest_voxel_transformation_likelihood_array = + std::move(omp_result.nearest_voxel_transformation_likelihood_array); + return result; +} + +} // namespace + +void OmpNdtBackend::initialize(const NdtParams & params) +{ + ndt_.set_params(to_omp_params(params)); +} + +std::string OmpNdtBackend::name() const +{ + return "ndt_omp"; +} + +NdtParams OmpNdtBackend::get_params() const +{ + return from_omp_params(ndt_.get_params()); +} + +void OmpNdtBackend::add_target( + const pcl::PointCloud::ConstPtr & cloud, const std::string & map_id) +{ + ndt_.add_target(cloud, map_id); +} + +void OmpNdtBackend::remove_target(const std::string & map_id) +{ + ndt_.remove_target(map_id); +} + +void OmpNdtBackend::commit_target() +{ + ndt_.create_voxel_kdtree(); +} + +std::vector OmpNdtBackend::get_current_map_ids() const +{ + return ndt_.get_current_map_ids(); +} + +bool OmpNdtBackend::has_target() const +{ + return ndt_.has_target(); +} + +NdtBackend::SharedPtr OmpNdtBackend::clone() const +{ + // The copy constructor of ndt_omp. It copies the map, and it shares the immutable voxel grids. + return std::make_shared(*this); +} + +NdtBackend::SharedPtr OmpNdtBackend::clone_empty() const +{ + // Copy the parameters of ndt_omp directly, so that the fields that only ndt_omp has stay too. + auto empty = std::make_shared(); + empty->ndt_.set_params(ndt_.get_params()); + return empty; +} + +void OmpNdtBackend::set_regularization_pose(const Eigen::Matrix4f & pose) +{ + ndt_.set_regularization_pose(pose); +} + +void OmpNdtBackend::unset_regularization_pose() +{ + ndt_.unset_regularization_pose(); +} + +NdtResult OmpNdtBackend::align( + const Eigen::Matrix4f & guess, const pcl::PointCloud::ConstPtr & source) +{ + // ndt_omp writes the aligned cloud here. The node does not use it. + pcl::PointCloud output; + ndt_.align(output, guess, source); + // A known difference from NdtResult::hessian: if a step of ndt_omp has the length 0 or is not a + // number, ndt_omp returns before it stores the hessian. Then the result holds the hessian of the + // alignment before. This is the behavior of ndt_omp before the backend interface. + return from_omp_result(ndt_.get_result()); +} + +double OmpNdtBackend::calculate_transformation_probability( + const pcl::PointCloud & cloud_in_map) const +{ + return ndt_.calculate_transformation_probability(cloud_in_map); +} + +double OmpNdtBackend::calculate_nearest_voxel_transformation_likelihood( + const pcl::PointCloud & cloud_in_map) const +{ + return ndt_.calculate_nearest_voxel_transformation_likelihood(cloud_in_map); +} + +pcl::PointCloud OmpNdtBackend::calculate_nearest_voxel_score_each_point( + const pcl::PointCloud & cloud_in_map) const +{ + return ndt_.calculate_nearest_voxel_score_each_point(cloud_in_map); +} + +} // namespace autoware::ndt_scan_matcher + +PLUGINLIB_EXPORT_CLASS( + autoware::ndt_scan_matcher::OmpNdtBackend, autoware::ndt_scan_matcher::NdtBackend) diff --git a/localization/autoware_ndt_scan_matcher/src/omp_ndt_backend.hpp b/localization/autoware_ndt_scan_matcher/src/omp_ndt_backend.hpp new file mode 100644 index 0000000000..9fa13ee370 --- /dev/null +++ b/localization/autoware_ndt_scan_matcher/src/omp_ndt_backend.hpp @@ -0,0 +1,66 @@ +// Copyright 2026 Autoware Foundation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef OMP_NDT_BACKEND_HPP_ +#define OMP_NDT_BACKEND_HPP_ + +#include "autoware/ndt_scan_matcher/ndt_omp/multigrid_ndt_omp.h" +#include "autoware/ndt_scan_matcher_common/ndt_backend.hpp" + +#include +#include + +namespace autoware::ndt_scan_matcher +{ + +/// The CPU backend "ndt_omp": pclomp::MultiGridNormalDistributionsTransform (ndt_omp), without a +/// change. It converts between the types of the interface and the types of ndt_omp. +class OmpNdtBackend : public NdtBackend +{ +public: + void initialize(const NdtParams & params) override; + std::string name() const override; + + NdtParams get_params() const override; + + void add_target( + const pcl::PointCloud::ConstPtr & cloud, const std::string & map_id) override; + void remove_target(const std::string & map_id) override; + void commit_target() override; + std::vector get_current_map_ids() const override; + bool has_target() const override; + + SharedPtr clone() const override; + SharedPtr clone_empty() const override; + + void set_regularization_pose(const Eigen::Matrix4f & pose) override; + void unset_regularization_pose() override; + + NdtResult align( + const Eigen::Matrix4f & guess, const pcl::PointCloud::ConstPtr & source) override; + + double calculate_transformation_probability( + const pcl::PointCloud & cloud_in_map) const override; + double calculate_nearest_voxel_transformation_likelihood( + const pcl::PointCloud & cloud_in_map) const override; + pcl::PointCloud calculate_nearest_voxel_score_each_point( + const pcl::PointCloud & cloud_in_map) const override; + +private: + pclomp::MultiGridNormalDistributionsTransform ndt_; +}; + +} // namespace autoware::ndt_scan_matcher + +#endif // OMP_NDT_BACKEND_HPP_ diff --git a/localization/autoware_ndt_scan_matcher/test/harness/ndt_harness.hpp b/localization/autoware_ndt_scan_matcher/test/harness/ndt_harness.hpp index 5bd950c120..51b93962c6 100644 --- a/localization/autoware_ndt_scan_matcher/test/harness/ndt_harness.hpp +++ b/localization/autoware_ndt_scan_matcher/test/harness/ndt_harness.hpp @@ -32,6 +32,7 @@ #include +#include #include #include #include @@ -116,7 +117,8 @@ class NdtHarness using Record = DiagnosticsCapture::Record; /// @param overrides Appended *after* the shipped yaml. `NodeOptions::parameter_overrides()` - /// is applied in vector order into a map, so the last write wins and these take effect. + /// is applied in vector order into a map, so the last write wins and these take effect. An + /// override without a value removes that parameter of the yaml. /// @param with_map_loader False leaves `pcd_loader_service` unserved, for the loader-absent /// case; everything else is unchanged. explicit NdtHarness(std::vector overrides = {}, bool with_map_loader = true) @@ -560,8 +562,18 @@ class NdtHarness node_options.parameter_overrides().push_back(parameter); } } + auto & parameters = node_options.parameter_overrides(); for (const auto & parameter : overrides_) { - node_options.parameter_overrides().push_back(parameter); + if (parameter.get_type() == rclcpp::ParameterType::PARAMETER_NOT_SET) { + // An override without a value removes the parameter, as if the yaml did not have it. + parameters.erase( + std::remove_if( + parameters.begin(), parameters.end(), + [&](const auto & other) { return other.get_name() == parameter.get_name(); }), + parameters.end()); + } else { + parameters.push_back(parameter); + } } return node_options; } diff --git a/localization/autoware_ndt_scan_matcher/test/test_estimate_covariance.cpp b/localization/autoware_ndt_scan_matcher/test/test_estimate_covariance.cpp index 8869f40c27..2814d3a8d0 100644 --- a/localization/autoware_ndt_scan_matcher/test/test_estimate_covariance.cpp +++ b/localization/autoware_ndt_scan_matcher/test/test_estimate_covariance.cpp @@ -61,7 +61,7 @@ TEST(EstimateCovariance, CalculateWeightedMeanAndCovKnownValues) // NOLINT // adds them to the center translation. TEST(EstimateCovariance, ProposePosesToSearchRotatesOffsets) // NOLINT { - pclomp::NdtResult ndt_result{}; + autoware::ndt_scan_matcher::NdtResult ndt_result{}; ndt_result.pose = Eigen::Matrix4f::Identity(); // 90 degrees CCW about z in the top-left 2x2 block. ndt_result.pose(0, 0) = 0.0f; diff --git a/localization/autoware_ndt_scan_matcher/test/test_map_update_module.cpp b/localization/autoware_ndt_scan_matcher/test/test_map_update_module.cpp index e359ebb623..e73c016839 100644 --- a/localization/autoware_ndt_scan_matcher/test/test_map_update_module.cpp +++ b/localization/autoware_ndt_scan_matcher/test/test_map_update_module.cpp @@ -15,6 +15,7 @@ #include "test_util.hpp" #include +#include #include #include @@ -99,14 +100,14 @@ class MapUpdateModuleTest : public ::testing::Test protected: void SetUp() override { - pclomp::NdtParams ndt_params{}; + NdtParams ndt_params{}; ndt_params.trans_epsilon = 0.01; ndt_params.step_size = 0.1; ndt_params.resolution = 2.0F; ndt_params.max_iterations = 30; ndt_params.num_threads = 1; ndt_params.regularization_scale_factor = 0.0F; - ndt_ptr_.with([&](auto & ndt) { ndt->set_params(ndt_params); }); + ndt_ptr_.with([&](auto & ndt) { ndt->initialize(ndt_params); }); param_.update_distance = 5.0; param_.map_radius = 30.0; @@ -131,7 +132,7 @@ class MapUpdateModuleTest : public ::testing::Test return ndt_ptr.with([](const auto & ndt) { return ndt->has_target(); }); } - Guarded ndt_ptr_{std::make_shared()}; + Guarded ndt_ptr_{load_ndt_backend("ndt_omp")}; HyperParameters::DynamicMapLoading param_{}; }; @@ -146,6 +147,33 @@ TEST_F(MapUpdateModuleTest, FirstUpdateRebuildsAndLoadsMap) // NOLINT EXPECT_TRUE(ndt_has_target(ndt_ptr_)); } +// The second update loads the new cell into the secondary backend, then swaps a copy of it in. +// This runs clone_empty() and clone() on a backend that pluginlib made. +TEST_F(MapUpdateModuleTest, SecondUpdateLoadsIntoTheSecondaryAndSwaps) // NOLINT +{ + int calls = 0; + MapUpdateModule::PcdLoaderFunction loader = + [&calls](const GetDifferentialPointCloudMap::Request::SharedPtr & /*request*/) + -> GetDifferentialPointCloudMap::Response::SharedPtr { + auto response = std::make_shared(); + autoware_map_msgs::msg::PointCloudMapCellWithID cell; + cell.cell_id = std::to_string(calls++); + pcl::toROSMsg(make_sample_half_cubic_pcd(), cell.pointcloud); + response->new_pointcloud_with_ids.push_back(cell); + response->header.frame_id = "map"; + return response; + }; + MapUpdateModule module(ndt_ptr_, param_, loader); + + ASSERT_TRUE(update_map(module, make_point(0.0, 0.0)).map_updated); // rebuild: cell "0" + // 6 m > update_distance (5 m), and 6 + 5 < map_radius (30 m): no rebuild. + const auto result = update_map(module, make_point(6.0, 0.0)); + + EXPECT_TRUE(result.map_updated); + const auto map_ids = ndt_ptr_.with([](const auto & ndt) { return ndt->get_current_map_ids(); }); + EXPECT_EQ(map_ids.size(), 2U); +} + // out_of_map_range is true before any update, false at the last update position, and true again // once the query moves beyond (map_radius - lidar_radius) from it. TEST_F(MapUpdateModuleTest, OutOfMapRangeTracksLastUpdate) // NOLINT diff --git a/localization/autoware_ndt_scan_matcher/test/test_ndt_backend.cpp b/localization/autoware_ndt_scan_matcher/test/test_ndt_backend.cpp new file mode 100644 index 0000000000..3d4382b073 --- /dev/null +++ b/localization/autoware_ndt_scan_matcher/test/test_ndt_backend.cpp @@ -0,0 +1,102 @@ +// Copyright 2026 Autoware Foundation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// A backend for the tests of the error messages of the node. It is built three times as a plugin +// library: with a constructor that throws, with an initialize() that throws, and with another heap +// allocator of Eigen, as a backend that was built with other compiler options. + +#include +#include + +#include +#include +#include +#include + +// Each library has its own class name. pluginlib uses one class loader for all libraries, and it +// finds a class by its name. +#if defined(TEST_NDT_BACKEND_CONSTRUCTOR_THROWS) +#define TEST_NDT_BACKEND_CLASS ConstructorThrowsBackend +#elif defined(TEST_NDT_BACKEND_INITIALIZE_THROWS) +#define TEST_NDT_BACKEND_CLASS InitializeThrowsBackend +#else +#define TEST_NDT_BACKEND_CLASS OtherAbiBackend +#endif + +namespace test_ndt_backend +{ + +using autoware::ndt_scan_matcher::NdtBackend; +using autoware::ndt_scan_matcher::NdtParams; +using autoware::ndt_scan_matcher::NdtResult; + +class TEST_NDT_BACKEND_CLASS : public NdtBackend +{ +public: + TEST_NDT_BACKEND_CLASS() + { +#ifdef TEST_NDT_BACKEND_CONSTRUCTOR_THROWS + throw std::logic_error("the test backend cannot be made"); +#endif + } + TEST_NDT_BACKEND_CLASS(const TEST_NDT_BACKEND_CLASS &) = default; + + void initialize(const NdtParams & params) override + { +#ifdef TEST_NDT_BACKEND_INITIALIZE_THROWS + throw std::runtime_error("this computer has no test device"); +#endif + params_ = params; + } + std::string name() const override { return "test"; } + NdtParams get_params() const override { return params_; } + void add_target(const pcl::PointCloud::ConstPtr &, const std::string &) override {} + void remove_target(const std::string &) override {} + void commit_target() override {} + std::vector get_current_map_ids() const override { return {}; } + bool has_target() const override { return false; } + SharedPtr clone() const override { return std::make_shared(*this); } + SharedPtr clone_empty() const override { return std::make_shared(); } + void set_regularization_pose(const Eigen::Matrix4f &) override {} + void unset_regularization_pose() override {} + NdtResult align( + const Eigen::Matrix4f & guess, const pcl::PointCloud::ConstPtr &) override + { + NdtResult result; + result.pose = guess; + return result; + } + double calculate_transformation_probability(const pcl::PointCloud &) const override + { + return 0.0; + } + double calculate_nearest_voxel_transformation_likelihood( + const pcl::PointCloud &) const override + { + return 0.0; + } + pcl::PointCloud calculate_nearest_voxel_score_each_point( + const pcl::PointCloud &) const override + { + return {}; + } + +private: + NdtParams params_{}; +}; + +} // namespace test_ndt_backend + +PLUGINLIB_EXPORT_CLASS( + test_ndt_backend::TEST_NDT_BACKEND_CLASS, autoware::ndt_scan_matcher::NdtBackend) diff --git a/localization/autoware_ndt_scan_matcher/test/test_ndt_backend_loader.cpp b/localization/autoware_ndt_scan_matcher/test/test_ndt_backend_loader.cpp new file mode 100644 index 0000000000..327bbc9fb3 --- /dev/null +++ b/localization/autoware_ndt_scan_matcher/test/test_ndt_backend_loader.cpp @@ -0,0 +1,134 @@ +// Copyright 2026 Autoware Foundation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Loads the backends with pluginlib, as the node does. pluginlib loads the backend "ndt_omp" from +// the library autoware_ndt_scan_matcher_omp_backend, and this test does not link it. + +#include + +#include +#include +#include + +#include +#include + +namespace autoware::ndt_scan_matcher +{ + +TEST(LoadNdtBackend, LoadsTheOmpBackend) +{ + const NdtBackend::SharedPtr backend = load_ndt_backend("ndt_omp"); + ASSERT_NE(backend, nullptr); + EXPECT_EQ(backend->name(), "ndt_omp"); + + // The backend makes its clones without pluginlib. + const NdtBackend::SharedPtr clone = backend->clone(); + ASSERT_NE(clone, nullptr); + EXPECT_EQ(clone->name(), "ndt_omp"); +} + +namespace +{ +// Keeps the log messages of class_loader while it exists. +class LogSpy : public console_bridge::OutputHandler +{ +public: + LogSpy() { console_bridge::useOutputHandler(this); } + ~LogSpy() override { console_bridge::restorePreviousOutputHandler(); } + LogSpy(const LogSpy &) = delete; + LogSpy & operator=(const LogSpy &) = delete; + + void log(const std::string & text, console_bridge::LogLevel, const char *, int) override + { + text_ += text + "\n"; + } + const std::string & text() const { return text_; } + +private: + std::string text_; +}; +} // namespace + +TEST(LoadNdtBackend, TheBackendLibraryStaysLoaded) +{ + // The clones of a backend come from the backend library, not from pluginlib. So the library must + // stay loaded after the instance from pluginlib is gone. + // + // A loader that is destroyed while the instance from pluginlib exists cannot unload the library, + // and class_loader then gives a warning. The test expects no such warning. The test cannot find + // a loader that is destroyed while only a clone exists: in this process, the library stays + // loaded in that case too. + NdtBackend::SharedPtr clone; + { + LogSpy spy; + clone = load_ndt_backend("ndt_omp")->clone(); + EXPECT_EQ(spy.text().find("SEVERE WARNING"), std::string::npos) << spy.text(); + } + + void * handle = dlopen("libautoware_ndt_scan_matcher_omp_backend.so", RTLD_NOW | RTLD_NOLOAD); + ASSERT_NE(handle, nullptr) << "the backend library was unloaded"; + dlclose(handle); + EXPECT_FALSE(clone->clone_empty()->has_target()); +} + +TEST(LoadNdtBackend, UnknownBackendThrowsAndListsTheAvailableOnes) +{ + try { + load_ndt_backend("no_such_backend"); + FAIL() << "load_ndt_backend() did not throw"; + } catch (const std::runtime_error & e) { + const std::string message = e.what(); + EXPECT_NE(message.find("no_such_backend"), std::string::npos) << message; + EXPECT_NE(message.find("ndt_omp"), std::string::npos) << message; + } +} + +// An exception from the constructor of a backend gets the name of the backend. +TEST(LoadNdtBackend, BackendWhoseConstructorThrowsGetsItsNameInTheMessage) +{ + try { + load_ndt_backend("test_constructor_throws"); + FAIL() << "load_ndt_backend() did not throw"; + } catch (const std::runtime_error & e) { + const std::string message = e.what(); + EXPECT_NE( + message.find("Failed to create the NDT backend 'test_constructor_throws'"), std::string::npos) + << message; + EXPECT_NE(message.find("the test backend cannot be made"), std::string::npos) << message; + } +} + +// The test backend "test_other_abi" was built with EIGEN_MALLOC_ALREADY_ALIGNED=0. In a normal +// build, it then has another heap allocator of Eigen than this test, so its library has no factory +// for the interface of this test. +TEST(LoadNdtBackend, BackendWithAnotherAbiThrowsWithTheCause) +{ +#if (EIGEN_DEFAULT_ALIGN_BYTES == 0) || !EIGEN_MALLOC_ALREADY_ALIGNED + GTEST_SKIP() << "This build already has the Eigen allocator of the test backend."; +#endif + try { + load_ndt_backend("test_other_abi"); + FAIL() << "load_ndt_backend() did not throw"; + } catch (const std::runtime_error & e) { + const std::string message = e.what(); + EXPECT_NE(message.find("Failed to create the NDT backend 'test_other_abi'"), std::string::npos) + << message; + EXPECT_NE( + message.find("another version of autoware_ndt_scan_matcher_common"), std::string::npos) + << message; + } +} + +} // namespace autoware::ndt_scan_matcher diff --git a/localization/autoware_ndt_scan_matcher/test/test_ndt_backend_plugins.xml b/localization/autoware_ndt_scan_matcher/test/test_ndt_backend_plugins.xml new file mode 100644 index 0000000000..329e726c32 --- /dev/null +++ b/localization/autoware_ndt_scan_matcher/test/test_ndt_backend_plugins.xml @@ -0,0 +1,17 @@ + + + + A test backend whose constructor throws. + + + + + A test backend whose initialize() throws. + + + + + A test backend that was built with another heap allocator of Eigen. + + + diff --git a/localization/autoware_ndt_scan_matcher/test/test_ndt_scan_matcher_characteristics.cpp b/localization/autoware_ndt_scan_matcher/test/test_ndt_scan_matcher_characteristics.cpp index 18853eb57a..9242f7cd44 100644 --- a/localization/autoware_ndt_scan_matcher/test/test_ndt_scan_matcher_characteristics.cpp +++ b/localization/autoware_ndt_scan_matcher/test/test_ndt_scan_matcher_characteristics.cpp @@ -2150,6 +2150,53 @@ TEST(NdtScanMatcherCharacteristics, SteadyStateOperationKeepsPublishingWhenMapUp EXPECT_EQ(second.value("is_updated_map"), "False"); } +// --------------------------------------------------------------------------------------------- +// NDT backend +// --------------------------------------------------------------------------------------------- + +/// An unknown `ndt.backend` stops the node in its constructor, with the name in the message. +TEST(NdtScanMatcherCharacteristics, UnknownBackendThrowsAtConstruction) +{ + try { + NdtHarness harness({rclcpp::Parameter("ndt.backend", "no_such_backend")}); + FAIL() << "the node started with an unknown backend"; + } catch (const std::runtime_error & e) { + EXPECT_NE(std::string(e.what()).find("no_such_backend"), std::string::npos) << e.what(); + } +} + +/// A parameter file without `ndt.backend` (from before the parameter) stops the node in its +/// constructor, with the line to add in the message. +TEST(NdtScanMatcherCharacteristics, MissingBackendParameterThrowsAtConstruction) +{ + try { + NdtHarness harness({rclcpp::Parameter("ndt.backend")}); + FAIL() << "the node started without ndt.backend"; + } catch (const std::runtime_error & e) { + const std::string message = e.what(); + EXPECT_NE(message.find("The parameter 'ndt.backend' is not set."), std::string::npos) + << message; + EXPECT_NE(message.find("`backend: \"ndt_omp\"`"), std::string::npos) << message; + } +} + +/// An error from `initialize()` of the backend stops the node in its constructor, with the name +/// of the backend and the cause in the message. +TEST(NdtScanMatcherCharacteristics, BackendThatFailsToInitializeThrowsAtConstruction) +{ + try { + NdtHarness harness({rclcpp::Parameter("ndt.backend", "test_initialize_throws")}); + FAIL() << "the node started with a backend that cannot initialize"; + } catch (const std::runtime_error & e) { + const std::string message = e.what(); + EXPECT_NE( + message.find("Failed to initialize the NDT backend 'test_initialize_throws'"), + std::string::npos) + << message; + EXPECT_NE(message.find("this computer has no test device"), std::string::npos) << message; + } +} + } // namespace int main(int argc, char ** argv) diff --git a/localization/autoware_ndt_scan_matcher/test/test_omp_ndt_backend.cpp b/localization/autoware_ndt_scan_matcher/test/test_omp_ndt_backend.cpp new file mode 100644 index 0000000000..39a2bee9d1 --- /dev/null +++ b/localization/autoware_ndt_scan_matcher/test/test_omp_ndt_backend.cpp @@ -0,0 +1,202 @@ +// Copyright 2026 Autoware Foundation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// The OMP backend must give exactly the results of ndt_omp, and its copies must be independent. + +#include "omp_ndt_backend.hpp" +#include "test_util.hpp" + +#include + +#include +#include +#include + +#include +#include +#include +#include + +namespace autoware::ndt_scan_matcher +{ +namespace +{ + +NdtParams make_params() +{ + NdtParams params{}; + params.trans_epsilon = 0.01; + params.step_size = 0.1; + params.resolution = 2.0F; + params.max_iterations = 30; + params.num_threads = 1; + params.regularization_scale_factor = 0.01F; + return params; +} + +// The same values as make_params(), for ndt_omp. +pclomp::NdtParams make_omp_params() +{ + const NdtParams params = make_params(); + pclomp::NdtParams omp_params{}; + omp_params.trans_epsilon = params.trans_epsilon; + omp_params.step_size = params.step_size; + omp_params.resolution = params.resolution; + omp_params.max_iterations = params.max_iterations; + omp_params.num_threads = params.num_threads; + omp_params.regularization_scale_factor = params.regularization_scale_factor; + return omp_params; +} + +pcl::PointCloud::Ptr make_map() +{ + return std::make_shared>(make_sample_half_cubic_pcd()); +} + +// Every 10th point of the map, as the scan. +pcl::PointCloud::Ptr make_scan() +{ + const auto map = make_sample_half_cubic_pcd(); + auto scan = std::make_shared>(); + for (std::size_t i = 0; i < map.size(); i += 10) { + scan->push_back(map.points[i]); + } + return scan; +} + +Eigen::Matrix4f make_guess() +{ + Eigen::Affine3f guess = Eigen::Affine3f::Identity(); + guess.translate(Eigen::Vector3f(0.3F, -0.2F, 0.1F)); + guess.rotate(Eigen::AngleAxisf(0.02F, Eigen::Vector3f::UnitZ())); + return guess.matrix(); +} + +} // namespace + +TEST(OmpNdtBackend, AlignGivesTheResultOfNdtOmp) +{ + pclomp::MultiGridNormalDistributionsTransform ndt; + ndt.set_params(make_omp_params()); + ndt.add_target(make_map(), "a"); + ndt.create_voxel_kdtree(); + ndt.set_regularization_pose(Eigen::Matrix4f::Identity()); + pcl::PointCloud output; + ndt.align(output, make_guess(), make_scan()); + const pclomp::NdtResult expected = ndt.get_result(); + + OmpNdtBackend backend; + backend.initialize(make_params()); + backend.add_target(make_map(), "a"); + backend.commit_target(); + backend.set_regularization_pose(Eigen::Matrix4f::Identity()); + const NdtResult result = backend.align(make_guess(), make_scan()); + + EXPECT_EQ(result.pose, expected.pose); + EXPECT_EQ(result.hessian, expected.hessian); + EXPECT_EQ(result.iteration_num, expected.iteration_num); + EXPECT_EQ(result.transform_probability, expected.transform_probability); + EXPECT_EQ( + result.nearest_voxel_transformation_likelihood, + expected.nearest_voxel_transformation_likelihood); + ASSERT_EQ(result.transformation_array.size(), expected.transformation_array.size()); + for (std::size_t i = 0; i < result.transformation_array.size(); ++i) { + EXPECT_EQ(result.transformation_array[i], expected.transformation_array[i]); + } + EXPECT_EQ(result.transform_probability_array, expected.transform_probability_array); + EXPECT_EQ( + result.nearest_voxel_transformation_likelihood_array, + expected.nearest_voxel_transformation_likelihood_array); + + pcl::PointCloud scan_in_map; + pcl::transformPointCloud(*make_scan(), scan_in_map, expected.pose); + EXPECT_EQ( + backend.calculate_nearest_voxel_transformation_likelihood(scan_in_map), + ndt.calculate_nearest_voxel_transformation_likelihood(scan_in_map)); + EXPECT_EQ( + backend.calculate_transformation_probability(scan_in_map), + ndt.calculate_transformation_probability(scan_in_map)); + + const pcl::PointCloud scores = + backend.calculate_nearest_voxel_score_each_point(scan_in_map); + const pcl::PointCloud expected_scores = + ndt.calculate_nearest_voxel_score_each_point(scan_in_map); + ASSERT_EQ(scores.size(), expected_scores.size()); + for (std::size_t i = 0; i < scores.size(); ++i) { + EXPECT_EQ(scores[i].getVector4fMap(), expected_scores[i].getVector4fMap()); + EXPECT_EQ(scores[i].intensity, expected_scores[i].intensity); + } + + // Without the regularization pose, the result changes, and it is again the result of ndt_omp. + ndt.unset_regularization_pose(); + ndt.align(output, make_guess(), make_scan()); + backend.unset_regularization_pose(); + const NdtResult result_without = backend.align(make_guess(), make_scan()); + EXPECT_EQ(result_without.pose, ndt.get_result().pose); + EXPECT_EQ(result_without.transform_probability, ndt.get_result().transform_probability); + EXPECT_EQ(result_without.hessian, ndt.get_result().hessian); + EXPECT_NE(result_without.transform_probability, expected.transform_probability); +} + +TEST(OmpNdtBackend, CloneIsIndependent) +{ + OmpNdtBackend backend; + backend.initialize(make_params()); + backend.add_target(make_map(), "a"); + backend.commit_target(); + + const NdtBackend::SharedPtr clone = backend.clone(); + EXPECT_EQ(clone->get_current_map_ids(), std::vector{"a"}); + EXPECT_EQ(clone->get_params().max_iterations, make_params().max_iterations); + + clone->remove_target("a"); + clone->commit_target(); + EXPECT_FALSE(clone->has_target()); + EXPECT_TRUE(backend.has_target()); +} + +TEST(OmpNdtBackend, CloneAlignsLikeTheOriginal) +{ + OmpNdtBackend backend; + backend.initialize(make_params()); + backend.add_target(make_map(), "a"); + backend.commit_target(); + const NdtBackend::SharedPtr clone = backend.clone(); + + EXPECT_EQ( + clone->align(make_guess(), make_scan()).pose, backend.align(make_guess(), make_scan()).pose); +} + +TEST(OmpNdtBackend, CloneEmptyHasTheParametersAndNoMap) +{ + OmpNdtBackend backend; + NdtParams params = make_params(); + params.max_iterations = 17; + backend.initialize(params); + backend.add_target(make_map(), "a"); + backend.commit_target(); + + const NdtBackend::SharedPtr empty = backend.clone_empty(); + EXPECT_FALSE(empty->has_target()); + EXPECT_EQ(empty->name(), "ndt_omp"); + const NdtParams empty_params = empty->get_params(); + EXPECT_EQ(empty_params.trans_epsilon, params.trans_epsilon); + EXPECT_EQ(empty_params.step_size, params.step_size); + EXPECT_EQ(empty_params.resolution, params.resolution); + EXPECT_EQ(empty_params.max_iterations, 17); + EXPECT_EQ(empty_params.num_threads, params.num_threads); + EXPECT_EQ(empty_params.regularization_scale_factor, params.regularization_scale_factor); +} + +} // namespace autoware::ndt_scan_matcher